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/SmallPtrSet.h" 21 #include "llvm/ADT/SetVector.h" 22 #include "llvm/ADT/Statistic.h" 23 #include "llvm/Analysis/AliasAnalysis.h" 24 #include "llvm/CodeGen/MachineFrameInfo.h" 25 #include "llvm/CodeGen/MachineFunction.h" 26 #include "llvm/IR/DataLayout.h" 27 #include "llvm/IR/DerivedTypes.h" 28 #include "llvm/IR/Function.h" 29 #include "llvm/IR/LLVMContext.h" 30 #include "llvm/Support/CommandLine.h" 31 #include "llvm/Support/Debug.h" 32 #include "llvm/Support/ErrorHandling.h" 33 #include "llvm/Support/MathExtras.h" 34 #include "llvm/Support/raw_ostream.h" 35 #include "llvm/Target/TargetLowering.h" 36 #include "llvm/Target/TargetMachine.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 visitFCOPYSIGN(SDNode *N); 280 SDValue visitSINT_TO_FP(SDNode *N); 281 SDValue visitUINT_TO_FP(SDNode *N); 282 SDValue visitFP_TO_SINT(SDNode *N); 283 SDValue visitFP_TO_UINT(SDNode *N); 284 SDValue visitFP_ROUND(SDNode *N); 285 SDValue visitFP_ROUND_INREG(SDNode *N); 286 SDValue visitFP_EXTEND(SDNode *N); 287 SDValue visitFNEG(SDNode *N); 288 SDValue visitFABS(SDNode *N); 289 SDValue visitFCEIL(SDNode *N); 290 SDValue visitFTRUNC(SDNode *N); 291 SDValue visitFFLOOR(SDNode *N); 292 SDValue visitBRCOND(SDNode *N); 293 SDValue visitBR_CC(SDNode *N); 294 SDValue visitLOAD(SDNode *N); 295 SDValue visitSTORE(SDNode *N); 296 SDValue visitINSERT_VECTOR_ELT(SDNode *N); 297 SDValue visitEXTRACT_VECTOR_ELT(SDNode *N); 298 SDValue visitBUILD_VECTOR(SDNode *N); 299 SDValue visitCONCAT_VECTORS(SDNode *N); 300 SDValue visitEXTRACT_SUBVECTOR(SDNode *N); 301 SDValue visitVECTOR_SHUFFLE(SDNode *N); 302 SDValue visitINSERT_SUBVECTOR(SDNode *N); 303 304 SDValue XformToShuffleWithZero(SDNode *N); 305 SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS); 306 307 SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt); 308 309 bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS); 310 SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N); 311 SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2); 312 SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2, 313 SDValue N3, ISD::CondCode CC, 314 bool NotExtCompare = false); 315 SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond, 316 SDLoc DL, bool foldBooleans = true); 317 318 bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS, 319 SDValue &CC) const; 320 bool isOneUseSetCC(SDValue N) const; 321 322 SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp, 323 unsigned HiOp); 324 SDValue CombineConsecutiveLoads(SDNode *N, EVT VT); 325 SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT); 326 SDValue BuildSDIV(SDNode *N); 327 SDValue BuildSDIVPow2(SDNode *N); 328 SDValue BuildUDIV(SDNode *N); 329 SDValue BuildRSQRTE(SDNode *N); 330 SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1, 331 bool DemandHighBits = true); 332 SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1); 333 SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg, 334 SDValue InnerPos, SDValue InnerNeg, 335 unsigned PosOpcode, unsigned NegOpcode, 336 SDLoc DL); 337 SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL); 338 SDValue ReduceLoadWidth(SDNode *N); 339 SDValue ReduceLoadOpStoreWidth(SDNode *N); 340 SDValue TransformFPLoadStorePair(SDNode *N); 341 SDValue reduceBuildVecExtToExtBuildVec(SDNode *N); 342 SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N); 343 344 SDValue GetDemandedBits(SDValue V, const APInt &Mask); 345 346 /// Walk up chain skipping non-aliasing memory nodes, 347 /// looking for aliasing nodes and adding them to the Aliases vector. 348 void GatherAllAliases(SDNode *N, SDValue OriginalChain, 349 SmallVectorImpl<SDValue> &Aliases); 350 351 /// Return true if there is any possibility that the two addresses overlap. 352 bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const; 353 354 /// Walk up chain skipping non-aliasing memory nodes, looking for a better 355 /// chain (aliasing node.) 356 SDValue FindBetterChain(SDNode *N, SDValue Chain); 357 358 /// Merge consecutive store operations into a wide store. 359 /// This optimization uses wide integers or vectors when possible. 360 /// \return True if some memory operations were changed. 361 bool MergeConsecutiveStores(StoreSDNode *N); 362 363 /// \brief Try to transform a truncation where C is a constant: 364 /// (trunc (and X, C)) -> (and (trunc X), (trunc C)) 365 /// 366 /// \p N needs to be a truncation and its first operand an AND. Other 367 /// requirements are checked by the function (e.g. that trunc is 368 /// single-use) and if missed an empty SDValue is returned. 369 SDValue distributeTruncateThroughAnd(SDNode *N); 370 371 public: 372 DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL) 373 : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes), 374 OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) { 375 AttributeSet FnAttrs = 376 DAG.getMachineFunction().getFunction()->getAttributes(); 377 ForCodeSize = 378 FnAttrs.hasAttribute(AttributeSet::FunctionIndex, 379 Attribute::OptimizeForSize) || 380 FnAttrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::MinSize); 381 } 382 383 /// Runs the dag combiner on all nodes in the work list 384 void Run(CombineLevel AtLevel); 385 386 SelectionDAG &getDAG() const { return DAG; } 387 388 /// Returns a type large enough to hold any valid shift amount - before type 389 /// legalization these can be huge. 390 EVT getShiftAmountTy(EVT LHSTy) { 391 assert(LHSTy.isInteger() && "Shift amount is not an integer type!"); 392 if (LHSTy.isVector()) 393 return LHSTy; 394 return LegalTypes ? TLI.getScalarShiftAmountTy(LHSTy) 395 : TLI.getPointerTy(); 396 } 397 398 /// This method returns true if we are running before type legalization or 399 /// if the specified VT is legal. 400 bool isTypeLegal(const EVT &VT) { 401 if (!LegalTypes) return true; 402 return TLI.isTypeLegal(VT); 403 } 404 405 /// Convenience wrapper around TargetLowering::getSetCCResultType 406 EVT getSetCCResultType(EVT VT) const { 407 return TLI.getSetCCResultType(*DAG.getContext(), VT); 408 } 409 }; 410 } 411 412 413 namespace { 414 /// This class is a DAGUpdateListener that removes any deleted 415 /// nodes from the worklist. 416 class WorklistRemover : public SelectionDAG::DAGUpdateListener { 417 DAGCombiner &DC; 418 public: 419 explicit WorklistRemover(DAGCombiner &dc) 420 : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {} 421 422 void NodeDeleted(SDNode *N, SDNode *E) override { 423 DC.removeFromWorklist(N); 424 } 425 }; 426 } 427 428 //===----------------------------------------------------------------------===// 429 // TargetLowering::DAGCombinerInfo implementation 430 //===----------------------------------------------------------------------===// 431 432 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) { 433 ((DAGCombiner*)DC)->AddToWorklist(N); 434 } 435 436 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) { 437 ((DAGCombiner*)DC)->removeFromWorklist(N); 438 } 439 440 SDValue TargetLowering::DAGCombinerInfo:: 441 CombineTo(SDNode *N, const std::vector<SDValue> &To, bool AddTo) { 442 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo); 443 } 444 445 SDValue TargetLowering::DAGCombinerInfo:: 446 CombineTo(SDNode *N, SDValue Res, bool AddTo) { 447 return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo); 448 } 449 450 451 SDValue TargetLowering::DAGCombinerInfo:: 452 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) { 453 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo); 454 } 455 456 void TargetLowering::DAGCombinerInfo:: 457 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) { 458 return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO); 459 } 460 461 //===----------------------------------------------------------------------===// 462 // Helper Functions 463 //===----------------------------------------------------------------------===// 464 465 void DAGCombiner::deleteAndRecombine(SDNode *N) { 466 removeFromWorklist(N); 467 468 // If the operands of this node are only used by the node, they will now be 469 // dead. Make sure to re-visit them and recursively delete dead nodes. 470 for (const SDValue &Op : N->ops()) 471 // For an operand generating multiple values, one of the values may 472 // become dead allowing further simplification (e.g. split index 473 // arithmetic from an indexed load). 474 if (Op->hasOneUse() || Op->getNumValues() > 1) 475 AddToWorklist(Op.getNode()); 476 477 DAG.DeleteNode(N); 478 } 479 480 /// Return 1 if we can compute the negated form of the specified expression for 481 /// the same cost as the expression itself, or 2 if we can compute the negated 482 /// form more cheaply than the expression itself. 483 static char isNegatibleForFree(SDValue Op, bool LegalOperations, 484 const TargetLowering &TLI, 485 const TargetOptions *Options, 486 unsigned Depth = 0) { 487 // fneg is removable even if it has multiple uses. 488 if (Op.getOpcode() == ISD::FNEG) return 2; 489 490 // Don't allow anything with multiple uses. 491 if (!Op.hasOneUse()) return 0; 492 493 // Don't recurse exponentially. 494 if (Depth > 6) return 0; 495 496 switch (Op.getOpcode()) { 497 default: return false; 498 case ISD::ConstantFP: 499 // Don't invert constant FP values after legalize. The negated constant 500 // isn't necessarily legal. 501 return LegalOperations ? 0 : 1; 502 case ISD::FADD: 503 // FIXME: determine better conditions for this xform. 504 if (!Options->UnsafeFPMath) return 0; 505 506 // After operation legalization, it might not be legal to create new FSUBs. 507 if (LegalOperations && 508 !TLI.isOperationLegalOrCustom(ISD::FSUB, Op.getValueType())) 509 return 0; 510 511 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B) 512 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, 513 Options, Depth + 1)) 514 return V; 515 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A) 516 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options, 517 Depth + 1); 518 case ISD::FSUB: 519 // We can't turn -(A-B) into B-A when we honor signed zeros. 520 if (!Options->UnsafeFPMath) return 0; 521 522 // fold (fneg (fsub A, B)) -> (fsub B, A) 523 return 1; 524 525 case ISD::FMUL: 526 case ISD::FDIV: 527 if (Options->HonorSignDependentRoundingFPMath()) return 0; 528 529 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y)) 530 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, 531 Options, Depth + 1)) 532 return V; 533 534 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options, 535 Depth + 1); 536 537 case ISD::FP_EXTEND: 538 case ISD::FP_ROUND: 539 case ISD::FSIN: 540 return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options, 541 Depth + 1); 542 } 543 } 544 545 /// If isNegatibleForFree returns true, return the newly negated expression. 546 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG, 547 bool LegalOperations, unsigned Depth = 0) { 548 const TargetOptions &Options = DAG.getTarget().Options; 549 // fneg is removable even if it has multiple uses. 550 if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0); 551 552 // Don't allow anything with multiple uses. 553 assert(Op.hasOneUse() && "Unknown reuse!"); 554 555 assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree"); 556 switch (Op.getOpcode()) { 557 default: llvm_unreachable("Unknown code"); 558 case ISD::ConstantFP: { 559 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF(); 560 V.changeSign(); 561 return DAG.getConstantFP(V, Op.getValueType()); 562 } 563 case ISD::FADD: 564 // FIXME: determine better conditions for this xform. 565 assert(Options.UnsafeFPMath); 566 567 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B) 568 if (isNegatibleForFree(Op.getOperand(0), LegalOperations, 569 DAG.getTargetLoweringInfo(), &Options, Depth+1)) 570 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(), 571 GetNegatedExpression(Op.getOperand(0), DAG, 572 LegalOperations, Depth+1), 573 Op.getOperand(1)); 574 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A) 575 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(), 576 GetNegatedExpression(Op.getOperand(1), DAG, 577 LegalOperations, Depth+1), 578 Op.getOperand(0)); 579 case ISD::FSUB: 580 // We can't turn -(A-B) into B-A when we honor signed zeros. 581 assert(Options.UnsafeFPMath); 582 583 // fold (fneg (fsub 0, B)) -> B 584 if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0))) 585 if (N0CFP->getValueAPF().isZero()) 586 return Op.getOperand(1); 587 588 // fold (fneg (fsub A, B)) -> (fsub B, A) 589 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(), 590 Op.getOperand(1), Op.getOperand(0)); 591 592 case ISD::FMUL: 593 case ISD::FDIV: 594 assert(!Options.HonorSignDependentRoundingFPMath()); 595 596 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) 597 if (isNegatibleForFree(Op.getOperand(0), LegalOperations, 598 DAG.getTargetLoweringInfo(), &Options, Depth+1)) 599 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(), 600 GetNegatedExpression(Op.getOperand(0), DAG, 601 LegalOperations, Depth+1), 602 Op.getOperand(1)); 603 604 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y)) 605 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(), 606 Op.getOperand(0), 607 GetNegatedExpression(Op.getOperand(1), DAG, 608 LegalOperations, Depth+1)); 609 610 case ISD::FP_EXTEND: 611 case ISD::FSIN: 612 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(), 613 GetNegatedExpression(Op.getOperand(0), DAG, 614 LegalOperations, Depth+1)); 615 case ISD::FP_ROUND: 616 return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(), 617 GetNegatedExpression(Op.getOperand(0), DAG, 618 LegalOperations, Depth+1), 619 Op.getOperand(1)); 620 } 621 } 622 623 // Return true if this node is a setcc, or is a select_cc 624 // that selects between the target values used for true and false, making it 625 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to 626 // the appropriate nodes based on the type of node we are checking. This 627 // simplifies life a bit for the callers. 628 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS, 629 SDValue &CC) const { 630 if (N.getOpcode() == ISD::SETCC) { 631 LHS = N.getOperand(0); 632 RHS = N.getOperand(1); 633 CC = N.getOperand(2); 634 return true; 635 } 636 637 if (N.getOpcode() != ISD::SELECT_CC || 638 !TLI.isConstTrueVal(N.getOperand(2).getNode()) || 639 !TLI.isConstFalseVal(N.getOperand(3).getNode())) 640 return false; 641 642 LHS = N.getOperand(0); 643 RHS = N.getOperand(1); 644 CC = N.getOperand(4); 645 return true; 646 } 647 648 /// Return true if this is a SetCC-equivalent operation with only one use. 649 /// If this is true, it allows the users to invert the operation for free when 650 /// it is profitable to do so. 651 bool DAGCombiner::isOneUseSetCC(SDValue N) const { 652 SDValue N0, N1, N2; 653 if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse()) 654 return true; 655 return false; 656 } 657 658 /// Returns true if N is a BUILD_VECTOR node whose 659 /// elements are all the same constant or undefined. 660 static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) { 661 BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N); 662 if (!C) 663 return false; 664 665 APInt SplatUndef; 666 unsigned SplatBitSize; 667 bool HasAnyUndefs; 668 EVT EltVT = N->getValueType(0).getVectorElementType(); 669 return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize, 670 HasAnyUndefs) && 671 EltVT.getSizeInBits() >= SplatBitSize); 672 } 673 674 // \brief Returns the SDNode if it is a constant BuildVector or constant. 675 static SDNode *isConstantBuildVectorOrConstantInt(SDValue N) { 676 if (isa<ConstantSDNode>(N)) 677 return N.getNode(); 678 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N); 679 if (BV && BV->isConstant()) 680 return BV; 681 return nullptr; 682 } 683 684 // \brief Returns the SDNode if it is a constant splat BuildVector or constant 685 // int. 686 static ConstantSDNode *isConstOrConstSplat(SDValue N) { 687 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) 688 return CN; 689 690 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) { 691 BitVector UndefElements; 692 ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements); 693 694 // BuildVectors can truncate their operands. Ignore that case here. 695 // FIXME: We blindly ignore splats which include undef which is overly 696 // pessimistic. 697 if (CN && UndefElements.none() && 698 CN->getValueType(0) == N.getValueType().getScalarType()) 699 return CN; 700 } 701 702 return nullptr; 703 } 704 705 // \brief Returns the SDNode if it is a constant splat BuildVector or constant 706 // float. 707 static ConstantFPSDNode *isConstOrConstSplatFP(SDValue N) { 708 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N)) 709 return CN; 710 711 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) { 712 BitVector UndefElements; 713 ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements); 714 715 if (CN && UndefElements.none()) 716 return CN; 717 } 718 719 return nullptr; 720 } 721 722 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL, 723 SDValue N0, SDValue N1) { 724 EVT VT = N0.getValueType(); 725 if (N0.getOpcode() == Opc) { 726 if (SDNode *L = isConstantBuildVectorOrConstantInt(N0.getOperand(1))) { 727 if (SDNode *R = isConstantBuildVectorOrConstantInt(N1)) { 728 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2)) 729 SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, L, R); 730 if (!OpNode.getNode()) 731 return SDValue(); 732 return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode); 733 } 734 if (N0.hasOneUse()) { 735 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one 736 // use 737 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1); 738 if (!OpNode.getNode()) 739 return SDValue(); 740 AddToWorklist(OpNode.getNode()); 741 return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1)); 742 } 743 } 744 } 745 746 if (N1.getOpcode() == Opc) { 747 if (SDNode *R = isConstantBuildVectorOrConstantInt(N1.getOperand(1))) { 748 if (SDNode *L = isConstantBuildVectorOrConstantInt(N0)) { 749 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2)) 750 SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, R, L); 751 if (!OpNode.getNode()) 752 return SDValue(); 753 return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode); 754 } 755 if (N1.hasOneUse()) { 756 // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one 757 // use 758 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0); 759 if (!OpNode.getNode()) 760 return SDValue(); 761 AddToWorklist(OpNode.getNode()); 762 return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1)); 763 } 764 } 765 } 766 767 return SDValue(); 768 } 769 770 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo, 771 bool AddTo) { 772 assert(N->getNumValues() == NumTo && "Broken CombineTo call!"); 773 ++NodesCombined; 774 DEBUG(dbgs() << "\nReplacing.1 "; 775 N->dump(&DAG); 776 dbgs() << "\nWith: "; 777 To[0].getNode()->dump(&DAG); 778 dbgs() << " and " << NumTo-1 << " other values\n"; 779 for (unsigned i = 0, e = NumTo; i != e; ++i) 780 assert((!To[i].getNode() || 781 N->getValueType(i) == To[i].getValueType()) && 782 "Cannot combine value to value of different type!")); 783 WorklistRemover DeadNodes(*this); 784 DAG.ReplaceAllUsesWith(N, To); 785 if (AddTo) { 786 // Push the new nodes and any users onto the worklist 787 for (unsigned i = 0, e = NumTo; i != e; ++i) { 788 if (To[i].getNode()) { 789 AddToWorklist(To[i].getNode()); 790 AddUsersToWorklist(To[i].getNode()); 791 } 792 } 793 } 794 795 // Finally, if the node is now dead, remove it from the graph. The node 796 // may not be dead if the replacement process recursively simplified to 797 // something else needing this node. 798 if (N->use_empty()) 799 deleteAndRecombine(N); 800 return SDValue(N, 0); 801 } 802 803 void DAGCombiner:: 804 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) { 805 // Replace all uses. If any nodes become isomorphic to other nodes and 806 // are deleted, make sure to remove them from our worklist. 807 WorklistRemover DeadNodes(*this); 808 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New); 809 810 // Push the new node and any (possibly new) users onto the worklist. 811 AddToWorklist(TLO.New.getNode()); 812 AddUsersToWorklist(TLO.New.getNode()); 813 814 // Finally, if the node is now dead, remove it from the graph. The node 815 // may not be dead if the replacement process recursively simplified to 816 // something else needing this node. 817 if (TLO.Old.getNode()->use_empty()) 818 deleteAndRecombine(TLO.Old.getNode()); 819 } 820 821 /// Check the specified integer node value to see if it can be simplified or if 822 /// things it uses can be simplified by bit propagation. If so, return true. 823 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) { 824 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations); 825 APInt KnownZero, KnownOne; 826 if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO)) 827 return false; 828 829 // Revisit the node. 830 AddToWorklist(Op.getNode()); 831 832 // Replace the old value with the new one. 833 ++NodesCombined; 834 DEBUG(dbgs() << "\nReplacing.2 "; 835 TLO.Old.getNode()->dump(&DAG); 836 dbgs() << "\nWith: "; 837 TLO.New.getNode()->dump(&DAG); 838 dbgs() << '\n'); 839 840 CommitTargetLoweringOpt(TLO); 841 return true; 842 } 843 844 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) { 845 SDLoc dl(Load); 846 EVT VT = Load->getValueType(0); 847 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0)); 848 849 DEBUG(dbgs() << "\nReplacing.9 "; 850 Load->dump(&DAG); 851 dbgs() << "\nWith: "; 852 Trunc.getNode()->dump(&DAG); 853 dbgs() << '\n'); 854 WorklistRemover DeadNodes(*this); 855 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc); 856 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1)); 857 deleteAndRecombine(Load); 858 AddToWorklist(Trunc.getNode()); 859 } 860 861 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) { 862 Replace = false; 863 SDLoc dl(Op); 864 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) { 865 EVT MemVT = LD->getMemoryVT(); 866 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD) 867 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD 868 : ISD::EXTLOAD) 869 : LD->getExtensionType(); 870 Replace = true; 871 return DAG.getExtLoad(ExtType, dl, PVT, 872 LD->getChain(), LD->getBasePtr(), 873 MemVT, LD->getMemOperand()); 874 } 875 876 unsigned Opc = Op.getOpcode(); 877 switch (Opc) { 878 default: break; 879 case ISD::AssertSext: 880 return DAG.getNode(ISD::AssertSext, dl, PVT, 881 SExtPromoteOperand(Op.getOperand(0), PVT), 882 Op.getOperand(1)); 883 case ISD::AssertZext: 884 return DAG.getNode(ISD::AssertZext, dl, PVT, 885 ZExtPromoteOperand(Op.getOperand(0), PVT), 886 Op.getOperand(1)); 887 case ISD::Constant: { 888 unsigned ExtOpc = 889 Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 890 return DAG.getNode(ExtOpc, dl, PVT, Op); 891 } 892 } 893 894 if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT)) 895 return SDValue(); 896 return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op); 897 } 898 899 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) { 900 if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT)) 901 return SDValue(); 902 EVT OldVT = Op.getValueType(); 903 SDLoc dl(Op); 904 bool Replace = false; 905 SDValue NewOp = PromoteOperand(Op, PVT, Replace); 906 if (!NewOp.getNode()) 907 return SDValue(); 908 AddToWorklist(NewOp.getNode()); 909 910 if (Replace) 911 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode()); 912 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp, 913 DAG.getValueType(OldVT)); 914 } 915 916 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) { 917 EVT OldVT = Op.getValueType(); 918 SDLoc dl(Op); 919 bool Replace = false; 920 SDValue NewOp = PromoteOperand(Op, PVT, Replace); 921 if (!NewOp.getNode()) 922 return SDValue(); 923 AddToWorklist(NewOp.getNode()); 924 925 if (Replace) 926 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode()); 927 return DAG.getZeroExtendInReg(NewOp, dl, OldVT); 928 } 929 930 /// Promote the specified integer binary operation if the target indicates it is 931 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to 932 /// i32 since i16 instructions are longer. 933 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) { 934 if (!LegalOperations) 935 return SDValue(); 936 937 EVT VT = Op.getValueType(); 938 if (VT.isVector() || !VT.isInteger()) 939 return SDValue(); 940 941 // If operation type is 'undesirable', e.g. i16 on x86, consider 942 // promoting it. 943 unsigned Opc = Op.getOpcode(); 944 if (TLI.isTypeDesirableForOp(Opc, VT)) 945 return SDValue(); 946 947 EVT PVT = VT; 948 // Consult target whether it is a good idea to promote this operation and 949 // what's the right type to promote it to. 950 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 951 assert(PVT != VT && "Don't know what type to promote to!"); 952 953 bool Replace0 = false; 954 SDValue N0 = Op.getOperand(0); 955 SDValue NN0 = PromoteOperand(N0, PVT, Replace0); 956 if (!NN0.getNode()) 957 return SDValue(); 958 959 bool Replace1 = false; 960 SDValue N1 = Op.getOperand(1); 961 SDValue NN1; 962 if (N0 == N1) 963 NN1 = NN0; 964 else { 965 NN1 = PromoteOperand(N1, PVT, Replace1); 966 if (!NN1.getNode()) 967 return SDValue(); 968 } 969 970 AddToWorklist(NN0.getNode()); 971 if (NN1.getNode()) 972 AddToWorklist(NN1.getNode()); 973 974 if (Replace0) 975 ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode()); 976 if (Replace1) 977 ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode()); 978 979 DEBUG(dbgs() << "\nPromoting "; 980 Op.getNode()->dump(&DAG)); 981 SDLoc dl(Op); 982 return DAG.getNode(ISD::TRUNCATE, dl, VT, 983 DAG.getNode(Opc, dl, PVT, NN0, NN1)); 984 } 985 return SDValue(); 986 } 987 988 /// Promote the specified integer shift operation if the target indicates it is 989 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to 990 /// i32 since i16 instructions are longer. 991 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) { 992 if (!LegalOperations) 993 return SDValue(); 994 995 EVT VT = Op.getValueType(); 996 if (VT.isVector() || !VT.isInteger()) 997 return SDValue(); 998 999 // If operation type is 'undesirable', e.g. i16 on x86, consider 1000 // promoting it. 1001 unsigned Opc = Op.getOpcode(); 1002 if (TLI.isTypeDesirableForOp(Opc, VT)) 1003 return SDValue(); 1004 1005 EVT PVT = VT; 1006 // Consult target whether it is a good idea to promote this operation and 1007 // what's the right type to promote it to. 1008 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 1009 assert(PVT != VT && "Don't know what type to promote to!"); 1010 1011 bool Replace = false; 1012 SDValue N0 = Op.getOperand(0); 1013 if (Opc == ISD::SRA) 1014 N0 = SExtPromoteOperand(Op.getOperand(0), PVT); 1015 else if (Opc == ISD::SRL) 1016 N0 = ZExtPromoteOperand(Op.getOperand(0), PVT); 1017 else 1018 N0 = PromoteOperand(N0, PVT, Replace); 1019 if (!N0.getNode()) 1020 return SDValue(); 1021 1022 AddToWorklist(N0.getNode()); 1023 if (Replace) 1024 ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode()); 1025 1026 DEBUG(dbgs() << "\nPromoting "; 1027 Op.getNode()->dump(&DAG)); 1028 SDLoc dl(Op); 1029 return DAG.getNode(ISD::TRUNCATE, dl, VT, 1030 DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1))); 1031 } 1032 return SDValue(); 1033 } 1034 1035 SDValue DAGCombiner::PromoteExtend(SDValue Op) { 1036 if (!LegalOperations) 1037 return SDValue(); 1038 1039 EVT VT = Op.getValueType(); 1040 if (VT.isVector() || !VT.isInteger()) 1041 return SDValue(); 1042 1043 // If operation type is 'undesirable', e.g. i16 on x86, consider 1044 // promoting it. 1045 unsigned Opc = Op.getOpcode(); 1046 if (TLI.isTypeDesirableForOp(Opc, VT)) 1047 return SDValue(); 1048 1049 EVT PVT = VT; 1050 // Consult target whether it is a good idea to promote this operation and 1051 // what's the right type to promote it to. 1052 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 1053 assert(PVT != VT && "Don't know what type to promote to!"); 1054 // fold (aext (aext x)) -> (aext x) 1055 // fold (aext (zext x)) -> (zext x) 1056 // fold (aext (sext x)) -> (sext x) 1057 DEBUG(dbgs() << "\nPromoting "; 1058 Op.getNode()->dump(&DAG)); 1059 return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0)); 1060 } 1061 return SDValue(); 1062 } 1063 1064 bool DAGCombiner::PromoteLoad(SDValue Op) { 1065 if (!LegalOperations) 1066 return false; 1067 1068 EVT VT = Op.getValueType(); 1069 if (VT.isVector() || !VT.isInteger()) 1070 return false; 1071 1072 // If operation type is 'undesirable', e.g. i16 on x86, consider 1073 // promoting it. 1074 unsigned Opc = Op.getOpcode(); 1075 if (TLI.isTypeDesirableForOp(Opc, VT)) 1076 return false; 1077 1078 EVT PVT = VT; 1079 // Consult target whether it is a good idea to promote this operation and 1080 // what's the right type to promote it to. 1081 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 1082 assert(PVT != VT && "Don't know what type to promote to!"); 1083 1084 SDLoc dl(Op); 1085 SDNode *N = Op.getNode(); 1086 LoadSDNode *LD = cast<LoadSDNode>(N); 1087 EVT MemVT = LD->getMemoryVT(); 1088 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD) 1089 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD 1090 : ISD::EXTLOAD) 1091 : LD->getExtensionType(); 1092 SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT, 1093 LD->getChain(), LD->getBasePtr(), 1094 MemVT, LD->getMemOperand()); 1095 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD); 1096 1097 DEBUG(dbgs() << "\nPromoting "; 1098 N->dump(&DAG); 1099 dbgs() << "\nTo: "; 1100 Result.getNode()->dump(&DAG); 1101 dbgs() << '\n'); 1102 WorklistRemover DeadNodes(*this); 1103 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result); 1104 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1)); 1105 deleteAndRecombine(N); 1106 AddToWorklist(Result.getNode()); 1107 return true; 1108 } 1109 return false; 1110 } 1111 1112 /// \brief Recursively delete a node which has no uses and any operands for 1113 /// which it is the only use. 1114 /// 1115 /// Note that this both deletes the nodes and removes them from the worklist. 1116 /// It also adds any nodes who have had a user deleted to the worklist as they 1117 /// may now have only one use and subject to other combines. 1118 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) { 1119 if (!N->use_empty()) 1120 return false; 1121 1122 SmallSetVector<SDNode *, 16> Nodes; 1123 Nodes.insert(N); 1124 do { 1125 N = Nodes.pop_back_val(); 1126 if (!N) 1127 continue; 1128 1129 if (N->use_empty()) { 1130 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) 1131 Nodes.insert(N->getOperand(i).getNode()); 1132 1133 removeFromWorklist(N); 1134 DAG.DeleteNode(N); 1135 } else { 1136 AddToWorklist(N); 1137 } 1138 } while (!Nodes.empty()); 1139 return true; 1140 } 1141 1142 //===----------------------------------------------------------------------===// 1143 // Main DAG Combiner implementation 1144 //===----------------------------------------------------------------------===// 1145 1146 void DAGCombiner::Run(CombineLevel AtLevel) { 1147 // set the instance variables, so that the various visit routines may use it. 1148 Level = AtLevel; 1149 LegalOperations = Level >= AfterLegalizeVectorOps; 1150 LegalTypes = Level >= AfterLegalizeTypes; 1151 1152 // Add all the dag nodes to the worklist. 1153 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(), 1154 E = DAG.allnodes_end(); I != E; ++I) 1155 AddToWorklist(I); 1156 1157 // Create a dummy node (which is not added to allnodes), that adds a reference 1158 // to the root node, preventing it from being deleted, and tracking any 1159 // changes of the root. 1160 HandleSDNode Dummy(DAG.getRoot()); 1161 1162 // while the worklist isn't empty, find a node and 1163 // try and combine it. 1164 while (!WorklistMap.empty()) { 1165 SDNode *N; 1166 // The Worklist holds the SDNodes in order, but it may contain null entries. 1167 do { 1168 N = Worklist.pop_back_val(); 1169 } while (!N); 1170 1171 bool GoodWorklistEntry = WorklistMap.erase(N); 1172 (void)GoodWorklistEntry; 1173 assert(GoodWorklistEntry && 1174 "Found a worklist entry without a corresponding map entry!"); 1175 1176 // If N has no uses, it is dead. Make sure to revisit all N's operands once 1177 // N is deleted from the DAG, since they too may now be dead or may have a 1178 // reduced number of uses, allowing other xforms. 1179 if (recursivelyDeleteUnusedNodes(N)) 1180 continue; 1181 1182 WorklistRemover DeadNodes(*this); 1183 1184 // If this combine is running after legalizing the DAG, re-legalize any 1185 // nodes pulled off the worklist. 1186 if (Level == AfterLegalizeDAG) { 1187 SmallSetVector<SDNode *, 16> UpdatedNodes; 1188 bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes); 1189 1190 for (SDNode *LN : UpdatedNodes) { 1191 AddToWorklist(LN); 1192 AddUsersToWorklist(LN); 1193 } 1194 if (!NIsValid) 1195 continue; 1196 } 1197 1198 DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG)); 1199 1200 // Add any operands of the new node which have not yet been combined to the 1201 // worklist as well. Because the worklist uniques things already, this 1202 // won't repeatedly process the same operand. 1203 CombinedNodes.insert(N); 1204 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) 1205 if (!CombinedNodes.count(N->getOperand(i).getNode())) 1206 AddToWorklist(N->getOperand(i).getNode()); 1207 1208 SDValue RV = combine(N); 1209 1210 if (!RV.getNode()) 1211 continue; 1212 1213 ++NodesCombined; 1214 1215 // If we get back the same node we passed in, rather than a new node or 1216 // zero, we know that the node must have defined multiple values and 1217 // CombineTo was used. Since CombineTo takes care of the worklist 1218 // mechanics for us, we have no work to do in this case. 1219 if (RV.getNode() == N) 1220 continue; 1221 1222 assert(N->getOpcode() != ISD::DELETED_NODE && 1223 RV.getNode()->getOpcode() != ISD::DELETED_NODE && 1224 "Node was deleted but visit returned new node!"); 1225 1226 DEBUG(dbgs() << " ... into: "; 1227 RV.getNode()->dump(&DAG)); 1228 1229 // Transfer debug value. 1230 DAG.TransferDbgValues(SDValue(N, 0), RV); 1231 if (N->getNumValues() == RV.getNode()->getNumValues()) 1232 DAG.ReplaceAllUsesWith(N, RV.getNode()); 1233 else { 1234 assert(N->getValueType(0) == RV.getValueType() && 1235 N->getNumValues() == 1 && "Type mismatch"); 1236 SDValue OpV = RV; 1237 DAG.ReplaceAllUsesWith(N, &OpV); 1238 } 1239 1240 // Push the new node and any users onto the worklist 1241 AddToWorklist(RV.getNode()); 1242 AddUsersToWorklist(RV.getNode()); 1243 1244 // Finally, if the node is now dead, remove it from the graph. The node 1245 // may not be dead if the replacement process recursively simplified to 1246 // something else needing this node. This will also take care of adding any 1247 // operands which have lost a user to the worklist. 1248 recursivelyDeleteUnusedNodes(N); 1249 } 1250 1251 // If the root changed (e.g. it was a dead load, update the root). 1252 DAG.setRoot(Dummy.getValue()); 1253 DAG.RemoveDeadNodes(); 1254 } 1255 1256 SDValue DAGCombiner::visit(SDNode *N) { 1257 switch (N->getOpcode()) { 1258 default: break; 1259 case ISD::TokenFactor: return visitTokenFactor(N); 1260 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N); 1261 case ISD::ADD: return visitADD(N); 1262 case ISD::SUB: return visitSUB(N); 1263 case ISD::ADDC: return visitADDC(N); 1264 case ISD::SUBC: return visitSUBC(N); 1265 case ISD::ADDE: return visitADDE(N); 1266 case ISD::SUBE: return visitSUBE(N); 1267 case ISD::MUL: return visitMUL(N); 1268 case ISD::SDIV: return visitSDIV(N); 1269 case ISD::UDIV: return visitUDIV(N); 1270 case ISD::SREM: return visitSREM(N); 1271 case ISD::UREM: return visitUREM(N); 1272 case ISD::MULHU: return visitMULHU(N); 1273 case ISD::MULHS: return visitMULHS(N); 1274 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N); 1275 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N); 1276 case ISD::SMULO: return visitSMULO(N); 1277 case ISD::UMULO: return visitUMULO(N); 1278 case ISD::SDIVREM: return visitSDIVREM(N); 1279 case ISD::UDIVREM: return visitUDIVREM(N); 1280 case ISD::AND: return visitAND(N); 1281 case ISD::OR: return visitOR(N); 1282 case ISD::XOR: return visitXOR(N); 1283 case ISD::SHL: return visitSHL(N); 1284 case ISD::SRA: return visitSRA(N); 1285 case ISD::SRL: return visitSRL(N); 1286 case ISD::ROTR: 1287 case ISD::ROTL: return visitRotate(N); 1288 case ISD::CTLZ: return visitCTLZ(N); 1289 case ISD::CTLZ_ZERO_UNDEF: return visitCTLZ_ZERO_UNDEF(N); 1290 case ISD::CTTZ: return visitCTTZ(N); 1291 case ISD::CTTZ_ZERO_UNDEF: return visitCTTZ_ZERO_UNDEF(N); 1292 case ISD::CTPOP: return visitCTPOP(N); 1293 case ISD::SELECT: return visitSELECT(N); 1294 case ISD::VSELECT: return visitVSELECT(N); 1295 case ISD::SELECT_CC: return visitSELECT_CC(N); 1296 case ISD::SETCC: return visitSETCC(N); 1297 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N); 1298 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N); 1299 case ISD::ANY_EXTEND: return visitANY_EXTEND(N); 1300 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N); 1301 case ISD::TRUNCATE: return visitTRUNCATE(N); 1302 case ISD::BITCAST: return visitBITCAST(N); 1303 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N); 1304 case ISD::FADD: return visitFADD(N); 1305 case ISD::FSUB: return visitFSUB(N); 1306 case ISD::FMUL: return visitFMUL(N); 1307 case ISD::FMA: return visitFMA(N); 1308 case ISD::FDIV: return visitFDIV(N); 1309 case ISD::FREM: return visitFREM(N); 1310 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N); 1311 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N); 1312 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N); 1313 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N); 1314 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N); 1315 case ISD::FP_ROUND: return visitFP_ROUND(N); 1316 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N); 1317 case ISD::FP_EXTEND: return visitFP_EXTEND(N); 1318 case ISD::FNEG: return visitFNEG(N); 1319 case ISD::FABS: return visitFABS(N); 1320 case ISD::FFLOOR: return visitFFLOOR(N); 1321 case ISD::FCEIL: return visitFCEIL(N); 1322 case ISD::FTRUNC: return visitFTRUNC(N); 1323 case ISD::BRCOND: return visitBRCOND(N); 1324 case ISD::BR_CC: return visitBR_CC(N); 1325 case ISD::LOAD: return visitLOAD(N); 1326 case ISD::STORE: return visitSTORE(N); 1327 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N); 1328 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N); 1329 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N); 1330 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N); 1331 case ISD::EXTRACT_SUBVECTOR: return visitEXTRACT_SUBVECTOR(N); 1332 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N); 1333 case ISD::INSERT_SUBVECTOR: return visitINSERT_SUBVECTOR(N); 1334 } 1335 return SDValue(); 1336 } 1337 1338 SDValue DAGCombiner::combine(SDNode *N) { 1339 SDValue RV = visit(N); 1340 1341 // If nothing happened, try a target-specific DAG combine. 1342 if (!RV.getNode()) { 1343 assert(N->getOpcode() != ISD::DELETED_NODE && 1344 "Node was deleted but visit returned NULL!"); 1345 1346 if (N->getOpcode() >= ISD::BUILTIN_OP_END || 1347 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) { 1348 1349 // Expose the DAG combiner to the target combiner impls. 1350 TargetLowering::DAGCombinerInfo 1351 DagCombineInfo(DAG, Level, false, this); 1352 1353 RV = TLI.PerformDAGCombine(N, DagCombineInfo); 1354 } 1355 } 1356 1357 // If nothing happened still, try promoting the operation. 1358 if (!RV.getNode()) { 1359 switch (N->getOpcode()) { 1360 default: break; 1361 case ISD::ADD: 1362 case ISD::SUB: 1363 case ISD::MUL: 1364 case ISD::AND: 1365 case ISD::OR: 1366 case ISD::XOR: 1367 RV = PromoteIntBinOp(SDValue(N, 0)); 1368 break; 1369 case ISD::SHL: 1370 case ISD::SRA: 1371 case ISD::SRL: 1372 RV = PromoteIntShiftOp(SDValue(N, 0)); 1373 break; 1374 case ISD::SIGN_EXTEND: 1375 case ISD::ZERO_EXTEND: 1376 case ISD::ANY_EXTEND: 1377 RV = PromoteExtend(SDValue(N, 0)); 1378 break; 1379 case ISD::LOAD: 1380 if (PromoteLoad(SDValue(N, 0))) 1381 RV = SDValue(N, 0); 1382 break; 1383 } 1384 } 1385 1386 // If N is a commutative binary node, try commuting it to enable more 1387 // sdisel CSE. 1388 if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) && 1389 N->getNumValues() == 1) { 1390 SDValue N0 = N->getOperand(0); 1391 SDValue N1 = N->getOperand(1); 1392 1393 // Constant operands are canonicalized to RHS. 1394 if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) { 1395 SDValue Ops[] = {N1, N0}; 1396 SDNode *CSENode; 1397 if (const BinaryWithFlagsSDNode *BinNode = 1398 dyn_cast<BinaryWithFlagsSDNode>(N)) { 1399 CSENode = DAG.getNodeIfExists( 1400 N->getOpcode(), N->getVTList(), Ops, BinNode->hasNoUnsignedWrap(), 1401 BinNode->hasNoSignedWrap(), BinNode->isExact()); 1402 } else { 1403 CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops); 1404 } 1405 if (CSENode) 1406 return SDValue(CSENode, 0); 1407 } 1408 } 1409 1410 return RV; 1411 } 1412 1413 /// Given a node, return its input chain if it has one, otherwise return a null 1414 /// sd operand. 1415 static SDValue getInputChainForNode(SDNode *N) { 1416 if (unsigned NumOps = N->getNumOperands()) { 1417 if (N->getOperand(0).getValueType() == MVT::Other) 1418 return N->getOperand(0); 1419 if (N->getOperand(NumOps-1).getValueType() == MVT::Other) 1420 return N->getOperand(NumOps-1); 1421 for (unsigned i = 1; i < NumOps-1; ++i) 1422 if (N->getOperand(i).getValueType() == MVT::Other) 1423 return N->getOperand(i); 1424 } 1425 return SDValue(); 1426 } 1427 1428 SDValue DAGCombiner::visitTokenFactor(SDNode *N) { 1429 // If N has two operands, where one has an input chain equal to the other, 1430 // the 'other' chain is redundant. 1431 if (N->getNumOperands() == 2) { 1432 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1)) 1433 return N->getOperand(0); 1434 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0)) 1435 return N->getOperand(1); 1436 } 1437 1438 SmallVector<SDNode *, 8> TFs; // List of token factors to visit. 1439 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor. 1440 SmallPtrSet<SDNode*, 16> SeenOps; 1441 bool Changed = false; // If we should replace this token factor. 1442 1443 // Start out with this token factor. 1444 TFs.push_back(N); 1445 1446 // Iterate through token factors. The TFs grows when new token factors are 1447 // encountered. 1448 for (unsigned i = 0; i < TFs.size(); ++i) { 1449 SDNode *TF = TFs[i]; 1450 1451 // Check each of the operands. 1452 for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) { 1453 SDValue Op = TF->getOperand(i); 1454 1455 switch (Op.getOpcode()) { 1456 case ISD::EntryToken: 1457 // Entry tokens don't need to be added to the list. They are 1458 // rededundant. 1459 Changed = true; 1460 break; 1461 1462 case ISD::TokenFactor: 1463 if (Op.hasOneUse() && 1464 std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) { 1465 // Queue up for processing. 1466 TFs.push_back(Op.getNode()); 1467 // Clean up in case the token factor is removed. 1468 AddToWorklist(Op.getNode()); 1469 Changed = true; 1470 break; 1471 } 1472 // Fall thru 1473 1474 default: 1475 // Only add if it isn't already in the list. 1476 if (SeenOps.insert(Op.getNode())) 1477 Ops.push_back(Op); 1478 else 1479 Changed = true; 1480 break; 1481 } 1482 } 1483 } 1484 1485 SDValue Result; 1486 1487 // If we've change things around then replace token factor. 1488 if (Changed) { 1489 if (Ops.empty()) { 1490 // The entry token is the only possible outcome. 1491 Result = DAG.getEntryNode(); 1492 } else { 1493 // New and improved token factor. 1494 Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops); 1495 } 1496 1497 // Don't add users to work list. 1498 return CombineTo(N, Result, false); 1499 } 1500 1501 return Result; 1502 } 1503 1504 /// MERGE_VALUES can always be eliminated. 1505 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) { 1506 WorklistRemover DeadNodes(*this); 1507 // Replacing results may cause a different MERGE_VALUES to suddenly 1508 // be CSE'd with N, and carry its uses with it. Iterate until no 1509 // uses remain, to ensure that the node can be safely deleted. 1510 // First add the users of this node to the work list so that they 1511 // can be tried again once they have new operands. 1512 AddUsersToWorklist(N); 1513 do { 1514 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) 1515 DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i)); 1516 } while (!N->use_empty()); 1517 deleteAndRecombine(N); 1518 return SDValue(N, 0); // Return N so it doesn't get rechecked! 1519 } 1520 1521 SDValue DAGCombiner::visitADD(SDNode *N) { 1522 SDValue N0 = N->getOperand(0); 1523 SDValue N1 = N->getOperand(1); 1524 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 1525 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 1526 EVT VT = N0.getValueType(); 1527 1528 // fold vector ops 1529 if (VT.isVector()) { 1530 SDValue FoldedVOp = SimplifyVBinOp(N); 1531 if (FoldedVOp.getNode()) return FoldedVOp; 1532 1533 // fold (add x, 0) -> x, vector edition 1534 if (ISD::isBuildVectorAllZeros(N1.getNode())) 1535 return N0; 1536 if (ISD::isBuildVectorAllZeros(N0.getNode())) 1537 return N1; 1538 } 1539 1540 // fold (add x, undef) -> undef 1541 if (N0.getOpcode() == ISD::UNDEF) 1542 return N0; 1543 if (N1.getOpcode() == ISD::UNDEF) 1544 return N1; 1545 // fold (add c1, c2) -> c1+c2 1546 if (N0C && N1C) 1547 return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C); 1548 // canonicalize constant to RHS 1549 if (N0C && !N1C) 1550 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0); 1551 // fold (add x, 0) -> x 1552 if (N1C && N1C->isNullValue()) 1553 return N0; 1554 // fold (add Sym, c) -> Sym+c 1555 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0)) 1556 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C && 1557 GA->getOpcode() == ISD::GlobalAddress) 1558 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT, 1559 GA->getOffset() + 1560 (uint64_t)N1C->getSExtValue()); 1561 // fold ((c1-A)+c2) -> (c1+c2)-A 1562 if (N1C && N0.getOpcode() == ISD::SUB) 1563 if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0))) 1564 return DAG.getNode(ISD::SUB, SDLoc(N), VT, 1565 DAG.getConstant(N1C->getAPIntValue()+ 1566 N0C->getAPIntValue(), VT), 1567 N0.getOperand(1)); 1568 // reassociate add 1569 SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1); 1570 if (RADD.getNode()) 1571 return RADD; 1572 // fold ((0-A) + B) -> B-A 1573 if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) && 1574 cast<ConstantSDNode>(N0.getOperand(0))->isNullValue()) 1575 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1)); 1576 // fold (A + (0-B)) -> A-B 1577 if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) && 1578 cast<ConstantSDNode>(N1.getOperand(0))->isNullValue()) 1579 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1)); 1580 // fold (A+(B-A)) -> B 1581 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1)) 1582 return N1.getOperand(0); 1583 // fold ((B-A)+A) -> B 1584 if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1)) 1585 return N0.getOperand(0); 1586 // fold (A+(B-(A+C))) to (B-C) 1587 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD && 1588 N0 == N1.getOperand(1).getOperand(0)) 1589 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0), 1590 N1.getOperand(1).getOperand(1)); 1591 // fold (A+(B-(C+A))) to (B-C) 1592 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD && 1593 N0 == N1.getOperand(1).getOperand(1)) 1594 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0), 1595 N1.getOperand(1).getOperand(0)); 1596 // fold (A+((B-A)+or-C)) to (B+or-C) 1597 if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) && 1598 N1.getOperand(0).getOpcode() == ISD::SUB && 1599 N0 == N1.getOperand(0).getOperand(1)) 1600 return DAG.getNode(N1.getOpcode(), SDLoc(N), VT, 1601 N1.getOperand(0).getOperand(0), N1.getOperand(1)); 1602 1603 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant 1604 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) { 1605 SDValue N00 = N0.getOperand(0); 1606 SDValue N01 = N0.getOperand(1); 1607 SDValue N10 = N1.getOperand(0); 1608 SDValue N11 = N1.getOperand(1); 1609 1610 if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10)) 1611 return DAG.getNode(ISD::SUB, SDLoc(N), VT, 1612 DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10), 1613 DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11)); 1614 } 1615 1616 if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0))) 1617 return SDValue(N, 0); 1618 1619 // fold (a+b) -> (a|b) iff a and b share no bits. 1620 if (VT.isInteger() && !VT.isVector()) { 1621 APInt LHSZero, LHSOne; 1622 APInt RHSZero, RHSOne; 1623 DAG.computeKnownBits(N0, LHSZero, LHSOne); 1624 1625 if (LHSZero.getBoolValue()) { 1626 DAG.computeKnownBits(N1, RHSZero, RHSOne); 1627 1628 // If all possibly-set bits on the LHS are clear on the RHS, return an OR. 1629 // If all possibly-set bits on the RHS are clear on the LHS, return an OR. 1630 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){ 1631 if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT)) 1632 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1); 1633 } 1634 } 1635 } 1636 1637 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n)) 1638 if (N1.getOpcode() == ISD::SHL && 1639 N1.getOperand(0).getOpcode() == ISD::SUB) 1640 if (ConstantSDNode *C = 1641 dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0))) 1642 if (C->getAPIntValue() == 0) 1643 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, 1644 DAG.getNode(ISD::SHL, SDLoc(N), VT, 1645 N1.getOperand(0).getOperand(1), 1646 N1.getOperand(1))); 1647 if (N0.getOpcode() == ISD::SHL && 1648 N0.getOperand(0).getOpcode() == ISD::SUB) 1649 if (ConstantSDNode *C = 1650 dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0))) 1651 if (C->getAPIntValue() == 0) 1652 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, 1653 DAG.getNode(ISD::SHL, SDLoc(N), VT, 1654 N0.getOperand(0).getOperand(1), 1655 N0.getOperand(1))); 1656 1657 if (N1.getOpcode() == ISD::AND) { 1658 SDValue AndOp0 = N1.getOperand(0); 1659 ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1)); 1660 unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0); 1661 unsigned DestBits = VT.getScalarType().getSizeInBits(); 1662 1663 // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x)) 1664 // and similar xforms where the inner op is either ~0 or 0. 1665 if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) { 1666 SDLoc DL(N); 1667 return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0); 1668 } 1669 } 1670 1671 // add (sext i1), X -> sub X, (zext i1) 1672 if (N0.getOpcode() == ISD::SIGN_EXTEND && 1673 N0.getOperand(0).getValueType() == MVT::i1 && 1674 !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) { 1675 SDLoc DL(N); 1676 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)); 1677 return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt); 1678 } 1679 1680 return SDValue(); 1681 } 1682 1683 SDValue DAGCombiner::visitADDC(SDNode *N) { 1684 SDValue N0 = N->getOperand(0); 1685 SDValue N1 = N->getOperand(1); 1686 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 1687 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 1688 EVT VT = N0.getValueType(); 1689 1690 // If the flag result is dead, turn this into an ADD. 1691 if (!N->hasAnyUseOfValue(1)) 1692 return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1), 1693 DAG.getNode(ISD::CARRY_FALSE, 1694 SDLoc(N), MVT::Glue)); 1695 1696 // canonicalize constant to RHS. 1697 if (N0C && !N1C) 1698 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0); 1699 1700 // fold (addc x, 0) -> x + no carry out 1701 if (N1C && N1C->isNullValue()) 1702 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, 1703 SDLoc(N), MVT::Glue)); 1704 1705 // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits. 1706 APInt LHSZero, LHSOne; 1707 APInt RHSZero, RHSOne; 1708 DAG.computeKnownBits(N0, LHSZero, LHSOne); 1709 1710 if (LHSZero.getBoolValue()) { 1711 DAG.computeKnownBits(N1, RHSZero, RHSOne); 1712 1713 // If all possibly-set bits on the LHS are clear on the RHS, return an OR. 1714 // If all possibly-set bits on the RHS are clear on the LHS, return an OR. 1715 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero) 1716 return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1), 1717 DAG.getNode(ISD::CARRY_FALSE, 1718 SDLoc(N), MVT::Glue)); 1719 } 1720 1721 return SDValue(); 1722 } 1723 1724 SDValue DAGCombiner::visitADDE(SDNode *N) { 1725 SDValue N0 = N->getOperand(0); 1726 SDValue N1 = N->getOperand(1); 1727 SDValue CarryIn = N->getOperand(2); 1728 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 1729 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 1730 1731 // canonicalize constant to RHS 1732 if (N0C && !N1C) 1733 return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(), 1734 N1, N0, CarryIn); 1735 1736 // fold (adde x, y, false) -> (addc x, y) 1737 if (CarryIn.getOpcode() == ISD::CARRY_FALSE) 1738 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1); 1739 1740 return SDValue(); 1741 } 1742 1743 // Since it may not be valid to emit a fold to zero for vector initializers 1744 // check if we can before folding. 1745 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT, 1746 SelectionDAG &DAG, 1747 bool LegalOperations, bool LegalTypes) { 1748 if (!VT.isVector()) 1749 return DAG.getConstant(0, VT); 1750 if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT)) 1751 return DAG.getConstant(0, VT); 1752 return SDValue(); 1753 } 1754 1755 SDValue DAGCombiner::visitSUB(SDNode *N) { 1756 SDValue N0 = N->getOperand(0); 1757 SDValue N1 = N->getOperand(1); 1758 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode()); 1759 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode()); 1760 ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr : 1761 dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode()); 1762 EVT VT = N0.getValueType(); 1763 1764 // fold vector ops 1765 if (VT.isVector()) { 1766 SDValue FoldedVOp = SimplifyVBinOp(N); 1767 if (FoldedVOp.getNode()) return FoldedVOp; 1768 1769 // fold (sub x, 0) -> x, vector edition 1770 if (ISD::isBuildVectorAllZeros(N1.getNode())) 1771 return N0; 1772 } 1773 1774 // fold (sub x, x) -> 0 1775 // FIXME: Refactor this and xor and other similar operations together. 1776 if (N0 == N1) 1777 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes); 1778 // fold (sub c1, c2) -> c1-c2 1779 if (N0C && N1C) 1780 return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C); 1781 // fold (sub x, c) -> (add x, -c) 1782 if (N1C) 1783 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, 1784 DAG.getConstant(-N1C->getAPIntValue(), VT)); 1785 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) 1786 if (N0C && N0C->isAllOnesValue()) 1787 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0); 1788 // fold A-(A-B) -> B 1789 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0)) 1790 return N1.getOperand(1); 1791 // fold (A+B)-A -> B 1792 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1) 1793 return N0.getOperand(1); 1794 // fold (A+B)-B -> A 1795 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1) 1796 return N0.getOperand(0); 1797 // fold C2-(A+C1) -> (C2-C1)-A 1798 if (N1.getOpcode() == ISD::ADD && N0C && N1C1) { 1799 SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(), 1800 VT); 1801 return DAG.getNode(ISD::SUB, SDLoc(N), VT, NewC, 1802 N1.getOperand(0)); 1803 } 1804 // fold ((A+(B+or-C))-B) -> A+or-C 1805 if (N0.getOpcode() == ISD::ADD && 1806 (N0.getOperand(1).getOpcode() == ISD::SUB || 1807 N0.getOperand(1).getOpcode() == ISD::ADD) && 1808 N0.getOperand(1).getOperand(0) == N1) 1809 return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT, 1810 N0.getOperand(0), N0.getOperand(1).getOperand(1)); 1811 // fold ((A+(C+B))-B) -> A+C 1812 if (N0.getOpcode() == ISD::ADD && 1813 N0.getOperand(1).getOpcode() == ISD::ADD && 1814 N0.getOperand(1).getOperand(1) == N1) 1815 return DAG.getNode(ISD::ADD, SDLoc(N), VT, 1816 N0.getOperand(0), N0.getOperand(1).getOperand(0)); 1817 // fold ((A-(B-C))-C) -> A-B 1818 if (N0.getOpcode() == ISD::SUB && 1819 N0.getOperand(1).getOpcode() == ISD::SUB && 1820 N0.getOperand(1).getOperand(1) == N1) 1821 return DAG.getNode(ISD::SUB, SDLoc(N), VT, 1822 N0.getOperand(0), N0.getOperand(1).getOperand(0)); 1823 1824 // If either operand of a sub is undef, the result is undef 1825 if (N0.getOpcode() == ISD::UNDEF) 1826 return N0; 1827 if (N1.getOpcode() == ISD::UNDEF) 1828 return N1; 1829 1830 // If the relocation model supports it, consider symbol offsets. 1831 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0)) 1832 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) { 1833 // fold (sub Sym, c) -> Sym-c 1834 if (N1C && GA->getOpcode() == ISD::GlobalAddress) 1835 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT, 1836 GA->getOffset() - 1837 (uint64_t)N1C->getSExtValue()); 1838 // fold (sub Sym+c1, Sym+c2) -> c1-c2 1839 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1)) 1840 if (GA->getGlobal() == GB->getGlobal()) 1841 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(), 1842 VT); 1843 } 1844 1845 return SDValue(); 1846 } 1847 1848 SDValue DAGCombiner::visitSUBC(SDNode *N) { 1849 SDValue N0 = N->getOperand(0); 1850 SDValue N1 = N->getOperand(1); 1851 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 1852 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 1853 EVT VT = N0.getValueType(); 1854 1855 // If the flag result is dead, turn this into an SUB. 1856 if (!N->hasAnyUseOfValue(1)) 1857 return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1), 1858 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N), 1859 MVT::Glue)); 1860 1861 // fold (subc x, x) -> 0 + no borrow 1862 if (N0 == N1) 1863 return CombineTo(N, DAG.getConstant(0, VT), 1864 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N), 1865 MVT::Glue)); 1866 1867 // fold (subc x, 0) -> x + no borrow 1868 if (N1C && N1C->isNullValue()) 1869 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N), 1870 MVT::Glue)); 1871 1872 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow 1873 if (N0C && N0C->isAllOnesValue()) 1874 return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0), 1875 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N), 1876 MVT::Glue)); 1877 1878 return SDValue(); 1879 } 1880 1881 SDValue DAGCombiner::visitSUBE(SDNode *N) { 1882 SDValue N0 = N->getOperand(0); 1883 SDValue N1 = N->getOperand(1); 1884 SDValue CarryIn = N->getOperand(2); 1885 1886 // fold (sube x, y, false) -> (subc x, y) 1887 if (CarryIn.getOpcode() == ISD::CARRY_FALSE) 1888 return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1); 1889 1890 return SDValue(); 1891 } 1892 1893 SDValue DAGCombiner::visitMUL(SDNode *N) { 1894 SDValue N0 = N->getOperand(0); 1895 SDValue N1 = N->getOperand(1); 1896 EVT VT = N0.getValueType(); 1897 1898 // fold (mul x, undef) -> 0 1899 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF) 1900 return DAG.getConstant(0, VT); 1901 1902 bool N0IsConst = false; 1903 bool N1IsConst = false; 1904 APInt ConstValue0, ConstValue1; 1905 // fold vector ops 1906 if (VT.isVector()) { 1907 SDValue FoldedVOp = SimplifyVBinOp(N); 1908 if (FoldedVOp.getNode()) return FoldedVOp; 1909 1910 N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0); 1911 N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1); 1912 } else { 1913 N0IsConst = dyn_cast<ConstantSDNode>(N0) != nullptr; 1914 ConstValue0 = N0IsConst ? (dyn_cast<ConstantSDNode>(N0))->getAPIntValue() 1915 : APInt(); 1916 N1IsConst = dyn_cast<ConstantSDNode>(N1) != nullptr; 1917 ConstValue1 = N1IsConst ? (dyn_cast<ConstantSDNode>(N1))->getAPIntValue() 1918 : APInt(); 1919 } 1920 1921 // fold (mul c1, c2) -> c1*c2 1922 if (N0IsConst && N1IsConst) 1923 return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0.getNode(), N1.getNode()); 1924 1925 // canonicalize constant to RHS 1926 if (N0IsConst && !N1IsConst) 1927 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0); 1928 // fold (mul x, 0) -> 0 1929 if (N1IsConst && ConstValue1 == 0) 1930 return N1; 1931 // We require a splat of the entire scalar bit width for non-contiguous 1932 // bit patterns. 1933 bool IsFullSplat = 1934 ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits(); 1935 // fold (mul x, 1) -> x 1936 if (N1IsConst && ConstValue1 == 1 && IsFullSplat) 1937 return N0; 1938 // fold (mul x, -1) -> 0-x 1939 if (N1IsConst && ConstValue1.isAllOnesValue()) 1940 return DAG.getNode(ISD::SUB, SDLoc(N), VT, 1941 DAG.getConstant(0, VT), N0); 1942 // fold (mul x, (1 << c)) -> x << c 1943 if (N1IsConst && ConstValue1.isPowerOf2() && IsFullSplat) 1944 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, 1945 DAG.getConstant(ConstValue1.logBase2(), 1946 getShiftAmountTy(N0.getValueType()))); 1947 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c 1948 if (N1IsConst && (-ConstValue1).isPowerOf2() && IsFullSplat) { 1949 unsigned Log2Val = (-ConstValue1).logBase2(); 1950 // FIXME: If the input is something that is easily negated (e.g. a 1951 // single-use add), we should put the negate there. 1952 return DAG.getNode(ISD::SUB, SDLoc(N), VT, 1953 DAG.getConstant(0, VT), 1954 DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, 1955 DAG.getConstant(Log2Val, 1956 getShiftAmountTy(N0.getValueType())))); 1957 } 1958 1959 APInt Val; 1960 // (mul (shl X, c1), c2) -> (mul X, c2 << c1) 1961 if (N1IsConst && N0.getOpcode() == ISD::SHL && 1962 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) || 1963 isa<ConstantSDNode>(N0.getOperand(1)))) { 1964 SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT, 1965 N1, N0.getOperand(1)); 1966 AddToWorklist(C3.getNode()); 1967 return DAG.getNode(ISD::MUL, SDLoc(N), VT, 1968 N0.getOperand(0), C3); 1969 } 1970 1971 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one 1972 // use. 1973 { 1974 SDValue Sh(nullptr,0), Y(nullptr,0); 1975 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)). 1976 if (N0.getOpcode() == ISD::SHL && 1977 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) || 1978 isa<ConstantSDNode>(N0.getOperand(1))) && 1979 N0.getNode()->hasOneUse()) { 1980 Sh = N0; Y = N1; 1981 } else if (N1.getOpcode() == ISD::SHL && 1982 isa<ConstantSDNode>(N1.getOperand(1)) && 1983 N1.getNode()->hasOneUse()) { 1984 Sh = N1; Y = N0; 1985 } 1986 1987 if (Sh.getNode()) { 1988 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT, 1989 Sh.getOperand(0), Y); 1990 return DAG.getNode(ISD::SHL, SDLoc(N), VT, 1991 Mul, Sh.getOperand(1)); 1992 } 1993 } 1994 1995 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2) 1996 if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() && 1997 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) || 1998 isa<ConstantSDNode>(N0.getOperand(1)))) 1999 return DAG.getNode(ISD::ADD, SDLoc(N), VT, 2000 DAG.getNode(ISD::MUL, SDLoc(N0), VT, 2001 N0.getOperand(0), N1), 2002 DAG.getNode(ISD::MUL, SDLoc(N1), VT, 2003 N0.getOperand(1), N1)); 2004 2005 // reassociate mul 2006 SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1); 2007 if (RMUL.getNode()) 2008 return RMUL; 2009 2010 return SDValue(); 2011 } 2012 2013 SDValue DAGCombiner::visitSDIV(SDNode *N) { 2014 SDValue N0 = N->getOperand(0); 2015 SDValue N1 = N->getOperand(1); 2016 ConstantSDNode *N0C = isConstOrConstSplat(N0); 2017 ConstantSDNode *N1C = isConstOrConstSplat(N1); 2018 EVT VT = N->getValueType(0); 2019 2020 // fold vector ops 2021 if (VT.isVector()) { 2022 SDValue FoldedVOp = SimplifyVBinOp(N); 2023 if (FoldedVOp.getNode()) return FoldedVOp; 2024 } 2025 2026 // fold (sdiv c1, c2) -> c1/c2 2027 if (N0C && N1C && !N1C->isNullValue()) 2028 return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C); 2029 // fold (sdiv X, 1) -> X 2030 if (N1C && N1C->getAPIntValue() == 1LL) 2031 return N0; 2032 // fold (sdiv X, -1) -> 0-X 2033 if (N1C && N1C->isAllOnesValue()) 2034 return DAG.getNode(ISD::SUB, SDLoc(N), VT, 2035 DAG.getConstant(0, VT), N0); 2036 // If we know the sign bits of both operands are zero, strength reduce to a 2037 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2 2038 if (!VT.isVector()) { 2039 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0)) 2040 return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(), 2041 N0, N1); 2042 } 2043 2044 // fold (sdiv X, pow2) -> simple ops after legalize 2045 if (N1C && !N1C->isNullValue() && (N1C->getAPIntValue().isPowerOf2() || 2046 (-N1C->getAPIntValue()).isPowerOf2())) { 2047 // If dividing by powers of two is cheap, then don't perform the following 2048 // fold. 2049 if (TLI.isPow2SDivCheap()) 2050 return SDValue(); 2051 2052 // Target-specific implementation of sdiv x, pow2. 2053 SDValue Res = BuildSDIVPow2(N); 2054 if (Res.getNode()) 2055 return Res; 2056 2057 unsigned lg2 = N1C->getAPIntValue().countTrailingZeros(); 2058 2059 // Splat the sign bit into the register 2060 SDValue SGN = 2061 DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, 2062 DAG.getConstant(VT.getScalarSizeInBits() - 1, 2063 getShiftAmountTy(N0.getValueType()))); 2064 AddToWorklist(SGN.getNode()); 2065 2066 // Add (N0 < 0) ? abs2 - 1 : 0; 2067 SDValue SRL = 2068 DAG.getNode(ISD::SRL, SDLoc(N), VT, SGN, 2069 DAG.getConstant(VT.getScalarSizeInBits() - lg2, 2070 getShiftAmountTy(SGN.getValueType()))); 2071 SDValue ADD = DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, SRL); 2072 AddToWorklist(SRL.getNode()); 2073 AddToWorklist(ADD.getNode()); // Divide by pow2 2074 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), VT, ADD, 2075 DAG.getConstant(lg2, getShiftAmountTy(ADD.getValueType()))); 2076 2077 // If we're dividing by a positive value, we're done. Otherwise, we must 2078 // negate the result. 2079 if (N1C->getAPIntValue().isNonNegative()) 2080 return SRA; 2081 2082 AddToWorklist(SRA.getNode()); 2083 return DAG.getNode(ISD::SUB, SDLoc(N), VT, DAG.getConstant(0, VT), SRA); 2084 } 2085 2086 // if integer divide is expensive and we satisfy the requirements, emit an 2087 // alternate sequence. 2088 if (N1C && !TLI.isIntDivCheap()) { 2089 SDValue Op = BuildSDIV(N); 2090 if (Op.getNode()) return Op; 2091 } 2092 2093 // undef / X -> 0 2094 if (N0.getOpcode() == ISD::UNDEF) 2095 return DAG.getConstant(0, VT); 2096 // X / undef -> undef 2097 if (N1.getOpcode() == ISD::UNDEF) 2098 return N1; 2099 2100 return SDValue(); 2101 } 2102 2103 SDValue DAGCombiner::visitUDIV(SDNode *N) { 2104 SDValue N0 = N->getOperand(0); 2105 SDValue N1 = N->getOperand(1); 2106 ConstantSDNode *N0C = isConstOrConstSplat(N0); 2107 ConstantSDNode *N1C = isConstOrConstSplat(N1); 2108 EVT VT = N->getValueType(0); 2109 2110 // fold vector ops 2111 if (VT.isVector()) { 2112 SDValue FoldedVOp = SimplifyVBinOp(N); 2113 if (FoldedVOp.getNode()) return FoldedVOp; 2114 } 2115 2116 // fold (udiv c1, c2) -> c1/c2 2117 if (N0C && N1C && !N1C->isNullValue()) 2118 return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C); 2119 // fold (udiv x, (1 << c)) -> x >>u c 2120 if (N1C && N1C->getAPIntValue().isPowerOf2()) 2121 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, 2122 DAG.getConstant(N1C->getAPIntValue().logBase2(), 2123 getShiftAmountTy(N0.getValueType()))); 2124 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2 2125 if (N1.getOpcode() == ISD::SHL) { 2126 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) { 2127 if (SHC->getAPIntValue().isPowerOf2()) { 2128 EVT ADDVT = N1.getOperand(1).getValueType(); 2129 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N), ADDVT, 2130 N1.getOperand(1), 2131 DAG.getConstant(SHC->getAPIntValue() 2132 .logBase2(), 2133 ADDVT)); 2134 AddToWorklist(Add.getNode()); 2135 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, Add); 2136 } 2137 } 2138 } 2139 // fold (udiv x, c) -> alternate 2140 if (N1C && !TLI.isIntDivCheap()) { 2141 SDValue Op = BuildUDIV(N); 2142 if (Op.getNode()) return Op; 2143 } 2144 2145 // undef / X -> 0 2146 if (N0.getOpcode() == ISD::UNDEF) 2147 return DAG.getConstant(0, VT); 2148 // X / undef -> undef 2149 if (N1.getOpcode() == ISD::UNDEF) 2150 return N1; 2151 2152 return SDValue(); 2153 } 2154 2155 SDValue DAGCombiner::visitSREM(SDNode *N) { 2156 SDValue N0 = N->getOperand(0); 2157 SDValue N1 = N->getOperand(1); 2158 ConstantSDNode *N0C = isConstOrConstSplat(N0); 2159 ConstantSDNode *N1C = isConstOrConstSplat(N1); 2160 EVT VT = N->getValueType(0); 2161 2162 // fold (srem c1, c2) -> c1%c2 2163 if (N0C && N1C && !N1C->isNullValue()) 2164 return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C); 2165 // If we know the sign bits of both operands are zero, strength reduce to a 2166 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15 2167 if (!VT.isVector()) { 2168 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0)) 2169 return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1); 2170 } 2171 2172 // If X/C can be simplified by the division-by-constant logic, lower 2173 // X%C to the equivalent of X-X/C*C. 2174 if (N1C && !N1C->isNullValue()) { 2175 SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1); 2176 AddToWorklist(Div.getNode()); 2177 SDValue OptimizedDiv = combine(Div.getNode()); 2178 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) { 2179 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT, 2180 OptimizedDiv, N1); 2181 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul); 2182 AddToWorklist(Mul.getNode()); 2183 return Sub; 2184 } 2185 } 2186 2187 // undef % X -> 0 2188 if (N0.getOpcode() == ISD::UNDEF) 2189 return DAG.getConstant(0, VT); 2190 // X % undef -> undef 2191 if (N1.getOpcode() == ISD::UNDEF) 2192 return N1; 2193 2194 return SDValue(); 2195 } 2196 2197 SDValue DAGCombiner::visitUREM(SDNode *N) { 2198 SDValue N0 = N->getOperand(0); 2199 SDValue N1 = N->getOperand(1); 2200 ConstantSDNode *N0C = isConstOrConstSplat(N0); 2201 ConstantSDNode *N1C = isConstOrConstSplat(N1); 2202 EVT VT = N->getValueType(0); 2203 2204 // fold (urem c1, c2) -> c1%c2 2205 if (N0C && N1C && !N1C->isNullValue()) 2206 return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C); 2207 // fold (urem x, pow2) -> (and x, pow2-1) 2208 if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2()) 2209 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, 2210 DAG.getConstant(N1C->getAPIntValue()-1,VT)); 2211 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1)) 2212 if (N1.getOpcode() == ISD::SHL) { 2213 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) { 2214 if (SHC->getAPIntValue().isPowerOf2()) { 2215 SDValue Add = 2216 DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, 2217 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), 2218 VT)); 2219 AddToWorklist(Add.getNode()); 2220 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, Add); 2221 } 2222 } 2223 } 2224 2225 // If X/C can be simplified by the division-by-constant logic, lower 2226 // X%C to the equivalent of X-X/C*C. 2227 if (N1C && !N1C->isNullValue()) { 2228 SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1); 2229 AddToWorklist(Div.getNode()); 2230 SDValue OptimizedDiv = combine(Div.getNode()); 2231 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) { 2232 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT, 2233 OptimizedDiv, N1); 2234 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul); 2235 AddToWorklist(Mul.getNode()); 2236 return Sub; 2237 } 2238 } 2239 2240 // undef % X -> 0 2241 if (N0.getOpcode() == ISD::UNDEF) 2242 return DAG.getConstant(0, VT); 2243 // X % undef -> undef 2244 if (N1.getOpcode() == ISD::UNDEF) 2245 return N1; 2246 2247 return SDValue(); 2248 } 2249 2250 SDValue DAGCombiner::visitMULHS(SDNode *N) { 2251 SDValue N0 = N->getOperand(0); 2252 SDValue N1 = N->getOperand(1); 2253 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 2254 EVT VT = N->getValueType(0); 2255 SDLoc DL(N); 2256 2257 // fold (mulhs x, 0) -> 0 2258 if (N1C && N1C->isNullValue()) 2259 return N1; 2260 // fold (mulhs x, 1) -> (sra x, size(x)-1) 2261 if (N1C && N1C->getAPIntValue() == 1) 2262 return DAG.getNode(ISD::SRA, SDLoc(N), N0.getValueType(), N0, 2263 DAG.getConstant(N0.getValueType().getSizeInBits() - 1, 2264 getShiftAmountTy(N0.getValueType()))); 2265 // fold (mulhs x, undef) -> 0 2266 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF) 2267 return DAG.getConstant(0, VT); 2268 2269 // If the type twice as wide is legal, transform the mulhs to a wider multiply 2270 // plus a shift. 2271 if (VT.isSimple() && !VT.isVector()) { 2272 MVT Simple = VT.getSimpleVT(); 2273 unsigned SimpleSize = Simple.getSizeInBits(); 2274 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 2275 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 2276 N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0); 2277 N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1); 2278 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1); 2279 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1, 2280 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType()))); 2281 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1); 2282 } 2283 } 2284 2285 return SDValue(); 2286 } 2287 2288 SDValue DAGCombiner::visitMULHU(SDNode *N) { 2289 SDValue N0 = N->getOperand(0); 2290 SDValue N1 = N->getOperand(1); 2291 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 2292 EVT VT = N->getValueType(0); 2293 SDLoc DL(N); 2294 2295 // fold (mulhu x, 0) -> 0 2296 if (N1C && N1C->isNullValue()) 2297 return N1; 2298 // fold (mulhu x, 1) -> 0 2299 if (N1C && N1C->getAPIntValue() == 1) 2300 return DAG.getConstant(0, N0.getValueType()); 2301 // fold (mulhu x, undef) -> 0 2302 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF) 2303 return DAG.getConstant(0, VT); 2304 2305 // If the type twice as wide is legal, transform the mulhu to a wider multiply 2306 // plus a shift. 2307 if (VT.isSimple() && !VT.isVector()) { 2308 MVT Simple = VT.getSimpleVT(); 2309 unsigned SimpleSize = Simple.getSizeInBits(); 2310 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 2311 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 2312 N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0); 2313 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1); 2314 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1); 2315 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1, 2316 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType()))); 2317 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1); 2318 } 2319 } 2320 2321 return SDValue(); 2322 } 2323 2324 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp 2325 /// give the opcodes for the two computations that are being performed. Return 2326 /// true if a simplification was made. 2327 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp, 2328 unsigned HiOp) { 2329 // If the high half is not needed, just compute the low half. 2330 bool HiExists = N->hasAnyUseOfValue(1); 2331 if (!HiExists && 2332 (!LegalOperations || 2333 TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) { 2334 SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops()); 2335 return CombineTo(N, Res, Res); 2336 } 2337 2338 // If the low half is not needed, just compute the high half. 2339 bool LoExists = N->hasAnyUseOfValue(0); 2340 if (!LoExists && 2341 (!LegalOperations || 2342 TLI.isOperationLegal(HiOp, N->getValueType(1)))) { 2343 SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops()); 2344 return CombineTo(N, Res, Res); 2345 } 2346 2347 // If both halves are used, return as it is. 2348 if (LoExists && HiExists) 2349 return SDValue(); 2350 2351 // If the two computed results can be simplified separately, separate them. 2352 if (LoExists) { 2353 SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops()); 2354 AddToWorklist(Lo.getNode()); 2355 SDValue LoOpt = combine(Lo.getNode()); 2356 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() && 2357 (!LegalOperations || 2358 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType()))) 2359 return CombineTo(N, LoOpt, LoOpt); 2360 } 2361 2362 if (HiExists) { 2363 SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops()); 2364 AddToWorklist(Hi.getNode()); 2365 SDValue HiOpt = combine(Hi.getNode()); 2366 if (HiOpt.getNode() && HiOpt != Hi && 2367 (!LegalOperations || 2368 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType()))) 2369 return CombineTo(N, HiOpt, HiOpt); 2370 } 2371 2372 return SDValue(); 2373 } 2374 2375 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) { 2376 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS); 2377 if (Res.getNode()) return Res; 2378 2379 EVT VT = N->getValueType(0); 2380 SDLoc DL(N); 2381 2382 // If the type twice as wide is legal, transform the mulhu to a wider multiply 2383 // plus a shift. 2384 if (VT.isSimple() && !VT.isVector()) { 2385 MVT Simple = VT.getSimpleVT(); 2386 unsigned SimpleSize = Simple.getSizeInBits(); 2387 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 2388 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 2389 SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0)); 2390 SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1)); 2391 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi); 2392 // Compute the high part as N1. 2393 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo, 2394 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType()))); 2395 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi); 2396 // Compute the low part as N0. 2397 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo); 2398 return CombineTo(N, Lo, Hi); 2399 } 2400 } 2401 2402 return SDValue(); 2403 } 2404 2405 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) { 2406 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU); 2407 if (Res.getNode()) return Res; 2408 2409 EVT VT = N->getValueType(0); 2410 SDLoc DL(N); 2411 2412 // If the type twice as wide is legal, transform the mulhu to a wider multiply 2413 // plus a shift. 2414 if (VT.isSimple() && !VT.isVector()) { 2415 MVT Simple = VT.getSimpleVT(); 2416 unsigned SimpleSize = Simple.getSizeInBits(); 2417 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 2418 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 2419 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0)); 2420 SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1)); 2421 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi); 2422 // Compute the high part as N1. 2423 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo, 2424 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType()))); 2425 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi); 2426 // Compute the low part as N0. 2427 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo); 2428 return CombineTo(N, Lo, Hi); 2429 } 2430 } 2431 2432 return SDValue(); 2433 } 2434 2435 SDValue DAGCombiner::visitSMULO(SDNode *N) { 2436 // (smulo x, 2) -> (saddo x, x) 2437 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1))) 2438 if (C2->getAPIntValue() == 2) 2439 return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(), 2440 N->getOperand(0), N->getOperand(0)); 2441 2442 return SDValue(); 2443 } 2444 2445 SDValue DAGCombiner::visitUMULO(SDNode *N) { 2446 // (umulo x, 2) -> (uaddo x, x) 2447 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1))) 2448 if (C2->getAPIntValue() == 2) 2449 return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(), 2450 N->getOperand(0), N->getOperand(0)); 2451 2452 return SDValue(); 2453 } 2454 2455 SDValue DAGCombiner::visitSDIVREM(SDNode *N) { 2456 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM); 2457 if (Res.getNode()) return Res; 2458 2459 return SDValue(); 2460 } 2461 2462 SDValue DAGCombiner::visitUDIVREM(SDNode *N) { 2463 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM); 2464 if (Res.getNode()) return Res; 2465 2466 return SDValue(); 2467 } 2468 2469 /// If this is a binary operator with two operands of the same opcode, try to 2470 /// simplify it. 2471 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) { 2472 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1); 2473 EVT VT = N0.getValueType(); 2474 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!"); 2475 2476 // Bail early if none of these transforms apply. 2477 if (N0.getNode()->getNumOperands() == 0) return SDValue(); 2478 2479 // For each of OP in AND/OR/XOR: 2480 // fold (OP (zext x), (zext y)) -> (zext (OP x, y)) 2481 // fold (OP (sext x), (sext y)) -> (sext (OP x, y)) 2482 // fold (OP (aext x), (aext y)) -> (aext (OP x, y)) 2483 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free) 2484 // 2485 // do not sink logical op inside of a vector extend, since it may combine 2486 // into a vsetcc. 2487 EVT Op0VT = N0.getOperand(0).getValueType(); 2488 if ((N0.getOpcode() == ISD::ZERO_EXTEND || 2489 N0.getOpcode() == ISD::SIGN_EXTEND || 2490 // Avoid infinite looping with PromoteIntBinOp. 2491 (N0.getOpcode() == ISD::ANY_EXTEND && 2492 (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) || 2493 (N0.getOpcode() == ISD::TRUNCATE && 2494 (!TLI.isZExtFree(VT, Op0VT) || 2495 !TLI.isTruncateFree(Op0VT, VT)) && 2496 TLI.isTypeLegal(Op0VT))) && 2497 !VT.isVector() && 2498 Op0VT == N1.getOperand(0).getValueType() && 2499 (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) { 2500 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0), 2501 N0.getOperand(0).getValueType(), 2502 N0.getOperand(0), N1.getOperand(0)); 2503 AddToWorklist(ORNode.getNode()); 2504 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode); 2505 } 2506 2507 // For each of OP in SHL/SRL/SRA/AND... 2508 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z) 2509 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z) 2510 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z) 2511 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL || 2512 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) && 2513 N0.getOperand(1) == N1.getOperand(1)) { 2514 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0), 2515 N0.getOperand(0).getValueType(), 2516 N0.getOperand(0), N1.getOperand(0)); 2517 AddToWorklist(ORNode.getNode()); 2518 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, 2519 ORNode, N0.getOperand(1)); 2520 } 2521 2522 // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B)) 2523 // Only perform this optimization after type legalization and before 2524 // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by 2525 // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and 2526 // we don't want to undo this promotion. 2527 // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper 2528 // on scalars. 2529 if ((N0.getOpcode() == ISD::BITCAST || 2530 N0.getOpcode() == ISD::SCALAR_TO_VECTOR) && 2531 Level == AfterLegalizeTypes) { 2532 SDValue In0 = N0.getOperand(0); 2533 SDValue In1 = N1.getOperand(0); 2534 EVT In0Ty = In0.getValueType(); 2535 EVT In1Ty = In1.getValueType(); 2536 SDLoc DL(N); 2537 // If both incoming values are integers, and the original types are the 2538 // same. 2539 if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) { 2540 SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1); 2541 SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op); 2542 AddToWorklist(Op.getNode()); 2543 return BC; 2544 } 2545 } 2546 2547 // Xor/and/or are indifferent to the swizzle operation (shuffle of one value). 2548 // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B)) 2549 // If both shuffles use the same mask, and both shuffle within a single 2550 // vector, then it is worthwhile to move the swizzle after the operation. 2551 // The type-legalizer generates this pattern when loading illegal 2552 // vector types from memory. In many cases this allows additional shuffle 2553 // optimizations. 2554 // There are other cases where moving the shuffle after the xor/and/or 2555 // is profitable even if shuffles don't perform a swizzle. 2556 // If both shuffles use the same mask, and both shuffles have the same first 2557 // or second operand, then it might still be profitable to move the shuffle 2558 // after the xor/and/or operation. 2559 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) { 2560 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0); 2561 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1); 2562 2563 assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() && 2564 "Inputs to shuffles are not the same type"); 2565 2566 // Check that both shuffles use the same mask. The masks are known to be of 2567 // the same length because the result vector type is the same. 2568 // Check also that shuffles have only one use to avoid introducing extra 2569 // instructions. 2570 if (SVN0->hasOneUse() && SVN1->hasOneUse() && 2571 SVN0->getMask().equals(SVN1->getMask())) { 2572 SDValue ShOp = N0->getOperand(1); 2573 2574 // Don't try to fold this node if it requires introducing a 2575 // build vector of all zeros that might be illegal at this stage. 2576 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) { 2577 if (!LegalTypes) 2578 ShOp = DAG.getConstant(0, VT); 2579 else 2580 ShOp = SDValue(); 2581 } 2582 2583 // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C) 2584 // (OR (shuf (A, C), shuf (B, C)) -> shuf (OR (A, B), C) 2585 // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0) 2586 if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) { 2587 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT, 2588 N0->getOperand(0), N1->getOperand(0)); 2589 AddToWorklist(NewNode.getNode()); 2590 return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp, 2591 &SVN0->getMask()[0]); 2592 } 2593 2594 // Don't try to fold this node if it requires introducing a 2595 // build vector of all zeros that might be illegal at this stage. 2596 ShOp = N0->getOperand(0); 2597 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) { 2598 if (!LegalTypes) 2599 ShOp = DAG.getConstant(0, VT); 2600 else 2601 ShOp = SDValue(); 2602 } 2603 2604 // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B)) 2605 // (OR (shuf (C, A), shuf (C, B)) -> shuf (C, OR (A, B)) 2606 // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B)) 2607 if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) { 2608 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT, 2609 N0->getOperand(1), N1->getOperand(1)); 2610 AddToWorklist(NewNode.getNode()); 2611 return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode, 2612 &SVN0->getMask()[0]); 2613 } 2614 } 2615 } 2616 2617 return SDValue(); 2618 } 2619 2620 SDValue DAGCombiner::visitAND(SDNode *N) { 2621 SDValue N0 = N->getOperand(0); 2622 SDValue N1 = N->getOperand(1); 2623 SDValue LL, LR, RL, RR, CC0, CC1; 2624 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 2625 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 2626 EVT VT = N1.getValueType(); 2627 unsigned BitWidth = VT.getScalarType().getSizeInBits(); 2628 2629 // fold vector ops 2630 if (VT.isVector()) { 2631 SDValue FoldedVOp = SimplifyVBinOp(N); 2632 if (FoldedVOp.getNode()) return FoldedVOp; 2633 2634 // fold (and x, 0) -> 0, vector edition 2635 if (ISD::isBuildVectorAllZeros(N0.getNode())) 2636 // do not return N0, because undef node may exist in N0 2637 return DAG.getConstant( 2638 APInt::getNullValue( 2639 N0.getValueType().getScalarType().getSizeInBits()), 2640 N0.getValueType()); 2641 if (ISD::isBuildVectorAllZeros(N1.getNode())) 2642 // do not return N1, because undef node may exist in N1 2643 return DAG.getConstant( 2644 APInt::getNullValue( 2645 N1.getValueType().getScalarType().getSizeInBits()), 2646 N1.getValueType()); 2647 2648 // fold (and x, -1) -> x, vector edition 2649 if (ISD::isBuildVectorAllOnes(N0.getNode())) 2650 return N1; 2651 if (ISD::isBuildVectorAllOnes(N1.getNode())) 2652 return N0; 2653 } 2654 2655 // fold (and x, undef) -> 0 2656 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF) 2657 return DAG.getConstant(0, VT); 2658 // fold (and c1, c2) -> c1&c2 2659 if (N0C && N1C) 2660 return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C); 2661 // canonicalize constant to RHS 2662 if (N0C && !N1C) 2663 return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0); 2664 // fold (and x, -1) -> x 2665 if (N1C && N1C->isAllOnesValue()) 2666 return N0; 2667 // if (and x, c) is known to be zero, return 0 2668 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0), 2669 APInt::getAllOnesValue(BitWidth))) 2670 return DAG.getConstant(0, VT); 2671 // reassociate and 2672 SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1); 2673 if (RAND.getNode()) 2674 return RAND; 2675 // fold (and (or x, C), D) -> D if (C & D) == D 2676 if (N1C && N0.getOpcode() == ISD::OR) 2677 if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) 2678 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue()) 2679 return N1; 2680 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits. 2681 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) { 2682 SDValue N0Op0 = N0.getOperand(0); 2683 APInt Mask = ~N1C->getAPIntValue(); 2684 Mask = Mask.trunc(N0Op0.getValueSizeInBits()); 2685 if (DAG.MaskedValueIsZero(N0Op0, Mask)) { 2686 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), 2687 N0.getValueType(), N0Op0); 2688 2689 // Replace uses of the AND with uses of the Zero extend node. 2690 CombineTo(N, Zext); 2691 2692 // We actually want to replace all uses of the any_extend with the 2693 // zero_extend, to avoid duplicating things. This will later cause this 2694 // AND to be folded. 2695 CombineTo(N0.getNode(), Zext); 2696 return SDValue(N, 0); // Return N so it doesn't get rechecked! 2697 } 2698 } 2699 // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) -> 2700 // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must 2701 // already be zero by virtue of the width of the base type of the load. 2702 // 2703 // the 'X' node here can either be nothing or an extract_vector_elt to catch 2704 // more cases. 2705 if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT && 2706 N0.getOperand(0).getOpcode() == ISD::LOAD) || 2707 N0.getOpcode() == ISD::LOAD) { 2708 LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ? 2709 N0 : N0.getOperand(0) ); 2710 2711 // Get the constant (if applicable) the zero'th operand is being ANDed with. 2712 // This can be a pure constant or a vector splat, in which case we treat the 2713 // vector as a scalar and use the splat value. 2714 APInt Constant = APInt::getNullValue(1); 2715 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) { 2716 Constant = C->getAPIntValue(); 2717 } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) { 2718 APInt SplatValue, SplatUndef; 2719 unsigned SplatBitSize; 2720 bool HasAnyUndefs; 2721 bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef, 2722 SplatBitSize, HasAnyUndefs); 2723 if (IsSplat) { 2724 // Undef bits can contribute to a possible optimisation if set, so 2725 // set them. 2726 SplatValue |= SplatUndef; 2727 2728 // The splat value may be something like "0x00FFFFFF", which means 0 for 2729 // the first vector value and FF for the rest, repeating. We need a mask 2730 // that will apply equally to all members of the vector, so AND all the 2731 // lanes of the constant together. 2732 EVT VT = Vector->getValueType(0); 2733 unsigned BitWidth = VT.getVectorElementType().getSizeInBits(); 2734 2735 // If the splat value has been compressed to a bitlength lower 2736 // than the size of the vector lane, we need to re-expand it to 2737 // the lane size. 2738 if (BitWidth > SplatBitSize) 2739 for (SplatValue = SplatValue.zextOrTrunc(BitWidth); 2740 SplatBitSize < BitWidth; 2741 SplatBitSize = SplatBitSize * 2) 2742 SplatValue |= SplatValue.shl(SplatBitSize); 2743 2744 Constant = APInt::getAllOnesValue(BitWidth); 2745 for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i) 2746 Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth); 2747 } 2748 } 2749 2750 // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is 2751 // actually legal and isn't going to get expanded, else this is a false 2752 // optimisation. 2753 bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD, 2754 Load->getMemoryVT()); 2755 2756 // Resize the constant to the same size as the original memory access before 2757 // extension. If it is still the AllOnesValue then this AND is completely 2758 // unneeded. 2759 Constant = 2760 Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits()); 2761 2762 bool B; 2763 switch (Load->getExtensionType()) { 2764 default: B = false; break; 2765 case ISD::EXTLOAD: B = CanZextLoadProfitably; break; 2766 case ISD::ZEXTLOAD: 2767 case ISD::NON_EXTLOAD: B = true; break; 2768 } 2769 2770 if (B && Constant.isAllOnesValue()) { 2771 // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to 2772 // preserve semantics once we get rid of the AND. 2773 SDValue NewLoad(Load, 0); 2774 if (Load->getExtensionType() == ISD::EXTLOAD) { 2775 NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD, 2776 Load->getValueType(0), SDLoc(Load), 2777 Load->getChain(), Load->getBasePtr(), 2778 Load->getOffset(), Load->getMemoryVT(), 2779 Load->getMemOperand()); 2780 // Replace uses of the EXTLOAD with the new ZEXTLOAD. 2781 if (Load->getNumValues() == 3) { 2782 // PRE/POST_INC loads have 3 values. 2783 SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1), 2784 NewLoad.getValue(2) }; 2785 CombineTo(Load, To, 3, true); 2786 } else { 2787 CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1)); 2788 } 2789 } 2790 2791 // Fold the AND away, taking care not to fold to the old load node if we 2792 // replaced it. 2793 CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0); 2794 2795 return SDValue(N, 0); // Return N so it doesn't get rechecked! 2796 } 2797 } 2798 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y)) 2799 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){ 2800 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get(); 2801 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get(); 2802 2803 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 && 2804 LL.getValueType().isInteger()) { 2805 // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0) 2806 if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) { 2807 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0), 2808 LR.getValueType(), LL, RL); 2809 AddToWorklist(ORNode.getNode()); 2810 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1); 2811 } 2812 // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1) 2813 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) { 2814 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0), 2815 LR.getValueType(), LL, RL); 2816 AddToWorklist(ANDNode.getNode()); 2817 return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1); 2818 } 2819 // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1) 2820 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) { 2821 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0), 2822 LR.getValueType(), LL, RL); 2823 AddToWorklist(ORNode.getNode()); 2824 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1); 2825 } 2826 } 2827 // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2) 2828 if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) && 2829 Op0 == Op1 && LL.getValueType().isInteger() && 2830 Op0 == ISD::SETNE && ((cast<ConstantSDNode>(LR)->isNullValue() && 2831 cast<ConstantSDNode>(RR)->isAllOnesValue()) || 2832 (cast<ConstantSDNode>(LR)->isAllOnesValue() && 2833 cast<ConstantSDNode>(RR)->isNullValue()))) { 2834 SDValue ADDNode = DAG.getNode(ISD::ADD, SDLoc(N0), LL.getValueType(), 2835 LL, DAG.getConstant(1, LL.getValueType())); 2836 AddToWorklist(ADDNode.getNode()); 2837 return DAG.getSetCC(SDLoc(N), VT, ADDNode, 2838 DAG.getConstant(2, LL.getValueType()), ISD::SETUGE); 2839 } 2840 // canonicalize equivalent to ll == rl 2841 if (LL == RR && LR == RL) { 2842 Op1 = ISD::getSetCCSwappedOperands(Op1); 2843 std::swap(RL, RR); 2844 } 2845 if (LL == RL && LR == RR) { 2846 bool isInteger = LL.getValueType().isInteger(); 2847 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger); 2848 if (Result != ISD::SETCC_INVALID && 2849 (!LegalOperations || 2850 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) && 2851 TLI.isOperationLegal(ISD::SETCC, 2852 getSetCCResultType(N0.getSimpleValueType()))))) 2853 return DAG.getSetCC(SDLoc(N), N0.getValueType(), 2854 LL, LR, Result); 2855 } 2856 } 2857 2858 // Simplify: (and (op x...), (op y...)) -> (op (and x, y)) 2859 if (N0.getOpcode() == N1.getOpcode()) { 2860 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N); 2861 if (Tmp.getNode()) return Tmp; 2862 } 2863 2864 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1) 2865 // fold (and (sra)) -> (and (srl)) when possible. 2866 if (!VT.isVector() && 2867 SimplifyDemandedBits(SDValue(N, 0))) 2868 return SDValue(N, 0); 2869 2870 // fold (zext_inreg (extload x)) -> (zextload x) 2871 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) { 2872 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 2873 EVT MemVT = LN0->getMemoryVT(); 2874 // If we zero all the possible extended bits, then we can turn this into 2875 // a zextload if we are running before legalize or the operation is legal. 2876 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits(); 2877 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth, 2878 BitWidth - MemVT.getScalarType().getSizeInBits())) && 2879 ((!LegalOperations && !LN0->isVolatile()) || 2880 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) { 2881 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT, 2882 LN0->getChain(), LN0->getBasePtr(), 2883 MemVT, LN0->getMemOperand()); 2884 AddToWorklist(N); 2885 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 2886 return SDValue(N, 0); // Return N so it doesn't get rechecked! 2887 } 2888 } 2889 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use 2890 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 2891 N0.hasOneUse()) { 2892 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 2893 EVT MemVT = LN0->getMemoryVT(); 2894 // If we zero all the possible extended bits, then we can turn this into 2895 // a zextload if we are running before legalize or the operation is legal. 2896 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits(); 2897 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth, 2898 BitWidth - MemVT.getScalarType().getSizeInBits())) && 2899 ((!LegalOperations && !LN0->isVolatile()) || 2900 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) { 2901 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT, 2902 LN0->getChain(), LN0->getBasePtr(), 2903 MemVT, LN0->getMemOperand()); 2904 AddToWorklist(N); 2905 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 2906 return SDValue(N, 0); // Return N so it doesn't get rechecked! 2907 } 2908 } 2909 2910 // fold (and (load x), 255) -> (zextload x, i8) 2911 // fold (and (extload x, i16), 255) -> (zextload x, i8) 2912 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8) 2913 if (N1C && (N0.getOpcode() == ISD::LOAD || 2914 (N0.getOpcode() == ISD::ANY_EXTEND && 2915 N0.getOperand(0).getOpcode() == ISD::LOAD))) { 2916 bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND; 2917 LoadSDNode *LN0 = HasAnyExt 2918 ? cast<LoadSDNode>(N0.getOperand(0)) 2919 : cast<LoadSDNode>(N0); 2920 if (LN0->getExtensionType() != ISD::SEXTLOAD && 2921 LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) { 2922 uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits(); 2923 if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){ 2924 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits); 2925 EVT LoadedVT = LN0->getMemoryVT(); 2926 2927 if (ExtVT == LoadedVT && 2928 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) { 2929 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT; 2930 2931 SDValue NewLoad = 2932 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy, 2933 LN0->getChain(), LN0->getBasePtr(), ExtVT, 2934 LN0->getMemOperand()); 2935 AddToWorklist(N); 2936 CombineTo(LN0, NewLoad, NewLoad.getValue(1)); 2937 return SDValue(N, 0); // Return N so it doesn't get rechecked! 2938 } 2939 2940 // Do not change the width of a volatile load. 2941 // Do not generate loads of non-round integer types since these can 2942 // be expensive (and would be wrong if the type is not byte sized). 2943 if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() && 2944 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) { 2945 EVT PtrType = LN0->getOperand(1).getValueType(); 2946 2947 unsigned Alignment = LN0->getAlignment(); 2948 SDValue NewPtr = LN0->getBasePtr(); 2949 2950 // For big endian targets, we need to add an offset to the pointer 2951 // to load the correct bytes. For little endian systems, we merely 2952 // need to read fewer bytes from the same pointer. 2953 if (TLI.isBigEndian()) { 2954 unsigned LVTStoreBytes = LoadedVT.getStoreSize(); 2955 unsigned EVTStoreBytes = ExtVT.getStoreSize(); 2956 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes; 2957 NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0), PtrType, 2958 NewPtr, DAG.getConstant(PtrOff, PtrType)); 2959 Alignment = MinAlign(Alignment, PtrOff); 2960 } 2961 2962 AddToWorklist(NewPtr.getNode()); 2963 2964 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT; 2965 SDValue Load = 2966 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy, 2967 LN0->getChain(), NewPtr, 2968 LN0->getPointerInfo(), 2969 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(), 2970 LN0->isInvariant(), Alignment, LN0->getAAInfo()); 2971 AddToWorklist(N); 2972 CombineTo(LN0, Load, Load.getValue(1)); 2973 return SDValue(N, 0); // Return N so it doesn't get rechecked! 2974 } 2975 } 2976 } 2977 } 2978 2979 if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL && 2980 VT.getSizeInBits() <= 64) { 2981 if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 2982 APInt ADDC = ADDI->getAPIntValue(); 2983 if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) { 2984 // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal 2985 // immediate for an add, but it is legal if its top c2 bits are set, 2986 // transform the ADD so the immediate doesn't need to be materialized 2987 // in a register. 2988 if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) { 2989 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(), 2990 SRLI->getZExtValue()); 2991 if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) { 2992 ADDC |= Mask; 2993 if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) { 2994 SDValue NewAdd = 2995 DAG.getNode(ISD::ADD, SDLoc(N0), VT, 2996 N0.getOperand(0), DAG.getConstant(ADDC, VT)); 2997 CombineTo(N0.getNode(), NewAdd); 2998 return SDValue(N, 0); // Return N so it doesn't get rechecked! 2999 } 3000 } 3001 } 3002 } 3003 } 3004 } 3005 3006 // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const) 3007 if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) { 3008 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0), 3009 N0.getOperand(1), false); 3010 if (BSwap.getNode()) 3011 return BSwap; 3012 } 3013 3014 return SDValue(); 3015 } 3016 3017 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16. 3018 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1, 3019 bool DemandHighBits) { 3020 if (!LegalOperations) 3021 return SDValue(); 3022 3023 EVT VT = N->getValueType(0); 3024 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16) 3025 return SDValue(); 3026 if (!TLI.isOperationLegal(ISD::BSWAP, VT)) 3027 return SDValue(); 3028 3029 // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00) 3030 bool LookPassAnd0 = false; 3031 bool LookPassAnd1 = false; 3032 if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL) 3033 std::swap(N0, N1); 3034 if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL) 3035 std::swap(N0, N1); 3036 if (N0.getOpcode() == ISD::AND) { 3037 if (!N0.getNode()->hasOneUse()) 3038 return SDValue(); 3039 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 3040 if (!N01C || N01C->getZExtValue() != 0xFF00) 3041 return SDValue(); 3042 N0 = N0.getOperand(0); 3043 LookPassAnd0 = true; 3044 } 3045 3046 if (N1.getOpcode() == ISD::AND) { 3047 if (!N1.getNode()->hasOneUse()) 3048 return SDValue(); 3049 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 3050 if (!N11C || N11C->getZExtValue() != 0xFF) 3051 return SDValue(); 3052 N1 = N1.getOperand(0); 3053 LookPassAnd1 = true; 3054 } 3055 3056 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL) 3057 std::swap(N0, N1); 3058 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL) 3059 return SDValue(); 3060 if (!N0.getNode()->hasOneUse() || 3061 !N1.getNode()->hasOneUse()) 3062 return SDValue(); 3063 3064 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 3065 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 3066 if (!N01C || !N11C) 3067 return SDValue(); 3068 if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8) 3069 return SDValue(); 3070 3071 // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8) 3072 SDValue N00 = N0->getOperand(0); 3073 if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) { 3074 if (!N00.getNode()->hasOneUse()) 3075 return SDValue(); 3076 ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1)); 3077 if (!N001C || N001C->getZExtValue() != 0xFF) 3078 return SDValue(); 3079 N00 = N00.getOperand(0); 3080 LookPassAnd0 = true; 3081 } 3082 3083 SDValue N10 = N1->getOperand(0); 3084 if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) { 3085 if (!N10.getNode()->hasOneUse()) 3086 return SDValue(); 3087 ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1)); 3088 if (!N101C || N101C->getZExtValue() != 0xFF00) 3089 return SDValue(); 3090 N10 = N10.getOperand(0); 3091 LookPassAnd1 = true; 3092 } 3093 3094 if (N00 != N10) 3095 return SDValue(); 3096 3097 // Make sure everything beyond the low halfword gets set to zero since the SRL 3098 // 16 will clear the top bits. 3099 unsigned OpSizeInBits = VT.getSizeInBits(); 3100 if (DemandHighBits && OpSizeInBits > 16) { 3101 // If the left-shift isn't masked out then the only way this is a bswap is 3102 // if all bits beyond the low 8 are 0. In that case the entire pattern 3103 // reduces to a left shift anyway: leave it for other parts of the combiner. 3104 if (!LookPassAnd0) 3105 return SDValue(); 3106 3107 // However, if the right shift isn't masked out then it might be because 3108 // it's not needed. See if we can spot that too. 3109 if (!LookPassAnd1 && 3110 !DAG.MaskedValueIsZero( 3111 N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16))) 3112 return SDValue(); 3113 } 3114 3115 SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00); 3116 if (OpSizeInBits > 16) 3117 Res = DAG.getNode(ISD::SRL, SDLoc(N), VT, Res, 3118 DAG.getConstant(OpSizeInBits-16, getShiftAmountTy(VT))); 3119 return Res; 3120 } 3121 3122 /// Return true if the specified node is an element that makes up a 32-bit 3123 /// packed halfword byteswap. 3124 /// ((x & 0x000000ff) << 8) | 3125 /// ((x & 0x0000ff00) >> 8) | 3126 /// ((x & 0x00ff0000) << 8) | 3127 /// ((x & 0xff000000) >> 8) 3128 static bool isBSwapHWordElement(SDValue N, SmallVectorImpl<SDNode *> &Parts) { 3129 if (!N.getNode()->hasOneUse()) 3130 return false; 3131 3132 unsigned Opc = N.getOpcode(); 3133 if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL) 3134 return false; 3135 3136 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1)); 3137 if (!N1C) 3138 return false; 3139 3140 unsigned Num; 3141 switch (N1C->getZExtValue()) { 3142 default: 3143 return false; 3144 case 0xFF: Num = 0; break; 3145 case 0xFF00: Num = 1; break; 3146 case 0xFF0000: Num = 2; break; 3147 case 0xFF000000: Num = 3; break; 3148 } 3149 3150 // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00). 3151 SDValue N0 = N.getOperand(0); 3152 if (Opc == ISD::AND) { 3153 if (Num == 0 || Num == 2) { 3154 // (x >> 8) & 0xff 3155 // (x >> 8) & 0xff0000 3156 if (N0.getOpcode() != ISD::SRL) 3157 return false; 3158 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 3159 if (!C || C->getZExtValue() != 8) 3160 return false; 3161 } else { 3162 // (x << 8) & 0xff00 3163 // (x << 8) & 0xff000000 3164 if (N0.getOpcode() != ISD::SHL) 3165 return false; 3166 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 3167 if (!C || C->getZExtValue() != 8) 3168 return false; 3169 } 3170 } else if (Opc == ISD::SHL) { 3171 // (x & 0xff) << 8 3172 // (x & 0xff0000) << 8 3173 if (Num != 0 && Num != 2) 3174 return false; 3175 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1)); 3176 if (!C || C->getZExtValue() != 8) 3177 return false; 3178 } else { // Opc == ISD::SRL 3179 // (x & 0xff00) >> 8 3180 // (x & 0xff000000) >> 8 3181 if (Num != 1 && Num != 3) 3182 return false; 3183 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1)); 3184 if (!C || C->getZExtValue() != 8) 3185 return false; 3186 } 3187 3188 if (Parts[Num]) 3189 return false; 3190 3191 Parts[Num] = N0.getOperand(0).getNode(); 3192 return true; 3193 } 3194 3195 /// Match a 32-bit packed halfword bswap. That is 3196 /// ((x & 0x000000ff) << 8) | 3197 /// ((x & 0x0000ff00) >> 8) | 3198 /// ((x & 0x00ff0000) << 8) | 3199 /// ((x & 0xff000000) >> 8) 3200 /// => (rotl (bswap x), 16) 3201 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) { 3202 if (!LegalOperations) 3203 return SDValue(); 3204 3205 EVT VT = N->getValueType(0); 3206 if (VT != MVT::i32) 3207 return SDValue(); 3208 if (!TLI.isOperationLegal(ISD::BSWAP, VT)) 3209 return SDValue(); 3210 3211 SmallVector<SDNode*,4> Parts(4, (SDNode*)nullptr); 3212 // Look for either 3213 // (or (or (and), (and)), (or (and), (and))) 3214 // (or (or (or (and), (and)), (and)), (and)) 3215 if (N0.getOpcode() != ISD::OR) 3216 return SDValue(); 3217 SDValue N00 = N0.getOperand(0); 3218 SDValue N01 = N0.getOperand(1); 3219 3220 if (N1.getOpcode() == ISD::OR && 3221 N00.getNumOperands() == 2 && N01.getNumOperands() == 2) { 3222 // (or (or (and), (and)), (or (and), (and))) 3223 SDValue N000 = N00.getOperand(0); 3224 if (!isBSwapHWordElement(N000, Parts)) 3225 return SDValue(); 3226 3227 SDValue N001 = N00.getOperand(1); 3228 if (!isBSwapHWordElement(N001, Parts)) 3229 return SDValue(); 3230 SDValue N010 = N01.getOperand(0); 3231 if (!isBSwapHWordElement(N010, Parts)) 3232 return SDValue(); 3233 SDValue N011 = N01.getOperand(1); 3234 if (!isBSwapHWordElement(N011, Parts)) 3235 return SDValue(); 3236 } else { 3237 // (or (or (or (and), (and)), (and)), (and)) 3238 if (!isBSwapHWordElement(N1, Parts)) 3239 return SDValue(); 3240 if (!isBSwapHWordElement(N01, Parts)) 3241 return SDValue(); 3242 if (N00.getOpcode() != ISD::OR) 3243 return SDValue(); 3244 SDValue N000 = N00.getOperand(0); 3245 if (!isBSwapHWordElement(N000, Parts)) 3246 return SDValue(); 3247 SDValue N001 = N00.getOperand(1); 3248 if (!isBSwapHWordElement(N001, Parts)) 3249 return SDValue(); 3250 } 3251 3252 // Make sure the parts are all coming from the same node. 3253 if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3]) 3254 return SDValue(); 3255 3256 SDValue BSwap = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, 3257 SDValue(Parts[0],0)); 3258 3259 // Result of the bswap should be rotated by 16. If it's not legal, then 3260 // do (x << 16) | (x >> 16). 3261 SDValue ShAmt = DAG.getConstant(16, getShiftAmountTy(VT)); 3262 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT)) 3263 return DAG.getNode(ISD::ROTL, SDLoc(N), VT, BSwap, ShAmt); 3264 if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT)) 3265 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, BSwap, ShAmt); 3266 return DAG.getNode(ISD::OR, SDLoc(N), VT, 3267 DAG.getNode(ISD::SHL, SDLoc(N), VT, BSwap, ShAmt), 3268 DAG.getNode(ISD::SRL, SDLoc(N), VT, BSwap, ShAmt)); 3269 } 3270 3271 SDValue DAGCombiner::visitOR(SDNode *N) { 3272 SDValue N0 = N->getOperand(0); 3273 SDValue N1 = N->getOperand(1); 3274 SDValue LL, LR, RL, RR, CC0, CC1; 3275 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 3276 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 3277 EVT VT = N1.getValueType(); 3278 3279 // fold vector ops 3280 if (VT.isVector()) { 3281 SDValue FoldedVOp = SimplifyVBinOp(N); 3282 if (FoldedVOp.getNode()) return FoldedVOp; 3283 3284 // fold (or x, 0) -> x, vector edition 3285 if (ISD::isBuildVectorAllZeros(N0.getNode())) 3286 return N1; 3287 if (ISD::isBuildVectorAllZeros(N1.getNode())) 3288 return N0; 3289 3290 // fold (or x, -1) -> -1, vector edition 3291 if (ISD::isBuildVectorAllOnes(N0.getNode())) 3292 // do not return N0, because undef node may exist in N0 3293 return DAG.getConstant( 3294 APInt::getAllOnesValue( 3295 N0.getValueType().getScalarType().getSizeInBits()), 3296 N0.getValueType()); 3297 if (ISD::isBuildVectorAllOnes(N1.getNode())) 3298 // do not return N1, because undef node may exist in N1 3299 return DAG.getConstant( 3300 APInt::getAllOnesValue( 3301 N1.getValueType().getScalarType().getSizeInBits()), 3302 N1.getValueType()); 3303 3304 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1) 3305 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2) 3306 // Do this only if the resulting shuffle is legal. 3307 if (isa<ShuffleVectorSDNode>(N0) && 3308 isa<ShuffleVectorSDNode>(N1) && 3309 // Avoid folding a node with illegal type. 3310 TLI.isTypeLegal(VT) && 3311 N0->getOperand(1) == N1->getOperand(1) && 3312 ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) { 3313 bool CanFold = true; 3314 unsigned NumElts = VT.getVectorNumElements(); 3315 const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0); 3316 const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1); 3317 // We construct two shuffle masks: 3318 // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand 3319 // and N1 as the second operand. 3320 // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand 3321 // and N0 as the second operand. 3322 // We do this because OR is commutable and therefore there might be 3323 // two ways to fold this node into a shuffle. 3324 SmallVector<int,4> Mask1; 3325 SmallVector<int,4> Mask2; 3326 3327 for (unsigned i = 0; i != NumElts && CanFold; ++i) { 3328 int M0 = SV0->getMaskElt(i); 3329 int M1 = SV1->getMaskElt(i); 3330 3331 // Both shuffle indexes are undef. Propagate Undef. 3332 if (M0 < 0 && M1 < 0) { 3333 Mask1.push_back(M0); 3334 Mask2.push_back(M0); 3335 continue; 3336 } 3337 3338 if (M0 < 0 || M1 < 0 || 3339 (M0 < (int)NumElts && M1 < (int)NumElts) || 3340 (M0 >= (int)NumElts && M1 >= (int)NumElts)) { 3341 CanFold = false; 3342 break; 3343 } 3344 3345 Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts); 3346 Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts); 3347 } 3348 3349 if (CanFold) { 3350 // Fold this sequence only if the resulting shuffle is 'legal'. 3351 if (TLI.isShuffleMaskLegal(Mask1, VT)) 3352 return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0), 3353 N1->getOperand(0), &Mask1[0]); 3354 if (TLI.isShuffleMaskLegal(Mask2, VT)) 3355 return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0), 3356 N0->getOperand(0), &Mask2[0]); 3357 } 3358 } 3359 } 3360 3361 // fold (or x, undef) -> -1 3362 if (!LegalOperations && 3363 (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) { 3364 EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT; 3365 return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT); 3366 } 3367 // fold (or c1, c2) -> c1|c2 3368 if (N0C && N1C) 3369 return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C); 3370 // canonicalize constant to RHS 3371 if (N0C && !N1C) 3372 return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0); 3373 // fold (or x, 0) -> x 3374 if (N1C && N1C->isNullValue()) 3375 return N0; 3376 // fold (or x, -1) -> -1 3377 if (N1C && N1C->isAllOnesValue()) 3378 return N1; 3379 // fold (or x, c) -> c iff (x & ~c) == 0 3380 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue())) 3381 return N1; 3382 3383 // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16) 3384 SDValue BSwap = MatchBSwapHWord(N, N0, N1); 3385 if (BSwap.getNode()) 3386 return BSwap; 3387 BSwap = MatchBSwapHWordLow(N, N0, N1); 3388 if (BSwap.getNode()) 3389 return BSwap; 3390 3391 // reassociate or 3392 SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1); 3393 if (ROR.getNode()) 3394 return ROR; 3395 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2) 3396 // iff (c1 & c2) == 0. 3397 if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() && 3398 isa<ConstantSDNode>(N0.getOperand(1))) { 3399 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1)); 3400 if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) { 3401 SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1); 3402 if (!COR.getNode()) 3403 return SDValue(); 3404 return DAG.getNode(ISD::AND, SDLoc(N), VT, 3405 DAG.getNode(ISD::OR, SDLoc(N0), VT, 3406 N0.getOperand(0), N1), COR); 3407 } 3408 } 3409 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y)) 3410 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){ 3411 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get(); 3412 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get(); 3413 3414 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 && 3415 LL.getValueType().isInteger()) { 3416 // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0) 3417 // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0) 3418 if (cast<ConstantSDNode>(LR)->isNullValue() && 3419 (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) { 3420 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR), 3421 LR.getValueType(), LL, RL); 3422 AddToWorklist(ORNode.getNode()); 3423 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1); 3424 } 3425 // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1) 3426 // fold (or (setgt X, -1), (setgt Y -1)) -> (setgt (and X, Y), -1) 3427 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && 3428 (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) { 3429 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR), 3430 LR.getValueType(), LL, RL); 3431 AddToWorklist(ANDNode.getNode()); 3432 return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1); 3433 } 3434 } 3435 // canonicalize equivalent to ll == rl 3436 if (LL == RR && LR == RL) { 3437 Op1 = ISD::getSetCCSwappedOperands(Op1); 3438 std::swap(RL, RR); 3439 } 3440 if (LL == RL && LR == RR) { 3441 bool isInteger = LL.getValueType().isInteger(); 3442 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger); 3443 if (Result != ISD::SETCC_INVALID && 3444 (!LegalOperations || 3445 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) && 3446 TLI.isOperationLegal(ISD::SETCC, 3447 getSetCCResultType(N0.getValueType()))))) 3448 return DAG.getSetCC(SDLoc(N), N0.getValueType(), 3449 LL, LR, Result); 3450 } 3451 } 3452 3453 // Simplify: (or (op x...), (op y...)) -> (op (or x, y)) 3454 if (N0.getOpcode() == N1.getOpcode()) { 3455 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N); 3456 if (Tmp.getNode()) return Tmp; 3457 } 3458 3459 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible. 3460 if (N0.getOpcode() == ISD::AND && 3461 N1.getOpcode() == ISD::AND && 3462 N0.getOperand(1).getOpcode() == ISD::Constant && 3463 N1.getOperand(1).getOpcode() == ISD::Constant && 3464 // Don't increase # computations. 3465 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) { 3466 // We can only do this xform if we know that bits from X that are set in C2 3467 // but not in C1 are already zero. Likewise for Y. 3468 const APInt &LHSMask = 3469 cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 3470 const APInt &RHSMask = 3471 cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue(); 3472 3473 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) && 3474 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) { 3475 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT, 3476 N0.getOperand(0), N1.getOperand(0)); 3477 return DAG.getNode(ISD::AND, SDLoc(N), VT, X, 3478 DAG.getConstant(LHSMask | RHSMask, VT)); 3479 } 3480 } 3481 3482 // See if this is some rotate idiom. 3483 if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N))) 3484 return SDValue(Rot, 0); 3485 3486 // Simplify the operands using demanded-bits information. 3487 if (!VT.isVector() && 3488 SimplifyDemandedBits(SDValue(N, 0))) 3489 return SDValue(N, 0); 3490 3491 return SDValue(); 3492 } 3493 3494 /// Match "(X shl/srl V1) & V2" where V2 may not be present. 3495 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) { 3496 if (Op.getOpcode() == ISD::AND) { 3497 if (isa<ConstantSDNode>(Op.getOperand(1))) { 3498 Mask = Op.getOperand(1); 3499 Op = Op.getOperand(0); 3500 } else { 3501 return false; 3502 } 3503 } 3504 3505 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) { 3506 Shift = Op; 3507 return true; 3508 } 3509 3510 return false; 3511 } 3512 3513 // Return true if we can prove that, whenever Neg and Pos are both in the 3514 // range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos). This means that 3515 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits: 3516 // 3517 // (or (shift1 X, Neg), (shift2 X, Pos)) 3518 // 3519 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate 3520 // in direction shift1 by Neg. The range [0, OpSize) means that we only need 3521 // to consider shift amounts with defined behavior. 3522 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) { 3523 // If OpSize is a power of 2 then: 3524 // 3525 // (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1) 3526 // (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize). 3527 // 3528 // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check 3529 // for the stronger condition: 3530 // 3531 // Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1) [A] 3532 // 3533 // for all Neg and Pos. Since Neg & (OpSize - 1) == Neg' & (OpSize - 1) 3534 // we can just replace Neg with Neg' for the rest of the function. 3535 // 3536 // In other cases we check for the even stronger condition: 3537 // 3538 // Neg == OpSize - Pos [B] 3539 // 3540 // for all Neg and Pos. Note that the (or ...) then invokes undefined 3541 // behavior if Pos == 0 (and consequently Neg == OpSize). 3542 // 3543 // We could actually use [A] whenever OpSize is a power of 2, but the 3544 // only extra cases that it would match are those uninteresting ones 3545 // where Neg and Pos are never in range at the same time. E.g. for 3546 // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos) 3547 // as well as (sub 32, Pos), but: 3548 // 3549 // (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos)) 3550 // 3551 // always invokes undefined behavior for 32-bit X. 3552 // 3553 // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise. 3554 unsigned MaskLoBits = 0; 3555 if (Neg.getOpcode() == ISD::AND && 3556 isPowerOf2_64(OpSize) && 3557 Neg.getOperand(1).getOpcode() == ISD::Constant && 3558 cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) { 3559 Neg = Neg.getOperand(0); 3560 MaskLoBits = Log2_64(OpSize); 3561 } 3562 3563 // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1. 3564 if (Neg.getOpcode() != ISD::SUB) 3565 return 0; 3566 ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0)); 3567 if (!NegC) 3568 return 0; 3569 SDValue NegOp1 = Neg.getOperand(1); 3570 3571 // On the RHS of [A], if Pos is Pos' & (OpSize - 1), just replace Pos with 3572 // Pos'. The truncation is redundant for the purpose of the equality. 3573 if (MaskLoBits && 3574 Pos.getOpcode() == ISD::AND && 3575 Pos.getOperand(1).getOpcode() == ISD::Constant && 3576 cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() == OpSize - 1) 3577 Pos = Pos.getOperand(0); 3578 3579 // The condition we need is now: 3580 // 3581 // (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask 3582 // 3583 // If NegOp1 == Pos then we need: 3584 // 3585 // OpSize & Mask == NegC & Mask 3586 // 3587 // (because "x & Mask" is a truncation and distributes through subtraction). 3588 APInt Width; 3589 if (Pos == NegOp1) 3590 Width = NegC->getAPIntValue(); 3591 // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC. 3592 // Then the condition we want to prove becomes: 3593 // 3594 // (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask 3595 // 3596 // which, again because "x & Mask" is a truncation, becomes: 3597 // 3598 // NegC & Mask == (OpSize - PosC) & Mask 3599 // OpSize & Mask == (NegC + PosC) & Mask 3600 else if (Pos.getOpcode() == ISD::ADD && 3601 Pos.getOperand(0) == NegOp1 && 3602 Pos.getOperand(1).getOpcode() == ISD::Constant) 3603 Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() + 3604 NegC->getAPIntValue()); 3605 else 3606 return false; 3607 3608 // Now we just need to check that OpSize & Mask == Width & Mask. 3609 if (MaskLoBits) 3610 // Opsize & Mask is 0 since Mask is Opsize - 1. 3611 return Width.getLoBits(MaskLoBits) == 0; 3612 return Width == OpSize; 3613 } 3614 3615 // A subroutine of MatchRotate used once we have found an OR of two opposite 3616 // shifts of Shifted. If Neg == <operand size> - Pos then the OR reduces 3617 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the 3618 // former being preferred if supported. InnerPos and InnerNeg are Pos and 3619 // Neg with outer conversions stripped away. 3620 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos, 3621 SDValue Neg, SDValue InnerPos, 3622 SDValue InnerNeg, unsigned PosOpcode, 3623 unsigned NegOpcode, SDLoc DL) { 3624 // fold (or (shl x, (*ext y)), 3625 // (srl x, (*ext (sub 32, y)))) -> 3626 // (rotl x, y) or (rotr x, (sub 32, y)) 3627 // 3628 // fold (or (shl x, (*ext (sub 32, y))), 3629 // (srl x, (*ext y))) -> 3630 // (rotr x, y) or (rotl x, (sub 32, y)) 3631 EVT VT = Shifted.getValueType(); 3632 if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) { 3633 bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT); 3634 return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted, 3635 HasPos ? Pos : Neg).getNode(); 3636 } 3637 3638 return nullptr; 3639 } 3640 3641 // MatchRotate - Handle an 'or' of two operands. If this is one of the many 3642 // idioms for rotate, and if the target supports rotation instructions, generate 3643 // a rot[lr]. 3644 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) { 3645 // Must be a legal type. Expanded 'n promoted things won't work with rotates. 3646 EVT VT = LHS.getValueType(); 3647 if (!TLI.isTypeLegal(VT)) return nullptr; 3648 3649 // The target must have at least one rotate flavor. 3650 bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT); 3651 bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT); 3652 if (!HasROTL && !HasROTR) return nullptr; 3653 3654 // Match "(X shl/srl V1) & V2" where V2 may not be present. 3655 SDValue LHSShift; // The shift. 3656 SDValue LHSMask; // AND value if any. 3657 if (!MatchRotateHalf(LHS, LHSShift, LHSMask)) 3658 return nullptr; // Not part of a rotate. 3659 3660 SDValue RHSShift; // The shift. 3661 SDValue RHSMask; // AND value if any. 3662 if (!MatchRotateHalf(RHS, RHSShift, RHSMask)) 3663 return nullptr; // Not part of a rotate. 3664 3665 if (LHSShift.getOperand(0) != RHSShift.getOperand(0)) 3666 return nullptr; // Not shifting the same value. 3667 3668 if (LHSShift.getOpcode() == RHSShift.getOpcode()) 3669 return nullptr; // Shifts must disagree. 3670 3671 // Canonicalize shl to left side in a shl/srl pair. 3672 if (RHSShift.getOpcode() == ISD::SHL) { 3673 std::swap(LHS, RHS); 3674 std::swap(LHSShift, RHSShift); 3675 std::swap(LHSMask , RHSMask ); 3676 } 3677 3678 unsigned OpSizeInBits = VT.getSizeInBits(); 3679 SDValue LHSShiftArg = LHSShift.getOperand(0); 3680 SDValue LHSShiftAmt = LHSShift.getOperand(1); 3681 SDValue RHSShiftArg = RHSShift.getOperand(0); 3682 SDValue RHSShiftAmt = RHSShift.getOperand(1); 3683 3684 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1) 3685 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2) 3686 if (LHSShiftAmt.getOpcode() == ISD::Constant && 3687 RHSShiftAmt.getOpcode() == ISD::Constant) { 3688 uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue(); 3689 uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue(); 3690 if ((LShVal + RShVal) != OpSizeInBits) 3691 return nullptr; 3692 3693 SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT, 3694 LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt); 3695 3696 // If there is an AND of either shifted operand, apply it to the result. 3697 if (LHSMask.getNode() || RHSMask.getNode()) { 3698 APInt Mask = APInt::getAllOnesValue(OpSizeInBits); 3699 3700 if (LHSMask.getNode()) { 3701 APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal); 3702 Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits; 3703 } 3704 if (RHSMask.getNode()) { 3705 APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal); 3706 Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits; 3707 } 3708 3709 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT)); 3710 } 3711 3712 return Rot.getNode(); 3713 } 3714 3715 // If there is a mask here, and we have a variable shift, we can't be sure 3716 // that we're masking out the right stuff. 3717 if (LHSMask.getNode() || RHSMask.getNode()) 3718 return nullptr; 3719 3720 // If the shift amount is sign/zext/any-extended just peel it off. 3721 SDValue LExtOp0 = LHSShiftAmt; 3722 SDValue RExtOp0 = RHSShiftAmt; 3723 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND || 3724 LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND || 3725 LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND || 3726 LHSShiftAmt.getOpcode() == ISD::TRUNCATE) && 3727 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND || 3728 RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND || 3729 RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND || 3730 RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) { 3731 LExtOp0 = LHSShiftAmt.getOperand(0); 3732 RExtOp0 = RHSShiftAmt.getOperand(0); 3733 } 3734 3735 SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt, 3736 LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL); 3737 if (TryL) 3738 return TryL; 3739 3740 SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt, 3741 RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL); 3742 if (TryR) 3743 return TryR; 3744 3745 return nullptr; 3746 } 3747 3748 SDValue DAGCombiner::visitXOR(SDNode *N) { 3749 SDValue N0 = N->getOperand(0); 3750 SDValue N1 = N->getOperand(1); 3751 SDValue LHS, RHS, CC; 3752 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 3753 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 3754 EVT VT = N0.getValueType(); 3755 3756 // fold vector ops 3757 if (VT.isVector()) { 3758 SDValue FoldedVOp = SimplifyVBinOp(N); 3759 if (FoldedVOp.getNode()) return FoldedVOp; 3760 3761 // fold (xor x, 0) -> x, vector edition 3762 if (ISD::isBuildVectorAllZeros(N0.getNode())) 3763 return N1; 3764 if (ISD::isBuildVectorAllZeros(N1.getNode())) 3765 return N0; 3766 } 3767 3768 // fold (xor undef, undef) -> 0. This is a common idiom (misuse). 3769 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF) 3770 return DAG.getConstant(0, VT); 3771 // fold (xor x, undef) -> undef 3772 if (N0.getOpcode() == ISD::UNDEF) 3773 return N0; 3774 if (N1.getOpcode() == ISD::UNDEF) 3775 return N1; 3776 // fold (xor c1, c2) -> c1^c2 3777 if (N0C && N1C) 3778 return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C); 3779 // canonicalize constant to RHS 3780 if (N0C && !N1C) 3781 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0); 3782 // fold (xor x, 0) -> x 3783 if (N1C && N1C->isNullValue()) 3784 return N0; 3785 // reassociate xor 3786 SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1); 3787 if (RXOR.getNode()) 3788 return RXOR; 3789 3790 // fold !(x cc y) -> (x !cc y) 3791 if (N1C && N1C->getAPIntValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) { 3792 bool isInt = LHS.getValueType().isInteger(); 3793 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(), 3794 isInt); 3795 3796 if (!LegalOperations || 3797 TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) { 3798 switch (N0.getOpcode()) { 3799 default: 3800 llvm_unreachable("Unhandled SetCC Equivalent!"); 3801 case ISD::SETCC: 3802 return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC); 3803 case ISD::SELECT_CC: 3804 return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2), 3805 N0.getOperand(3), NotCC); 3806 } 3807 } 3808 } 3809 3810 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y))) 3811 if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND && 3812 N0.getNode()->hasOneUse() && 3813 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){ 3814 SDValue V = N0.getOperand(0); 3815 V = DAG.getNode(ISD::XOR, SDLoc(N0), V.getValueType(), V, 3816 DAG.getConstant(1, V.getValueType())); 3817 AddToWorklist(V.getNode()); 3818 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V); 3819 } 3820 3821 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc 3822 if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 && 3823 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) { 3824 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1); 3825 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) { 3826 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND; 3827 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS 3828 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS 3829 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode()); 3830 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS); 3831 } 3832 } 3833 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants 3834 if (N1C && N1C->isAllOnesValue() && 3835 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) { 3836 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1); 3837 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) { 3838 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND; 3839 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS 3840 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS 3841 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode()); 3842 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS); 3843 } 3844 } 3845 // fold (xor (and x, y), y) -> (and (not x), y) 3846 if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() && 3847 N0->getOperand(1) == N1) { 3848 SDValue X = N0->getOperand(0); 3849 SDValue NotX = DAG.getNOT(SDLoc(X), X, VT); 3850 AddToWorklist(NotX.getNode()); 3851 return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1); 3852 } 3853 // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2)) 3854 if (N1C && N0.getOpcode() == ISD::XOR) { 3855 ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0)); 3856 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 3857 if (N00C) 3858 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(1), 3859 DAG.getConstant(N1C->getAPIntValue() ^ 3860 N00C->getAPIntValue(), VT)); 3861 if (N01C) 3862 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(0), 3863 DAG.getConstant(N1C->getAPIntValue() ^ 3864 N01C->getAPIntValue(), VT)); 3865 } 3866 // fold (xor x, x) -> 0 3867 if (N0 == N1) 3868 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes); 3869 3870 // Simplify: xor (op x...), (op y...) -> (op (xor x, y)) 3871 if (N0.getOpcode() == N1.getOpcode()) { 3872 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N); 3873 if (Tmp.getNode()) return Tmp; 3874 } 3875 3876 // Simplify the expression using non-local knowledge. 3877 if (!VT.isVector() && 3878 SimplifyDemandedBits(SDValue(N, 0))) 3879 return SDValue(N, 0); 3880 3881 return SDValue(); 3882 } 3883 3884 /// Handle transforms common to the three shifts, when the shift amount is a 3885 /// constant. 3886 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) { 3887 // We can't and shouldn't fold opaque constants. 3888 if (Amt->isOpaque()) 3889 return SDValue(); 3890 3891 SDNode *LHS = N->getOperand(0).getNode(); 3892 if (!LHS->hasOneUse()) return SDValue(); 3893 3894 // We want to pull some binops through shifts, so that we have (and (shift)) 3895 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of 3896 // thing happens with address calculations, so it's important to canonicalize 3897 // it. 3898 bool HighBitSet = false; // Can we transform this if the high bit is set? 3899 3900 switch (LHS->getOpcode()) { 3901 default: return SDValue(); 3902 case ISD::OR: 3903 case ISD::XOR: 3904 HighBitSet = false; // We can only transform sra if the high bit is clear. 3905 break; 3906 case ISD::AND: 3907 HighBitSet = true; // We can only transform sra if the high bit is set. 3908 break; 3909 case ISD::ADD: 3910 if (N->getOpcode() != ISD::SHL) 3911 return SDValue(); // only shl(add) not sr[al](add). 3912 HighBitSet = false; // We can only transform sra if the high bit is clear. 3913 break; 3914 } 3915 3916 // We require the RHS of the binop to be a constant and not opaque as well. 3917 ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1)); 3918 if (!BinOpCst || BinOpCst->isOpaque()) return SDValue(); 3919 3920 // FIXME: disable this unless the input to the binop is a shift by a constant. 3921 // If it is not a shift, it pessimizes some common cases like: 3922 // 3923 // void foo(int *X, int i) { X[i & 1235] = 1; } 3924 // int bar(int *X, int i) { return X[i & 255]; } 3925 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode(); 3926 if ((BinOpLHSVal->getOpcode() != ISD::SHL && 3927 BinOpLHSVal->getOpcode() != ISD::SRA && 3928 BinOpLHSVal->getOpcode() != ISD::SRL) || 3929 !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1))) 3930 return SDValue(); 3931 3932 EVT VT = N->getValueType(0); 3933 3934 // If this is a signed shift right, and the high bit is modified by the 3935 // logical operation, do not perform the transformation. The highBitSet 3936 // boolean indicates the value of the high bit of the constant which would 3937 // cause it to be modified for this operation. 3938 if (N->getOpcode() == ISD::SRA) { 3939 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative(); 3940 if (BinOpRHSSignSet != HighBitSet) 3941 return SDValue(); 3942 } 3943 3944 if (!TLI.isDesirableToCommuteWithShift(LHS)) 3945 return SDValue(); 3946 3947 // Fold the constants, shifting the binop RHS by the shift amount. 3948 SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)), 3949 N->getValueType(0), 3950 LHS->getOperand(1), N->getOperand(1)); 3951 assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!"); 3952 3953 // Create the new shift. 3954 SDValue NewShift = DAG.getNode(N->getOpcode(), 3955 SDLoc(LHS->getOperand(0)), 3956 VT, LHS->getOperand(0), N->getOperand(1)); 3957 3958 // Create the new binop. 3959 return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS); 3960 } 3961 3962 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) { 3963 assert(N->getOpcode() == ISD::TRUNCATE); 3964 assert(N->getOperand(0).getOpcode() == ISD::AND); 3965 3966 // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC) 3967 if (N->hasOneUse() && N->getOperand(0).hasOneUse()) { 3968 SDValue N01 = N->getOperand(0).getOperand(1); 3969 3970 if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) { 3971 EVT TruncVT = N->getValueType(0); 3972 SDValue N00 = N->getOperand(0).getOperand(0); 3973 APInt TruncC = N01C->getAPIntValue(); 3974 TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits()); 3975 3976 return DAG.getNode(ISD::AND, SDLoc(N), TruncVT, 3977 DAG.getNode(ISD::TRUNCATE, SDLoc(N), TruncVT, N00), 3978 DAG.getConstant(TruncC, TruncVT)); 3979 } 3980 } 3981 3982 return SDValue(); 3983 } 3984 3985 SDValue DAGCombiner::visitRotate(SDNode *N) { 3986 // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))). 3987 if (N->getOperand(1).getOpcode() == ISD::TRUNCATE && 3988 N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) { 3989 SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode()); 3990 if (NewOp1.getNode()) 3991 return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0), 3992 N->getOperand(0), NewOp1); 3993 } 3994 return SDValue(); 3995 } 3996 3997 SDValue DAGCombiner::visitSHL(SDNode *N) { 3998 SDValue N0 = N->getOperand(0); 3999 SDValue N1 = N->getOperand(1); 4000 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 4001 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 4002 EVT VT = N0.getValueType(); 4003 unsigned OpSizeInBits = VT.getScalarSizeInBits(); 4004 4005 // fold vector ops 4006 if (VT.isVector()) { 4007 SDValue FoldedVOp = SimplifyVBinOp(N); 4008 if (FoldedVOp.getNode()) return FoldedVOp; 4009 4010 BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1); 4011 // If setcc produces all-one true value then: 4012 // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV) 4013 if (N1CV && N1CV->isConstant()) { 4014 if (N0.getOpcode() == ISD::AND) { 4015 SDValue N00 = N0->getOperand(0); 4016 SDValue N01 = N0->getOperand(1); 4017 BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01); 4018 4019 if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC && 4020 TLI.getBooleanContents(N00.getOperand(0).getValueType()) == 4021 TargetLowering::ZeroOrNegativeOneBooleanContent) { 4022 SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, VT, N01CV, N1CV); 4023 if (C.getNode()) 4024 return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C); 4025 } 4026 } else { 4027 N1C = isConstOrConstSplat(N1); 4028 } 4029 } 4030 } 4031 4032 // fold (shl c1, c2) -> c1<<c2 4033 if (N0C && N1C) 4034 return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C); 4035 // fold (shl 0, x) -> 0 4036 if (N0C && N0C->isNullValue()) 4037 return N0; 4038 // fold (shl x, c >= size(x)) -> undef 4039 if (N1C && N1C->getZExtValue() >= OpSizeInBits) 4040 return DAG.getUNDEF(VT); 4041 // fold (shl x, 0) -> x 4042 if (N1C && N1C->isNullValue()) 4043 return N0; 4044 // fold (shl undef, x) -> 0 4045 if (N0.getOpcode() == ISD::UNDEF) 4046 return DAG.getConstant(0, VT); 4047 // if (shl x, c) is known to be zero, return 0 4048 if (DAG.MaskedValueIsZero(SDValue(N, 0), 4049 APInt::getAllOnesValue(OpSizeInBits))) 4050 return DAG.getConstant(0, VT); 4051 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))). 4052 if (N1.getOpcode() == ISD::TRUNCATE && 4053 N1.getOperand(0).getOpcode() == ISD::AND) { 4054 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()); 4055 if (NewOp1.getNode()) 4056 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1); 4057 } 4058 4059 if (N1C && SimplifyDemandedBits(SDValue(N, 0))) 4060 return SDValue(N, 0); 4061 4062 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2)) 4063 if (N1C && N0.getOpcode() == ISD::SHL) { 4064 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) { 4065 uint64_t c1 = N0C1->getZExtValue(); 4066 uint64_t c2 = N1C->getZExtValue(); 4067 if (c1 + c2 >= OpSizeInBits) 4068 return DAG.getConstant(0, VT); 4069 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0), 4070 DAG.getConstant(c1 + c2, N1.getValueType())); 4071 } 4072 } 4073 4074 // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2))) 4075 // For this to be valid, the second form must not preserve any of the bits 4076 // that are shifted out by the inner shift in the first form. This means 4077 // the outer shift size must be >= the number of bits added by the ext. 4078 // As a corollary, we don't care what kind of ext it is. 4079 if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND || 4080 N0.getOpcode() == ISD::ANY_EXTEND || 4081 N0.getOpcode() == ISD::SIGN_EXTEND) && 4082 N0.getOperand(0).getOpcode() == ISD::SHL) { 4083 SDValue N0Op0 = N0.getOperand(0); 4084 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) { 4085 uint64_t c1 = N0Op0C1->getZExtValue(); 4086 uint64_t c2 = N1C->getZExtValue(); 4087 EVT InnerShiftVT = N0Op0.getValueType(); 4088 uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits(); 4089 if (c2 >= OpSizeInBits - InnerShiftSize) { 4090 if (c1 + c2 >= OpSizeInBits) 4091 return DAG.getConstant(0, VT); 4092 return DAG.getNode(ISD::SHL, SDLoc(N0), VT, 4093 DAG.getNode(N0.getOpcode(), SDLoc(N0), VT, 4094 N0Op0->getOperand(0)), 4095 DAG.getConstant(c1 + c2, N1.getValueType())); 4096 } 4097 } 4098 } 4099 4100 // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C)) 4101 // Only fold this if the inner zext has no other uses to avoid increasing 4102 // the total number of instructions. 4103 if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() && 4104 N0.getOperand(0).getOpcode() == ISD::SRL) { 4105 SDValue N0Op0 = N0.getOperand(0); 4106 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) { 4107 uint64_t c1 = N0Op0C1->getZExtValue(); 4108 if (c1 < VT.getScalarSizeInBits()) { 4109 uint64_t c2 = N1C->getZExtValue(); 4110 if (c1 == c2) { 4111 SDValue NewOp0 = N0.getOperand(0); 4112 EVT CountVT = NewOp0.getOperand(1).getValueType(); 4113 SDValue NewSHL = DAG.getNode(ISD::SHL, SDLoc(N), NewOp0.getValueType(), 4114 NewOp0, DAG.getConstant(c2, CountVT)); 4115 AddToWorklist(NewSHL.getNode()); 4116 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL); 4117 } 4118 } 4119 } 4120 } 4121 4122 // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or 4123 // (and (srl x, (sub c1, c2), MASK) 4124 // Only fold this if the inner shift has no other uses -- if it does, folding 4125 // this will increase the total number of instructions. 4126 if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) { 4127 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) { 4128 uint64_t c1 = N0C1->getZExtValue(); 4129 if (c1 < OpSizeInBits) { 4130 uint64_t c2 = N1C->getZExtValue(); 4131 APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1); 4132 SDValue Shift; 4133 if (c2 > c1) { 4134 Mask = Mask.shl(c2 - c1); 4135 Shift = DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0), 4136 DAG.getConstant(c2 - c1, N1.getValueType())); 4137 } else { 4138 Mask = Mask.lshr(c1 - c2); 4139 Shift = DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), 4140 DAG.getConstant(c1 - c2, N1.getValueType())); 4141 } 4142 return DAG.getNode(ISD::AND, SDLoc(N0), VT, Shift, 4143 DAG.getConstant(Mask, VT)); 4144 } 4145 } 4146 } 4147 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1)) 4148 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) { 4149 unsigned BitSize = VT.getScalarSizeInBits(); 4150 SDValue HiBitsMask = 4151 DAG.getConstant(APInt::getHighBitsSet(BitSize, 4152 BitSize - N1C->getZExtValue()), VT); 4153 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0), 4154 HiBitsMask); 4155 } 4156 4157 // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2) 4158 // Variant of version done on multiply, except mul by a power of 2 is turned 4159 // into a shift. 4160 APInt Val; 4161 if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() && 4162 (isa<ConstantSDNode>(N0.getOperand(1)) || 4163 isConstantSplatVector(N0.getOperand(1).getNode(), Val))) { 4164 SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1); 4165 SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1); 4166 return DAG.getNode(ISD::ADD, SDLoc(N), VT, Shl0, Shl1); 4167 } 4168 4169 if (N1C) { 4170 SDValue NewSHL = visitShiftByConstant(N, N1C); 4171 if (NewSHL.getNode()) 4172 return NewSHL; 4173 } 4174 4175 return SDValue(); 4176 } 4177 4178 SDValue DAGCombiner::visitSRA(SDNode *N) { 4179 SDValue N0 = N->getOperand(0); 4180 SDValue N1 = N->getOperand(1); 4181 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 4182 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 4183 EVT VT = N0.getValueType(); 4184 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits(); 4185 4186 // fold vector ops 4187 if (VT.isVector()) { 4188 SDValue FoldedVOp = SimplifyVBinOp(N); 4189 if (FoldedVOp.getNode()) return FoldedVOp; 4190 4191 N1C = isConstOrConstSplat(N1); 4192 } 4193 4194 // fold (sra c1, c2) -> (sra c1, c2) 4195 if (N0C && N1C) 4196 return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C); 4197 // fold (sra 0, x) -> 0 4198 if (N0C && N0C->isNullValue()) 4199 return N0; 4200 // fold (sra -1, x) -> -1 4201 if (N0C && N0C->isAllOnesValue()) 4202 return N0; 4203 // fold (sra x, (setge c, size(x))) -> undef 4204 if (N1C && N1C->getZExtValue() >= OpSizeInBits) 4205 return DAG.getUNDEF(VT); 4206 // fold (sra x, 0) -> x 4207 if (N1C && N1C->isNullValue()) 4208 return N0; 4209 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports 4210 // sext_inreg. 4211 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) { 4212 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue(); 4213 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits); 4214 if (VT.isVector()) 4215 ExtVT = EVT::getVectorVT(*DAG.getContext(), 4216 ExtVT, VT.getVectorNumElements()); 4217 if ((!LegalOperations || 4218 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT))) 4219 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, 4220 N0.getOperand(0), DAG.getValueType(ExtVT)); 4221 } 4222 4223 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2)) 4224 if (N1C && N0.getOpcode() == ISD::SRA) { 4225 if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) { 4226 unsigned Sum = N1C->getZExtValue() + C1->getZExtValue(); 4227 if (Sum >= OpSizeInBits) 4228 Sum = OpSizeInBits - 1; 4229 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0.getOperand(0), 4230 DAG.getConstant(Sum, N1.getValueType())); 4231 } 4232 } 4233 4234 // fold (sra (shl X, m), (sub result_size, n)) 4235 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for 4236 // result_size - n != m. 4237 // If truncate is free for the target sext(shl) is likely to result in better 4238 // code. 4239 if (N0.getOpcode() == ISD::SHL && N1C) { 4240 // Get the two constanst of the shifts, CN0 = m, CN = n. 4241 const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1)); 4242 if (N01C) { 4243 LLVMContext &Ctx = *DAG.getContext(); 4244 // Determine what the truncate's result bitsize and type would be. 4245 EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue()); 4246 4247 if (VT.isVector()) 4248 TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements()); 4249 4250 // Determine the residual right-shift amount. 4251 signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue(); 4252 4253 // If the shift is not a no-op (in which case this should be just a sign 4254 // extend already), the truncated to type is legal, sign_extend is legal 4255 // on that type, and the truncate to that type is both legal and free, 4256 // perform the transform. 4257 if ((ShiftAmt > 0) && 4258 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) && 4259 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) && 4260 TLI.isTruncateFree(VT, TruncVT)) { 4261 4262 SDValue Amt = DAG.getConstant(ShiftAmt, 4263 getShiftAmountTy(N0.getOperand(0).getValueType())); 4264 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), VT, 4265 N0.getOperand(0), Amt); 4266 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), TruncVT, 4267 Shift); 4268 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), 4269 N->getValueType(0), Trunc); 4270 } 4271 } 4272 } 4273 4274 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))). 4275 if (N1.getOpcode() == ISD::TRUNCATE && 4276 N1.getOperand(0).getOpcode() == ISD::AND) { 4277 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()); 4278 if (NewOp1.getNode()) 4279 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1); 4280 } 4281 4282 // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2)) 4283 // if c1 is equal to the number of bits the trunc removes 4284 if (N0.getOpcode() == ISD::TRUNCATE && 4285 (N0.getOperand(0).getOpcode() == ISD::SRL || 4286 N0.getOperand(0).getOpcode() == ISD::SRA) && 4287 N0.getOperand(0).hasOneUse() && 4288 N0.getOperand(0).getOperand(1).hasOneUse() && 4289 N1C) { 4290 SDValue N0Op0 = N0.getOperand(0); 4291 if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) { 4292 unsigned LargeShiftVal = LargeShift->getZExtValue(); 4293 EVT LargeVT = N0Op0.getValueType(); 4294 4295 if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) { 4296 SDValue Amt = 4297 DAG.getConstant(LargeShiftVal + N1C->getZExtValue(), 4298 getShiftAmountTy(N0Op0.getOperand(0).getValueType())); 4299 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), LargeVT, 4300 N0Op0.getOperand(0), Amt); 4301 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, SRA); 4302 } 4303 } 4304 } 4305 4306 // Simplify, based on bits shifted out of the LHS. 4307 if (N1C && SimplifyDemandedBits(SDValue(N, 0))) 4308 return SDValue(N, 0); 4309 4310 4311 // If the sign bit is known to be zero, switch this to a SRL. 4312 if (DAG.SignBitIsZero(N0)) 4313 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1); 4314 4315 if (N1C) { 4316 SDValue NewSRA = visitShiftByConstant(N, N1C); 4317 if (NewSRA.getNode()) 4318 return NewSRA; 4319 } 4320 4321 return SDValue(); 4322 } 4323 4324 SDValue DAGCombiner::visitSRL(SDNode *N) { 4325 SDValue N0 = N->getOperand(0); 4326 SDValue N1 = N->getOperand(1); 4327 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 4328 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 4329 EVT VT = N0.getValueType(); 4330 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits(); 4331 4332 // fold vector ops 4333 if (VT.isVector()) { 4334 SDValue FoldedVOp = SimplifyVBinOp(N); 4335 if (FoldedVOp.getNode()) return FoldedVOp; 4336 4337 N1C = isConstOrConstSplat(N1); 4338 } 4339 4340 // fold (srl c1, c2) -> c1 >>u c2 4341 if (N0C && N1C) 4342 return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C); 4343 // fold (srl 0, x) -> 0 4344 if (N0C && N0C->isNullValue()) 4345 return N0; 4346 // fold (srl x, c >= size(x)) -> undef 4347 if (N1C && N1C->getZExtValue() >= OpSizeInBits) 4348 return DAG.getUNDEF(VT); 4349 // fold (srl x, 0) -> x 4350 if (N1C && N1C->isNullValue()) 4351 return N0; 4352 // if (srl x, c) is known to be zero, return 0 4353 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0), 4354 APInt::getAllOnesValue(OpSizeInBits))) 4355 return DAG.getConstant(0, VT); 4356 4357 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2)) 4358 if (N1C && N0.getOpcode() == ISD::SRL) { 4359 if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) { 4360 uint64_t c1 = N01C->getZExtValue(); 4361 uint64_t c2 = N1C->getZExtValue(); 4362 if (c1 + c2 >= OpSizeInBits) 4363 return DAG.getConstant(0, VT); 4364 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), 4365 DAG.getConstant(c1 + c2, N1.getValueType())); 4366 } 4367 } 4368 4369 // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2))) 4370 if (N1C && N0.getOpcode() == ISD::TRUNCATE && 4371 N0.getOperand(0).getOpcode() == ISD::SRL && 4372 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) { 4373 uint64_t c1 = 4374 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue(); 4375 uint64_t c2 = N1C->getZExtValue(); 4376 EVT InnerShiftVT = N0.getOperand(0).getValueType(); 4377 EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType(); 4378 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits(); 4379 // This is only valid if the OpSizeInBits + c1 = size of inner shift. 4380 if (c1 + OpSizeInBits == InnerShiftSize) { 4381 if (c1 + c2 >= InnerShiftSize) 4382 return DAG.getConstant(0, VT); 4383 return DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, 4384 DAG.getNode(ISD::SRL, SDLoc(N0), InnerShiftVT, 4385 N0.getOperand(0)->getOperand(0), 4386 DAG.getConstant(c1 + c2, ShiftCountVT))); 4387 } 4388 } 4389 4390 // fold (srl (shl x, c), c) -> (and x, cst2) 4391 if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) { 4392 unsigned BitSize = N0.getScalarValueSizeInBits(); 4393 if (BitSize <= 64) { 4394 uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize; 4395 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0), 4396 DAG.getConstant(~0ULL >> ShAmt, VT)); 4397 } 4398 } 4399 4400 // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask) 4401 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) { 4402 // Shifting in all undef bits? 4403 EVT SmallVT = N0.getOperand(0).getValueType(); 4404 unsigned BitSize = SmallVT.getScalarSizeInBits(); 4405 if (N1C->getZExtValue() >= BitSize) 4406 return DAG.getUNDEF(VT); 4407 4408 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) { 4409 uint64_t ShiftAmt = N1C->getZExtValue(); 4410 SDValue SmallShift = DAG.getNode(ISD::SRL, SDLoc(N0), SmallVT, 4411 N0.getOperand(0), 4412 DAG.getConstant(ShiftAmt, getShiftAmountTy(SmallVT))); 4413 AddToWorklist(SmallShift.getNode()); 4414 APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt); 4415 return DAG.getNode(ISD::AND, SDLoc(N), VT, 4416 DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, SmallShift), 4417 DAG.getConstant(Mask, VT)); 4418 } 4419 } 4420 4421 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign 4422 // bit, which is unmodified by sra. 4423 if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) { 4424 if (N0.getOpcode() == ISD::SRA) 4425 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1); 4426 } 4427 4428 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit). 4429 if (N1C && N0.getOpcode() == ISD::CTLZ && 4430 N1C->getAPIntValue() == Log2_32(OpSizeInBits)) { 4431 APInt KnownZero, KnownOne; 4432 DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne); 4433 4434 // If any of the input bits are KnownOne, then the input couldn't be all 4435 // zeros, thus the result of the srl will always be zero. 4436 if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT); 4437 4438 // If all of the bits input the to ctlz node are known to be zero, then 4439 // the result of the ctlz is "32" and the result of the shift is one. 4440 APInt UnknownBits = ~KnownZero; 4441 if (UnknownBits == 0) return DAG.getConstant(1, VT); 4442 4443 // Otherwise, check to see if there is exactly one bit input to the ctlz. 4444 if ((UnknownBits & (UnknownBits - 1)) == 0) { 4445 // Okay, we know that only that the single bit specified by UnknownBits 4446 // could be set on input to the CTLZ node. If this bit is set, the SRL 4447 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair 4448 // to an SRL/XOR pair, which is likely to simplify more. 4449 unsigned ShAmt = UnknownBits.countTrailingZeros(); 4450 SDValue Op = N0.getOperand(0); 4451 4452 if (ShAmt) { 4453 Op = DAG.getNode(ISD::SRL, SDLoc(N0), VT, Op, 4454 DAG.getConstant(ShAmt, getShiftAmountTy(Op.getValueType()))); 4455 AddToWorklist(Op.getNode()); 4456 } 4457 4458 return DAG.getNode(ISD::XOR, SDLoc(N), VT, 4459 Op, DAG.getConstant(1, VT)); 4460 } 4461 } 4462 4463 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))). 4464 if (N1.getOpcode() == ISD::TRUNCATE && 4465 N1.getOperand(0).getOpcode() == ISD::AND) { 4466 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()); 4467 if (NewOp1.getNode()) 4468 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1); 4469 } 4470 4471 // fold operands of srl based on knowledge that the low bits are not 4472 // demanded. 4473 if (N1C && SimplifyDemandedBits(SDValue(N, 0))) 4474 return SDValue(N, 0); 4475 4476 if (N1C) { 4477 SDValue NewSRL = visitShiftByConstant(N, N1C); 4478 if (NewSRL.getNode()) 4479 return NewSRL; 4480 } 4481 4482 // Attempt to convert a srl of a load into a narrower zero-extending load. 4483 SDValue NarrowLoad = ReduceLoadWidth(N); 4484 if (NarrowLoad.getNode()) 4485 return NarrowLoad; 4486 4487 // Here is a common situation. We want to optimize: 4488 // 4489 // %a = ... 4490 // %b = and i32 %a, 2 4491 // %c = srl i32 %b, 1 4492 // brcond i32 %c ... 4493 // 4494 // into 4495 // 4496 // %a = ... 4497 // %b = and %a, 2 4498 // %c = setcc eq %b, 0 4499 // brcond %c ... 4500 // 4501 // However when after the source operand of SRL is optimized into AND, the SRL 4502 // itself may not be optimized further. Look for it and add the BRCOND into 4503 // the worklist. 4504 if (N->hasOneUse()) { 4505 SDNode *Use = *N->use_begin(); 4506 if (Use->getOpcode() == ISD::BRCOND) 4507 AddToWorklist(Use); 4508 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) { 4509 // Also look pass the truncate. 4510 Use = *Use->use_begin(); 4511 if (Use->getOpcode() == ISD::BRCOND) 4512 AddToWorklist(Use); 4513 } 4514 } 4515 4516 return SDValue(); 4517 } 4518 4519 SDValue DAGCombiner::visitCTLZ(SDNode *N) { 4520 SDValue N0 = N->getOperand(0); 4521 EVT VT = N->getValueType(0); 4522 4523 // fold (ctlz c1) -> c2 4524 if (isa<ConstantSDNode>(N0)) 4525 return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0); 4526 return SDValue(); 4527 } 4528 4529 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) { 4530 SDValue N0 = N->getOperand(0); 4531 EVT VT = N->getValueType(0); 4532 4533 // fold (ctlz_zero_undef c1) -> c2 4534 if (isa<ConstantSDNode>(N0)) 4535 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0); 4536 return SDValue(); 4537 } 4538 4539 SDValue DAGCombiner::visitCTTZ(SDNode *N) { 4540 SDValue N0 = N->getOperand(0); 4541 EVT VT = N->getValueType(0); 4542 4543 // fold (cttz c1) -> c2 4544 if (isa<ConstantSDNode>(N0)) 4545 return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0); 4546 return SDValue(); 4547 } 4548 4549 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) { 4550 SDValue N0 = N->getOperand(0); 4551 EVT VT = N->getValueType(0); 4552 4553 // fold (cttz_zero_undef c1) -> c2 4554 if (isa<ConstantSDNode>(N0)) 4555 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0); 4556 return SDValue(); 4557 } 4558 4559 SDValue DAGCombiner::visitCTPOP(SDNode *N) { 4560 SDValue N0 = N->getOperand(0); 4561 EVT VT = N->getValueType(0); 4562 4563 // fold (ctpop c1) -> c2 4564 if (isa<ConstantSDNode>(N0)) 4565 return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0); 4566 return SDValue(); 4567 } 4568 4569 SDValue DAGCombiner::visitSELECT(SDNode *N) { 4570 SDValue N0 = N->getOperand(0); 4571 SDValue N1 = N->getOperand(1); 4572 SDValue N2 = N->getOperand(2); 4573 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 4574 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 4575 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2); 4576 EVT VT = N->getValueType(0); 4577 EVT VT0 = N0.getValueType(); 4578 4579 // fold (select C, X, X) -> X 4580 if (N1 == N2) 4581 return N1; 4582 // fold (select true, X, Y) -> X 4583 if (N0C && !N0C->isNullValue()) 4584 return N1; 4585 // fold (select false, X, Y) -> Y 4586 if (N0C && N0C->isNullValue()) 4587 return N2; 4588 // fold (select C, 1, X) -> (or C, X) 4589 if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1) 4590 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2); 4591 // fold (select C, 0, 1) -> (xor C, 1) 4592 // We can't do this reliably if integer based booleans have different contents 4593 // to floating point based booleans. This is because we can't tell whether we 4594 // have an integer-based boolean or a floating-point-based boolean unless we 4595 // can find the SETCC that produced it and inspect its operands. This is 4596 // fairly easy if C is the SETCC node, but it can potentially be 4597 // undiscoverable (or not reasonably discoverable). For example, it could be 4598 // in another basic block or it could require searching a complicated 4599 // expression. 4600 if (VT.isInteger() && 4601 (VT0 == MVT::i1 || (VT0.isInteger() && 4602 TLI.getBooleanContents(false, false) == 4603 TLI.getBooleanContents(false, true) && 4604 TLI.getBooleanContents(false, false) == 4605 TargetLowering::ZeroOrOneBooleanContent)) && 4606 N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) { 4607 SDValue XORNode; 4608 if (VT == VT0) 4609 return DAG.getNode(ISD::XOR, SDLoc(N), VT0, 4610 N0, DAG.getConstant(1, VT0)); 4611 XORNode = DAG.getNode(ISD::XOR, SDLoc(N0), VT0, 4612 N0, DAG.getConstant(1, VT0)); 4613 AddToWorklist(XORNode.getNode()); 4614 if (VT.bitsGT(VT0)) 4615 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode); 4616 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode); 4617 } 4618 // fold (select C, 0, X) -> (and (not C), X) 4619 if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) { 4620 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT); 4621 AddToWorklist(NOTNode.getNode()); 4622 return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2); 4623 } 4624 // fold (select C, X, 1) -> (or (not C), X) 4625 if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) { 4626 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT); 4627 AddToWorklist(NOTNode.getNode()); 4628 return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1); 4629 } 4630 // fold (select C, X, 0) -> (and C, X) 4631 if (VT == MVT::i1 && N2C && N2C->isNullValue()) 4632 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1); 4633 // fold (select X, X, Y) -> (or X, Y) 4634 // fold (select X, 1, Y) -> (or X, Y) 4635 if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1))) 4636 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2); 4637 // fold (select X, Y, X) -> (and X, Y) 4638 // fold (select X, Y, 0) -> (and X, Y) 4639 if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0))) 4640 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1); 4641 4642 // If we can fold this based on the true/false value, do so. 4643 if (SimplifySelectOps(N, N1, N2)) 4644 return SDValue(N, 0); // Don't revisit N. 4645 4646 // fold selects based on a setcc into other things, such as min/max/abs 4647 if (N0.getOpcode() == ISD::SETCC) { 4648 if ((!LegalOperations && 4649 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) || 4650 TLI.isOperationLegal(ISD::SELECT_CC, VT)) 4651 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, 4652 N0.getOperand(0), N0.getOperand(1), 4653 N1, N2, N0.getOperand(2)); 4654 return SimplifySelect(SDLoc(N), N0, N1, N2); 4655 } 4656 4657 return SDValue(); 4658 } 4659 4660 static 4661 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) { 4662 SDLoc DL(N); 4663 EVT LoVT, HiVT; 4664 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0)); 4665 4666 // Split the inputs. 4667 SDValue Lo, Hi, LL, LH, RL, RH; 4668 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0); 4669 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1); 4670 4671 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2)); 4672 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2)); 4673 4674 return std::make_pair(Lo, Hi); 4675 } 4676 4677 // This function assumes all the vselect's arguments are CONCAT_VECTOR 4678 // nodes and that the condition is a BV of ConstantSDNodes (or undefs). 4679 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) { 4680 SDLoc dl(N); 4681 SDValue Cond = N->getOperand(0); 4682 SDValue LHS = N->getOperand(1); 4683 SDValue RHS = N->getOperand(2); 4684 EVT VT = N->getValueType(0); 4685 int NumElems = VT.getVectorNumElements(); 4686 assert(LHS.getOpcode() == ISD::CONCAT_VECTORS && 4687 RHS.getOpcode() == ISD::CONCAT_VECTORS && 4688 Cond.getOpcode() == ISD::BUILD_VECTOR); 4689 4690 // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about 4691 // binary ones here. 4692 if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2) 4693 return SDValue(); 4694 4695 // We're sure we have an even number of elements due to the 4696 // concat_vectors we have as arguments to vselect. 4697 // Skip BV elements until we find one that's not an UNDEF 4698 // After we find an UNDEF element, keep looping until we get to half the 4699 // length of the BV and see if all the non-undef nodes are the same. 4700 ConstantSDNode *BottomHalf = nullptr; 4701 for (int i = 0; i < NumElems / 2; ++i) { 4702 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF) 4703 continue; 4704 4705 if (BottomHalf == nullptr) 4706 BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i)); 4707 else if (Cond->getOperand(i).getNode() != BottomHalf) 4708 return SDValue(); 4709 } 4710 4711 // Do the same for the second half of the BuildVector 4712 ConstantSDNode *TopHalf = nullptr; 4713 for (int i = NumElems / 2; i < NumElems; ++i) { 4714 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF) 4715 continue; 4716 4717 if (TopHalf == nullptr) 4718 TopHalf = cast<ConstantSDNode>(Cond.getOperand(i)); 4719 else if (Cond->getOperand(i).getNode() != TopHalf) 4720 return SDValue(); 4721 } 4722 4723 assert(TopHalf && BottomHalf && 4724 "One half of the selector was all UNDEFs and the other was all the " 4725 "same value. This should have been addressed before this function."); 4726 return DAG.getNode( 4727 ISD::CONCAT_VECTORS, dl, VT, 4728 BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0), 4729 TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1)); 4730 } 4731 4732 SDValue DAGCombiner::visitVSELECT(SDNode *N) { 4733 SDValue N0 = N->getOperand(0); 4734 SDValue N1 = N->getOperand(1); 4735 SDValue N2 = N->getOperand(2); 4736 SDLoc DL(N); 4737 4738 // Canonicalize integer abs. 4739 // vselect (setg[te] X, 0), X, -X -> 4740 // vselect (setgt X, -1), X, -X -> 4741 // vselect (setl[te] X, 0), -X, X -> 4742 // Y = sra (X, size(X)-1); xor (add (X, Y), Y) 4743 if (N0.getOpcode() == ISD::SETCC) { 4744 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1); 4745 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get(); 4746 bool isAbs = false; 4747 bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode()); 4748 4749 if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) || 4750 (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) && 4751 N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1)) 4752 isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode()); 4753 else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) && 4754 N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1)) 4755 isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode()); 4756 4757 if (isAbs) { 4758 EVT VT = LHS.getValueType(); 4759 SDValue Shift = DAG.getNode( 4760 ISD::SRA, DL, VT, LHS, 4761 DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, VT)); 4762 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift); 4763 AddToWorklist(Shift.getNode()); 4764 AddToWorklist(Add.getNode()); 4765 return DAG.getNode(ISD::XOR, DL, VT, Add, Shift); 4766 } 4767 } 4768 4769 // If the VSELECT result requires splitting and the mask is provided by a 4770 // SETCC, then split both nodes and its operands before legalization. This 4771 // prevents the type legalizer from unrolling SETCC into scalar comparisons 4772 // and enables future optimizations (e.g. min/max pattern matching on X86). 4773 if (N0.getOpcode() == ISD::SETCC) { 4774 EVT VT = N->getValueType(0); 4775 4776 // Check if any splitting is required. 4777 if (TLI.getTypeAction(*DAG.getContext(), VT) != 4778 TargetLowering::TypeSplitVector) 4779 return SDValue(); 4780 4781 SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH; 4782 std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG); 4783 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1); 4784 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2); 4785 4786 Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL); 4787 Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH); 4788 4789 // Add the new VSELECT nodes to the work list in case they need to be split 4790 // again. 4791 AddToWorklist(Lo.getNode()); 4792 AddToWorklist(Hi.getNode()); 4793 4794 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi); 4795 } 4796 4797 // Fold (vselect (build_vector all_ones), N1, N2) -> N1 4798 if (ISD::isBuildVectorAllOnes(N0.getNode())) 4799 return N1; 4800 // Fold (vselect (build_vector all_zeros), N1, N2) -> N2 4801 if (ISD::isBuildVectorAllZeros(N0.getNode())) 4802 return N2; 4803 4804 // The ConvertSelectToConcatVector function is assuming both the above 4805 // checks for (vselect (build_vector all{ones,zeros) ...) have been made 4806 // and addressed. 4807 if (N1.getOpcode() == ISD::CONCAT_VECTORS && 4808 N2.getOpcode() == ISD::CONCAT_VECTORS && 4809 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) { 4810 SDValue CV = ConvertSelectToConcatVector(N, DAG); 4811 if (CV.getNode()) 4812 return CV; 4813 } 4814 4815 return SDValue(); 4816 } 4817 4818 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) { 4819 SDValue N0 = N->getOperand(0); 4820 SDValue N1 = N->getOperand(1); 4821 SDValue N2 = N->getOperand(2); 4822 SDValue N3 = N->getOperand(3); 4823 SDValue N4 = N->getOperand(4); 4824 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get(); 4825 4826 // fold select_cc lhs, rhs, x, x, cc -> x 4827 if (N2 == N3) 4828 return N2; 4829 4830 // Determine if the condition we're dealing with is constant 4831 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()), 4832 N0, N1, CC, SDLoc(N), false); 4833 if (SCC.getNode()) { 4834 AddToWorklist(SCC.getNode()); 4835 4836 if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) { 4837 if (!SCCC->isNullValue()) 4838 return N2; // cond always true -> true val 4839 else 4840 return N3; // cond always false -> false val 4841 } 4842 4843 // Fold to a simpler select_cc 4844 if (SCC.getOpcode() == ISD::SETCC) 4845 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(), 4846 SCC.getOperand(0), SCC.getOperand(1), N2, N3, 4847 SCC.getOperand(2)); 4848 } 4849 4850 // If we can fold this based on the true/false value, do so. 4851 if (SimplifySelectOps(N, N2, N3)) 4852 return SDValue(N, 0); // Don't revisit N. 4853 4854 // fold select_cc into other things, such as min/max/abs 4855 return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC); 4856 } 4857 4858 SDValue DAGCombiner::visitSETCC(SDNode *N) { 4859 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1), 4860 cast<CondCodeSDNode>(N->getOperand(2))->get(), 4861 SDLoc(N)); 4862 } 4863 4864 // tryToFoldExtendOfConstant - Try to fold a sext/zext/aext 4865 // dag node into a ConstantSDNode or a build_vector of constants. 4866 // This function is called by the DAGCombiner when visiting sext/zext/aext 4867 // dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND). 4868 // Vector extends are not folded if operations are legal; this is to 4869 // avoid introducing illegal build_vector dag nodes. 4870 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI, 4871 SelectionDAG &DAG, bool LegalTypes, 4872 bool LegalOperations) { 4873 unsigned Opcode = N->getOpcode(); 4874 SDValue N0 = N->getOperand(0); 4875 EVT VT = N->getValueType(0); 4876 4877 assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND || 4878 Opcode == ISD::ANY_EXTEND) && "Expected EXTEND dag node in input!"); 4879 4880 // fold (sext c1) -> c1 4881 // fold (zext c1) -> c1 4882 // fold (aext c1) -> c1 4883 if (isa<ConstantSDNode>(N0)) 4884 return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode(); 4885 4886 // fold (sext (build_vector AllConstants) -> (build_vector AllConstants) 4887 // fold (zext (build_vector AllConstants) -> (build_vector AllConstants) 4888 // fold (aext (build_vector AllConstants) -> (build_vector AllConstants) 4889 EVT SVT = VT.getScalarType(); 4890 if (!(VT.isVector() && 4891 (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) && 4892 ISD::isBuildVectorOfConstantSDNodes(N0.getNode()))) 4893 return nullptr; 4894 4895 // We can fold this node into a build_vector. 4896 unsigned VTBits = SVT.getSizeInBits(); 4897 unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits(); 4898 unsigned ShAmt = VTBits - EVTBits; 4899 SmallVector<SDValue, 8> Elts; 4900 unsigned NumElts = N0->getNumOperands(); 4901 SDLoc DL(N); 4902 4903 for (unsigned i=0; i != NumElts; ++i) { 4904 SDValue Op = N0->getOperand(i); 4905 if (Op->getOpcode() == ISD::UNDEF) { 4906 Elts.push_back(DAG.getUNDEF(SVT)); 4907 continue; 4908 } 4909 4910 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op); 4911 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue()); 4912 if (Opcode == ISD::SIGN_EXTEND) 4913 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(), 4914 SVT)); 4915 else 4916 Elts.push_back(DAG.getConstant(C.shl(ShAmt).lshr(ShAmt).getZExtValue(), 4917 SVT)); 4918 } 4919 4920 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts).getNode(); 4921 } 4922 4923 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this: 4924 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))" 4925 // transformation. Returns true if extension are possible and the above 4926 // mentioned transformation is profitable. 4927 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0, 4928 unsigned ExtOpc, 4929 SmallVectorImpl<SDNode *> &ExtendNodes, 4930 const TargetLowering &TLI) { 4931 bool HasCopyToRegUses = false; 4932 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType()); 4933 for (SDNode::use_iterator UI = N0.getNode()->use_begin(), 4934 UE = N0.getNode()->use_end(); 4935 UI != UE; ++UI) { 4936 SDNode *User = *UI; 4937 if (User == N) 4938 continue; 4939 if (UI.getUse().getResNo() != N0.getResNo()) 4940 continue; 4941 // FIXME: Only extend SETCC N, N and SETCC N, c for now. 4942 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) { 4943 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get(); 4944 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC)) 4945 // Sign bits will be lost after a zext. 4946 return false; 4947 bool Add = false; 4948 for (unsigned i = 0; i != 2; ++i) { 4949 SDValue UseOp = User->getOperand(i); 4950 if (UseOp == N0) 4951 continue; 4952 if (!isa<ConstantSDNode>(UseOp)) 4953 return false; 4954 Add = true; 4955 } 4956 if (Add) 4957 ExtendNodes.push_back(User); 4958 continue; 4959 } 4960 // If truncates aren't free and there are users we can't 4961 // extend, it isn't worthwhile. 4962 if (!isTruncFree) 4963 return false; 4964 // Remember if this value is live-out. 4965 if (User->getOpcode() == ISD::CopyToReg) 4966 HasCopyToRegUses = true; 4967 } 4968 4969 if (HasCopyToRegUses) { 4970 bool BothLiveOut = false; 4971 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end(); 4972 UI != UE; ++UI) { 4973 SDUse &Use = UI.getUse(); 4974 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) { 4975 BothLiveOut = true; 4976 break; 4977 } 4978 } 4979 if (BothLiveOut) 4980 // Both unextended and extended values are live out. There had better be 4981 // a good reason for the transformation. 4982 return ExtendNodes.size(); 4983 } 4984 return true; 4985 } 4986 4987 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs, 4988 SDValue Trunc, SDValue ExtLoad, SDLoc DL, 4989 ISD::NodeType ExtType) { 4990 // Extend SetCC uses if necessary. 4991 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) { 4992 SDNode *SetCC = SetCCs[i]; 4993 SmallVector<SDValue, 4> Ops; 4994 4995 for (unsigned j = 0; j != 2; ++j) { 4996 SDValue SOp = SetCC->getOperand(j); 4997 if (SOp == Trunc) 4998 Ops.push_back(ExtLoad); 4999 else 5000 Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp)); 5001 } 5002 5003 Ops.push_back(SetCC->getOperand(2)); 5004 CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops)); 5005 } 5006 } 5007 5008 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) { 5009 SDValue N0 = N->getOperand(0); 5010 EVT VT = N->getValueType(0); 5011 5012 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes, 5013 LegalOperations)) 5014 return SDValue(Res, 0); 5015 5016 // fold (sext (sext x)) -> (sext x) 5017 // fold (sext (aext x)) -> (sext x) 5018 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) 5019 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, 5020 N0.getOperand(0)); 5021 5022 if (N0.getOpcode() == ISD::TRUNCATE) { 5023 // fold (sext (truncate (load x))) -> (sext (smaller load x)) 5024 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n))) 5025 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode()); 5026 if (NarrowLoad.getNode()) { 5027 SDNode* oye = N0.getNode()->getOperand(0).getNode(); 5028 if (NarrowLoad.getNode() != N0.getNode()) { 5029 CombineTo(N0.getNode(), NarrowLoad); 5030 // CombineTo deleted the truncate, if needed, but not what's under it. 5031 AddToWorklist(oye); 5032 } 5033 return SDValue(N, 0); // Return N so it doesn't get rechecked! 5034 } 5035 5036 // See if the value being truncated is already sign extended. If so, just 5037 // eliminate the trunc/sext pair. 5038 SDValue Op = N0.getOperand(0); 5039 unsigned OpBits = Op.getValueType().getScalarType().getSizeInBits(); 5040 unsigned MidBits = N0.getValueType().getScalarType().getSizeInBits(); 5041 unsigned DestBits = VT.getScalarType().getSizeInBits(); 5042 unsigned NumSignBits = DAG.ComputeNumSignBits(Op); 5043 5044 if (OpBits == DestBits) { 5045 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign 5046 // bits, it is already ready. 5047 if (NumSignBits > DestBits-MidBits) 5048 return Op; 5049 } else if (OpBits < DestBits) { 5050 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign 5051 // bits, just sext from i32. 5052 if (NumSignBits > OpBits-MidBits) 5053 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op); 5054 } else { 5055 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign 5056 // bits, just truncate to i32. 5057 if (NumSignBits > OpBits-MidBits) 5058 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op); 5059 } 5060 5061 // fold (sext (truncate x)) -> (sextinreg x). 5062 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, 5063 N0.getValueType())) { 5064 if (OpBits < DestBits) 5065 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op); 5066 else if (OpBits > DestBits) 5067 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op); 5068 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op, 5069 DAG.getValueType(N0.getValueType())); 5070 } 5071 } 5072 5073 // fold (sext (load x)) -> (sext (truncate (sextload x))) 5074 // None of the supported targets knows how to perform load and sign extend 5075 // on vectors in one instruction. We only perform this transformation on 5076 // scalars. 5077 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() && 5078 ISD::isUNINDEXEDLoad(N0.getNode()) && 5079 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) || 5080 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()))) { 5081 bool DoXform = true; 5082 SmallVector<SDNode*, 4> SetCCs; 5083 if (!N0.hasOneUse()) 5084 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI); 5085 if (DoXform) { 5086 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 5087 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT, 5088 LN0->getChain(), 5089 LN0->getBasePtr(), N0.getValueType(), 5090 LN0->getMemOperand()); 5091 CombineTo(N, ExtLoad); 5092 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 5093 N0.getValueType(), ExtLoad); 5094 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1)); 5095 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N), 5096 ISD::SIGN_EXTEND); 5097 return SDValue(N, 0); // Return N so it doesn't get rechecked! 5098 } 5099 } 5100 5101 // fold (sext (sextload x)) -> (sext (truncate (sextload x))) 5102 // fold (sext ( extload x)) -> (sext (truncate (sextload x))) 5103 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) && 5104 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) { 5105 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 5106 EVT MemVT = LN0->getMemoryVT(); 5107 if ((!LegalOperations && !LN0->isVolatile()) || 5108 TLI.isLoadExtLegal(ISD::SEXTLOAD, MemVT)) { 5109 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT, 5110 LN0->getChain(), 5111 LN0->getBasePtr(), MemVT, 5112 LN0->getMemOperand()); 5113 CombineTo(N, ExtLoad); 5114 CombineTo(N0.getNode(), 5115 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 5116 N0.getValueType(), ExtLoad), 5117 ExtLoad.getValue(1)); 5118 return SDValue(N, 0); // Return N so it doesn't get rechecked! 5119 } 5120 } 5121 5122 // fold (sext (and/or/xor (load x), cst)) -> 5123 // (and/or/xor (sextload x), (sext cst)) 5124 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR || 5125 N0.getOpcode() == ISD::XOR) && 5126 isa<LoadSDNode>(N0.getOperand(0)) && 5127 N0.getOperand(1).getOpcode() == ISD::Constant && 5128 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()) && 5129 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) { 5130 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0)); 5131 if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) { 5132 bool DoXform = true; 5133 SmallVector<SDNode*, 4> SetCCs; 5134 if (!N0.hasOneUse()) 5135 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND, 5136 SetCCs, TLI); 5137 if (DoXform) { 5138 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT, 5139 LN0->getChain(), LN0->getBasePtr(), 5140 LN0->getMemoryVT(), 5141 LN0->getMemOperand()); 5142 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 5143 Mask = Mask.sext(VT.getSizeInBits()); 5144 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT, 5145 ExtLoad, DAG.getConstant(Mask, VT)); 5146 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, 5147 SDLoc(N0.getOperand(0)), 5148 N0.getOperand(0).getValueType(), ExtLoad); 5149 CombineTo(N, And); 5150 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1)); 5151 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N), 5152 ISD::SIGN_EXTEND); 5153 return SDValue(N, 0); // Return N so it doesn't get rechecked! 5154 } 5155 } 5156 } 5157 5158 if (N0.getOpcode() == ISD::SETCC) { 5159 EVT N0VT = N0.getOperand(0).getValueType(); 5160 // sext(setcc) -> sext_in_reg(vsetcc) for vectors. 5161 // Only do this before legalize for now. 5162 if (VT.isVector() && !LegalOperations && 5163 TLI.getBooleanContents(N0VT) == 5164 TargetLowering::ZeroOrNegativeOneBooleanContent) { 5165 // On some architectures (such as SSE/NEON/etc) the SETCC result type is 5166 // of the same size as the compared operands. Only optimize sext(setcc()) 5167 // if this is the case. 5168 EVT SVT = getSetCCResultType(N0VT); 5169 5170 // We know that the # elements of the results is the same as the 5171 // # elements of the compare (and the # elements of the compare result 5172 // for that matter). Check to see that they are the same size. If so, 5173 // we know that the element size of the sext'd result matches the 5174 // element size of the compare operands. 5175 if (VT.getSizeInBits() == SVT.getSizeInBits()) 5176 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0), 5177 N0.getOperand(1), 5178 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 5179 5180 // If the desired elements are smaller or larger than the source 5181 // elements we can use a matching integer vector type and then 5182 // truncate/sign extend 5183 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger(); 5184 if (SVT == MatchingVectorType) { 5185 SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType, 5186 N0.getOperand(0), N0.getOperand(1), 5187 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 5188 return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT); 5189 } 5190 } 5191 5192 // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0) 5193 unsigned ElementWidth = VT.getScalarType().getSizeInBits(); 5194 SDValue NegOne = 5195 DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT); 5196 SDValue SCC = 5197 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1), 5198 NegOne, DAG.getConstant(0, VT), 5199 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true); 5200 if (SCC.getNode()) return SCC; 5201 5202 if (!VT.isVector()) { 5203 EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType()); 5204 if (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, SetCCVT)) { 5205 SDLoc DL(N); 5206 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get(); 5207 SDValue SetCC = DAG.getSetCC(DL, 5208 SetCCVT, 5209 N0.getOperand(0), N0.getOperand(1), CC); 5210 EVT SelectVT = getSetCCResultType(VT); 5211 return DAG.getSelect(DL, VT, 5212 DAG.getSExtOrTrunc(SetCC, DL, SelectVT), 5213 NegOne, DAG.getConstant(0, VT)); 5214 5215 } 5216 } 5217 } 5218 5219 // fold (sext x) -> (zext x) if the sign bit is known zero. 5220 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) && 5221 DAG.SignBitIsZero(N0)) 5222 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0); 5223 5224 return SDValue(); 5225 } 5226 5227 // isTruncateOf - If N is a truncate of some other value, return true, record 5228 // the value being truncated in Op and which of Op's bits are zero in KnownZero. 5229 // This function computes KnownZero to avoid a duplicated call to 5230 // computeKnownBits in the caller. 5231 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op, 5232 APInt &KnownZero) { 5233 APInt KnownOne; 5234 if (N->getOpcode() == ISD::TRUNCATE) { 5235 Op = N->getOperand(0); 5236 DAG.computeKnownBits(Op, KnownZero, KnownOne); 5237 return true; 5238 } 5239 5240 if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 || 5241 cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE) 5242 return false; 5243 5244 SDValue Op0 = N->getOperand(0); 5245 SDValue Op1 = N->getOperand(1); 5246 assert(Op0.getValueType() == Op1.getValueType()); 5247 5248 ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0); 5249 ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1); 5250 if (COp0 && COp0->isNullValue()) 5251 Op = Op1; 5252 else if (COp1 && COp1->isNullValue()) 5253 Op = Op0; 5254 else 5255 return false; 5256 5257 DAG.computeKnownBits(Op, KnownZero, KnownOne); 5258 5259 if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue()) 5260 return false; 5261 5262 return true; 5263 } 5264 5265 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) { 5266 SDValue N0 = N->getOperand(0); 5267 EVT VT = N->getValueType(0); 5268 5269 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes, 5270 LegalOperations)) 5271 return SDValue(Res, 0); 5272 5273 // fold (zext (zext x)) -> (zext x) 5274 // fold (zext (aext x)) -> (zext x) 5275 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) 5276 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, 5277 N0.getOperand(0)); 5278 5279 // fold (zext (truncate x)) -> (zext x) or 5280 // (zext (truncate x)) -> (truncate x) 5281 // This is valid when the truncated bits of x are already zero. 5282 // FIXME: We should extend this to work for vectors too. 5283 SDValue Op; 5284 APInt KnownZero; 5285 if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) { 5286 APInt TruncatedBits = 5287 (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ? 5288 APInt(Op.getValueSizeInBits(), 0) : 5289 APInt::getBitsSet(Op.getValueSizeInBits(), 5290 N0.getValueSizeInBits(), 5291 std::min(Op.getValueSizeInBits(), 5292 VT.getSizeInBits())); 5293 if (TruncatedBits == (KnownZero & TruncatedBits)) { 5294 if (VT.bitsGT(Op.getValueType())) 5295 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op); 5296 if (VT.bitsLT(Op.getValueType())) 5297 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op); 5298 5299 return Op; 5300 } 5301 } 5302 5303 // fold (zext (truncate (load x))) -> (zext (smaller load x)) 5304 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n))) 5305 if (N0.getOpcode() == ISD::TRUNCATE) { 5306 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode()); 5307 if (NarrowLoad.getNode()) { 5308 SDNode* oye = N0.getNode()->getOperand(0).getNode(); 5309 if (NarrowLoad.getNode() != N0.getNode()) { 5310 CombineTo(N0.getNode(), NarrowLoad); 5311 // CombineTo deleted the truncate, if needed, but not what's under it. 5312 AddToWorklist(oye); 5313 } 5314 return SDValue(N, 0); // Return N so it doesn't get rechecked! 5315 } 5316 } 5317 5318 // fold (zext (truncate x)) -> (and x, mask) 5319 if (N0.getOpcode() == ISD::TRUNCATE && 5320 (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) { 5321 5322 // fold (zext (truncate (load x))) -> (zext (smaller load x)) 5323 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n))) 5324 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode()); 5325 if (NarrowLoad.getNode()) { 5326 SDNode* oye = N0.getNode()->getOperand(0).getNode(); 5327 if (NarrowLoad.getNode() != N0.getNode()) { 5328 CombineTo(N0.getNode(), NarrowLoad); 5329 // CombineTo deleted the truncate, if needed, but not what's under it. 5330 AddToWorklist(oye); 5331 } 5332 return SDValue(N, 0); // Return N so it doesn't get rechecked! 5333 } 5334 5335 SDValue Op = N0.getOperand(0); 5336 if (Op.getValueType().bitsLT(VT)) { 5337 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op); 5338 AddToWorklist(Op.getNode()); 5339 } else if (Op.getValueType().bitsGT(VT)) { 5340 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op); 5341 AddToWorklist(Op.getNode()); 5342 } 5343 return DAG.getZeroExtendInReg(Op, SDLoc(N), 5344 N0.getValueType().getScalarType()); 5345 } 5346 5347 // Fold (zext (and (trunc x), cst)) -> (and x, cst), 5348 // if either of the casts is not free. 5349 if (N0.getOpcode() == ISD::AND && 5350 N0.getOperand(0).getOpcode() == ISD::TRUNCATE && 5351 N0.getOperand(1).getOpcode() == ISD::Constant && 5352 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(), 5353 N0.getValueType()) || 5354 !TLI.isZExtFree(N0.getValueType(), VT))) { 5355 SDValue X = N0.getOperand(0).getOperand(0); 5356 if (X.getValueType().bitsLT(VT)) { 5357 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X); 5358 } else if (X.getValueType().bitsGT(VT)) { 5359 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X); 5360 } 5361 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 5362 Mask = Mask.zext(VT.getSizeInBits()); 5363 return DAG.getNode(ISD::AND, SDLoc(N), VT, 5364 X, DAG.getConstant(Mask, VT)); 5365 } 5366 5367 // fold (zext (load x)) -> (zext (truncate (zextload x))) 5368 // None of the supported targets knows how to perform load and vector_zext 5369 // on vectors in one instruction. We only perform this transformation on 5370 // scalars. 5371 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() && 5372 ISD::isUNINDEXEDLoad(N0.getNode()) && 5373 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) || 5374 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()))) { 5375 bool DoXform = true; 5376 SmallVector<SDNode*, 4> SetCCs; 5377 if (!N0.hasOneUse()) 5378 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI); 5379 if (DoXform) { 5380 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 5381 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT, 5382 LN0->getChain(), 5383 LN0->getBasePtr(), N0.getValueType(), 5384 LN0->getMemOperand()); 5385 CombineTo(N, ExtLoad); 5386 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 5387 N0.getValueType(), ExtLoad); 5388 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1)); 5389 5390 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N), 5391 ISD::ZERO_EXTEND); 5392 return SDValue(N, 0); // Return N so it doesn't get rechecked! 5393 } 5394 } 5395 5396 // fold (zext (and/or/xor (load x), cst)) -> 5397 // (and/or/xor (zextload x), (zext cst)) 5398 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR || 5399 N0.getOpcode() == ISD::XOR) && 5400 isa<LoadSDNode>(N0.getOperand(0)) && 5401 N0.getOperand(1).getOpcode() == ISD::Constant && 5402 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()) && 5403 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) { 5404 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0)); 5405 if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) { 5406 bool DoXform = true; 5407 SmallVector<SDNode*, 4> SetCCs; 5408 if (!N0.hasOneUse()) 5409 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND, 5410 SetCCs, TLI); 5411 if (DoXform) { 5412 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT, 5413 LN0->getChain(), LN0->getBasePtr(), 5414 LN0->getMemoryVT(), 5415 LN0->getMemOperand()); 5416 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 5417 Mask = Mask.zext(VT.getSizeInBits()); 5418 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT, 5419 ExtLoad, DAG.getConstant(Mask, VT)); 5420 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, 5421 SDLoc(N0.getOperand(0)), 5422 N0.getOperand(0).getValueType(), ExtLoad); 5423 CombineTo(N, And); 5424 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1)); 5425 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N), 5426 ISD::ZERO_EXTEND); 5427 return SDValue(N, 0); // Return N so it doesn't get rechecked! 5428 } 5429 } 5430 } 5431 5432 // fold (zext (zextload x)) -> (zext (truncate (zextload x))) 5433 // fold (zext ( extload x)) -> (zext (truncate (zextload x))) 5434 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) && 5435 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) { 5436 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 5437 EVT MemVT = LN0->getMemoryVT(); 5438 if ((!LegalOperations && !LN0->isVolatile()) || 5439 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT)) { 5440 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT, 5441 LN0->getChain(), 5442 LN0->getBasePtr(), MemVT, 5443 LN0->getMemOperand()); 5444 CombineTo(N, ExtLoad); 5445 CombineTo(N0.getNode(), 5446 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), 5447 ExtLoad), 5448 ExtLoad.getValue(1)); 5449 return SDValue(N, 0); // Return N so it doesn't get rechecked! 5450 } 5451 } 5452 5453 if (N0.getOpcode() == ISD::SETCC) { 5454 if (!LegalOperations && VT.isVector() && 5455 N0.getValueType().getVectorElementType() == MVT::i1) { 5456 EVT N0VT = N0.getOperand(0).getValueType(); 5457 if (getSetCCResultType(N0VT) == N0.getValueType()) 5458 return SDValue(); 5459 5460 // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors. 5461 // Only do this before legalize for now. 5462 EVT EltVT = VT.getVectorElementType(); 5463 SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(), 5464 DAG.getConstant(1, EltVT)); 5465 if (VT.getSizeInBits() == N0VT.getSizeInBits()) 5466 // We know that the # elements of the results is the same as the 5467 // # elements of the compare (and the # elements of the compare result 5468 // for that matter). Check to see that they are the same size. If so, 5469 // we know that the element size of the sext'd result matches the 5470 // element size of the compare operands. 5471 return DAG.getNode(ISD::AND, SDLoc(N), VT, 5472 DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0), 5473 N0.getOperand(1), 5474 cast<CondCodeSDNode>(N0.getOperand(2))->get()), 5475 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, 5476 OneOps)); 5477 5478 // If the desired elements are smaller or larger than the source 5479 // elements we can use a matching integer vector type and then 5480 // truncate/sign extend 5481 EVT MatchingElementType = 5482 EVT::getIntegerVT(*DAG.getContext(), 5483 N0VT.getScalarType().getSizeInBits()); 5484 EVT MatchingVectorType = 5485 EVT::getVectorVT(*DAG.getContext(), MatchingElementType, 5486 N0VT.getVectorNumElements()); 5487 SDValue VsetCC = 5488 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0), 5489 N0.getOperand(1), 5490 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 5491 return DAG.getNode(ISD::AND, SDLoc(N), VT, 5492 DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT), 5493 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, OneOps)); 5494 } 5495 5496 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc 5497 SDValue SCC = 5498 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1), 5499 DAG.getConstant(1, VT), DAG.getConstant(0, VT), 5500 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true); 5501 if (SCC.getNode()) return SCC; 5502 } 5503 5504 // (zext (shl (zext x), cst)) -> (shl (zext x), cst) 5505 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) && 5506 isa<ConstantSDNode>(N0.getOperand(1)) && 5507 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND && 5508 N0.hasOneUse()) { 5509 SDValue ShAmt = N0.getOperand(1); 5510 unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue(); 5511 if (N0.getOpcode() == ISD::SHL) { 5512 SDValue InnerZExt = N0.getOperand(0); 5513 // If the original shl may be shifting out bits, do not perform this 5514 // transformation. 5515 unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() - 5516 InnerZExt.getOperand(0).getValueType().getSizeInBits(); 5517 if (ShAmtVal > KnownZeroBits) 5518 return SDValue(); 5519 } 5520 5521 SDLoc DL(N); 5522 5523 // Ensure that the shift amount is wide enough for the shifted value. 5524 if (VT.getSizeInBits() >= 256) 5525 ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt); 5526 5527 return DAG.getNode(N0.getOpcode(), DL, VT, 5528 DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)), 5529 ShAmt); 5530 } 5531 5532 return SDValue(); 5533 } 5534 5535 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) { 5536 SDValue N0 = N->getOperand(0); 5537 EVT VT = N->getValueType(0); 5538 5539 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes, 5540 LegalOperations)) 5541 return SDValue(Res, 0); 5542 5543 // fold (aext (aext x)) -> (aext x) 5544 // fold (aext (zext x)) -> (zext x) 5545 // fold (aext (sext x)) -> (sext x) 5546 if (N0.getOpcode() == ISD::ANY_EXTEND || 5547 N0.getOpcode() == ISD::ZERO_EXTEND || 5548 N0.getOpcode() == ISD::SIGN_EXTEND) 5549 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0)); 5550 5551 // fold (aext (truncate (load x))) -> (aext (smaller load x)) 5552 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n))) 5553 if (N0.getOpcode() == ISD::TRUNCATE) { 5554 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode()); 5555 if (NarrowLoad.getNode()) { 5556 SDNode* oye = N0.getNode()->getOperand(0).getNode(); 5557 if (NarrowLoad.getNode() != N0.getNode()) { 5558 CombineTo(N0.getNode(), NarrowLoad); 5559 // CombineTo deleted the truncate, if needed, but not what's under it. 5560 AddToWorklist(oye); 5561 } 5562 return SDValue(N, 0); // Return N so it doesn't get rechecked! 5563 } 5564 } 5565 5566 // fold (aext (truncate x)) 5567 if (N0.getOpcode() == ISD::TRUNCATE) { 5568 SDValue TruncOp = N0.getOperand(0); 5569 if (TruncOp.getValueType() == VT) 5570 return TruncOp; // x iff x size == zext size. 5571 if (TruncOp.getValueType().bitsGT(VT)) 5572 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp); 5573 return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp); 5574 } 5575 5576 // Fold (aext (and (trunc x), cst)) -> (and x, cst) 5577 // if the trunc is not free. 5578 if (N0.getOpcode() == ISD::AND && 5579 N0.getOperand(0).getOpcode() == ISD::TRUNCATE && 5580 N0.getOperand(1).getOpcode() == ISD::Constant && 5581 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(), 5582 N0.getValueType())) { 5583 SDValue X = N0.getOperand(0).getOperand(0); 5584 if (X.getValueType().bitsLT(VT)) { 5585 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X); 5586 } else if (X.getValueType().bitsGT(VT)) { 5587 X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X); 5588 } 5589 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 5590 Mask = Mask.zext(VT.getSizeInBits()); 5591 return DAG.getNode(ISD::AND, SDLoc(N), VT, 5592 X, DAG.getConstant(Mask, VT)); 5593 } 5594 5595 // fold (aext (load x)) -> (aext (truncate (extload x))) 5596 // None of the supported targets knows how to perform load and any_ext 5597 // on vectors in one instruction. We only perform this transformation on 5598 // scalars. 5599 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() && 5600 ISD::isUNINDEXEDLoad(N0.getNode()) && 5601 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType())) { 5602 bool DoXform = true; 5603 SmallVector<SDNode*, 4> SetCCs; 5604 if (!N0.hasOneUse()) 5605 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI); 5606 if (DoXform) { 5607 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 5608 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT, 5609 LN0->getChain(), 5610 LN0->getBasePtr(), N0.getValueType(), 5611 LN0->getMemOperand()); 5612 CombineTo(N, ExtLoad); 5613 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 5614 N0.getValueType(), ExtLoad); 5615 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1)); 5616 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N), 5617 ISD::ANY_EXTEND); 5618 return SDValue(N, 0); // Return N so it doesn't get rechecked! 5619 } 5620 } 5621 5622 // fold (aext (zextload x)) -> (aext (truncate (zextload x))) 5623 // fold (aext (sextload x)) -> (aext (truncate (sextload x))) 5624 // fold (aext ( extload x)) -> (aext (truncate (extload x))) 5625 if (N0.getOpcode() == ISD::LOAD && 5626 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 5627 N0.hasOneUse()) { 5628 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 5629 ISD::LoadExtType ExtType = LN0->getExtensionType(); 5630 EVT MemVT = LN0->getMemoryVT(); 5631 if (!LegalOperations || TLI.isLoadExtLegal(ExtType, MemVT)) { 5632 SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N), 5633 VT, LN0->getChain(), LN0->getBasePtr(), 5634 MemVT, LN0->getMemOperand()); 5635 CombineTo(N, ExtLoad); 5636 CombineTo(N0.getNode(), 5637 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 5638 N0.getValueType(), ExtLoad), 5639 ExtLoad.getValue(1)); 5640 return SDValue(N, 0); // Return N so it doesn't get rechecked! 5641 } 5642 } 5643 5644 if (N0.getOpcode() == ISD::SETCC) { 5645 // For vectors: 5646 // aext(setcc) -> vsetcc 5647 // aext(setcc) -> truncate(vsetcc) 5648 // aext(setcc) -> aext(vsetcc) 5649 // Only do this before legalize for now. 5650 if (VT.isVector() && !LegalOperations) { 5651 EVT N0VT = N0.getOperand(0).getValueType(); 5652 // We know that the # elements of the results is the same as the 5653 // # elements of the compare (and the # elements of the compare result 5654 // for that matter). Check to see that they are the same size. If so, 5655 // we know that the element size of the sext'd result matches the 5656 // element size of the compare operands. 5657 if (VT.getSizeInBits() == N0VT.getSizeInBits()) 5658 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0), 5659 N0.getOperand(1), 5660 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 5661 // If the desired elements are smaller or larger than the source 5662 // elements we can use a matching integer vector type and then 5663 // truncate/any extend 5664 else { 5665 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger(); 5666 SDValue VsetCC = 5667 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0), 5668 N0.getOperand(1), 5669 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 5670 return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT); 5671 } 5672 } 5673 5674 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc 5675 SDValue SCC = 5676 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1), 5677 DAG.getConstant(1, VT), DAG.getConstant(0, VT), 5678 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true); 5679 if (SCC.getNode()) 5680 return SCC; 5681 } 5682 5683 return SDValue(); 5684 } 5685 5686 /// See if the specified operand can be simplified with the knowledge that only 5687 /// the bits specified by Mask are used. If so, return the simpler operand, 5688 /// otherwise return a null SDValue. 5689 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) { 5690 switch (V.getOpcode()) { 5691 default: break; 5692 case ISD::Constant: { 5693 const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode()); 5694 assert(CV && "Const value should be ConstSDNode."); 5695 const APInt &CVal = CV->getAPIntValue(); 5696 APInt NewVal = CVal & Mask; 5697 if (NewVal != CVal) 5698 return DAG.getConstant(NewVal, V.getValueType()); 5699 break; 5700 } 5701 case ISD::OR: 5702 case ISD::XOR: 5703 // If the LHS or RHS don't contribute bits to the or, drop them. 5704 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask)) 5705 return V.getOperand(1); 5706 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask)) 5707 return V.getOperand(0); 5708 break; 5709 case ISD::SRL: 5710 // Only look at single-use SRLs. 5711 if (!V.getNode()->hasOneUse()) 5712 break; 5713 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) { 5714 // See if we can recursively simplify the LHS. 5715 unsigned Amt = RHSC->getZExtValue(); 5716 5717 // Watch out for shift count overflow though. 5718 if (Amt >= Mask.getBitWidth()) break; 5719 APInt NewMask = Mask << Amt; 5720 SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask); 5721 if (SimplifyLHS.getNode()) 5722 return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(), 5723 SimplifyLHS, V.getOperand(1)); 5724 } 5725 } 5726 return SDValue(); 5727 } 5728 5729 /// If the result of a wider load is shifted to right of N bits and then 5730 /// truncated to a narrower type and where N is a multiple of number of bits of 5731 /// the narrower type, transform it to a narrower load from address + N / num of 5732 /// bits of new type. If the result is to be extended, also fold the extension 5733 /// to form a extending load. 5734 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) { 5735 unsigned Opc = N->getOpcode(); 5736 5737 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD; 5738 SDValue N0 = N->getOperand(0); 5739 EVT VT = N->getValueType(0); 5740 EVT ExtVT = VT; 5741 5742 // This transformation isn't valid for vector loads. 5743 if (VT.isVector()) 5744 return SDValue(); 5745 5746 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then 5747 // extended to VT. 5748 if (Opc == ISD::SIGN_EXTEND_INREG) { 5749 ExtType = ISD::SEXTLOAD; 5750 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT(); 5751 } else if (Opc == ISD::SRL) { 5752 // Another special-case: SRL is basically zero-extending a narrower value. 5753 ExtType = ISD::ZEXTLOAD; 5754 N0 = SDValue(N, 0); 5755 ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 5756 if (!N01) return SDValue(); 5757 ExtVT = EVT::getIntegerVT(*DAG.getContext(), 5758 VT.getSizeInBits() - N01->getZExtValue()); 5759 } 5760 if (LegalOperations && !TLI.isLoadExtLegal(ExtType, ExtVT)) 5761 return SDValue(); 5762 5763 unsigned EVTBits = ExtVT.getSizeInBits(); 5764 5765 // Do not generate loads of non-round integer types since these can 5766 // be expensive (and would be wrong if the type is not byte sized). 5767 if (!ExtVT.isRound()) 5768 return SDValue(); 5769 5770 unsigned ShAmt = 0; 5771 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) { 5772 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 5773 ShAmt = N01->getZExtValue(); 5774 // Is the shift amount a multiple of size of VT? 5775 if ((ShAmt & (EVTBits-1)) == 0) { 5776 N0 = N0.getOperand(0); 5777 // Is the load width a multiple of size of VT? 5778 if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0) 5779 return SDValue(); 5780 } 5781 5782 // At this point, we must have a load or else we can't do the transform. 5783 if (!isa<LoadSDNode>(N0)) return SDValue(); 5784 5785 // Because a SRL must be assumed to *need* to zero-extend the high bits 5786 // (as opposed to anyext the high bits), we can't combine the zextload 5787 // lowering of SRL and an sextload. 5788 if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD) 5789 return SDValue(); 5790 5791 // If the shift amount is larger than the input type then we're not 5792 // accessing any of the loaded bytes. If the load was a zextload/extload 5793 // then the result of the shift+trunc is zero/undef (handled elsewhere). 5794 if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits()) 5795 return SDValue(); 5796 } 5797 } 5798 5799 // If the load is shifted left (and the result isn't shifted back right), 5800 // we can fold the truncate through the shift. 5801 unsigned ShLeftAmt = 0; 5802 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() && 5803 ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) { 5804 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 5805 ShLeftAmt = N01->getZExtValue(); 5806 N0 = N0.getOperand(0); 5807 } 5808 } 5809 5810 // If we haven't found a load, we can't narrow it. Don't transform one with 5811 // multiple uses, this would require adding a new load. 5812 if (!isa<LoadSDNode>(N0) || !N0.hasOneUse()) 5813 return SDValue(); 5814 5815 // Don't change the width of a volatile load. 5816 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 5817 if (LN0->isVolatile()) 5818 return SDValue(); 5819 5820 // Verify that we are actually reducing a load width here. 5821 if (LN0->getMemoryVT().getSizeInBits() < EVTBits) 5822 return SDValue(); 5823 5824 // For the transform to be legal, the load must produce only two values 5825 // (the value loaded and the chain). Don't transform a pre-increment 5826 // load, for example, which produces an extra value. Otherwise the 5827 // transformation is not equivalent, and the downstream logic to replace 5828 // uses gets things wrong. 5829 if (LN0->getNumValues() > 2) 5830 return SDValue(); 5831 5832 // If the load that we're shrinking is an extload and we're not just 5833 // discarding the extension we can't simply shrink the load. Bail. 5834 // TODO: It would be possible to merge the extensions in some cases. 5835 if (LN0->getExtensionType() != ISD::NON_EXTLOAD && 5836 LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt) 5837 return SDValue(); 5838 5839 EVT PtrType = N0.getOperand(1).getValueType(); 5840 5841 if (PtrType == MVT::Untyped || PtrType.isExtended()) 5842 // It's not possible to generate a constant of extended or untyped type. 5843 return SDValue(); 5844 5845 // For big endian targets, we need to adjust the offset to the pointer to 5846 // load the correct bytes. 5847 if (TLI.isBigEndian()) { 5848 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits(); 5849 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits(); 5850 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt; 5851 } 5852 5853 uint64_t PtrOff = ShAmt / 8; 5854 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff); 5855 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0), 5856 PtrType, LN0->getBasePtr(), 5857 DAG.getConstant(PtrOff, PtrType)); 5858 AddToWorklist(NewPtr.getNode()); 5859 5860 SDValue Load; 5861 if (ExtType == ISD::NON_EXTLOAD) 5862 Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr, 5863 LN0->getPointerInfo().getWithOffset(PtrOff), 5864 LN0->isVolatile(), LN0->isNonTemporal(), 5865 LN0->isInvariant(), NewAlign, LN0->getAAInfo()); 5866 else 5867 Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr, 5868 LN0->getPointerInfo().getWithOffset(PtrOff), 5869 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(), 5870 LN0->isInvariant(), NewAlign, LN0->getAAInfo()); 5871 5872 // Replace the old load's chain with the new load's chain. 5873 WorklistRemover DeadNodes(*this); 5874 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1)); 5875 5876 // Shift the result left, if we've swallowed a left shift. 5877 SDValue Result = Load; 5878 if (ShLeftAmt != 0) { 5879 EVT ShImmTy = getShiftAmountTy(Result.getValueType()); 5880 if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt)) 5881 ShImmTy = VT; 5882 // If the shift amount is as large as the result size (but, presumably, 5883 // no larger than the source) then the useful bits of the result are 5884 // zero; we can't simply return the shortened shift, because the result 5885 // of that operation is undefined. 5886 if (ShLeftAmt >= VT.getSizeInBits()) 5887 Result = DAG.getConstant(0, VT); 5888 else 5889 Result = DAG.getNode(ISD::SHL, SDLoc(N0), VT, 5890 Result, DAG.getConstant(ShLeftAmt, ShImmTy)); 5891 } 5892 5893 // Return the new loaded value. 5894 return Result; 5895 } 5896 5897 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) { 5898 SDValue N0 = N->getOperand(0); 5899 SDValue N1 = N->getOperand(1); 5900 EVT VT = N->getValueType(0); 5901 EVT EVT = cast<VTSDNode>(N1)->getVT(); 5902 unsigned VTBits = VT.getScalarType().getSizeInBits(); 5903 unsigned EVTBits = EVT.getScalarType().getSizeInBits(); 5904 5905 // fold (sext_in_reg c1) -> c1 5906 if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF) 5907 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1); 5908 5909 // If the input is already sign extended, just drop the extension. 5910 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1) 5911 return N0; 5912 5913 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2 5914 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG && 5915 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT())) 5916 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, 5917 N0.getOperand(0), N1); 5918 5919 // fold (sext_in_reg (sext x)) -> (sext x) 5920 // fold (sext_in_reg (aext x)) -> (sext x) 5921 // if x is small enough. 5922 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) { 5923 SDValue N00 = N0.getOperand(0); 5924 if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits && 5925 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT))) 5926 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1); 5927 } 5928 5929 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero. 5930 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits))) 5931 return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT); 5932 5933 // fold operands of sext_in_reg based on knowledge that the top bits are not 5934 // demanded. 5935 if (SimplifyDemandedBits(SDValue(N, 0))) 5936 return SDValue(N, 0); 5937 5938 // fold (sext_in_reg (load x)) -> (smaller sextload x) 5939 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits)) 5940 SDValue NarrowLoad = ReduceLoadWidth(N); 5941 if (NarrowLoad.getNode()) 5942 return NarrowLoad; 5943 5944 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24) 5945 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible. 5946 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above. 5947 if (N0.getOpcode() == ISD::SRL) { 5948 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1))) 5949 if (ShAmt->getZExtValue()+EVTBits <= VTBits) { 5950 // We can turn this into an SRA iff the input to the SRL is already sign 5951 // extended enough. 5952 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0)); 5953 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits) 5954 return DAG.getNode(ISD::SRA, SDLoc(N), VT, 5955 N0.getOperand(0), N0.getOperand(1)); 5956 } 5957 } 5958 5959 // fold (sext_inreg (extload x)) -> (sextload x) 5960 if (ISD::isEXTLoad(N0.getNode()) && 5961 ISD::isUNINDEXEDLoad(N0.getNode()) && 5962 EVT == cast<LoadSDNode>(N0)->getMemoryVT() && 5963 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) || 5964 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) { 5965 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 5966 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT, 5967 LN0->getChain(), 5968 LN0->getBasePtr(), EVT, 5969 LN0->getMemOperand()); 5970 CombineTo(N, ExtLoad); 5971 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 5972 AddToWorklist(ExtLoad.getNode()); 5973 return SDValue(N, 0); // Return N so it doesn't get rechecked! 5974 } 5975 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use 5976 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 5977 N0.hasOneUse() && 5978 EVT == cast<LoadSDNode>(N0)->getMemoryVT() && 5979 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) || 5980 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) { 5981 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 5982 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT, 5983 LN0->getChain(), 5984 LN0->getBasePtr(), EVT, 5985 LN0->getMemOperand()); 5986 CombineTo(N, ExtLoad); 5987 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 5988 return SDValue(N, 0); // Return N so it doesn't get rechecked! 5989 } 5990 5991 // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16)) 5992 if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) { 5993 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0), 5994 N0.getOperand(1), false); 5995 if (BSwap.getNode()) 5996 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, 5997 BSwap, N1); 5998 } 5999 6000 // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs 6001 // into a build_vector. 6002 if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) { 6003 SmallVector<SDValue, 8> Elts; 6004 unsigned NumElts = N0->getNumOperands(); 6005 unsigned ShAmt = VTBits - EVTBits; 6006 6007 for (unsigned i = 0; i != NumElts; ++i) { 6008 SDValue Op = N0->getOperand(i); 6009 if (Op->getOpcode() == ISD::UNDEF) { 6010 Elts.push_back(Op); 6011 continue; 6012 } 6013 6014 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op); 6015 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue()); 6016 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(), 6017 Op.getValueType())); 6018 } 6019 6020 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Elts); 6021 } 6022 6023 return SDValue(); 6024 } 6025 6026 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) { 6027 SDValue N0 = N->getOperand(0); 6028 EVT VT = N->getValueType(0); 6029 bool isLE = TLI.isLittleEndian(); 6030 6031 // noop truncate 6032 if (N0.getValueType() == N->getValueType(0)) 6033 return N0; 6034 // fold (truncate c1) -> c1 6035 if (isa<ConstantSDNode>(N0)) 6036 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0); 6037 // fold (truncate (truncate x)) -> (truncate x) 6038 if (N0.getOpcode() == ISD::TRUNCATE) 6039 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0)); 6040 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x 6041 if (N0.getOpcode() == ISD::ZERO_EXTEND || 6042 N0.getOpcode() == ISD::SIGN_EXTEND || 6043 N0.getOpcode() == ISD::ANY_EXTEND) { 6044 if (N0.getOperand(0).getValueType().bitsLT(VT)) 6045 // if the source is smaller than the dest, we still need an extend 6046 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, 6047 N0.getOperand(0)); 6048 if (N0.getOperand(0).getValueType().bitsGT(VT)) 6049 // if the source is larger than the dest, than we just need the truncate 6050 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0)); 6051 // if the source and dest are the same type, we can drop both the extend 6052 // and the truncate. 6053 return N0.getOperand(0); 6054 } 6055 6056 // Fold extract-and-trunc into a narrow extract. For example: 6057 // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1) 6058 // i32 y = TRUNCATE(i64 x) 6059 // -- becomes -- 6060 // v16i8 b = BITCAST (v2i64 val) 6061 // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8) 6062 // 6063 // Note: We only run this optimization after type legalization (which often 6064 // creates this pattern) and before operation legalization after which 6065 // we need to be more careful about the vector instructions that we generate. 6066 if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT && 6067 LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) { 6068 6069 EVT VecTy = N0.getOperand(0).getValueType(); 6070 EVT ExTy = N0.getValueType(); 6071 EVT TrTy = N->getValueType(0); 6072 6073 unsigned NumElem = VecTy.getVectorNumElements(); 6074 unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits(); 6075 6076 EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem); 6077 assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size"); 6078 6079 SDValue EltNo = N0->getOperand(1); 6080 if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) { 6081 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue(); 6082 EVT IndexTy = TLI.getVectorIdxTy(); 6083 int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1)); 6084 6085 SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N), 6086 NVT, N0.getOperand(0)); 6087 6088 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, 6089 SDLoc(N), TrTy, V, 6090 DAG.getConstant(Index, IndexTy)); 6091 } 6092 } 6093 6094 // trunc (select c, a, b) -> select c, (trunc a), (trunc b) 6095 if (N0.getOpcode() == ISD::SELECT) { 6096 EVT SrcVT = N0.getValueType(); 6097 if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) && 6098 TLI.isTruncateFree(SrcVT, VT)) { 6099 SDLoc SL(N0); 6100 SDValue Cond = N0.getOperand(0); 6101 SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1)); 6102 SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2)); 6103 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1); 6104 } 6105 } 6106 6107 // Fold a series of buildvector, bitcast, and truncate if possible. 6108 // For example fold 6109 // (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to 6110 // (2xi32 (buildvector x, y)). 6111 if (Level == AfterLegalizeVectorOps && VT.isVector() && 6112 N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() && 6113 N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR && 6114 N0.getOperand(0).hasOneUse()) { 6115 6116 SDValue BuildVect = N0.getOperand(0); 6117 EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType(); 6118 EVT TruncVecEltTy = VT.getVectorElementType(); 6119 6120 // Check that the element types match. 6121 if (BuildVectEltTy == TruncVecEltTy) { 6122 // Now we only need to compute the offset of the truncated elements. 6123 unsigned BuildVecNumElts = BuildVect.getNumOperands(); 6124 unsigned TruncVecNumElts = VT.getVectorNumElements(); 6125 unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts; 6126 6127 assert((BuildVecNumElts % TruncVecNumElts) == 0 && 6128 "Invalid number of elements"); 6129 6130 SmallVector<SDValue, 8> Opnds; 6131 for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset) 6132 Opnds.push_back(BuildVect.getOperand(i)); 6133 6134 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds); 6135 } 6136 } 6137 6138 // See if we can simplify the input to this truncate through knowledge that 6139 // only the low bits are being used. 6140 // For example "trunc (or (shl x, 8), y)" // -> trunc y 6141 // Currently we only perform this optimization on scalars because vectors 6142 // may have different active low bits. 6143 if (!VT.isVector()) { 6144 SDValue Shorter = 6145 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(), 6146 VT.getSizeInBits())); 6147 if (Shorter.getNode()) 6148 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter); 6149 } 6150 // fold (truncate (load x)) -> (smaller load x) 6151 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits)) 6152 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) { 6153 SDValue Reduced = ReduceLoadWidth(N); 6154 if (Reduced.getNode()) 6155 return Reduced; 6156 // Handle the case where the load remains an extending load even 6157 // after truncation. 6158 if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) { 6159 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6160 if (!LN0->isVolatile() && 6161 LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) { 6162 SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0), 6163 VT, LN0->getChain(), LN0->getBasePtr(), 6164 LN0->getMemoryVT(), 6165 LN0->getMemOperand()); 6166 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1)); 6167 return NewLoad; 6168 } 6169 } 6170 } 6171 // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)), 6172 // where ... are all 'undef'. 6173 if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) { 6174 SmallVector<EVT, 8> VTs; 6175 SDValue V; 6176 unsigned Idx = 0; 6177 unsigned NumDefs = 0; 6178 6179 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) { 6180 SDValue X = N0.getOperand(i); 6181 if (X.getOpcode() != ISD::UNDEF) { 6182 V = X; 6183 Idx = i; 6184 NumDefs++; 6185 } 6186 // Stop if more than one members are non-undef. 6187 if (NumDefs > 1) 6188 break; 6189 VTs.push_back(EVT::getVectorVT(*DAG.getContext(), 6190 VT.getVectorElementType(), 6191 X.getValueType().getVectorNumElements())); 6192 } 6193 6194 if (NumDefs == 0) 6195 return DAG.getUNDEF(VT); 6196 6197 if (NumDefs == 1) { 6198 assert(V.getNode() && "The single defined operand is empty!"); 6199 SmallVector<SDValue, 8> Opnds; 6200 for (unsigned i = 0, e = VTs.size(); i != e; ++i) { 6201 if (i != Idx) { 6202 Opnds.push_back(DAG.getUNDEF(VTs[i])); 6203 continue; 6204 } 6205 SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V); 6206 AddToWorklist(NV.getNode()); 6207 Opnds.push_back(NV); 6208 } 6209 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds); 6210 } 6211 } 6212 6213 // Simplify the operands using demanded-bits information. 6214 if (!VT.isVector() && 6215 SimplifyDemandedBits(SDValue(N, 0))) 6216 return SDValue(N, 0); 6217 6218 return SDValue(); 6219 } 6220 6221 static SDNode *getBuildPairElt(SDNode *N, unsigned i) { 6222 SDValue Elt = N->getOperand(i); 6223 if (Elt.getOpcode() != ISD::MERGE_VALUES) 6224 return Elt.getNode(); 6225 return Elt.getOperand(Elt.getResNo()).getNode(); 6226 } 6227 6228 /// build_pair (load, load) -> load 6229 /// if load locations are consecutive. 6230 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) { 6231 assert(N->getOpcode() == ISD::BUILD_PAIR); 6232 6233 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0)); 6234 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1)); 6235 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() || 6236 LD1->getAddressSpace() != LD2->getAddressSpace()) 6237 return SDValue(); 6238 EVT LD1VT = LD1->getValueType(0); 6239 6240 if (ISD::isNON_EXTLoad(LD2) && 6241 LD2->hasOneUse() && 6242 // If both are volatile this would reduce the number of volatile loads. 6243 // If one is volatile it might be ok, but play conservative and bail out. 6244 !LD1->isVolatile() && 6245 !LD2->isVolatile() && 6246 DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) { 6247 unsigned Align = LD1->getAlignment(); 6248 unsigned NewAlign = TLI.getDataLayout()-> 6249 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext())); 6250 6251 if (NewAlign <= Align && 6252 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT))) 6253 return DAG.getLoad(VT, SDLoc(N), LD1->getChain(), 6254 LD1->getBasePtr(), LD1->getPointerInfo(), 6255 false, false, false, Align); 6256 } 6257 6258 return SDValue(); 6259 } 6260 6261 SDValue DAGCombiner::visitBITCAST(SDNode *N) { 6262 SDValue N0 = N->getOperand(0); 6263 EVT VT = N->getValueType(0); 6264 6265 // If the input is a BUILD_VECTOR with all constant elements, fold this now. 6266 // Only do this before legalize, since afterward the target may be depending 6267 // on the bitconvert. 6268 // First check to see if this is all constant. 6269 if (!LegalTypes && 6270 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() && 6271 VT.isVector()) { 6272 bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant(); 6273 6274 EVT DestEltVT = N->getValueType(0).getVectorElementType(); 6275 assert(!DestEltVT.isVector() && 6276 "Element type of vector ValueType must not be vector!"); 6277 if (isSimple) 6278 return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT); 6279 } 6280 6281 // If the input is a constant, let getNode fold it. 6282 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) { 6283 SDValue Res = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0); 6284 if (Res.getNode() != N) { 6285 if (!LegalOperations || 6286 TLI.isOperationLegal(Res.getNode()->getOpcode(), VT)) 6287 return Res; 6288 6289 // Folding it resulted in an illegal node, and it's too late to 6290 // do that. Clean up the old node and forego the transformation. 6291 // Ideally this won't happen very often, because instcombine 6292 // and the earlier dagcombine runs (where illegal nodes are 6293 // permitted) should have folded most of them already. 6294 deleteAndRecombine(Res.getNode()); 6295 } 6296 } 6297 6298 // (conv (conv x, t1), t2) -> (conv x, t2) 6299 if (N0.getOpcode() == ISD::BITCAST) 6300 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, 6301 N0.getOperand(0)); 6302 6303 // fold (conv (load x)) -> (load (conv*)x) 6304 // If the resultant load doesn't need a higher alignment than the original! 6305 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() && 6306 // Do not change the width of a volatile load. 6307 !cast<LoadSDNode>(N0)->isVolatile() && 6308 // Do not remove the cast if the types differ in endian layout. 6309 TLI.hasBigEndianPartOrdering(N0.getValueType()) == 6310 TLI.hasBigEndianPartOrdering(VT) && 6311 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) && 6312 TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) { 6313 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6314 unsigned Align = TLI.getDataLayout()-> 6315 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext())); 6316 unsigned OrigAlign = LN0->getAlignment(); 6317 6318 if (Align <= OrigAlign) { 6319 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(), 6320 LN0->getBasePtr(), LN0->getPointerInfo(), 6321 LN0->isVolatile(), LN0->isNonTemporal(), 6322 LN0->isInvariant(), OrigAlign, 6323 LN0->getAAInfo()); 6324 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1)); 6325 return Load; 6326 } 6327 } 6328 6329 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit) 6330 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit)) 6331 // This often reduces constant pool loads. 6332 if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) || 6333 (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) && 6334 N0.getNode()->hasOneUse() && VT.isInteger() && 6335 !VT.isVector() && !N0.getValueType().isVector()) { 6336 SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT, 6337 N0.getOperand(0)); 6338 AddToWorklist(NewConv.getNode()); 6339 6340 APInt SignBit = APInt::getSignBit(VT.getSizeInBits()); 6341 if (N0.getOpcode() == ISD::FNEG) 6342 return DAG.getNode(ISD::XOR, SDLoc(N), VT, 6343 NewConv, DAG.getConstant(SignBit, VT)); 6344 assert(N0.getOpcode() == ISD::FABS); 6345 return DAG.getNode(ISD::AND, SDLoc(N), VT, 6346 NewConv, DAG.getConstant(~SignBit, VT)); 6347 } 6348 6349 // fold (bitconvert (fcopysign cst, x)) -> 6350 // (or (and (bitconvert x), sign), (and cst, (not sign))) 6351 // Note that we don't handle (copysign x, cst) because this can always be 6352 // folded to an fneg or fabs. 6353 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() && 6354 isa<ConstantFPSDNode>(N0.getOperand(0)) && 6355 VT.isInteger() && !VT.isVector()) { 6356 unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits(); 6357 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth); 6358 if (isTypeLegal(IntXVT)) { 6359 SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0), 6360 IntXVT, N0.getOperand(1)); 6361 AddToWorklist(X.getNode()); 6362 6363 // If X has a different width than the result/lhs, sext it or truncate it. 6364 unsigned VTWidth = VT.getSizeInBits(); 6365 if (OrigXWidth < VTWidth) { 6366 X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X); 6367 AddToWorklist(X.getNode()); 6368 } else if (OrigXWidth > VTWidth) { 6369 // To get the sign bit in the right place, we have to shift it right 6370 // before truncating. 6371 X = DAG.getNode(ISD::SRL, SDLoc(X), 6372 X.getValueType(), X, 6373 DAG.getConstant(OrigXWidth-VTWidth, X.getValueType())); 6374 AddToWorklist(X.getNode()); 6375 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X); 6376 AddToWorklist(X.getNode()); 6377 } 6378 6379 APInt SignBit = APInt::getSignBit(VT.getSizeInBits()); 6380 X = DAG.getNode(ISD::AND, SDLoc(X), VT, 6381 X, DAG.getConstant(SignBit, VT)); 6382 AddToWorklist(X.getNode()); 6383 6384 SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0), 6385 VT, N0.getOperand(0)); 6386 Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT, 6387 Cst, DAG.getConstant(~SignBit, VT)); 6388 AddToWorklist(Cst.getNode()); 6389 6390 return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst); 6391 } 6392 } 6393 6394 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive. 6395 if (N0.getOpcode() == ISD::BUILD_PAIR) { 6396 SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT); 6397 if (CombineLD.getNode()) 6398 return CombineLD; 6399 } 6400 6401 return SDValue(); 6402 } 6403 6404 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) { 6405 EVT VT = N->getValueType(0); 6406 return CombineConsecutiveLoads(N, VT); 6407 } 6408 6409 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef 6410 /// operands. DstEltVT indicates the destination element value type. 6411 SDValue DAGCombiner:: 6412 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) { 6413 EVT SrcEltVT = BV->getValueType(0).getVectorElementType(); 6414 6415 // If this is already the right type, we're done. 6416 if (SrcEltVT == DstEltVT) return SDValue(BV, 0); 6417 6418 unsigned SrcBitSize = SrcEltVT.getSizeInBits(); 6419 unsigned DstBitSize = DstEltVT.getSizeInBits(); 6420 6421 // If this is a conversion of N elements of one type to N elements of another 6422 // type, convert each element. This handles FP<->INT cases. 6423 if (SrcBitSize == DstBitSize) { 6424 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, 6425 BV->getValueType(0).getVectorNumElements()); 6426 6427 // Due to the FP element handling below calling this routine recursively, 6428 // we can end up with a scalar-to-vector node here. 6429 if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR) 6430 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT, 6431 DAG.getNode(ISD::BITCAST, SDLoc(BV), 6432 DstEltVT, BV->getOperand(0))); 6433 6434 SmallVector<SDValue, 8> Ops; 6435 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) { 6436 SDValue Op = BV->getOperand(i); 6437 // If the vector element type is not legal, the BUILD_VECTOR operands 6438 // are promoted and implicitly truncated. Make that explicit here. 6439 if (Op.getValueType() != SrcEltVT) 6440 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op); 6441 Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV), 6442 DstEltVT, Op)); 6443 AddToWorklist(Ops.back().getNode()); 6444 } 6445 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops); 6446 } 6447 6448 // Otherwise, we're growing or shrinking the elements. To avoid having to 6449 // handle annoying details of growing/shrinking FP values, we convert them to 6450 // int first. 6451 if (SrcEltVT.isFloatingPoint()) { 6452 // Convert the input float vector to a int vector where the elements are the 6453 // same sizes. 6454 assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!"); 6455 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits()); 6456 BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode(); 6457 SrcEltVT = IntVT; 6458 } 6459 6460 // Now we know the input is an integer vector. If the output is a FP type, 6461 // convert to integer first, then to FP of the right size. 6462 if (DstEltVT.isFloatingPoint()) { 6463 assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!"); 6464 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits()); 6465 SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode(); 6466 6467 // Next, convert to FP elements of the same size. 6468 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT); 6469 } 6470 6471 // Okay, we know the src/dst types are both integers of differing types. 6472 // Handling growing first. 6473 assert(SrcEltVT.isInteger() && DstEltVT.isInteger()); 6474 if (SrcBitSize < DstBitSize) { 6475 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize; 6476 6477 SmallVector<SDValue, 8> Ops; 6478 for (unsigned i = 0, e = BV->getNumOperands(); i != e; 6479 i += NumInputsPerOutput) { 6480 bool isLE = TLI.isLittleEndian(); 6481 APInt NewBits = APInt(DstBitSize, 0); 6482 bool EltIsUndef = true; 6483 for (unsigned j = 0; j != NumInputsPerOutput; ++j) { 6484 // Shift the previously computed bits over. 6485 NewBits <<= SrcBitSize; 6486 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j)); 6487 if (Op.getOpcode() == ISD::UNDEF) continue; 6488 EltIsUndef = false; 6489 6490 NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue(). 6491 zextOrTrunc(SrcBitSize).zext(DstBitSize); 6492 } 6493 6494 if (EltIsUndef) 6495 Ops.push_back(DAG.getUNDEF(DstEltVT)); 6496 else 6497 Ops.push_back(DAG.getConstant(NewBits, DstEltVT)); 6498 } 6499 6500 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size()); 6501 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops); 6502 } 6503 6504 // Finally, this must be the case where we are shrinking elements: each input 6505 // turns into multiple outputs. 6506 bool isS2V = ISD::isScalarToVector(BV); 6507 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize; 6508 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, 6509 NumOutputsPerInput*BV->getNumOperands()); 6510 SmallVector<SDValue, 8> Ops; 6511 6512 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) { 6513 if (BV->getOperand(i).getOpcode() == ISD::UNDEF) { 6514 for (unsigned j = 0; j != NumOutputsPerInput; ++j) 6515 Ops.push_back(DAG.getUNDEF(DstEltVT)); 6516 continue; 6517 } 6518 6519 APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))-> 6520 getAPIntValue().zextOrTrunc(SrcBitSize); 6521 6522 for (unsigned j = 0; j != NumOutputsPerInput; ++j) { 6523 APInt ThisVal = OpVal.trunc(DstBitSize); 6524 Ops.push_back(DAG.getConstant(ThisVal, DstEltVT)); 6525 if (isS2V && i == 0 && j == 0 && ThisVal.zext(SrcBitSize) == OpVal) 6526 // Simply turn this into a SCALAR_TO_VECTOR of the new type. 6527 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT, 6528 Ops[0]); 6529 OpVal = OpVal.lshr(DstBitSize); 6530 } 6531 6532 // For big endian targets, swap the order of the pieces of each element. 6533 if (TLI.isBigEndian()) 6534 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end()); 6535 } 6536 6537 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops); 6538 } 6539 6540 SDValue DAGCombiner::visitFADD(SDNode *N) { 6541 SDValue N0 = N->getOperand(0); 6542 SDValue N1 = N->getOperand(1); 6543 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 6544 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 6545 EVT VT = N->getValueType(0); 6546 const TargetOptions &Options = DAG.getTarget().Options; 6547 6548 // fold vector ops 6549 if (VT.isVector()) { 6550 SDValue FoldedVOp = SimplifyVBinOp(N); 6551 if (FoldedVOp.getNode()) return FoldedVOp; 6552 } 6553 6554 // fold (fadd c1, c2) -> c1 + c2 6555 if (N0CFP && N1CFP) 6556 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N1); 6557 6558 // canonicalize constant to RHS 6559 if (N0CFP && !N1CFP) 6560 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N0); 6561 6562 // fold (fadd A, (fneg B)) -> (fsub A, B) 6563 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) && 6564 isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2) 6565 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0, 6566 GetNegatedExpression(N1, DAG, LegalOperations)); 6567 6568 // fold (fadd (fneg A), B) -> (fsub B, A) 6569 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) && 6570 isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2) 6571 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N1, 6572 GetNegatedExpression(N0, DAG, LegalOperations)); 6573 6574 // If 'unsafe math' is enabled, fold lots of things. 6575 if (Options.UnsafeFPMath) { 6576 // No FP constant should be created after legalization as Instruction 6577 // Selection pass has a hard time dealing with FP constants. 6578 bool AllowNewConst = (Level < AfterLegalizeDAG); 6579 6580 // fold (fadd A, 0) -> A 6581 if (N1CFP && N1CFP->getValueAPF().isZero()) 6582 return N0; 6583 6584 // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2)) 6585 if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() && 6586 isa<ConstantFPSDNode>(N0.getOperand(1))) 6587 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0.getOperand(0), 6588 DAG.getNode(ISD::FADD, SDLoc(N), VT, 6589 N0.getOperand(1), N1)); 6590 6591 // If allowed, fold (fadd (fneg x), x) -> 0.0 6592 if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1) 6593 return DAG.getConstantFP(0.0, VT); 6594 6595 // If allowed, fold (fadd x, (fneg x)) -> 0.0 6596 if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0) 6597 return DAG.getConstantFP(0.0, VT); 6598 6599 // We can fold chains of FADD's of the same value into multiplications. 6600 // This transform is not safe in general because we are reducing the number 6601 // of rounding steps. 6602 if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) { 6603 if (N0.getOpcode() == ISD::FMUL) { 6604 ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0)); 6605 ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1)); 6606 6607 // (fadd (fmul x, c), x) -> (fmul x, c+1) 6608 if (CFP01 && !CFP00 && N0.getOperand(0) == N1) { 6609 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT, 6610 SDValue(CFP01, 0), 6611 DAG.getConstantFP(1.0, VT)); 6612 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, NewCFP); 6613 } 6614 6615 // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2) 6616 if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD && 6617 N1.getOperand(0) == N1.getOperand(1) && 6618 N0.getOperand(0) == N1.getOperand(0)) { 6619 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT, 6620 SDValue(CFP01, 0), 6621 DAG.getConstantFP(2.0, VT)); 6622 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, 6623 N0.getOperand(0), NewCFP); 6624 } 6625 } 6626 6627 if (N1.getOpcode() == ISD::FMUL) { 6628 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0)); 6629 ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1)); 6630 6631 // (fadd x, (fmul x, c)) -> (fmul x, c+1) 6632 if (CFP11 && !CFP10 && N1.getOperand(0) == N0) { 6633 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT, 6634 SDValue(CFP11, 0), 6635 DAG.getConstantFP(1.0, VT)); 6636 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, NewCFP); 6637 } 6638 6639 // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2) 6640 if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD && 6641 N0.getOperand(0) == N0.getOperand(1) && 6642 N1.getOperand(0) == N0.getOperand(0)) { 6643 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT, 6644 SDValue(CFP11, 0), 6645 DAG.getConstantFP(2.0, VT)); 6646 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1.getOperand(0), NewCFP); 6647 } 6648 } 6649 6650 if (N0.getOpcode() == ISD::FADD && AllowNewConst) { 6651 ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0)); 6652 // (fadd (fadd x, x), x) -> (fmul x, 3.0) 6653 if (!CFP && N0.getOperand(0) == N0.getOperand(1) && 6654 (N0.getOperand(0) == N1)) 6655 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, 6656 N1, DAG.getConstantFP(3.0, VT)); 6657 } 6658 6659 if (N1.getOpcode() == ISD::FADD && AllowNewConst) { 6660 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0)); 6661 // (fadd x, (fadd x, x)) -> (fmul x, 3.0) 6662 if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) && 6663 N1.getOperand(0) == N0) 6664 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, 6665 N0, DAG.getConstantFP(3.0, VT)); 6666 } 6667 6668 // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0) 6669 if (AllowNewConst && 6670 N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD && 6671 N0.getOperand(0) == N0.getOperand(1) && 6672 N1.getOperand(0) == N1.getOperand(1) && 6673 N0.getOperand(0) == N1.getOperand(0)) 6674 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, 6675 N0.getOperand(0), DAG.getConstantFP(4.0, VT)); 6676 } 6677 } // enable-unsafe-fp-math 6678 6679 // FADD -> FMA combines: 6680 if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath) && 6681 DAG.getTarget() 6682 .getSubtargetImpl() 6683 ->getTargetLowering() 6684 ->isFMAFasterThanFMulAndFAdd(VT) && 6685 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) { 6686 6687 // fold (fadd (fmul x, y), z) -> (fma x, y, z) 6688 if (N0.getOpcode() == ISD::FMUL && 6689 (N0->hasOneUse() || TLI.enableAggressiveFMAFusion(VT))) 6690 return DAG.getNode(ISD::FMA, SDLoc(N), VT, 6691 N0.getOperand(0), N0.getOperand(1), N1); 6692 6693 // fold (fadd x, (fmul y, z)) -> (fma y, z, x) 6694 // Note: Commutes FADD operands. 6695 if (N1.getOpcode() == ISD::FMUL && 6696 (N1->hasOneUse() || TLI.enableAggressiveFMAFusion(VT))) 6697 return DAG.getNode(ISD::FMA, SDLoc(N), VT, 6698 N1.getOperand(0), N1.getOperand(1), N0); 6699 } 6700 6701 return SDValue(); 6702 } 6703 6704 SDValue DAGCombiner::visitFSUB(SDNode *N) { 6705 SDValue N0 = N->getOperand(0); 6706 SDValue N1 = N->getOperand(1); 6707 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0); 6708 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1); 6709 EVT VT = N->getValueType(0); 6710 SDLoc dl(N); 6711 const TargetOptions &Options = DAG.getTarget().Options; 6712 6713 // fold vector ops 6714 if (VT.isVector()) { 6715 SDValue FoldedVOp = SimplifyVBinOp(N); 6716 if (FoldedVOp.getNode()) return FoldedVOp; 6717 } 6718 6719 // fold (fsub c1, c2) -> c1-c2 6720 if (N0CFP && N1CFP) 6721 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0, N1); 6722 6723 // fold (fsub A, (fneg B)) -> (fadd A, B) 6724 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options)) 6725 return DAG.getNode(ISD::FADD, dl, VT, N0, 6726 GetNegatedExpression(N1, DAG, LegalOperations)); 6727 6728 // If 'unsafe math' is enabled, fold lots of things. 6729 if (Options.UnsafeFPMath) { 6730 // (fsub A, 0) -> A 6731 if (N1CFP && N1CFP->getValueAPF().isZero()) 6732 return N0; 6733 6734 // (fsub 0, B) -> -B 6735 if (N0CFP && N0CFP->getValueAPF().isZero()) { 6736 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options)) 6737 return GetNegatedExpression(N1, DAG, LegalOperations); 6738 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT)) 6739 return DAG.getNode(ISD::FNEG, dl, VT, N1); 6740 } 6741 6742 // (fsub x, x) -> 0.0 6743 if (N0 == N1) 6744 return DAG.getConstantFP(0.0f, VT); 6745 6746 // (fsub x, (fadd x, y)) -> (fneg y) 6747 // (fsub x, (fadd y, x)) -> (fneg y) 6748 if (N1.getOpcode() == ISD::FADD) { 6749 SDValue N10 = N1->getOperand(0); 6750 SDValue N11 = N1->getOperand(1); 6751 6752 if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options)) 6753 return GetNegatedExpression(N11, DAG, LegalOperations); 6754 6755 if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options)) 6756 return GetNegatedExpression(N10, DAG, LegalOperations); 6757 } 6758 } 6759 6760 // FSUB -> FMA combines: 6761 if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath) && 6762 DAG.getTarget().getSubtargetImpl() 6763 ->getTargetLowering() 6764 ->isFMAFasterThanFMulAndFAdd(VT) && 6765 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) { 6766 6767 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z)) 6768 if (N0.getOpcode() == ISD::FMUL && 6769 (N0->hasOneUse() || TLI.enableAggressiveFMAFusion(VT))) 6770 return DAG.getNode(ISD::FMA, dl, VT, 6771 N0.getOperand(0), N0.getOperand(1), 6772 DAG.getNode(ISD::FNEG, dl, VT, N1)); 6773 6774 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x) 6775 // Note: Commutes FSUB operands. 6776 if (N1.getOpcode() == ISD::FMUL && 6777 (N1->hasOneUse() || TLI.enableAggressiveFMAFusion(VT))) 6778 return DAG.getNode(ISD::FMA, dl, VT, 6779 DAG.getNode(ISD::FNEG, dl, VT, 6780 N1.getOperand(0)), 6781 N1.getOperand(1), N0); 6782 6783 // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z)) 6784 if (N0.getOpcode() == ISD::FNEG && 6785 N0.getOperand(0).getOpcode() == ISD::FMUL && 6786 ((N0->hasOneUse() && N0.getOperand(0).hasOneUse()) || 6787 TLI.enableAggressiveFMAFusion(VT))) { 6788 SDValue N00 = N0.getOperand(0).getOperand(0); 6789 SDValue N01 = N0.getOperand(0).getOperand(1); 6790 return DAG.getNode(ISD::FMA, dl, VT, 6791 DAG.getNode(ISD::FNEG, dl, VT, N00), N01, 6792 DAG.getNode(ISD::FNEG, dl, VT, N1)); 6793 } 6794 } 6795 6796 return SDValue(); 6797 } 6798 6799 SDValue DAGCombiner::visitFMUL(SDNode *N) { 6800 SDValue N0 = N->getOperand(0); 6801 SDValue N1 = N->getOperand(1); 6802 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0); 6803 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1); 6804 EVT VT = N->getValueType(0); 6805 const TargetOptions &Options = DAG.getTarget().Options; 6806 6807 // fold vector ops 6808 if (VT.isVector()) { 6809 // This just handles C1 * C2 for vectors. Other vector folds are below. 6810 SDValue FoldedVOp = SimplifyVBinOp(N); 6811 if (FoldedVOp.getNode()) 6812 return FoldedVOp; 6813 // Canonicalize vector constant to RHS. 6814 if (N0.getOpcode() == ISD::BUILD_VECTOR && 6815 N1.getOpcode() != ISD::BUILD_VECTOR) 6816 if (auto *BV0 = dyn_cast<BuildVectorSDNode>(N0)) 6817 if (BV0->isConstant()) 6818 return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N1, N0); 6819 } 6820 6821 // fold (fmul c1, c2) -> c1*c2 6822 if (N0CFP && N1CFP) 6823 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, N1); 6824 6825 // canonicalize constant to RHS 6826 if (N0CFP && !N1CFP) 6827 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, N0); 6828 6829 // fold (fmul A, 1.0) -> A 6830 if (N1CFP && N1CFP->isExactlyValue(1.0)) 6831 return N0; 6832 6833 if (Options.UnsafeFPMath) { 6834 // fold (fmul A, 0) -> 0 6835 if (N1CFP && N1CFP->getValueAPF().isZero()) 6836 return N1; 6837 6838 // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2)) 6839 if (N0.getOpcode() == ISD::FMUL) { 6840 // Fold scalars or any vector constants (not just splats). 6841 // This fold is done in general by InstCombine, but extra fmul insts 6842 // may have been generated during lowering. 6843 SDValue N01 = N0.getOperand(1); 6844 auto *BV1 = dyn_cast<BuildVectorSDNode>(N1); 6845 auto *BV01 = dyn_cast<BuildVectorSDNode>(N01); 6846 if ((N1CFP && isConstOrConstSplatFP(N01)) || 6847 (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) { 6848 SDLoc SL(N); 6849 SDValue MulConsts = DAG.getNode(ISD::FMUL, SL, VT, N01, N1); 6850 return DAG.getNode(ISD::FMUL, SL, VT, N0.getOperand(0), MulConsts); 6851 } 6852 } 6853 6854 // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c)) 6855 // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs 6856 // during an early run of DAGCombiner can prevent folding with fmuls 6857 // inserted during lowering. 6858 if (N0.getOpcode() == ISD::FADD && N0.getOperand(0) == N0.getOperand(1)) { 6859 SDLoc SL(N); 6860 const SDValue Two = DAG.getConstantFP(2.0, VT); 6861 SDValue MulConsts = DAG.getNode(ISD::FMUL, SL, VT, Two, N1); 6862 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0), MulConsts); 6863 } 6864 } 6865 6866 // fold (fmul X, 2.0) -> (fadd X, X) 6867 if (N1CFP && N1CFP->isExactlyValue(+2.0)) 6868 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N0); 6869 6870 // fold (fmul X, -1.0) -> (fneg X) 6871 if (N1CFP && N1CFP->isExactlyValue(-1.0)) 6872 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT)) 6873 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0); 6874 6875 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y) 6876 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) { 6877 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) { 6878 // Both can be negated for free, check to see if at least one is cheaper 6879 // negated. 6880 if (LHSNeg == 2 || RHSNeg == 2) 6881 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, 6882 GetNegatedExpression(N0, DAG, LegalOperations), 6883 GetNegatedExpression(N1, DAG, LegalOperations)); 6884 } 6885 } 6886 6887 return SDValue(); 6888 } 6889 6890 SDValue DAGCombiner::visitFMA(SDNode *N) { 6891 SDValue N0 = N->getOperand(0); 6892 SDValue N1 = N->getOperand(1); 6893 SDValue N2 = N->getOperand(2); 6894 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 6895 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 6896 EVT VT = N->getValueType(0); 6897 SDLoc dl(N); 6898 const TargetOptions &Options = DAG.getTarget().Options; 6899 6900 // Constant fold FMA. 6901 if (isa<ConstantFPSDNode>(N0) && 6902 isa<ConstantFPSDNode>(N1) && 6903 isa<ConstantFPSDNode>(N2)) { 6904 return DAG.getNode(ISD::FMA, dl, VT, N0, N1, N2); 6905 } 6906 6907 if (Options.UnsafeFPMath) { 6908 if (N0CFP && N0CFP->isZero()) 6909 return N2; 6910 if (N1CFP && N1CFP->isZero()) 6911 return N2; 6912 } 6913 if (N0CFP && N0CFP->isExactlyValue(1.0)) 6914 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2); 6915 if (N1CFP && N1CFP->isExactlyValue(1.0)) 6916 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2); 6917 6918 // Canonicalize (fma c, x, y) -> (fma x, c, y) 6919 if (N0CFP && !N1CFP) 6920 return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2); 6921 6922 // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2) 6923 if (Options.UnsafeFPMath && N1CFP && 6924 N2.getOpcode() == ISD::FMUL && 6925 N0 == N2.getOperand(0) && 6926 N2.getOperand(1).getOpcode() == ISD::ConstantFP) { 6927 return DAG.getNode(ISD::FMUL, dl, VT, N0, 6928 DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1))); 6929 } 6930 6931 6932 // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y) 6933 if (Options.UnsafeFPMath && 6934 N0.getOpcode() == ISD::FMUL && N1CFP && 6935 N0.getOperand(1).getOpcode() == ISD::ConstantFP) { 6936 return DAG.getNode(ISD::FMA, dl, VT, 6937 N0.getOperand(0), 6938 DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)), 6939 N2); 6940 } 6941 6942 // (fma x, 1, y) -> (fadd x, y) 6943 // (fma x, -1, y) -> (fadd (fneg x), y) 6944 if (N1CFP) { 6945 if (N1CFP->isExactlyValue(1.0)) 6946 return DAG.getNode(ISD::FADD, dl, VT, N0, N2); 6947 6948 if (N1CFP->isExactlyValue(-1.0) && 6949 (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) { 6950 SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0); 6951 AddToWorklist(RHSNeg.getNode()); 6952 return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg); 6953 } 6954 } 6955 6956 // (fma x, c, x) -> (fmul x, (c+1)) 6957 if (Options.UnsafeFPMath && N1CFP && N0 == N2) 6958 return DAG.getNode(ISD::FMUL, dl, VT, N0, 6959 DAG.getNode(ISD::FADD, dl, VT, 6960 N1, DAG.getConstantFP(1.0, VT))); 6961 6962 // (fma x, c, (fneg x)) -> (fmul x, (c-1)) 6963 if (Options.UnsafeFPMath && N1CFP && 6964 N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0) 6965 return DAG.getNode(ISD::FMUL, dl, VT, N0, 6966 DAG.getNode(ISD::FADD, dl, VT, 6967 N1, DAG.getConstantFP(-1.0, VT))); 6968 6969 6970 return SDValue(); 6971 } 6972 6973 SDValue DAGCombiner::visitFDIV(SDNode *N) { 6974 SDValue N0 = N->getOperand(0); 6975 SDValue N1 = N->getOperand(1); 6976 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 6977 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 6978 EVT VT = N->getValueType(0); 6979 const TargetOptions &Options = DAG.getTarget().Options; 6980 6981 // fold vector ops 6982 if (VT.isVector()) { 6983 SDValue FoldedVOp = SimplifyVBinOp(N); 6984 if (FoldedVOp.getNode()) return FoldedVOp; 6985 } 6986 6987 // fold (fdiv c1, c2) -> c1/c2 6988 if (N0CFP && N1CFP) 6989 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1); 6990 6991 if (Options.UnsafeFPMath) { 6992 // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable. 6993 if (N1CFP) { 6994 // Compute the reciprocal 1.0 / c2. 6995 APFloat N1APF = N1CFP->getValueAPF(); 6996 APFloat Recip(N1APF.getSemantics(), 1); // 1.0 6997 APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven); 6998 // Only do the transform if the reciprocal is a legal fp immediate that 6999 // isn't too nasty (eg NaN, denormal, ...). 7000 if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty 7001 (!LegalOperations || 7002 // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM 7003 // backend)... we should handle this gracefully after Legalize. 7004 // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) || 7005 TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) || 7006 TLI.isFPImmLegal(Recip, VT))) 7007 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, 7008 DAG.getConstantFP(Recip, VT)); 7009 } 7010 // If this FDIV is part of a reciprocal square root, it may be folded 7011 // into a target-specific square root estimate instruction. 7012 if (SDValue SqrtOp = BuildRSQRTE(N)) 7013 return SqrtOp; 7014 } 7015 7016 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y) 7017 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) { 7018 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) { 7019 // Both can be negated for free, check to see if at least one is cheaper 7020 // negated. 7021 if (LHSNeg == 2 || RHSNeg == 2) 7022 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, 7023 GetNegatedExpression(N0, DAG, LegalOperations), 7024 GetNegatedExpression(N1, DAG, LegalOperations)); 7025 } 7026 } 7027 7028 return SDValue(); 7029 } 7030 7031 SDValue DAGCombiner::visitFREM(SDNode *N) { 7032 SDValue N0 = N->getOperand(0); 7033 SDValue N1 = N->getOperand(1); 7034 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 7035 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 7036 EVT VT = N->getValueType(0); 7037 7038 // fold (frem c1, c2) -> fmod(c1,c2) 7039 if (N0CFP && N1CFP) 7040 return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1); 7041 7042 return SDValue(); 7043 } 7044 7045 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) { 7046 SDValue N0 = N->getOperand(0); 7047 SDValue N1 = N->getOperand(1); 7048 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 7049 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 7050 EVT VT = N->getValueType(0); 7051 7052 if (N0CFP && N1CFP) // Constant fold 7053 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1); 7054 7055 if (N1CFP) { 7056 const APFloat& V = N1CFP->getValueAPF(); 7057 // copysign(x, c1) -> fabs(x) iff ispos(c1) 7058 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1) 7059 if (!V.isNegative()) { 7060 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT)) 7061 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0); 7062 } else { 7063 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT)) 7064 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, 7065 DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0)); 7066 } 7067 } 7068 7069 // copysign(fabs(x), y) -> copysign(x, y) 7070 // copysign(fneg(x), y) -> copysign(x, y) 7071 // copysign(copysign(x,z), y) -> copysign(x, y) 7072 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG || 7073 N0.getOpcode() == ISD::FCOPYSIGN) 7074 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, 7075 N0.getOperand(0), N1); 7076 7077 // copysign(x, abs(y)) -> abs(x) 7078 if (N1.getOpcode() == ISD::FABS) 7079 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0); 7080 7081 // copysign(x, copysign(y,z)) -> copysign(x, z) 7082 if (N1.getOpcode() == ISD::FCOPYSIGN) 7083 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, 7084 N0, N1.getOperand(1)); 7085 7086 // copysign(x, fp_extend(y)) -> copysign(x, y) 7087 // copysign(x, fp_round(y)) -> copysign(x, y) 7088 if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND) 7089 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, 7090 N0, N1.getOperand(0)); 7091 7092 return SDValue(); 7093 } 7094 7095 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) { 7096 SDValue N0 = N->getOperand(0); 7097 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 7098 EVT VT = N->getValueType(0); 7099 EVT OpVT = N0.getValueType(); 7100 7101 // fold (sint_to_fp c1) -> c1fp 7102 if (N0C && 7103 // ...but only if the target supports immediate floating-point values 7104 (!LegalOperations || 7105 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) 7106 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0); 7107 7108 // If the input is a legal type, and SINT_TO_FP is not legal on this target, 7109 // but UINT_TO_FP is legal on this target, try to convert. 7110 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) && 7111 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) { 7112 // If the sign bit is known to be zero, we can change this to UINT_TO_FP. 7113 if (DAG.SignBitIsZero(N0)) 7114 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0); 7115 } 7116 7117 // The next optimizations are desirable only if SELECT_CC can be lowered. 7118 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) { 7119 // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc) 7120 if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 && 7121 !VT.isVector() && 7122 (!LegalOperations || 7123 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) { 7124 SDValue Ops[] = 7125 { N0.getOperand(0), N0.getOperand(1), 7126 DAG.getConstantFP(-1.0, VT) , DAG.getConstantFP(0.0, VT), 7127 N0.getOperand(2) }; 7128 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops); 7129 } 7130 7131 // fold (sint_to_fp (zext (setcc x, y, cc))) -> 7132 // (select_cc x, y, 1.0, 0.0,, cc) 7133 if (N0.getOpcode() == ISD::ZERO_EXTEND && 7134 N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() && 7135 (!LegalOperations || 7136 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) { 7137 SDValue Ops[] = 7138 { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1), 7139 DAG.getConstantFP(1.0, VT) , DAG.getConstantFP(0.0, VT), 7140 N0.getOperand(0).getOperand(2) }; 7141 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops); 7142 } 7143 } 7144 7145 return SDValue(); 7146 } 7147 7148 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) { 7149 SDValue N0 = N->getOperand(0); 7150 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 7151 EVT VT = N->getValueType(0); 7152 EVT OpVT = N0.getValueType(); 7153 7154 // fold (uint_to_fp c1) -> c1fp 7155 if (N0C && 7156 // ...but only if the target supports immediate floating-point values 7157 (!LegalOperations || 7158 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) 7159 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0); 7160 7161 // If the input is a legal type, and UINT_TO_FP is not legal on this target, 7162 // but SINT_TO_FP is legal on this target, try to convert. 7163 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) && 7164 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) { 7165 // If the sign bit is known to be zero, we can change this to SINT_TO_FP. 7166 if (DAG.SignBitIsZero(N0)) 7167 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0); 7168 } 7169 7170 // The next optimizations are desirable only if SELECT_CC can be lowered. 7171 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) { 7172 // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc) 7173 7174 if (N0.getOpcode() == ISD::SETCC && !VT.isVector() && 7175 (!LegalOperations || 7176 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) { 7177 SDValue Ops[] = 7178 { N0.getOperand(0), N0.getOperand(1), 7179 DAG.getConstantFP(1.0, VT), DAG.getConstantFP(0.0, VT), 7180 N0.getOperand(2) }; 7181 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops); 7182 } 7183 } 7184 7185 return SDValue(); 7186 } 7187 7188 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) { 7189 SDValue N0 = N->getOperand(0); 7190 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 7191 EVT VT = N->getValueType(0); 7192 7193 // fold (fp_to_sint c1fp) -> c1 7194 if (N0CFP) 7195 return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0); 7196 7197 return SDValue(); 7198 } 7199 7200 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) { 7201 SDValue N0 = N->getOperand(0); 7202 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 7203 EVT VT = N->getValueType(0); 7204 7205 // fold (fp_to_uint c1fp) -> c1 7206 if (N0CFP) 7207 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0); 7208 7209 return SDValue(); 7210 } 7211 7212 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) { 7213 SDValue N0 = N->getOperand(0); 7214 SDValue N1 = N->getOperand(1); 7215 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 7216 EVT VT = N->getValueType(0); 7217 7218 // fold (fp_round c1fp) -> c1fp 7219 if (N0CFP) 7220 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1); 7221 7222 // fold (fp_round (fp_extend x)) -> x 7223 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType()) 7224 return N0.getOperand(0); 7225 7226 // fold (fp_round (fp_round x)) -> (fp_round x) 7227 if (N0.getOpcode() == ISD::FP_ROUND) { 7228 // This is a value preserving truncation if both round's are. 7229 bool IsTrunc = N->getConstantOperandVal(1) == 1 && 7230 N0.getNode()->getConstantOperandVal(1) == 1; 7231 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0.getOperand(0), 7232 DAG.getIntPtrConstant(IsTrunc)); 7233 } 7234 7235 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y) 7236 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) { 7237 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT, 7238 N0.getOperand(0), N1); 7239 AddToWorklist(Tmp.getNode()); 7240 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, 7241 Tmp, N0.getOperand(1)); 7242 } 7243 7244 return SDValue(); 7245 } 7246 7247 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) { 7248 SDValue N0 = N->getOperand(0); 7249 EVT VT = N->getValueType(0); 7250 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT(); 7251 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 7252 7253 // fold (fp_round_inreg c1fp) -> c1fp 7254 if (N0CFP && isTypeLegal(EVT)) { 7255 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT); 7256 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, Round); 7257 } 7258 7259 return SDValue(); 7260 } 7261 7262 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) { 7263 SDValue N0 = N->getOperand(0); 7264 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 7265 EVT VT = N->getValueType(0); 7266 7267 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded. 7268 if (N->hasOneUse() && 7269 N->use_begin()->getOpcode() == ISD::FP_ROUND) 7270 return SDValue(); 7271 7272 // fold (fp_extend c1fp) -> c1fp 7273 if (N0CFP) 7274 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0); 7275 7276 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the 7277 // value of X. 7278 if (N0.getOpcode() == ISD::FP_ROUND 7279 && N0.getNode()->getConstantOperandVal(1) == 1) { 7280 SDValue In = N0.getOperand(0); 7281 if (In.getValueType() == VT) return In; 7282 if (VT.bitsLT(In.getValueType())) 7283 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, 7284 In, N0.getOperand(1)); 7285 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In); 7286 } 7287 7288 // fold (fpext (load x)) -> (fpext (fptrunc (extload x))) 7289 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() && 7290 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType())) { 7291 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 7292 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT, 7293 LN0->getChain(), 7294 LN0->getBasePtr(), N0.getValueType(), 7295 LN0->getMemOperand()); 7296 CombineTo(N, ExtLoad); 7297 CombineTo(N0.getNode(), 7298 DAG.getNode(ISD::FP_ROUND, SDLoc(N0), 7299 N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)), 7300 ExtLoad.getValue(1)); 7301 return SDValue(N, 0); // Return N so it doesn't get rechecked! 7302 } 7303 7304 return SDValue(); 7305 } 7306 7307 SDValue DAGCombiner::visitFCEIL(SDNode *N) { 7308 SDValue N0 = N->getOperand(0); 7309 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 7310 EVT VT = N->getValueType(0); 7311 7312 // fold (fceil c1) -> fceil(c1) 7313 if (N0CFP) 7314 return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0); 7315 7316 return SDValue(); 7317 } 7318 7319 SDValue DAGCombiner::visitFTRUNC(SDNode *N) { 7320 SDValue N0 = N->getOperand(0); 7321 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 7322 EVT VT = N->getValueType(0); 7323 7324 // fold (ftrunc c1) -> ftrunc(c1) 7325 if (N0CFP) 7326 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0); 7327 7328 return SDValue(); 7329 } 7330 7331 SDValue DAGCombiner::visitFFLOOR(SDNode *N) { 7332 SDValue N0 = N->getOperand(0); 7333 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 7334 EVT VT = N->getValueType(0); 7335 7336 // fold (ffloor c1) -> ffloor(c1) 7337 if (N0CFP) 7338 return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0); 7339 7340 return SDValue(); 7341 } 7342 7343 // FIXME: FNEG and FABS have a lot in common; refactor. 7344 SDValue DAGCombiner::visitFNEG(SDNode *N) { 7345 SDValue N0 = N->getOperand(0); 7346 EVT VT = N->getValueType(0); 7347 7348 if (VT.isVector()) { 7349 SDValue FoldedVOp = SimplifyVUnaryOp(N); 7350 if (FoldedVOp.getNode()) return FoldedVOp; 7351 } 7352 7353 // Constant fold FNEG. 7354 if (isa<ConstantFPSDNode>(N0)) 7355 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N->getOperand(0)); 7356 7357 if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(), 7358 &DAG.getTarget().Options)) 7359 return GetNegatedExpression(N0, DAG, LegalOperations); 7360 7361 // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading 7362 // constant pool values. 7363 if (!TLI.isFNegFree(VT) && 7364 N0.getOpcode() == ISD::BITCAST && 7365 N0.getNode()->hasOneUse()) { 7366 SDValue Int = N0.getOperand(0); 7367 EVT IntVT = Int.getValueType(); 7368 if (IntVT.isInteger() && !IntVT.isVector()) { 7369 APInt SignMask; 7370 if (N0.getValueType().isVector()) { 7371 // For a vector, get a mask such as 0x80... per scalar element 7372 // and splat it. 7373 SignMask = APInt::getSignBit(N0.getValueType().getScalarSizeInBits()); 7374 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask); 7375 } else { 7376 // For a scalar, just generate 0x80... 7377 SignMask = APInt::getSignBit(IntVT.getSizeInBits()); 7378 } 7379 Int = DAG.getNode(ISD::XOR, SDLoc(N0), IntVT, Int, 7380 DAG.getConstant(SignMask, IntVT)); 7381 AddToWorklist(Int.getNode()); 7382 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Int); 7383 } 7384 } 7385 7386 // (fneg (fmul c, x)) -> (fmul -c, x) 7387 if (N0.getOpcode() == ISD::FMUL) { 7388 ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1)); 7389 if (CFP1) { 7390 APFloat CVal = CFP1->getValueAPF(); 7391 CVal.changeSign(); 7392 if (Level >= AfterLegalizeDAG && 7393 (TLI.isFPImmLegal(CVal, N->getValueType(0)) || 7394 TLI.isOperationLegal(ISD::ConstantFP, N->getValueType(0)))) 7395 return DAG.getNode( 7396 ISD::FMUL, SDLoc(N), VT, N0.getOperand(0), 7397 DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0.getOperand(1))); 7398 } 7399 } 7400 7401 return SDValue(); 7402 } 7403 7404 SDValue DAGCombiner::visitFABS(SDNode *N) { 7405 SDValue N0 = N->getOperand(0); 7406 EVT VT = N->getValueType(0); 7407 7408 if (VT.isVector()) { 7409 SDValue FoldedVOp = SimplifyVUnaryOp(N); 7410 if (FoldedVOp.getNode()) return FoldedVOp; 7411 } 7412 7413 // fold (fabs c1) -> fabs(c1) 7414 if (isa<ConstantFPSDNode>(N0)) 7415 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0); 7416 7417 // fold (fabs (fabs x)) -> (fabs x) 7418 if (N0.getOpcode() == ISD::FABS) 7419 return N->getOperand(0); 7420 7421 // fold (fabs (fneg x)) -> (fabs x) 7422 // fold (fabs (fcopysign x, y)) -> (fabs x) 7423 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN) 7424 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0)); 7425 7426 // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading 7427 // constant pool values. 7428 if (!TLI.isFAbsFree(VT) && 7429 N0.getOpcode() == ISD::BITCAST && 7430 N0.getNode()->hasOneUse()) { 7431 SDValue Int = N0.getOperand(0); 7432 EVT IntVT = Int.getValueType(); 7433 if (IntVT.isInteger() && !IntVT.isVector()) { 7434 APInt SignMask; 7435 if (N0.getValueType().isVector()) { 7436 // For a vector, get a mask such as 0x7f... per scalar element 7437 // and splat it. 7438 SignMask = ~APInt::getSignBit(N0.getValueType().getScalarSizeInBits()); 7439 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask); 7440 } else { 7441 // For a scalar, just generate 0x7f... 7442 SignMask = ~APInt::getSignBit(IntVT.getSizeInBits()); 7443 } 7444 Int = DAG.getNode(ISD::AND, SDLoc(N0), IntVT, Int, 7445 DAG.getConstant(SignMask, IntVT)); 7446 AddToWorklist(Int.getNode()); 7447 return DAG.getNode(ISD::BITCAST, SDLoc(N), N->getValueType(0), Int); 7448 } 7449 } 7450 7451 return SDValue(); 7452 } 7453 7454 SDValue DAGCombiner::visitBRCOND(SDNode *N) { 7455 SDValue Chain = N->getOperand(0); 7456 SDValue N1 = N->getOperand(1); 7457 SDValue N2 = N->getOperand(2); 7458 7459 // If N is a constant we could fold this into a fallthrough or unconditional 7460 // branch. However that doesn't happen very often in normal code, because 7461 // Instcombine/SimplifyCFG should have handled the available opportunities. 7462 // If we did this folding here, it would be necessary to update the 7463 // MachineBasicBlock CFG, which is awkward. 7464 7465 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal 7466 // on the target. 7467 if (N1.getOpcode() == ISD::SETCC && 7468 TLI.isOperationLegalOrCustom(ISD::BR_CC, 7469 N1.getOperand(0).getValueType())) { 7470 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other, 7471 Chain, N1.getOperand(2), 7472 N1.getOperand(0), N1.getOperand(1), N2); 7473 } 7474 7475 if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) || 7476 ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) && 7477 (N1.getOperand(0).hasOneUse() && 7478 N1.getOperand(0).getOpcode() == ISD::SRL))) { 7479 SDNode *Trunc = nullptr; 7480 if (N1.getOpcode() == ISD::TRUNCATE) { 7481 // Look pass the truncate. 7482 Trunc = N1.getNode(); 7483 N1 = N1.getOperand(0); 7484 } 7485 7486 // Match this pattern so that we can generate simpler code: 7487 // 7488 // %a = ... 7489 // %b = and i32 %a, 2 7490 // %c = srl i32 %b, 1 7491 // brcond i32 %c ... 7492 // 7493 // into 7494 // 7495 // %a = ... 7496 // %b = and i32 %a, 2 7497 // %c = setcc eq %b, 0 7498 // brcond %c ... 7499 // 7500 // This applies only when the AND constant value has one bit set and the 7501 // SRL constant is equal to the log2 of the AND constant. The back-end is 7502 // smart enough to convert the result into a TEST/JMP sequence. 7503 SDValue Op0 = N1.getOperand(0); 7504 SDValue Op1 = N1.getOperand(1); 7505 7506 if (Op0.getOpcode() == ISD::AND && 7507 Op1.getOpcode() == ISD::Constant) { 7508 SDValue AndOp1 = Op0.getOperand(1); 7509 7510 if (AndOp1.getOpcode() == ISD::Constant) { 7511 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue(); 7512 7513 if (AndConst.isPowerOf2() && 7514 cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) { 7515 SDValue SetCC = 7516 DAG.getSetCC(SDLoc(N), 7517 getSetCCResultType(Op0.getValueType()), 7518 Op0, DAG.getConstant(0, Op0.getValueType()), 7519 ISD::SETNE); 7520 7521 SDValue NewBRCond = DAG.getNode(ISD::BRCOND, SDLoc(N), 7522 MVT::Other, Chain, SetCC, N2); 7523 // Don't add the new BRCond into the worklist or else SimplifySelectCC 7524 // will convert it back to (X & C1) >> C2. 7525 CombineTo(N, NewBRCond, false); 7526 // Truncate is dead. 7527 if (Trunc) 7528 deleteAndRecombine(Trunc); 7529 // Replace the uses of SRL with SETCC 7530 WorklistRemover DeadNodes(*this); 7531 DAG.ReplaceAllUsesOfValueWith(N1, SetCC); 7532 deleteAndRecombine(N1.getNode()); 7533 return SDValue(N, 0); // Return N so it doesn't get rechecked! 7534 } 7535 } 7536 } 7537 7538 if (Trunc) 7539 // Restore N1 if the above transformation doesn't match. 7540 N1 = N->getOperand(1); 7541 } 7542 7543 // Transform br(xor(x, y)) -> br(x != y) 7544 // Transform br(xor(xor(x,y), 1)) -> br (x == y) 7545 if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) { 7546 SDNode *TheXor = N1.getNode(); 7547 SDValue Op0 = TheXor->getOperand(0); 7548 SDValue Op1 = TheXor->getOperand(1); 7549 if (Op0.getOpcode() == Op1.getOpcode()) { 7550 // Avoid missing important xor optimizations. 7551 SDValue Tmp = visitXOR(TheXor); 7552 if (Tmp.getNode()) { 7553 if (Tmp.getNode() != TheXor) { 7554 DEBUG(dbgs() << "\nReplacing.8 "; 7555 TheXor->dump(&DAG); 7556 dbgs() << "\nWith: "; 7557 Tmp.getNode()->dump(&DAG); 7558 dbgs() << '\n'); 7559 WorklistRemover DeadNodes(*this); 7560 DAG.ReplaceAllUsesOfValueWith(N1, Tmp); 7561 deleteAndRecombine(TheXor); 7562 return DAG.getNode(ISD::BRCOND, SDLoc(N), 7563 MVT::Other, Chain, Tmp, N2); 7564 } 7565 7566 // visitXOR has changed XOR's operands or replaced the XOR completely, 7567 // bail out. 7568 return SDValue(N, 0); 7569 } 7570 } 7571 7572 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) { 7573 bool Equal = false; 7574 if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0)) 7575 if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() && 7576 Op0.getOpcode() == ISD::XOR) { 7577 TheXor = Op0.getNode(); 7578 Equal = true; 7579 } 7580 7581 EVT SetCCVT = N1.getValueType(); 7582 if (LegalTypes) 7583 SetCCVT = getSetCCResultType(SetCCVT); 7584 SDValue SetCC = DAG.getSetCC(SDLoc(TheXor), 7585 SetCCVT, 7586 Op0, Op1, 7587 Equal ? ISD::SETEQ : ISD::SETNE); 7588 // Replace the uses of XOR with SETCC 7589 WorklistRemover DeadNodes(*this); 7590 DAG.ReplaceAllUsesOfValueWith(N1, SetCC); 7591 deleteAndRecombine(N1.getNode()); 7592 return DAG.getNode(ISD::BRCOND, SDLoc(N), 7593 MVT::Other, Chain, SetCC, N2); 7594 } 7595 } 7596 7597 return SDValue(); 7598 } 7599 7600 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB. 7601 // 7602 SDValue DAGCombiner::visitBR_CC(SDNode *N) { 7603 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1)); 7604 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3); 7605 7606 // If N is a constant we could fold this into a fallthrough or unconditional 7607 // branch. However that doesn't happen very often in normal code, because 7608 // Instcombine/SimplifyCFG should have handled the available opportunities. 7609 // If we did this folding here, it would be necessary to update the 7610 // MachineBasicBlock CFG, which is awkward. 7611 7612 // Use SimplifySetCC to simplify SETCC's. 7613 SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()), 7614 CondLHS, CondRHS, CC->get(), SDLoc(N), 7615 false); 7616 if (Simp.getNode()) AddToWorklist(Simp.getNode()); 7617 7618 // fold to a simpler setcc 7619 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC) 7620 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other, 7621 N->getOperand(0), Simp.getOperand(2), 7622 Simp.getOperand(0), Simp.getOperand(1), 7623 N->getOperand(4)); 7624 7625 return SDValue(); 7626 } 7627 7628 /// Return true if 'Use' is a load or a store that uses N as its base pointer 7629 /// and that N may be folded in the load / store addressing mode. 7630 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use, 7631 SelectionDAG &DAG, 7632 const TargetLowering &TLI) { 7633 EVT VT; 7634 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) { 7635 if (LD->isIndexed() || LD->getBasePtr().getNode() != N) 7636 return false; 7637 VT = Use->getValueType(0); 7638 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) { 7639 if (ST->isIndexed() || ST->getBasePtr().getNode() != N) 7640 return false; 7641 VT = ST->getValue().getValueType(); 7642 } else 7643 return false; 7644 7645 TargetLowering::AddrMode AM; 7646 if (N->getOpcode() == ISD::ADD) { 7647 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1)); 7648 if (Offset) 7649 // [reg +/- imm] 7650 AM.BaseOffs = Offset->getSExtValue(); 7651 else 7652 // [reg +/- reg] 7653 AM.Scale = 1; 7654 } else if (N->getOpcode() == ISD::SUB) { 7655 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1)); 7656 if (Offset) 7657 // [reg +/- imm] 7658 AM.BaseOffs = -Offset->getSExtValue(); 7659 else 7660 // [reg +/- reg] 7661 AM.Scale = 1; 7662 } else 7663 return false; 7664 7665 return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext())); 7666 } 7667 7668 /// Try turning a load/store into a pre-indexed load/store when the base 7669 /// pointer is an add or subtract and it has other uses besides the load/store. 7670 /// After the transformation, the new indexed load/store has effectively folded 7671 /// the add/subtract in and all of its other uses are redirected to the 7672 /// new load/store. 7673 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) { 7674 if (Level < AfterLegalizeDAG) 7675 return false; 7676 7677 bool isLoad = true; 7678 SDValue Ptr; 7679 EVT VT; 7680 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 7681 if (LD->isIndexed()) 7682 return false; 7683 VT = LD->getMemoryVT(); 7684 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) && 7685 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT)) 7686 return false; 7687 Ptr = LD->getBasePtr(); 7688 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 7689 if (ST->isIndexed()) 7690 return false; 7691 VT = ST->getMemoryVT(); 7692 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) && 7693 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT)) 7694 return false; 7695 Ptr = ST->getBasePtr(); 7696 isLoad = false; 7697 } else { 7698 return false; 7699 } 7700 7701 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail 7702 // out. There is no reason to make this a preinc/predec. 7703 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) || 7704 Ptr.getNode()->hasOneUse()) 7705 return false; 7706 7707 // Ask the target to do addressing mode selection. 7708 SDValue BasePtr; 7709 SDValue Offset; 7710 ISD::MemIndexedMode AM = ISD::UNINDEXED; 7711 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG)) 7712 return false; 7713 7714 // Backends without true r+i pre-indexed forms may need to pass a 7715 // constant base with a variable offset so that constant coercion 7716 // will work with the patterns in canonical form. 7717 bool Swapped = false; 7718 if (isa<ConstantSDNode>(BasePtr)) { 7719 std::swap(BasePtr, Offset); 7720 Swapped = true; 7721 } 7722 7723 // Don't create a indexed load / store with zero offset. 7724 if (isa<ConstantSDNode>(Offset) && 7725 cast<ConstantSDNode>(Offset)->isNullValue()) 7726 return false; 7727 7728 // Try turning it into a pre-indexed load / store except when: 7729 // 1) The new base ptr is a frame index. 7730 // 2) If N is a store and the new base ptr is either the same as or is a 7731 // predecessor of the value being stored. 7732 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded 7733 // that would create a cycle. 7734 // 4) All uses are load / store ops that use it as old base ptr. 7735 7736 // Check #1. Preinc'ing a frame index would require copying the stack pointer 7737 // (plus the implicit offset) to a register to preinc anyway. 7738 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr)) 7739 return false; 7740 7741 // Check #2. 7742 if (!isLoad) { 7743 SDValue Val = cast<StoreSDNode>(N)->getValue(); 7744 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode())) 7745 return false; 7746 } 7747 7748 // If the offset is a constant, there may be other adds of constants that 7749 // can be folded with this one. We should do this to avoid having to keep 7750 // a copy of the original base pointer. 7751 SmallVector<SDNode *, 16> OtherUses; 7752 if (isa<ConstantSDNode>(Offset)) 7753 for (SDNode *Use : BasePtr.getNode()->uses()) { 7754 if (Use == Ptr.getNode()) 7755 continue; 7756 7757 if (Use->isPredecessorOf(N)) 7758 continue; 7759 7760 if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) { 7761 OtherUses.clear(); 7762 break; 7763 } 7764 7765 SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1); 7766 if (Op1.getNode() == BasePtr.getNode()) 7767 std::swap(Op0, Op1); 7768 assert(Op0.getNode() == BasePtr.getNode() && 7769 "Use of ADD/SUB but not an operand"); 7770 7771 if (!isa<ConstantSDNode>(Op1)) { 7772 OtherUses.clear(); 7773 break; 7774 } 7775 7776 // FIXME: In some cases, we can be smarter about this. 7777 if (Op1.getValueType() != Offset.getValueType()) { 7778 OtherUses.clear(); 7779 break; 7780 } 7781 7782 OtherUses.push_back(Use); 7783 } 7784 7785 if (Swapped) 7786 std::swap(BasePtr, Offset); 7787 7788 // Now check for #3 and #4. 7789 bool RealUse = false; 7790 7791 // Caches for hasPredecessorHelper 7792 SmallPtrSet<const SDNode *, 32> Visited; 7793 SmallVector<const SDNode *, 16> Worklist; 7794 7795 for (SDNode *Use : Ptr.getNode()->uses()) { 7796 if (Use == N) 7797 continue; 7798 if (N->hasPredecessorHelper(Use, Visited, Worklist)) 7799 return false; 7800 7801 // If Ptr may be folded in addressing mode of other use, then it's 7802 // not profitable to do this transformation. 7803 if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI)) 7804 RealUse = true; 7805 } 7806 7807 if (!RealUse) 7808 return false; 7809 7810 SDValue Result; 7811 if (isLoad) 7812 Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N), 7813 BasePtr, Offset, AM); 7814 else 7815 Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N), 7816 BasePtr, Offset, AM); 7817 ++PreIndexedNodes; 7818 ++NodesCombined; 7819 DEBUG(dbgs() << "\nReplacing.4 "; 7820 N->dump(&DAG); 7821 dbgs() << "\nWith: "; 7822 Result.getNode()->dump(&DAG); 7823 dbgs() << '\n'); 7824 WorklistRemover DeadNodes(*this); 7825 if (isLoad) { 7826 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0)); 7827 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2)); 7828 } else { 7829 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1)); 7830 } 7831 7832 // Finally, since the node is now dead, remove it from the graph. 7833 deleteAndRecombine(N); 7834 7835 if (Swapped) 7836 std::swap(BasePtr, Offset); 7837 7838 // Replace other uses of BasePtr that can be updated to use Ptr 7839 for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) { 7840 unsigned OffsetIdx = 1; 7841 if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode()) 7842 OffsetIdx = 0; 7843 assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() == 7844 BasePtr.getNode() && "Expected BasePtr operand"); 7845 7846 // We need to replace ptr0 in the following expression: 7847 // x0 * offset0 + y0 * ptr0 = t0 7848 // knowing that 7849 // x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store) 7850 // 7851 // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the 7852 // indexed load/store and the expresion that needs to be re-written. 7853 // 7854 // Therefore, we have: 7855 // t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1 7856 7857 ConstantSDNode *CN = 7858 cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx)); 7859 int X0, X1, Y0, Y1; 7860 APInt Offset0 = CN->getAPIntValue(); 7861 APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue(); 7862 7863 X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1; 7864 Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1; 7865 X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1; 7866 Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1; 7867 7868 unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD; 7869 7870 APInt CNV = Offset0; 7871 if (X0 < 0) CNV = -CNV; 7872 if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1; 7873 else CNV = CNV - Offset1; 7874 7875 // We can now generate the new expression. 7876 SDValue NewOp1 = DAG.getConstant(CNV, CN->getValueType(0)); 7877 SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0); 7878 7879 SDValue NewUse = DAG.getNode(Opcode, 7880 SDLoc(OtherUses[i]), 7881 OtherUses[i]->getValueType(0), NewOp1, NewOp2); 7882 DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse); 7883 deleteAndRecombine(OtherUses[i]); 7884 } 7885 7886 // Replace the uses of Ptr with uses of the updated base value. 7887 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0)); 7888 deleteAndRecombine(Ptr.getNode()); 7889 7890 return true; 7891 } 7892 7893 /// Try to combine a load/store with a add/sub of the base pointer node into a 7894 /// post-indexed load/store. The transformation folded the add/subtract into the 7895 /// new indexed load/store effectively and all of its uses are redirected to the 7896 /// new load/store. 7897 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) { 7898 if (Level < AfterLegalizeDAG) 7899 return false; 7900 7901 bool isLoad = true; 7902 SDValue Ptr; 7903 EVT VT; 7904 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 7905 if (LD->isIndexed()) 7906 return false; 7907 VT = LD->getMemoryVT(); 7908 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) && 7909 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT)) 7910 return false; 7911 Ptr = LD->getBasePtr(); 7912 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 7913 if (ST->isIndexed()) 7914 return false; 7915 VT = ST->getMemoryVT(); 7916 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) && 7917 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT)) 7918 return false; 7919 Ptr = ST->getBasePtr(); 7920 isLoad = false; 7921 } else { 7922 return false; 7923 } 7924 7925 if (Ptr.getNode()->hasOneUse()) 7926 return false; 7927 7928 for (SDNode *Op : Ptr.getNode()->uses()) { 7929 if (Op == N || 7930 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB)) 7931 continue; 7932 7933 SDValue BasePtr; 7934 SDValue Offset; 7935 ISD::MemIndexedMode AM = ISD::UNINDEXED; 7936 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) { 7937 // Don't create a indexed load / store with zero offset. 7938 if (isa<ConstantSDNode>(Offset) && 7939 cast<ConstantSDNode>(Offset)->isNullValue()) 7940 continue; 7941 7942 // Try turning it into a post-indexed load / store except when 7943 // 1) All uses are load / store ops that use it as base ptr (and 7944 // it may be folded as addressing mmode). 7945 // 2) Op must be independent of N, i.e. Op is neither a predecessor 7946 // nor a successor of N. Otherwise, if Op is folded that would 7947 // create a cycle. 7948 7949 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr)) 7950 continue; 7951 7952 // Check for #1. 7953 bool TryNext = false; 7954 for (SDNode *Use : BasePtr.getNode()->uses()) { 7955 if (Use == Ptr.getNode()) 7956 continue; 7957 7958 // If all the uses are load / store addresses, then don't do the 7959 // transformation. 7960 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){ 7961 bool RealUse = false; 7962 for (SDNode *UseUse : Use->uses()) { 7963 if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI)) 7964 RealUse = true; 7965 } 7966 7967 if (!RealUse) { 7968 TryNext = true; 7969 break; 7970 } 7971 } 7972 } 7973 7974 if (TryNext) 7975 continue; 7976 7977 // Check for #2 7978 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) { 7979 SDValue Result = isLoad 7980 ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N), 7981 BasePtr, Offset, AM) 7982 : DAG.getIndexedStore(SDValue(N,0), SDLoc(N), 7983 BasePtr, Offset, AM); 7984 ++PostIndexedNodes; 7985 ++NodesCombined; 7986 DEBUG(dbgs() << "\nReplacing.5 "; 7987 N->dump(&DAG); 7988 dbgs() << "\nWith: "; 7989 Result.getNode()->dump(&DAG); 7990 dbgs() << '\n'); 7991 WorklistRemover DeadNodes(*this); 7992 if (isLoad) { 7993 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0)); 7994 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2)); 7995 } else { 7996 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1)); 7997 } 7998 7999 // Finally, since the node is now dead, remove it from the graph. 8000 deleteAndRecombine(N); 8001 8002 // Replace the uses of Use with uses of the updated base value. 8003 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0), 8004 Result.getValue(isLoad ? 1 : 0)); 8005 deleteAndRecombine(Op); 8006 return true; 8007 } 8008 } 8009 } 8010 8011 return false; 8012 } 8013 8014 /// \brief Return the base-pointer arithmetic from an indexed \p LD. 8015 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) { 8016 ISD::MemIndexedMode AM = LD->getAddressingMode(); 8017 assert(AM != ISD::UNINDEXED); 8018 SDValue BP = LD->getOperand(1); 8019 SDValue Inc = LD->getOperand(2); 8020 8021 // Some backends use TargetConstants for load offsets, but don't expect 8022 // TargetConstants in general ADD nodes. We can convert these constants into 8023 // regular Constants (if the constant is not opaque). 8024 assert((Inc.getOpcode() != ISD::TargetConstant || 8025 !cast<ConstantSDNode>(Inc)->isOpaque()) && 8026 "Cannot split out indexing using opaque target constants"); 8027 if (Inc.getOpcode() == ISD::TargetConstant) { 8028 ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc); 8029 Inc = DAG.getConstant(*ConstInc->getConstantIntValue(), 8030 ConstInc->getValueType(0)); 8031 } 8032 8033 unsigned Opc = 8034 (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB); 8035 return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc); 8036 } 8037 8038 SDValue DAGCombiner::visitLOAD(SDNode *N) { 8039 LoadSDNode *LD = cast<LoadSDNode>(N); 8040 SDValue Chain = LD->getChain(); 8041 SDValue Ptr = LD->getBasePtr(); 8042 8043 // If load is not volatile and there are no uses of the loaded value (and 8044 // the updated indexed value in case of indexed loads), change uses of the 8045 // chain value into uses of the chain input (i.e. delete the dead load). 8046 if (!LD->isVolatile()) { 8047 if (N->getValueType(1) == MVT::Other) { 8048 // Unindexed loads. 8049 if (!N->hasAnyUseOfValue(0)) { 8050 // It's not safe to use the two value CombineTo variant here. e.g. 8051 // v1, chain2 = load chain1, loc 8052 // v2, chain3 = load chain2, loc 8053 // v3 = add v2, c 8054 // Now we replace use of chain2 with chain1. This makes the second load 8055 // isomorphic to the one we are deleting, and thus makes this load live. 8056 DEBUG(dbgs() << "\nReplacing.6 "; 8057 N->dump(&DAG); 8058 dbgs() << "\nWith chain: "; 8059 Chain.getNode()->dump(&DAG); 8060 dbgs() << "\n"); 8061 WorklistRemover DeadNodes(*this); 8062 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain); 8063 8064 if (N->use_empty()) 8065 deleteAndRecombine(N); 8066 8067 return SDValue(N, 0); // Return N so it doesn't get rechecked! 8068 } 8069 } else { 8070 // Indexed loads. 8071 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?"); 8072 8073 // If this load has an opaque TargetConstant offset, then we cannot split 8074 // the indexing into an add/sub directly (that TargetConstant may not be 8075 // valid for a different type of node, and we cannot convert an opaque 8076 // target constant into a regular constant). 8077 bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant && 8078 cast<ConstantSDNode>(LD->getOperand(2))->isOpaque(); 8079 8080 if (!N->hasAnyUseOfValue(0) && 8081 ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) { 8082 SDValue Undef = DAG.getUNDEF(N->getValueType(0)); 8083 SDValue Index; 8084 if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) { 8085 Index = SplitIndexingFromLoad(LD); 8086 // Try to fold the base pointer arithmetic into subsequent loads and 8087 // stores. 8088 AddUsersToWorklist(N); 8089 } else 8090 Index = DAG.getUNDEF(N->getValueType(1)); 8091 DEBUG(dbgs() << "\nReplacing.7 "; 8092 N->dump(&DAG); 8093 dbgs() << "\nWith: "; 8094 Undef.getNode()->dump(&DAG); 8095 dbgs() << " and 2 other values\n"); 8096 WorklistRemover DeadNodes(*this); 8097 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef); 8098 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index); 8099 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain); 8100 deleteAndRecombine(N); 8101 return SDValue(N, 0); // Return N so it doesn't get rechecked! 8102 } 8103 } 8104 } 8105 8106 // If this load is directly stored, replace the load value with the stored 8107 // value. 8108 // TODO: Handle store large -> read small portion. 8109 // TODO: Handle TRUNCSTORE/LOADEXT 8110 if (ISD::isNormalLoad(N) && !LD->isVolatile()) { 8111 if (ISD::isNON_TRUNCStore(Chain.getNode())) { 8112 StoreSDNode *PrevST = cast<StoreSDNode>(Chain); 8113 if (PrevST->getBasePtr() == Ptr && 8114 PrevST->getValue().getValueType() == N->getValueType(0)) 8115 return CombineTo(N, Chain.getOperand(1), Chain); 8116 } 8117 } 8118 8119 // Try to infer better alignment information than the load already has. 8120 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) { 8121 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) { 8122 if (Align > LD->getMemOperand()->getBaseAlignment()) { 8123 SDValue NewLoad = 8124 DAG.getExtLoad(LD->getExtensionType(), SDLoc(N), 8125 LD->getValueType(0), 8126 Chain, Ptr, LD->getPointerInfo(), 8127 LD->getMemoryVT(), 8128 LD->isVolatile(), LD->isNonTemporal(), 8129 LD->isInvariant(), Align, LD->getAAInfo()); 8130 return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true); 8131 } 8132 } 8133 } 8134 8135 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA : 8136 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA(); 8137 #ifndef NDEBUG 8138 if (CombinerAAOnlyFunc.getNumOccurrences() && 8139 CombinerAAOnlyFunc != DAG.getMachineFunction().getName()) 8140 UseAA = false; 8141 #endif 8142 if (UseAA && LD->isUnindexed()) { 8143 // Walk up chain skipping non-aliasing memory nodes. 8144 SDValue BetterChain = FindBetterChain(N, Chain); 8145 8146 // If there is a better chain. 8147 if (Chain != BetterChain) { 8148 SDValue ReplLoad; 8149 8150 // Replace the chain to void dependency. 8151 if (LD->getExtensionType() == ISD::NON_EXTLOAD) { 8152 ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD), 8153 BetterChain, Ptr, LD->getMemOperand()); 8154 } else { 8155 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), 8156 LD->getValueType(0), 8157 BetterChain, Ptr, LD->getMemoryVT(), 8158 LD->getMemOperand()); 8159 } 8160 8161 // Create token factor to keep old chain connected. 8162 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N), 8163 MVT::Other, Chain, ReplLoad.getValue(1)); 8164 8165 // Make sure the new and old chains are cleaned up. 8166 AddToWorklist(Token.getNode()); 8167 8168 // Replace uses with load result and token factor. Don't add users 8169 // to work list. 8170 return CombineTo(N, ReplLoad.getValue(0), Token, false); 8171 } 8172 } 8173 8174 // Try transforming N to an indexed load. 8175 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N)) 8176 return SDValue(N, 0); 8177 8178 // Try to slice up N to more direct loads if the slices are mapped to 8179 // different register banks or pairing can take place. 8180 if (SliceUpLoad(N)) 8181 return SDValue(N, 0); 8182 8183 return SDValue(); 8184 } 8185 8186 namespace { 8187 /// \brief Helper structure used to slice a load in smaller loads. 8188 /// Basically a slice is obtained from the following sequence: 8189 /// Origin = load Ty1, Base 8190 /// Shift = srl Ty1 Origin, CstTy Amount 8191 /// Inst = trunc Shift to Ty2 8192 /// 8193 /// Then, it will be rewriten into: 8194 /// Slice = load SliceTy, Base + SliceOffset 8195 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2 8196 /// 8197 /// SliceTy is deduced from the number of bits that are actually used to 8198 /// build Inst. 8199 struct LoadedSlice { 8200 /// \brief Helper structure used to compute the cost of a slice. 8201 struct Cost { 8202 /// Are we optimizing for code size. 8203 bool ForCodeSize; 8204 /// Various cost. 8205 unsigned Loads; 8206 unsigned Truncates; 8207 unsigned CrossRegisterBanksCopies; 8208 unsigned ZExts; 8209 unsigned Shift; 8210 8211 Cost(bool ForCodeSize = false) 8212 : ForCodeSize(ForCodeSize), Loads(0), Truncates(0), 8213 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {} 8214 8215 /// \brief Get the cost of one isolated slice. 8216 Cost(const LoadedSlice &LS, bool ForCodeSize = false) 8217 : ForCodeSize(ForCodeSize), Loads(1), Truncates(0), 8218 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) { 8219 EVT TruncType = LS.Inst->getValueType(0); 8220 EVT LoadedType = LS.getLoadedType(); 8221 if (TruncType != LoadedType && 8222 !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType)) 8223 ZExts = 1; 8224 } 8225 8226 /// \brief Account for slicing gain in the current cost. 8227 /// Slicing provide a few gains like removing a shift or a 8228 /// truncate. This method allows to grow the cost of the original 8229 /// load with the gain from this slice. 8230 void addSliceGain(const LoadedSlice &LS) { 8231 // Each slice saves a truncate. 8232 const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo(); 8233 if (!TLI.isTruncateFree(LS.Inst->getValueType(0), 8234 LS.Inst->getOperand(0).getValueType())) 8235 ++Truncates; 8236 // If there is a shift amount, this slice gets rid of it. 8237 if (LS.Shift) 8238 ++Shift; 8239 // If this slice can merge a cross register bank copy, account for it. 8240 if (LS.canMergeExpensiveCrossRegisterBankCopy()) 8241 ++CrossRegisterBanksCopies; 8242 } 8243 8244 Cost &operator+=(const Cost &RHS) { 8245 Loads += RHS.Loads; 8246 Truncates += RHS.Truncates; 8247 CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies; 8248 ZExts += RHS.ZExts; 8249 Shift += RHS.Shift; 8250 return *this; 8251 } 8252 8253 bool operator==(const Cost &RHS) const { 8254 return Loads == RHS.Loads && Truncates == RHS.Truncates && 8255 CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies && 8256 ZExts == RHS.ZExts && Shift == RHS.Shift; 8257 } 8258 8259 bool operator!=(const Cost &RHS) const { return !(*this == RHS); } 8260 8261 bool operator<(const Cost &RHS) const { 8262 // Assume cross register banks copies are as expensive as loads. 8263 // FIXME: Do we want some more target hooks? 8264 unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies; 8265 unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies; 8266 // Unless we are optimizing for code size, consider the 8267 // expensive operation first. 8268 if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS) 8269 return ExpensiveOpsLHS < ExpensiveOpsRHS; 8270 return (Truncates + ZExts + Shift + ExpensiveOpsLHS) < 8271 (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS); 8272 } 8273 8274 bool operator>(const Cost &RHS) const { return RHS < *this; } 8275 8276 bool operator<=(const Cost &RHS) const { return !(RHS < *this); } 8277 8278 bool operator>=(const Cost &RHS) const { return !(*this < RHS); } 8279 }; 8280 // The last instruction that represent the slice. This should be a 8281 // truncate instruction. 8282 SDNode *Inst; 8283 // The original load instruction. 8284 LoadSDNode *Origin; 8285 // The right shift amount in bits from the original load. 8286 unsigned Shift; 8287 // The DAG from which Origin came from. 8288 // This is used to get some contextual information about legal types, etc. 8289 SelectionDAG *DAG; 8290 8291 LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr, 8292 unsigned Shift = 0, SelectionDAG *DAG = nullptr) 8293 : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {} 8294 8295 LoadedSlice(const LoadedSlice &LS) 8296 : Inst(LS.Inst), Origin(LS.Origin), Shift(LS.Shift), DAG(LS.DAG) {} 8297 8298 /// \brief Get the bits used in a chunk of bits \p BitWidth large. 8299 /// \return Result is \p BitWidth and has used bits set to 1 and 8300 /// not used bits set to 0. 8301 APInt getUsedBits() const { 8302 // Reproduce the trunc(lshr) sequence: 8303 // - Start from the truncated value. 8304 // - Zero extend to the desired bit width. 8305 // - Shift left. 8306 assert(Origin && "No original load to compare against."); 8307 unsigned BitWidth = Origin->getValueSizeInBits(0); 8308 assert(Inst && "This slice is not bound to an instruction"); 8309 assert(Inst->getValueSizeInBits(0) <= BitWidth && 8310 "Extracted slice is bigger than the whole type!"); 8311 APInt UsedBits(Inst->getValueSizeInBits(0), 0); 8312 UsedBits.setAllBits(); 8313 UsedBits = UsedBits.zext(BitWidth); 8314 UsedBits <<= Shift; 8315 return UsedBits; 8316 } 8317 8318 /// \brief Get the size of the slice to be loaded in bytes. 8319 unsigned getLoadedSize() const { 8320 unsigned SliceSize = getUsedBits().countPopulation(); 8321 assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte."); 8322 return SliceSize / 8; 8323 } 8324 8325 /// \brief Get the type that will be loaded for this slice. 8326 /// Note: This may not be the final type for the slice. 8327 EVT getLoadedType() const { 8328 assert(DAG && "Missing context"); 8329 LLVMContext &Ctxt = *DAG->getContext(); 8330 return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8); 8331 } 8332 8333 /// \brief Get the alignment of the load used for this slice. 8334 unsigned getAlignment() const { 8335 unsigned Alignment = Origin->getAlignment(); 8336 unsigned Offset = getOffsetFromBase(); 8337 if (Offset != 0) 8338 Alignment = MinAlign(Alignment, Alignment + Offset); 8339 return Alignment; 8340 } 8341 8342 /// \brief Check if this slice can be rewritten with legal operations. 8343 bool isLegal() const { 8344 // An invalid slice is not legal. 8345 if (!Origin || !Inst || !DAG) 8346 return false; 8347 8348 // Offsets are for indexed load only, we do not handle that. 8349 if (Origin->getOffset().getOpcode() != ISD::UNDEF) 8350 return false; 8351 8352 const TargetLowering &TLI = DAG->getTargetLoweringInfo(); 8353 8354 // Check that the type is legal. 8355 EVT SliceType = getLoadedType(); 8356 if (!TLI.isTypeLegal(SliceType)) 8357 return false; 8358 8359 // Check that the load is legal for this type. 8360 if (!TLI.isOperationLegal(ISD::LOAD, SliceType)) 8361 return false; 8362 8363 // Check that the offset can be computed. 8364 // 1. Check its type. 8365 EVT PtrType = Origin->getBasePtr().getValueType(); 8366 if (PtrType == MVT::Untyped || PtrType.isExtended()) 8367 return false; 8368 8369 // 2. Check that it fits in the immediate. 8370 if (!TLI.isLegalAddImmediate(getOffsetFromBase())) 8371 return false; 8372 8373 // 3. Check that the computation is legal. 8374 if (!TLI.isOperationLegal(ISD::ADD, PtrType)) 8375 return false; 8376 8377 // Check that the zext is legal if it needs one. 8378 EVT TruncateType = Inst->getValueType(0); 8379 if (TruncateType != SliceType && 8380 !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType)) 8381 return false; 8382 8383 return true; 8384 } 8385 8386 /// \brief Get the offset in bytes of this slice in the original chunk of 8387 /// bits. 8388 /// \pre DAG != nullptr. 8389 uint64_t getOffsetFromBase() const { 8390 assert(DAG && "Missing context."); 8391 bool IsBigEndian = 8392 DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian(); 8393 assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported."); 8394 uint64_t Offset = Shift / 8; 8395 unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8; 8396 assert(!(Origin->getValueSizeInBits(0) & 0x7) && 8397 "The size of the original loaded type is not a multiple of a" 8398 " byte."); 8399 // If Offset is bigger than TySizeInBytes, it means we are loading all 8400 // zeros. This should have been optimized before in the process. 8401 assert(TySizeInBytes > Offset && 8402 "Invalid shift amount for given loaded size"); 8403 if (IsBigEndian) 8404 Offset = TySizeInBytes - Offset - getLoadedSize(); 8405 return Offset; 8406 } 8407 8408 /// \brief Generate the sequence of instructions to load the slice 8409 /// represented by this object and redirect the uses of this slice to 8410 /// this new sequence of instructions. 8411 /// \pre this->Inst && this->Origin are valid Instructions and this 8412 /// object passed the legal check: LoadedSlice::isLegal returned true. 8413 /// \return The last instruction of the sequence used to load the slice. 8414 SDValue loadSlice() const { 8415 assert(Inst && Origin && "Unable to replace a non-existing slice."); 8416 const SDValue &OldBaseAddr = Origin->getBasePtr(); 8417 SDValue BaseAddr = OldBaseAddr; 8418 // Get the offset in that chunk of bytes w.r.t. the endianess. 8419 int64_t Offset = static_cast<int64_t>(getOffsetFromBase()); 8420 assert(Offset >= 0 && "Offset too big to fit in int64_t!"); 8421 if (Offset) { 8422 // BaseAddr = BaseAddr + Offset. 8423 EVT ArithType = BaseAddr.getValueType(); 8424 BaseAddr = DAG->getNode(ISD::ADD, SDLoc(Origin), ArithType, BaseAddr, 8425 DAG->getConstant(Offset, ArithType)); 8426 } 8427 8428 // Create the type of the loaded slice according to its size. 8429 EVT SliceType = getLoadedType(); 8430 8431 // Create the load for the slice. 8432 SDValue LastInst = DAG->getLoad( 8433 SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr, 8434 Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(), 8435 Origin->isNonTemporal(), Origin->isInvariant(), getAlignment()); 8436 // If the final type is not the same as the loaded type, this means that 8437 // we have to pad with zero. Create a zero extend for that. 8438 EVT FinalType = Inst->getValueType(0); 8439 if (SliceType != FinalType) 8440 LastInst = 8441 DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst); 8442 return LastInst; 8443 } 8444 8445 /// \brief Check if this slice can be merged with an expensive cross register 8446 /// bank copy. E.g., 8447 /// i = load i32 8448 /// f = bitcast i32 i to float 8449 bool canMergeExpensiveCrossRegisterBankCopy() const { 8450 if (!Inst || !Inst->hasOneUse()) 8451 return false; 8452 SDNode *Use = *Inst->use_begin(); 8453 if (Use->getOpcode() != ISD::BITCAST) 8454 return false; 8455 assert(DAG && "Missing context"); 8456 const TargetLowering &TLI = DAG->getTargetLoweringInfo(); 8457 EVT ResVT = Use->getValueType(0); 8458 const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT()); 8459 const TargetRegisterClass *ArgRC = 8460 TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT()); 8461 if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT)) 8462 return false; 8463 8464 // At this point, we know that we perform a cross-register-bank copy. 8465 // Check if it is expensive. 8466 const TargetRegisterInfo *TRI = 8467 TLI.getTargetMachine().getSubtargetImpl()->getRegisterInfo(); 8468 // Assume bitcasts are cheap, unless both register classes do not 8469 // explicitly share a common sub class. 8470 if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC)) 8471 return false; 8472 8473 // Check if it will be merged with the load. 8474 // 1. Check the alignment constraint. 8475 unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment( 8476 ResVT.getTypeForEVT(*DAG->getContext())); 8477 8478 if (RequiredAlignment > getAlignment()) 8479 return false; 8480 8481 // 2. Check that the load is a legal operation for that type. 8482 if (!TLI.isOperationLegal(ISD::LOAD, ResVT)) 8483 return false; 8484 8485 // 3. Check that we do not have a zext in the way. 8486 if (Inst->getValueType(0) != getLoadedType()) 8487 return false; 8488 8489 return true; 8490 } 8491 }; 8492 } 8493 8494 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e., 8495 /// \p UsedBits looks like 0..0 1..1 0..0. 8496 static bool areUsedBitsDense(const APInt &UsedBits) { 8497 // If all the bits are one, this is dense! 8498 if (UsedBits.isAllOnesValue()) 8499 return true; 8500 8501 // Get rid of the unused bits on the right. 8502 APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros()); 8503 // Get rid of the unused bits on the left. 8504 if (NarrowedUsedBits.countLeadingZeros()) 8505 NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits()); 8506 // Check that the chunk of bits is completely used. 8507 return NarrowedUsedBits.isAllOnesValue(); 8508 } 8509 8510 /// \brief Check whether or not \p First and \p Second are next to each other 8511 /// in memory. This means that there is no hole between the bits loaded 8512 /// by \p First and the bits loaded by \p Second. 8513 static bool areSlicesNextToEachOther(const LoadedSlice &First, 8514 const LoadedSlice &Second) { 8515 assert(First.Origin == Second.Origin && First.Origin && 8516 "Unable to match different memory origins."); 8517 APInt UsedBits = First.getUsedBits(); 8518 assert((UsedBits & Second.getUsedBits()) == 0 && 8519 "Slices are not supposed to overlap."); 8520 UsedBits |= Second.getUsedBits(); 8521 return areUsedBitsDense(UsedBits); 8522 } 8523 8524 /// \brief Adjust the \p GlobalLSCost according to the target 8525 /// paring capabilities and the layout of the slices. 8526 /// \pre \p GlobalLSCost should account for at least as many loads as 8527 /// there is in the slices in \p LoadedSlices. 8528 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices, 8529 LoadedSlice::Cost &GlobalLSCost) { 8530 unsigned NumberOfSlices = LoadedSlices.size(); 8531 // If there is less than 2 elements, no pairing is possible. 8532 if (NumberOfSlices < 2) 8533 return; 8534 8535 // Sort the slices so that elements that are likely to be next to each 8536 // other in memory are next to each other in the list. 8537 std::sort(LoadedSlices.begin(), LoadedSlices.end(), 8538 [](const LoadedSlice &LHS, const LoadedSlice &RHS) { 8539 assert(LHS.Origin == RHS.Origin && "Different bases not implemented."); 8540 return LHS.getOffsetFromBase() < RHS.getOffsetFromBase(); 8541 }); 8542 const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo(); 8543 // First (resp. Second) is the first (resp. Second) potentially candidate 8544 // to be placed in a paired load. 8545 const LoadedSlice *First = nullptr; 8546 const LoadedSlice *Second = nullptr; 8547 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice, 8548 // Set the beginning of the pair. 8549 First = Second) { 8550 8551 Second = &LoadedSlices[CurrSlice]; 8552 8553 // If First is NULL, it means we start a new pair. 8554 // Get to the next slice. 8555 if (!First) 8556 continue; 8557 8558 EVT LoadedType = First->getLoadedType(); 8559 8560 // If the types of the slices are different, we cannot pair them. 8561 if (LoadedType != Second->getLoadedType()) 8562 continue; 8563 8564 // Check if the target supplies paired loads for this type. 8565 unsigned RequiredAlignment = 0; 8566 if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) { 8567 // move to the next pair, this type is hopeless. 8568 Second = nullptr; 8569 continue; 8570 } 8571 // Check if we meet the alignment requirement. 8572 if (RequiredAlignment > First->getAlignment()) 8573 continue; 8574 8575 // Check that both loads are next to each other in memory. 8576 if (!areSlicesNextToEachOther(*First, *Second)) 8577 continue; 8578 8579 assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!"); 8580 --GlobalLSCost.Loads; 8581 // Move to the next pair. 8582 Second = nullptr; 8583 } 8584 } 8585 8586 /// \brief Check the profitability of all involved LoadedSlice. 8587 /// Currently, it is considered profitable if there is exactly two 8588 /// involved slices (1) which are (2) next to each other in memory, and 8589 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3). 8590 /// 8591 /// Note: The order of the elements in \p LoadedSlices may be modified, but not 8592 /// the elements themselves. 8593 /// 8594 /// FIXME: When the cost model will be mature enough, we can relax 8595 /// constraints (1) and (2). 8596 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices, 8597 const APInt &UsedBits, bool ForCodeSize) { 8598 unsigned NumberOfSlices = LoadedSlices.size(); 8599 if (StressLoadSlicing) 8600 return NumberOfSlices > 1; 8601 8602 // Check (1). 8603 if (NumberOfSlices != 2) 8604 return false; 8605 8606 // Check (2). 8607 if (!areUsedBitsDense(UsedBits)) 8608 return false; 8609 8610 // Check (3). 8611 LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize); 8612 // The original code has one big load. 8613 OrigCost.Loads = 1; 8614 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) { 8615 const LoadedSlice &LS = LoadedSlices[CurrSlice]; 8616 // Accumulate the cost of all the slices. 8617 LoadedSlice::Cost SliceCost(LS, ForCodeSize); 8618 GlobalSlicingCost += SliceCost; 8619 8620 // Account as cost in the original configuration the gain obtained 8621 // with the current slices. 8622 OrigCost.addSliceGain(LS); 8623 } 8624 8625 // If the target supports paired load, adjust the cost accordingly. 8626 adjustCostForPairing(LoadedSlices, GlobalSlicingCost); 8627 return OrigCost > GlobalSlicingCost; 8628 } 8629 8630 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr) 8631 /// operations, split it in the various pieces being extracted. 8632 /// 8633 /// This sort of thing is introduced by SROA. 8634 /// This slicing takes care not to insert overlapping loads. 8635 /// \pre LI is a simple load (i.e., not an atomic or volatile load). 8636 bool DAGCombiner::SliceUpLoad(SDNode *N) { 8637 if (Level < AfterLegalizeDAG) 8638 return false; 8639 8640 LoadSDNode *LD = cast<LoadSDNode>(N); 8641 if (LD->isVolatile() || !ISD::isNormalLoad(LD) || 8642 !LD->getValueType(0).isInteger()) 8643 return false; 8644 8645 // Keep track of already used bits to detect overlapping values. 8646 // In that case, we will just abort the transformation. 8647 APInt UsedBits(LD->getValueSizeInBits(0), 0); 8648 8649 SmallVector<LoadedSlice, 4> LoadedSlices; 8650 8651 // Check if this load is used as several smaller chunks of bits. 8652 // Basically, look for uses in trunc or trunc(lshr) and record a new chain 8653 // of computation for each trunc. 8654 for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end(); 8655 UI != UIEnd; ++UI) { 8656 // Skip the uses of the chain. 8657 if (UI.getUse().getResNo() != 0) 8658 continue; 8659 8660 SDNode *User = *UI; 8661 unsigned Shift = 0; 8662 8663 // Check if this is a trunc(lshr). 8664 if (User->getOpcode() == ISD::SRL && User->hasOneUse() && 8665 isa<ConstantSDNode>(User->getOperand(1))) { 8666 Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue(); 8667 User = *User->use_begin(); 8668 } 8669 8670 // At this point, User is a Truncate, iff we encountered, trunc or 8671 // trunc(lshr). 8672 if (User->getOpcode() != ISD::TRUNCATE) 8673 return false; 8674 8675 // The width of the type must be a power of 2 and greater than 8-bits. 8676 // Otherwise the load cannot be represented in LLVM IR. 8677 // Moreover, if we shifted with a non-8-bits multiple, the slice 8678 // will be across several bytes. We do not support that. 8679 unsigned Width = User->getValueSizeInBits(0); 8680 if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7)) 8681 return 0; 8682 8683 // Build the slice for this chain of computations. 8684 LoadedSlice LS(User, LD, Shift, &DAG); 8685 APInt CurrentUsedBits = LS.getUsedBits(); 8686 8687 // Check if this slice overlaps with another. 8688 if ((CurrentUsedBits & UsedBits) != 0) 8689 return false; 8690 // Update the bits used globally. 8691 UsedBits |= CurrentUsedBits; 8692 8693 // Check if the new slice would be legal. 8694 if (!LS.isLegal()) 8695 return false; 8696 8697 // Record the slice. 8698 LoadedSlices.push_back(LS); 8699 } 8700 8701 // Abort slicing if it does not seem to be profitable. 8702 if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize)) 8703 return false; 8704 8705 ++SlicedLoads; 8706 8707 // Rewrite each chain to use an independent load. 8708 // By construction, each chain can be represented by a unique load. 8709 8710 // Prepare the argument for the new token factor for all the slices. 8711 SmallVector<SDValue, 8> ArgChains; 8712 for (SmallVectorImpl<LoadedSlice>::const_iterator 8713 LSIt = LoadedSlices.begin(), 8714 LSItEnd = LoadedSlices.end(); 8715 LSIt != LSItEnd; ++LSIt) { 8716 SDValue SliceInst = LSIt->loadSlice(); 8717 CombineTo(LSIt->Inst, SliceInst, true); 8718 if (SliceInst.getNode()->getOpcode() != ISD::LOAD) 8719 SliceInst = SliceInst.getOperand(0); 8720 assert(SliceInst->getOpcode() == ISD::LOAD && 8721 "It takes more than a zext to get to the loaded slice!!"); 8722 ArgChains.push_back(SliceInst.getValue(1)); 8723 } 8724 8725 SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other, 8726 ArgChains); 8727 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain); 8728 return true; 8729 } 8730 8731 /// Check to see if V is (and load (ptr), imm), where the load is having 8732 /// specific bytes cleared out. If so, return the byte size being masked out 8733 /// and the shift amount. 8734 static std::pair<unsigned, unsigned> 8735 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) { 8736 std::pair<unsigned, unsigned> Result(0, 0); 8737 8738 // Check for the structure we're looking for. 8739 if (V->getOpcode() != ISD::AND || 8740 !isa<ConstantSDNode>(V->getOperand(1)) || 8741 !ISD::isNormalLoad(V->getOperand(0).getNode())) 8742 return Result; 8743 8744 // Check the chain and pointer. 8745 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0)); 8746 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer. 8747 8748 // The store should be chained directly to the load or be an operand of a 8749 // tokenfactor. 8750 if (LD == Chain.getNode()) 8751 ; // ok. 8752 else if (Chain->getOpcode() != ISD::TokenFactor) 8753 return Result; // Fail. 8754 else { 8755 bool isOk = false; 8756 for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i) 8757 if (Chain->getOperand(i).getNode() == LD) { 8758 isOk = true; 8759 break; 8760 } 8761 if (!isOk) return Result; 8762 } 8763 8764 // This only handles simple types. 8765 if (V.getValueType() != MVT::i16 && 8766 V.getValueType() != MVT::i32 && 8767 V.getValueType() != MVT::i64) 8768 return Result; 8769 8770 // Check the constant mask. Invert it so that the bits being masked out are 8771 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits 8772 // follow the sign bit for uniformity. 8773 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue(); 8774 unsigned NotMaskLZ = countLeadingZeros(NotMask); 8775 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte. 8776 unsigned NotMaskTZ = countTrailingZeros(NotMask); 8777 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte. 8778 if (NotMaskLZ == 64) return Result; // All zero mask. 8779 8780 // See if we have a continuous run of bits. If so, we have 0*1+0* 8781 if (CountTrailingOnes_64(NotMask >> NotMaskTZ)+NotMaskTZ+NotMaskLZ != 64) 8782 return Result; 8783 8784 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64. 8785 if (V.getValueType() != MVT::i64 && NotMaskLZ) 8786 NotMaskLZ -= 64-V.getValueSizeInBits(); 8787 8788 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8; 8789 switch (MaskedBytes) { 8790 case 1: 8791 case 2: 8792 case 4: break; 8793 default: return Result; // All one mask, or 5-byte mask. 8794 } 8795 8796 // Verify that the first bit starts at a multiple of mask so that the access 8797 // is aligned the same as the access width. 8798 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result; 8799 8800 Result.first = MaskedBytes; 8801 Result.second = NotMaskTZ/8; 8802 return Result; 8803 } 8804 8805 8806 /// Check to see if IVal is something that provides a value as specified by 8807 /// MaskInfo. If so, replace the specified store with a narrower store of 8808 /// truncated IVal. 8809 static SDNode * 8810 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo, 8811 SDValue IVal, StoreSDNode *St, 8812 DAGCombiner *DC) { 8813 unsigned NumBytes = MaskInfo.first; 8814 unsigned ByteShift = MaskInfo.second; 8815 SelectionDAG &DAG = DC->getDAG(); 8816 8817 // Check to see if IVal is all zeros in the part being masked in by the 'or' 8818 // that uses this. If not, this is not a replacement. 8819 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(), 8820 ByteShift*8, (ByteShift+NumBytes)*8); 8821 if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr; 8822 8823 // Check that it is legal on the target to do this. It is legal if the new 8824 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type 8825 // legalization. 8826 MVT VT = MVT::getIntegerVT(NumBytes*8); 8827 if (!DC->isTypeLegal(VT)) 8828 return nullptr; 8829 8830 // Okay, we can do this! Replace the 'St' store with a store of IVal that is 8831 // shifted by ByteShift and truncated down to NumBytes. 8832 if (ByteShift) 8833 IVal = DAG.getNode(ISD::SRL, SDLoc(IVal), IVal.getValueType(), IVal, 8834 DAG.getConstant(ByteShift*8, 8835 DC->getShiftAmountTy(IVal.getValueType()))); 8836 8837 // Figure out the offset for the store and the alignment of the access. 8838 unsigned StOffset; 8839 unsigned NewAlign = St->getAlignment(); 8840 8841 if (DAG.getTargetLoweringInfo().isLittleEndian()) 8842 StOffset = ByteShift; 8843 else 8844 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes; 8845 8846 SDValue Ptr = St->getBasePtr(); 8847 if (StOffset) { 8848 Ptr = DAG.getNode(ISD::ADD, SDLoc(IVal), Ptr.getValueType(), 8849 Ptr, DAG.getConstant(StOffset, Ptr.getValueType())); 8850 NewAlign = MinAlign(NewAlign, StOffset); 8851 } 8852 8853 // Truncate down to the new size. 8854 IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal); 8855 8856 ++OpsNarrowed; 8857 return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr, 8858 St->getPointerInfo().getWithOffset(StOffset), 8859 false, false, NewAlign).getNode(); 8860 } 8861 8862 8863 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and 8864 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try 8865 /// narrowing the load and store if it would end up being a win for performance 8866 /// or code size. 8867 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) { 8868 StoreSDNode *ST = cast<StoreSDNode>(N); 8869 if (ST->isVolatile()) 8870 return SDValue(); 8871 8872 SDValue Chain = ST->getChain(); 8873 SDValue Value = ST->getValue(); 8874 SDValue Ptr = ST->getBasePtr(); 8875 EVT VT = Value.getValueType(); 8876 8877 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse()) 8878 return SDValue(); 8879 8880 unsigned Opc = Value.getOpcode(); 8881 8882 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst 8883 // is a byte mask indicating a consecutive number of bytes, check to see if 8884 // Y is known to provide just those bytes. If so, we try to replace the 8885 // load + replace + store sequence with a single (narrower) store, which makes 8886 // the load dead. 8887 if (Opc == ISD::OR) { 8888 std::pair<unsigned, unsigned> MaskedLoad; 8889 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain); 8890 if (MaskedLoad.first) 8891 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad, 8892 Value.getOperand(1), ST,this)) 8893 return SDValue(NewST, 0); 8894 8895 // Or is commutative, so try swapping X and Y. 8896 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain); 8897 if (MaskedLoad.first) 8898 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad, 8899 Value.getOperand(0), ST,this)) 8900 return SDValue(NewST, 0); 8901 } 8902 8903 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) || 8904 Value.getOperand(1).getOpcode() != ISD::Constant) 8905 return SDValue(); 8906 8907 SDValue N0 = Value.getOperand(0); 8908 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() && 8909 Chain == SDValue(N0.getNode(), 1)) { 8910 LoadSDNode *LD = cast<LoadSDNode>(N0); 8911 if (LD->getBasePtr() != Ptr || 8912 LD->getPointerInfo().getAddrSpace() != 8913 ST->getPointerInfo().getAddrSpace()) 8914 return SDValue(); 8915 8916 // Find the type to narrow it the load / op / store to. 8917 SDValue N1 = Value.getOperand(1); 8918 unsigned BitWidth = N1.getValueSizeInBits(); 8919 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue(); 8920 if (Opc == ISD::AND) 8921 Imm ^= APInt::getAllOnesValue(BitWidth); 8922 if (Imm == 0 || Imm.isAllOnesValue()) 8923 return SDValue(); 8924 unsigned ShAmt = Imm.countTrailingZeros(); 8925 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1; 8926 unsigned NewBW = NextPowerOf2(MSB - ShAmt); 8927 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW); 8928 while (NewBW < BitWidth && 8929 !(TLI.isOperationLegalOrCustom(Opc, NewVT) && 8930 TLI.isNarrowingProfitable(VT, NewVT))) { 8931 NewBW = NextPowerOf2(NewBW); 8932 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW); 8933 } 8934 if (NewBW >= BitWidth) 8935 return SDValue(); 8936 8937 // If the lsb changed does not start at the type bitwidth boundary, 8938 // start at the previous one. 8939 if (ShAmt % NewBW) 8940 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW; 8941 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt, 8942 std::min(BitWidth, ShAmt + NewBW)); 8943 if ((Imm & Mask) == Imm) { 8944 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW); 8945 if (Opc == ISD::AND) 8946 NewImm ^= APInt::getAllOnesValue(NewBW); 8947 uint64_t PtrOff = ShAmt / 8; 8948 // For big endian targets, we need to adjust the offset to the pointer to 8949 // load the correct bytes. 8950 if (TLI.isBigEndian()) 8951 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff; 8952 8953 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff); 8954 Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext()); 8955 if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy)) 8956 return SDValue(); 8957 8958 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD), 8959 Ptr.getValueType(), Ptr, 8960 DAG.getConstant(PtrOff, Ptr.getValueType())); 8961 SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0), 8962 LD->getChain(), NewPtr, 8963 LD->getPointerInfo().getWithOffset(PtrOff), 8964 LD->isVolatile(), LD->isNonTemporal(), 8965 LD->isInvariant(), NewAlign, 8966 LD->getAAInfo()); 8967 SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD, 8968 DAG.getConstant(NewImm, NewVT)); 8969 SDValue NewST = DAG.getStore(Chain, SDLoc(N), 8970 NewVal, NewPtr, 8971 ST->getPointerInfo().getWithOffset(PtrOff), 8972 false, false, NewAlign); 8973 8974 AddToWorklist(NewPtr.getNode()); 8975 AddToWorklist(NewLD.getNode()); 8976 AddToWorklist(NewVal.getNode()); 8977 WorklistRemover DeadNodes(*this); 8978 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1)); 8979 ++OpsNarrowed; 8980 return NewST; 8981 } 8982 } 8983 8984 return SDValue(); 8985 } 8986 8987 /// For a given floating point load / store pair, if the load value isn't used 8988 /// by any other operations, then consider transforming the pair to integer 8989 /// load / store operations if the target deems the transformation profitable. 8990 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) { 8991 StoreSDNode *ST = cast<StoreSDNode>(N); 8992 SDValue Chain = ST->getChain(); 8993 SDValue Value = ST->getValue(); 8994 if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) && 8995 Value.hasOneUse() && 8996 Chain == SDValue(Value.getNode(), 1)) { 8997 LoadSDNode *LD = cast<LoadSDNode>(Value); 8998 EVT VT = LD->getMemoryVT(); 8999 if (!VT.isFloatingPoint() || 9000 VT != ST->getMemoryVT() || 9001 LD->isNonTemporal() || 9002 ST->isNonTemporal() || 9003 LD->getPointerInfo().getAddrSpace() != 0 || 9004 ST->getPointerInfo().getAddrSpace() != 0) 9005 return SDValue(); 9006 9007 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits()); 9008 if (!TLI.isOperationLegal(ISD::LOAD, IntVT) || 9009 !TLI.isOperationLegal(ISD::STORE, IntVT) || 9010 !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) || 9011 !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT)) 9012 return SDValue(); 9013 9014 unsigned LDAlign = LD->getAlignment(); 9015 unsigned STAlign = ST->getAlignment(); 9016 Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext()); 9017 unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy); 9018 if (LDAlign < ABIAlign || STAlign < ABIAlign) 9019 return SDValue(); 9020 9021 SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value), 9022 LD->getChain(), LD->getBasePtr(), 9023 LD->getPointerInfo(), 9024 false, false, false, LDAlign); 9025 9026 SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N), 9027 NewLD, ST->getBasePtr(), 9028 ST->getPointerInfo(), 9029 false, false, STAlign); 9030 9031 AddToWorklist(NewLD.getNode()); 9032 AddToWorklist(NewST.getNode()); 9033 WorklistRemover DeadNodes(*this); 9034 DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1)); 9035 ++LdStFP2Int; 9036 return NewST; 9037 } 9038 9039 return SDValue(); 9040 } 9041 9042 /// Helper struct to parse and store a memory address as base + index + offset. 9043 /// We ignore sign extensions when it is safe to do so. 9044 /// The following two expressions are not equivalent. To differentiate we need 9045 /// to store whether there was a sign extension involved in the index 9046 /// computation. 9047 /// (load (i64 add (i64 copyfromreg %c) 9048 /// (i64 signextend (add (i8 load %index) 9049 /// (i8 1)))) 9050 /// vs 9051 /// 9052 /// (load (i64 add (i64 copyfromreg %c) 9053 /// (i64 signextend (i32 add (i32 signextend (i8 load %index)) 9054 /// (i32 1))))) 9055 struct BaseIndexOffset { 9056 SDValue Base; 9057 SDValue Index; 9058 int64_t Offset; 9059 bool IsIndexSignExt; 9060 9061 BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {} 9062 9063 BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset, 9064 bool IsIndexSignExt) : 9065 Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {} 9066 9067 bool equalBaseIndex(const BaseIndexOffset &Other) { 9068 return Other.Base == Base && Other.Index == Index && 9069 Other.IsIndexSignExt == IsIndexSignExt; 9070 } 9071 9072 /// Parses tree in Ptr for base, index, offset addresses. 9073 static BaseIndexOffset match(SDValue Ptr) { 9074 bool IsIndexSignExt = false; 9075 9076 // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD 9077 // instruction, then it could be just the BASE or everything else we don't 9078 // know how to handle. Just use Ptr as BASE and give up. 9079 if (Ptr->getOpcode() != ISD::ADD) 9080 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt); 9081 9082 // We know that we have at least an ADD instruction. Try to pattern match 9083 // the simple case of BASE + OFFSET. 9084 if (isa<ConstantSDNode>(Ptr->getOperand(1))) { 9085 int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue(); 9086 return BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset, 9087 IsIndexSignExt); 9088 } 9089 9090 // Inside a loop the current BASE pointer is calculated using an ADD and a 9091 // MUL instruction. In this case Ptr is the actual BASE pointer. 9092 // (i64 add (i64 %array_ptr) 9093 // (i64 mul (i64 %induction_var) 9094 // (i64 %element_size))) 9095 if (Ptr->getOperand(1)->getOpcode() == ISD::MUL) 9096 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt); 9097 9098 // Look at Base + Index + Offset cases. 9099 SDValue Base = Ptr->getOperand(0); 9100 SDValue IndexOffset = Ptr->getOperand(1); 9101 9102 // Skip signextends. 9103 if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) { 9104 IndexOffset = IndexOffset->getOperand(0); 9105 IsIndexSignExt = true; 9106 } 9107 9108 // Either the case of Base + Index (no offset) or something else. 9109 if (IndexOffset->getOpcode() != ISD::ADD) 9110 return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt); 9111 9112 // Now we have the case of Base + Index + offset. 9113 SDValue Index = IndexOffset->getOperand(0); 9114 SDValue Offset = IndexOffset->getOperand(1); 9115 9116 if (!isa<ConstantSDNode>(Offset)) 9117 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt); 9118 9119 // Ignore signextends. 9120 if (Index->getOpcode() == ISD::SIGN_EXTEND) { 9121 Index = Index->getOperand(0); 9122 IsIndexSignExt = true; 9123 } else IsIndexSignExt = false; 9124 9125 int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue(); 9126 return BaseIndexOffset(Base, Index, Off, IsIndexSignExt); 9127 } 9128 }; 9129 9130 /// Holds a pointer to an LSBaseSDNode as well as information on where it 9131 /// is located in a sequence of memory operations connected by a chain. 9132 struct MemOpLink { 9133 MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq): 9134 MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { } 9135 // Ptr to the mem node. 9136 LSBaseSDNode *MemNode; 9137 // Offset from the base ptr. 9138 int64_t OffsetFromBase; 9139 // What is the sequence number of this mem node. 9140 // Lowest mem operand in the DAG starts at zero. 9141 unsigned SequenceNum; 9142 }; 9143 9144 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) { 9145 EVT MemVT = St->getMemoryVT(); 9146 int64_t ElementSizeBytes = MemVT.getSizeInBits()/8; 9147 bool NoVectors = DAG.getMachineFunction().getFunction()->getAttributes(). 9148 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat); 9149 9150 // Don't merge vectors into wider inputs. 9151 if (MemVT.isVector() || !MemVT.isSimple()) 9152 return false; 9153 9154 // Perform an early exit check. Do not bother looking at stored values that 9155 // are not constants or loads. 9156 SDValue StoredVal = St->getValue(); 9157 bool IsLoadSrc = isa<LoadSDNode>(StoredVal); 9158 if (!isa<ConstantSDNode>(StoredVal) && !isa<ConstantFPSDNode>(StoredVal) && 9159 !IsLoadSrc) 9160 return false; 9161 9162 // Only look at ends of store sequences. 9163 SDValue Chain = SDValue(St, 0); 9164 if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE) 9165 return false; 9166 9167 // This holds the base pointer, index, and the offset in bytes from the base 9168 // pointer. 9169 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr()); 9170 9171 // We must have a base and an offset. 9172 if (!BasePtr.Base.getNode()) 9173 return false; 9174 9175 // Do not handle stores to undef base pointers. 9176 if (BasePtr.Base.getOpcode() == ISD::UNDEF) 9177 return false; 9178 9179 // Save the LoadSDNodes that we find in the chain. 9180 // We need to make sure that these nodes do not interfere with 9181 // any of the store nodes. 9182 SmallVector<LSBaseSDNode*, 8> AliasLoadNodes; 9183 9184 // Save the StoreSDNodes that we find in the chain. 9185 SmallVector<MemOpLink, 8> StoreNodes; 9186 9187 // Walk up the chain and look for nodes with offsets from the same 9188 // base pointer. Stop when reaching an instruction with a different kind 9189 // or instruction which has a different base pointer. 9190 unsigned Seq = 0; 9191 StoreSDNode *Index = St; 9192 while (Index) { 9193 // If the chain has more than one use, then we can't reorder the mem ops. 9194 if (Index != St && !SDValue(Index, 0)->hasOneUse()) 9195 break; 9196 9197 // Find the base pointer and offset for this memory node. 9198 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr()); 9199 9200 // Check that the base pointer is the same as the original one. 9201 if (!Ptr.equalBaseIndex(BasePtr)) 9202 break; 9203 9204 // Check that the alignment is the same. 9205 if (Index->getAlignment() != St->getAlignment()) 9206 break; 9207 9208 // The memory operands must not be volatile. 9209 if (Index->isVolatile() || Index->isIndexed()) 9210 break; 9211 9212 // No truncation. 9213 if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index)) 9214 if (St->isTruncatingStore()) 9215 break; 9216 9217 // The stored memory type must be the same. 9218 if (Index->getMemoryVT() != MemVT) 9219 break; 9220 9221 // We do not allow unaligned stores because we want to prevent overriding 9222 // stores. 9223 if (Index->getAlignment()*8 != MemVT.getSizeInBits()) 9224 break; 9225 9226 // We found a potential memory operand to merge. 9227 StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++)); 9228 9229 // Find the next memory operand in the chain. If the next operand in the 9230 // chain is a store then move up and continue the scan with the next 9231 // memory operand. If the next operand is a load save it and use alias 9232 // information to check if it interferes with anything. 9233 SDNode *NextInChain = Index->getChain().getNode(); 9234 while (1) { 9235 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) { 9236 // We found a store node. Use it for the next iteration. 9237 Index = STn; 9238 break; 9239 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) { 9240 if (Ldn->isVolatile()) { 9241 Index = nullptr; 9242 break; 9243 } 9244 9245 // Save the load node for later. Continue the scan. 9246 AliasLoadNodes.push_back(Ldn); 9247 NextInChain = Ldn->getChain().getNode(); 9248 continue; 9249 } else { 9250 Index = nullptr; 9251 break; 9252 } 9253 } 9254 } 9255 9256 // Check if there is anything to merge. 9257 if (StoreNodes.size() < 2) 9258 return false; 9259 9260 // Sort the memory operands according to their distance from the base pointer. 9261 std::sort(StoreNodes.begin(), StoreNodes.end(), 9262 [](MemOpLink LHS, MemOpLink RHS) { 9263 return LHS.OffsetFromBase < RHS.OffsetFromBase || 9264 (LHS.OffsetFromBase == RHS.OffsetFromBase && 9265 LHS.SequenceNum > RHS.SequenceNum); 9266 }); 9267 9268 // Scan the memory operations on the chain and find the first non-consecutive 9269 // store memory address. 9270 unsigned LastConsecutiveStore = 0; 9271 int64_t StartAddress = StoreNodes[0].OffsetFromBase; 9272 for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) { 9273 9274 // Check that the addresses are consecutive starting from the second 9275 // element in the list of stores. 9276 if (i > 0) { 9277 int64_t CurrAddress = StoreNodes[i].OffsetFromBase; 9278 if (CurrAddress - StartAddress != (ElementSizeBytes * i)) 9279 break; 9280 } 9281 9282 bool Alias = false; 9283 // Check if this store interferes with any of the loads that we found. 9284 for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld) 9285 if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) { 9286 Alias = true; 9287 break; 9288 } 9289 // We found a load that alias with this store. Stop the sequence. 9290 if (Alias) 9291 break; 9292 9293 // Mark this node as useful. 9294 LastConsecutiveStore = i; 9295 } 9296 9297 // The node with the lowest store address. 9298 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode; 9299 9300 // Store the constants into memory as one consecutive store. 9301 if (!IsLoadSrc) { 9302 unsigned LastLegalType = 0; 9303 unsigned LastLegalVectorType = 0; 9304 bool NonZero = false; 9305 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) { 9306 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 9307 SDValue StoredVal = St->getValue(); 9308 9309 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) { 9310 NonZero |= !C->isNullValue(); 9311 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) { 9312 NonZero |= !C->getConstantFPValue()->isNullValue(); 9313 } else { 9314 // Non-constant. 9315 break; 9316 } 9317 9318 // Find a legal type for the constant store. 9319 unsigned StoreBW = (i+1) * ElementSizeBytes * 8; 9320 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW); 9321 if (TLI.isTypeLegal(StoreTy)) 9322 LastLegalType = i+1; 9323 // Or check whether a truncstore is legal. 9324 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) == 9325 TargetLowering::TypePromoteInteger) { 9326 EVT LegalizedStoredValueTy = 9327 TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType()); 9328 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy)) 9329 LastLegalType = i+1; 9330 } 9331 9332 // Find a legal type for the vector store. 9333 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1); 9334 if (TLI.isTypeLegal(Ty)) 9335 LastLegalVectorType = i + 1; 9336 } 9337 9338 // We only use vectors if the constant is known to be zero and the 9339 // function is not marked with the noimplicitfloat attribute. 9340 if (NonZero || NoVectors) 9341 LastLegalVectorType = 0; 9342 9343 // Check if we found a legal integer type to store. 9344 if (LastLegalType == 0 && LastLegalVectorType == 0) 9345 return false; 9346 9347 bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors; 9348 unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType; 9349 9350 // Make sure we have something to merge. 9351 if (NumElem < 2) 9352 return false; 9353 9354 unsigned EarliestNodeUsed = 0; 9355 for (unsigned i=0; i < NumElem; ++i) { 9356 // Find a chain for the new wide-store operand. Notice that some 9357 // of the store nodes that we found may not be selected for inclusion 9358 // in the wide store. The chain we use needs to be the chain of the 9359 // earliest store node which is *used* and replaced by the wide store. 9360 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum) 9361 EarliestNodeUsed = i; 9362 } 9363 9364 // The earliest Node in the DAG. 9365 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode; 9366 SDLoc DL(StoreNodes[0].MemNode); 9367 9368 SDValue StoredVal; 9369 if (UseVector) { 9370 // Find a legal type for the vector store. 9371 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem); 9372 assert(TLI.isTypeLegal(Ty) && "Illegal vector store"); 9373 StoredVal = DAG.getConstant(0, Ty); 9374 } else { 9375 unsigned StoreBW = NumElem * ElementSizeBytes * 8; 9376 APInt StoreInt(StoreBW, 0); 9377 9378 // Construct a single integer constant which is made of the smaller 9379 // constant inputs. 9380 bool IsLE = TLI.isLittleEndian(); 9381 for (unsigned i = 0; i < NumElem ; ++i) { 9382 unsigned Idx = IsLE ?(NumElem - 1 - i) : i; 9383 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[Idx].MemNode); 9384 SDValue Val = St->getValue(); 9385 StoreInt<<=ElementSizeBytes*8; 9386 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) { 9387 StoreInt|=C->getAPIntValue().zext(StoreBW); 9388 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) { 9389 StoreInt|= C->getValueAPF().bitcastToAPInt().zext(StoreBW); 9390 } else { 9391 assert(false && "Invalid constant element type"); 9392 } 9393 } 9394 9395 // Create the new Load and Store operations. 9396 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW); 9397 StoredVal = DAG.getConstant(StoreInt, StoreTy); 9398 } 9399 9400 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), DL, StoredVal, 9401 FirstInChain->getBasePtr(), 9402 FirstInChain->getPointerInfo(), 9403 false, false, 9404 FirstInChain->getAlignment()); 9405 9406 // Replace the first store with the new store 9407 CombineTo(EarliestOp, NewStore); 9408 // Erase all other stores. 9409 for (unsigned i = 0; i < NumElem ; ++i) { 9410 if (StoreNodes[i].MemNode == EarliestOp) 9411 continue; 9412 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 9413 // ReplaceAllUsesWith will replace all uses that existed when it was 9414 // called, but graph optimizations may cause new ones to appear. For 9415 // example, the case in pr14333 looks like 9416 // 9417 // St's chain -> St -> another store -> X 9418 // 9419 // And the only difference from St to the other store is the chain. 9420 // When we change it's chain to be St's chain they become identical, 9421 // get CSEed and the net result is that X is now a use of St. 9422 // Since we know that St is redundant, just iterate. 9423 while (!St->use_empty()) 9424 DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain()); 9425 deleteAndRecombine(St); 9426 } 9427 9428 return true; 9429 } 9430 9431 // Below we handle the case of multiple consecutive stores that 9432 // come from multiple consecutive loads. We merge them into a single 9433 // wide load and a single wide store. 9434 9435 // Look for load nodes which are used by the stored values. 9436 SmallVector<MemOpLink, 8> LoadNodes; 9437 9438 // Find acceptable loads. Loads need to have the same chain (token factor), 9439 // must not be zext, volatile, indexed, and they must be consecutive. 9440 BaseIndexOffset LdBasePtr; 9441 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) { 9442 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 9443 LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue()); 9444 if (!Ld) break; 9445 9446 // Loads must only have one use. 9447 if (!Ld->hasNUsesOfValue(1, 0)) 9448 break; 9449 9450 // Check that the alignment is the same as the stores. 9451 if (Ld->getAlignment() != St->getAlignment()) 9452 break; 9453 9454 // The memory operands must not be volatile. 9455 if (Ld->isVolatile() || Ld->isIndexed()) 9456 break; 9457 9458 // We do not accept ext loads. 9459 if (Ld->getExtensionType() != ISD::NON_EXTLOAD) 9460 break; 9461 9462 // The stored memory type must be the same. 9463 if (Ld->getMemoryVT() != MemVT) 9464 break; 9465 9466 BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr()); 9467 // If this is not the first ptr that we check. 9468 if (LdBasePtr.Base.getNode()) { 9469 // The base ptr must be the same. 9470 if (!LdPtr.equalBaseIndex(LdBasePtr)) 9471 break; 9472 } else { 9473 // Check that all other base pointers are the same as this one. 9474 LdBasePtr = LdPtr; 9475 } 9476 9477 // We found a potential memory operand to merge. 9478 LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0)); 9479 } 9480 9481 if (LoadNodes.size() < 2) 9482 return false; 9483 9484 // If we have load/store pair instructions and we only have two values, 9485 // don't bother. 9486 unsigned RequiredAlignment; 9487 if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) && 9488 St->getAlignment() >= RequiredAlignment) 9489 return false; 9490 9491 // Scan the memory operations on the chain and find the first non-consecutive 9492 // load memory address. These variables hold the index in the store node 9493 // array. 9494 unsigned LastConsecutiveLoad = 0; 9495 // This variable refers to the size and not index in the array. 9496 unsigned LastLegalVectorType = 0; 9497 unsigned LastLegalIntegerType = 0; 9498 StartAddress = LoadNodes[0].OffsetFromBase; 9499 SDValue FirstChain = LoadNodes[0].MemNode->getChain(); 9500 for (unsigned i = 1; i < LoadNodes.size(); ++i) { 9501 // All loads much share the same chain. 9502 if (LoadNodes[i].MemNode->getChain() != FirstChain) 9503 break; 9504 9505 int64_t CurrAddress = LoadNodes[i].OffsetFromBase; 9506 if (CurrAddress - StartAddress != (ElementSizeBytes * i)) 9507 break; 9508 LastConsecutiveLoad = i; 9509 9510 // Find a legal type for the vector store. 9511 EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1); 9512 if (TLI.isTypeLegal(StoreTy)) 9513 LastLegalVectorType = i + 1; 9514 9515 // Find a legal type for the integer store. 9516 unsigned StoreBW = (i+1) * ElementSizeBytes * 8; 9517 StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW); 9518 if (TLI.isTypeLegal(StoreTy)) 9519 LastLegalIntegerType = i + 1; 9520 // Or check whether a truncstore and extload is legal. 9521 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) == 9522 TargetLowering::TypePromoteInteger) { 9523 EVT LegalizedStoredValueTy = 9524 TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy); 9525 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) && 9526 TLI.isLoadExtLegal(ISD::ZEXTLOAD, StoreTy) && 9527 TLI.isLoadExtLegal(ISD::SEXTLOAD, StoreTy) && 9528 TLI.isLoadExtLegal(ISD::EXTLOAD, StoreTy)) 9529 LastLegalIntegerType = i+1; 9530 } 9531 } 9532 9533 // Only use vector types if the vector type is larger than the integer type. 9534 // If they are the same, use integers. 9535 bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors; 9536 unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType); 9537 9538 // We add +1 here because the LastXXX variables refer to location while 9539 // the NumElem refers to array/index size. 9540 unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1; 9541 NumElem = std::min(LastLegalType, NumElem); 9542 9543 if (NumElem < 2) 9544 return false; 9545 9546 // The earliest Node in the DAG. 9547 unsigned EarliestNodeUsed = 0; 9548 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode; 9549 for (unsigned i=1; i<NumElem; ++i) { 9550 // Find a chain for the new wide-store operand. Notice that some 9551 // of the store nodes that we found may not be selected for inclusion 9552 // in the wide store. The chain we use needs to be the chain of the 9553 // earliest store node which is *used* and replaced by the wide store. 9554 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum) 9555 EarliestNodeUsed = i; 9556 } 9557 9558 // Find if it is better to use vectors or integers to load and store 9559 // to memory. 9560 EVT JointMemOpVT; 9561 if (UseVectorTy) { 9562 JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem); 9563 } else { 9564 unsigned StoreBW = NumElem * ElementSizeBytes * 8; 9565 JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW); 9566 } 9567 9568 SDLoc LoadDL(LoadNodes[0].MemNode); 9569 SDLoc StoreDL(StoreNodes[0].MemNode); 9570 9571 LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode); 9572 SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL, 9573 FirstLoad->getChain(), 9574 FirstLoad->getBasePtr(), 9575 FirstLoad->getPointerInfo(), 9576 false, false, false, 9577 FirstLoad->getAlignment()); 9578 9579 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), StoreDL, NewLoad, 9580 FirstInChain->getBasePtr(), 9581 FirstInChain->getPointerInfo(), false, false, 9582 FirstInChain->getAlignment()); 9583 9584 // Replace one of the loads with the new load. 9585 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode); 9586 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), 9587 SDValue(NewLoad.getNode(), 1)); 9588 9589 // Remove the rest of the load chains. 9590 for (unsigned i = 1; i < NumElem ; ++i) { 9591 // Replace all chain users of the old load nodes with the chain of the new 9592 // load node. 9593 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode); 9594 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain()); 9595 } 9596 9597 // Replace the first store with the new store. 9598 CombineTo(EarliestOp, NewStore); 9599 // Erase all other stores. 9600 for (unsigned i = 0; i < NumElem ; ++i) { 9601 // Remove all Store nodes. 9602 if (StoreNodes[i].MemNode == EarliestOp) 9603 continue; 9604 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 9605 DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain()); 9606 deleteAndRecombine(St); 9607 } 9608 9609 return true; 9610 } 9611 9612 SDValue DAGCombiner::visitSTORE(SDNode *N) { 9613 StoreSDNode *ST = cast<StoreSDNode>(N); 9614 SDValue Chain = ST->getChain(); 9615 SDValue Value = ST->getValue(); 9616 SDValue Ptr = ST->getBasePtr(); 9617 9618 // If this is a store of a bit convert, store the input value if the 9619 // resultant store does not need a higher alignment than the original. 9620 if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() && 9621 ST->isUnindexed()) { 9622 unsigned OrigAlign = ST->getAlignment(); 9623 EVT SVT = Value.getOperand(0).getValueType(); 9624 unsigned Align = TLI.getDataLayout()-> 9625 getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext())); 9626 if (Align <= OrigAlign && 9627 ((!LegalOperations && !ST->isVolatile()) || 9628 TLI.isOperationLegalOrCustom(ISD::STORE, SVT))) 9629 return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0), 9630 Ptr, ST->getPointerInfo(), ST->isVolatile(), 9631 ST->isNonTemporal(), OrigAlign, 9632 ST->getAAInfo()); 9633 } 9634 9635 // Turn 'store undef, Ptr' -> nothing. 9636 if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed()) 9637 return Chain; 9638 9639 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr' 9640 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) { 9641 // NOTE: If the original store is volatile, this transform must not increase 9642 // the number of stores. For example, on x86-32 an f64 can be stored in one 9643 // processor operation but an i64 (which is not legal) requires two. So the 9644 // transform should not be done in this case. 9645 if (Value.getOpcode() != ISD::TargetConstantFP) { 9646 SDValue Tmp; 9647 switch (CFP->getSimpleValueType(0).SimpleTy) { 9648 default: llvm_unreachable("Unknown FP type"); 9649 case MVT::f16: // We don't do this for these yet. 9650 case MVT::f80: 9651 case MVT::f128: 9652 case MVT::ppcf128: 9653 break; 9654 case MVT::f32: 9655 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) || 9656 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) { 9657 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF(). 9658 bitcastToAPInt().getZExtValue(), MVT::i32); 9659 return DAG.getStore(Chain, SDLoc(N), Tmp, 9660 Ptr, ST->getMemOperand()); 9661 } 9662 break; 9663 case MVT::f64: 9664 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations && 9665 !ST->isVolatile()) || 9666 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) { 9667 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt(). 9668 getZExtValue(), MVT::i64); 9669 return DAG.getStore(Chain, SDLoc(N), Tmp, 9670 Ptr, ST->getMemOperand()); 9671 } 9672 9673 if (!ST->isVolatile() && 9674 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) { 9675 // Many FP stores are not made apparent until after legalize, e.g. for 9676 // argument passing. Since this is so common, custom legalize the 9677 // 64-bit integer store into two 32-bit stores. 9678 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue(); 9679 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32); 9680 SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32); 9681 if (TLI.isBigEndian()) std::swap(Lo, Hi); 9682 9683 unsigned Alignment = ST->getAlignment(); 9684 bool isVolatile = ST->isVolatile(); 9685 bool isNonTemporal = ST->isNonTemporal(); 9686 AAMDNodes AAInfo = ST->getAAInfo(); 9687 9688 SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo, 9689 Ptr, ST->getPointerInfo(), 9690 isVolatile, isNonTemporal, 9691 ST->getAlignment(), AAInfo); 9692 Ptr = DAG.getNode(ISD::ADD, SDLoc(N), Ptr.getValueType(), Ptr, 9693 DAG.getConstant(4, Ptr.getValueType())); 9694 Alignment = MinAlign(Alignment, 4U); 9695 SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi, 9696 Ptr, ST->getPointerInfo().getWithOffset(4), 9697 isVolatile, isNonTemporal, 9698 Alignment, AAInfo); 9699 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, 9700 St0, St1); 9701 } 9702 9703 break; 9704 } 9705 } 9706 } 9707 9708 // Try to infer better alignment information than the store already has. 9709 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) { 9710 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) { 9711 if (Align > ST->getAlignment()) 9712 return DAG.getTruncStore(Chain, SDLoc(N), Value, 9713 Ptr, ST->getPointerInfo(), ST->getMemoryVT(), 9714 ST->isVolatile(), ST->isNonTemporal(), Align, 9715 ST->getAAInfo()); 9716 } 9717 } 9718 9719 // Try transforming a pair floating point load / store ops to integer 9720 // load / store ops. 9721 SDValue NewST = TransformFPLoadStorePair(N); 9722 if (NewST.getNode()) 9723 return NewST; 9724 9725 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA : 9726 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA(); 9727 #ifndef NDEBUG 9728 if (CombinerAAOnlyFunc.getNumOccurrences() && 9729 CombinerAAOnlyFunc != DAG.getMachineFunction().getName()) 9730 UseAA = false; 9731 #endif 9732 if (UseAA && ST->isUnindexed()) { 9733 // Walk up chain skipping non-aliasing memory nodes. 9734 SDValue BetterChain = FindBetterChain(N, Chain); 9735 9736 // If there is a better chain. 9737 if (Chain != BetterChain) { 9738 SDValue ReplStore; 9739 9740 // Replace the chain to avoid dependency. 9741 if (ST->isTruncatingStore()) { 9742 ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr, 9743 ST->getMemoryVT(), ST->getMemOperand()); 9744 } else { 9745 ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr, 9746 ST->getMemOperand()); 9747 } 9748 9749 // Create token to keep both nodes around. 9750 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N), 9751 MVT::Other, Chain, ReplStore); 9752 9753 // Make sure the new and old chains are cleaned up. 9754 AddToWorklist(Token.getNode()); 9755 9756 // Don't add users to work list. 9757 return CombineTo(N, Token, false); 9758 } 9759 } 9760 9761 // Try transforming N to an indexed store. 9762 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N)) 9763 return SDValue(N, 0); 9764 9765 // FIXME: is there such a thing as a truncating indexed store? 9766 if (ST->isTruncatingStore() && ST->isUnindexed() && 9767 Value.getValueType().isInteger()) { 9768 // See if we can simplify the input to this truncstore with knowledge that 9769 // only the low bits are being used. For example: 9770 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8" 9771 SDValue Shorter = 9772 GetDemandedBits(Value, 9773 APInt::getLowBitsSet( 9774 Value.getValueType().getScalarType().getSizeInBits(), 9775 ST->getMemoryVT().getScalarType().getSizeInBits())); 9776 AddToWorklist(Value.getNode()); 9777 if (Shorter.getNode()) 9778 return DAG.getTruncStore(Chain, SDLoc(N), Shorter, 9779 Ptr, ST->getMemoryVT(), ST->getMemOperand()); 9780 9781 // Otherwise, see if we can simplify the operation with 9782 // SimplifyDemandedBits, which only works if the value has a single use. 9783 if (SimplifyDemandedBits(Value, 9784 APInt::getLowBitsSet( 9785 Value.getValueType().getScalarType().getSizeInBits(), 9786 ST->getMemoryVT().getScalarType().getSizeInBits()))) 9787 return SDValue(N, 0); 9788 } 9789 9790 // If this is a load followed by a store to the same location, then the store 9791 // is dead/noop. 9792 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) { 9793 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() && 9794 ST->isUnindexed() && !ST->isVolatile() && 9795 // There can't be any side effects between the load and store, such as 9796 // a call or store. 9797 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) { 9798 // The store is dead, remove it. 9799 return Chain; 9800 } 9801 } 9802 9803 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a 9804 // truncating store. We can do this even if this is already a truncstore. 9805 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE) 9806 && Value.getNode()->hasOneUse() && ST->isUnindexed() && 9807 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(), 9808 ST->getMemoryVT())) { 9809 return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0), 9810 Ptr, ST->getMemoryVT(), ST->getMemOperand()); 9811 } 9812 9813 // Only perform this optimization before the types are legal, because we 9814 // don't want to perform this optimization on every DAGCombine invocation. 9815 if (!LegalTypes) { 9816 bool EverChanged = false; 9817 9818 do { 9819 // There can be multiple store sequences on the same chain. 9820 // Keep trying to merge store sequences until we are unable to do so 9821 // or until we merge the last store on the chain. 9822 bool Changed = MergeConsecutiveStores(ST); 9823 EverChanged |= Changed; 9824 if (!Changed) break; 9825 } while (ST->getOpcode() != ISD::DELETED_NODE); 9826 9827 if (EverChanged) 9828 return SDValue(N, 0); 9829 } 9830 9831 return ReduceLoadOpStoreWidth(N); 9832 } 9833 9834 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) { 9835 SDValue InVec = N->getOperand(0); 9836 SDValue InVal = N->getOperand(1); 9837 SDValue EltNo = N->getOperand(2); 9838 SDLoc dl(N); 9839 9840 // If the inserted element is an UNDEF, just use the input vector. 9841 if (InVal.getOpcode() == ISD::UNDEF) 9842 return InVec; 9843 9844 EVT VT = InVec.getValueType(); 9845 9846 // If we can't generate a legal BUILD_VECTOR, exit 9847 if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT)) 9848 return SDValue(); 9849 9850 // Check that we know which element is being inserted 9851 if (!isa<ConstantSDNode>(EltNo)) 9852 return SDValue(); 9853 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue(); 9854 9855 // Canonicalize insert_vector_elt dag nodes. 9856 // Example: 9857 // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1) 9858 // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0) 9859 // 9860 // Do this only if the child insert_vector node has one use; also 9861 // do this only if indices are both constants and Idx1 < Idx0. 9862 if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse() 9863 && isa<ConstantSDNode>(InVec.getOperand(2))) { 9864 unsigned OtherElt = 9865 cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue(); 9866 if (Elt < OtherElt) { 9867 // Swap nodes. 9868 SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT, 9869 InVec.getOperand(0), InVal, EltNo); 9870 AddToWorklist(NewOp.getNode()); 9871 return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()), 9872 VT, NewOp, InVec.getOperand(1), InVec.getOperand(2)); 9873 } 9874 } 9875 9876 // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially 9877 // be converted to a BUILD_VECTOR). Fill in the Ops vector with the 9878 // vector elements. 9879 SmallVector<SDValue, 8> Ops; 9880 // Do not combine these two vectors if the output vector will not replace 9881 // the input vector. 9882 if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) { 9883 Ops.append(InVec.getNode()->op_begin(), 9884 InVec.getNode()->op_end()); 9885 } else if (InVec.getOpcode() == ISD::UNDEF) { 9886 unsigned NElts = VT.getVectorNumElements(); 9887 Ops.append(NElts, DAG.getUNDEF(InVal.getValueType())); 9888 } else { 9889 return SDValue(); 9890 } 9891 9892 // Insert the element 9893 if (Elt < Ops.size()) { 9894 // All the operands of BUILD_VECTOR must have the same type; 9895 // we enforce that here. 9896 EVT OpVT = Ops[0].getValueType(); 9897 if (InVal.getValueType() != OpVT) 9898 InVal = OpVT.bitsGT(InVal.getValueType()) ? 9899 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) : 9900 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal); 9901 Ops[Elt] = InVal; 9902 } 9903 9904 // Return the new vector 9905 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops); 9906 } 9907 9908 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad( 9909 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) { 9910 EVT ResultVT = EVE->getValueType(0); 9911 EVT VecEltVT = InVecVT.getVectorElementType(); 9912 unsigned Align = OriginalLoad->getAlignment(); 9913 unsigned NewAlign = TLI.getDataLayout()->getABITypeAlignment( 9914 VecEltVT.getTypeForEVT(*DAG.getContext())); 9915 9916 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT)) 9917 return SDValue(); 9918 9919 Align = NewAlign; 9920 9921 SDValue NewPtr = OriginalLoad->getBasePtr(); 9922 SDValue Offset; 9923 EVT PtrType = NewPtr.getValueType(); 9924 MachinePointerInfo MPI; 9925 if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) { 9926 int Elt = ConstEltNo->getZExtValue(); 9927 unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8; 9928 if (TLI.isBigEndian()) 9929 PtrOff = InVecVT.getSizeInBits() / 8 - PtrOff; 9930 Offset = DAG.getConstant(PtrOff, PtrType); 9931 MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff); 9932 } else { 9933 Offset = DAG.getNode( 9934 ISD::MUL, SDLoc(EVE), EltNo.getValueType(), EltNo, 9935 DAG.getConstant(VecEltVT.getStoreSize(), EltNo.getValueType())); 9936 if (TLI.isBigEndian()) 9937 Offset = DAG.getNode( 9938 ISD::SUB, SDLoc(EVE), EltNo.getValueType(), 9939 DAG.getConstant(InVecVT.getStoreSize(), EltNo.getValueType()), Offset); 9940 MPI = OriginalLoad->getPointerInfo(); 9941 } 9942 NewPtr = DAG.getNode(ISD::ADD, SDLoc(EVE), PtrType, NewPtr, Offset); 9943 9944 // The replacement we need to do here is a little tricky: we need to 9945 // replace an extractelement of a load with a load. 9946 // Use ReplaceAllUsesOfValuesWith to do the replacement. 9947 // Note that this replacement assumes that the extractvalue is the only 9948 // use of the load; that's okay because we don't want to perform this 9949 // transformation in other cases anyway. 9950 SDValue Load; 9951 SDValue Chain; 9952 if (ResultVT.bitsGT(VecEltVT)) { 9953 // If the result type of vextract is wider than the load, then issue an 9954 // extending load instead. 9955 ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, VecEltVT) 9956 ? ISD::ZEXTLOAD 9957 : ISD::EXTLOAD; 9958 Load = DAG.getExtLoad( 9959 ExtType, SDLoc(EVE), ResultVT, OriginalLoad->getChain(), NewPtr, MPI, 9960 VecEltVT, OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(), 9961 OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo()); 9962 Chain = Load.getValue(1); 9963 } else { 9964 Load = DAG.getLoad( 9965 VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, MPI, 9966 OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(), 9967 OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo()); 9968 Chain = Load.getValue(1); 9969 if (ResultVT.bitsLT(VecEltVT)) 9970 Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load); 9971 else 9972 Load = DAG.getNode(ISD::BITCAST, SDLoc(EVE), ResultVT, Load); 9973 } 9974 WorklistRemover DeadNodes(*this); 9975 SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) }; 9976 SDValue To[] = { Load, Chain }; 9977 DAG.ReplaceAllUsesOfValuesWith(From, To, 2); 9978 // Since we're explicitly calling ReplaceAllUses, add the new node to the 9979 // worklist explicitly as well. 9980 AddToWorklist(Load.getNode()); 9981 AddUsersToWorklist(Load.getNode()); // Add users too 9982 // Make sure to revisit this node to clean it up; it will usually be dead. 9983 AddToWorklist(EVE); 9984 ++OpsNarrowed; 9985 return SDValue(EVE, 0); 9986 } 9987 9988 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) { 9989 // (vextract (scalar_to_vector val, 0) -> val 9990 SDValue InVec = N->getOperand(0); 9991 EVT VT = InVec.getValueType(); 9992 EVT NVT = N->getValueType(0); 9993 9994 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) { 9995 // Check if the result type doesn't match the inserted element type. A 9996 // SCALAR_TO_VECTOR may truncate the inserted element and the 9997 // EXTRACT_VECTOR_ELT may widen the extracted vector. 9998 SDValue InOp = InVec.getOperand(0); 9999 if (InOp.getValueType() != NVT) { 10000 assert(InOp.getValueType().isInteger() && NVT.isInteger()); 10001 return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT); 10002 } 10003 return InOp; 10004 } 10005 10006 SDValue EltNo = N->getOperand(1); 10007 bool ConstEltNo = isa<ConstantSDNode>(EltNo); 10008 10009 // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT. 10010 // We only perform this optimization before the op legalization phase because 10011 // we may introduce new vector instructions which are not backed by TD 10012 // patterns. For example on AVX, extracting elements from a wide vector 10013 // without using extract_subvector. However, if we can find an underlying 10014 // scalar value, then we can always use that. 10015 if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE 10016 && ConstEltNo) { 10017 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue(); 10018 int NumElem = VT.getVectorNumElements(); 10019 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec); 10020 // Find the new index to extract from. 10021 int OrigElt = SVOp->getMaskElt(Elt); 10022 10023 // Extracting an undef index is undef. 10024 if (OrigElt == -1) 10025 return DAG.getUNDEF(NVT); 10026 10027 // Select the right vector half to extract from. 10028 SDValue SVInVec; 10029 if (OrigElt < NumElem) { 10030 SVInVec = InVec->getOperand(0); 10031 } else { 10032 SVInVec = InVec->getOperand(1); 10033 OrigElt -= NumElem; 10034 } 10035 10036 if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) { 10037 SDValue InOp = SVInVec.getOperand(OrigElt); 10038 if (InOp.getValueType() != NVT) { 10039 assert(InOp.getValueType().isInteger() && NVT.isInteger()); 10040 InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT); 10041 } 10042 10043 return InOp; 10044 } 10045 10046 // FIXME: We should handle recursing on other vector shuffles and 10047 // scalar_to_vector here as well. 10048 10049 if (!LegalOperations) { 10050 EVT IndexTy = TLI.getVectorIdxTy(); 10051 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT, 10052 SVInVec, DAG.getConstant(OrigElt, IndexTy)); 10053 } 10054 } 10055 10056 bool BCNumEltsChanged = false; 10057 EVT ExtVT = VT.getVectorElementType(); 10058 EVT LVT = ExtVT; 10059 10060 // If the result of load has to be truncated, then it's not necessarily 10061 // profitable. 10062 if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT)) 10063 return SDValue(); 10064 10065 if (InVec.getOpcode() == ISD::BITCAST) { 10066 // Don't duplicate a load with other uses. 10067 if (!InVec.hasOneUse()) 10068 return SDValue(); 10069 10070 EVT BCVT = InVec.getOperand(0).getValueType(); 10071 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType())) 10072 return SDValue(); 10073 if (VT.getVectorNumElements() != BCVT.getVectorNumElements()) 10074 BCNumEltsChanged = true; 10075 InVec = InVec.getOperand(0); 10076 ExtVT = BCVT.getVectorElementType(); 10077 } 10078 10079 // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size) 10080 if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() && 10081 ISD::isNormalLoad(InVec.getNode()) && 10082 !N->getOperand(1)->hasPredecessor(InVec.getNode())) { 10083 SDValue Index = N->getOperand(1); 10084 if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec)) 10085 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index, 10086 OrigLoad); 10087 } 10088 10089 // Perform only after legalization to ensure build_vector / vector_shuffle 10090 // optimizations have already been done. 10091 if (!LegalOperations) return SDValue(); 10092 10093 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size) 10094 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size) 10095 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr) 10096 10097 if (ConstEltNo) { 10098 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue(); 10099 10100 LoadSDNode *LN0 = nullptr; 10101 const ShuffleVectorSDNode *SVN = nullptr; 10102 if (ISD::isNormalLoad(InVec.getNode())) { 10103 LN0 = cast<LoadSDNode>(InVec); 10104 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR && 10105 InVec.getOperand(0).getValueType() == ExtVT && 10106 ISD::isNormalLoad(InVec.getOperand(0).getNode())) { 10107 // Don't duplicate a load with other uses. 10108 if (!InVec.hasOneUse()) 10109 return SDValue(); 10110 10111 LN0 = cast<LoadSDNode>(InVec.getOperand(0)); 10112 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) { 10113 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1) 10114 // => 10115 // (load $addr+1*size) 10116 10117 // Don't duplicate a load with other uses. 10118 if (!InVec.hasOneUse()) 10119 return SDValue(); 10120 10121 // If the bit convert changed the number of elements, it is unsafe 10122 // to examine the mask. 10123 if (BCNumEltsChanged) 10124 return SDValue(); 10125 10126 // Select the input vector, guarding against out of range extract vector. 10127 unsigned NumElems = VT.getVectorNumElements(); 10128 int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt); 10129 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1); 10130 10131 if (InVec.getOpcode() == ISD::BITCAST) { 10132 // Don't duplicate a load with other uses. 10133 if (!InVec.hasOneUse()) 10134 return SDValue(); 10135 10136 InVec = InVec.getOperand(0); 10137 } 10138 if (ISD::isNormalLoad(InVec.getNode())) { 10139 LN0 = cast<LoadSDNode>(InVec); 10140 Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems; 10141 EltNo = DAG.getConstant(Elt, EltNo.getValueType()); 10142 } 10143 } 10144 10145 // Make sure we found a non-volatile load and the extractelement is 10146 // the only use. 10147 if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile()) 10148 return SDValue(); 10149 10150 // If Idx was -1 above, Elt is going to be -1, so just return undef. 10151 if (Elt == -1) 10152 return DAG.getUNDEF(LVT); 10153 10154 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0); 10155 } 10156 10157 return SDValue(); 10158 } 10159 10160 // Simplify (build_vec (ext )) to (bitcast (build_vec )) 10161 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) { 10162 // We perform this optimization post type-legalization because 10163 // the type-legalizer often scalarizes integer-promoted vectors. 10164 // Performing this optimization before may create bit-casts which 10165 // will be type-legalized to complex code sequences. 10166 // We perform this optimization only before the operation legalizer because we 10167 // may introduce illegal operations. 10168 if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes) 10169 return SDValue(); 10170 10171 unsigned NumInScalars = N->getNumOperands(); 10172 SDLoc dl(N); 10173 EVT VT = N->getValueType(0); 10174 10175 // Check to see if this is a BUILD_VECTOR of a bunch of values 10176 // which come from any_extend or zero_extend nodes. If so, we can create 10177 // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR 10178 // optimizations. We do not handle sign-extend because we can't fill the sign 10179 // using shuffles. 10180 EVT SourceType = MVT::Other; 10181 bool AllAnyExt = true; 10182 10183 for (unsigned i = 0; i != NumInScalars; ++i) { 10184 SDValue In = N->getOperand(i); 10185 // Ignore undef inputs. 10186 if (In.getOpcode() == ISD::UNDEF) continue; 10187 10188 bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND; 10189 bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND; 10190 10191 // Abort if the element is not an extension. 10192 if (!ZeroExt && !AnyExt) { 10193 SourceType = MVT::Other; 10194 break; 10195 } 10196 10197 // The input is a ZeroExt or AnyExt. Check the original type. 10198 EVT InTy = In.getOperand(0).getValueType(); 10199 10200 // Check that all of the widened source types are the same. 10201 if (SourceType == MVT::Other) 10202 // First time. 10203 SourceType = InTy; 10204 else if (InTy != SourceType) { 10205 // Multiple income types. Abort. 10206 SourceType = MVT::Other; 10207 break; 10208 } 10209 10210 // Check if all of the extends are ANY_EXTENDs. 10211 AllAnyExt &= AnyExt; 10212 } 10213 10214 // In order to have valid types, all of the inputs must be extended from the 10215 // same source type and all of the inputs must be any or zero extend. 10216 // Scalar sizes must be a power of two. 10217 EVT OutScalarTy = VT.getScalarType(); 10218 bool ValidTypes = SourceType != MVT::Other && 10219 isPowerOf2_32(OutScalarTy.getSizeInBits()) && 10220 isPowerOf2_32(SourceType.getSizeInBits()); 10221 10222 // Create a new simpler BUILD_VECTOR sequence which other optimizations can 10223 // turn into a single shuffle instruction. 10224 if (!ValidTypes) 10225 return SDValue(); 10226 10227 bool isLE = TLI.isLittleEndian(); 10228 unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits(); 10229 assert(ElemRatio > 1 && "Invalid element size ratio"); 10230 SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType): 10231 DAG.getConstant(0, SourceType); 10232 10233 unsigned NewBVElems = ElemRatio * VT.getVectorNumElements(); 10234 SmallVector<SDValue, 8> Ops(NewBVElems, Filler); 10235 10236 // Populate the new build_vector 10237 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 10238 SDValue Cast = N->getOperand(i); 10239 assert((Cast.getOpcode() == ISD::ANY_EXTEND || 10240 Cast.getOpcode() == ISD::ZERO_EXTEND || 10241 Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode"); 10242 SDValue In; 10243 if (Cast.getOpcode() == ISD::UNDEF) 10244 In = DAG.getUNDEF(SourceType); 10245 else 10246 In = Cast->getOperand(0); 10247 unsigned Index = isLE ? (i * ElemRatio) : 10248 (i * ElemRatio + (ElemRatio - 1)); 10249 10250 assert(Index < Ops.size() && "Invalid index"); 10251 Ops[Index] = In; 10252 } 10253 10254 // The type of the new BUILD_VECTOR node. 10255 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems); 10256 assert(VecVT.getSizeInBits() == VT.getSizeInBits() && 10257 "Invalid vector size"); 10258 // Check if the new vector type is legal. 10259 if (!isTypeLegal(VecVT)) return SDValue(); 10260 10261 // Make the new BUILD_VECTOR. 10262 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops); 10263 10264 // The new BUILD_VECTOR node has the potential to be further optimized. 10265 AddToWorklist(BV.getNode()); 10266 // Bitcast to the desired type. 10267 return DAG.getNode(ISD::BITCAST, dl, VT, BV); 10268 } 10269 10270 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) { 10271 EVT VT = N->getValueType(0); 10272 10273 unsigned NumInScalars = N->getNumOperands(); 10274 SDLoc dl(N); 10275 10276 EVT SrcVT = MVT::Other; 10277 unsigned Opcode = ISD::DELETED_NODE; 10278 unsigned NumDefs = 0; 10279 10280 for (unsigned i = 0; i != NumInScalars; ++i) { 10281 SDValue In = N->getOperand(i); 10282 unsigned Opc = In.getOpcode(); 10283 10284 if (Opc == ISD::UNDEF) 10285 continue; 10286 10287 // If all scalar values are floats and converted from integers. 10288 if (Opcode == ISD::DELETED_NODE && 10289 (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) { 10290 Opcode = Opc; 10291 } 10292 10293 if (Opc != Opcode) 10294 return SDValue(); 10295 10296 EVT InVT = In.getOperand(0).getValueType(); 10297 10298 // If all scalar values are typed differently, bail out. It's chosen to 10299 // simplify BUILD_VECTOR of integer types. 10300 if (SrcVT == MVT::Other) 10301 SrcVT = InVT; 10302 if (SrcVT != InVT) 10303 return SDValue(); 10304 NumDefs++; 10305 } 10306 10307 // If the vector has just one element defined, it's not worth to fold it into 10308 // a vectorized one. 10309 if (NumDefs < 2) 10310 return SDValue(); 10311 10312 assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP) 10313 && "Should only handle conversion from integer to float."); 10314 assert(SrcVT != MVT::Other && "Cannot determine source type!"); 10315 10316 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars); 10317 10318 if (!TLI.isOperationLegalOrCustom(Opcode, NVT)) 10319 return SDValue(); 10320 10321 SmallVector<SDValue, 8> Opnds; 10322 for (unsigned i = 0; i != NumInScalars; ++i) { 10323 SDValue In = N->getOperand(i); 10324 10325 if (In.getOpcode() == ISD::UNDEF) 10326 Opnds.push_back(DAG.getUNDEF(SrcVT)); 10327 else 10328 Opnds.push_back(In.getOperand(0)); 10329 } 10330 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds); 10331 AddToWorklist(BV.getNode()); 10332 10333 return DAG.getNode(Opcode, dl, VT, BV); 10334 } 10335 10336 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) { 10337 unsigned NumInScalars = N->getNumOperands(); 10338 SDLoc dl(N); 10339 EVT VT = N->getValueType(0); 10340 10341 // A vector built entirely of undefs is undef. 10342 if (ISD::allOperandsUndef(N)) 10343 return DAG.getUNDEF(VT); 10344 10345 SDValue V = reduceBuildVecExtToExtBuildVec(N); 10346 if (V.getNode()) 10347 return V; 10348 10349 V = reduceBuildVecConvertToConvertBuildVec(N); 10350 if (V.getNode()) 10351 return V; 10352 10353 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT 10354 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from 10355 // at most two distinct vectors, turn this into a shuffle node. 10356 10357 // May only combine to shuffle after legalize if shuffle is legal. 10358 if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT)) 10359 return SDValue(); 10360 10361 SDValue VecIn1, VecIn2; 10362 for (unsigned i = 0; i != NumInScalars; ++i) { 10363 // Ignore undef inputs. 10364 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue; 10365 10366 // If this input is something other than a EXTRACT_VECTOR_ELT with a 10367 // constant index, bail out. 10368 if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT || 10369 !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) { 10370 VecIn1 = VecIn2 = SDValue(nullptr, 0); 10371 break; 10372 } 10373 10374 // We allow up to two distinct input vectors. 10375 SDValue ExtractedFromVec = N->getOperand(i).getOperand(0); 10376 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2) 10377 continue; 10378 10379 if (!VecIn1.getNode()) { 10380 VecIn1 = ExtractedFromVec; 10381 } else if (!VecIn2.getNode()) { 10382 VecIn2 = ExtractedFromVec; 10383 } else { 10384 // Too many inputs. 10385 VecIn1 = VecIn2 = SDValue(nullptr, 0); 10386 break; 10387 } 10388 } 10389 10390 // If everything is good, we can make a shuffle operation. 10391 if (VecIn1.getNode()) { 10392 SmallVector<int, 8> Mask; 10393 for (unsigned i = 0; i != NumInScalars; ++i) { 10394 if (N->getOperand(i).getOpcode() == ISD::UNDEF) { 10395 Mask.push_back(-1); 10396 continue; 10397 } 10398 10399 // If extracting from the first vector, just use the index directly. 10400 SDValue Extract = N->getOperand(i); 10401 SDValue ExtVal = Extract.getOperand(1); 10402 if (Extract.getOperand(0) == VecIn1) { 10403 unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue(); 10404 if (ExtIndex > VT.getVectorNumElements()) 10405 return SDValue(); 10406 10407 Mask.push_back(ExtIndex); 10408 continue; 10409 } 10410 10411 // Otherwise, use InIdx + VecSize 10412 unsigned Idx = cast<ConstantSDNode>(ExtVal)->getZExtValue(); 10413 Mask.push_back(Idx+NumInScalars); 10414 } 10415 10416 // We can't generate a shuffle node with mismatched input and output types. 10417 // Attempt to transform a single input vector to the correct type. 10418 if ((VT != VecIn1.getValueType())) { 10419 // We don't support shuffeling between TWO values of different types. 10420 if (VecIn2.getNode()) 10421 return SDValue(); 10422 10423 // We only support widening of vectors which are half the size of the 10424 // output registers. For example XMM->YMM widening on X86 with AVX. 10425 if (VecIn1.getValueType().getSizeInBits()*2 != VT.getSizeInBits()) 10426 return SDValue(); 10427 10428 // If the input vector type has a different base type to the output 10429 // vector type, bail out. 10430 if (VecIn1.getValueType().getVectorElementType() != 10431 VT.getVectorElementType()) 10432 return SDValue(); 10433 10434 // Widen the input vector by adding undef values. 10435 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, 10436 VecIn1, DAG.getUNDEF(VecIn1.getValueType())); 10437 } 10438 10439 // If VecIn2 is unused then change it to undef. 10440 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT); 10441 10442 // Check that we were able to transform all incoming values to the same 10443 // type. 10444 if (VecIn2.getValueType() != VecIn1.getValueType() || 10445 VecIn1.getValueType() != VT) 10446 return SDValue(); 10447 10448 // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes. 10449 if (!isTypeLegal(VT)) 10450 return SDValue(); 10451 10452 // Return the new VECTOR_SHUFFLE node. 10453 SDValue Ops[2]; 10454 Ops[0] = VecIn1; 10455 Ops[1] = VecIn2; 10456 return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]); 10457 } 10458 10459 return SDValue(); 10460 } 10461 10462 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) { 10463 // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of 10464 // EXTRACT_SUBVECTOR operations. If so, and if the EXTRACT_SUBVECTOR vector 10465 // inputs come from at most two distinct vectors, turn this into a shuffle 10466 // node. 10467 10468 // If we only have one input vector, we don't need to do any concatenation. 10469 if (N->getNumOperands() == 1) 10470 return N->getOperand(0); 10471 10472 // Check if all of the operands are undefs. 10473 EVT VT = N->getValueType(0); 10474 if (ISD::allOperandsUndef(N)) 10475 return DAG.getUNDEF(VT); 10476 10477 // Optimize concat_vectors where one of the vectors is undef. 10478 if (N->getNumOperands() == 2 && 10479 N->getOperand(1)->getOpcode() == ISD::UNDEF) { 10480 SDValue In = N->getOperand(0); 10481 assert(In.getValueType().isVector() && "Must concat vectors"); 10482 10483 // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr). 10484 if (In->getOpcode() == ISD::BITCAST && 10485 !In->getOperand(0)->getValueType(0).isVector()) { 10486 SDValue Scalar = In->getOperand(0); 10487 EVT SclTy = Scalar->getValueType(0); 10488 10489 if (!SclTy.isFloatingPoint() && !SclTy.isInteger()) 10490 return SDValue(); 10491 10492 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy, 10493 VT.getSizeInBits() / SclTy.getSizeInBits()); 10494 if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType())) 10495 return SDValue(); 10496 10497 SDLoc dl = SDLoc(N); 10498 SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar); 10499 return DAG.getNode(ISD::BITCAST, dl, VT, Res); 10500 } 10501 } 10502 10503 // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...)) 10504 // -> (BUILD_VECTOR A, B, ..., C, D, ...) 10505 if (N->getNumOperands() == 2 && 10506 N->getOperand(0).getOpcode() == ISD::BUILD_VECTOR && 10507 N->getOperand(1).getOpcode() == ISD::BUILD_VECTOR) { 10508 EVT VT = N->getValueType(0); 10509 SDValue N0 = N->getOperand(0); 10510 SDValue N1 = N->getOperand(1); 10511 SmallVector<SDValue, 8> Opnds; 10512 unsigned BuildVecNumElts = N0.getNumOperands(); 10513 10514 EVT SclTy0 = N0.getOperand(0)->getValueType(0); 10515 EVT SclTy1 = N1.getOperand(0)->getValueType(0); 10516 if (SclTy0.isFloatingPoint()) { 10517 for (unsigned i = 0; i != BuildVecNumElts; ++i) 10518 Opnds.push_back(N0.getOperand(i)); 10519 for (unsigned i = 0; i != BuildVecNumElts; ++i) 10520 Opnds.push_back(N1.getOperand(i)); 10521 } else { 10522 // If BUILD_VECTOR are from built from integer, they may have different 10523 // operand types. Get the smaller type and truncate all operands to it. 10524 EVT MinTy = SclTy0.bitsLE(SclTy1) ? SclTy0 : SclTy1; 10525 for (unsigned i = 0; i != BuildVecNumElts; ++i) 10526 Opnds.push_back(DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinTy, 10527 N0.getOperand(i))); 10528 for (unsigned i = 0; i != BuildVecNumElts; ++i) 10529 Opnds.push_back(DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinTy, 10530 N1.getOperand(i))); 10531 } 10532 10533 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds); 10534 } 10535 10536 // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR 10537 // nodes often generate nop CONCAT_VECTOR nodes. 10538 // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that 10539 // place the incoming vectors at the exact same location. 10540 SDValue SingleSource = SDValue(); 10541 unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements(); 10542 10543 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 10544 SDValue Op = N->getOperand(i); 10545 10546 if (Op.getOpcode() == ISD::UNDEF) 10547 continue; 10548 10549 // Check if this is the identity extract: 10550 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR) 10551 return SDValue(); 10552 10553 // Find the single incoming vector for the extract_subvector. 10554 if (SingleSource.getNode()) { 10555 if (Op.getOperand(0) != SingleSource) 10556 return SDValue(); 10557 } else { 10558 SingleSource = Op.getOperand(0); 10559 10560 // Check the source type is the same as the type of the result. 10561 // If not, this concat may extend the vector, so we can not 10562 // optimize it away. 10563 if (SingleSource.getValueType() != N->getValueType(0)) 10564 return SDValue(); 10565 } 10566 10567 unsigned IdentityIndex = i * PartNumElem; 10568 ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 10569 // The extract index must be constant. 10570 if (!CS) 10571 return SDValue(); 10572 10573 // Check that we are reading from the identity index. 10574 if (CS->getZExtValue() != IdentityIndex) 10575 return SDValue(); 10576 } 10577 10578 if (SingleSource.getNode()) 10579 return SingleSource; 10580 10581 return SDValue(); 10582 } 10583 10584 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) { 10585 EVT NVT = N->getValueType(0); 10586 SDValue V = N->getOperand(0); 10587 10588 if (V->getOpcode() == ISD::CONCAT_VECTORS) { 10589 // Combine: 10590 // (extract_subvec (concat V1, V2, ...), i) 10591 // Into: 10592 // Vi if possible 10593 // Only operand 0 is checked as 'concat' assumes all inputs of the same 10594 // type. 10595 if (V->getOperand(0).getValueType() != NVT) 10596 return SDValue(); 10597 unsigned Idx = dyn_cast<ConstantSDNode>(N->getOperand(1))->getZExtValue(); 10598 unsigned NumElems = NVT.getVectorNumElements(); 10599 assert((Idx % NumElems) == 0 && 10600 "IDX in concat is not a multiple of the result vector length."); 10601 return V->getOperand(Idx / NumElems); 10602 } 10603 10604 // Skip bitcasting 10605 if (V->getOpcode() == ISD::BITCAST) 10606 V = V.getOperand(0); 10607 10608 if (V->getOpcode() == ISD::INSERT_SUBVECTOR) { 10609 SDLoc dl(N); 10610 // Handle only simple case where vector being inserted and vector 10611 // being extracted are of same type, and are half size of larger vectors. 10612 EVT BigVT = V->getOperand(0).getValueType(); 10613 EVT SmallVT = V->getOperand(1).getValueType(); 10614 if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits()) 10615 return SDValue(); 10616 10617 // Only handle cases where both indexes are constants with the same type. 10618 ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1)); 10619 ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2)); 10620 10621 if (InsIdx && ExtIdx && 10622 InsIdx->getValueType(0).getSizeInBits() <= 64 && 10623 ExtIdx->getValueType(0).getSizeInBits() <= 64) { 10624 // Combine: 10625 // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx) 10626 // Into: 10627 // indices are equal or bit offsets are equal => V1 10628 // otherwise => (extract_subvec V1, ExtIdx) 10629 if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() == 10630 ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits()) 10631 return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1)); 10632 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT, 10633 DAG.getNode(ISD::BITCAST, dl, 10634 N->getOperand(0).getValueType(), 10635 V->getOperand(0)), N->getOperand(1)); 10636 } 10637 } 10638 10639 return SDValue(); 10640 } 10641 10642 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat. 10643 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) { 10644 EVT VT = N->getValueType(0); 10645 unsigned NumElts = VT.getVectorNumElements(); 10646 10647 SDValue N0 = N->getOperand(0); 10648 SDValue N1 = N->getOperand(1); 10649 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N); 10650 10651 SmallVector<SDValue, 4> Ops; 10652 EVT ConcatVT = N0.getOperand(0).getValueType(); 10653 unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements(); 10654 unsigned NumConcats = NumElts / NumElemsPerConcat; 10655 10656 // Look at every vector that's inserted. We're looking for exact 10657 // subvector-sized copies from a concatenated vector 10658 for (unsigned I = 0; I != NumConcats; ++I) { 10659 // Make sure we're dealing with a copy. 10660 unsigned Begin = I * NumElemsPerConcat; 10661 bool AllUndef = true, NoUndef = true; 10662 for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) { 10663 if (SVN->getMaskElt(J) >= 0) 10664 AllUndef = false; 10665 else 10666 NoUndef = false; 10667 } 10668 10669 if (NoUndef) { 10670 if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0) 10671 return SDValue(); 10672 10673 for (unsigned J = 1; J != NumElemsPerConcat; ++J) 10674 if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J)) 10675 return SDValue(); 10676 10677 unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat; 10678 if (FirstElt < N0.getNumOperands()) 10679 Ops.push_back(N0.getOperand(FirstElt)); 10680 else 10681 Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands())); 10682 10683 } else if (AllUndef) { 10684 Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType())); 10685 } else { // Mixed with general masks and undefs, can't do optimization. 10686 return SDValue(); 10687 } 10688 } 10689 10690 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops); 10691 } 10692 10693 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) { 10694 EVT VT = N->getValueType(0); 10695 unsigned NumElts = VT.getVectorNumElements(); 10696 10697 SDValue N0 = N->getOperand(0); 10698 SDValue N1 = N->getOperand(1); 10699 10700 assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG"); 10701 10702 // Canonicalize shuffle undef, undef -> undef 10703 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF) 10704 return DAG.getUNDEF(VT); 10705 10706 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N); 10707 10708 // Canonicalize shuffle v, v -> v, undef 10709 if (N0 == N1) { 10710 SmallVector<int, 8> NewMask; 10711 for (unsigned i = 0; i != NumElts; ++i) { 10712 int Idx = SVN->getMaskElt(i); 10713 if (Idx >= (int)NumElts) Idx -= NumElts; 10714 NewMask.push_back(Idx); 10715 } 10716 return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT), 10717 &NewMask[0]); 10718 } 10719 10720 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask. 10721 if (N0.getOpcode() == ISD::UNDEF) { 10722 SmallVector<int, 8> NewMask; 10723 for (unsigned i = 0; i != NumElts; ++i) { 10724 int Idx = SVN->getMaskElt(i); 10725 if (Idx >= 0) { 10726 if (Idx >= (int)NumElts) 10727 Idx -= NumElts; 10728 else 10729 Idx = -1; // remove reference to lhs 10730 } 10731 NewMask.push_back(Idx); 10732 } 10733 return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT), 10734 &NewMask[0]); 10735 } 10736 10737 // Remove references to rhs if it is undef 10738 if (N1.getOpcode() == ISD::UNDEF) { 10739 bool Changed = false; 10740 SmallVector<int, 8> NewMask; 10741 for (unsigned i = 0; i != NumElts; ++i) { 10742 int Idx = SVN->getMaskElt(i); 10743 if (Idx >= (int)NumElts) { 10744 Idx = -1; 10745 Changed = true; 10746 } 10747 NewMask.push_back(Idx); 10748 } 10749 if (Changed) 10750 return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]); 10751 } 10752 10753 // If it is a splat, check if the argument vector is another splat or a 10754 // build_vector with all scalar elements the same. 10755 if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) { 10756 SDNode *V = N0.getNode(); 10757 10758 // If this is a bit convert that changes the element type of the vector but 10759 // not the number of vector elements, look through it. Be careful not to 10760 // look though conversions that change things like v4f32 to v2f64. 10761 if (V->getOpcode() == ISD::BITCAST) { 10762 SDValue ConvInput = V->getOperand(0); 10763 if (ConvInput.getValueType().isVector() && 10764 ConvInput.getValueType().getVectorNumElements() == NumElts) 10765 V = ConvInput.getNode(); 10766 } 10767 10768 if (V->getOpcode() == ISD::BUILD_VECTOR) { 10769 assert(V->getNumOperands() == NumElts && 10770 "BUILD_VECTOR has wrong number of operands"); 10771 SDValue Base; 10772 bool AllSame = true; 10773 for (unsigned i = 0; i != NumElts; ++i) { 10774 if (V->getOperand(i).getOpcode() != ISD::UNDEF) { 10775 Base = V->getOperand(i); 10776 break; 10777 } 10778 } 10779 // Splat of <u, u, u, u>, return <u, u, u, u> 10780 if (!Base.getNode()) 10781 return N0; 10782 for (unsigned i = 0; i != NumElts; ++i) { 10783 if (V->getOperand(i) != Base) { 10784 AllSame = false; 10785 break; 10786 } 10787 } 10788 // Splat of <x, x, x, x>, return <x, x, x, x> 10789 if (AllSame) 10790 return N0; 10791 } 10792 } 10793 10794 if (N0.getOpcode() == ISD::CONCAT_VECTORS && 10795 Level < AfterLegalizeVectorOps && 10796 (N1.getOpcode() == ISD::UNDEF || 10797 (N1.getOpcode() == ISD::CONCAT_VECTORS && 10798 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) { 10799 SDValue V = partitionShuffleOfConcats(N, DAG); 10800 10801 if (V.getNode()) 10802 return V; 10803 } 10804 10805 // If this shuffle node is simply a swizzle of another shuffle node, 10806 // then try to simplify it. 10807 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG && 10808 N1.getOpcode() == ISD::UNDEF) { 10809 10810 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0); 10811 10812 // The incoming shuffle must be of the same type as the result of the 10813 // current shuffle. 10814 assert(OtherSV->getOperand(0).getValueType() == VT && 10815 "Shuffle types don't match"); 10816 10817 SmallVector<int, 4> Mask; 10818 // Compute the combined shuffle mask. 10819 for (unsigned i = 0; i != NumElts; ++i) { 10820 int Idx = SVN->getMaskElt(i); 10821 assert(Idx < (int)NumElts && "Index references undef operand"); 10822 // Next, this index comes from the first value, which is the incoming 10823 // shuffle. Adopt the incoming index. 10824 if (Idx >= 0) 10825 Idx = OtherSV->getMaskElt(Idx); 10826 Mask.push_back(Idx); 10827 } 10828 10829 // Check if all indices in Mask are Undef. In case, propagate Undef. 10830 bool isUndefMask = true; 10831 for (unsigned i = 0; i != NumElts && isUndefMask; ++i) 10832 isUndefMask &= Mask[i] < 0; 10833 10834 if (isUndefMask) 10835 return DAG.getUNDEF(VT); 10836 10837 bool CommuteOperands = false; 10838 if (N0.getOperand(1).getOpcode() != ISD::UNDEF) { 10839 // To be valid, the combine shuffle mask should only reference elements 10840 // from one of the two vectors in input to the inner shufflevector. 10841 bool IsValidMask = true; 10842 for (unsigned i = 0; i != NumElts && IsValidMask; ++i) 10843 // See if the combined mask only reference undefs or elements coming 10844 // from the first shufflevector operand. 10845 IsValidMask = Mask[i] < 0 || (unsigned)Mask[i] < NumElts; 10846 10847 if (!IsValidMask) { 10848 IsValidMask = true; 10849 for (unsigned i = 0; i != NumElts && IsValidMask; ++i) 10850 // Check that all the elements come from the second shuffle operand. 10851 IsValidMask = Mask[i] < 0 || (unsigned)Mask[i] >= NumElts; 10852 CommuteOperands = IsValidMask; 10853 } 10854 10855 // Early exit if the combined shuffle mask is not valid. 10856 if (!IsValidMask) 10857 return SDValue(); 10858 } 10859 10860 // See if this pair of shuffles can be safely folded according to either 10861 // of the following rules: 10862 // shuffle(shuffle(x, y), undef) -> x 10863 // shuffle(shuffle(x, undef), undef) -> x 10864 // shuffle(shuffle(x, y), undef) -> y 10865 bool IsIdentityMask = true; 10866 unsigned BaseMaskIndex = CommuteOperands ? NumElts : 0; 10867 for (unsigned i = 0; i != NumElts && IsIdentityMask; ++i) { 10868 // Skip Undefs. 10869 if (Mask[i] < 0) 10870 continue; 10871 10872 // The combined shuffle must map each index to itself. 10873 IsIdentityMask = (unsigned)Mask[i] == i + BaseMaskIndex; 10874 } 10875 10876 if (IsIdentityMask) { 10877 if (CommuteOperands) 10878 // optimize shuffle(shuffle(x, y), undef) -> y. 10879 return OtherSV->getOperand(1); 10880 10881 // optimize shuffle(shuffle(x, undef), undef) -> x 10882 // optimize shuffle(shuffle(x, y), undef) -> x 10883 return OtherSV->getOperand(0); 10884 } 10885 10886 // It may still be beneficial to combine the two shuffles if the 10887 // resulting shuffle is legal. 10888 if (TLI.isTypeLegal(VT)) { 10889 if (!CommuteOperands) { 10890 if (TLI.isShuffleMaskLegal(Mask, VT)) 10891 // shuffle(shuffle(x, undef, M1), undef, M2) -> shuffle(x, undef, M3). 10892 // shuffle(shuffle(x, y, M1), undef, M2) -> shuffle(x, undef, M3) 10893 return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0), N1, 10894 &Mask[0]); 10895 } else { 10896 // Compute the commuted shuffle mask. 10897 for (unsigned i = 0; i != NumElts; ++i) { 10898 int idx = Mask[i]; 10899 if (idx < 0) 10900 continue; 10901 else if (idx < (int)NumElts) 10902 Mask[i] = idx + NumElts; 10903 else 10904 Mask[i] = idx - NumElts; 10905 } 10906 10907 if (TLI.isShuffleMaskLegal(Mask, VT)) 10908 // shuffle(shuffle(x, y, M1), undef, M2) -> shuffle(y, undef, M3) 10909 return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(1), N1, 10910 &Mask[0]); 10911 } 10912 } 10913 } 10914 10915 // Canonicalize shuffles according to rules: 10916 // shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A) 10917 // shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B) 10918 // shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B) 10919 if (N1.getOpcode() == ISD::VECTOR_SHUFFLE && N0.getOpcode() != ISD::UNDEF && 10920 N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG && 10921 TLI.isTypeLegal(VT)) { 10922 // The incoming shuffle must be of the same type as the result of the 10923 // current shuffle. 10924 assert(N1->getOperand(0).getValueType() == VT && 10925 "Shuffle types don't match"); 10926 10927 SDValue SV0 = N1->getOperand(0); 10928 SDValue SV1 = N1->getOperand(1); 10929 bool HasSameOp0 = N0 == SV0; 10930 bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF; 10931 if (HasSameOp0 || IsSV1Undef || N0 == SV1) 10932 // Commute the operands of this shuffle so that next rule 10933 // will trigger. 10934 return DAG.getCommutedVectorShuffle(*SVN); 10935 } 10936 10937 // Try to fold according to rules: 10938 // shuffle(shuffle(A, B, M0), B, M1) -> shuffle(A, B, M2) 10939 // shuffle(shuffle(A, B, M0), A, M1) -> shuffle(A, B, M2) 10940 // shuffle(shuffle(A, Undef, M0), B, M1) -> shuffle(A, B, M2) 10941 // shuffle(shuffle(A, Undef, M0), A, M1) -> shuffle(A, Undef, M2) 10942 // Don't try to fold shuffles with illegal type. 10943 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG && 10944 N1.getOpcode() != ISD::UNDEF && TLI.isTypeLegal(VT)) { 10945 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0); 10946 10947 // The incoming shuffle must be of the same type as the result of the 10948 // current shuffle. 10949 assert(OtherSV->getOperand(0).getValueType() == VT && 10950 "Shuffle types don't match"); 10951 10952 SDValue SV0 = OtherSV->getOperand(0); 10953 SDValue SV1 = OtherSV->getOperand(1); 10954 bool HasSameOp0 = N1 == SV0; 10955 bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF; 10956 if (!HasSameOp0 && !IsSV1Undef && N1 != SV1) 10957 // Early exit. 10958 return SDValue(); 10959 10960 SmallVector<int, 4> Mask; 10961 // Compute the combined shuffle mask for a shuffle with SV0 as the first 10962 // operand, and SV1 as the second operand. 10963 for (unsigned i = 0; i != NumElts; ++i) { 10964 int Idx = SVN->getMaskElt(i); 10965 if (Idx < 0) { 10966 // Propagate Undef. 10967 Mask.push_back(Idx); 10968 continue; 10969 } 10970 10971 if (Idx < (int)NumElts) { 10972 Idx = OtherSV->getMaskElt(Idx); 10973 if (IsSV1Undef && Idx >= (int) NumElts) 10974 Idx = -1; // Propagate Undef. 10975 } else 10976 Idx = HasSameOp0 ? Idx - NumElts : Idx; 10977 10978 Mask.push_back(Idx); 10979 } 10980 10981 // Check if all indices in Mask are Undef. In case, propagate Undef. 10982 bool isUndefMask = true; 10983 for (unsigned i = 0; i != NumElts && isUndefMask; ++i) 10984 isUndefMask &= Mask[i] < 0; 10985 10986 if (isUndefMask) 10987 return DAG.getUNDEF(VT); 10988 10989 // Avoid introducing shuffles with illegal mask. 10990 if (TLI.isShuffleMaskLegal(Mask, VT)) { 10991 if (IsSV1Undef) 10992 // shuffle(shuffle(A, Undef, M0), B, M1) -> shuffle(A, B, M2) 10993 // shuffle(shuffle(A, Undef, M0), A, M1) -> shuffle(A, Undef, M2) 10994 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, N1, &Mask[0]); 10995 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, &Mask[0]); 10996 } 10997 } 10998 10999 return SDValue(); 11000 } 11001 11002 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) { 11003 SDValue N0 = N->getOperand(0); 11004 SDValue N2 = N->getOperand(2); 11005 11006 // If the input vector is a concatenation, and the insert replaces 11007 // one of the halves, we can optimize into a single concat_vectors. 11008 if (N0.getOpcode() == ISD::CONCAT_VECTORS && 11009 N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) { 11010 APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue(); 11011 EVT VT = N->getValueType(0); 11012 11013 // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) -> 11014 // (concat_vectors Z, Y) 11015 if (InsIdx == 0) 11016 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, 11017 N->getOperand(1), N0.getOperand(1)); 11018 11019 // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) -> 11020 // (concat_vectors X, Z) 11021 if (InsIdx == VT.getVectorNumElements()/2) 11022 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, 11023 N0.getOperand(0), N->getOperand(1)); 11024 } 11025 11026 return SDValue(); 11027 } 11028 11029 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle 11030 /// with the destination vector and a zero vector. 11031 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==> 11032 /// vector_shuffle V, Zero, <0, 4, 2, 4> 11033 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) { 11034 EVT VT = N->getValueType(0); 11035 SDLoc dl(N); 11036 SDValue LHS = N->getOperand(0); 11037 SDValue RHS = N->getOperand(1); 11038 if (N->getOpcode() == ISD::AND) { 11039 if (RHS.getOpcode() == ISD::BITCAST) 11040 RHS = RHS.getOperand(0); 11041 if (RHS.getOpcode() == ISD::BUILD_VECTOR) { 11042 SmallVector<int, 8> Indices; 11043 unsigned NumElts = RHS.getNumOperands(); 11044 for (unsigned i = 0; i != NumElts; ++i) { 11045 SDValue Elt = RHS.getOperand(i); 11046 if (!isa<ConstantSDNode>(Elt)) 11047 return SDValue(); 11048 11049 if (cast<ConstantSDNode>(Elt)->isAllOnesValue()) 11050 Indices.push_back(i); 11051 else if (cast<ConstantSDNode>(Elt)->isNullValue()) 11052 Indices.push_back(NumElts); 11053 else 11054 return SDValue(); 11055 } 11056 11057 // Let's see if the target supports this vector_shuffle. 11058 EVT RVT = RHS.getValueType(); 11059 if (!TLI.isVectorClearMaskLegal(Indices, RVT)) 11060 return SDValue(); 11061 11062 // Return the new VECTOR_SHUFFLE node. 11063 EVT EltVT = RVT.getVectorElementType(); 11064 SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(), 11065 DAG.getConstant(0, EltVT)); 11066 SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), RVT, ZeroOps); 11067 LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS); 11068 SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]); 11069 return DAG.getNode(ISD::BITCAST, dl, VT, Shuf); 11070 } 11071 } 11072 11073 return SDValue(); 11074 } 11075 11076 /// Visit a binary vector operation, like ADD. 11077 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) { 11078 assert(N->getValueType(0).isVector() && 11079 "SimplifyVBinOp only works on vectors!"); 11080 11081 SDValue LHS = N->getOperand(0); 11082 SDValue RHS = N->getOperand(1); 11083 SDValue Shuffle = XformToShuffleWithZero(N); 11084 if (Shuffle.getNode()) return Shuffle; 11085 11086 // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold 11087 // this operation. 11088 if (LHS.getOpcode() == ISD::BUILD_VECTOR && 11089 RHS.getOpcode() == ISD::BUILD_VECTOR) { 11090 // Check if both vectors are constants. If not bail out. 11091 if (!(cast<BuildVectorSDNode>(LHS)->isConstant() && 11092 cast<BuildVectorSDNode>(RHS)->isConstant())) 11093 return SDValue(); 11094 11095 SmallVector<SDValue, 8> Ops; 11096 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) { 11097 SDValue LHSOp = LHS.getOperand(i); 11098 SDValue RHSOp = RHS.getOperand(i); 11099 11100 // Can't fold divide by zero. 11101 if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV || 11102 N->getOpcode() == ISD::FDIV) { 11103 if ((RHSOp.getOpcode() == ISD::Constant && 11104 cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) || 11105 (RHSOp.getOpcode() == ISD::ConstantFP && 11106 cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero())) 11107 break; 11108 } 11109 11110 EVT VT = LHSOp.getValueType(); 11111 EVT RVT = RHSOp.getValueType(); 11112 if (RVT != VT) { 11113 // Integer BUILD_VECTOR operands may have types larger than the element 11114 // size (e.g., when the element type is not legal). Prior to type 11115 // legalization, the types may not match between the two BUILD_VECTORS. 11116 // Truncate one of the operands to make them match. 11117 if (RVT.getSizeInBits() > VT.getSizeInBits()) { 11118 RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp); 11119 } else { 11120 LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp); 11121 VT = RVT; 11122 } 11123 } 11124 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT, 11125 LHSOp, RHSOp); 11126 if (FoldOp.getOpcode() != ISD::UNDEF && 11127 FoldOp.getOpcode() != ISD::Constant && 11128 FoldOp.getOpcode() != ISD::ConstantFP) 11129 break; 11130 Ops.push_back(FoldOp); 11131 AddToWorklist(FoldOp.getNode()); 11132 } 11133 11134 if (Ops.size() == LHS.getNumOperands()) 11135 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), LHS.getValueType(), Ops); 11136 } 11137 11138 // Type legalization might introduce new shuffles in the DAG. 11139 // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask))) 11140 // -> (shuffle (VBinOp (A, B)), Undef, Mask). 11141 if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) && 11142 isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() && 11143 LHS.getOperand(1).getOpcode() == ISD::UNDEF && 11144 RHS.getOperand(1).getOpcode() == ISD::UNDEF) { 11145 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS); 11146 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS); 11147 11148 if (SVN0->getMask().equals(SVN1->getMask())) { 11149 EVT VT = N->getValueType(0); 11150 SDValue UndefVector = LHS.getOperand(1); 11151 SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT, 11152 LHS.getOperand(0), RHS.getOperand(0)); 11153 AddUsersToWorklist(N); 11154 return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector, 11155 &SVN0->getMask()[0]); 11156 } 11157 } 11158 11159 return SDValue(); 11160 } 11161 11162 /// Visit a binary vector operation, like FABS/FNEG. 11163 SDValue DAGCombiner::SimplifyVUnaryOp(SDNode *N) { 11164 assert(N->getValueType(0).isVector() && 11165 "SimplifyVUnaryOp only works on vectors!"); 11166 11167 SDValue N0 = N->getOperand(0); 11168 11169 if (N0.getOpcode() != ISD::BUILD_VECTOR) 11170 return SDValue(); 11171 11172 // Operand is a BUILD_VECTOR node, see if we can constant fold it. 11173 SmallVector<SDValue, 8> Ops; 11174 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) { 11175 SDValue Op = N0.getOperand(i); 11176 if (Op.getOpcode() != ISD::UNDEF && 11177 Op.getOpcode() != ISD::ConstantFP) 11178 break; 11179 EVT EltVT = Op.getValueType(); 11180 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(N0), EltVT, Op); 11181 if (FoldOp.getOpcode() != ISD::UNDEF && 11182 FoldOp.getOpcode() != ISD::ConstantFP) 11183 break; 11184 Ops.push_back(FoldOp); 11185 AddToWorklist(FoldOp.getNode()); 11186 } 11187 11188 if (Ops.size() != N0.getNumOperands()) 11189 return SDValue(); 11190 11191 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), N0.getValueType(), Ops); 11192 } 11193 11194 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0, 11195 SDValue N1, SDValue N2){ 11196 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!"); 11197 11198 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2, 11199 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 11200 11201 // If we got a simplified select_cc node back from SimplifySelectCC, then 11202 // break it down into a new SETCC node, and a new SELECT node, and then return 11203 // the SELECT node, since we were called with a SELECT node. 11204 if (SCC.getNode()) { 11205 // Check to see if we got a select_cc back (to turn into setcc/select). 11206 // Otherwise, just return whatever node we got back, like fabs. 11207 if (SCC.getOpcode() == ISD::SELECT_CC) { 11208 SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0), 11209 N0.getValueType(), 11210 SCC.getOperand(0), SCC.getOperand(1), 11211 SCC.getOperand(4)); 11212 AddToWorklist(SETCC.getNode()); 11213 return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC, 11214 SCC.getOperand(2), SCC.getOperand(3)); 11215 } 11216 11217 return SCC; 11218 } 11219 return SDValue(); 11220 } 11221 11222 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values 11223 /// being selected between, see if we can simplify the select. Callers of this 11224 /// should assume that TheSelect is deleted if this returns true. As such, they 11225 /// should return the appropriate thing (e.g. the node) back to the top-level of 11226 /// the DAG combiner loop to avoid it being looked at. 11227 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS, 11228 SDValue RHS) { 11229 11230 // Cannot simplify select with vector condition 11231 if (TheSelect->getOperand(0).getValueType().isVector()) return false; 11232 11233 // If this is a select from two identical things, try to pull the operation 11234 // through the select. 11235 if (LHS.getOpcode() != RHS.getOpcode() || 11236 !LHS.hasOneUse() || !RHS.hasOneUse()) 11237 return false; 11238 11239 // If this is a load and the token chain is identical, replace the select 11240 // of two loads with a load through a select of the address to load from. 11241 // This triggers in things like "select bool X, 10.0, 123.0" after the FP 11242 // constants have been dropped into the constant pool. 11243 if (LHS.getOpcode() == ISD::LOAD) { 11244 LoadSDNode *LLD = cast<LoadSDNode>(LHS); 11245 LoadSDNode *RLD = cast<LoadSDNode>(RHS); 11246 11247 // Token chains must be identical. 11248 if (LHS.getOperand(0) != RHS.getOperand(0) || 11249 // Do not let this transformation reduce the number of volatile loads. 11250 LLD->isVolatile() || RLD->isVolatile() || 11251 // If this is an EXTLOAD, the VT's must match. 11252 LLD->getMemoryVT() != RLD->getMemoryVT() || 11253 // If this is an EXTLOAD, the kind of extension must match. 11254 (LLD->getExtensionType() != RLD->getExtensionType() && 11255 // The only exception is if one of the extensions is anyext. 11256 LLD->getExtensionType() != ISD::EXTLOAD && 11257 RLD->getExtensionType() != ISD::EXTLOAD) || 11258 // FIXME: this discards src value information. This is 11259 // over-conservative. It would be beneficial to be able to remember 11260 // both potential memory locations. Since we are discarding 11261 // src value info, don't do the transformation if the memory 11262 // locations are not in the default address space. 11263 LLD->getPointerInfo().getAddrSpace() != 0 || 11264 RLD->getPointerInfo().getAddrSpace() != 0 || 11265 !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(), 11266 LLD->getBasePtr().getValueType())) 11267 return false; 11268 11269 // Check that the select condition doesn't reach either load. If so, 11270 // folding this will induce a cycle into the DAG. If not, this is safe to 11271 // xform, so create a select of the addresses. 11272 SDValue Addr; 11273 if (TheSelect->getOpcode() == ISD::SELECT) { 11274 SDNode *CondNode = TheSelect->getOperand(0).getNode(); 11275 if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) || 11276 (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode))) 11277 return false; 11278 // The loads must not depend on one another. 11279 if (LLD->isPredecessorOf(RLD) || 11280 RLD->isPredecessorOf(LLD)) 11281 return false; 11282 Addr = DAG.getSelect(SDLoc(TheSelect), 11283 LLD->getBasePtr().getValueType(), 11284 TheSelect->getOperand(0), LLD->getBasePtr(), 11285 RLD->getBasePtr()); 11286 } else { // Otherwise SELECT_CC 11287 SDNode *CondLHS = TheSelect->getOperand(0).getNode(); 11288 SDNode *CondRHS = TheSelect->getOperand(1).getNode(); 11289 11290 if ((LLD->hasAnyUseOfValue(1) && 11291 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) || 11292 (RLD->hasAnyUseOfValue(1) && 11293 (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS)))) 11294 return false; 11295 11296 Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect), 11297 LLD->getBasePtr().getValueType(), 11298 TheSelect->getOperand(0), 11299 TheSelect->getOperand(1), 11300 LLD->getBasePtr(), RLD->getBasePtr(), 11301 TheSelect->getOperand(4)); 11302 } 11303 11304 SDValue Load; 11305 // It is safe to replace the two loads if they have different alignments, 11306 // but the new load must be the minimum (most restrictive) alignment of the 11307 // inputs. 11308 bool isInvariant = LLD->getAlignment() & RLD->getAlignment(); 11309 unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment()); 11310 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) { 11311 Load = DAG.getLoad(TheSelect->getValueType(0), 11312 SDLoc(TheSelect), 11313 // FIXME: Discards pointer and AA info. 11314 LLD->getChain(), Addr, MachinePointerInfo(), 11315 LLD->isVolatile(), LLD->isNonTemporal(), 11316 isInvariant, Alignment); 11317 } else { 11318 Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ? 11319 RLD->getExtensionType() : LLD->getExtensionType(), 11320 SDLoc(TheSelect), 11321 TheSelect->getValueType(0), 11322 // FIXME: Discards pointer and AA info. 11323 LLD->getChain(), Addr, MachinePointerInfo(), 11324 LLD->getMemoryVT(), LLD->isVolatile(), 11325 LLD->isNonTemporal(), isInvariant, Alignment); 11326 } 11327 11328 // Users of the select now use the result of the load. 11329 CombineTo(TheSelect, Load); 11330 11331 // Users of the old loads now use the new load's chain. We know the 11332 // old-load value is dead now. 11333 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1)); 11334 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1)); 11335 return true; 11336 } 11337 11338 return false; 11339 } 11340 11341 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3 11342 /// where 'cond' is the comparison specified by CC. 11343 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, 11344 SDValue N2, SDValue N3, 11345 ISD::CondCode CC, bool NotExtCompare) { 11346 // (x ? y : y) -> y. 11347 if (N2 == N3) return N2; 11348 11349 EVT VT = N2.getValueType(); 11350 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode()); 11351 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode()); 11352 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode()); 11353 11354 // Determine if the condition we're dealing with is constant 11355 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()), 11356 N0, N1, CC, DL, false); 11357 if (SCC.getNode()) AddToWorklist(SCC.getNode()); 11358 ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode()); 11359 11360 // fold select_cc true, x, y -> x 11361 if (SCCC && !SCCC->isNullValue()) 11362 return N2; 11363 // fold select_cc false, x, y -> y 11364 if (SCCC && SCCC->isNullValue()) 11365 return N3; 11366 11367 // Check to see if we can simplify the select into an fabs node 11368 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) { 11369 // Allow either -0.0 or 0.0 11370 if (CFP->getValueAPF().isZero()) { 11371 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs 11372 if ((CC == ISD::SETGE || CC == ISD::SETGT) && 11373 N0 == N2 && N3.getOpcode() == ISD::FNEG && 11374 N2 == N3.getOperand(0)) 11375 return DAG.getNode(ISD::FABS, DL, VT, N0); 11376 11377 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs 11378 if ((CC == ISD::SETLT || CC == ISD::SETLE) && 11379 N0 == N3 && N2.getOpcode() == ISD::FNEG && 11380 N2.getOperand(0) == N3) 11381 return DAG.getNode(ISD::FABS, DL, VT, N3); 11382 } 11383 } 11384 11385 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)" 11386 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0 11387 // in it. This is a win when the constant is not otherwise available because 11388 // it replaces two constant pool loads with one. We only do this if the FP 11389 // type is known to be legal, because if it isn't, then we are before legalize 11390 // types an we want the other legalization to happen first (e.g. to avoid 11391 // messing with soft float) and if the ConstantFP is not legal, because if 11392 // it is legal, we may not need to store the FP constant in a constant pool. 11393 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2)) 11394 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) { 11395 if (TLI.isTypeLegal(N2.getValueType()) && 11396 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) != 11397 TargetLowering::Legal && 11398 !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) && 11399 !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) && 11400 // If both constants have multiple uses, then we won't need to do an 11401 // extra load, they are likely around in registers for other users. 11402 (TV->hasOneUse() || FV->hasOneUse())) { 11403 Constant *Elts[] = { 11404 const_cast<ConstantFP*>(FV->getConstantFPValue()), 11405 const_cast<ConstantFP*>(TV->getConstantFPValue()) 11406 }; 11407 Type *FPTy = Elts[0]->getType(); 11408 const DataLayout &TD = *TLI.getDataLayout(); 11409 11410 // Create a ConstantArray of the two constants. 11411 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts); 11412 SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(), 11413 TD.getPrefTypeAlignment(FPTy)); 11414 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment(); 11415 11416 // Get the offsets to the 0 and 1 element of the array so that we can 11417 // select between them. 11418 SDValue Zero = DAG.getIntPtrConstant(0); 11419 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType()); 11420 SDValue One = DAG.getIntPtrConstant(EltSize); 11421 11422 SDValue Cond = DAG.getSetCC(DL, 11423 getSetCCResultType(N0.getValueType()), 11424 N0, N1, CC); 11425 AddToWorklist(Cond.getNode()); 11426 SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(), 11427 Cond, One, Zero); 11428 AddToWorklist(CstOffset.getNode()); 11429 CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx, 11430 CstOffset); 11431 AddToWorklist(CPIdx.getNode()); 11432 return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx, 11433 MachinePointerInfo::getConstantPool(), false, 11434 false, false, Alignment); 11435 11436 } 11437 } 11438 11439 // Check to see if we can perform the "gzip trick", transforming 11440 // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A) 11441 if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT && 11442 (N1C->isNullValue() || // (a < 0) ? b : 0 11443 (N1C->getAPIntValue() == 1 && N0 == N2))) { // (a < 1) ? a : 0 11444 EVT XType = N0.getValueType(); 11445 EVT AType = N2.getValueType(); 11446 if (XType.bitsGE(AType)) { 11447 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a 11448 // single-bit constant. 11449 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) { 11450 unsigned ShCtV = N2C->getAPIntValue().logBase2(); 11451 ShCtV = XType.getSizeInBits()-ShCtV-1; 11452 SDValue ShCt = DAG.getConstant(ShCtV, 11453 getShiftAmountTy(N0.getValueType())); 11454 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), 11455 XType, N0, ShCt); 11456 AddToWorklist(Shift.getNode()); 11457 11458 if (XType.bitsGT(AType)) { 11459 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift); 11460 AddToWorklist(Shift.getNode()); 11461 } 11462 11463 return DAG.getNode(ISD::AND, DL, AType, Shift, N2); 11464 } 11465 11466 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), 11467 XType, N0, 11468 DAG.getConstant(XType.getSizeInBits()-1, 11469 getShiftAmountTy(N0.getValueType()))); 11470 AddToWorklist(Shift.getNode()); 11471 11472 if (XType.bitsGT(AType)) { 11473 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift); 11474 AddToWorklist(Shift.getNode()); 11475 } 11476 11477 return DAG.getNode(ISD::AND, DL, AType, Shift, N2); 11478 } 11479 } 11480 11481 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A) 11482 // where y is has a single bit set. 11483 // A plaintext description would be, we can turn the SELECT_CC into an AND 11484 // when the condition can be materialized as an all-ones register. Any 11485 // single bit-test can be materialized as an all-ones register with 11486 // shift-left and shift-right-arith. 11487 if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND && 11488 N0->getValueType(0) == VT && 11489 N1C && N1C->isNullValue() && 11490 N2C && N2C->isNullValue()) { 11491 SDValue AndLHS = N0->getOperand(0); 11492 ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 11493 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) { 11494 // Shift the tested bit over the sign bit. 11495 APInt AndMask = ConstAndRHS->getAPIntValue(); 11496 SDValue ShlAmt = 11497 DAG.getConstant(AndMask.countLeadingZeros(), 11498 getShiftAmountTy(AndLHS.getValueType())); 11499 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt); 11500 11501 // Now arithmetic right shift it all the way over, so the result is either 11502 // all-ones, or zero. 11503 SDValue ShrAmt = 11504 DAG.getConstant(AndMask.getBitWidth()-1, 11505 getShiftAmountTy(Shl.getValueType())); 11506 SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt); 11507 11508 return DAG.getNode(ISD::AND, DL, VT, Shr, N3); 11509 } 11510 } 11511 11512 // fold select C, 16, 0 -> shl C, 4 11513 if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() && 11514 TLI.getBooleanContents(N0.getValueType()) == 11515 TargetLowering::ZeroOrOneBooleanContent) { 11516 11517 // If the caller doesn't want us to simplify this into a zext of a compare, 11518 // don't do it. 11519 if (NotExtCompare && N2C->getAPIntValue() == 1) 11520 return SDValue(); 11521 11522 // Get a SetCC of the condition 11523 // NOTE: Don't create a SETCC if it's not legal on this target. 11524 if (!LegalOperations || 11525 TLI.isOperationLegal(ISD::SETCC, 11526 LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) { 11527 SDValue Temp, SCC; 11528 // cast from setcc result type to select result type 11529 if (LegalTypes) { 11530 SCC = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()), 11531 N0, N1, CC); 11532 if (N2.getValueType().bitsLT(SCC.getValueType())) 11533 Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2), 11534 N2.getValueType()); 11535 else 11536 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2), 11537 N2.getValueType(), SCC); 11538 } else { 11539 SCC = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC); 11540 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2), 11541 N2.getValueType(), SCC); 11542 } 11543 11544 AddToWorklist(SCC.getNode()); 11545 AddToWorklist(Temp.getNode()); 11546 11547 if (N2C->getAPIntValue() == 1) 11548 return Temp; 11549 11550 // shl setcc result by log2 n2c 11551 return DAG.getNode( 11552 ISD::SHL, DL, N2.getValueType(), Temp, 11553 DAG.getConstant(N2C->getAPIntValue().logBase2(), 11554 getShiftAmountTy(Temp.getValueType()))); 11555 } 11556 } 11557 11558 // Check to see if this is the equivalent of setcc 11559 // FIXME: Turn all of these into setcc if setcc if setcc is legal 11560 // otherwise, go ahead with the folds. 11561 if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) { 11562 EVT XType = N0.getValueType(); 11563 if (!LegalOperations || 11564 TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) { 11565 SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC); 11566 if (Res.getValueType() != VT) 11567 Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res); 11568 return Res; 11569 } 11570 11571 // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X)))) 11572 if (N1C && N1C->isNullValue() && CC == ISD::SETEQ && 11573 (!LegalOperations || 11574 TLI.isOperationLegal(ISD::CTLZ, XType))) { 11575 SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0); 11576 return DAG.getNode(ISD::SRL, DL, XType, Ctlz, 11577 DAG.getConstant(Log2_32(XType.getSizeInBits()), 11578 getShiftAmountTy(Ctlz.getValueType()))); 11579 } 11580 // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1)) 11581 if (N1C && N1C->isNullValue() && CC == ISD::SETGT) { 11582 SDValue NegN0 = DAG.getNode(ISD::SUB, SDLoc(N0), 11583 XType, DAG.getConstant(0, XType), N0); 11584 SDValue NotN0 = DAG.getNOT(SDLoc(N0), N0, XType); 11585 return DAG.getNode(ISD::SRL, DL, XType, 11586 DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0), 11587 DAG.getConstant(XType.getSizeInBits()-1, 11588 getShiftAmountTy(XType))); 11589 } 11590 // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1)) 11591 if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) { 11592 SDValue Sign = DAG.getNode(ISD::SRL, SDLoc(N0), XType, N0, 11593 DAG.getConstant(XType.getSizeInBits()-1, 11594 getShiftAmountTy(N0.getValueType()))); 11595 return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType)); 11596 } 11597 } 11598 11599 // Check to see if this is an integer abs. 11600 // select_cc setg[te] X, 0, X, -X -> 11601 // select_cc setgt X, -1, X, -X -> 11602 // select_cc setl[te] X, 0, -X, X -> 11603 // select_cc setlt X, 1, -X, X -> 11604 // Y = sra (X, size(X)-1); xor (add (X, Y), Y) 11605 if (N1C) { 11606 ConstantSDNode *SubC = nullptr; 11607 if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) || 11608 (N1C->isAllOnesValue() && CC == ISD::SETGT)) && 11609 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1)) 11610 SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0)); 11611 else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) || 11612 (N1C->isOne() && CC == ISD::SETLT)) && 11613 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1)) 11614 SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0)); 11615 11616 EVT XType = N0.getValueType(); 11617 if (SubC && SubC->isNullValue() && XType.isInteger()) { 11618 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), XType, 11619 N0, 11620 DAG.getConstant(XType.getSizeInBits()-1, 11621 getShiftAmountTy(N0.getValueType()))); 11622 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0), 11623 XType, N0, Shift); 11624 AddToWorklist(Shift.getNode()); 11625 AddToWorklist(Add.getNode()); 11626 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift); 11627 } 11628 } 11629 11630 return SDValue(); 11631 } 11632 11633 /// This is a stub for TargetLowering::SimplifySetCC. 11634 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0, 11635 SDValue N1, ISD::CondCode Cond, 11636 SDLoc DL, bool foldBooleans) { 11637 TargetLowering::DAGCombinerInfo 11638 DagCombineInfo(DAG, Level, false, this); 11639 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL); 11640 } 11641 11642 /// Given an ISD::SDIV node expressing a divide by constant, return 11643 /// a DAG expression to select that will generate the same value by multiplying 11644 /// by a magic number. 11645 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide". 11646 SDValue DAGCombiner::BuildSDIV(SDNode *N) { 11647 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1)); 11648 if (!C) 11649 return SDValue(); 11650 11651 // Avoid division by zero. 11652 if (!C->getAPIntValue()) 11653 return SDValue(); 11654 11655 std::vector<SDNode*> Built; 11656 SDValue S = 11657 TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built); 11658 11659 for (SDNode *N : Built) 11660 AddToWorklist(N); 11661 return S; 11662 } 11663 11664 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a 11665 /// DAG expression that will generate the same value by right shifting. 11666 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) { 11667 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1)); 11668 if (!C) 11669 return SDValue(); 11670 11671 // Avoid division by zero. 11672 if (!C->getAPIntValue()) 11673 return SDValue(); 11674 11675 std::vector<SDNode *> Built; 11676 SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built); 11677 11678 for (SDNode *N : Built) 11679 AddToWorklist(N); 11680 return S; 11681 } 11682 11683 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG 11684 /// expression that will generate the same value by multiplying by a magic 11685 /// number. 11686 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide". 11687 SDValue DAGCombiner::BuildUDIV(SDNode *N) { 11688 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1)); 11689 if (!C) 11690 return SDValue(); 11691 11692 // Avoid division by zero. 11693 if (!C->getAPIntValue()) 11694 return SDValue(); 11695 11696 std::vector<SDNode*> Built; 11697 SDValue S = 11698 TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built); 11699 11700 for (SDNode *N : Built) 11701 AddToWorklist(N); 11702 return S; 11703 } 11704 11705 /// Given an ISD::FDIV node with either a direct or indirect ISD::FSQRT operand, 11706 /// generate a DAG expression using a reciprocal square root estimate op. 11707 SDValue DAGCombiner::BuildRSQRTE(SDNode *N) { 11708 // Expose the DAG combiner to the target combiner implementations. 11709 TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this); 11710 SDLoc DL(N); 11711 EVT VT = N->getValueType(0); 11712 SDValue N1 = N->getOperand(1); 11713 11714 if (N1.getOpcode() == ISD::FSQRT) { 11715 if (SDValue RV = TLI.BuildRSQRTE(N1.getOperand(0), DCI)) { 11716 AddToWorklist(RV.getNode()); 11717 return DAG.getNode(ISD::FMUL, DL, VT, N->getOperand(0), RV); 11718 } 11719 } else if (N1.getOpcode() == ISD::FP_EXTEND && 11720 N1.getOperand(0).getOpcode() == ISD::FSQRT) { 11721 if (SDValue RV = TLI.BuildRSQRTE(N1.getOperand(0).getOperand(0), DCI)) { 11722 DCI.AddToWorklist(RV.getNode()); 11723 RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV); 11724 AddToWorklist(RV.getNode()); 11725 return DAG.getNode(ISD::FMUL, DL, VT, N->getOperand(0), RV); 11726 } 11727 } else if (N1.getOpcode() == ISD::FP_ROUND && 11728 N1.getOperand(0).getOpcode() == ISD::FSQRT) { 11729 if (SDValue RV = TLI.BuildRSQRTE(N1.getOperand(0).getOperand(0), DCI)) { 11730 DCI.AddToWorklist(RV.getNode()); 11731 RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1)); 11732 AddToWorklist(RV.getNode()); 11733 return DAG.getNode(ISD::FMUL, DL, VT, N->getOperand(0), RV); 11734 } 11735 } 11736 11737 return SDValue(); 11738 } 11739 11740 /// Return true if base is a frame index, which is known not to alias with 11741 /// anything but itself. Provides base object and offset as results. 11742 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset, 11743 const GlobalValue *&GV, const void *&CV) { 11744 // Assume it is a primitive operation. 11745 Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr; 11746 11747 // If it's an adding a simple constant then integrate the offset. 11748 if (Base.getOpcode() == ISD::ADD) { 11749 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) { 11750 Base = Base.getOperand(0); 11751 Offset += C->getZExtValue(); 11752 } 11753 } 11754 11755 // Return the underlying GlobalValue, and update the Offset. Return false 11756 // for GlobalAddressSDNode since the same GlobalAddress may be represented 11757 // by multiple nodes with different offsets. 11758 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) { 11759 GV = G->getGlobal(); 11760 Offset += G->getOffset(); 11761 return false; 11762 } 11763 11764 // Return the underlying Constant value, and update the Offset. Return false 11765 // for ConstantSDNodes since the same constant pool entry may be represented 11766 // by multiple nodes with different offsets. 11767 if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) { 11768 CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal() 11769 : (const void *)C->getConstVal(); 11770 Offset += C->getOffset(); 11771 return false; 11772 } 11773 // If it's any of the following then it can't alias with anything but itself. 11774 return isa<FrameIndexSDNode>(Base); 11775 } 11776 11777 /// Return true if there is any possibility that the two addresses overlap. 11778 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const { 11779 // If they are the same then they must be aliases. 11780 if (Op0->getBasePtr() == Op1->getBasePtr()) return true; 11781 11782 // If they are both volatile then they cannot be reordered. 11783 if (Op0->isVolatile() && Op1->isVolatile()) return true; 11784 11785 // Gather base node and offset information. 11786 SDValue Base1, Base2; 11787 int64_t Offset1, Offset2; 11788 const GlobalValue *GV1, *GV2; 11789 const void *CV1, *CV2; 11790 bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(), 11791 Base1, Offset1, GV1, CV1); 11792 bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(), 11793 Base2, Offset2, GV2, CV2); 11794 11795 // If they have a same base address then check to see if they overlap. 11796 if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2))) 11797 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 || 11798 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1); 11799 11800 // It is possible for different frame indices to alias each other, mostly 11801 // when tail call optimization reuses return address slots for arguments. 11802 // To catch this case, look up the actual index of frame indices to compute 11803 // the real alias relationship. 11804 if (isFrameIndex1 && isFrameIndex2) { 11805 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo(); 11806 Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex()); 11807 Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex()); 11808 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 || 11809 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1); 11810 } 11811 11812 // Otherwise, if we know what the bases are, and they aren't identical, then 11813 // we know they cannot alias. 11814 if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2)) 11815 return false; 11816 11817 // If we know required SrcValue1 and SrcValue2 have relatively large alignment 11818 // compared to the size and offset of the access, we may be able to prove they 11819 // do not alias. This check is conservative for now to catch cases created by 11820 // splitting vector types. 11821 if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) && 11822 (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) && 11823 (Op0->getMemoryVT().getSizeInBits() >> 3 == 11824 Op1->getMemoryVT().getSizeInBits() >> 3) && 11825 (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) { 11826 int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment(); 11827 int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment(); 11828 11829 // There is no overlap between these relatively aligned accesses of similar 11830 // size, return no alias. 11831 if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 || 11832 (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1) 11833 return false; 11834 } 11835 11836 bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0 ? CombinerGlobalAA : 11837 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA(); 11838 #ifndef NDEBUG 11839 if (CombinerAAOnlyFunc.getNumOccurrences() && 11840 CombinerAAOnlyFunc != DAG.getMachineFunction().getName()) 11841 UseAA = false; 11842 #endif 11843 if (UseAA && 11844 Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) { 11845 // Use alias analysis information. 11846 int64_t MinOffset = std::min(Op0->getSrcValueOffset(), 11847 Op1->getSrcValueOffset()); 11848 int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) + 11849 Op0->getSrcValueOffset() - MinOffset; 11850 int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) + 11851 Op1->getSrcValueOffset() - MinOffset; 11852 AliasAnalysis::AliasResult AAResult = 11853 AA.alias(AliasAnalysis::Location(Op0->getMemOperand()->getValue(), 11854 Overlap1, 11855 UseTBAA ? Op0->getAAInfo() : AAMDNodes()), 11856 AliasAnalysis::Location(Op1->getMemOperand()->getValue(), 11857 Overlap2, 11858 UseTBAA ? Op1->getAAInfo() : AAMDNodes())); 11859 if (AAResult == AliasAnalysis::NoAlias) 11860 return false; 11861 } 11862 11863 // Otherwise we have to assume they alias. 11864 return true; 11865 } 11866 11867 /// Walk up chain skipping non-aliasing memory nodes, 11868 /// looking for aliasing nodes and adding them to the Aliases vector. 11869 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain, 11870 SmallVectorImpl<SDValue> &Aliases) { 11871 SmallVector<SDValue, 8> Chains; // List of chains to visit. 11872 SmallPtrSet<SDNode *, 16> Visited; // Visited node set. 11873 11874 // Get alias information for node. 11875 bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile(); 11876 11877 // Starting off. 11878 Chains.push_back(OriginalChain); 11879 unsigned Depth = 0; 11880 11881 // Look at each chain and determine if it is an alias. If so, add it to the 11882 // aliases list. If not, then continue up the chain looking for the next 11883 // candidate. 11884 while (!Chains.empty()) { 11885 SDValue Chain = Chains.back(); 11886 Chains.pop_back(); 11887 11888 // For TokenFactor nodes, look at each operand and only continue up the 11889 // chain until we find two aliases. If we've seen two aliases, assume we'll 11890 // find more and revert to original chain since the xform is unlikely to be 11891 // profitable. 11892 // 11893 // FIXME: The depth check could be made to return the last non-aliasing 11894 // chain we found before we hit a tokenfactor rather than the original 11895 // chain. 11896 if (Depth > 6 || Aliases.size() == 2) { 11897 Aliases.clear(); 11898 Aliases.push_back(OriginalChain); 11899 return; 11900 } 11901 11902 // Don't bother if we've been before. 11903 if (!Visited.insert(Chain.getNode())) 11904 continue; 11905 11906 switch (Chain.getOpcode()) { 11907 case ISD::EntryToken: 11908 // Entry token is ideal chain operand, but handled in FindBetterChain. 11909 break; 11910 11911 case ISD::LOAD: 11912 case ISD::STORE: { 11913 // Get alias information for Chain. 11914 bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) && 11915 !cast<LSBaseSDNode>(Chain.getNode())->isVolatile(); 11916 11917 // If chain is alias then stop here. 11918 if (!(IsLoad && IsOpLoad) && 11919 isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) { 11920 Aliases.push_back(Chain); 11921 } else { 11922 // Look further up the chain. 11923 Chains.push_back(Chain.getOperand(0)); 11924 ++Depth; 11925 } 11926 break; 11927 } 11928 11929 case ISD::TokenFactor: 11930 // We have to check each of the operands of the token factor for "small" 11931 // token factors, so we queue them up. Adding the operands to the queue 11932 // (stack) in reverse order maintains the original order and increases the 11933 // likelihood that getNode will find a matching token factor (CSE.) 11934 if (Chain.getNumOperands() > 16) { 11935 Aliases.push_back(Chain); 11936 break; 11937 } 11938 for (unsigned n = Chain.getNumOperands(); n;) 11939 Chains.push_back(Chain.getOperand(--n)); 11940 ++Depth; 11941 break; 11942 11943 default: 11944 // For all other instructions we will just have to take what we can get. 11945 Aliases.push_back(Chain); 11946 break; 11947 } 11948 } 11949 11950 // We need to be careful here to also search for aliases through the 11951 // value operand of a store, etc. Consider the following situation: 11952 // Token1 = ... 11953 // L1 = load Token1, %52 11954 // S1 = store Token1, L1, %51 11955 // L2 = load Token1, %52+8 11956 // S2 = store Token1, L2, %51+8 11957 // Token2 = Token(S1, S2) 11958 // L3 = load Token2, %53 11959 // S3 = store Token2, L3, %52 11960 // L4 = load Token2, %53+8 11961 // S4 = store Token2, L4, %52+8 11962 // If we search for aliases of S3 (which loads address %52), and we look 11963 // only through the chain, then we'll miss the trivial dependence on L1 11964 // (which also loads from %52). We then might change all loads and 11965 // stores to use Token1 as their chain operand, which could result in 11966 // copying %53 into %52 before copying %52 into %51 (which should 11967 // happen first). 11968 // 11969 // The problem is, however, that searching for such data dependencies 11970 // can become expensive, and the cost is not directly related to the 11971 // chain depth. Instead, we'll rule out such configurations here by 11972 // insisting that we've visited all chain users (except for users 11973 // of the original chain, which is not necessary). When doing this, 11974 // we need to look through nodes we don't care about (otherwise, things 11975 // like register copies will interfere with trivial cases). 11976 11977 SmallVector<const SDNode *, 16> Worklist; 11978 for (const SDNode *N : Visited) 11979 if (N != OriginalChain.getNode()) 11980 Worklist.push_back(N); 11981 11982 while (!Worklist.empty()) { 11983 const SDNode *M = Worklist.pop_back_val(); 11984 11985 // We have already visited M, and want to make sure we've visited any uses 11986 // of M that we care about. For uses that we've not visisted, and don't 11987 // care about, queue them to the worklist. 11988 11989 for (SDNode::use_iterator UI = M->use_begin(), 11990 UIE = M->use_end(); UI != UIE; ++UI) 11991 if (UI.getUse().getValueType() == MVT::Other && Visited.insert(*UI)) { 11992 if (isa<MemIntrinsicSDNode>(*UI) || isa<MemSDNode>(*UI)) { 11993 // We've not visited this use, and we care about it (it could have an 11994 // ordering dependency with the original node). 11995 Aliases.clear(); 11996 Aliases.push_back(OriginalChain); 11997 return; 11998 } 11999 12000 // We've not visited this use, but we don't care about it. Mark it as 12001 // visited and enqueue it to the worklist. 12002 Worklist.push_back(*UI); 12003 } 12004 } 12005 } 12006 12007 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain 12008 /// (aliasing node.) 12009 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) { 12010 SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor. 12011 12012 // Accumulate all the aliases to this node. 12013 GatherAllAliases(N, OldChain, Aliases); 12014 12015 // If no operands then chain to entry token. 12016 if (Aliases.size() == 0) 12017 return DAG.getEntryNode(); 12018 12019 // If a single operand then chain to it. We don't need to revisit it. 12020 if (Aliases.size() == 1) 12021 return Aliases[0]; 12022 12023 // Construct a custom tailored token factor. 12024 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases); 12025 } 12026 12027 /// This is the entry point for the file. 12028 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA, 12029 CodeGenOpt::Level OptLevel) { 12030 /// This is the main entry point to this class. 12031 DAGCombiner(*this, AA, OptLevel).Run(Level); 12032 } 12033