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/Statistic.h" 22 #include "llvm/Analysis/AliasAnalysis.h" 23 #include "llvm/CodeGen/MachineFrameInfo.h" 24 #include "llvm/CodeGen/MachineFunction.h" 25 #include "llvm/IR/DataLayout.h" 26 #include "llvm/IR/DerivedTypes.h" 27 #include "llvm/IR/Function.h" 28 #include "llvm/IR/LLVMContext.h" 29 #include "llvm/Support/CommandLine.h" 30 #include "llvm/Support/Debug.h" 31 #include "llvm/Support/ErrorHandling.h" 32 #include "llvm/Support/MathExtras.h" 33 #include "llvm/Support/raw_ostream.h" 34 #include "llvm/Target/TargetLowering.h" 35 #include "llvm/Target/TargetMachine.h" 36 #include "llvm/Target/TargetOptions.h" 37 #include "llvm/Target/TargetRegisterInfo.h" 38 #include "llvm/Target/TargetSubtargetInfo.h" 39 #include <algorithm> 40 using namespace llvm; 41 42 #define DEBUG_TYPE "dagcombine" 43 44 STATISTIC(NodesCombined , "Number of dag nodes combined"); 45 STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created"); 46 STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created"); 47 STATISTIC(OpsNarrowed , "Number of load/op/store narrowed"); 48 STATISTIC(LdStFP2Int , "Number of fp load/store pairs transformed to int"); 49 STATISTIC(SlicedLoads, "Number of load sliced"); 50 51 namespace { 52 static cl::opt<bool> 53 CombinerAA("combiner-alias-analysis", cl::Hidden, 54 cl::desc("Enable DAG combiner alias-analysis heuristics")); 55 56 static cl::opt<bool> 57 CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden, 58 cl::desc("Enable DAG combiner's use of IR alias analysis")); 59 60 static cl::opt<bool> 61 UseTBAA("combiner-use-tbaa", cl::Hidden, cl::init(true), 62 cl::desc("Enable DAG combiner's use of TBAA")); 63 64 #ifndef NDEBUG 65 static cl::opt<std::string> 66 CombinerAAOnlyFunc("combiner-aa-only-func", cl::Hidden, 67 cl::desc("Only use DAG-combiner alias analysis in this" 68 " function")); 69 #endif 70 71 /// Hidden option to stress test load slicing, i.e., when this option 72 /// is enabled, load slicing bypasses most of its profitability guards. 73 static cl::opt<bool> 74 StressLoadSlicing("combiner-stress-load-slicing", cl::Hidden, 75 cl::desc("Bypass the profitability model of load " 76 "slicing"), 77 cl::init(false)); 78 79 //------------------------------ DAGCombiner ---------------------------------// 80 81 class DAGCombiner { 82 SelectionDAG &DAG; 83 const TargetLowering &TLI; 84 CombineLevel Level; 85 CodeGenOpt::Level OptLevel; 86 bool LegalOperations; 87 bool LegalTypes; 88 bool ForCodeSize; 89 90 // Worklist of all of the nodes that need to be simplified. 91 // 92 // This has the semantics that when adding to the worklist, 93 // the item added must be next to be processed. It should 94 // also only appear once. The naive approach to this takes 95 // linear time. 96 // 97 // To reduce the insert/remove time to logarithmic, we use 98 // a set and a vector to maintain our worklist. 99 // 100 // The set contains the items on the worklist, but does not 101 // maintain the order they should be visited. 102 // 103 // The vector maintains the order nodes should be visited, but may 104 // contain duplicate or removed nodes. When choosing a node to 105 // visit, we pop off the order stack until we find an item that is 106 // also in the contents set. All operations are O(log N). 107 SmallPtrSet<SDNode*, 64> WorkListContents; 108 SmallVector<SDNode*, 64> WorkListOrder; 109 110 // AA - Used for DAG load/store alias analysis. 111 AliasAnalysis &AA; 112 113 /// AddUsersToWorkList - When an instruction is simplified, add all users of 114 /// the instruction to the work lists because they might get more simplified 115 /// now. 116 /// 117 void AddUsersToWorkList(SDNode *N) { 118 for (SDNode *Node : N->uses()) 119 AddToWorkList(Node); 120 } 121 122 /// visit - call the node-specific routine that knows how to fold each 123 /// particular type of node. 124 SDValue visit(SDNode *N); 125 126 public: 127 /// AddToWorkList - Add to the work list making sure its instance is at the 128 /// back (next to be processed.) 129 void AddToWorkList(SDNode *N) { 130 WorkListContents.insert(N); 131 WorkListOrder.push_back(N); 132 } 133 134 /// removeFromWorkList - remove all instances of N from the worklist. 135 /// 136 void removeFromWorkList(SDNode *N) { 137 WorkListContents.erase(N); 138 } 139 140 SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo, 141 bool AddTo = true); 142 143 SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) { 144 return CombineTo(N, &Res, 1, AddTo); 145 } 146 147 SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1, 148 bool AddTo = true) { 149 SDValue To[] = { Res0, Res1 }; 150 return CombineTo(N, To, 2, AddTo); 151 } 152 153 void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO); 154 155 private: 156 157 /// SimplifyDemandedBits - Check the specified integer node value to see if 158 /// it can be simplified or if things it uses can be simplified by bit 159 /// propagation. If so, return true. 160 bool SimplifyDemandedBits(SDValue Op) { 161 unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits(); 162 APInt Demanded = APInt::getAllOnesValue(BitWidth); 163 return SimplifyDemandedBits(Op, Demanded); 164 } 165 166 bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded); 167 168 bool CombineToPreIndexedLoadStore(SDNode *N); 169 bool CombineToPostIndexedLoadStore(SDNode *N); 170 bool SliceUpLoad(SDNode *N); 171 172 /// \brief Replace an ISD::EXTRACT_VECTOR_ELT of a load with a narrowed 173 /// load. 174 /// 175 /// \param EVE ISD::EXTRACT_VECTOR_ELT to be replaced. 176 /// \param InVecVT type of the input vector to EVE with bitcasts resolved. 177 /// \param EltNo index of the vector element to load. 178 /// \param OriginalLoad load that EVE came from to be replaced. 179 /// \returns EVE on success SDValue() on failure. 180 SDValue ReplaceExtractVectorEltOfLoadWithNarrowedLoad( 181 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad); 182 void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad); 183 SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace); 184 SDValue SExtPromoteOperand(SDValue Op, EVT PVT); 185 SDValue ZExtPromoteOperand(SDValue Op, EVT PVT); 186 SDValue PromoteIntBinOp(SDValue Op); 187 SDValue PromoteIntShiftOp(SDValue Op); 188 SDValue PromoteExtend(SDValue Op); 189 bool PromoteLoad(SDValue Op); 190 191 void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs, 192 SDValue Trunc, SDValue ExtLoad, SDLoc DL, 193 ISD::NodeType ExtType); 194 195 /// combine - call the node-specific routine that knows how to fold each 196 /// particular type of node. If that doesn't do anything, try the 197 /// target-specific DAG combines. 198 SDValue combine(SDNode *N); 199 200 // Visitation implementation - Implement dag node combining for different 201 // node types. The semantics are as follows: 202 // Return Value: 203 // SDValue.getNode() == 0 - No change was made 204 // SDValue.getNode() == N - N was replaced, is dead and has been handled. 205 // otherwise - N should be replaced by the returned Operand. 206 // 207 SDValue visitTokenFactor(SDNode *N); 208 SDValue visitMERGE_VALUES(SDNode *N); 209 SDValue visitADD(SDNode *N); 210 SDValue visitSUB(SDNode *N); 211 SDValue visitADDC(SDNode *N); 212 SDValue visitSUBC(SDNode *N); 213 SDValue visitADDE(SDNode *N); 214 SDValue visitSUBE(SDNode *N); 215 SDValue visitMUL(SDNode *N); 216 SDValue visitSDIV(SDNode *N); 217 SDValue visitUDIV(SDNode *N); 218 SDValue visitSREM(SDNode *N); 219 SDValue visitUREM(SDNode *N); 220 SDValue visitMULHU(SDNode *N); 221 SDValue visitMULHS(SDNode *N); 222 SDValue visitSMUL_LOHI(SDNode *N); 223 SDValue visitUMUL_LOHI(SDNode *N); 224 SDValue visitSMULO(SDNode *N); 225 SDValue visitUMULO(SDNode *N); 226 SDValue visitSDIVREM(SDNode *N); 227 SDValue visitUDIVREM(SDNode *N); 228 SDValue visitAND(SDNode *N); 229 SDValue visitOR(SDNode *N); 230 SDValue visitXOR(SDNode *N); 231 SDValue SimplifyVBinOp(SDNode *N); 232 SDValue SimplifyVUnaryOp(SDNode *N); 233 SDValue visitSHL(SDNode *N); 234 SDValue visitSRA(SDNode *N); 235 SDValue visitSRL(SDNode *N); 236 SDValue visitRotate(SDNode *N); 237 SDValue visitCTLZ(SDNode *N); 238 SDValue visitCTLZ_ZERO_UNDEF(SDNode *N); 239 SDValue visitCTTZ(SDNode *N); 240 SDValue visitCTTZ_ZERO_UNDEF(SDNode *N); 241 SDValue visitCTPOP(SDNode *N); 242 SDValue visitSELECT(SDNode *N); 243 SDValue visitVSELECT(SDNode *N); 244 SDValue visitSELECT_CC(SDNode *N); 245 SDValue visitSETCC(SDNode *N); 246 SDValue visitSIGN_EXTEND(SDNode *N); 247 SDValue visitZERO_EXTEND(SDNode *N); 248 SDValue visitANY_EXTEND(SDNode *N); 249 SDValue visitSIGN_EXTEND_INREG(SDNode *N); 250 SDValue visitTRUNCATE(SDNode *N); 251 SDValue visitBITCAST(SDNode *N); 252 SDValue visitBUILD_PAIR(SDNode *N); 253 SDValue visitFADD(SDNode *N); 254 SDValue visitFSUB(SDNode *N); 255 SDValue visitFMUL(SDNode *N); 256 SDValue visitFMA(SDNode *N); 257 SDValue visitFDIV(SDNode *N); 258 SDValue visitFREM(SDNode *N); 259 SDValue visitFCOPYSIGN(SDNode *N); 260 SDValue visitSINT_TO_FP(SDNode *N); 261 SDValue visitUINT_TO_FP(SDNode *N); 262 SDValue visitFP_TO_SINT(SDNode *N); 263 SDValue visitFP_TO_UINT(SDNode *N); 264 SDValue visitFP_ROUND(SDNode *N); 265 SDValue visitFP_ROUND_INREG(SDNode *N); 266 SDValue visitFP_EXTEND(SDNode *N); 267 SDValue visitFNEG(SDNode *N); 268 SDValue visitFABS(SDNode *N); 269 SDValue visitFCEIL(SDNode *N); 270 SDValue visitFTRUNC(SDNode *N); 271 SDValue visitFFLOOR(SDNode *N); 272 SDValue visitBRCOND(SDNode *N); 273 SDValue visitBR_CC(SDNode *N); 274 SDValue visitLOAD(SDNode *N); 275 SDValue visitSTORE(SDNode *N); 276 SDValue visitINSERT_VECTOR_ELT(SDNode *N); 277 SDValue visitEXTRACT_VECTOR_ELT(SDNode *N); 278 SDValue visitBUILD_VECTOR(SDNode *N); 279 SDValue visitCONCAT_VECTORS(SDNode *N); 280 SDValue visitEXTRACT_SUBVECTOR(SDNode *N); 281 SDValue visitVECTOR_SHUFFLE(SDNode *N); 282 SDValue visitINSERT_SUBVECTOR(SDNode *N); 283 284 SDValue XformToShuffleWithZero(SDNode *N); 285 SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS); 286 287 SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt); 288 289 bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS); 290 SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N); 291 SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2); 292 SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2, 293 SDValue N3, ISD::CondCode CC, 294 bool NotExtCompare = false); 295 SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond, 296 SDLoc DL, bool foldBooleans = true); 297 298 bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS, 299 SDValue &CC) const; 300 bool isOneUseSetCC(SDValue N) const; 301 302 SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp, 303 unsigned HiOp); 304 SDValue CombineConsecutiveLoads(SDNode *N, EVT VT); 305 SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT); 306 SDValue BuildSDIV(SDNode *N); 307 SDValue BuildUDIV(SDNode *N); 308 SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1, 309 bool DemandHighBits = true); 310 SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1); 311 SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg, 312 SDValue InnerPos, SDValue InnerNeg, 313 unsigned PosOpcode, unsigned NegOpcode, 314 SDLoc DL); 315 SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL); 316 SDValue ReduceLoadWidth(SDNode *N); 317 SDValue ReduceLoadOpStoreWidth(SDNode *N); 318 SDValue TransformFPLoadStorePair(SDNode *N); 319 SDValue reduceBuildVecExtToExtBuildVec(SDNode *N); 320 SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N); 321 322 SDValue GetDemandedBits(SDValue V, const APInt &Mask); 323 324 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes, 325 /// looking for aliasing nodes and adding them to the Aliases vector. 326 void GatherAllAliases(SDNode *N, SDValue OriginalChain, 327 SmallVectorImpl<SDValue> &Aliases); 328 329 /// isAlias - Return true if there is any possibility that the two addresses 330 /// overlap. 331 bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const; 332 333 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes, 334 /// looking for a better chain (aliasing node.) 335 SDValue FindBetterChain(SDNode *N, SDValue Chain); 336 337 /// Merge consecutive store operations into a wide store. 338 /// This optimization uses wide integers or vectors when possible. 339 /// \return True if some memory operations were changed. 340 bool MergeConsecutiveStores(StoreSDNode *N); 341 342 /// \brief Try to transform a truncation where C is a constant: 343 /// (trunc (and X, C)) -> (and (trunc X), (trunc C)) 344 /// 345 /// \p N needs to be a truncation and its first operand an AND. Other 346 /// requirements are checked by the function (e.g. that trunc is 347 /// single-use) and if missed an empty SDValue is returned. 348 SDValue distributeTruncateThroughAnd(SDNode *N); 349 350 public: 351 DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL) 352 : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes), 353 OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) { 354 AttributeSet FnAttrs = 355 DAG.getMachineFunction().getFunction()->getAttributes(); 356 ForCodeSize = 357 FnAttrs.hasAttribute(AttributeSet::FunctionIndex, 358 Attribute::OptimizeForSize) || 359 FnAttrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::MinSize); 360 } 361 362 /// Run - runs the dag combiner on all nodes in the work list 363 void Run(CombineLevel AtLevel); 364 365 SelectionDAG &getDAG() const { return DAG; } 366 367 /// getShiftAmountTy - Returns a type large enough to hold any valid 368 /// shift amount - before type legalization these can be huge. 369 EVT getShiftAmountTy(EVT LHSTy) { 370 assert(LHSTy.isInteger() && "Shift amount is not an integer type!"); 371 if (LHSTy.isVector()) 372 return LHSTy; 373 return LegalTypes ? TLI.getScalarShiftAmountTy(LHSTy) 374 : TLI.getPointerTy(); 375 } 376 377 /// isTypeLegal - This method returns true if we are running before type 378 /// legalization or if the specified VT is legal. 379 bool isTypeLegal(const EVT &VT) { 380 if (!LegalTypes) return true; 381 return TLI.isTypeLegal(VT); 382 } 383 384 /// getSetCCResultType - Convenience wrapper around 385 /// TargetLowering::getSetCCResultType 386 EVT getSetCCResultType(EVT VT) const { 387 return TLI.getSetCCResultType(*DAG.getContext(), VT); 388 } 389 }; 390 } 391 392 393 namespace { 394 /// WorkListRemover - This class is a DAGUpdateListener that removes any deleted 395 /// nodes from the worklist. 396 class WorkListRemover : public SelectionDAG::DAGUpdateListener { 397 DAGCombiner &DC; 398 public: 399 explicit WorkListRemover(DAGCombiner &dc) 400 : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {} 401 402 void NodeDeleted(SDNode *N, SDNode *E) override { 403 DC.removeFromWorkList(N); 404 } 405 }; 406 } 407 408 //===----------------------------------------------------------------------===// 409 // TargetLowering::DAGCombinerInfo implementation 410 //===----------------------------------------------------------------------===// 411 412 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) { 413 ((DAGCombiner*)DC)->AddToWorkList(N); 414 } 415 416 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) { 417 ((DAGCombiner*)DC)->removeFromWorkList(N); 418 } 419 420 SDValue TargetLowering::DAGCombinerInfo:: 421 CombineTo(SDNode *N, const std::vector<SDValue> &To, bool AddTo) { 422 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo); 423 } 424 425 SDValue TargetLowering::DAGCombinerInfo:: 426 CombineTo(SDNode *N, SDValue Res, bool AddTo) { 427 return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo); 428 } 429 430 431 SDValue TargetLowering::DAGCombinerInfo:: 432 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) { 433 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo); 434 } 435 436 void TargetLowering::DAGCombinerInfo:: 437 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) { 438 return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO); 439 } 440 441 //===----------------------------------------------------------------------===// 442 // Helper Functions 443 //===----------------------------------------------------------------------===// 444 445 /// isNegatibleForFree - Return 1 if we can compute the negated form of the 446 /// specified expression for the same cost as the expression itself, or 2 if we 447 /// can compute the negated form more cheaply than the expression itself. 448 static char isNegatibleForFree(SDValue Op, bool LegalOperations, 449 const TargetLowering &TLI, 450 const TargetOptions *Options, 451 unsigned Depth = 0) { 452 // fneg is removable even if it has multiple uses. 453 if (Op.getOpcode() == ISD::FNEG) return 2; 454 455 // Don't allow anything with multiple uses. 456 if (!Op.hasOneUse()) return 0; 457 458 // Don't recurse exponentially. 459 if (Depth > 6) return 0; 460 461 switch (Op.getOpcode()) { 462 default: return false; 463 case ISD::ConstantFP: 464 // Don't invert constant FP values after legalize. The negated constant 465 // isn't necessarily legal. 466 return LegalOperations ? 0 : 1; 467 case ISD::FADD: 468 // FIXME: determine better conditions for this xform. 469 if (!Options->UnsafeFPMath) return 0; 470 471 // After operation legalization, it might not be legal to create new FSUBs. 472 if (LegalOperations && 473 !TLI.isOperationLegalOrCustom(ISD::FSUB, Op.getValueType())) 474 return 0; 475 476 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B) 477 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, 478 Options, Depth + 1)) 479 return V; 480 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A) 481 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options, 482 Depth + 1); 483 case ISD::FSUB: 484 // We can't turn -(A-B) into B-A when we honor signed zeros. 485 if (!Options->UnsafeFPMath) return 0; 486 487 // fold (fneg (fsub A, B)) -> (fsub B, A) 488 return 1; 489 490 case ISD::FMUL: 491 case ISD::FDIV: 492 if (Options->HonorSignDependentRoundingFPMath()) return 0; 493 494 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y)) 495 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, 496 Options, Depth + 1)) 497 return V; 498 499 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options, 500 Depth + 1); 501 502 case ISD::FP_EXTEND: 503 case ISD::FP_ROUND: 504 case ISD::FSIN: 505 return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options, 506 Depth + 1); 507 } 508 } 509 510 /// GetNegatedExpression - If isNegatibleForFree returns true, this function 511 /// returns the newly negated expression. 512 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG, 513 bool LegalOperations, unsigned Depth = 0) { 514 // fneg is removable even if it has multiple uses. 515 if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0); 516 517 // Don't allow anything with multiple uses. 518 assert(Op.hasOneUse() && "Unknown reuse!"); 519 520 assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree"); 521 switch (Op.getOpcode()) { 522 default: llvm_unreachable("Unknown code"); 523 case ISD::ConstantFP: { 524 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF(); 525 V.changeSign(); 526 return DAG.getConstantFP(V, Op.getValueType()); 527 } 528 case ISD::FADD: 529 // FIXME: determine better conditions for this xform. 530 assert(DAG.getTarget().Options.UnsafeFPMath); 531 532 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B) 533 if (isNegatibleForFree(Op.getOperand(0), LegalOperations, 534 DAG.getTargetLoweringInfo(), 535 &DAG.getTarget().Options, Depth+1)) 536 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(), 537 GetNegatedExpression(Op.getOperand(0), DAG, 538 LegalOperations, Depth+1), 539 Op.getOperand(1)); 540 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A) 541 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(), 542 GetNegatedExpression(Op.getOperand(1), DAG, 543 LegalOperations, Depth+1), 544 Op.getOperand(0)); 545 case ISD::FSUB: 546 // We can't turn -(A-B) into B-A when we honor signed zeros. 547 assert(DAG.getTarget().Options.UnsafeFPMath); 548 549 // fold (fneg (fsub 0, B)) -> B 550 if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0))) 551 if (N0CFP->getValueAPF().isZero()) 552 return Op.getOperand(1); 553 554 // fold (fneg (fsub A, B)) -> (fsub B, A) 555 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(), 556 Op.getOperand(1), Op.getOperand(0)); 557 558 case ISD::FMUL: 559 case ISD::FDIV: 560 assert(!DAG.getTarget().Options.HonorSignDependentRoundingFPMath()); 561 562 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) 563 if (isNegatibleForFree(Op.getOperand(0), LegalOperations, 564 DAG.getTargetLoweringInfo(), 565 &DAG.getTarget().Options, Depth+1)) 566 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(), 567 GetNegatedExpression(Op.getOperand(0), DAG, 568 LegalOperations, Depth+1), 569 Op.getOperand(1)); 570 571 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y)) 572 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(), 573 Op.getOperand(0), 574 GetNegatedExpression(Op.getOperand(1), DAG, 575 LegalOperations, Depth+1)); 576 577 case ISD::FP_EXTEND: 578 case ISD::FSIN: 579 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(), 580 GetNegatedExpression(Op.getOperand(0), DAG, 581 LegalOperations, Depth+1)); 582 case ISD::FP_ROUND: 583 return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(), 584 GetNegatedExpression(Op.getOperand(0), DAG, 585 LegalOperations, Depth+1), 586 Op.getOperand(1)); 587 } 588 } 589 590 // isSetCCEquivalent - Return true if this node is a setcc, or is a select_cc 591 // that selects between the target values used for true and false, making it 592 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to 593 // the appropriate nodes based on the type of node we are checking. This 594 // simplifies life a bit for the callers. 595 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS, 596 SDValue &CC) const { 597 if (N.getOpcode() == ISD::SETCC) { 598 LHS = N.getOperand(0); 599 RHS = N.getOperand(1); 600 CC = N.getOperand(2); 601 return true; 602 } 603 604 if (N.getOpcode() != ISD::SELECT_CC || 605 !TLI.isConstTrueVal(N.getOperand(2).getNode()) || 606 !TLI.isConstFalseVal(N.getOperand(3).getNode())) 607 return false; 608 609 LHS = N.getOperand(0); 610 RHS = N.getOperand(1); 611 CC = N.getOperand(4); 612 return true; 613 } 614 615 // isOneUseSetCC - Return true if this is a SetCC-equivalent operation with only 616 // one use. If this is true, it allows the users to invert the operation for 617 // free when it is profitable to do so. 618 bool DAGCombiner::isOneUseSetCC(SDValue N) const { 619 SDValue N0, N1, N2; 620 if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse()) 621 return true; 622 return false; 623 } 624 625 /// isConstantSplatVector - Returns true if N is a BUILD_VECTOR node whose 626 /// elements are all the same constant or undefined. 627 static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) { 628 BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N); 629 if (!C) 630 return false; 631 632 APInt SplatUndef; 633 unsigned SplatBitSize; 634 bool HasAnyUndefs; 635 EVT EltVT = N->getValueType(0).getVectorElementType(); 636 return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize, 637 HasAnyUndefs) && 638 EltVT.getSizeInBits() >= SplatBitSize); 639 } 640 641 // \brief Returns the SDNode if it is a constant BuildVector or constant. 642 static SDNode *isConstantBuildVectorOrConstantInt(SDValue N) { 643 if (isa<ConstantSDNode>(N)) 644 return N.getNode(); 645 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N); 646 if(BV && BV->isConstant()) 647 return BV; 648 return nullptr; 649 } 650 651 // \brief Returns the SDNode if it is a constant splat BuildVector or constant 652 // int. 653 static ConstantSDNode *isConstOrConstSplat(SDValue N) { 654 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) 655 return CN; 656 657 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) { 658 ConstantSDNode *CN = BV->getConstantSplatValue(); 659 660 // BuildVectors can truncate their operands. Ignore that case here. 661 if (CN && CN->getValueType(0) == N.getValueType().getScalarType()) 662 return CN; 663 } 664 665 return nullptr; 666 } 667 668 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL, 669 SDValue N0, SDValue N1) { 670 EVT VT = N0.getValueType(); 671 if (N0.getOpcode() == Opc) { 672 if (SDNode *L = isConstantBuildVectorOrConstantInt(N0.getOperand(1))) { 673 if (SDNode *R = isConstantBuildVectorOrConstantInt(N1)) { 674 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2)) 675 SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, L, R); 676 if (!OpNode.getNode()) 677 return SDValue(); 678 return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode); 679 } 680 if (N0.hasOneUse()) { 681 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one 682 // use 683 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1); 684 if (!OpNode.getNode()) 685 return SDValue(); 686 AddToWorkList(OpNode.getNode()); 687 return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1)); 688 } 689 } 690 } 691 692 if (N1.getOpcode() == Opc) { 693 if (SDNode *R = isConstantBuildVectorOrConstantInt(N1.getOperand(1))) { 694 if (SDNode *L = isConstantBuildVectorOrConstantInt(N0)) { 695 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2)) 696 SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, R, L); 697 if (!OpNode.getNode()) 698 return SDValue(); 699 return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode); 700 } 701 if (N1.hasOneUse()) { 702 // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one 703 // use 704 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0); 705 if (!OpNode.getNode()) 706 return SDValue(); 707 AddToWorkList(OpNode.getNode()); 708 return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1)); 709 } 710 } 711 } 712 713 return SDValue(); 714 } 715 716 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo, 717 bool AddTo) { 718 assert(N->getNumValues() == NumTo && "Broken CombineTo call!"); 719 ++NodesCombined; 720 DEBUG(dbgs() << "\nReplacing.1 "; 721 N->dump(&DAG); 722 dbgs() << "\nWith: "; 723 To[0].getNode()->dump(&DAG); 724 dbgs() << " and " << NumTo-1 << " other values\n"; 725 for (unsigned i = 0, e = NumTo; i != e; ++i) 726 assert((!To[i].getNode() || 727 N->getValueType(i) == To[i].getValueType()) && 728 "Cannot combine value to value of different type!")); 729 WorkListRemover DeadNodes(*this); 730 DAG.ReplaceAllUsesWith(N, To); 731 if (AddTo) { 732 // Push the new nodes and any users onto the worklist 733 for (unsigned i = 0, e = NumTo; i != e; ++i) { 734 if (To[i].getNode()) { 735 AddToWorkList(To[i].getNode()); 736 AddUsersToWorkList(To[i].getNode()); 737 } 738 } 739 } 740 741 // Finally, if the node is now dead, remove it from the graph. The node 742 // may not be dead if the replacement process recursively simplified to 743 // something else needing this node. 744 if (N->use_empty()) { 745 // Nodes can be reintroduced into the worklist. Make sure we do not 746 // process a node that has been replaced. 747 removeFromWorkList(N); 748 749 // Finally, since the node is now dead, remove it from the graph. 750 DAG.DeleteNode(N); 751 } 752 return SDValue(N, 0); 753 } 754 755 void DAGCombiner:: 756 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) { 757 // Replace all uses. If any nodes become isomorphic to other nodes and 758 // are deleted, make sure to remove them from our worklist. 759 WorkListRemover DeadNodes(*this); 760 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New); 761 762 // Push the new node and any (possibly new) users onto the worklist. 763 AddToWorkList(TLO.New.getNode()); 764 AddUsersToWorkList(TLO.New.getNode()); 765 766 // Finally, if the node is now dead, remove it from the graph. The node 767 // may not be dead if the replacement process recursively simplified to 768 // something else needing this node. 769 if (TLO.Old.getNode()->use_empty()) { 770 removeFromWorkList(TLO.Old.getNode()); 771 772 // If the operands of this node are only used by the node, they will now 773 // be dead. Make sure to visit them first to delete dead nodes early. 774 for (unsigned i = 0, e = TLO.Old.getNode()->getNumOperands(); i != e; ++i) 775 if (TLO.Old.getNode()->getOperand(i).getNode()->hasOneUse()) 776 AddToWorkList(TLO.Old.getNode()->getOperand(i).getNode()); 777 778 DAG.DeleteNode(TLO.Old.getNode()); 779 } 780 } 781 782 /// SimplifyDemandedBits - Check the specified integer node value to see if 783 /// it can be simplified or if things it uses can be simplified by bit 784 /// propagation. If so, return true. 785 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) { 786 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations); 787 APInt KnownZero, KnownOne; 788 if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO)) 789 return false; 790 791 // Revisit the node. 792 AddToWorkList(Op.getNode()); 793 794 // Replace the old value with the new one. 795 ++NodesCombined; 796 DEBUG(dbgs() << "\nReplacing.2 "; 797 TLO.Old.getNode()->dump(&DAG); 798 dbgs() << "\nWith: "; 799 TLO.New.getNode()->dump(&DAG); 800 dbgs() << '\n'); 801 802 CommitTargetLoweringOpt(TLO); 803 return true; 804 } 805 806 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) { 807 SDLoc dl(Load); 808 EVT VT = Load->getValueType(0); 809 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0)); 810 811 DEBUG(dbgs() << "\nReplacing.9 "; 812 Load->dump(&DAG); 813 dbgs() << "\nWith: "; 814 Trunc.getNode()->dump(&DAG); 815 dbgs() << '\n'); 816 WorkListRemover DeadNodes(*this); 817 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc); 818 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1)); 819 removeFromWorkList(Load); 820 DAG.DeleteNode(Load); 821 AddToWorkList(Trunc.getNode()); 822 } 823 824 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) { 825 Replace = false; 826 SDLoc dl(Op); 827 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) { 828 EVT MemVT = LD->getMemoryVT(); 829 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD) 830 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD 831 : ISD::EXTLOAD) 832 : LD->getExtensionType(); 833 Replace = true; 834 return DAG.getExtLoad(ExtType, dl, PVT, 835 LD->getChain(), LD->getBasePtr(), 836 MemVT, LD->getMemOperand()); 837 } 838 839 unsigned Opc = Op.getOpcode(); 840 switch (Opc) { 841 default: break; 842 case ISD::AssertSext: 843 return DAG.getNode(ISD::AssertSext, dl, PVT, 844 SExtPromoteOperand(Op.getOperand(0), PVT), 845 Op.getOperand(1)); 846 case ISD::AssertZext: 847 return DAG.getNode(ISD::AssertZext, dl, PVT, 848 ZExtPromoteOperand(Op.getOperand(0), PVT), 849 Op.getOperand(1)); 850 case ISD::Constant: { 851 unsigned ExtOpc = 852 Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 853 return DAG.getNode(ExtOpc, dl, PVT, Op); 854 } 855 } 856 857 if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT)) 858 return SDValue(); 859 return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op); 860 } 861 862 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) { 863 if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT)) 864 return SDValue(); 865 EVT OldVT = Op.getValueType(); 866 SDLoc dl(Op); 867 bool Replace = false; 868 SDValue NewOp = PromoteOperand(Op, PVT, Replace); 869 if (!NewOp.getNode()) 870 return SDValue(); 871 AddToWorkList(NewOp.getNode()); 872 873 if (Replace) 874 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode()); 875 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp, 876 DAG.getValueType(OldVT)); 877 } 878 879 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) { 880 EVT OldVT = Op.getValueType(); 881 SDLoc dl(Op); 882 bool Replace = false; 883 SDValue NewOp = PromoteOperand(Op, PVT, Replace); 884 if (!NewOp.getNode()) 885 return SDValue(); 886 AddToWorkList(NewOp.getNode()); 887 888 if (Replace) 889 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode()); 890 return DAG.getZeroExtendInReg(NewOp, dl, OldVT); 891 } 892 893 /// PromoteIntBinOp - Promote the specified integer binary operation if the 894 /// target indicates it is beneficial. e.g. On x86, it's usually better to 895 /// promote i16 operations to i32 since i16 instructions are longer. 896 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) { 897 if (!LegalOperations) 898 return SDValue(); 899 900 EVT VT = Op.getValueType(); 901 if (VT.isVector() || !VT.isInteger()) 902 return SDValue(); 903 904 // If operation type is 'undesirable', e.g. i16 on x86, consider 905 // promoting it. 906 unsigned Opc = Op.getOpcode(); 907 if (TLI.isTypeDesirableForOp(Opc, VT)) 908 return SDValue(); 909 910 EVT PVT = VT; 911 // Consult target whether it is a good idea to promote this operation and 912 // what's the right type to promote it to. 913 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 914 assert(PVT != VT && "Don't know what type to promote to!"); 915 916 bool Replace0 = false; 917 SDValue N0 = Op.getOperand(0); 918 SDValue NN0 = PromoteOperand(N0, PVT, Replace0); 919 if (!NN0.getNode()) 920 return SDValue(); 921 922 bool Replace1 = false; 923 SDValue N1 = Op.getOperand(1); 924 SDValue NN1; 925 if (N0 == N1) 926 NN1 = NN0; 927 else { 928 NN1 = PromoteOperand(N1, PVT, Replace1); 929 if (!NN1.getNode()) 930 return SDValue(); 931 } 932 933 AddToWorkList(NN0.getNode()); 934 if (NN1.getNode()) 935 AddToWorkList(NN1.getNode()); 936 937 if (Replace0) 938 ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode()); 939 if (Replace1) 940 ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode()); 941 942 DEBUG(dbgs() << "\nPromoting "; 943 Op.getNode()->dump(&DAG)); 944 SDLoc dl(Op); 945 return DAG.getNode(ISD::TRUNCATE, dl, VT, 946 DAG.getNode(Opc, dl, PVT, NN0, NN1)); 947 } 948 return SDValue(); 949 } 950 951 /// PromoteIntShiftOp - Promote the specified integer shift operation if the 952 /// target indicates it is beneficial. e.g. On x86, it's usually better to 953 /// promote i16 operations to i32 since i16 instructions are longer. 954 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) { 955 if (!LegalOperations) 956 return SDValue(); 957 958 EVT VT = Op.getValueType(); 959 if (VT.isVector() || !VT.isInteger()) 960 return SDValue(); 961 962 // If operation type is 'undesirable', e.g. i16 on x86, consider 963 // promoting it. 964 unsigned Opc = Op.getOpcode(); 965 if (TLI.isTypeDesirableForOp(Opc, VT)) 966 return SDValue(); 967 968 EVT PVT = VT; 969 // Consult target whether it is a good idea to promote this operation and 970 // what's the right type to promote it to. 971 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 972 assert(PVT != VT && "Don't know what type to promote to!"); 973 974 bool Replace = false; 975 SDValue N0 = Op.getOperand(0); 976 if (Opc == ISD::SRA) 977 N0 = SExtPromoteOperand(Op.getOperand(0), PVT); 978 else if (Opc == ISD::SRL) 979 N0 = ZExtPromoteOperand(Op.getOperand(0), PVT); 980 else 981 N0 = PromoteOperand(N0, PVT, Replace); 982 if (!N0.getNode()) 983 return SDValue(); 984 985 AddToWorkList(N0.getNode()); 986 if (Replace) 987 ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode()); 988 989 DEBUG(dbgs() << "\nPromoting "; 990 Op.getNode()->dump(&DAG)); 991 SDLoc dl(Op); 992 return DAG.getNode(ISD::TRUNCATE, dl, VT, 993 DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1))); 994 } 995 return SDValue(); 996 } 997 998 SDValue DAGCombiner::PromoteExtend(SDValue Op) { 999 if (!LegalOperations) 1000 return SDValue(); 1001 1002 EVT VT = Op.getValueType(); 1003 if (VT.isVector() || !VT.isInteger()) 1004 return SDValue(); 1005 1006 // If operation type is 'undesirable', e.g. i16 on x86, consider 1007 // promoting it. 1008 unsigned Opc = Op.getOpcode(); 1009 if (TLI.isTypeDesirableForOp(Opc, VT)) 1010 return SDValue(); 1011 1012 EVT PVT = VT; 1013 // Consult target whether it is a good idea to promote this operation and 1014 // what's the right type to promote it to. 1015 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 1016 assert(PVT != VT && "Don't know what type to promote to!"); 1017 // fold (aext (aext x)) -> (aext x) 1018 // fold (aext (zext x)) -> (zext x) 1019 // fold (aext (sext x)) -> (sext x) 1020 DEBUG(dbgs() << "\nPromoting "; 1021 Op.getNode()->dump(&DAG)); 1022 return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0)); 1023 } 1024 return SDValue(); 1025 } 1026 1027 bool DAGCombiner::PromoteLoad(SDValue Op) { 1028 if (!LegalOperations) 1029 return false; 1030 1031 EVT VT = Op.getValueType(); 1032 if (VT.isVector() || !VT.isInteger()) 1033 return false; 1034 1035 // If operation type is 'undesirable', e.g. i16 on x86, consider 1036 // promoting it. 1037 unsigned Opc = Op.getOpcode(); 1038 if (TLI.isTypeDesirableForOp(Opc, VT)) 1039 return false; 1040 1041 EVT PVT = VT; 1042 // Consult target whether it is a good idea to promote this operation and 1043 // what's the right type to promote it to. 1044 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 1045 assert(PVT != VT && "Don't know what type to promote to!"); 1046 1047 SDLoc dl(Op); 1048 SDNode *N = Op.getNode(); 1049 LoadSDNode *LD = cast<LoadSDNode>(N); 1050 EVT MemVT = LD->getMemoryVT(); 1051 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD) 1052 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD 1053 : ISD::EXTLOAD) 1054 : LD->getExtensionType(); 1055 SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT, 1056 LD->getChain(), LD->getBasePtr(), 1057 MemVT, LD->getMemOperand()); 1058 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD); 1059 1060 DEBUG(dbgs() << "\nPromoting "; 1061 N->dump(&DAG); 1062 dbgs() << "\nTo: "; 1063 Result.getNode()->dump(&DAG); 1064 dbgs() << '\n'); 1065 WorkListRemover DeadNodes(*this); 1066 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result); 1067 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1)); 1068 removeFromWorkList(N); 1069 DAG.DeleteNode(N); 1070 AddToWorkList(Result.getNode()); 1071 return true; 1072 } 1073 return false; 1074 } 1075 1076 1077 //===----------------------------------------------------------------------===// 1078 // Main DAG Combiner implementation 1079 //===----------------------------------------------------------------------===// 1080 1081 void DAGCombiner::Run(CombineLevel AtLevel) { 1082 // set the instance variables, so that the various visit routines may use it. 1083 Level = AtLevel; 1084 LegalOperations = Level >= AfterLegalizeVectorOps; 1085 LegalTypes = Level >= AfterLegalizeTypes; 1086 1087 // Add all the dag nodes to the worklist. 1088 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(), 1089 E = DAG.allnodes_end(); I != E; ++I) 1090 AddToWorkList(I); 1091 1092 // Create a dummy node (which is not added to allnodes), that adds a reference 1093 // to the root node, preventing it from being deleted, and tracking any 1094 // changes of the root. 1095 HandleSDNode Dummy(DAG.getRoot()); 1096 1097 // The root of the dag may dangle to deleted nodes until the dag combiner is 1098 // done. Set it to null to avoid confusion. 1099 DAG.setRoot(SDValue()); 1100 1101 // while the worklist isn't empty, find a node and 1102 // try and combine it. 1103 while (!WorkListContents.empty()) { 1104 SDNode *N; 1105 // The WorkListOrder holds the SDNodes in order, but it may contain 1106 // duplicates. 1107 // In order to avoid a linear scan, we use a set (O(log N)) to hold what the 1108 // worklist *should* contain, and check the node we want to visit is should 1109 // actually be visited. 1110 do { 1111 N = WorkListOrder.pop_back_val(); 1112 } while (!WorkListContents.erase(N)); 1113 1114 // If N has no uses, it is dead. Make sure to revisit all N's operands once 1115 // N is deleted from the DAG, since they too may now be dead or may have a 1116 // reduced number of uses, allowing other xforms. 1117 if (N->use_empty() && N != &Dummy) { 1118 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) 1119 AddToWorkList(N->getOperand(i).getNode()); 1120 1121 DAG.DeleteNode(N); 1122 continue; 1123 } 1124 1125 SDValue RV = combine(N); 1126 1127 if (!RV.getNode()) 1128 continue; 1129 1130 ++NodesCombined; 1131 1132 // If we get back the same node we passed in, rather than a new node or 1133 // zero, we know that the node must have defined multiple values and 1134 // CombineTo was used. Since CombineTo takes care of the worklist 1135 // mechanics for us, we have no work to do in this case. 1136 if (RV.getNode() == N) 1137 continue; 1138 1139 assert(N->getOpcode() != ISD::DELETED_NODE && 1140 RV.getNode()->getOpcode() != ISD::DELETED_NODE && 1141 "Node was deleted but visit returned new node!"); 1142 1143 DEBUG(dbgs() << "\nReplacing.3 "; 1144 N->dump(&DAG); 1145 dbgs() << "\nWith: "; 1146 RV.getNode()->dump(&DAG); 1147 dbgs() << '\n'); 1148 1149 // Transfer debug value. 1150 DAG.TransferDbgValues(SDValue(N, 0), RV); 1151 WorkListRemover DeadNodes(*this); 1152 if (N->getNumValues() == RV.getNode()->getNumValues()) 1153 DAG.ReplaceAllUsesWith(N, RV.getNode()); 1154 else { 1155 assert(N->getValueType(0) == RV.getValueType() && 1156 N->getNumValues() == 1 && "Type mismatch"); 1157 SDValue OpV = RV; 1158 DAG.ReplaceAllUsesWith(N, &OpV); 1159 } 1160 1161 // Push the new node and any users onto the worklist 1162 AddToWorkList(RV.getNode()); 1163 AddUsersToWorkList(RV.getNode()); 1164 1165 // Add any uses of the old node to the worklist in case this node is the 1166 // last one that uses them. They may become dead after this node is 1167 // deleted. 1168 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) 1169 AddToWorkList(N->getOperand(i).getNode()); 1170 1171 // Finally, if the node is now dead, remove it from the graph. The node 1172 // may not be dead if the replacement process recursively simplified to 1173 // something else needing this node. 1174 if (N->use_empty()) { 1175 // Nodes can be reintroduced into the worklist. Make sure we do not 1176 // process a node that has been replaced. 1177 removeFromWorkList(N); 1178 1179 // Finally, since the node is now dead, remove it from the graph. 1180 DAG.DeleteNode(N); 1181 } 1182 } 1183 1184 // If the root changed (e.g. it was a dead load, update the root). 1185 DAG.setRoot(Dummy.getValue()); 1186 DAG.RemoveDeadNodes(); 1187 } 1188 1189 SDValue DAGCombiner::visit(SDNode *N) { 1190 switch (N->getOpcode()) { 1191 default: break; 1192 case ISD::TokenFactor: return visitTokenFactor(N); 1193 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N); 1194 case ISD::ADD: return visitADD(N); 1195 case ISD::SUB: return visitSUB(N); 1196 case ISD::ADDC: return visitADDC(N); 1197 case ISD::SUBC: return visitSUBC(N); 1198 case ISD::ADDE: return visitADDE(N); 1199 case ISD::SUBE: return visitSUBE(N); 1200 case ISD::MUL: return visitMUL(N); 1201 case ISD::SDIV: return visitSDIV(N); 1202 case ISD::UDIV: return visitUDIV(N); 1203 case ISD::SREM: return visitSREM(N); 1204 case ISD::UREM: return visitUREM(N); 1205 case ISD::MULHU: return visitMULHU(N); 1206 case ISD::MULHS: return visitMULHS(N); 1207 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N); 1208 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N); 1209 case ISD::SMULO: return visitSMULO(N); 1210 case ISD::UMULO: return visitUMULO(N); 1211 case ISD::SDIVREM: return visitSDIVREM(N); 1212 case ISD::UDIVREM: return visitUDIVREM(N); 1213 case ISD::AND: return visitAND(N); 1214 case ISD::OR: return visitOR(N); 1215 case ISD::XOR: return visitXOR(N); 1216 case ISD::SHL: return visitSHL(N); 1217 case ISD::SRA: return visitSRA(N); 1218 case ISD::SRL: return visitSRL(N); 1219 case ISD::ROTR: 1220 case ISD::ROTL: return visitRotate(N); 1221 case ISD::CTLZ: return visitCTLZ(N); 1222 case ISD::CTLZ_ZERO_UNDEF: return visitCTLZ_ZERO_UNDEF(N); 1223 case ISD::CTTZ: return visitCTTZ(N); 1224 case ISD::CTTZ_ZERO_UNDEF: return visitCTTZ_ZERO_UNDEF(N); 1225 case ISD::CTPOP: return visitCTPOP(N); 1226 case ISD::SELECT: return visitSELECT(N); 1227 case ISD::VSELECT: return visitVSELECT(N); 1228 case ISD::SELECT_CC: return visitSELECT_CC(N); 1229 case ISD::SETCC: return visitSETCC(N); 1230 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N); 1231 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N); 1232 case ISD::ANY_EXTEND: return visitANY_EXTEND(N); 1233 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N); 1234 case ISD::TRUNCATE: return visitTRUNCATE(N); 1235 case ISD::BITCAST: return visitBITCAST(N); 1236 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N); 1237 case ISD::FADD: return visitFADD(N); 1238 case ISD::FSUB: return visitFSUB(N); 1239 case ISD::FMUL: return visitFMUL(N); 1240 case ISD::FMA: return visitFMA(N); 1241 case ISD::FDIV: return visitFDIV(N); 1242 case ISD::FREM: return visitFREM(N); 1243 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N); 1244 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N); 1245 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N); 1246 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N); 1247 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N); 1248 case ISD::FP_ROUND: return visitFP_ROUND(N); 1249 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N); 1250 case ISD::FP_EXTEND: return visitFP_EXTEND(N); 1251 case ISD::FNEG: return visitFNEG(N); 1252 case ISD::FABS: return visitFABS(N); 1253 case ISD::FFLOOR: return visitFFLOOR(N); 1254 case ISD::FCEIL: return visitFCEIL(N); 1255 case ISD::FTRUNC: return visitFTRUNC(N); 1256 case ISD::BRCOND: return visitBRCOND(N); 1257 case ISD::BR_CC: return visitBR_CC(N); 1258 case ISD::LOAD: return visitLOAD(N); 1259 case ISD::STORE: return visitSTORE(N); 1260 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N); 1261 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N); 1262 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N); 1263 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N); 1264 case ISD::EXTRACT_SUBVECTOR: return visitEXTRACT_SUBVECTOR(N); 1265 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N); 1266 case ISD::INSERT_SUBVECTOR: return visitINSERT_SUBVECTOR(N); 1267 } 1268 return SDValue(); 1269 } 1270 1271 SDValue DAGCombiner::combine(SDNode *N) { 1272 SDValue RV = visit(N); 1273 1274 // If nothing happened, try a target-specific DAG combine. 1275 if (!RV.getNode()) { 1276 assert(N->getOpcode() != ISD::DELETED_NODE && 1277 "Node was deleted but visit returned NULL!"); 1278 1279 if (N->getOpcode() >= ISD::BUILTIN_OP_END || 1280 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) { 1281 1282 // Expose the DAG combiner to the target combiner impls. 1283 TargetLowering::DAGCombinerInfo 1284 DagCombineInfo(DAG, Level, false, this); 1285 1286 RV = TLI.PerformDAGCombine(N, DagCombineInfo); 1287 } 1288 } 1289 1290 // If nothing happened still, try promoting the operation. 1291 if (!RV.getNode()) { 1292 switch (N->getOpcode()) { 1293 default: break; 1294 case ISD::ADD: 1295 case ISD::SUB: 1296 case ISD::MUL: 1297 case ISD::AND: 1298 case ISD::OR: 1299 case ISD::XOR: 1300 RV = PromoteIntBinOp(SDValue(N, 0)); 1301 break; 1302 case ISD::SHL: 1303 case ISD::SRA: 1304 case ISD::SRL: 1305 RV = PromoteIntShiftOp(SDValue(N, 0)); 1306 break; 1307 case ISD::SIGN_EXTEND: 1308 case ISD::ZERO_EXTEND: 1309 case ISD::ANY_EXTEND: 1310 RV = PromoteExtend(SDValue(N, 0)); 1311 break; 1312 case ISD::LOAD: 1313 if (PromoteLoad(SDValue(N, 0))) 1314 RV = SDValue(N, 0); 1315 break; 1316 } 1317 } 1318 1319 // If N is a commutative binary node, try commuting it to enable more 1320 // sdisel CSE. 1321 if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) && 1322 N->getNumValues() == 1) { 1323 SDValue N0 = N->getOperand(0); 1324 SDValue N1 = N->getOperand(1); 1325 1326 // Constant operands are canonicalized to RHS. 1327 if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) { 1328 SDValue Ops[] = {N1, N0}; 1329 SDNode *CSENode; 1330 if (const BinaryWithFlagsSDNode *BinNode = 1331 dyn_cast<BinaryWithFlagsSDNode>(N)) { 1332 CSENode = DAG.getNodeIfExists( 1333 N->getOpcode(), N->getVTList(), Ops, BinNode->hasNoUnsignedWrap(), 1334 BinNode->hasNoSignedWrap(), BinNode->isExact()); 1335 } else { 1336 CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops); 1337 } 1338 if (CSENode) 1339 return SDValue(CSENode, 0); 1340 } 1341 } 1342 1343 return RV; 1344 } 1345 1346 /// getInputChainForNode - Given a node, return its input chain if it has one, 1347 /// otherwise return a null sd operand. 1348 static SDValue getInputChainForNode(SDNode *N) { 1349 if (unsigned NumOps = N->getNumOperands()) { 1350 if (N->getOperand(0).getValueType() == MVT::Other) 1351 return N->getOperand(0); 1352 if (N->getOperand(NumOps-1).getValueType() == MVT::Other) 1353 return N->getOperand(NumOps-1); 1354 for (unsigned i = 1; i < NumOps-1; ++i) 1355 if (N->getOperand(i).getValueType() == MVT::Other) 1356 return N->getOperand(i); 1357 } 1358 return SDValue(); 1359 } 1360 1361 SDValue DAGCombiner::visitTokenFactor(SDNode *N) { 1362 // If N has two operands, where one has an input chain equal to the other, 1363 // the 'other' chain is redundant. 1364 if (N->getNumOperands() == 2) { 1365 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1)) 1366 return N->getOperand(0); 1367 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0)) 1368 return N->getOperand(1); 1369 } 1370 1371 SmallVector<SDNode *, 8> TFs; // List of token factors to visit. 1372 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor. 1373 SmallPtrSet<SDNode*, 16> SeenOps; 1374 bool Changed = false; // If we should replace this token factor. 1375 1376 // Start out with this token factor. 1377 TFs.push_back(N); 1378 1379 // Iterate through token factors. The TFs grows when new token factors are 1380 // encountered. 1381 for (unsigned i = 0; i < TFs.size(); ++i) { 1382 SDNode *TF = TFs[i]; 1383 1384 // Check each of the operands. 1385 for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) { 1386 SDValue Op = TF->getOperand(i); 1387 1388 switch (Op.getOpcode()) { 1389 case ISD::EntryToken: 1390 // Entry tokens don't need to be added to the list. They are 1391 // rededundant. 1392 Changed = true; 1393 break; 1394 1395 case ISD::TokenFactor: 1396 if (Op.hasOneUse() && 1397 std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) { 1398 // Queue up for processing. 1399 TFs.push_back(Op.getNode()); 1400 // Clean up in case the token factor is removed. 1401 AddToWorkList(Op.getNode()); 1402 Changed = true; 1403 break; 1404 } 1405 // Fall thru 1406 1407 default: 1408 // Only add if it isn't already in the list. 1409 if (SeenOps.insert(Op.getNode())) 1410 Ops.push_back(Op); 1411 else 1412 Changed = true; 1413 break; 1414 } 1415 } 1416 } 1417 1418 SDValue Result; 1419 1420 // If we've change things around then replace token factor. 1421 if (Changed) { 1422 if (Ops.empty()) { 1423 // The entry token is the only possible outcome. 1424 Result = DAG.getEntryNode(); 1425 } else { 1426 // New and improved token factor. 1427 Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops); 1428 } 1429 1430 // Don't add users to work list. 1431 return CombineTo(N, Result, false); 1432 } 1433 1434 return Result; 1435 } 1436 1437 /// MERGE_VALUES can always be eliminated. 1438 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) { 1439 WorkListRemover DeadNodes(*this); 1440 // Replacing results may cause a different MERGE_VALUES to suddenly 1441 // be CSE'd with N, and carry its uses with it. Iterate until no 1442 // uses remain, to ensure that the node can be safely deleted. 1443 // First add the users of this node to the work list so that they 1444 // can be tried again once they have new operands. 1445 AddUsersToWorkList(N); 1446 do { 1447 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) 1448 DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i)); 1449 } while (!N->use_empty()); 1450 removeFromWorkList(N); 1451 DAG.DeleteNode(N); 1452 return SDValue(N, 0); // Return N so it doesn't get rechecked! 1453 } 1454 1455 static 1456 SDValue combineShlAddConstant(SDLoc DL, SDValue N0, SDValue N1, 1457 SelectionDAG &DAG) { 1458 EVT VT = N0.getValueType(); 1459 SDValue N00 = N0.getOperand(0); 1460 SDValue N01 = N0.getOperand(1); 1461 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N01); 1462 1463 if (N01C && N00.getOpcode() == ISD::ADD && N00.getNode()->hasOneUse() && 1464 isa<ConstantSDNode>(N00.getOperand(1))) { 1465 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), ) 1466 N0 = DAG.getNode(ISD::ADD, SDLoc(N0), VT, 1467 DAG.getNode(ISD::SHL, SDLoc(N00), VT, 1468 N00.getOperand(0), N01), 1469 DAG.getNode(ISD::SHL, SDLoc(N01), VT, 1470 N00.getOperand(1), N01)); 1471 return DAG.getNode(ISD::ADD, DL, VT, N0, N1); 1472 } 1473 1474 return SDValue(); 1475 } 1476 1477 SDValue DAGCombiner::visitADD(SDNode *N) { 1478 SDValue N0 = N->getOperand(0); 1479 SDValue N1 = N->getOperand(1); 1480 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 1481 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 1482 EVT VT = N0.getValueType(); 1483 1484 // fold vector ops 1485 if (VT.isVector()) { 1486 SDValue FoldedVOp = SimplifyVBinOp(N); 1487 if (FoldedVOp.getNode()) return FoldedVOp; 1488 1489 // fold (add x, 0) -> x, vector edition 1490 if (ISD::isBuildVectorAllZeros(N1.getNode())) 1491 return N0; 1492 if (ISD::isBuildVectorAllZeros(N0.getNode())) 1493 return N1; 1494 } 1495 1496 // fold (add x, undef) -> undef 1497 if (N0.getOpcode() == ISD::UNDEF) 1498 return N0; 1499 if (N1.getOpcode() == ISD::UNDEF) 1500 return N1; 1501 // fold (add c1, c2) -> c1+c2 1502 if (N0C && N1C) 1503 return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C); 1504 // canonicalize constant to RHS 1505 if (N0C && !N1C) 1506 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0); 1507 // fold (add x, 0) -> x 1508 if (N1C && N1C->isNullValue()) 1509 return N0; 1510 // fold (add Sym, c) -> Sym+c 1511 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0)) 1512 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C && 1513 GA->getOpcode() == ISD::GlobalAddress) 1514 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT, 1515 GA->getOffset() + 1516 (uint64_t)N1C->getSExtValue()); 1517 // fold ((c1-A)+c2) -> (c1+c2)-A 1518 if (N1C && N0.getOpcode() == ISD::SUB) 1519 if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0))) 1520 return DAG.getNode(ISD::SUB, SDLoc(N), VT, 1521 DAG.getConstant(N1C->getAPIntValue()+ 1522 N0C->getAPIntValue(), VT), 1523 N0.getOperand(1)); 1524 // reassociate add 1525 SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1); 1526 if (RADD.getNode()) 1527 return RADD; 1528 // fold ((0-A) + B) -> B-A 1529 if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) && 1530 cast<ConstantSDNode>(N0.getOperand(0))->isNullValue()) 1531 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1)); 1532 // fold (A + (0-B)) -> A-B 1533 if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) && 1534 cast<ConstantSDNode>(N1.getOperand(0))->isNullValue()) 1535 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1)); 1536 // fold (A+(B-A)) -> B 1537 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1)) 1538 return N1.getOperand(0); 1539 // fold ((B-A)+A) -> B 1540 if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1)) 1541 return N0.getOperand(0); 1542 // fold (A+(B-(A+C))) to (B-C) 1543 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD && 1544 N0 == N1.getOperand(1).getOperand(0)) 1545 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0), 1546 N1.getOperand(1).getOperand(1)); 1547 // fold (A+(B-(C+A))) to (B-C) 1548 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD && 1549 N0 == N1.getOperand(1).getOperand(1)) 1550 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0), 1551 N1.getOperand(1).getOperand(0)); 1552 // fold (A+((B-A)+or-C)) to (B+or-C) 1553 if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) && 1554 N1.getOperand(0).getOpcode() == ISD::SUB && 1555 N0 == N1.getOperand(0).getOperand(1)) 1556 return DAG.getNode(N1.getOpcode(), SDLoc(N), VT, 1557 N1.getOperand(0).getOperand(0), N1.getOperand(1)); 1558 1559 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant 1560 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) { 1561 SDValue N00 = N0.getOperand(0); 1562 SDValue N01 = N0.getOperand(1); 1563 SDValue N10 = N1.getOperand(0); 1564 SDValue N11 = N1.getOperand(1); 1565 1566 if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10)) 1567 return DAG.getNode(ISD::SUB, SDLoc(N), VT, 1568 DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10), 1569 DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11)); 1570 } 1571 1572 if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0))) 1573 return SDValue(N, 0); 1574 1575 // fold (a+b) -> (a|b) iff a and b share no bits. 1576 if (VT.isInteger() && !VT.isVector()) { 1577 APInt LHSZero, LHSOne; 1578 APInt RHSZero, RHSOne; 1579 DAG.computeKnownBits(N0, LHSZero, LHSOne); 1580 1581 if (LHSZero.getBoolValue()) { 1582 DAG.computeKnownBits(N1, RHSZero, RHSOne); 1583 1584 // If all possibly-set bits on the LHS are clear on the RHS, return an OR. 1585 // If all possibly-set bits on the RHS are clear on the LHS, return an OR. 1586 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){ 1587 if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT)) 1588 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1); 1589 } 1590 } 1591 } 1592 1593 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), ) 1594 if (N0.getOpcode() == ISD::SHL && N0.getNode()->hasOneUse()) { 1595 SDValue Result = combineShlAddConstant(SDLoc(N), N0, N1, DAG); 1596 if (Result.getNode()) return Result; 1597 } 1598 if (N1.getOpcode() == ISD::SHL && N1.getNode()->hasOneUse()) { 1599 SDValue Result = combineShlAddConstant(SDLoc(N), N1, N0, DAG); 1600 if (Result.getNode()) return Result; 1601 } 1602 1603 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n)) 1604 if (N1.getOpcode() == ISD::SHL && 1605 N1.getOperand(0).getOpcode() == ISD::SUB) 1606 if (ConstantSDNode *C = 1607 dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0))) 1608 if (C->getAPIntValue() == 0) 1609 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, 1610 DAG.getNode(ISD::SHL, SDLoc(N), VT, 1611 N1.getOperand(0).getOperand(1), 1612 N1.getOperand(1))); 1613 if (N0.getOpcode() == ISD::SHL && 1614 N0.getOperand(0).getOpcode() == ISD::SUB) 1615 if (ConstantSDNode *C = 1616 dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0))) 1617 if (C->getAPIntValue() == 0) 1618 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, 1619 DAG.getNode(ISD::SHL, SDLoc(N), VT, 1620 N0.getOperand(0).getOperand(1), 1621 N0.getOperand(1))); 1622 1623 if (N1.getOpcode() == ISD::AND) { 1624 SDValue AndOp0 = N1.getOperand(0); 1625 ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1)); 1626 unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0); 1627 unsigned DestBits = VT.getScalarType().getSizeInBits(); 1628 1629 // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x)) 1630 // and similar xforms where the inner op is either ~0 or 0. 1631 if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) { 1632 SDLoc DL(N); 1633 return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0); 1634 } 1635 } 1636 1637 // add (sext i1), X -> sub X, (zext i1) 1638 if (N0.getOpcode() == ISD::SIGN_EXTEND && 1639 N0.getOperand(0).getValueType() == MVT::i1 && 1640 !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) { 1641 SDLoc DL(N); 1642 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)); 1643 return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt); 1644 } 1645 1646 return SDValue(); 1647 } 1648 1649 SDValue DAGCombiner::visitADDC(SDNode *N) { 1650 SDValue N0 = N->getOperand(0); 1651 SDValue N1 = N->getOperand(1); 1652 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 1653 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 1654 EVT VT = N0.getValueType(); 1655 1656 // If the flag result is dead, turn this into an ADD. 1657 if (!N->hasAnyUseOfValue(1)) 1658 return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1), 1659 DAG.getNode(ISD::CARRY_FALSE, 1660 SDLoc(N), MVT::Glue)); 1661 1662 // canonicalize constant to RHS. 1663 if (N0C && !N1C) 1664 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0); 1665 1666 // fold (addc x, 0) -> x + no carry out 1667 if (N1C && N1C->isNullValue()) 1668 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, 1669 SDLoc(N), MVT::Glue)); 1670 1671 // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits. 1672 APInt LHSZero, LHSOne; 1673 APInt RHSZero, RHSOne; 1674 DAG.computeKnownBits(N0, LHSZero, LHSOne); 1675 1676 if (LHSZero.getBoolValue()) { 1677 DAG.computeKnownBits(N1, RHSZero, RHSOne); 1678 1679 // If all possibly-set bits on the LHS are clear on the RHS, return an OR. 1680 // If all possibly-set bits on the RHS are clear on the LHS, return an OR. 1681 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero) 1682 return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1), 1683 DAG.getNode(ISD::CARRY_FALSE, 1684 SDLoc(N), MVT::Glue)); 1685 } 1686 1687 return SDValue(); 1688 } 1689 1690 SDValue DAGCombiner::visitADDE(SDNode *N) { 1691 SDValue N0 = N->getOperand(0); 1692 SDValue N1 = N->getOperand(1); 1693 SDValue CarryIn = N->getOperand(2); 1694 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 1695 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 1696 1697 // canonicalize constant to RHS 1698 if (N0C && !N1C) 1699 return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(), 1700 N1, N0, CarryIn); 1701 1702 // fold (adde x, y, false) -> (addc x, y) 1703 if (CarryIn.getOpcode() == ISD::CARRY_FALSE) 1704 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1); 1705 1706 return SDValue(); 1707 } 1708 1709 // Since it may not be valid to emit a fold to zero for vector initializers 1710 // check if we can before folding. 1711 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT, 1712 SelectionDAG &DAG, 1713 bool LegalOperations, bool LegalTypes) { 1714 if (!VT.isVector()) 1715 return DAG.getConstant(0, VT); 1716 if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT)) 1717 return DAG.getConstant(0, VT); 1718 return SDValue(); 1719 } 1720 1721 SDValue DAGCombiner::visitSUB(SDNode *N) { 1722 SDValue N0 = N->getOperand(0); 1723 SDValue N1 = N->getOperand(1); 1724 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode()); 1725 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode()); 1726 ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr : 1727 dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode()); 1728 EVT VT = N0.getValueType(); 1729 1730 // fold vector ops 1731 if (VT.isVector()) { 1732 SDValue FoldedVOp = SimplifyVBinOp(N); 1733 if (FoldedVOp.getNode()) return FoldedVOp; 1734 1735 // fold (sub x, 0) -> x, vector edition 1736 if (ISD::isBuildVectorAllZeros(N1.getNode())) 1737 return N0; 1738 } 1739 1740 // fold (sub x, x) -> 0 1741 // FIXME: Refactor this and xor and other similar operations together. 1742 if (N0 == N1) 1743 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes); 1744 // fold (sub c1, c2) -> c1-c2 1745 if (N0C && N1C) 1746 return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C); 1747 // fold (sub x, c) -> (add x, -c) 1748 if (N1C) 1749 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, 1750 DAG.getConstant(-N1C->getAPIntValue(), VT)); 1751 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) 1752 if (N0C && N0C->isAllOnesValue()) 1753 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0); 1754 // fold A-(A-B) -> B 1755 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0)) 1756 return N1.getOperand(1); 1757 // fold (A+B)-A -> B 1758 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1) 1759 return N0.getOperand(1); 1760 // fold (A+B)-B -> A 1761 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1) 1762 return N0.getOperand(0); 1763 // fold C2-(A+C1) -> (C2-C1)-A 1764 if (N1.getOpcode() == ISD::ADD && N0C && N1C1) { 1765 SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(), 1766 VT); 1767 return DAG.getNode(ISD::SUB, SDLoc(N), VT, NewC, 1768 N1.getOperand(0)); 1769 } 1770 // fold ((A+(B+or-C))-B) -> A+or-C 1771 if (N0.getOpcode() == ISD::ADD && 1772 (N0.getOperand(1).getOpcode() == ISD::SUB || 1773 N0.getOperand(1).getOpcode() == ISD::ADD) && 1774 N0.getOperand(1).getOperand(0) == N1) 1775 return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT, 1776 N0.getOperand(0), N0.getOperand(1).getOperand(1)); 1777 // fold ((A+(C+B))-B) -> A+C 1778 if (N0.getOpcode() == ISD::ADD && 1779 N0.getOperand(1).getOpcode() == ISD::ADD && 1780 N0.getOperand(1).getOperand(1) == N1) 1781 return DAG.getNode(ISD::ADD, SDLoc(N), VT, 1782 N0.getOperand(0), N0.getOperand(1).getOperand(0)); 1783 // fold ((A-(B-C))-C) -> A-B 1784 if (N0.getOpcode() == ISD::SUB && 1785 N0.getOperand(1).getOpcode() == ISD::SUB && 1786 N0.getOperand(1).getOperand(1) == N1) 1787 return DAG.getNode(ISD::SUB, SDLoc(N), VT, 1788 N0.getOperand(0), N0.getOperand(1).getOperand(0)); 1789 1790 // If either operand of a sub is undef, the result is undef 1791 if (N0.getOpcode() == ISD::UNDEF) 1792 return N0; 1793 if (N1.getOpcode() == ISD::UNDEF) 1794 return N1; 1795 1796 // If the relocation model supports it, consider symbol offsets. 1797 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0)) 1798 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) { 1799 // fold (sub Sym, c) -> Sym-c 1800 if (N1C && GA->getOpcode() == ISD::GlobalAddress) 1801 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT, 1802 GA->getOffset() - 1803 (uint64_t)N1C->getSExtValue()); 1804 // fold (sub Sym+c1, Sym+c2) -> c1-c2 1805 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1)) 1806 if (GA->getGlobal() == GB->getGlobal()) 1807 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(), 1808 VT); 1809 } 1810 1811 return SDValue(); 1812 } 1813 1814 SDValue DAGCombiner::visitSUBC(SDNode *N) { 1815 SDValue N0 = N->getOperand(0); 1816 SDValue N1 = N->getOperand(1); 1817 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 1818 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 1819 EVT VT = N0.getValueType(); 1820 1821 // If the flag result is dead, turn this into an SUB. 1822 if (!N->hasAnyUseOfValue(1)) 1823 return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1), 1824 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N), 1825 MVT::Glue)); 1826 1827 // fold (subc x, x) -> 0 + no borrow 1828 if (N0 == N1) 1829 return CombineTo(N, DAG.getConstant(0, VT), 1830 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N), 1831 MVT::Glue)); 1832 1833 // fold (subc x, 0) -> x + no borrow 1834 if (N1C && N1C->isNullValue()) 1835 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N), 1836 MVT::Glue)); 1837 1838 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow 1839 if (N0C && N0C->isAllOnesValue()) 1840 return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0), 1841 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N), 1842 MVT::Glue)); 1843 1844 return SDValue(); 1845 } 1846 1847 SDValue DAGCombiner::visitSUBE(SDNode *N) { 1848 SDValue N0 = N->getOperand(0); 1849 SDValue N1 = N->getOperand(1); 1850 SDValue CarryIn = N->getOperand(2); 1851 1852 // fold (sube x, y, false) -> (subc x, y) 1853 if (CarryIn.getOpcode() == ISD::CARRY_FALSE) 1854 return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1); 1855 1856 return SDValue(); 1857 } 1858 1859 SDValue DAGCombiner::visitMUL(SDNode *N) { 1860 SDValue N0 = N->getOperand(0); 1861 SDValue N1 = N->getOperand(1); 1862 EVT VT = N0.getValueType(); 1863 1864 // fold (mul x, undef) -> 0 1865 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF) 1866 return DAG.getConstant(0, VT); 1867 1868 bool N0IsConst = false; 1869 bool N1IsConst = false; 1870 APInt ConstValue0, ConstValue1; 1871 // fold vector ops 1872 if (VT.isVector()) { 1873 SDValue FoldedVOp = SimplifyVBinOp(N); 1874 if (FoldedVOp.getNode()) return FoldedVOp; 1875 1876 N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0); 1877 N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1); 1878 } else { 1879 N0IsConst = dyn_cast<ConstantSDNode>(N0) != nullptr; 1880 ConstValue0 = N0IsConst ? (dyn_cast<ConstantSDNode>(N0))->getAPIntValue() 1881 : APInt(); 1882 N1IsConst = dyn_cast<ConstantSDNode>(N1) != nullptr; 1883 ConstValue1 = N1IsConst ? (dyn_cast<ConstantSDNode>(N1))->getAPIntValue() 1884 : APInt(); 1885 } 1886 1887 // fold (mul c1, c2) -> c1*c2 1888 if (N0IsConst && N1IsConst) 1889 return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0.getNode(), N1.getNode()); 1890 1891 // canonicalize constant to RHS 1892 if (N0IsConst && !N1IsConst) 1893 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0); 1894 // fold (mul x, 0) -> 0 1895 if (N1IsConst && ConstValue1 == 0) 1896 return N1; 1897 // We require a splat of the entire scalar bit width for non-contiguous 1898 // bit patterns. 1899 bool IsFullSplat = 1900 ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits(); 1901 // fold (mul x, 1) -> x 1902 if (N1IsConst && ConstValue1 == 1 && IsFullSplat) 1903 return N0; 1904 // fold (mul x, -1) -> 0-x 1905 if (N1IsConst && ConstValue1.isAllOnesValue()) 1906 return DAG.getNode(ISD::SUB, SDLoc(N), VT, 1907 DAG.getConstant(0, VT), N0); 1908 // fold (mul x, (1 << c)) -> x << c 1909 if (N1IsConst && ConstValue1.isPowerOf2() && IsFullSplat) 1910 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, 1911 DAG.getConstant(ConstValue1.logBase2(), 1912 getShiftAmountTy(N0.getValueType()))); 1913 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c 1914 if (N1IsConst && (-ConstValue1).isPowerOf2() && IsFullSplat) { 1915 unsigned Log2Val = (-ConstValue1).logBase2(); 1916 // FIXME: If the input is something that is easily negated (e.g. a 1917 // single-use add), we should put the negate there. 1918 return DAG.getNode(ISD::SUB, SDLoc(N), VT, 1919 DAG.getConstant(0, VT), 1920 DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, 1921 DAG.getConstant(Log2Val, 1922 getShiftAmountTy(N0.getValueType())))); 1923 } 1924 1925 APInt Val; 1926 // (mul (shl X, c1), c2) -> (mul X, c2 << c1) 1927 if (N1IsConst && N0.getOpcode() == ISD::SHL && 1928 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) || 1929 isa<ConstantSDNode>(N0.getOperand(1)))) { 1930 SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT, 1931 N1, N0.getOperand(1)); 1932 AddToWorkList(C3.getNode()); 1933 return DAG.getNode(ISD::MUL, SDLoc(N), VT, 1934 N0.getOperand(0), C3); 1935 } 1936 1937 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one 1938 // use. 1939 { 1940 SDValue Sh(nullptr,0), Y(nullptr,0); 1941 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)). 1942 if (N0.getOpcode() == ISD::SHL && 1943 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) || 1944 isa<ConstantSDNode>(N0.getOperand(1))) && 1945 N0.getNode()->hasOneUse()) { 1946 Sh = N0; Y = N1; 1947 } else if (N1.getOpcode() == ISD::SHL && 1948 isa<ConstantSDNode>(N1.getOperand(1)) && 1949 N1.getNode()->hasOneUse()) { 1950 Sh = N1; Y = N0; 1951 } 1952 1953 if (Sh.getNode()) { 1954 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT, 1955 Sh.getOperand(0), Y); 1956 return DAG.getNode(ISD::SHL, SDLoc(N), VT, 1957 Mul, Sh.getOperand(1)); 1958 } 1959 } 1960 1961 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2) 1962 if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() && 1963 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) || 1964 isa<ConstantSDNode>(N0.getOperand(1)))) 1965 return DAG.getNode(ISD::ADD, SDLoc(N), VT, 1966 DAG.getNode(ISD::MUL, SDLoc(N0), VT, 1967 N0.getOperand(0), N1), 1968 DAG.getNode(ISD::MUL, SDLoc(N1), VT, 1969 N0.getOperand(1), N1)); 1970 1971 // reassociate mul 1972 SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1); 1973 if (RMUL.getNode()) 1974 return RMUL; 1975 1976 return SDValue(); 1977 } 1978 1979 SDValue DAGCombiner::visitSDIV(SDNode *N) { 1980 SDValue N0 = N->getOperand(0); 1981 SDValue N1 = N->getOperand(1); 1982 ConstantSDNode *N0C = isConstOrConstSplat(N0); 1983 ConstantSDNode *N1C = isConstOrConstSplat(N1); 1984 EVT VT = N->getValueType(0); 1985 1986 // fold vector ops 1987 if (VT.isVector()) { 1988 SDValue FoldedVOp = SimplifyVBinOp(N); 1989 if (FoldedVOp.getNode()) return FoldedVOp; 1990 } 1991 1992 // fold (sdiv c1, c2) -> c1/c2 1993 if (N0C && N1C && !N1C->isNullValue()) 1994 return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C); 1995 // fold (sdiv X, 1) -> X 1996 if (N1C && N1C->getAPIntValue() == 1LL) 1997 return N0; 1998 // fold (sdiv X, -1) -> 0-X 1999 if (N1C && N1C->isAllOnesValue()) 2000 return DAG.getNode(ISD::SUB, SDLoc(N), VT, 2001 DAG.getConstant(0, VT), N0); 2002 // If we know the sign bits of both operands are zero, strength reduce to a 2003 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2 2004 if (!VT.isVector()) { 2005 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0)) 2006 return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(), 2007 N0, N1); 2008 } 2009 2010 // fold (sdiv X, pow2) -> simple ops after legalize 2011 if (N1C && !N1C->isNullValue() && (N1C->getAPIntValue().isPowerOf2() || 2012 (-N1C->getAPIntValue()).isPowerOf2())) { 2013 // If dividing by powers of two is cheap, then don't perform the following 2014 // fold. 2015 if (TLI.isPow2DivCheap()) 2016 return SDValue(); 2017 2018 unsigned lg2 = N1C->getAPIntValue().countTrailingZeros(); 2019 2020 // Splat the sign bit into the register 2021 SDValue SGN = 2022 DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, 2023 DAG.getConstant(VT.getScalarSizeInBits() - 1, 2024 getShiftAmountTy(N0.getValueType()))); 2025 AddToWorkList(SGN.getNode()); 2026 2027 // Add (N0 < 0) ? abs2 - 1 : 0; 2028 SDValue SRL = 2029 DAG.getNode(ISD::SRL, SDLoc(N), VT, SGN, 2030 DAG.getConstant(VT.getScalarSizeInBits() - lg2, 2031 getShiftAmountTy(SGN.getValueType()))); 2032 SDValue ADD = DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, SRL); 2033 AddToWorkList(SRL.getNode()); 2034 AddToWorkList(ADD.getNode()); // Divide by pow2 2035 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), VT, ADD, 2036 DAG.getConstant(lg2, getShiftAmountTy(ADD.getValueType()))); 2037 2038 // If we're dividing by a positive value, we're done. Otherwise, we must 2039 // negate the result. 2040 if (N1C->getAPIntValue().isNonNegative()) 2041 return SRA; 2042 2043 AddToWorkList(SRA.getNode()); 2044 return DAG.getNode(ISD::SUB, SDLoc(N), VT, DAG.getConstant(0, VT), SRA); 2045 } 2046 2047 // if integer divide is expensive and we satisfy the requirements, emit an 2048 // alternate sequence. 2049 if (N1C && !TLI.isIntDivCheap()) { 2050 SDValue Op = BuildSDIV(N); 2051 if (Op.getNode()) return Op; 2052 } 2053 2054 // undef / X -> 0 2055 if (N0.getOpcode() == ISD::UNDEF) 2056 return DAG.getConstant(0, VT); 2057 // X / undef -> undef 2058 if (N1.getOpcode() == ISD::UNDEF) 2059 return N1; 2060 2061 return SDValue(); 2062 } 2063 2064 SDValue DAGCombiner::visitUDIV(SDNode *N) { 2065 SDValue N0 = N->getOperand(0); 2066 SDValue N1 = N->getOperand(1); 2067 ConstantSDNode *N0C = isConstOrConstSplat(N0); 2068 ConstantSDNode *N1C = isConstOrConstSplat(N1); 2069 EVT VT = N->getValueType(0); 2070 2071 // fold vector ops 2072 if (VT.isVector()) { 2073 SDValue FoldedVOp = SimplifyVBinOp(N); 2074 if (FoldedVOp.getNode()) return FoldedVOp; 2075 } 2076 2077 // fold (udiv c1, c2) -> c1/c2 2078 if (N0C && N1C && !N1C->isNullValue()) 2079 return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C); 2080 // fold (udiv x, (1 << c)) -> x >>u c 2081 if (N1C && N1C->getAPIntValue().isPowerOf2()) 2082 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, 2083 DAG.getConstant(N1C->getAPIntValue().logBase2(), 2084 getShiftAmountTy(N0.getValueType()))); 2085 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2 2086 if (N1.getOpcode() == ISD::SHL) { 2087 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) { 2088 if (SHC->getAPIntValue().isPowerOf2()) { 2089 EVT ADDVT = N1.getOperand(1).getValueType(); 2090 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N), ADDVT, 2091 N1.getOperand(1), 2092 DAG.getConstant(SHC->getAPIntValue() 2093 .logBase2(), 2094 ADDVT)); 2095 AddToWorkList(Add.getNode()); 2096 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, Add); 2097 } 2098 } 2099 } 2100 // fold (udiv x, c) -> alternate 2101 if (N1C && !TLI.isIntDivCheap()) { 2102 SDValue Op = BuildUDIV(N); 2103 if (Op.getNode()) return Op; 2104 } 2105 2106 // undef / X -> 0 2107 if (N0.getOpcode() == ISD::UNDEF) 2108 return DAG.getConstant(0, VT); 2109 // X / undef -> undef 2110 if (N1.getOpcode() == ISD::UNDEF) 2111 return N1; 2112 2113 return SDValue(); 2114 } 2115 2116 SDValue DAGCombiner::visitSREM(SDNode *N) { 2117 SDValue N0 = N->getOperand(0); 2118 SDValue N1 = N->getOperand(1); 2119 ConstantSDNode *N0C = isConstOrConstSplat(N0); 2120 ConstantSDNode *N1C = isConstOrConstSplat(N1); 2121 EVT VT = N->getValueType(0); 2122 2123 // fold (srem c1, c2) -> c1%c2 2124 if (N0C && N1C && !N1C->isNullValue()) 2125 return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C); 2126 // If we know the sign bits of both operands are zero, strength reduce to a 2127 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15 2128 if (!VT.isVector()) { 2129 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0)) 2130 return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1); 2131 } 2132 2133 // If X/C can be simplified by the division-by-constant logic, lower 2134 // X%C to the equivalent of X-X/C*C. 2135 if (N1C && !N1C->isNullValue()) { 2136 SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1); 2137 AddToWorkList(Div.getNode()); 2138 SDValue OptimizedDiv = combine(Div.getNode()); 2139 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) { 2140 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT, 2141 OptimizedDiv, N1); 2142 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul); 2143 AddToWorkList(Mul.getNode()); 2144 return Sub; 2145 } 2146 } 2147 2148 // undef % X -> 0 2149 if (N0.getOpcode() == ISD::UNDEF) 2150 return DAG.getConstant(0, VT); 2151 // X % undef -> undef 2152 if (N1.getOpcode() == ISD::UNDEF) 2153 return N1; 2154 2155 return SDValue(); 2156 } 2157 2158 SDValue DAGCombiner::visitUREM(SDNode *N) { 2159 SDValue N0 = N->getOperand(0); 2160 SDValue N1 = N->getOperand(1); 2161 ConstantSDNode *N0C = isConstOrConstSplat(N0); 2162 ConstantSDNode *N1C = isConstOrConstSplat(N1); 2163 EVT VT = N->getValueType(0); 2164 2165 // fold (urem c1, c2) -> c1%c2 2166 if (N0C && N1C && !N1C->isNullValue()) 2167 return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C); 2168 // fold (urem x, pow2) -> (and x, pow2-1) 2169 if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2()) 2170 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, 2171 DAG.getConstant(N1C->getAPIntValue()-1,VT)); 2172 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1)) 2173 if (N1.getOpcode() == ISD::SHL) { 2174 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) { 2175 if (SHC->getAPIntValue().isPowerOf2()) { 2176 SDValue Add = 2177 DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, 2178 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), 2179 VT)); 2180 AddToWorkList(Add.getNode()); 2181 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, Add); 2182 } 2183 } 2184 } 2185 2186 // If X/C can be simplified by the division-by-constant logic, lower 2187 // X%C to the equivalent of X-X/C*C. 2188 if (N1C && !N1C->isNullValue()) { 2189 SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1); 2190 AddToWorkList(Div.getNode()); 2191 SDValue OptimizedDiv = combine(Div.getNode()); 2192 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) { 2193 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT, 2194 OptimizedDiv, N1); 2195 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul); 2196 AddToWorkList(Mul.getNode()); 2197 return Sub; 2198 } 2199 } 2200 2201 // undef % X -> 0 2202 if (N0.getOpcode() == ISD::UNDEF) 2203 return DAG.getConstant(0, VT); 2204 // X % undef -> undef 2205 if (N1.getOpcode() == ISD::UNDEF) 2206 return N1; 2207 2208 return SDValue(); 2209 } 2210 2211 SDValue DAGCombiner::visitMULHS(SDNode *N) { 2212 SDValue N0 = N->getOperand(0); 2213 SDValue N1 = N->getOperand(1); 2214 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 2215 EVT VT = N->getValueType(0); 2216 SDLoc DL(N); 2217 2218 // fold (mulhs x, 0) -> 0 2219 if (N1C && N1C->isNullValue()) 2220 return N1; 2221 // fold (mulhs x, 1) -> (sra x, size(x)-1) 2222 if (N1C && N1C->getAPIntValue() == 1) 2223 return DAG.getNode(ISD::SRA, SDLoc(N), N0.getValueType(), N0, 2224 DAG.getConstant(N0.getValueType().getSizeInBits() - 1, 2225 getShiftAmountTy(N0.getValueType()))); 2226 // fold (mulhs x, undef) -> 0 2227 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF) 2228 return DAG.getConstant(0, VT); 2229 2230 // If the type twice as wide is legal, transform the mulhs to a wider multiply 2231 // plus a shift. 2232 if (VT.isSimple() && !VT.isVector()) { 2233 MVT Simple = VT.getSimpleVT(); 2234 unsigned SimpleSize = Simple.getSizeInBits(); 2235 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 2236 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 2237 N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0); 2238 N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1); 2239 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1); 2240 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1, 2241 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType()))); 2242 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1); 2243 } 2244 } 2245 2246 return SDValue(); 2247 } 2248 2249 SDValue DAGCombiner::visitMULHU(SDNode *N) { 2250 SDValue N0 = N->getOperand(0); 2251 SDValue N1 = N->getOperand(1); 2252 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 2253 EVT VT = N->getValueType(0); 2254 SDLoc DL(N); 2255 2256 // fold (mulhu x, 0) -> 0 2257 if (N1C && N1C->isNullValue()) 2258 return N1; 2259 // fold (mulhu x, 1) -> 0 2260 if (N1C && N1C->getAPIntValue() == 1) 2261 return DAG.getConstant(0, N0.getValueType()); 2262 // fold (mulhu x, undef) -> 0 2263 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF) 2264 return DAG.getConstant(0, VT); 2265 2266 // If the type twice as wide is legal, transform the mulhu to a wider multiply 2267 // plus a shift. 2268 if (VT.isSimple() && !VT.isVector()) { 2269 MVT Simple = VT.getSimpleVT(); 2270 unsigned SimpleSize = Simple.getSizeInBits(); 2271 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 2272 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 2273 N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0); 2274 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1); 2275 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1); 2276 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1, 2277 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType()))); 2278 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1); 2279 } 2280 } 2281 2282 return SDValue(); 2283 } 2284 2285 /// SimplifyNodeWithTwoResults - Perform optimizations common to nodes that 2286 /// compute two values. LoOp and HiOp give the opcodes for the two computations 2287 /// that are being performed. Return true if a simplification was made. 2288 /// 2289 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp, 2290 unsigned HiOp) { 2291 // If the high half is not needed, just compute the low half. 2292 bool HiExists = N->hasAnyUseOfValue(1); 2293 if (!HiExists && 2294 (!LegalOperations || 2295 TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) { 2296 SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), 2297 ArrayRef<SDUse>(N->op_begin(), N->op_end())); 2298 return CombineTo(N, Res, Res); 2299 } 2300 2301 // If the low half is not needed, just compute the high half. 2302 bool LoExists = N->hasAnyUseOfValue(0); 2303 if (!LoExists && 2304 (!LegalOperations || 2305 TLI.isOperationLegal(HiOp, N->getValueType(1)))) { 2306 SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), 2307 ArrayRef<SDUse>(N->op_begin(), N->op_end())); 2308 return CombineTo(N, Res, Res); 2309 } 2310 2311 // If both halves are used, return as it is. 2312 if (LoExists && HiExists) 2313 return SDValue(); 2314 2315 // If the two computed results can be simplified separately, separate them. 2316 if (LoExists) { 2317 SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), 2318 ArrayRef<SDUse>(N->op_begin(), N->op_end())); 2319 AddToWorkList(Lo.getNode()); 2320 SDValue LoOpt = combine(Lo.getNode()); 2321 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() && 2322 (!LegalOperations || 2323 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType()))) 2324 return CombineTo(N, LoOpt, LoOpt); 2325 } 2326 2327 if (HiExists) { 2328 SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), 2329 ArrayRef<SDUse>(N->op_begin(), N->op_end())); 2330 AddToWorkList(Hi.getNode()); 2331 SDValue HiOpt = combine(Hi.getNode()); 2332 if (HiOpt.getNode() && HiOpt != Hi && 2333 (!LegalOperations || 2334 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType()))) 2335 return CombineTo(N, HiOpt, HiOpt); 2336 } 2337 2338 return SDValue(); 2339 } 2340 2341 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) { 2342 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS); 2343 if (Res.getNode()) return Res; 2344 2345 EVT VT = N->getValueType(0); 2346 SDLoc DL(N); 2347 2348 // If the type twice as wide is legal, transform the mulhu to a wider multiply 2349 // plus a shift. 2350 if (VT.isSimple() && !VT.isVector()) { 2351 MVT Simple = VT.getSimpleVT(); 2352 unsigned SimpleSize = Simple.getSizeInBits(); 2353 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 2354 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 2355 SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0)); 2356 SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1)); 2357 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi); 2358 // Compute the high part as N1. 2359 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo, 2360 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType()))); 2361 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi); 2362 // Compute the low part as N0. 2363 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo); 2364 return CombineTo(N, Lo, Hi); 2365 } 2366 } 2367 2368 return SDValue(); 2369 } 2370 2371 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) { 2372 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU); 2373 if (Res.getNode()) return Res; 2374 2375 EVT VT = N->getValueType(0); 2376 SDLoc DL(N); 2377 2378 // If the type twice as wide is legal, transform the mulhu to a wider multiply 2379 // plus a shift. 2380 if (VT.isSimple() && !VT.isVector()) { 2381 MVT Simple = VT.getSimpleVT(); 2382 unsigned SimpleSize = Simple.getSizeInBits(); 2383 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 2384 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 2385 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0)); 2386 SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1)); 2387 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi); 2388 // Compute the high part as N1. 2389 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo, 2390 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType()))); 2391 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi); 2392 // Compute the low part as N0. 2393 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo); 2394 return CombineTo(N, Lo, Hi); 2395 } 2396 } 2397 2398 return SDValue(); 2399 } 2400 2401 SDValue DAGCombiner::visitSMULO(SDNode *N) { 2402 // (smulo x, 2) -> (saddo x, x) 2403 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1))) 2404 if (C2->getAPIntValue() == 2) 2405 return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(), 2406 N->getOperand(0), N->getOperand(0)); 2407 2408 return SDValue(); 2409 } 2410 2411 SDValue DAGCombiner::visitUMULO(SDNode *N) { 2412 // (umulo x, 2) -> (uaddo x, x) 2413 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1))) 2414 if (C2->getAPIntValue() == 2) 2415 return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(), 2416 N->getOperand(0), N->getOperand(0)); 2417 2418 return SDValue(); 2419 } 2420 2421 SDValue DAGCombiner::visitSDIVREM(SDNode *N) { 2422 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM); 2423 if (Res.getNode()) return Res; 2424 2425 return SDValue(); 2426 } 2427 2428 SDValue DAGCombiner::visitUDIVREM(SDNode *N) { 2429 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM); 2430 if (Res.getNode()) return Res; 2431 2432 return SDValue(); 2433 } 2434 2435 /// SimplifyBinOpWithSameOpcodeHands - If this is a binary operator with 2436 /// two operands of the same opcode, try to simplify it. 2437 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) { 2438 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1); 2439 EVT VT = N0.getValueType(); 2440 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!"); 2441 2442 // Bail early if none of these transforms apply. 2443 if (N0.getNode()->getNumOperands() == 0) return SDValue(); 2444 2445 // For each of OP in AND/OR/XOR: 2446 // fold (OP (zext x), (zext y)) -> (zext (OP x, y)) 2447 // fold (OP (sext x), (sext y)) -> (sext (OP x, y)) 2448 // fold (OP (aext x), (aext y)) -> (aext (OP x, y)) 2449 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free) 2450 // 2451 // do not sink logical op inside of a vector extend, since it may combine 2452 // into a vsetcc. 2453 EVT Op0VT = N0.getOperand(0).getValueType(); 2454 if ((N0.getOpcode() == ISD::ZERO_EXTEND || 2455 N0.getOpcode() == ISD::SIGN_EXTEND || 2456 // Avoid infinite looping with PromoteIntBinOp. 2457 (N0.getOpcode() == ISD::ANY_EXTEND && 2458 (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) || 2459 (N0.getOpcode() == ISD::TRUNCATE && 2460 (!TLI.isZExtFree(VT, Op0VT) || 2461 !TLI.isTruncateFree(Op0VT, VT)) && 2462 TLI.isTypeLegal(Op0VT))) && 2463 !VT.isVector() && 2464 Op0VT == N1.getOperand(0).getValueType() && 2465 (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) { 2466 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0), 2467 N0.getOperand(0).getValueType(), 2468 N0.getOperand(0), N1.getOperand(0)); 2469 AddToWorkList(ORNode.getNode()); 2470 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode); 2471 } 2472 2473 // For each of OP in SHL/SRL/SRA/AND... 2474 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z) 2475 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z) 2476 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z) 2477 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL || 2478 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) && 2479 N0.getOperand(1) == N1.getOperand(1)) { 2480 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0), 2481 N0.getOperand(0).getValueType(), 2482 N0.getOperand(0), N1.getOperand(0)); 2483 AddToWorkList(ORNode.getNode()); 2484 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, 2485 ORNode, N0.getOperand(1)); 2486 } 2487 2488 // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B)) 2489 // Only perform this optimization after type legalization and before 2490 // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by 2491 // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and 2492 // we don't want to undo this promotion. 2493 // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper 2494 // on scalars. 2495 if ((N0.getOpcode() == ISD::BITCAST || 2496 N0.getOpcode() == ISD::SCALAR_TO_VECTOR) && 2497 Level == AfterLegalizeTypes) { 2498 SDValue In0 = N0.getOperand(0); 2499 SDValue In1 = N1.getOperand(0); 2500 EVT In0Ty = In0.getValueType(); 2501 EVT In1Ty = In1.getValueType(); 2502 SDLoc DL(N); 2503 // If both incoming values are integers, and the original types are the 2504 // same. 2505 if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) { 2506 SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1); 2507 SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op); 2508 AddToWorkList(Op.getNode()); 2509 return BC; 2510 } 2511 } 2512 2513 // Xor/and/or are indifferent to the swizzle operation (shuffle of one value). 2514 // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B)) 2515 // If both shuffles use the same mask, and both shuffle within a single 2516 // vector, then it is worthwhile to move the swizzle after the operation. 2517 // The type-legalizer generates this pattern when loading illegal 2518 // vector types from memory. In many cases this allows additional shuffle 2519 // optimizations. 2520 // There are other cases where moving the shuffle after the xor/and/or 2521 // is profitable even if shuffles don't perform a swizzle. 2522 // If both shuffles use the same mask, and both shuffles have the same first 2523 // or second operand, then it might still be profitable to move the shuffle 2524 // after the xor/and/or operation. 2525 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) { 2526 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0); 2527 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1); 2528 2529 assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() && 2530 "Inputs to shuffles are not the same type"); 2531 2532 // Check that both shuffles use the same mask. The masks are known to be of 2533 // the same length because the result vector type is the same. 2534 // Check also that shuffles have only one use to avoid introducing extra 2535 // instructions. 2536 if (SVN0->hasOneUse() && SVN1->hasOneUse() && 2537 SVN0->getMask().equals(SVN1->getMask())) { 2538 SDValue ShOp = N0->getOperand(1); 2539 2540 // Don't try to fold this node if it requires introducing a 2541 // build vector of all zeros that might be illegal at this stage. 2542 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) { 2543 if (!LegalTypes) 2544 ShOp = DAG.getConstant(0, VT); 2545 else 2546 ShOp = SDValue(); 2547 } 2548 2549 // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C) 2550 // (OR (shuf (A, C), shuf (B, C)) -> shuf (OR (A, B), C) 2551 // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0) 2552 if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) { 2553 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT, 2554 N0->getOperand(0), N1->getOperand(0)); 2555 AddToWorkList(NewNode.getNode()); 2556 return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp, 2557 &SVN0->getMask()[0]); 2558 } 2559 2560 // Don't try to fold this node if it requires introducing a 2561 // build vector of all zeros that might be illegal at this stage. 2562 ShOp = N0->getOperand(0); 2563 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) { 2564 if (!LegalTypes) 2565 ShOp = DAG.getConstant(0, VT); 2566 else 2567 ShOp = SDValue(); 2568 } 2569 2570 // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B)) 2571 // (OR (shuf (C, A), shuf (C, B)) -> shuf (C, OR (A, B)) 2572 // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B)) 2573 if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) { 2574 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT, 2575 N0->getOperand(1), N1->getOperand(1)); 2576 AddToWorkList(NewNode.getNode()); 2577 return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode, 2578 &SVN0->getMask()[0]); 2579 } 2580 } 2581 } 2582 2583 return SDValue(); 2584 } 2585 2586 SDValue DAGCombiner::visitAND(SDNode *N) { 2587 SDValue N0 = N->getOperand(0); 2588 SDValue N1 = N->getOperand(1); 2589 SDValue LL, LR, RL, RR, CC0, CC1; 2590 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 2591 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 2592 EVT VT = N1.getValueType(); 2593 unsigned BitWidth = VT.getScalarType().getSizeInBits(); 2594 2595 // fold vector ops 2596 if (VT.isVector()) { 2597 SDValue FoldedVOp = SimplifyVBinOp(N); 2598 if (FoldedVOp.getNode()) return FoldedVOp; 2599 2600 // fold (and x, 0) -> 0, vector edition 2601 if (ISD::isBuildVectorAllZeros(N0.getNode())) 2602 return N0; 2603 if (ISD::isBuildVectorAllZeros(N1.getNode())) 2604 return N1; 2605 2606 // fold (and x, -1) -> x, vector edition 2607 if (ISD::isBuildVectorAllOnes(N0.getNode())) 2608 return N1; 2609 if (ISD::isBuildVectorAllOnes(N1.getNode())) 2610 return N0; 2611 } 2612 2613 // fold (and x, undef) -> 0 2614 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF) 2615 return DAG.getConstant(0, VT); 2616 // fold (and c1, c2) -> c1&c2 2617 if (N0C && N1C) 2618 return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C); 2619 // canonicalize constant to RHS 2620 if (N0C && !N1C) 2621 return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0); 2622 // fold (and x, -1) -> x 2623 if (N1C && N1C->isAllOnesValue()) 2624 return N0; 2625 // if (and x, c) is known to be zero, return 0 2626 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0), 2627 APInt::getAllOnesValue(BitWidth))) 2628 return DAG.getConstant(0, VT); 2629 // reassociate and 2630 SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1); 2631 if (RAND.getNode()) 2632 return RAND; 2633 // fold (and (or x, C), D) -> D if (C & D) == D 2634 if (N1C && N0.getOpcode() == ISD::OR) 2635 if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) 2636 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue()) 2637 return N1; 2638 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits. 2639 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) { 2640 SDValue N0Op0 = N0.getOperand(0); 2641 APInt Mask = ~N1C->getAPIntValue(); 2642 Mask = Mask.trunc(N0Op0.getValueSizeInBits()); 2643 if (DAG.MaskedValueIsZero(N0Op0, Mask)) { 2644 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), 2645 N0.getValueType(), N0Op0); 2646 2647 // Replace uses of the AND with uses of the Zero extend node. 2648 CombineTo(N, Zext); 2649 2650 // We actually want to replace all uses of the any_extend with the 2651 // zero_extend, to avoid duplicating things. This will later cause this 2652 // AND to be folded. 2653 CombineTo(N0.getNode(), Zext); 2654 return SDValue(N, 0); // Return N so it doesn't get rechecked! 2655 } 2656 } 2657 // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) -> 2658 // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must 2659 // already be zero by virtue of the width of the base type of the load. 2660 // 2661 // the 'X' node here can either be nothing or an extract_vector_elt to catch 2662 // more cases. 2663 if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT && 2664 N0.getOperand(0).getOpcode() == ISD::LOAD) || 2665 N0.getOpcode() == ISD::LOAD) { 2666 LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ? 2667 N0 : N0.getOperand(0) ); 2668 2669 // Get the constant (if applicable) the zero'th operand is being ANDed with. 2670 // This can be a pure constant or a vector splat, in which case we treat the 2671 // vector as a scalar and use the splat value. 2672 APInt Constant = APInt::getNullValue(1); 2673 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) { 2674 Constant = C->getAPIntValue(); 2675 } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) { 2676 APInt SplatValue, SplatUndef; 2677 unsigned SplatBitSize; 2678 bool HasAnyUndefs; 2679 bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef, 2680 SplatBitSize, HasAnyUndefs); 2681 if (IsSplat) { 2682 // Undef bits can contribute to a possible optimisation if set, so 2683 // set them. 2684 SplatValue |= SplatUndef; 2685 2686 // The splat value may be something like "0x00FFFFFF", which means 0 for 2687 // the first vector value and FF for the rest, repeating. We need a mask 2688 // that will apply equally to all members of the vector, so AND all the 2689 // lanes of the constant together. 2690 EVT VT = Vector->getValueType(0); 2691 unsigned BitWidth = VT.getVectorElementType().getSizeInBits(); 2692 2693 // If the splat value has been compressed to a bitlength lower 2694 // than the size of the vector lane, we need to re-expand it to 2695 // the lane size. 2696 if (BitWidth > SplatBitSize) 2697 for (SplatValue = SplatValue.zextOrTrunc(BitWidth); 2698 SplatBitSize < BitWidth; 2699 SplatBitSize = SplatBitSize * 2) 2700 SplatValue |= SplatValue.shl(SplatBitSize); 2701 2702 Constant = APInt::getAllOnesValue(BitWidth); 2703 for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i) 2704 Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth); 2705 } 2706 } 2707 2708 // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is 2709 // actually legal and isn't going to get expanded, else this is a false 2710 // optimisation. 2711 bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD, 2712 Load->getMemoryVT()); 2713 2714 // Resize the constant to the same size as the original memory access before 2715 // extension. If it is still the AllOnesValue then this AND is completely 2716 // unneeded. 2717 Constant = 2718 Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits()); 2719 2720 bool B; 2721 switch (Load->getExtensionType()) { 2722 default: B = false; break; 2723 case ISD::EXTLOAD: B = CanZextLoadProfitably; break; 2724 case ISD::ZEXTLOAD: 2725 case ISD::NON_EXTLOAD: B = true; break; 2726 } 2727 2728 if (B && Constant.isAllOnesValue()) { 2729 // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to 2730 // preserve semantics once we get rid of the AND. 2731 SDValue NewLoad(Load, 0); 2732 if (Load->getExtensionType() == ISD::EXTLOAD) { 2733 NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD, 2734 Load->getValueType(0), SDLoc(Load), 2735 Load->getChain(), Load->getBasePtr(), 2736 Load->getOffset(), Load->getMemoryVT(), 2737 Load->getMemOperand()); 2738 // Replace uses of the EXTLOAD with the new ZEXTLOAD. 2739 if (Load->getNumValues() == 3) { 2740 // PRE/POST_INC loads have 3 values. 2741 SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1), 2742 NewLoad.getValue(2) }; 2743 CombineTo(Load, To, 3, true); 2744 } else { 2745 CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1)); 2746 } 2747 } 2748 2749 // Fold the AND away, taking care not to fold to the old load node if we 2750 // replaced it. 2751 CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0); 2752 2753 return SDValue(N, 0); // Return N so it doesn't get rechecked! 2754 } 2755 } 2756 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y)) 2757 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){ 2758 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get(); 2759 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get(); 2760 2761 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 && 2762 LL.getValueType().isInteger()) { 2763 // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0) 2764 if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) { 2765 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0), 2766 LR.getValueType(), LL, RL); 2767 AddToWorkList(ORNode.getNode()); 2768 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1); 2769 } 2770 // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1) 2771 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) { 2772 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0), 2773 LR.getValueType(), LL, RL); 2774 AddToWorkList(ANDNode.getNode()); 2775 return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1); 2776 } 2777 // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1) 2778 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) { 2779 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0), 2780 LR.getValueType(), LL, RL); 2781 AddToWorkList(ORNode.getNode()); 2782 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1); 2783 } 2784 } 2785 // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2) 2786 if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) && 2787 Op0 == Op1 && LL.getValueType().isInteger() && 2788 Op0 == ISD::SETNE && ((cast<ConstantSDNode>(LR)->isNullValue() && 2789 cast<ConstantSDNode>(RR)->isAllOnesValue()) || 2790 (cast<ConstantSDNode>(LR)->isAllOnesValue() && 2791 cast<ConstantSDNode>(RR)->isNullValue()))) { 2792 SDValue ADDNode = DAG.getNode(ISD::ADD, SDLoc(N0), LL.getValueType(), 2793 LL, DAG.getConstant(1, LL.getValueType())); 2794 AddToWorkList(ADDNode.getNode()); 2795 return DAG.getSetCC(SDLoc(N), VT, ADDNode, 2796 DAG.getConstant(2, LL.getValueType()), ISD::SETUGE); 2797 } 2798 // canonicalize equivalent to ll == rl 2799 if (LL == RR && LR == RL) { 2800 Op1 = ISD::getSetCCSwappedOperands(Op1); 2801 std::swap(RL, RR); 2802 } 2803 if (LL == RL && LR == RR) { 2804 bool isInteger = LL.getValueType().isInteger(); 2805 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger); 2806 if (Result != ISD::SETCC_INVALID && 2807 (!LegalOperations || 2808 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) && 2809 TLI.isOperationLegal(ISD::SETCC, 2810 getSetCCResultType(N0.getSimpleValueType()))))) 2811 return DAG.getSetCC(SDLoc(N), N0.getValueType(), 2812 LL, LR, Result); 2813 } 2814 } 2815 2816 // Simplify: (and (op x...), (op y...)) -> (op (and x, y)) 2817 if (N0.getOpcode() == N1.getOpcode()) { 2818 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N); 2819 if (Tmp.getNode()) return Tmp; 2820 } 2821 2822 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1) 2823 // fold (and (sra)) -> (and (srl)) when possible. 2824 if (!VT.isVector() && 2825 SimplifyDemandedBits(SDValue(N, 0))) 2826 return SDValue(N, 0); 2827 2828 // fold (zext_inreg (extload x)) -> (zextload x) 2829 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) { 2830 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 2831 EVT MemVT = LN0->getMemoryVT(); 2832 // If we zero all the possible extended bits, then we can turn this into 2833 // a zextload if we are running before legalize or the operation is legal. 2834 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits(); 2835 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth, 2836 BitWidth - MemVT.getScalarType().getSizeInBits())) && 2837 ((!LegalOperations && !LN0->isVolatile()) || 2838 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) { 2839 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT, 2840 LN0->getChain(), LN0->getBasePtr(), 2841 MemVT, LN0->getMemOperand()); 2842 AddToWorkList(N); 2843 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 2844 return SDValue(N, 0); // Return N so it doesn't get rechecked! 2845 } 2846 } 2847 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use 2848 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 2849 N0.hasOneUse()) { 2850 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 2851 EVT MemVT = LN0->getMemoryVT(); 2852 // If we zero all the possible extended bits, then we can turn this into 2853 // a zextload if we are running before legalize or the operation is legal. 2854 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits(); 2855 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth, 2856 BitWidth - MemVT.getScalarType().getSizeInBits())) && 2857 ((!LegalOperations && !LN0->isVolatile()) || 2858 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) { 2859 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT, 2860 LN0->getChain(), LN0->getBasePtr(), 2861 MemVT, LN0->getMemOperand()); 2862 AddToWorkList(N); 2863 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 2864 return SDValue(N, 0); // Return N so it doesn't get rechecked! 2865 } 2866 } 2867 2868 // fold (and (load x), 255) -> (zextload x, i8) 2869 // fold (and (extload x, i16), 255) -> (zextload x, i8) 2870 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8) 2871 if (N1C && (N0.getOpcode() == ISD::LOAD || 2872 (N0.getOpcode() == ISD::ANY_EXTEND && 2873 N0.getOperand(0).getOpcode() == ISD::LOAD))) { 2874 bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND; 2875 LoadSDNode *LN0 = HasAnyExt 2876 ? cast<LoadSDNode>(N0.getOperand(0)) 2877 : cast<LoadSDNode>(N0); 2878 if (LN0->getExtensionType() != ISD::SEXTLOAD && 2879 LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) { 2880 uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits(); 2881 if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){ 2882 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits); 2883 EVT LoadedVT = LN0->getMemoryVT(); 2884 2885 if (ExtVT == LoadedVT && 2886 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) { 2887 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT; 2888 2889 SDValue NewLoad = 2890 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy, 2891 LN0->getChain(), LN0->getBasePtr(), ExtVT, 2892 LN0->getMemOperand()); 2893 AddToWorkList(N); 2894 CombineTo(LN0, NewLoad, NewLoad.getValue(1)); 2895 return SDValue(N, 0); // Return N so it doesn't get rechecked! 2896 } 2897 2898 // Do not change the width of a volatile load. 2899 // Do not generate loads of non-round integer types since these can 2900 // be expensive (and would be wrong if the type is not byte sized). 2901 if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() && 2902 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) { 2903 EVT PtrType = LN0->getOperand(1).getValueType(); 2904 2905 unsigned Alignment = LN0->getAlignment(); 2906 SDValue NewPtr = LN0->getBasePtr(); 2907 2908 // For big endian targets, we need to add an offset to the pointer 2909 // to load the correct bytes. For little endian systems, we merely 2910 // need to read fewer bytes from the same pointer. 2911 if (TLI.isBigEndian()) { 2912 unsigned LVTStoreBytes = LoadedVT.getStoreSize(); 2913 unsigned EVTStoreBytes = ExtVT.getStoreSize(); 2914 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes; 2915 NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0), PtrType, 2916 NewPtr, DAG.getConstant(PtrOff, PtrType)); 2917 Alignment = MinAlign(Alignment, PtrOff); 2918 } 2919 2920 AddToWorkList(NewPtr.getNode()); 2921 2922 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT; 2923 SDValue Load = 2924 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy, 2925 LN0->getChain(), NewPtr, 2926 LN0->getPointerInfo(), 2927 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(), 2928 Alignment, LN0->getTBAAInfo()); 2929 AddToWorkList(N); 2930 CombineTo(LN0, Load, Load.getValue(1)); 2931 return SDValue(N, 0); // Return N so it doesn't get rechecked! 2932 } 2933 } 2934 } 2935 } 2936 2937 if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL && 2938 VT.getSizeInBits() <= 64) { 2939 if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 2940 APInt ADDC = ADDI->getAPIntValue(); 2941 if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) { 2942 // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal 2943 // immediate for an add, but it is legal if its top c2 bits are set, 2944 // transform the ADD so the immediate doesn't need to be materialized 2945 // in a register. 2946 if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) { 2947 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(), 2948 SRLI->getZExtValue()); 2949 if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) { 2950 ADDC |= Mask; 2951 if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) { 2952 SDValue NewAdd = 2953 DAG.getNode(ISD::ADD, SDLoc(N0), VT, 2954 N0.getOperand(0), DAG.getConstant(ADDC, VT)); 2955 CombineTo(N0.getNode(), NewAdd); 2956 return SDValue(N, 0); // Return N so it doesn't get rechecked! 2957 } 2958 } 2959 } 2960 } 2961 } 2962 } 2963 2964 // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const) 2965 if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) { 2966 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0), 2967 N0.getOperand(1), false); 2968 if (BSwap.getNode()) 2969 return BSwap; 2970 } 2971 2972 return SDValue(); 2973 } 2974 2975 /// MatchBSwapHWord - Match (a >> 8) | (a << 8) as (bswap a) >> 16 2976 /// 2977 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1, 2978 bool DemandHighBits) { 2979 if (!LegalOperations) 2980 return SDValue(); 2981 2982 EVT VT = N->getValueType(0); 2983 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16) 2984 return SDValue(); 2985 if (!TLI.isOperationLegal(ISD::BSWAP, VT)) 2986 return SDValue(); 2987 2988 // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00) 2989 bool LookPassAnd0 = false; 2990 bool LookPassAnd1 = false; 2991 if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL) 2992 std::swap(N0, N1); 2993 if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL) 2994 std::swap(N0, N1); 2995 if (N0.getOpcode() == ISD::AND) { 2996 if (!N0.getNode()->hasOneUse()) 2997 return SDValue(); 2998 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 2999 if (!N01C || N01C->getZExtValue() != 0xFF00) 3000 return SDValue(); 3001 N0 = N0.getOperand(0); 3002 LookPassAnd0 = true; 3003 } 3004 3005 if (N1.getOpcode() == ISD::AND) { 3006 if (!N1.getNode()->hasOneUse()) 3007 return SDValue(); 3008 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 3009 if (!N11C || N11C->getZExtValue() != 0xFF) 3010 return SDValue(); 3011 N1 = N1.getOperand(0); 3012 LookPassAnd1 = true; 3013 } 3014 3015 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL) 3016 std::swap(N0, N1); 3017 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL) 3018 return SDValue(); 3019 if (!N0.getNode()->hasOneUse() || 3020 !N1.getNode()->hasOneUse()) 3021 return SDValue(); 3022 3023 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 3024 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 3025 if (!N01C || !N11C) 3026 return SDValue(); 3027 if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8) 3028 return SDValue(); 3029 3030 // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8) 3031 SDValue N00 = N0->getOperand(0); 3032 if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) { 3033 if (!N00.getNode()->hasOneUse()) 3034 return SDValue(); 3035 ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1)); 3036 if (!N001C || N001C->getZExtValue() != 0xFF) 3037 return SDValue(); 3038 N00 = N00.getOperand(0); 3039 LookPassAnd0 = true; 3040 } 3041 3042 SDValue N10 = N1->getOperand(0); 3043 if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) { 3044 if (!N10.getNode()->hasOneUse()) 3045 return SDValue(); 3046 ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1)); 3047 if (!N101C || N101C->getZExtValue() != 0xFF00) 3048 return SDValue(); 3049 N10 = N10.getOperand(0); 3050 LookPassAnd1 = true; 3051 } 3052 3053 if (N00 != N10) 3054 return SDValue(); 3055 3056 // Make sure everything beyond the low halfword gets set to zero since the SRL 3057 // 16 will clear the top bits. 3058 unsigned OpSizeInBits = VT.getSizeInBits(); 3059 if (DemandHighBits && OpSizeInBits > 16) { 3060 // If the left-shift isn't masked out then the only way this is a bswap is 3061 // if all bits beyond the low 8 are 0. In that case the entire pattern 3062 // reduces to a left shift anyway: leave it for other parts of the combiner. 3063 if (!LookPassAnd0) 3064 return SDValue(); 3065 3066 // However, if the right shift isn't masked out then it might be because 3067 // it's not needed. See if we can spot that too. 3068 if (!LookPassAnd1 && 3069 !DAG.MaskedValueIsZero( 3070 N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16))) 3071 return SDValue(); 3072 } 3073 3074 SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00); 3075 if (OpSizeInBits > 16) 3076 Res = DAG.getNode(ISD::SRL, SDLoc(N), VT, Res, 3077 DAG.getConstant(OpSizeInBits-16, getShiftAmountTy(VT))); 3078 return Res; 3079 } 3080 3081 /// isBSwapHWordElement - Return true if the specified node is an element 3082 /// that makes up a 32-bit packed halfword byteswap. i.e. 3083 /// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8) 3084 static bool isBSwapHWordElement(SDValue N, SmallVectorImpl<SDNode *> &Parts) { 3085 if (!N.getNode()->hasOneUse()) 3086 return false; 3087 3088 unsigned Opc = N.getOpcode(); 3089 if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL) 3090 return false; 3091 3092 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1)); 3093 if (!N1C) 3094 return false; 3095 3096 unsigned Num; 3097 switch (N1C->getZExtValue()) { 3098 default: 3099 return false; 3100 case 0xFF: Num = 0; break; 3101 case 0xFF00: Num = 1; break; 3102 case 0xFF0000: Num = 2; break; 3103 case 0xFF000000: Num = 3; break; 3104 } 3105 3106 // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00). 3107 SDValue N0 = N.getOperand(0); 3108 if (Opc == ISD::AND) { 3109 if (Num == 0 || Num == 2) { 3110 // (x >> 8) & 0xff 3111 // (x >> 8) & 0xff0000 3112 if (N0.getOpcode() != ISD::SRL) 3113 return false; 3114 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 3115 if (!C || C->getZExtValue() != 8) 3116 return false; 3117 } else { 3118 // (x << 8) & 0xff00 3119 // (x << 8) & 0xff000000 3120 if (N0.getOpcode() != ISD::SHL) 3121 return false; 3122 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 3123 if (!C || C->getZExtValue() != 8) 3124 return false; 3125 } 3126 } else if (Opc == ISD::SHL) { 3127 // (x & 0xff) << 8 3128 // (x & 0xff0000) << 8 3129 if (Num != 0 && Num != 2) 3130 return false; 3131 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1)); 3132 if (!C || C->getZExtValue() != 8) 3133 return false; 3134 } else { // Opc == ISD::SRL 3135 // (x & 0xff00) >> 8 3136 // (x & 0xff000000) >> 8 3137 if (Num != 1 && Num != 3) 3138 return false; 3139 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1)); 3140 if (!C || C->getZExtValue() != 8) 3141 return false; 3142 } 3143 3144 if (Parts[Num]) 3145 return false; 3146 3147 Parts[Num] = N0.getOperand(0).getNode(); 3148 return true; 3149 } 3150 3151 /// MatchBSwapHWord - Match a 32-bit packed halfword bswap. That is 3152 /// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8) 3153 /// => (rotl (bswap x), 16) 3154 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) { 3155 if (!LegalOperations) 3156 return SDValue(); 3157 3158 EVT VT = N->getValueType(0); 3159 if (VT != MVT::i32) 3160 return SDValue(); 3161 if (!TLI.isOperationLegal(ISD::BSWAP, VT)) 3162 return SDValue(); 3163 3164 SmallVector<SDNode*,4> Parts(4, (SDNode*)nullptr); 3165 // Look for either 3166 // (or (or (and), (and)), (or (and), (and))) 3167 // (or (or (or (and), (and)), (and)), (and)) 3168 if (N0.getOpcode() != ISD::OR) 3169 return SDValue(); 3170 SDValue N00 = N0.getOperand(0); 3171 SDValue N01 = N0.getOperand(1); 3172 3173 if (N1.getOpcode() == ISD::OR && 3174 N00.getNumOperands() == 2 && N01.getNumOperands() == 2) { 3175 // (or (or (and), (and)), (or (and), (and))) 3176 SDValue N000 = N00.getOperand(0); 3177 if (!isBSwapHWordElement(N000, Parts)) 3178 return SDValue(); 3179 3180 SDValue N001 = N00.getOperand(1); 3181 if (!isBSwapHWordElement(N001, Parts)) 3182 return SDValue(); 3183 SDValue N010 = N01.getOperand(0); 3184 if (!isBSwapHWordElement(N010, Parts)) 3185 return SDValue(); 3186 SDValue N011 = N01.getOperand(1); 3187 if (!isBSwapHWordElement(N011, Parts)) 3188 return SDValue(); 3189 } else { 3190 // (or (or (or (and), (and)), (and)), (and)) 3191 if (!isBSwapHWordElement(N1, Parts)) 3192 return SDValue(); 3193 if (!isBSwapHWordElement(N01, Parts)) 3194 return SDValue(); 3195 if (N00.getOpcode() != ISD::OR) 3196 return SDValue(); 3197 SDValue N000 = N00.getOperand(0); 3198 if (!isBSwapHWordElement(N000, Parts)) 3199 return SDValue(); 3200 SDValue N001 = N00.getOperand(1); 3201 if (!isBSwapHWordElement(N001, Parts)) 3202 return SDValue(); 3203 } 3204 3205 // Make sure the parts are all coming from the same node. 3206 if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3]) 3207 return SDValue(); 3208 3209 SDValue BSwap = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, 3210 SDValue(Parts[0],0)); 3211 3212 // Result of the bswap should be rotated by 16. If it's not legal, then 3213 // do (x << 16) | (x >> 16). 3214 SDValue ShAmt = DAG.getConstant(16, getShiftAmountTy(VT)); 3215 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT)) 3216 return DAG.getNode(ISD::ROTL, SDLoc(N), VT, BSwap, ShAmt); 3217 if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT)) 3218 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, BSwap, ShAmt); 3219 return DAG.getNode(ISD::OR, SDLoc(N), VT, 3220 DAG.getNode(ISD::SHL, SDLoc(N), VT, BSwap, ShAmt), 3221 DAG.getNode(ISD::SRL, SDLoc(N), VT, BSwap, ShAmt)); 3222 } 3223 3224 SDValue DAGCombiner::visitOR(SDNode *N) { 3225 SDValue N0 = N->getOperand(0); 3226 SDValue N1 = N->getOperand(1); 3227 SDValue LL, LR, RL, RR, CC0, CC1; 3228 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 3229 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 3230 EVT VT = N1.getValueType(); 3231 3232 // fold vector ops 3233 if (VT.isVector()) { 3234 SDValue FoldedVOp = SimplifyVBinOp(N); 3235 if (FoldedVOp.getNode()) return FoldedVOp; 3236 3237 // fold (or x, 0) -> x, vector edition 3238 if (ISD::isBuildVectorAllZeros(N0.getNode())) 3239 return N1; 3240 if (ISD::isBuildVectorAllZeros(N1.getNode())) 3241 return N0; 3242 3243 // fold (or x, -1) -> -1, vector edition 3244 if (ISD::isBuildVectorAllOnes(N0.getNode())) 3245 return N0; 3246 if (ISD::isBuildVectorAllOnes(N1.getNode())) 3247 return N1; 3248 3249 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1) 3250 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2) 3251 // Do this only if the resulting shuffle is legal. 3252 if (isa<ShuffleVectorSDNode>(N0) && 3253 isa<ShuffleVectorSDNode>(N1) && 3254 N0->getOperand(1) == N1->getOperand(1) && 3255 ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) { 3256 bool CanFold = true; 3257 unsigned NumElts = VT.getVectorNumElements(); 3258 const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0); 3259 const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1); 3260 // We construct two shuffle masks: 3261 // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand 3262 // and N1 as the second operand. 3263 // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand 3264 // and N0 as the second operand. 3265 // We do this because OR is commutable and therefore there might be 3266 // two ways to fold this node into a shuffle. 3267 SmallVector<int,4> Mask1; 3268 SmallVector<int,4> Mask2; 3269 3270 for (unsigned i = 0; i != NumElts && CanFold; ++i) { 3271 int M0 = SV0->getMaskElt(i); 3272 int M1 = SV1->getMaskElt(i); 3273 3274 // Both shuffle indexes are undef. Propagate Undef. 3275 if (M0 < 0 && M1 < 0) { 3276 Mask1.push_back(M0); 3277 Mask2.push_back(M0); 3278 continue; 3279 } 3280 3281 if (M0 < 0 || M1 < 0 || 3282 (M0 < (int)NumElts && M1 < (int)NumElts) || 3283 (M0 >= (int)NumElts && M1 >= (int)NumElts)) { 3284 CanFold = false; 3285 break; 3286 } 3287 3288 Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts); 3289 Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts); 3290 } 3291 3292 if (CanFold) { 3293 // Fold this sequence only if the resulting shuffle is 'legal'. 3294 if (TLI.isShuffleMaskLegal(Mask1, VT)) 3295 return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0), 3296 N1->getOperand(0), &Mask1[0]); 3297 if (TLI.isShuffleMaskLegal(Mask2, VT)) 3298 return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0), 3299 N0->getOperand(0), &Mask2[0]); 3300 } 3301 } 3302 } 3303 3304 // fold (or x, undef) -> -1 3305 if (!LegalOperations && 3306 (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) { 3307 EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT; 3308 return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT); 3309 } 3310 // fold (or c1, c2) -> c1|c2 3311 if (N0C && N1C) 3312 return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C); 3313 // canonicalize constant to RHS 3314 if (N0C && !N1C) 3315 return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0); 3316 // fold (or x, 0) -> x 3317 if (N1C && N1C->isNullValue()) 3318 return N0; 3319 // fold (or x, -1) -> -1 3320 if (N1C && N1C->isAllOnesValue()) 3321 return N1; 3322 // fold (or x, c) -> c iff (x & ~c) == 0 3323 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue())) 3324 return N1; 3325 3326 // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16) 3327 SDValue BSwap = MatchBSwapHWord(N, N0, N1); 3328 if (BSwap.getNode()) 3329 return BSwap; 3330 BSwap = MatchBSwapHWordLow(N, N0, N1); 3331 if (BSwap.getNode()) 3332 return BSwap; 3333 3334 // reassociate or 3335 SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1); 3336 if (ROR.getNode()) 3337 return ROR; 3338 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2) 3339 // iff (c1 & c2) == 0. 3340 if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() && 3341 isa<ConstantSDNode>(N0.getOperand(1))) { 3342 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1)); 3343 if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) { 3344 SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1); 3345 if (!COR.getNode()) 3346 return SDValue(); 3347 return DAG.getNode(ISD::AND, SDLoc(N), VT, 3348 DAG.getNode(ISD::OR, SDLoc(N0), VT, 3349 N0.getOperand(0), N1), COR); 3350 } 3351 } 3352 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y)) 3353 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){ 3354 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get(); 3355 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get(); 3356 3357 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 && 3358 LL.getValueType().isInteger()) { 3359 // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0) 3360 // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0) 3361 if (cast<ConstantSDNode>(LR)->isNullValue() && 3362 (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) { 3363 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR), 3364 LR.getValueType(), LL, RL); 3365 AddToWorkList(ORNode.getNode()); 3366 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1); 3367 } 3368 // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1) 3369 // fold (or (setgt X, -1), (setgt Y -1)) -> (setgt (and X, Y), -1) 3370 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && 3371 (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) { 3372 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR), 3373 LR.getValueType(), LL, RL); 3374 AddToWorkList(ANDNode.getNode()); 3375 return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1); 3376 } 3377 } 3378 // canonicalize equivalent to ll == rl 3379 if (LL == RR && LR == RL) { 3380 Op1 = ISD::getSetCCSwappedOperands(Op1); 3381 std::swap(RL, RR); 3382 } 3383 if (LL == RL && LR == RR) { 3384 bool isInteger = LL.getValueType().isInteger(); 3385 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger); 3386 if (Result != ISD::SETCC_INVALID && 3387 (!LegalOperations || 3388 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) && 3389 TLI.isOperationLegal(ISD::SETCC, 3390 getSetCCResultType(N0.getValueType()))))) 3391 return DAG.getSetCC(SDLoc(N), N0.getValueType(), 3392 LL, LR, Result); 3393 } 3394 } 3395 3396 // Simplify: (or (op x...), (op y...)) -> (op (or x, y)) 3397 if (N0.getOpcode() == N1.getOpcode()) { 3398 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N); 3399 if (Tmp.getNode()) return Tmp; 3400 } 3401 3402 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible. 3403 if (N0.getOpcode() == ISD::AND && 3404 N1.getOpcode() == ISD::AND && 3405 N0.getOperand(1).getOpcode() == ISD::Constant && 3406 N1.getOperand(1).getOpcode() == ISD::Constant && 3407 // Don't increase # computations. 3408 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) { 3409 // We can only do this xform if we know that bits from X that are set in C2 3410 // but not in C1 are already zero. Likewise for Y. 3411 const APInt &LHSMask = 3412 cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 3413 const APInt &RHSMask = 3414 cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue(); 3415 3416 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) && 3417 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) { 3418 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT, 3419 N0.getOperand(0), N1.getOperand(0)); 3420 return DAG.getNode(ISD::AND, SDLoc(N), VT, X, 3421 DAG.getConstant(LHSMask | RHSMask, VT)); 3422 } 3423 } 3424 3425 // See if this is some rotate idiom. 3426 if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N))) 3427 return SDValue(Rot, 0); 3428 3429 // Simplify the operands using demanded-bits information. 3430 if (!VT.isVector() && 3431 SimplifyDemandedBits(SDValue(N, 0))) 3432 return SDValue(N, 0); 3433 3434 return SDValue(); 3435 } 3436 3437 /// MatchRotateHalf - Match "(X shl/srl V1) & V2" where V2 may not be present. 3438 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) { 3439 if (Op.getOpcode() == ISD::AND) { 3440 if (isa<ConstantSDNode>(Op.getOperand(1))) { 3441 Mask = Op.getOperand(1); 3442 Op = Op.getOperand(0); 3443 } else { 3444 return false; 3445 } 3446 } 3447 3448 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) { 3449 Shift = Op; 3450 return true; 3451 } 3452 3453 return false; 3454 } 3455 3456 // Return true if we can prove that, whenever Neg and Pos are both in the 3457 // range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos). This means that 3458 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits: 3459 // 3460 // (or (shift1 X, Neg), (shift2 X, Pos)) 3461 // 3462 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate 3463 // in direction shift1 by Neg. The range [0, OpSize) means that we only need 3464 // to consider shift amounts with defined behavior. 3465 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) { 3466 // If OpSize is a power of 2 then: 3467 // 3468 // (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1) 3469 // (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize). 3470 // 3471 // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check 3472 // for the stronger condition: 3473 // 3474 // Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1) [A] 3475 // 3476 // for all Neg and Pos. Since Neg & (OpSize - 1) == Neg' & (OpSize - 1) 3477 // we can just replace Neg with Neg' for the rest of the function. 3478 // 3479 // In other cases we check for the even stronger condition: 3480 // 3481 // Neg == OpSize - Pos [B] 3482 // 3483 // for all Neg and Pos. Note that the (or ...) then invokes undefined 3484 // behavior if Pos == 0 (and consequently Neg == OpSize). 3485 // 3486 // We could actually use [A] whenever OpSize is a power of 2, but the 3487 // only extra cases that it would match are those uninteresting ones 3488 // where Neg and Pos are never in range at the same time. E.g. for 3489 // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos) 3490 // as well as (sub 32, Pos), but: 3491 // 3492 // (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos)) 3493 // 3494 // always invokes undefined behavior for 32-bit X. 3495 // 3496 // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise. 3497 unsigned MaskLoBits = 0; 3498 if (Neg.getOpcode() == ISD::AND && 3499 isPowerOf2_64(OpSize) && 3500 Neg.getOperand(1).getOpcode() == ISD::Constant && 3501 cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) { 3502 Neg = Neg.getOperand(0); 3503 MaskLoBits = Log2_64(OpSize); 3504 } 3505 3506 // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1. 3507 if (Neg.getOpcode() != ISD::SUB) 3508 return 0; 3509 ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0)); 3510 if (!NegC) 3511 return 0; 3512 SDValue NegOp1 = Neg.getOperand(1); 3513 3514 // On the RHS of [A], if Pos is Pos' & (OpSize - 1), just replace Pos with 3515 // Pos'. The truncation is redundant for the purpose of the equality. 3516 if (MaskLoBits && 3517 Pos.getOpcode() == ISD::AND && 3518 Pos.getOperand(1).getOpcode() == ISD::Constant && 3519 cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() == OpSize - 1) 3520 Pos = Pos.getOperand(0); 3521 3522 // The condition we need is now: 3523 // 3524 // (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask 3525 // 3526 // If NegOp1 == Pos then we need: 3527 // 3528 // OpSize & Mask == NegC & Mask 3529 // 3530 // (because "x & Mask" is a truncation and distributes through subtraction). 3531 APInt Width; 3532 if (Pos == NegOp1) 3533 Width = NegC->getAPIntValue(); 3534 // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC. 3535 // Then the condition we want to prove becomes: 3536 // 3537 // (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask 3538 // 3539 // which, again because "x & Mask" is a truncation, becomes: 3540 // 3541 // NegC & Mask == (OpSize - PosC) & Mask 3542 // OpSize & Mask == (NegC + PosC) & Mask 3543 else if (Pos.getOpcode() == ISD::ADD && 3544 Pos.getOperand(0) == NegOp1 && 3545 Pos.getOperand(1).getOpcode() == ISD::Constant) 3546 Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() + 3547 NegC->getAPIntValue()); 3548 else 3549 return false; 3550 3551 // Now we just need to check that OpSize & Mask == Width & Mask. 3552 if (MaskLoBits) 3553 // Opsize & Mask is 0 since Mask is Opsize - 1. 3554 return Width.getLoBits(MaskLoBits) == 0; 3555 return Width == OpSize; 3556 } 3557 3558 // A subroutine of MatchRotate used once we have found an OR of two opposite 3559 // shifts of Shifted. If Neg == <operand size> - Pos then the OR reduces 3560 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the 3561 // former being preferred if supported. InnerPos and InnerNeg are Pos and 3562 // Neg with outer conversions stripped away. 3563 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos, 3564 SDValue Neg, SDValue InnerPos, 3565 SDValue InnerNeg, unsigned PosOpcode, 3566 unsigned NegOpcode, SDLoc DL) { 3567 // fold (or (shl x, (*ext y)), 3568 // (srl x, (*ext (sub 32, y)))) -> 3569 // (rotl x, y) or (rotr x, (sub 32, y)) 3570 // 3571 // fold (or (shl x, (*ext (sub 32, y))), 3572 // (srl x, (*ext y))) -> 3573 // (rotr x, y) or (rotl x, (sub 32, y)) 3574 EVT VT = Shifted.getValueType(); 3575 if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) { 3576 bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT); 3577 return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted, 3578 HasPos ? Pos : Neg).getNode(); 3579 } 3580 3581 return nullptr; 3582 } 3583 3584 // MatchRotate - Handle an 'or' of two operands. If this is one of the many 3585 // idioms for rotate, and if the target supports rotation instructions, generate 3586 // a rot[lr]. 3587 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) { 3588 // Must be a legal type. Expanded 'n promoted things won't work with rotates. 3589 EVT VT = LHS.getValueType(); 3590 if (!TLI.isTypeLegal(VT)) return nullptr; 3591 3592 // The target must have at least one rotate flavor. 3593 bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT); 3594 bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT); 3595 if (!HasROTL && !HasROTR) return nullptr; 3596 3597 // Match "(X shl/srl V1) & V2" where V2 may not be present. 3598 SDValue LHSShift; // The shift. 3599 SDValue LHSMask; // AND value if any. 3600 if (!MatchRotateHalf(LHS, LHSShift, LHSMask)) 3601 return nullptr; // Not part of a rotate. 3602 3603 SDValue RHSShift; // The shift. 3604 SDValue RHSMask; // AND value if any. 3605 if (!MatchRotateHalf(RHS, RHSShift, RHSMask)) 3606 return nullptr; // Not part of a rotate. 3607 3608 if (LHSShift.getOperand(0) != RHSShift.getOperand(0)) 3609 return nullptr; // Not shifting the same value. 3610 3611 if (LHSShift.getOpcode() == RHSShift.getOpcode()) 3612 return nullptr; // Shifts must disagree. 3613 3614 // Canonicalize shl to left side in a shl/srl pair. 3615 if (RHSShift.getOpcode() == ISD::SHL) { 3616 std::swap(LHS, RHS); 3617 std::swap(LHSShift, RHSShift); 3618 std::swap(LHSMask , RHSMask ); 3619 } 3620 3621 unsigned OpSizeInBits = VT.getSizeInBits(); 3622 SDValue LHSShiftArg = LHSShift.getOperand(0); 3623 SDValue LHSShiftAmt = LHSShift.getOperand(1); 3624 SDValue RHSShiftArg = RHSShift.getOperand(0); 3625 SDValue RHSShiftAmt = RHSShift.getOperand(1); 3626 3627 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1) 3628 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2) 3629 if (LHSShiftAmt.getOpcode() == ISD::Constant && 3630 RHSShiftAmt.getOpcode() == ISD::Constant) { 3631 uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue(); 3632 uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue(); 3633 if ((LShVal + RShVal) != OpSizeInBits) 3634 return nullptr; 3635 3636 SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT, 3637 LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt); 3638 3639 // If there is an AND of either shifted operand, apply it to the result. 3640 if (LHSMask.getNode() || RHSMask.getNode()) { 3641 APInt Mask = APInt::getAllOnesValue(OpSizeInBits); 3642 3643 if (LHSMask.getNode()) { 3644 APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal); 3645 Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits; 3646 } 3647 if (RHSMask.getNode()) { 3648 APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal); 3649 Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits; 3650 } 3651 3652 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT)); 3653 } 3654 3655 return Rot.getNode(); 3656 } 3657 3658 // If there is a mask here, and we have a variable shift, we can't be sure 3659 // that we're masking out the right stuff. 3660 if (LHSMask.getNode() || RHSMask.getNode()) 3661 return nullptr; 3662 3663 // If the shift amount is sign/zext/any-extended just peel it off. 3664 SDValue LExtOp0 = LHSShiftAmt; 3665 SDValue RExtOp0 = RHSShiftAmt; 3666 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND || 3667 LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND || 3668 LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND || 3669 LHSShiftAmt.getOpcode() == ISD::TRUNCATE) && 3670 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND || 3671 RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND || 3672 RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND || 3673 RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) { 3674 LExtOp0 = LHSShiftAmt.getOperand(0); 3675 RExtOp0 = RHSShiftAmt.getOperand(0); 3676 } 3677 3678 SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt, 3679 LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL); 3680 if (TryL) 3681 return TryL; 3682 3683 SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt, 3684 RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL); 3685 if (TryR) 3686 return TryR; 3687 3688 return nullptr; 3689 } 3690 3691 SDValue DAGCombiner::visitXOR(SDNode *N) { 3692 SDValue N0 = N->getOperand(0); 3693 SDValue N1 = N->getOperand(1); 3694 SDValue LHS, RHS, CC; 3695 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 3696 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 3697 EVT VT = N0.getValueType(); 3698 3699 // fold vector ops 3700 if (VT.isVector()) { 3701 SDValue FoldedVOp = SimplifyVBinOp(N); 3702 if (FoldedVOp.getNode()) return FoldedVOp; 3703 3704 // fold (xor x, 0) -> x, vector edition 3705 if (ISD::isBuildVectorAllZeros(N0.getNode())) 3706 return N1; 3707 if (ISD::isBuildVectorAllZeros(N1.getNode())) 3708 return N0; 3709 } 3710 3711 // fold (xor undef, undef) -> 0. This is a common idiom (misuse). 3712 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF) 3713 return DAG.getConstant(0, VT); 3714 // fold (xor x, undef) -> undef 3715 if (N0.getOpcode() == ISD::UNDEF) 3716 return N0; 3717 if (N1.getOpcode() == ISD::UNDEF) 3718 return N1; 3719 // fold (xor c1, c2) -> c1^c2 3720 if (N0C && N1C) 3721 return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C); 3722 // canonicalize constant to RHS 3723 if (N0C && !N1C) 3724 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0); 3725 // fold (xor x, 0) -> x 3726 if (N1C && N1C->isNullValue()) 3727 return N0; 3728 // reassociate xor 3729 SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1); 3730 if (RXOR.getNode()) 3731 return RXOR; 3732 3733 // fold !(x cc y) -> (x !cc y) 3734 if (N1C && N1C->getAPIntValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) { 3735 bool isInt = LHS.getValueType().isInteger(); 3736 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(), 3737 isInt); 3738 3739 if (!LegalOperations || 3740 TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) { 3741 switch (N0.getOpcode()) { 3742 default: 3743 llvm_unreachable("Unhandled SetCC Equivalent!"); 3744 case ISD::SETCC: 3745 return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC); 3746 case ISD::SELECT_CC: 3747 return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2), 3748 N0.getOperand(3), NotCC); 3749 } 3750 } 3751 } 3752 3753 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y))) 3754 if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND && 3755 N0.getNode()->hasOneUse() && 3756 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){ 3757 SDValue V = N0.getOperand(0); 3758 V = DAG.getNode(ISD::XOR, SDLoc(N0), V.getValueType(), V, 3759 DAG.getConstant(1, V.getValueType())); 3760 AddToWorkList(V.getNode()); 3761 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V); 3762 } 3763 3764 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc 3765 if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 && 3766 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) { 3767 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1); 3768 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) { 3769 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND; 3770 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS 3771 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS 3772 AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode()); 3773 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS); 3774 } 3775 } 3776 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants 3777 if (N1C && N1C->isAllOnesValue() && 3778 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) { 3779 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1); 3780 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) { 3781 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND; 3782 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS 3783 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS 3784 AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode()); 3785 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS); 3786 } 3787 } 3788 // fold (xor (and x, y), y) -> (and (not x), y) 3789 if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() && 3790 N0->getOperand(1) == N1) { 3791 SDValue X = N0->getOperand(0); 3792 SDValue NotX = DAG.getNOT(SDLoc(X), X, VT); 3793 AddToWorkList(NotX.getNode()); 3794 return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1); 3795 } 3796 // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2)) 3797 if (N1C && N0.getOpcode() == ISD::XOR) { 3798 ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0)); 3799 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 3800 if (N00C) 3801 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(1), 3802 DAG.getConstant(N1C->getAPIntValue() ^ 3803 N00C->getAPIntValue(), VT)); 3804 if (N01C) 3805 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(0), 3806 DAG.getConstant(N1C->getAPIntValue() ^ 3807 N01C->getAPIntValue(), VT)); 3808 } 3809 // fold (xor x, x) -> 0 3810 if (N0 == N1) 3811 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes); 3812 3813 // Simplify: xor (op x...), (op y...) -> (op (xor x, y)) 3814 if (N0.getOpcode() == N1.getOpcode()) { 3815 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N); 3816 if (Tmp.getNode()) return Tmp; 3817 } 3818 3819 // Simplify the expression using non-local knowledge. 3820 if (!VT.isVector() && 3821 SimplifyDemandedBits(SDValue(N, 0))) 3822 return SDValue(N, 0); 3823 3824 return SDValue(); 3825 } 3826 3827 /// visitShiftByConstant - Handle transforms common to the three shifts, when 3828 /// the shift amount is a constant. 3829 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) { 3830 // We can't and shouldn't fold opaque constants. 3831 if (Amt->isOpaque()) 3832 return SDValue(); 3833 3834 SDNode *LHS = N->getOperand(0).getNode(); 3835 if (!LHS->hasOneUse()) return SDValue(); 3836 3837 // We want to pull some binops through shifts, so that we have (and (shift)) 3838 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of 3839 // thing happens with address calculations, so it's important to canonicalize 3840 // it. 3841 bool HighBitSet = false; // Can we transform this if the high bit is set? 3842 3843 switch (LHS->getOpcode()) { 3844 default: return SDValue(); 3845 case ISD::OR: 3846 case ISD::XOR: 3847 HighBitSet = false; // We can only transform sra if the high bit is clear. 3848 break; 3849 case ISD::AND: 3850 HighBitSet = true; // We can only transform sra if the high bit is set. 3851 break; 3852 case ISD::ADD: 3853 if (N->getOpcode() != ISD::SHL) 3854 return SDValue(); // only shl(add) not sr[al](add). 3855 HighBitSet = false; // We can only transform sra if the high bit is clear. 3856 break; 3857 } 3858 3859 // We require the RHS of the binop to be a constant and not opaque as well. 3860 ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1)); 3861 if (!BinOpCst || BinOpCst->isOpaque()) return SDValue(); 3862 3863 // FIXME: disable this unless the input to the binop is a shift by a constant. 3864 // If it is not a shift, it pessimizes some common cases like: 3865 // 3866 // void foo(int *X, int i) { X[i & 1235] = 1; } 3867 // int bar(int *X, int i) { return X[i & 255]; } 3868 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode(); 3869 if ((BinOpLHSVal->getOpcode() != ISD::SHL && 3870 BinOpLHSVal->getOpcode() != ISD::SRA && 3871 BinOpLHSVal->getOpcode() != ISD::SRL) || 3872 !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1))) 3873 return SDValue(); 3874 3875 EVT VT = N->getValueType(0); 3876 3877 // If this is a signed shift right, and the high bit is modified by the 3878 // logical operation, do not perform the transformation. The highBitSet 3879 // boolean indicates the value of the high bit of the constant which would 3880 // cause it to be modified for this operation. 3881 if (N->getOpcode() == ISD::SRA) { 3882 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative(); 3883 if (BinOpRHSSignSet != HighBitSet) 3884 return SDValue(); 3885 } 3886 3887 if (!TLI.isDesirableToCommuteWithShift(LHS)) 3888 return SDValue(); 3889 3890 // Fold the constants, shifting the binop RHS by the shift amount. 3891 SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)), 3892 N->getValueType(0), 3893 LHS->getOperand(1), N->getOperand(1)); 3894 assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!"); 3895 3896 // Create the new shift. 3897 SDValue NewShift = DAG.getNode(N->getOpcode(), 3898 SDLoc(LHS->getOperand(0)), 3899 VT, LHS->getOperand(0), N->getOperand(1)); 3900 3901 // Create the new binop. 3902 return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS); 3903 } 3904 3905 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) { 3906 assert(N->getOpcode() == ISD::TRUNCATE); 3907 assert(N->getOperand(0).getOpcode() == ISD::AND); 3908 3909 // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC) 3910 if (N->hasOneUse() && N->getOperand(0).hasOneUse()) { 3911 SDValue N01 = N->getOperand(0).getOperand(1); 3912 3913 if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) { 3914 EVT TruncVT = N->getValueType(0); 3915 SDValue N00 = N->getOperand(0).getOperand(0); 3916 APInt TruncC = N01C->getAPIntValue(); 3917 TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits()); 3918 3919 return DAG.getNode(ISD::AND, SDLoc(N), TruncVT, 3920 DAG.getNode(ISD::TRUNCATE, SDLoc(N), TruncVT, N00), 3921 DAG.getConstant(TruncC, TruncVT)); 3922 } 3923 } 3924 3925 return SDValue(); 3926 } 3927 3928 SDValue DAGCombiner::visitRotate(SDNode *N) { 3929 // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))). 3930 if (N->getOperand(1).getOpcode() == ISD::TRUNCATE && 3931 N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) { 3932 SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode()); 3933 if (NewOp1.getNode()) 3934 return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0), 3935 N->getOperand(0), NewOp1); 3936 } 3937 return SDValue(); 3938 } 3939 3940 SDValue DAGCombiner::visitSHL(SDNode *N) { 3941 SDValue N0 = N->getOperand(0); 3942 SDValue N1 = N->getOperand(1); 3943 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 3944 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 3945 EVT VT = N0.getValueType(); 3946 unsigned OpSizeInBits = VT.getScalarSizeInBits(); 3947 3948 // fold vector ops 3949 if (VT.isVector()) { 3950 SDValue FoldedVOp = SimplifyVBinOp(N); 3951 if (FoldedVOp.getNode()) return FoldedVOp; 3952 3953 BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1); 3954 // If setcc produces all-one true value then: 3955 // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV) 3956 if (N1CV && N1CV->isConstant()) { 3957 if (N0.getOpcode() == ISD::AND && 3958 TLI.getBooleanContents(true) == 3959 TargetLowering::ZeroOrNegativeOneBooleanContent) { 3960 SDValue N00 = N0->getOperand(0); 3961 SDValue N01 = N0->getOperand(1); 3962 BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01); 3963 3964 if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC) { 3965 SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, VT, N01CV, N1CV); 3966 if (C.getNode()) 3967 return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C); 3968 } 3969 } else { 3970 N1C = isConstOrConstSplat(N1); 3971 } 3972 } 3973 } 3974 3975 // fold (shl c1, c2) -> c1<<c2 3976 if (N0C && N1C) 3977 return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C); 3978 // fold (shl 0, x) -> 0 3979 if (N0C && N0C->isNullValue()) 3980 return N0; 3981 // fold (shl x, c >= size(x)) -> undef 3982 if (N1C && N1C->getZExtValue() >= OpSizeInBits) 3983 return DAG.getUNDEF(VT); 3984 // fold (shl x, 0) -> x 3985 if (N1C && N1C->isNullValue()) 3986 return N0; 3987 // fold (shl undef, x) -> 0 3988 if (N0.getOpcode() == ISD::UNDEF) 3989 return DAG.getConstant(0, VT); 3990 // if (shl x, c) is known to be zero, return 0 3991 if (DAG.MaskedValueIsZero(SDValue(N, 0), 3992 APInt::getAllOnesValue(OpSizeInBits))) 3993 return DAG.getConstant(0, VT); 3994 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))). 3995 if (N1.getOpcode() == ISD::TRUNCATE && 3996 N1.getOperand(0).getOpcode() == ISD::AND) { 3997 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()); 3998 if (NewOp1.getNode()) 3999 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1); 4000 } 4001 4002 if (N1C && SimplifyDemandedBits(SDValue(N, 0))) 4003 return SDValue(N, 0); 4004 4005 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2)) 4006 if (N1C && N0.getOpcode() == ISD::SHL) { 4007 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) { 4008 uint64_t c1 = N0C1->getZExtValue(); 4009 uint64_t c2 = N1C->getZExtValue(); 4010 if (c1 + c2 >= OpSizeInBits) 4011 return DAG.getConstant(0, VT); 4012 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0), 4013 DAG.getConstant(c1 + c2, N1.getValueType())); 4014 } 4015 } 4016 4017 // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2))) 4018 // For this to be valid, the second form must not preserve any of the bits 4019 // that are shifted out by the inner shift in the first form. This means 4020 // the outer shift size must be >= the number of bits added by the ext. 4021 // As a corollary, we don't care what kind of ext it is. 4022 if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND || 4023 N0.getOpcode() == ISD::ANY_EXTEND || 4024 N0.getOpcode() == ISD::SIGN_EXTEND) && 4025 N0.getOperand(0).getOpcode() == ISD::SHL) { 4026 SDValue N0Op0 = N0.getOperand(0); 4027 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) { 4028 uint64_t c1 = N0Op0C1->getZExtValue(); 4029 uint64_t c2 = N1C->getZExtValue(); 4030 EVT InnerShiftVT = N0Op0.getValueType(); 4031 uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits(); 4032 if (c2 >= OpSizeInBits - InnerShiftSize) { 4033 if (c1 + c2 >= OpSizeInBits) 4034 return DAG.getConstant(0, VT); 4035 return DAG.getNode(ISD::SHL, SDLoc(N0), VT, 4036 DAG.getNode(N0.getOpcode(), SDLoc(N0), VT, 4037 N0Op0->getOperand(0)), 4038 DAG.getConstant(c1 + c2, N1.getValueType())); 4039 } 4040 } 4041 } 4042 4043 // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C)) 4044 // Only fold this if the inner zext has no other uses to avoid increasing 4045 // the total number of instructions. 4046 if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() && 4047 N0.getOperand(0).getOpcode() == ISD::SRL) { 4048 SDValue N0Op0 = N0.getOperand(0); 4049 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) { 4050 uint64_t c1 = N0Op0C1->getZExtValue(); 4051 if (c1 < VT.getScalarSizeInBits()) { 4052 uint64_t c2 = N1C->getZExtValue(); 4053 if (c1 == c2) { 4054 SDValue NewOp0 = N0.getOperand(0); 4055 EVT CountVT = NewOp0.getOperand(1).getValueType(); 4056 SDValue NewSHL = DAG.getNode(ISD::SHL, SDLoc(N), NewOp0.getValueType(), 4057 NewOp0, DAG.getConstant(c2, CountVT)); 4058 AddToWorkList(NewSHL.getNode()); 4059 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL); 4060 } 4061 } 4062 } 4063 } 4064 4065 // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or 4066 // (and (srl x, (sub c1, c2), MASK) 4067 // Only fold this if the inner shift has no other uses -- if it does, folding 4068 // this will increase the total number of instructions. 4069 if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) { 4070 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) { 4071 uint64_t c1 = N0C1->getZExtValue(); 4072 if (c1 < OpSizeInBits) { 4073 uint64_t c2 = N1C->getZExtValue(); 4074 APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1); 4075 SDValue Shift; 4076 if (c2 > c1) { 4077 Mask = Mask.shl(c2 - c1); 4078 Shift = DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0), 4079 DAG.getConstant(c2 - c1, N1.getValueType())); 4080 } else { 4081 Mask = Mask.lshr(c1 - c2); 4082 Shift = DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), 4083 DAG.getConstant(c1 - c2, N1.getValueType())); 4084 } 4085 return DAG.getNode(ISD::AND, SDLoc(N0), VT, Shift, 4086 DAG.getConstant(Mask, VT)); 4087 } 4088 } 4089 } 4090 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1)) 4091 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) { 4092 unsigned BitSize = VT.getScalarSizeInBits(); 4093 SDValue HiBitsMask = 4094 DAG.getConstant(APInt::getHighBitsSet(BitSize, 4095 BitSize - N1C->getZExtValue()), VT); 4096 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0), 4097 HiBitsMask); 4098 } 4099 4100 if (N1C) { 4101 SDValue NewSHL = visitShiftByConstant(N, N1C); 4102 if (NewSHL.getNode()) 4103 return NewSHL; 4104 } 4105 4106 return SDValue(); 4107 } 4108 4109 SDValue DAGCombiner::visitSRA(SDNode *N) { 4110 SDValue N0 = N->getOperand(0); 4111 SDValue N1 = N->getOperand(1); 4112 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 4113 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 4114 EVT VT = N0.getValueType(); 4115 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits(); 4116 4117 // fold vector ops 4118 if (VT.isVector()) { 4119 SDValue FoldedVOp = SimplifyVBinOp(N); 4120 if (FoldedVOp.getNode()) return FoldedVOp; 4121 4122 N1C = isConstOrConstSplat(N1); 4123 } 4124 4125 // fold (sra c1, c2) -> (sra c1, c2) 4126 if (N0C && N1C) 4127 return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C); 4128 // fold (sra 0, x) -> 0 4129 if (N0C && N0C->isNullValue()) 4130 return N0; 4131 // fold (sra -1, x) -> -1 4132 if (N0C && N0C->isAllOnesValue()) 4133 return N0; 4134 // fold (sra x, (setge c, size(x))) -> undef 4135 if (N1C && N1C->getZExtValue() >= OpSizeInBits) 4136 return DAG.getUNDEF(VT); 4137 // fold (sra x, 0) -> x 4138 if (N1C && N1C->isNullValue()) 4139 return N0; 4140 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports 4141 // sext_inreg. 4142 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) { 4143 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue(); 4144 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits); 4145 if (VT.isVector()) 4146 ExtVT = EVT::getVectorVT(*DAG.getContext(), 4147 ExtVT, VT.getVectorNumElements()); 4148 if ((!LegalOperations || 4149 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT))) 4150 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, 4151 N0.getOperand(0), DAG.getValueType(ExtVT)); 4152 } 4153 4154 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2)) 4155 if (N1C && N0.getOpcode() == ISD::SRA) { 4156 if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) { 4157 unsigned Sum = N1C->getZExtValue() + C1->getZExtValue(); 4158 if (Sum >= OpSizeInBits) 4159 Sum = OpSizeInBits - 1; 4160 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0.getOperand(0), 4161 DAG.getConstant(Sum, N1.getValueType())); 4162 } 4163 } 4164 4165 // fold (sra (shl X, m), (sub result_size, n)) 4166 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for 4167 // result_size - n != m. 4168 // If truncate is free for the target sext(shl) is likely to result in better 4169 // code. 4170 if (N0.getOpcode() == ISD::SHL && N1C) { 4171 // Get the two constanst of the shifts, CN0 = m, CN = n. 4172 const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1)); 4173 if (N01C) { 4174 LLVMContext &Ctx = *DAG.getContext(); 4175 // Determine what the truncate's result bitsize and type would be. 4176 EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue()); 4177 4178 if (VT.isVector()) 4179 TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements()); 4180 4181 // Determine the residual right-shift amount. 4182 signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue(); 4183 4184 // If the shift is not a no-op (in which case this should be just a sign 4185 // extend already), the truncated to type is legal, sign_extend is legal 4186 // on that type, and the truncate to that type is both legal and free, 4187 // perform the transform. 4188 if ((ShiftAmt > 0) && 4189 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) && 4190 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) && 4191 TLI.isTruncateFree(VT, TruncVT)) { 4192 4193 SDValue Amt = DAG.getConstant(ShiftAmt, 4194 getShiftAmountTy(N0.getOperand(0).getValueType())); 4195 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), VT, 4196 N0.getOperand(0), Amt); 4197 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), TruncVT, 4198 Shift); 4199 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), 4200 N->getValueType(0), Trunc); 4201 } 4202 } 4203 } 4204 4205 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))). 4206 if (N1.getOpcode() == ISD::TRUNCATE && 4207 N1.getOperand(0).getOpcode() == ISD::AND) { 4208 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()); 4209 if (NewOp1.getNode()) 4210 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1); 4211 } 4212 4213 // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2)) 4214 // if c1 is equal to the number of bits the trunc removes 4215 if (N0.getOpcode() == ISD::TRUNCATE && 4216 (N0.getOperand(0).getOpcode() == ISD::SRL || 4217 N0.getOperand(0).getOpcode() == ISD::SRA) && 4218 N0.getOperand(0).hasOneUse() && 4219 N0.getOperand(0).getOperand(1).hasOneUse() && 4220 N1C) { 4221 SDValue N0Op0 = N0.getOperand(0); 4222 if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) { 4223 unsigned LargeShiftVal = LargeShift->getZExtValue(); 4224 EVT LargeVT = N0Op0.getValueType(); 4225 4226 if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) { 4227 SDValue Amt = 4228 DAG.getConstant(LargeShiftVal + N1C->getZExtValue(), 4229 getShiftAmountTy(N0Op0.getOperand(0).getValueType())); 4230 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), LargeVT, 4231 N0Op0.getOperand(0), Amt); 4232 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, SRA); 4233 } 4234 } 4235 } 4236 4237 // Simplify, based on bits shifted out of the LHS. 4238 if (N1C && SimplifyDemandedBits(SDValue(N, 0))) 4239 return SDValue(N, 0); 4240 4241 4242 // If the sign bit is known to be zero, switch this to a SRL. 4243 if (DAG.SignBitIsZero(N0)) 4244 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1); 4245 4246 if (N1C) { 4247 SDValue NewSRA = visitShiftByConstant(N, N1C); 4248 if (NewSRA.getNode()) 4249 return NewSRA; 4250 } 4251 4252 return SDValue(); 4253 } 4254 4255 SDValue DAGCombiner::visitSRL(SDNode *N) { 4256 SDValue N0 = N->getOperand(0); 4257 SDValue N1 = N->getOperand(1); 4258 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 4259 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 4260 EVT VT = N0.getValueType(); 4261 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits(); 4262 4263 // fold vector ops 4264 if (VT.isVector()) { 4265 SDValue FoldedVOp = SimplifyVBinOp(N); 4266 if (FoldedVOp.getNode()) return FoldedVOp; 4267 4268 N1C = isConstOrConstSplat(N1); 4269 } 4270 4271 // fold (srl c1, c2) -> c1 >>u c2 4272 if (N0C && N1C) 4273 return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C); 4274 // fold (srl 0, x) -> 0 4275 if (N0C && N0C->isNullValue()) 4276 return N0; 4277 // fold (srl x, c >= size(x)) -> undef 4278 if (N1C && N1C->getZExtValue() >= OpSizeInBits) 4279 return DAG.getUNDEF(VT); 4280 // fold (srl x, 0) -> x 4281 if (N1C && N1C->isNullValue()) 4282 return N0; 4283 // if (srl x, c) is known to be zero, return 0 4284 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0), 4285 APInt::getAllOnesValue(OpSizeInBits))) 4286 return DAG.getConstant(0, VT); 4287 4288 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2)) 4289 if (N1C && N0.getOpcode() == ISD::SRL) { 4290 if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) { 4291 uint64_t c1 = N01C->getZExtValue(); 4292 uint64_t c2 = N1C->getZExtValue(); 4293 if (c1 + c2 >= OpSizeInBits) 4294 return DAG.getConstant(0, VT); 4295 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), 4296 DAG.getConstant(c1 + c2, N1.getValueType())); 4297 } 4298 } 4299 4300 // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2))) 4301 if (N1C && N0.getOpcode() == ISD::TRUNCATE && 4302 N0.getOperand(0).getOpcode() == ISD::SRL && 4303 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) { 4304 uint64_t c1 = 4305 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue(); 4306 uint64_t c2 = N1C->getZExtValue(); 4307 EVT InnerShiftVT = N0.getOperand(0).getValueType(); 4308 EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType(); 4309 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits(); 4310 // This is only valid if the OpSizeInBits + c1 = size of inner shift. 4311 if (c1 + OpSizeInBits == InnerShiftSize) { 4312 if (c1 + c2 >= InnerShiftSize) 4313 return DAG.getConstant(0, VT); 4314 return DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, 4315 DAG.getNode(ISD::SRL, SDLoc(N0), InnerShiftVT, 4316 N0.getOperand(0)->getOperand(0), 4317 DAG.getConstant(c1 + c2, ShiftCountVT))); 4318 } 4319 } 4320 4321 // fold (srl (shl x, c), c) -> (and x, cst2) 4322 if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) { 4323 unsigned BitSize = N0.getScalarValueSizeInBits(); 4324 if (BitSize <= 64) { 4325 uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize; 4326 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0), 4327 DAG.getConstant(~0ULL >> ShAmt, VT)); 4328 } 4329 } 4330 4331 // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask) 4332 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) { 4333 // Shifting in all undef bits? 4334 EVT SmallVT = N0.getOperand(0).getValueType(); 4335 unsigned BitSize = SmallVT.getScalarSizeInBits(); 4336 if (N1C->getZExtValue() >= BitSize) 4337 return DAG.getUNDEF(VT); 4338 4339 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) { 4340 uint64_t ShiftAmt = N1C->getZExtValue(); 4341 SDValue SmallShift = DAG.getNode(ISD::SRL, SDLoc(N0), SmallVT, 4342 N0.getOperand(0), 4343 DAG.getConstant(ShiftAmt, getShiftAmountTy(SmallVT))); 4344 AddToWorkList(SmallShift.getNode()); 4345 APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt); 4346 return DAG.getNode(ISD::AND, SDLoc(N), VT, 4347 DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, SmallShift), 4348 DAG.getConstant(Mask, VT)); 4349 } 4350 } 4351 4352 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign 4353 // bit, which is unmodified by sra. 4354 if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) { 4355 if (N0.getOpcode() == ISD::SRA) 4356 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1); 4357 } 4358 4359 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit). 4360 if (N1C && N0.getOpcode() == ISD::CTLZ && 4361 N1C->getAPIntValue() == Log2_32(OpSizeInBits)) { 4362 APInt KnownZero, KnownOne; 4363 DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne); 4364 4365 // If any of the input bits are KnownOne, then the input couldn't be all 4366 // zeros, thus the result of the srl will always be zero. 4367 if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT); 4368 4369 // If all of the bits input the to ctlz node are known to be zero, then 4370 // the result of the ctlz is "32" and the result of the shift is one. 4371 APInt UnknownBits = ~KnownZero; 4372 if (UnknownBits == 0) return DAG.getConstant(1, VT); 4373 4374 // Otherwise, check to see if there is exactly one bit input to the ctlz. 4375 if ((UnknownBits & (UnknownBits - 1)) == 0) { 4376 // Okay, we know that only that the single bit specified by UnknownBits 4377 // could be set on input to the CTLZ node. If this bit is set, the SRL 4378 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair 4379 // to an SRL/XOR pair, which is likely to simplify more. 4380 unsigned ShAmt = UnknownBits.countTrailingZeros(); 4381 SDValue Op = N0.getOperand(0); 4382 4383 if (ShAmt) { 4384 Op = DAG.getNode(ISD::SRL, SDLoc(N0), VT, Op, 4385 DAG.getConstant(ShAmt, getShiftAmountTy(Op.getValueType()))); 4386 AddToWorkList(Op.getNode()); 4387 } 4388 4389 return DAG.getNode(ISD::XOR, SDLoc(N), VT, 4390 Op, DAG.getConstant(1, VT)); 4391 } 4392 } 4393 4394 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))). 4395 if (N1.getOpcode() == ISD::TRUNCATE && 4396 N1.getOperand(0).getOpcode() == ISD::AND) { 4397 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()); 4398 if (NewOp1.getNode()) 4399 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1); 4400 } 4401 4402 // fold operands of srl based on knowledge that the low bits are not 4403 // demanded. 4404 if (N1C && SimplifyDemandedBits(SDValue(N, 0))) 4405 return SDValue(N, 0); 4406 4407 if (N1C) { 4408 SDValue NewSRL = visitShiftByConstant(N, N1C); 4409 if (NewSRL.getNode()) 4410 return NewSRL; 4411 } 4412 4413 // Attempt to convert a srl of a load into a narrower zero-extending load. 4414 SDValue NarrowLoad = ReduceLoadWidth(N); 4415 if (NarrowLoad.getNode()) 4416 return NarrowLoad; 4417 4418 // Here is a common situation. We want to optimize: 4419 // 4420 // %a = ... 4421 // %b = and i32 %a, 2 4422 // %c = srl i32 %b, 1 4423 // brcond i32 %c ... 4424 // 4425 // into 4426 // 4427 // %a = ... 4428 // %b = and %a, 2 4429 // %c = setcc eq %b, 0 4430 // brcond %c ... 4431 // 4432 // However when after the source operand of SRL is optimized into AND, the SRL 4433 // itself may not be optimized further. Look for it and add the BRCOND into 4434 // the worklist. 4435 if (N->hasOneUse()) { 4436 SDNode *Use = *N->use_begin(); 4437 if (Use->getOpcode() == ISD::BRCOND) 4438 AddToWorkList(Use); 4439 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) { 4440 // Also look pass the truncate. 4441 Use = *Use->use_begin(); 4442 if (Use->getOpcode() == ISD::BRCOND) 4443 AddToWorkList(Use); 4444 } 4445 } 4446 4447 return SDValue(); 4448 } 4449 4450 SDValue DAGCombiner::visitCTLZ(SDNode *N) { 4451 SDValue N0 = N->getOperand(0); 4452 EVT VT = N->getValueType(0); 4453 4454 // fold (ctlz c1) -> c2 4455 if (isa<ConstantSDNode>(N0)) 4456 return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0); 4457 return SDValue(); 4458 } 4459 4460 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) { 4461 SDValue N0 = N->getOperand(0); 4462 EVT VT = N->getValueType(0); 4463 4464 // fold (ctlz_zero_undef c1) -> c2 4465 if (isa<ConstantSDNode>(N0)) 4466 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0); 4467 return SDValue(); 4468 } 4469 4470 SDValue DAGCombiner::visitCTTZ(SDNode *N) { 4471 SDValue N0 = N->getOperand(0); 4472 EVT VT = N->getValueType(0); 4473 4474 // fold (cttz c1) -> c2 4475 if (isa<ConstantSDNode>(N0)) 4476 return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0); 4477 return SDValue(); 4478 } 4479 4480 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) { 4481 SDValue N0 = N->getOperand(0); 4482 EVT VT = N->getValueType(0); 4483 4484 // fold (cttz_zero_undef c1) -> c2 4485 if (isa<ConstantSDNode>(N0)) 4486 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0); 4487 return SDValue(); 4488 } 4489 4490 SDValue DAGCombiner::visitCTPOP(SDNode *N) { 4491 SDValue N0 = N->getOperand(0); 4492 EVT VT = N->getValueType(0); 4493 4494 // fold (ctpop c1) -> c2 4495 if (isa<ConstantSDNode>(N0)) 4496 return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0); 4497 return SDValue(); 4498 } 4499 4500 SDValue DAGCombiner::visitSELECT(SDNode *N) { 4501 SDValue N0 = N->getOperand(0); 4502 SDValue N1 = N->getOperand(1); 4503 SDValue N2 = N->getOperand(2); 4504 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 4505 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 4506 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2); 4507 EVT VT = N->getValueType(0); 4508 EVT VT0 = N0.getValueType(); 4509 4510 // fold (select C, X, X) -> X 4511 if (N1 == N2) 4512 return N1; 4513 // fold (select true, X, Y) -> X 4514 if (N0C && !N0C->isNullValue()) 4515 return N1; 4516 // fold (select false, X, Y) -> Y 4517 if (N0C && N0C->isNullValue()) 4518 return N2; 4519 // fold (select C, 1, X) -> (or C, X) 4520 if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1) 4521 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2); 4522 // fold (select C, 0, 1) -> (xor C, 1) 4523 if (VT.isInteger() && 4524 (VT0 == MVT::i1 || 4525 (VT0.isInteger() && 4526 TLI.getBooleanContents(false) == 4527 TargetLowering::ZeroOrOneBooleanContent)) && 4528 N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) { 4529 SDValue XORNode; 4530 if (VT == VT0) 4531 return DAG.getNode(ISD::XOR, SDLoc(N), VT0, 4532 N0, DAG.getConstant(1, VT0)); 4533 XORNode = DAG.getNode(ISD::XOR, SDLoc(N0), VT0, 4534 N0, DAG.getConstant(1, VT0)); 4535 AddToWorkList(XORNode.getNode()); 4536 if (VT.bitsGT(VT0)) 4537 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode); 4538 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode); 4539 } 4540 // fold (select C, 0, X) -> (and (not C), X) 4541 if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) { 4542 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT); 4543 AddToWorkList(NOTNode.getNode()); 4544 return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2); 4545 } 4546 // fold (select C, X, 1) -> (or (not C), X) 4547 if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) { 4548 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT); 4549 AddToWorkList(NOTNode.getNode()); 4550 return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1); 4551 } 4552 // fold (select C, X, 0) -> (and C, X) 4553 if (VT == MVT::i1 && N2C && N2C->isNullValue()) 4554 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1); 4555 // fold (select X, X, Y) -> (or X, Y) 4556 // fold (select X, 1, Y) -> (or X, Y) 4557 if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1))) 4558 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2); 4559 // fold (select X, Y, X) -> (and X, Y) 4560 // fold (select X, Y, 0) -> (and X, Y) 4561 if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0))) 4562 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1); 4563 4564 // If we can fold this based on the true/false value, do so. 4565 if (SimplifySelectOps(N, N1, N2)) 4566 return SDValue(N, 0); // Don't revisit N. 4567 4568 // fold selects based on a setcc into other things, such as min/max/abs 4569 if (N0.getOpcode() == ISD::SETCC) { 4570 if ((!LegalOperations && 4571 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) || 4572 TLI.isOperationLegal(ISD::SELECT_CC, VT)) 4573 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, 4574 N0.getOperand(0), N0.getOperand(1), 4575 N1, N2, N0.getOperand(2)); 4576 return SimplifySelect(SDLoc(N), N0, N1, N2); 4577 } 4578 4579 return SDValue(); 4580 } 4581 4582 static 4583 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) { 4584 SDLoc DL(N); 4585 EVT LoVT, HiVT; 4586 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0)); 4587 4588 // Split the inputs. 4589 SDValue Lo, Hi, LL, LH, RL, RH; 4590 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0); 4591 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1); 4592 4593 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2)); 4594 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2)); 4595 4596 return std::make_pair(Lo, Hi); 4597 } 4598 4599 // This function assumes all the vselect's arguments are CONCAT_VECTOR 4600 // nodes and that the condition is a BV of ConstantSDNodes (or undefs). 4601 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) { 4602 SDLoc dl(N); 4603 SDValue Cond = N->getOperand(0); 4604 SDValue LHS = N->getOperand(1); 4605 SDValue RHS = N->getOperand(2); 4606 MVT VT = N->getSimpleValueType(0); 4607 int NumElems = VT.getVectorNumElements(); 4608 assert(LHS.getOpcode() == ISD::CONCAT_VECTORS && 4609 RHS.getOpcode() == ISD::CONCAT_VECTORS && 4610 Cond.getOpcode() == ISD::BUILD_VECTOR); 4611 4612 // We're sure we have an even number of elements due to the 4613 // concat_vectors we have as arguments to vselect. 4614 // Skip BV elements until we find one that's not an UNDEF 4615 // After we find an UNDEF element, keep looping until we get to half the 4616 // length of the BV and see if all the non-undef nodes are the same. 4617 ConstantSDNode *BottomHalf = nullptr; 4618 for (int i = 0; i < NumElems / 2; ++i) { 4619 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF) 4620 continue; 4621 4622 if (BottomHalf == nullptr) 4623 BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i)); 4624 else if (Cond->getOperand(i).getNode() != BottomHalf) 4625 return SDValue(); 4626 } 4627 4628 // Do the same for the second half of the BuildVector 4629 ConstantSDNode *TopHalf = nullptr; 4630 for (int i = NumElems / 2; i < NumElems; ++i) { 4631 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF) 4632 continue; 4633 4634 if (TopHalf == nullptr) 4635 TopHalf = cast<ConstantSDNode>(Cond.getOperand(i)); 4636 else if (Cond->getOperand(i).getNode() != TopHalf) 4637 return SDValue(); 4638 } 4639 4640 assert(TopHalf && BottomHalf && 4641 "One half of the selector was all UNDEFs and the other was all the " 4642 "same value. This should have been addressed before this function."); 4643 return DAG.getNode( 4644 ISD::CONCAT_VECTORS, dl, VT, 4645 BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0), 4646 TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1)); 4647 } 4648 4649 SDValue DAGCombiner::visitVSELECT(SDNode *N) { 4650 SDValue N0 = N->getOperand(0); 4651 SDValue N1 = N->getOperand(1); 4652 SDValue N2 = N->getOperand(2); 4653 SDLoc DL(N); 4654 4655 // Canonicalize integer abs. 4656 // vselect (setg[te] X, 0), X, -X -> 4657 // vselect (setgt X, -1), X, -X -> 4658 // vselect (setl[te] X, 0), -X, X -> 4659 // Y = sra (X, size(X)-1); xor (add (X, Y), Y) 4660 if (N0.getOpcode() == ISD::SETCC) { 4661 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1); 4662 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get(); 4663 bool isAbs = false; 4664 bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode()); 4665 4666 if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) || 4667 (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) && 4668 N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1)) 4669 isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode()); 4670 else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) && 4671 N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1)) 4672 isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode()); 4673 4674 if (isAbs) { 4675 EVT VT = LHS.getValueType(); 4676 SDValue Shift = DAG.getNode( 4677 ISD::SRA, DL, VT, LHS, 4678 DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, VT)); 4679 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift); 4680 AddToWorkList(Shift.getNode()); 4681 AddToWorkList(Add.getNode()); 4682 return DAG.getNode(ISD::XOR, DL, VT, Add, Shift); 4683 } 4684 } 4685 4686 // If the VSELECT result requires splitting and the mask is provided by a 4687 // SETCC, then split both nodes and its operands before legalization. This 4688 // prevents the type legalizer from unrolling SETCC into scalar comparisons 4689 // and enables future optimizations (e.g. min/max pattern matching on X86). 4690 if (N0.getOpcode() == ISD::SETCC) { 4691 EVT VT = N->getValueType(0); 4692 4693 // Check if any splitting is required. 4694 if (TLI.getTypeAction(*DAG.getContext(), VT) != 4695 TargetLowering::TypeSplitVector) 4696 return SDValue(); 4697 4698 SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH; 4699 std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG); 4700 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1); 4701 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2); 4702 4703 Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL); 4704 Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH); 4705 4706 // Add the new VSELECT nodes to the work list in case they need to be split 4707 // again. 4708 AddToWorkList(Lo.getNode()); 4709 AddToWorkList(Hi.getNode()); 4710 4711 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi); 4712 } 4713 4714 // Fold (vselect (build_vector all_ones), N1, N2) -> N1 4715 if (ISD::isBuildVectorAllOnes(N0.getNode())) 4716 return N1; 4717 // Fold (vselect (build_vector all_zeros), N1, N2) -> N2 4718 if (ISD::isBuildVectorAllZeros(N0.getNode())) 4719 return N2; 4720 4721 // The ConvertSelectToConcatVector function is assuming both the above 4722 // checks for (vselect (build_vector all{ones,zeros) ...) have been made 4723 // and addressed. 4724 if (N1.getOpcode() == ISD::CONCAT_VECTORS && 4725 N2.getOpcode() == ISD::CONCAT_VECTORS && 4726 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) { 4727 SDValue CV = ConvertSelectToConcatVector(N, DAG); 4728 if (CV.getNode()) 4729 return CV; 4730 } 4731 4732 return SDValue(); 4733 } 4734 4735 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) { 4736 SDValue N0 = N->getOperand(0); 4737 SDValue N1 = N->getOperand(1); 4738 SDValue N2 = N->getOperand(2); 4739 SDValue N3 = N->getOperand(3); 4740 SDValue N4 = N->getOperand(4); 4741 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get(); 4742 4743 // fold select_cc lhs, rhs, x, x, cc -> x 4744 if (N2 == N3) 4745 return N2; 4746 4747 // Determine if the condition we're dealing with is constant 4748 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()), 4749 N0, N1, CC, SDLoc(N), false); 4750 if (SCC.getNode()) { 4751 AddToWorkList(SCC.getNode()); 4752 4753 if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) { 4754 if (!SCCC->isNullValue()) 4755 return N2; // cond always true -> true val 4756 else 4757 return N3; // cond always false -> false val 4758 } 4759 4760 // Fold to a simpler select_cc 4761 if (SCC.getOpcode() == ISD::SETCC) 4762 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(), 4763 SCC.getOperand(0), SCC.getOperand(1), N2, N3, 4764 SCC.getOperand(2)); 4765 } 4766 4767 // If we can fold this based on the true/false value, do so. 4768 if (SimplifySelectOps(N, N2, N3)) 4769 return SDValue(N, 0); // Don't revisit N. 4770 4771 // fold select_cc into other things, such as min/max/abs 4772 return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC); 4773 } 4774 4775 SDValue DAGCombiner::visitSETCC(SDNode *N) { 4776 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1), 4777 cast<CondCodeSDNode>(N->getOperand(2))->get(), 4778 SDLoc(N)); 4779 } 4780 4781 // tryToFoldExtendOfConstant - Try to fold a sext/zext/aext 4782 // dag node into a ConstantSDNode or a build_vector of constants. 4783 // This function is called by the DAGCombiner when visiting sext/zext/aext 4784 // dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND). 4785 // Vector extends are not folded if operations are legal; this is to 4786 // avoid introducing illegal build_vector dag nodes. 4787 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI, 4788 SelectionDAG &DAG, bool LegalTypes, 4789 bool LegalOperations) { 4790 unsigned Opcode = N->getOpcode(); 4791 SDValue N0 = N->getOperand(0); 4792 EVT VT = N->getValueType(0); 4793 4794 assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND || 4795 Opcode == ISD::ANY_EXTEND) && "Expected EXTEND dag node in input!"); 4796 4797 // fold (sext c1) -> c1 4798 // fold (zext c1) -> c1 4799 // fold (aext c1) -> c1 4800 if (isa<ConstantSDNode>(N0)) 4801 return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode(); 4802 4803 // fold (sext (build_vector AllConstants) -> (build_vector AllConstants) 4804 // fold (zext (build_vector AllConstants) -> (build_vector AllConstants) 4805 // fold (aext (build_vector AllConstants) -> (build_vector AllConstants) 4806 EVT SVT = VT.getScalarType(); 4807 if (!(VT.isVector() && 4808 (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) && 4809 ISD::isBuildVectorOfConstantSDNodes(N0.getNode()))) 4810 return nullptr; 4811 4812 // We can fold this node into a build_vector. 4813 unsigned VTBits = SVT.getSizeInBits(); 4814 unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits(); 4815 unsigned ShAmt = VTBits - EVTBits; 4816 SmallVector<SDValue, 8> Elts; 4817 unsigned NumElts = N0->getNumOperands(); 4818 SDLoc DL(N); 4819 4820 for (unsigned i=0; i != NumElts; ++i) { 4821 SDValue Op = N0->getOperand(i); 4822 if (Op->getOpcode() == ISD::UNDEF) { 4823 Elts.push_back(DAG.getUNDEF(SVT)); 4824 continue; 4825 } 4826 4827 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op); 4828 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue()); 4829 if (Opcode == ISD::SIGN_EXTEND) 4830 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(), 4831 SVT)); 4832 else 4833 Elts.push_back(DAG.getConstant(C.shl(ShAmt).lshr(ShAmt).getZExtValue(), 4834 SVT)); 4835 } 4836 4837 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts).getNode(); 4838 } 4839 4840 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this: 4841 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))" 4842 // transformation. Returns true if extension are possible and the above 4843 // mentioned transformation is profitable. 4844 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0, 4845 unsigned ExtOpc, 4846 SmallVectorImpl<SDNode *> &ExtendNodes, 4847 const TargetLowering &TLI) { 4848 bool HasCopyToRegUses = false; 4849 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType()); 4850 for (SDNode::use_iterator UI = N0.getNode()->use_begin(), 4851 UE = N0.getNode()->use_end(); 4852 UI != UE; ++UI) { 4853 SDNode *User = *UI; 4854 if (User == N) 4855 continue; 4856 if (UI.getUse().getResNo() != N0.getResNo()) 4857 continue; 4858 // FIXME: Only extend SETCC N, N and SETCC N, c for now. 4859 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) { 4860 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get(); 4861 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC)) 4862 // Sign bits will be lost after a zext. 4863 return false; 4864 bool Add = false; 4865 for (unsigned i = 0; i != 2; ++i) { 4866 SDValue UseOp = User->getOperand(i); 4867 if (UseOp == N0) 4868 continue; 4869 if (!isa<ConstantSDNode>(UseOp)) 4870 return false; 4871 Add = true; 4872 } 4873 if (Add) 4874 ExtendNodes.push_back(User); 4875 continue; 4876 } 4877 // If truncates aren't free and there are users we can't 4878 // extend, it isn't worthwhile. 4879 if (!isTruncFree) 4880 return false; 4881 // Remember if this value is live-out. 4882 if (User->getOpcode() == ISD::CopyToReg) 4883 HasCopyToRegUses = true; 4884 } 4885 4886 if (HasCopyToRegUses) { 4887 bool BothLiveOut = false; 4888 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end(); 4889 UI != UE; ++UI) { 4890 SDUse &Use = UI.getUse(); 4891 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) { 4892 BothLiveOut = true; 4893 break; 4894 } 4895 } 4896 if (BothLiveOut) 4897 // Both unextended and extended values are live out. There had better be 4898 // a good reason for the transformation. 4899 return ExtendNodes.size(); 4900 } 4901 return true; 4902 } 4903 4904 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs, 4905 SDValue Trunc, SDValue ExtLoad, SDLoc DL, 4906 ISD::NodeType ExtType) { 4907 // Extend SetCC uses if necessary. 4908 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) { 4909 SDNode *SetCC = SetCCs[i]; 4910 SmallVector<SDValue, 4> Ops; 4911 4912 for (unsigned j = 0; j != 2; ++j) { 4913 SDValue SOp = SetCC->getOperand(j); 4914 if (SOp == Trunc) 4915 Ops.push_back(ExtLoad); 4916 else 4917 Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp)); 4918 } 4919 4920 Ops.push_back(SetCC->getOperand(2)); 4921 CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops)); 4922 } 4923 } 4924 4925 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) { 4926 SDValue N0 = N->getOperand(0); 4927 EVT VT = N->getValueType(0); 4928 4929 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes, 4930 LegalOperations)) 4931 return SDValue(Res, 0); 4932 4933 // fold (sext (sext x)) -> (sext x) 4934 // fold (sext (aext x)) -> (sext x) 4935 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) 4936 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, 4937 N0.getOperand(0)); 4938 4939 if (N0.getOpcode() == ISD::TRUNCATE) { 4940 // fold (sext (truncate (load x))) -> (sext (smaller load x)) 4941 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n))) 4942 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode()); 4943 if (NarrowLoad.getNode()) { 4944 SDNode* oye = N0.getNode()->getOperand(0).getNode(); 4945 if (NarrowLoad.getNode() != N0.getNode()) { 4946 CombineTo(N0.getNode(), NarrowLoad); 4947 // CombineTo deleted the truncate, if needed, but not what's under it. 4948 AddToWorkList(oye); 4949 } 4950 return SDValue(N, 0); // Return N so it doesn't get rechecked! 4951 } 4952 4953 // See if the value being truncated is already sign extended. If so, just 4954 // eliminate the trunc/sext pair. 4955 SDValue Op = N0.getOperand(0); 4956 unsigned OpBits = Op.getValueType().getScalarType().getSizeInBits(); 4957 unsigned MidBits = N0.getValueType().getScalarType().getSizeInBits(); 4958 unsigned DestBits = VT.getScalarType().getSizeInBits(); 4959 unsigned NumSignBits = DAG.ComputeNumSignBits(Op); 4960 4961 if (OpBits == DestBits) { 4962 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign 4963 // bits, it is already ready. 4964 if (NumSignBits > DestBits-MidBits) 4965 return Op; 4966 } else if (OpBits < DestBits) { 4967 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign 4968 // bits, just sext from i32. 4969 if (NumSignBits > OpBits-MidBits) 4970 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op); 4971 } else { 4972 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign 4973 // bits, just truncate to i32. 4974 if (NumSignBits > OpBits-MidBits) 4975 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op); 4976 } 4977 4978 // fold (sext (truncate x)) -> (sextinreg x). 4979 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, 4980 N0.getValueType())) { 4981 if (OpBits < DestBits) 4982 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op); 4983 else if (OpBits > DestBits) 4984 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op); 4985 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op, 4986 DAG.getValueType(N0.getValueType())); 4987 } 4988 } 4989 4990 // fold (sext (load x)) -> (sext (truncate (sextload x))) 4991 // None of the supported targets knows how to perform load and sign extend 4992 // on vectors in one instruction. We only perform this transformation on 4993 // scalars. 4994 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() && 4995 ISD::isUNINDEXEDLoad(N0.getNode()) && 4996 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) || 4997 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()))) { 4998 bool DoXform = true; 4999 SmallVector<SDNode*, 4> SetCCs; 5000 if (!N0.hasOneUse()) 5001 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI); 5002 if (DoXform) { 5003 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 5004 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT, 5005 LN0->getChain(), 5006 LN0->getBasePtr(), N0.getValueType(), 5007 LN0->getMemOperand()); 5008 CombineTo(N, ExtLoad); 5009 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 5010 N0.getValueType(), ExtLoad); 5011 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1)); 5012 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N), 5013 ISD::SIGN_EXTEND); 5014 return SDValue(N, 0); // Return N so it doesn't get rechecked! 5015 } 5016 } 5017 5018 // fold (sext (sextload x)) -> (sext (truncate (sextload x))) 5019 // fold (sext ( extload x)) -> (sext (truncate (sextload x))) 5020 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) && 5021 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) { 5022 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 5023 EVT MemVT = LN0->getMemoryVT(); 5024 if ((!LegalOperations && !LN0->isVolatile()) || 5025 TLI.isLoadExtLegal(ISD::SEXTLOAD, MemVT)) { 5026 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT, 5027 LN0->getChain(), 5028 LN0->getBasePtr(), MemVT, 5029 LN0->getMemOperand()); 5030 CombineTo(N, ExtLoad); 5031 CombineTo(N0.getNode(), 5032 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 5033 N0.getValueType(), ExtLoad), 5034 ExtLoad.getValue(1)); 5035 return SDValue(N, 0); // Return N so it doesn't get rechecked! 5036 } 5037 } 5038 5039 // fold (sext (and/or/xor (load x), cst)) -> 5040 // (and/or/xor (sextload x), (sext cst)) 5041 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR || 5042 N0.getOpcode() == ISD::XOR) && 5043 isa<LoadSDNode>(N0.getOperand(0)) && 5044 N0.getOperand(1).getOpcode() == ISD::Constant && 5045 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()) && 5046 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) { 5047 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0)); 5048 if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) { 5049 bool DoXform = true; 5050 SmallVector<SDNode*, 4> SetCCs; 5051 if (!N0.hasOneUse()) 5052 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND, 5053 SetCCs, TLI); 5054 if (DoXform) { 5055 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT, 5056 LN0->getChain(), LN0->getBasePtr(), 5057 LN0->getMemoryVT(), 5058 LN0->getMemOperand()); 5059 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 5060 Mask = Mask.sext(VT.getSizeInBits()); 5061 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT, 5062 ExtLoad, DAG.getConstant(Mask, VT)); 5063 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, 5064 SDLoc(N0.getOperand(0)), 5065 N0.getOperand(0).getValueType(), ExtLoad); 5066 CombineTo(N, And); 5067 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1)); 5068 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N), 5069 ISD::SIGN_EXTEND); 5070 return SDValue(N, 0); // Return N so it doesn't get rechecked! 5071 } 5072 } 5073 } 5074 5075 if (N0.getOpcode() == ISD::SETCC) { 5076 // sext(setcc) -> sext_in_reg(vsetcc) for vectors. 5077 // Only do this before legalize for now. 5078 if (VT.isVector() && !LegalOperations && 5079 TLI.getBooleanContents(true) == 5080 TargetLowering::ZeroOrNegativeOneBooleanContent) { 5081 EVT N0VT = N0.getOperand(0).getValueType(); 5082 // On some architectures (such as SSE/NEON/etc) the SETCC result type is 5083 // of the same size as the compared operands. Only optimize sext(setcc()) 5084 // if this is the case. 5085 EVT SVT = getSetCCResultType(N0VT); 5086 5087 // We know that the # elements of the results is the same as the 5088 // # elements of the compare (and the # elements of the compare result 5089 // for that matter). Check to see that they are the same size. If so, 5090 // we know that the element size of the sext'd result matches the 5091 // element size of the compare operands. 5092 if (VT.getSizeInBits() == SVT.getSizeInBits()) 5093 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0), 5094 N0.getOperand(1), 5095 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 5096 5097 // If the desired elements are smaller or larger than the source 5098 // elements we can use a matching integer vector type and then 5099 // truncate/sign extend 5100 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger(); 5101 if (SVT == MatchingVectorType) { 5102 SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType, 5103 N0.getOperand(0), N0.getOperand(1), 5104 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 5105 return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT); 5106 } 5107 } 5108 5109 // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0) 5110 unsigned ElementWidth = VT.getScalarType().getSizeInBits(); 5111 SDValue NegOne = 5112 DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT); 5113 SDValue SCC = 5114 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1), 5115 NegOne, DAG.getConstant(0, VT), 5116 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true); 5117 if (SCC.getNode()) return SCC; 5118 5119 if (!VT.isVector()) { 5120 EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType()); 5121 if (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, SetCCVT)) { 5122 SDLoc DL(N); 5123 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get(); 5124 SDValue SetCC = DAG.getSetCC(DL, 5125 SetCCVT, 5126 N0.getOperand(0), N0.getOperand(1), CC); 5127 EVT SelectVT = getSetCCResultType(VT); 5128 return DAG.getSelect(DL, VT, 5129 DAG.getSExtOrTrunc(SetCC, DL, SelectVT), 5130 NegOne, DAG.getConstant(0, VT)); 5131 5132 } 5133 } 5134 } 5135 5136 // fold (sext x) -> (zext x) if the sign bit is known zero. 5137 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) && 5138 DAG.SignBitIsZero(N0)) 5139 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0); 5140 5141 return SDValue(); 5142 } 5143 5144 // isTruncateOf - If N is a truncate of some other value, return true, record 5145 // the value being truncated in Op and which of Op's bits are zero in KnownZero. 5146 // This function computes KnownZero to avoid a duplicated call to 5147 // computeKnownBits in the caller. 5148 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op, 5149 APInt &KnownZero) { 5150 APInt KnownOne; 5151 if (N->getOpcode() == ISD::TRUNCATE) { 5152 Op = N->getOperand(0); 5153 DAG.computeKnownBits(Op, KnownZero, KnownOne); 5154 return true; 5155 } 5156 5157 if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 || 5158 cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE) 5159 return false; 5160 5161 SDValue Op0 = N->getOperand(0); 5162 SDValue Op1 = N->getOperand(1); 5163 assert(Op0.getValueType() == Op1.getValueType()); 5164 5165 ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0); 5166 ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1); 5167 if (COp0 && COp0->isNullValue()) 5168 Op = Op1; 5169 else if (COp1 && COp1->isNullValue()) 5170 Op = Op0; 5171 else 5172 return false; 5173 5174 DAG.computeKnownBits(Op, KnownZero, KnownOne); 5175 5176 if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue()) 5177 return false; 5178 5179 return true; 5180 } 5181 5182 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) { 5183 SDValue N0 = N->getOperand(0); 5184 EVT VT = N->getValueType(0); 5185 5186 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes, 5187 LegalOperations)) 5188 return SDValue(Res, 0); 5189 5190 // fold (zext (zext x)) -> (zext x) 5191 // fold (zext (aext x)) -> (zext x) 5192 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) 5193 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, 5194 N0.getOperand(0)); 5195 5196 // fold (zext (truncate x)) -> (zext x) or 5197 // (zext (truncate x)) -> (truncate x) 5198 // This is valid when the truncated bits of x are already zero. 5199 // FIXME: We should extend this to work for vectors too. 5200 SDValue Op; 5201 APInt KnownZero; 5202 if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) { 5203 APInt TruncatedBits = 5204 (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ? 5205 APInt(Op.getValueSizeInBits(), 0) : 5206 APInt::getBitsSet(Op.getValueSizeInBits(), 5207 N0.getValueSizeInBits(), 5208 std::min(Op.getValueSizeInBits(), 5209 VT.getSizeInBits())); 5210 if (TruncatedBits == (KnownZero & TruncatedBits)) { 5211 if (VT.bitsGT(Op.getValueType())) 5212 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op); 5213 if (VT.bitsLT(Op.getValueType())) 5214 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op); 5215 5216 return Op; 5217 } 5218 } 5219 5220 // fold (zext (truncate (load x))) -> (zext (smaller load x)) 5221 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n))) 5222 if (N0.getOpcode() == ISD::TRUNCATE) { 5223 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode()); 5224 if (NarrowLoad.getNode()) { 5225 SDNode* oye = N0.getNode()->getOperand(0).getNode(); 5226 if (NarrowLoad.getNode() != N0.getNode()) { 5227 CombineTo(N0.getNode(), NarrowLoad); 5228 // CombineTo deleted the truncate, if needed, but not what's under it. 5229 AddToWorkList(oye); 5230 } 5231 return SDValue(N, 0); // Return N so it doesn't get rechecked! 5232 } 5233 } 5234 5235 // fold (zext (truncate x)) -> (and x, mask) 5236 if (N0.getOpcode() == ISD::TRUNCATE && 5237 (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) { 5238 5239 // fold (zext (truncate (load x))) -> (zext (smaller load x)) 5240 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n))) 5241 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode()); 5242 if (NarrowLoad.getNode()) { 5243 SDNode* oye = N0.getNode()->getOperand(0).getNode(); 5244 if (NarrowLoad.getNode() != N0.getNode()) { 5245 CombineTo(N0.getNode(), NarrowLoad); 5246 // CombineTo deleted the truncate, if needed, but not what's under it. 5247 AddToWorkList(oye); 5248 } 5249 return SDValue(N, 0); // Return N so it doesn't get rechecked! 5250 } 5251 5252 SDValue Op = N0.getOperand(0); 5253 if (Op.getValueType().bitsLT(VT)) { 5254 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op); 5255 AddToWorkList(Op.getNode()); 5256 } else if (Op.getValueType().bitsGT(VT)) { 5257 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op); 5258 AddToWorkList(Op.getNode()); 5259 } 5260 return DAG.getZeroExtendInReg(Op, SDLoc(N), 5261 N0.getValueType().getScalarType()); 5262 } 5263 5264 // Fold (zext (and (trunc x), cst)) -> (and x, cst), 5265 // if either of the casts is not free. 5266 if (N0.getOpcode() == ISD::AND && 5267 N0.getOperand(0).getOpcode() == ISD::TRUNCATE && 5268 N0.getOperand(1).getOpcode() == ISD::Constant && 5269 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(), 5270 N0.getValueType()) || 5271 !TLI.isZExtFree(N0.getValueType(), VT))) { 5272 SDValue X = N0.getOperand(0).getOperand(0); 5273 if (X.getValueType().bitsLT(VT)) { 5274 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X); 5275 } else if (X.getValueType().bitsGT(VT)) { 5276 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X); 5277 } 5278 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 5279 Mask = Mask.zext(VT.getSizeInBits()); 5280 return DAG.getNode(ISD::AND, SDLoc(N), VT, 5281 X, DAG.getConstant(Mask, VT)); 5282 } 5283 5284 // fold (zext (load x)) -> (zext (truncate (zextload x))) 5285 // None of the supported targets knows how to perform load and vector_zext 5286 // on vectors in one instruction. We only perform this transformation on 5287 // scalars. 5288 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() && 5289 ISD::isUNINDEXEDLoad(N0.getNode()) && 5290 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) || 5291 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()))) { 5292 bool DoXform = true; 5293 SmallVector<SDNode*, 4> SetCCs; 5294 if (!N0.hasOneUse()) 5295 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI); 5296 if (DoXform) { 5297 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 5298 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT, 5299 LN0->getChain(), 5300 LN0->getBasePtr(), N0.getValueType(), 5301 LN0->getMemOperand()); 5302 CombineTo(N, ExtLoad); 5303 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 5304 N0.getValueType(), ExtLoad); 5305 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1)); 5306 5307 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N), 5308 ISD::ZERO_EXTEND); 5309 return SDValue(N, 0); // Return N so it doesn't get rechecked! 5310 } 5311 } 5312 5313 // fold (zext (and/or/xor (load x), cst)) -> 5314 // (and/or/xor (zextload x), (zext cst)) 5315 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR || 5316 N0.getOpcode() == ISD::XOR) && 5317 isa<LoadSDNode>(N0.getOperand(0)) && 5318 N0.getOperand(1).getOpcode() == ISD::Constant && 5319 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()) && 5320 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) { 5321 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0)); 5322 if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) { 5323 bool DoXform = true; 5324 SmallVector<SDNode*, 4> SetCCs; 5325 if (!N0.hasOneUse()) 5326 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND, 5327 SetCCs, TLI); 5328 if (DoXform) { 5329 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT, 5330 LN0->getChain(), LN0->getBasePtr(), 5331 LN0->getMemoryVT(), 5332 LN0->getMemOperand()); 5333 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 5334 Mask = Mask.zext(VT.getSizeInBits()); 5335 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT, 5336 ExtLoad, DAG.getConstant(Mask, VT)); 5337 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, 5338 SDLoc(N0.getOperand(0)), 5339 N0.getOperand(0).getValueType(), ExtLoad); 5340 CombineTo(N, And); 5341 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1)); 5342 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N), 5343 ISD::ZERO_EXTEND); 5344 return SDValue(N, 0); // Return N so it doesn't get rechecked! 5345 } 5346 } 5347 } 5348 5349 // fold (zext (zextload x)) -> (zext (truncate (zextload x))) 5350 // fold (zext ( extload x)) -> (zext (truncate (zextload x))) 5351 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) && 5352 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) { 5353 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 5354 EVT MemVT = LN0->getMemoryVT(); 5355 if ((!LegalOperations && !LN0->isVolatile()) || 5356 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT)) { 5357 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT, 5358 LN0->getChain(), 5359 LN0->getBasePtr(), MemVT, 5360 LN0->getMemOperand()); 5361 CombineTo(N, ExtLoad); 5362 CombineTo(N0.getNode(), 5363 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), 5364 ExtLoad), 5365 ExtLoad.getValue(1)); 5366 return SDValue(N, 0); // Return N so it doesn't get rechecked! 5367 } 5368 } 5369 5370 if (N0.getOpcode() == ISD::SETCC) { 5371 if (!LegalOperations && VT.isVector() && 5372 N0.getValueType().getVectorElementType() == MVT::i1) { 5373 EVT N0VT = N0.getOperand(0).getValueType(); 5374 if (getSetCCResultType(N0VT) == N0.getValueType()) 5375 return SDValue(); 5376 5377 // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors. 5378 // Only do this before legalize for now. 5379 EVT EltVT = VT.getVectorElementType(); 5380 SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(), 5381 DAG.getConstant(1, EltVT)); 5382 if (VT.getSizeInBits() == N0VT.getSizeInBits()) 5383 // We know that the # elements of the results is the same as the 5384 // # elements of the compare (and the # elements of the compare result 5385 // for that matter). Check to see that they are the same size. If so, 5386 // we know that the element size of the sext'd result matches the 5387 // element size of the compare operands. 5388 return DAG.getNode(ISD::AND, SDLoc(N), VT, 5389 DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0), 5390 N0.getOperand(1), 5391 cast<CondCodeSDNode>(N0.getOperand(2))->get()), 5392 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, 5393 OneOps)); 5394 5395 // If the desired elements are smaller or larger than the source 5396 // elements we can use a matching integer vector type and then 5397 // truncate/sign extend 5398 EVT MatchingElementType = 5399 EVT::getIntegerVT(*DAG.getContext(), 5400 N0VT.getScalarType().getSizeInBits()); 5401 EVT MatchingVectorType = 5402 EVT::getVectorVT(*DAG.getContext(), MatchingElementType, 5403 N0VT.getVectorNumElements()); 5404 SDValue VsetCC = 5405 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0), 5406 N0.getOperand(1), 5407 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 5408 return DAG.getNode(ISD::AND, SDLoc(N), VT, 5409 DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT), 5410 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, OneOps)); 5411 } 5412 5413 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc 5414 SDValue SCC = 5415 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1), 5416 DAG.getConstant(1, VT), DAG.getConstant(0, VT), 5417 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true); 5418 if (SCC.getNode()) return SCC; 5419 } 5420 5421 // (zext (shl (zext x), cst)) -> (shl (zext x), cst) 5422 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) && 5423 isa<ConstantSDNode>(N0.getOperand(1)) && 5424 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND && 5425 N0.hasOneUse()) { 5426 SDValue ShAmt = N0.getOperand(1); 5427 unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue(); 5428 if (N0.getOpcode() == ISD::SHL) { 5429 SDValue InnerZExt = N0.getOperand(0); 5430 // If the original shl may be shifting out bits, do not perform this 5431 // transformation. 5432 unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() - 5433 InnerZExt.getOperand(0).getValueType().getSizeInBits(); 5434 if (ShAmtVal > KnownZeroBits) 5435 return SDValue(); 5436 } 5437 5438 SDLoc DL(N); 5439 5440 // Ensure that the shift amount is wide enough for the shifted value. 5441 if (VT.getSizeInBits() >= 256) 5442 ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt); 5443 5444 return DAG.getNode(N0.getOpcode(), DL, VT, 5445 DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)), 5446 ShAmt); 5447 } 5448 5449 return SDValue(); 5450 } 5451 5452 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) { 5453 SDValue N0 = N->getOperand(0); 5454 EVT VT = N->getValueType(0); 5455 5456 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes, 5457 LegalOperations)) 5458 return SDValue(Res, 0); 5459 5460 // fold (aext (aext x)) -> (aext x) 5461 // fold (aext (zext x)) -> (zext x) 5462 // fold (aext (sext x)) -> (sext x) 5463 if (N0.getOpcode() == ISD::ANY_EXTEND || 5464 N0.getOpcode() == ISD::ZERO_EXTEND || 5465 N0.getOpcode() == ISD::SIGN_EXTEND) 5466 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0)); 5467 5468 // fold (aext (truncate (load x))) -> (aext (smaller load x)) 5469 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n))) 5470 if (N0.getOpcode() == ISD::TRUNCATE) { 5471 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode()); 5472 if (NarrowLoad.getNode()) { 5473 SDNode* oye = N0.getNode()->getOperand(0).getNode(); 5474 if (NarrowLoad.getNode() != N0.getNode()) { 5475 CombineTo(N0.getNode(), NarrowLoad); 5476 // CombineTo deleted the truncate, if needed, but not what's under it. 5477 AddToWorkList(oye); 5478 } 5479 return SDValue(N, 0); // Return N so it doesn't get rechecked! 5480 } 5481 } 5482 5483 // fold (aext (truncate x)) 5484 if (N0.getOpcode() == ISD::TRUNCATE) { 5485 SDValue TruncOp = N0.getOperand(0); 5486 if (TruncOp.getValueType() == VT) 5487 return TruncOp; // x iff x size == zext size. 5488 if (TruncOp.getValueType().bitsGT(VT)) 5489 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp); 5490 return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp); 5491 } 5492 5493 // Fold (aext (and (trunc x), cst)) -> (and x, cst) 5494 // if the trunc is not free. 5495 if (N0.getOpcode() == ISD::AND && 5496 N0.getOperand(0).getOpcode() == ISD::TRUNCATE && 5497 N0.getOperand(1).getOpcode() == ISD::Constant && 5498 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(), 5499 N0.getValueType())) { 5500 SDValue X = N0.getOperand(0).getOperand(0); 5501 if (X.getValueType().bitsLT(VT)) { 5502 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X); 5503 } else if (X.getValueType().bitsGT(VT)) { 5504 X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X); 5505 } 5506 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 5507 Mask = Mask.zext(VT.getSizeInBits()); 5508 return DAG.getNode(ISD::AND, SDLoc(N), VT, 5509 X, DAG.getConstant(Mask, VT)); 5510 } 5511 5512 // fold (aext (load x)) -> (aext (truncate (extload x))) 5513 // None of the supported targets knows how to perform load and any_ext 5514 // on vectors in one instruction. We only perform this transformation on 5515 // scalars. 5516 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() && 5517 ISD::isUNINDEXEDLoad(N0.getNode()) && 5518 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) || 5519 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) { 5520 bool DoXform = true; 5521 SmallVector<SDNode*, 4> SetCCs; 5522 if (!N0.hasOneUse()) 5523 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI); 5524 if (DoXform) { 5525 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 5526 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT, 5527 LN0->getChain(), 5528 LN0->getBasePtr(), N0.getValueType(), 5529 LN0->getMemOperand()); 5530 CombineTo(N, ExtLoad); 5531 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 5532 N0.getValueType(), ExtLoad); 5533 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1)); 5534 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N), 5535 ISD::ANY_EXTEND); 5536 return SDValue(N, 0); // Return N so it doesn't get rechecked! 5537 } 5538 } 5539 5540 // fold (aext (zextload x)) -> (aext (truncate (zextload x))) 5541 // fold (aext (sextload x)) -> (aext (truncate (sextload x))) 5542 // fold (aext ( extload x)) -> (aext (truncate (extload x))) 5543 if (N0.getOpcode() == ISD::LOAD && 5544 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 5545 N0.hasOneUse()) { 5546 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 5547 ISD::LoadExtType ExtType = LN0->getExtensionType(); 5548 EVT MemVT = LN0->getMemoryVT(); 5549 if (!LegalOperations || TLI.isLoadExtLegal(ExtType, MemVT)) { 5550 SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N), 5551 VT, LN0->getChain(), LN0->getBasePtr(), 5552 MemVT, LN0->getMemOperand()); 5553 CombineTo(N, ExtLoad); 5554 CombineTo(N0.getNode(), 5555 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 5556 N0.getValueType(), ExtLoad), 5557 ExtLoad.getValue(1)); 5558 return SDValue(N, 0); // Return N so it doesn't get rechecked! 5559 } 5560 } 5561 5562 if (N0.getOpcode() == ISD::SETCC) { 5563 // For vectors: 5564 // aext(setcc) -> vsetcc 5565 // aext(setcc) -> truncate(vsetcc) 5566 // aext(setcc) -> aext(vsetcc) 5567 // Only do this before legalize for now. 5568 if (VT.isVector() && !LegalOperations) { 5569 EVT N0VT = N0.getOperand(0).getValueType(); 5570 // We know that the # elements of the results is the same as the 5571 // # elements of the compare (and the # elements of the compare result 5572 // for that matter). Check to see that they are the same size. If so, 5573 // we know that the element size of the sext'd result matches the 5574 // element size of the compare operands. 5575 if (VT.getSizeInBits() == N0VT.getSizeInBits()) 5576 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0), 5577 N0.getOperand(1), 5578 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 5579 // If the desired elements are smaller or larger than the source 5580 // elements we can use a matching integer vector type and then 5581 // truncate/any extend 5582 else { 5583 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger(); 5584 SDValue VsetCC = 5585 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0), 5586 N0.getOperand(1), 5587 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 5588 return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT); 5589 } 5590 } 5591 5592 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc 5593 SDValue SCC = 5594 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1), 5595 DAG.getConstant(1, VT), DAG.getConstant(0, VT), 5596 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true); 5597 if (SCC.getNode()) 5598 return SCC; 5599 } 5600 5601 return SDValue(); 5602 } 5603 5604 /// GetDemandedBits - See if the specified operand can be simplified with the 5605 /// knowledge that only the bits specified by Mask are used. If so, return the 5606 /// simpler operand, otherwise return a null SDValue. 5607 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) { 5608 switch (V.getOpcode()) { 5609 default: break; 5610 case ISD::Constant: { 5611 const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode()); 5612 assert(CV && "Const value should be ConstSDNode."); 5613 const APInt &CVal = CV->getAPIntValue(); 5614 APInt NewVal = CVal & Mask; 5615 if (NewVal != CVal) 5616 return DAG.getConstant(NewVal, V.getValueType()); 5617 break; 5618 } 5619 case ISD::OR: 5620 case ISD::XOR: 5621 // If the LHS or RHS don't contribute bits to the or, drop them. 5622 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask)) 5623 return V.getOperand(1); 5624 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask)) 5625 return V.getOperand(0); 5626 break; 5627 case ISD::SRL: 5628 // Only look at single-use SRLs. 5629 if (!V.getNode()->hasOneUse()) 5630 break; 5631 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) { 5632 // See if we can recursively simplify the LHS. 5633 unsigned Amt = RHSC->getZExtValue(); 5634 5635 // Watch out for shift count overflow though. 5636 if (Amt >= Mask.getBitWidth()) break; 5637 APInt NewMask = Mask << Amt; 5638 SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask); 5639 if (SimplifyLHS.getNode()) 5640 return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(), 5641 SimplifyLHS, V.getOperand(1)); 5642 } 5643 } 5644 return SDValue(); 5645 } 5646 5647 /// ReduceLoadWidth - If the result of a wider load is shifted to right of N 5648 /// bits and then truncated to a narrower type and where N is a multiple 5649 /// of number of bits of the narrower type, transform it to a narrower load 5650 /// from address + N / num of bits of new type. If the result is to be 5651 /// extended, also fold the extension to form a extending load. 5652 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) { 5653 unsigned Opc = N->getOpcode(); 5654 5655 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD; 5656 SDValue N0 = N->getOperand(0); 5657 EVT VT = N->getValueType(0); 5658 EVT ExtVT = VT; 5659 5660 // This transformation isn't valid for vector loads. 5661 if (VT.isVector()) 5662 return SDValue(); 5663 5664 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then 5665 // extended to VT. 5666 if (Opc == ISD::SIGN_EXTEND_INREG) { 5667 ExtType = ISD::SEXTLOAD; 5668 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT(); 5669 } else if (Opc == ISD::SRL) { 5670 // Another special-case: SRL is basically zero-extending a narrower value. 5671 ExtType = ISD::ZEXTLOAD; 5672 N0 = SDValue(N, 0); 5673 ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 5674 if (!N01) return SDValue(); 5675 ExtVT = EVT::getIntegerVT(*DAG.getContext(), 5676 VT.getSizeInBits() - N01->getZExtValue()); 5677 } 5678 if (LegalOperations && !TLI.isLoadExtLegal(ExtType, ExtVT)) 5679 return SDValue(); 5680 5681 unsigned EVTBits = ExtVT.getSizeInBits(); 5682 5683 // Do not generate loads of non-round integer types since these can 5684 // be expensive (and would be wrong if the type is not byte sized). 5685 if (!ExtVT.isRound()) 5686 return SDValue(); 5687 5688 unsigned ShAmt = 0; 5689 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) { 5690 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 5691 ShAmt = N01->getZExtValue(); 5692 // Is the shift amount a multiple of size of VT? 5693 if ((ShAmt & (EVTBits-1)) == 0) { 5694 N0 = N0.getOperand(0); 5695 // Is the load width a multiple of size of VT? 5696 if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0) 5697 return SDValue(); 5698 } 5699 5700 // At this point, we must have a load or else we can't do the transform. 5701 if (!isa<LoadSDNode>(N0)) return SDValue(); 5702 5703 // Because a SRL must be assumed to *need* to zero-extend the high bits 5704 // (as opposed to anyext the high bits), we can't combine the zextload 5705 // lowering of SRL and an sextload. 5706 if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD) 5707 return SDValue(); 5708 5709 // If the shift amount is larger than the input type then we're not 5710 // accessing any of the loaded bytes. If the load was a zextload/extload 5711 // then the result of the shift+trunc is zero/undef (handled elsewhere). 5712 if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits()) 5713 return SDValue(); 5714 } 5715 } 5716 5717 // If the load is shifted left (and the result isn't shifted back right), 5718 // we can fold the truncate through the shift. 5719 unsigned ShLeftAmt = 0; 5720 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() && 5721 ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) { 5722 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 5723 ShLeftAmt = N01->getZExtValue(); 5724 N0 = N0.getOperand(0); 5725 } 5726 } 5727 5728 // If we haven't found a load, we can't narrow it. Don't transform one with 5729 // multiple uses, this would require adding a new load. 5730 if (!isa<LoadSDNode>(N0) || !N0.hasOneUse()) 5731 return SDValue(); 5732 5733 // Don't change the width of a volatile load. 5734 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 5735 if (LN0->isVolatile()) 5736 return SDValue(); 5737 5738 // Verify that we are actually reducing a load width here. 5739 if (LN0->getMemoryVT().getSizeInBits() < EVTBits) 5740 return SDValue(); 5741 5742 // For the transform to be legal, the load must produce only two values 5743 // (the value loaded and the chain). Don't transform a pre-increment 5744 // load, for example, which produces an extra value. Otherwise the 5745 // transformation is not equivalent, and the downstream logic to replace 5746 // uses gets things wrong. 5747 if (LN0->getNumValues() > 2) 5748 return SDValue(); 5749 5750 // If the load that we're shrinking is an extload and we're not just 5751 // discarding the extension we can't simply shrink the load. Bail. 5752 // TODO: It would be possible to merge the extensions in some cases. 5753 if (LN0->getExtensionType() != ISD::NON_EXTLOAD && 5754 LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt) 5755 return SDValue(); 5756 5757 EVT PtrType = N0.getOperand(1).getValueType(); 5758 5759 if (PtrType == MVT::Untyped || PtrType.isExtended()) 5760 // It's not possible to generate a constant of extended or untyped type. 5761 return SDValue(); 5762 5763 // For big endian targets, we need to adjust the offset to the pointer to 5764 // load the correct bytes. 5765 if (TLI.isBigEndian()) { 5766 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits(); 5767 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits(); 5768 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt; 5769 } 5770 5771 uint64_t PtrOff = ShAmt / 8; 5772 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff); 5773 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0), 5774 PtrType, LN0->getBasePtr(), 5775 DAG.getConstant(PtrOff, PtrType)); 5776 AddToWorkList(NewPtr.getNode()); 5777 5778 SDValue Load; 5779 if (ExtType == ISD::NON_EXTLOAD) 5780 Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr, 5781 LN0->getPointerInfo().getWithOffset(PtrOff), 5782 LN0->isVolatile(), LN0->isNonTemporal(), 5783 LN0->isInvariant(), NewAlign, LN0->getTBAAInfo()); 5784 else 5785 Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr, 5786 LN0->getPointerInfo().getWithOffset(PtrOff), 5787 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(), 5788 NewAlign, LN0->getTBAAInfo()); 5789 5790 // Replace the old load's chain with the new load's chain. 5791 WorkListRemover DeadNodes(*this); 5792 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1)); 5793 5794 // Shift the result left, if we've swallowed a left shift. 5795 SDValue Result = Load; 5796 if (ShLeftAmt != 0) { 5797 EVT ShImmTy = getShiftAmountTy(Result.getValueType()); 5798 if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt)) 5799 ShImmTy = VT; 5800 // If the shift amount is as large as the result size (but, presumably, 5801 // no larger than the source) then the useful bits of the result are 5802 // zero; we can't simply return the shortened shift, because the result 5803 // of that operation is undefined. 5804 if (ShLeftAmt >= VT.getSizeInBits()) 5805 Result = DAG.getConstant(0, VT); 5806 else 5807 Result = DAG.getNode(ISD::SHL, SDLoc(N0), VT, 5808 Result, DAG.getConstant(ShLeftAmt, ShImmTy)); 5809 } 5810 5811 // Return the new loaded value. 5812 return Result; 5813 } 5814 5815 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) { 5816 SDValue N0 = N->getOperand(0); 5817 SDValue N1 = N->getOperand(1); 5818 EVT VT = N->getValueType(0); 5819 EVT EVT = cast<VTSDNode>(N1)->getVT(); 5820 unsigned VTBits = VT.getScalarType().getSizeInBits(); 5821 unsigned EVTBits = EVT.getScalarType().getSizeInBits(); 5822 5823 // fold (sext_in_reg c1) -> c1 5824 if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF) 5825 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1); 5826 5827 // If the input is already sign extended, just drop the extension. 5828 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1) 5829 return N0; 5830 5831 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2 5832 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG && 5833 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT())) 5834 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, 5835 N0.getOperand(0), N1); 5836 5837 // fold (sext_in_reg (sext x)) -> (sext x) 5838 // fold (sext_in_reg (aext x)) -> (sext x) 5839 // if x is small enough. 5840 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) { 5841 SDValue N00 = N0.getOperand(0); 5842 if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits && 5843 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT))) 5844 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1); 5845 } 5846 5847 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero. 5848 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits))) 5849 return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT); 5850 5851 // fold operands of sext_in_reg based on knowledge that the top bits are not 5852 // demanded. 5853 if (SimplifyDemandedBits(SDValue(N, 0))) 5854 return SDValue(N, 0); 5855 5856 // fold (sext_in_reg (load x)) -> (smaller sextload x) 5857 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits)) 5858 SDValue NarrowLoad = ReduceLoadWidth(N); 5859 if (NarrowLoad.getNode()) 5860 return NarrowLoad; 5861 5862 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24) 5863 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible. 5864 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above. 5865 if (N0.getOpcode() == ISD::SRL) { 5866 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1))) 5867 if (ShAmt->getZExtValue()+EVTBits <= VTBits) { 5868 // We can turn this into an SRA iff the input to the SRL is already sign 5869 // extended enough. 5870 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0)); 5871 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits) 5872 return DAG.getNode(ISD::SRA, SDLoc(N), VT, 5873 N0.getOperand(0), N0.getOperand(1)); 5874 } 5875 } 5876 5877 // fold (sext_inreg (extload x)) -> (sextload x) 5878 if (ISD::isEXTLoad(N0.getNode()) && 5879 ISD::isUNINDEXEDLoad(N0.getNode()) && 5880 EVT == cast<LoadSDNode>(N0)->getMemoryVT() && 5881 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) || 5882 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) { 5883 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 5884 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT, 5885 LN0->getChain(), 5886 LN0->getBasePtr(), EVT, 5887 LN0->getMemOperand()); 5888 CombineTo(N, ExtLoad); 5889 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 5890 AddToWorkList(ExtLoad.getNode()); 5891 return SDValue(N, 0); // Return N so it doesn't get rechecked! 5892 } 5893 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use 5894 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 5895 N0.hasOneUse() && 5896 EVT == cast<LoadSDNode>(N0)->getMemoryVT() && 5897 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) || 5898 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) { 5899 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 5900 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT, 5901 LN0->getChain(), 5902 LN0->getBasePtr(), EVT, 5903 LN0->getMemOperand()); 5904 CombineTo(N, ExtLoad); 5905 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 5906 return SDValue(N, 0); // Return N so it doesn't get rechecked! 5907 } 5908 5909 // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16)) 5910 if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) { 5911 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0), 5912 N0.getOperand(1), false); 5913 if (BSwap.getNode()) 5914 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, 5915 BSwap, N1); 5916 } 5917 5918 // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs 5919 // into a build_vector. 5920 if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) { 5921 SmallVector<SDValue, 8> Elts; 5922 unsigned NumElts = N0->getNumOperands(); 5923 unsigned ShAmt = VTBits - EVTBits; 5924 5925 for (unsigned i = 0; i != NumElts; ++i) { 5926 SDValue Op = N0->getOperand(i); 5927 if (Op->getOpcode() == ISD::UNDEF) { 5928 Elts.push_back(Op); 5929 continue; 5930 } 5931 5932 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op); 5933 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue()); 5934 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(), 5935 Op.getValueType())); 5936 } 5937 5938 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Elts); 5939 } 5940 5941 return SDValue(); 5942 } 5943 5944 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) { 5945 SDValue N0 = N->getOperand(0); 5946 EVT VT = N->getValueType(0); 5947 bool isLE = TLI.isLittleEndian(); 5948 5949 // noop truncate 5950 if (N0.getValueType() == N->getValueType(0)) 5951 return N0; 5952 // fold (truncate c1) -> c1 5953 if (isa<ConstantSDNode>(N0)) 5954 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0); 5955 // fold (truncate (truncate x)) -> (truncate x) 5956 if (N0.getOpcode() == ISD::TRUNCATE) 5957 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0)); 5958 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x 5959 if (N0.getOpcode() == ISD::ZERO_EXTEND || 5960 N0.getOpcode() == ISD::SIGN_EXTEND || 5961 N0.getOpcode() == ISD::ANY_EXTEND) { 5962 if (N0.getOperand(0).getValueType().bitsLT(VT)) 5963 // if the source is smaller than the dest, we still need an extend 5964 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, 5965 N0.getOperand(0)); 5966 if (N0.getOperand(0).getValueType().bitsGT(VT)) 5967 // if the source is larger than the dest, than we just need the truncate 5968 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0)); 5969 // if the source and dest are the same type, we can drop both the extend 5970 // and the truncate. 5971 return N0.getOperand(0); 5972 } 5973 5974 // Fold extract-and-trunc into a narrow extract. For example: 5975 // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1) 5976 // i32 y = TRUNCATE(i64 x) 5977 // -- becomes -- 5978 // v16i8 b = BITCAST (v2i64 val) 5979 // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8) 5980 // 5981 // Note: We only run this optimization after type legalization (which often 5982 // creates this pattern) and before operation legalization after which 5983 // we need to be more careful about the vector instructions that we generate. 5984 if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT && 5985 LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) { 5986 5987 EVT VecTy = N0.getOperand(0).getValueType(); 5988 EVT ExTy = N0.getValueType(); 5989 EVT TrTy = N->getValueType(0); 5990 5991 unsigned NumElem = VecTy.getVectorNumElements(); 5992 unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits(); 5993 5994 EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem); 5995 assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size"); 5996 5997 SDValue EltNo = N0->getOperand(1); 5998 if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) { 5999 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue(); 6000 EVT IndexTy = TLI.getVectorIdxTy(); 6001 int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1)); 6002 6003 SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N), 6004 NVT, N0.getOperand(0)); 6005 6006 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, 6007 SDLoc(N), TrTy, V, 6008 DAG.getConstant(Index, IndexTy)); 6009 } 6010 } 6011 6012 // Fold a series of buildvector, bitcast, and truncate if possible. 6013 // For example fold 6014 // (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to 6015 // (2xi32 (buildvector x, y)). 6016 if (Level == AfterLegalizeVectorOps && VT.isVector() && 6017 N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() && 6018 N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR && 6019 N0.getOperand(0).hasOneUse()) { 6020 6021 SDValue BuildVect = N0.getOperand(0); 6022 EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType(); 6023 EVT TruncVecEltTy = VT.getVectorElementType(); 6024 6025 // Check that the element types match. 6026 if (BuildVectEltTy == TruncVecEltTy) { 6027 // Now we only need to compute the offset of the truncated elements. 6028 unsigned BuildVecNumElts = BuildVect.getNumOperands(); 6029 unsigned TruncVecNumElts = VT.getVectorNumElements(); 6030 unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts; 6031 6032 assert((BuildVecNumElts % TruncVecNumElts) == 0 && 6033 "Invalid number of elements"); 6034 6035 SmallVector<SDValue, 8> Opnds; 6036 for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset) 6037 Opnds.push_back(BuildVect.getOperand(i)); 6038 6039 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds); 6040 } 6041 } 6042 6043 // See if we can simplify the input to this truncate through knowledge that 6044 // only the low bits are being used. 6045 // For example "trunc (or (shl x, 8), y)" // -> trunc y 6046 // Currently we only perform this optimization on scalars because vectors 6047 // may have different active low bits. 6048 if (!VT.isVector()) { 6049 SDValue Shorter = 6050 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(), 6051 VT.getSizeInBits())); 6052 if (Shorter.getNode()) 6053 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter); 6054 } 6055 // fold (truncate (load x)) -> (smaller load x) 6056 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits)) 6057 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) { 6058 SDValue Reduced = ReduceLoadWidth(N); 6059 if (Reduced.getNode()) 6060 return Reduced; 6061 // Handle the case where the load remains an extending load even 6062 // after truncation. 6063 if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) { 6064 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6065 if (!LN0->isVolatile() && 6066 LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) { 6067 SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0), 6068 VT, LN0->getChain(), LN0->getBasePtr(), 6069 LN0->getMemoryVT(), 6070 LN0->getMemOperand()); 6071 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1)); 6072 return NewLoad; 6073 } 6074 } 6075 } 6076 // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)), 6077 // where ... are all 'undef'. 6078 if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) { 6079 SmallVector<EVT, 8> VTs; 6080 SDValue V; 6081 unsigned Idx = 0; 6082 unsigned NumDefs = 0; 6083 6084 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) { 6085 SDValue X = N0.getOperand(i); 6086 if (X.getOpcode() != ISD::UNDEF) { 6087 V = X; 6088 Idx = i; 6089 NumDefs++; 6090 } 6091 // Stop if more than one members are non-undef. 6092 if (NumDefs > 1) 6093 break; 6094 VTs.push_back(EVT::getVectorVT(*DAG.getContext(), 6095 VT.getVectorElementType(), 6096 X.getValueType().getVectorNumElements())); 6097 } 6098 6099 if (NumDefs == 0) 6100 return DAG.getUNDEF(VT); 6101 6102 if (NumDefs == 1) { 6103 assert(V.getNode() && "The single defined operand is empty!"); 6104 SmallVector<SDValue, 8> Opnds; 6105 for (unsigned i = 0, e = VTs.size(); i != e; ++i) { 6106 if (i != Idx) { 6107 Opnds.push_back(DAG.getUNDEF(VTs[i])); 6108 continue; 6109 } 6110 SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V); 6111 AddToWorkList(NV.getNode()); 6112 Opnds.push_back(NV); 6113 } 6114 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds); 6115 } 6116 } 6117 6118 // Simplify the operands using demanded-bits information. 6119 if (!VT.isVector() && 6120 SimplifyDemandedBits(SDValue(N, 0))) 6121 return SDValue(N, 0); 6122 6123 return SDValue(); 6124 } 6125 6126 static SDNode *getBuildPairElt(SDNode *N, unsigned i) { 6127 SDValue Elt = N->getOperand(i); 6128 if (Elt.getOpcode() != ISD::MERGE_VALUES) 6129 return Elt.getNode(); 6130 return Elt.getOperand(Elt.getResNo()).getNode(); 6131 } 6132 6133 /// CombineConsecutiveLoads - build_pair (load, load) -> load 6134 /// if load locations are consecutive. 6135 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) { 6136 assert(N->getOpcode() == ISD::BUILD_PAIR); 6137 6138 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0)); 6139 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1)); 6140 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() || 6141 LD1->getAddressSpace() != LD2->getAddressSpace()) 6142 return SDValue(); 6143 EVT LD1VT = LD1->getValueType(0); 6144 6145 if (ISD::isNON_EXTLoad(LD2) && 6146 LD2->hasOneUse() && 6147 // If both are volatile this would reduce the number of volatile loads. 6148 // If one is volatile it might be ok, but play conservative and bail out. 6149 !LD1->isVolatile() && 6150 !LD2->isVolatile() && 6151 DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) { 6152 unsigned Align = LD1->getAlignment(); 6153 unsigned NewAlign = TLI.getDataLayout()-> 6154 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext())); 6155 6156 if (NewAlign <= Align && 6157 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT))) 6158 return DAG.getLoad(VT, SDLoc(N), LD1->getChain(), 6159 LD1->getBasePtr(), LD1->getPointerInfo(), 6160 false, false, false, Align); 6161 } 6162 6163 return SDValue(); 6164 } 6165 6166 SDValue DAGCombiner::visitBITCAST(SDNode *N) { 6167 SDValue N0 = N->getOperand(0); 6168 EVT VT = N->getValueType(0); 6169 6170 // If the input is a BUILD_VECTOR with all constant elements, fold this now. 6171 // Only do this before legalize, since afterward the target may be depending 6172 // on the bitconvert. 6173 // First check to see if this is all constant. 6174 if (!LegalTypes && 6175 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() && 6176 VT.isVector()) { 6177 bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant(); 6178 6179 EVT DestEltVT = N->getValueType(0).getVectorElementType(); 6180 assert(!DestEltVT.isVector() && 6181 "Element type of vector ValueType must not be vector!"); 6182 if (isSimple) 6183 return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT); 6184 } 6185 6186 // If the input is a constant, let getNode fold it. 6187 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) { 6188 SDValue Res = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0); 6189 if (Res.getNode() != N) { 6190 if (!LegalOperations || 6191 TLI.isOperationLegal(Res.getNode()->getOpcode(), VT)) 6192 return Res; 6193 6194 // Folding it resulted in an illegal node, and it's too late to 6195 // do that. Clean up the old node and forego the transformation. 6196 // Ideally this won't happen very often, because instcombine 6197 // and the earlier dagcombine runs (where illegal nodes are 6198 // permitted) should have folded most of them already. 6199 DAG.DeleteNode(Res.getNode()); 6200 } 6201 } 6202 6203 // (conv (conv x, t1), t2) -> (conv x, t2) 6204 if (N0.getOpcode() == ISD::BITCAST) 6205 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, 6206 N0.getOperand(0)); 6207 6208 // fold (conv (load x)) -> (load (conv*)x) 6209 // If the resultant load doesn't need a higher alignment than the original! 6210 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() && 6211 // Do not change the width of a volatile load. 6212 !cast<LoadSDNode>(N0)->isVolatile() && 6213 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) && 6214 TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) { 6215 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6216 unsigned Align = TLI.getDataLayout()-> 6217 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext())); 6218 unsigned OrigAlign = LN0->getAlignment(); 6219 6220 if (Align <= OrigAlign) { 6221 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(), 6222 LN0->getBasePtr(), LN0->getPointerInfo(), 6223 LN0->isVolatile(), LN0->isNonTemporal(), 6224 LN0->isInvariant(), OrigAlign, 6225 LN0->getTBAAInfo()); 6226 AddToWorkList(N); 6227 CombineTo(N0.getNode(), 6228 DAG.getNode(ISD::BITCAST, SDLoc(N0), 6229 N0.getValueType(), Load), 6230 Load.getValue(1)); 6231 return Load; 6232 } 6233 } 6234 6235 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit) 6236 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit)) 6237 // This often reduces constant pool loads. 6238 if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) || 6239 (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) && 6240 N0.getNode()->hasOneUse() && VT.isInteger() && 6241 !VT.isVector() && !N0.getValueType().isVector()) { 6242 SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT, 6243 N0.getOperand(0)); 6244 AddToWorkList(NewConv.getNode()); 6245 6246 APInt SignBit = APInt::getSignBit(VT.getSizeInBits()); 6247 if (N0.getOpcode() == ISD::FNEG) 6248 return DAG.getNode(ISD::XOR, SDLoc(N), VT, 6249 NewConv, DAG.getConstant(SignBit, VT)); 6250 assert(N0.getOpcode() == ISD::FABS); 6251 return DAG.getNode(ISD::AND, SDLoc(N), VT, 6252 NewConv, DAG.getConstant(~SignBit, VT)); 6253 } 6254 6255 // fold (bitconvert (fcopysign cst, x)) -> 6256 // (or (and (bitconvert x), sign), (and cst, (not sign))) 6257 // Note that we don't handle (copysign x, cst) because this can always be 6258 // folded to an fneg or fabs. 6259 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() && 6260 isa<ConstantFPSDNode>(N0.getOperand(0)) && 6261 VT.isInteger() && !VT.isVector()) { 6262 unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits(); 6263 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth); 6264 if (isTypeLegal(IntXVT)) { 6265 SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0), 6266 IntXVT, N0.getOperand(1)); 6267 AddToWorkList(X.getNode()); 6268 6269 // If X has a different width than the result/lhs, sext it or truncate it. 6270 unsigned VTWidth = VT.getSizeInBits(); 6271 if (OrigXWidth < VTWidth) { 6272 X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X); 6273 AddToWorkList(X.getNode()); 6274 } else if (OrigXWidth > VTWidth) { 6275 // To get the sign bit in the right place, we have to shift it right 6276 // before truncating. 6277 X = DAG.getNode(ISD::SRL, SDLoc(X), 6278 X.getValueType(), X, 6279 DAG.getConstant(OrigXWidth-VTWidth, X.getValueType())); 6280 AddToWorkList(X.getNode()); 6281 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X); 6282 AddToWorkList(X.getNode()); 6283 } 6284 6285 APInt SignBit = APInt::getSignBit(VT.getSizeInBits()); 6286 X = DAG.getNode(ISD::AND, SDLoc(X), VT, 6287 X, DAG.getConstant(SignBit, VT)); 6288 AddToWorkList(X.getNode()); 6289 6290 SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0), 6291 VT, N0.getOperand(0)); 6292 Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT, 6293 Cst, DAG.getConstant(~SignBit, VT)); 6294 AddToWorkList(Cst.getNode()); 6295 6296 return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst); 6297 } 6298 } 6299 6300 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive. 6301 if (N0.getOpcode() == ISD::BUILD_PAIR) { 6302 SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT); 6303 if (CombineLD.getNode()) 6304 return CombineLD; 6305 } 6306 6307 return SDValue(); 6308 } 6309 6310 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) { 6311 EVT VT = N->getValueType(0); 6312 return CombineConsecutiveLoads(N, VT); 6313 } 6314 6315 /// ConstantFoldBITCASTofBUILD_VECTOR - We know that BV is a build_vector 6316 /// node with Constant, ConstantFP or Undef operands. DstEltVT indicates the 6317 /// destination element value type. 6318 SDValue DAGCombiner:: 6319 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) { 6320 EVT SrcEltVT = BV->getValueType(0).getVectorElementType(); 6321 6322 // If this is already the right type, we're done. 6323 if (SrcEltVT == DstEltVT) return SDValue(BV, 0); 6324 6325 unsigned SrcBitSize = SrcEltVT.getSizeInBits(); 6326 unsigned DstBitSize = DstEltVT.getSizeInBits(); 6327 6328 // If this is a conversion of N elements of one type to N elements of another 6329 // type, convert each element. This handles FP<->INT cases. 6330 if (SrcBitSize == DstBitSize) { 6331 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, 6332 BV->getValueType(0).getVectorNumElements()); 6333 6334 // Due to the FP element handling below calling this routine recursively, 6335 // we can end up with a scalar-to-vector node here. 6336 if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR) 6337 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT, 6338 DAG.getNode(ISD::BITCAST, SDLoc(BV), 6339 DstEltVT, BV->getOperand(0))); 6340 6341 SmallVector<SDValue, 8> Ops; 6342 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) { 6343 SDValue Op = BV->getOperand(i); 6344 // If the vector element type is not legal, the BUILD_VECTOR operands 6345 // are promoted and implicitly truncated. Make that explicit here. 6346 if (Op.getValueType() != SrcEltVT) 6347 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op); 6348 Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV), 6349 DstEltVT, Op)); 6350 AddToWorkList(Ops.back().getNode()); 6351 } 6352 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops); 6353 } 6354 6355 // Otherwise, we're growing or shrinking the elements. To avoid having to 6356 // handle annoying details of growing/shrinking FP values, we convert them to 6357 // int first. 6358 if (SrcEltVT.isFloatingPoint()) { 6359 // Convert the input float vector to a int vector where the elements are the 6360 // same sizes. 6361 assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!"); 6362 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits()); 6363 BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode(); 6364 SrcEltVT = IntVT; 6365 } 6366 6367 // Now we know the input is an integer vector. If the output is a FP type, 6368 // convert to integer first, then to FP of the right size. 6369 if (DstEltVT.isFloatingPoint()) { 6370 assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!"); 6371 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits()); 6372 SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode(); 6373 6374 // Next, convert to FP elements of the same size. 6375 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT); 6376 } 6377 6378 // Okay, we know the src/dst types are both integers of differing types. 6379 // Handling growing first. 6380 assert(SrcEltVT.isInteger() && DstEltVT.isInteger()); 6381 if (SrcBitSize < DstBitSize) { 6382 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize; 6383 6384 SmallVector<SDValue, 8> Ops; 6385 for (unsigned i = 0, e = BV->getNumOperands(); i != e; 6386 i += NumInputsPerOutput) { 6387 bool isLE = TLI.isLittleEndian(); 6388 APInt NewBits = APInt(DstBitSize, 0); 6389 bool EltIsUndef = true; 6390 for (unsigned j = 0; j != NumInputsPerOutput; ++j) { 6391 // Shift the previously computed bits over. 6392 NewBits <<= SrcBitSize; 6393 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j)); 6394 if (Op.getOpcode() == ISD::UNDEF) continue; 6395 EltIsUndef = false; 6396 6397 NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue(). 6398 zextOrTrunc(SrcBitSize).zext(DstBitSize); 6399 } 6400 6401 if (EltIsUndef) 6402 Ops.push_back(DAG.getUNDEF(DstEltVT)); 6403 else 6404 Ops.push_back(DAG.getConstant(NewBits, DstEltVT)); 6405 } 6406 6407 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size()); 6408 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops); 6409 } 6410 6411 // Finally, this must be the case where we are shrinking elements: each input 6412 // turns into multiple outputs. 6413 bool isS2V = ISD::isScalarToVector(BV); 6414 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize; 6415 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, 6416 NumOutputsPerInput*BV->getNumOperands()); 6417 SmallVector<SDValue, 8> Ops; 6418 6419 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) { 6420 if (BV->getOperand(i).getOpcode() == ISD::UNDEF) { 6421 for (unsigned j = 0; j != NumOutputsPerInput; ++j) 6422 Ops.push_back(DAG.getUNDEF(DstEltVT)); 6423 continue; 6424 } 6425 6426 APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))-> 6427 getAPIntValue().zextOrTrunc(SrcBitSize); 6428 6429 for (unsigned j = 0; j != NumOutputsPerInput; ++j) { 6430 APInt ThisVal = OpVal.trunc(DstBitSize); 6431 Ops.push_back(DAG.getConstant(ThisVal, DstEltVT)); 6432 if (isS2V && i == 0 && j == 0 && ThisVal.zext(SrcBitSize) == OpVal) 6433 // Simply turn this into a SCALAR_TO_VECTOR of the new type. 6434 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT, 6435 Ops[0]); 6436 OpVal = OpVal.lshr(DstBitSize); 6437 } 6438 6439 // For big endian targets, swap the order of the pieces of each element. 6440 if (TLI.isBigEndian()) 6441 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end()); 6442 } 6443 6444 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops); 6445 } 6446 6447 SDValue DAGCombiner::visitFADD(SDNode *N) { 6448 SDValue N0 = N->getOperand(0); 6449 SDValue N1 = N->getOperand(1); 6450 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 6451 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 6452 EVT VT = N->getValueType(0); 6453 6454 // fold vector ops 6455 if (VT.isVector()) { 6456 SDValue FoldedVOp = SimplifyVBinOp(N); 6457 if (FoldedVOp.getNode()) return FoldedVOp; 6458 } 6459 6460 // fold (fadd c1, c2) -> c1 + c2 6461 if (N0CFP && N1CFP) 6462 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N1); 6463 // canonicalize constant to RHS 6464 if (N0CFP && !N1CFP) 6465 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N0); 6466 // fold (fadd A, 0) -> A 6467 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP && 6468 N1CFP->getValueAPF().isZero()) 6469 return N0; 6470 // fold (fadd A, (fneg B)) -> (fsub A, B) 6471 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) && 6472 isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options) == 2) 6473 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0, 6474 GetNegatedExpression(N1, DAG, LegalOperations)); 6475 // fold (fadd (fneg A), B) -> (fsub B, A) 6476 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) && 6477 isNegatibleForFree(N0, LegalOperations, TLI, &DAG.getTarget().Options) == 2) 6478 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N1, 6479 GetNegatedExpression(N0, DAG, LegalOperations)); 6480 6481 // If allowed, fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2)) 6482 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP && 6483 N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() && 6484 isa<ConstantFPSDNode>(N0.getOperand(1))) 6485 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0.getOperand(0), 6486 DAG.getNode(ISD::FADD, SDLoc(N), VT, 6487 N0.getOperand(1), N1)); 6488 6489 // No FP constant should be created after legalization as Instruction 6490 // Selection pass has hard time in dealing with FP constant. 6491 // 6492 // We don't need test this condition for transformation like following, as 6493 // the DAG being transformed implies it is legal to take FP constant as 6494 // operand. 6495 // 6496 // (fadd (fmul c, x), x) -> (fmul c+1, x) 6497 // 6498 bool AllowNewFpConst = (Level < AfterLegalizeDAG); 6499 6500 // If allow, fold (fadd (fneg x), x) -> 0.0 6501 if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath && 6502 N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1) 6503 return DAG.getConstantFP(0.0, VT); 6504 6505 // If allow, fold (fadd x, (fneg x)) -> 0.0 6506 if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath && 6507 N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0) 6508 return DAG.getConstantFP(0.0, VT); 6509 6510 // In unsafe math mode, we can fold chains of FADD's of the same value 6511 // into multiplications. This transform is not safe in general because 6512 // we are reducing the number of rounding steps. 6513 if (DAG.getTarget().Options.UnsafeFPMath && 6514 TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && 6515 !N0CFP && !N1CFP) { 6516 if (N0.getOpcode() == ISD::FMUL) { 6517 ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0)); 6518 ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1)); 6519 6520 // (fadd (fmul c, x), x) -> (fmul x, c+1) 6521 if (CFP00 && !CFP01 && N0.getOperand(1) == N1) { 6522 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT, 6523 SDValue(CFP00, 0), 6524 DAG.getConstantFP(1.0, VT)); 6525 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, 6526 N1, NewCFP); 6527 } 6528 6529 // (fadd (fmul x, c), x) -> (fmul x, c+1) 6530 if (CFP01 && !CFP00 && N0.getOperand(0) == N1) { 6531 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT, 6532 SDValue(CFP01, 0), 6533 DAG.getConstantFP(1.0, VT)); 6534 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, 6535 N1, NewCFP); 6536 } 6537 6538 // (fadd (fmul c, x), (fadd x, x)) -> (fmul x, c+2) 6539 if (CFP00 && !CFP01 && N1.getOpcode() == ISD::FADD && 6540 N1.getOperand(0) == N1.getOperand(1) && 6541 N0.getOperand(1) == N1.getOperand(0)) { 6542 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT, 6543 SDValue(CFP00, 0), 6544 DAG.getConstantFP(2.0, VT)); 6545 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, 6546 N0.getOperand(1), NewCFP); 6547 } 6548 6549 // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2) 6550 if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD && 6551 N1.getOperand(0) == N1.getOperand(1) && 6552 N0.getOperand(0) == N1.getOperand(0)) { 6553 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT, 6554 SDValue(CFP01, 0), 6555 DAG.getConstantFP(2.0, VT)); 6556 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, 6557 N0.getOperand(0), NewCFP); 6558 } 6559 } 6560 6561 if (N1.getOpcode() == ISD::FMUL) { 6562 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0)); 6563 ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1)); 6564 6565 // (fadd x, (fmul c, x)) -> (fmul x, c+1) 6566 if (CFP10 && !CFP11 && N1.getOperand(1) == N0) { 6567 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT, 6568 SDValue(CFP10, 0), 6569 DAG.getConstantFP(1.0, VT)); 6570 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, 6571 N0, NewCFP); 6572 } 6573 6574 // (fadd x, (fmul x, c)) -> (fmul x, c+1) 6575 if (CFP11 && !CFP10 && N1.getOperand(0) == N0) { 6576 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT, 6577 SDValue(CFP11, 0), 6578 DAG.getConstantFP(1.0, VT)); 6579 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, 6580 N0, NewCFP); 6581 } 6582 6583 6584 // (fadd (fadd x, x), (fmul c, x)) -> (fmul x, c+2) 6585 if (CFP10 && !CFP11 && N0.getOpcode() == ISD::FADD && 6586 N0.getOperand(0) == N0.getOperand(1) && 6587 N1.getOperand(1) == N0.getOperand(0)) { 6588 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT, 6589 SDValue(CFP10, 0), 6590 DAG.getConstantFP(2.0, VT)); 6591 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, 6592 N1.getOperand(1), NewCFP); 6593 } 6594 6595 // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2) 6596 if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD && 6597 N0.getOperand(0) == N0.getOperand(1) && 6598 N1.getOperand(0) == N0.getOperand(0)) { 6599 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT, 6600 SDValue(CFP11, 0), 6601 DAG.getConstantFP(2.0, VT)); 6602 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, 6603 N1.getOperand(0), NewCFP); 6604 } 6605 } 6606 6607 if (N0.getOpcode() == ISD::FADD && AllowNewFpConst) { 6608 ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0)); 6609 // (fadd (fadd x, x), x) -> (fmul x, 3.0) 6610 if (!CFP && N0.getOperand(0) == N0.getOperand(1) && 6611 (N0.getOperand(0) == N1)) 6612 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, 6613 N1, DAG.getConstantFP(3.0, VT)); 6614 } 6615 6616 if (N1.getOpcode() == ISD::FADD && AllowNewFpConst) { 6617 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0)); 6618 // (fadd x, (fadd x, x)) -> (fmul x, 3.0) 6619 if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) && 6620 N1.getOperand(0) == N0) 6621 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, 6622 N0, DAG.getConstantFP(3.0, VT)); 6623 } 6624 6625 // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0) 6626 if (AllowNewFpConst && 6627 N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD && 6628 N0.getOperand(0) == N0.getOperand(1) && 6629 N1.getOperand(0) == N1.getOperand(1) && 6630 N0.getOperand(0) == N1.getOperand(0)) 6631 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, 6632 N0.getOperand(0), 6633 DAG.getConstantFP(4.0, VT)); 6634 } 6635 6636 // FADD -> FMA combines: 6637 if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast || 6638 DAG.getTarget().Options.UnsafeFPMath) && 6639 DAG.getTarget().getTargetLowering()->isFMAFasterThanFMulAndFAdd(VT) && 6640 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) { 6641 6642 // fold (fadd (fmul x, y), z) -> (fma x, y, z) 6643 if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse()) 6644 return DAG.getNode(ISD::FMA, SDLoc(N), VT, 6645 N0.getOperand(0), N0.getOperand(1), N1); 6646 6647 // fold (fadd x, (fmul y, z)) -> (fma y, z, x) 6648 // Note: Commutes FADD operands. 6649 if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse()) 6650 return DAG.getNode(ISD::FMA, SDLoc(N), VT, 6651 N1.getOperand(0), N1.getOperand(1), N0); 6652 } 6653 6654 return SDValue(); 6655 } 6656 6657 SDValue DAGCombiner::visitFSUB(SDNode *N) { 6658 SDValue N0 = N->getOperand(0); 6659 SDValue N1 = N->getOperand(1); 6660 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 6661 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 6662 EVT VT = N->getValueType(0); 6663 SDLoc dl(N); 6664 6665 // fold vector ops 6666 if (VT.isVector()) { 6667 SDValue FoldedVOp = SimplifyVBinOp(N); 6668 if (FoldedVOp.getNode()) return FoldedVOp; 6669 } 6670 6671 // fold (fsub c1, c2) -> c1-c2 6672 if (N0CFP && N1CFP) 6673 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0, N1); 6674 // fold (fsub A, 0) -> A 6675 if (DAG.getTarget().Options.UnsafeFPMath && 6676 N1CFP && N1CFP->getValueAPF().isZero()) 6677 return N0; 6678 // fold (fsub 0, B) -> -B 6679 if (DAG.getTarget().Options.UnsafeFPMath && 6680 N0CFP && N0CFP->getValueAPF().isZero()) { 6681 if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options)) 6682 return GetNegatedExpression(N1, DAG, LegalOperations); 6683 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT)) 6684 return DAG.getNode(ISD::FNEG, dl, VT, N1); 6685 } 6686 // fold (fsub A, (fneg B)) -> (fadd A, B) 6687 if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options)) 6688 return DAG.getNode(ISD::FADD, dl, VT, N0, 6689 GetNegatedExpression(N1, DAG, LegalOperations)); 6690 6691 // If 'unsafe math' is enabled, fold 6692 // (fsub x, x) -> 0.0 & 6693 // (fsub x, (fadd x, y)) -> (fneg y) & 6694 // (fsub x, (fadd y, x)) -> (fneg y) 6695 if (DAG.getTarget().Options.UnsafeFPMath) { 6696 if (N0 == N1) 6697 return DAG.getConstantFP(0.0f, VT); 6698 6699 if (N1.getOpcode() == ISD::FADD) { 6700 SDValue N10 = N1->getOperand(0); 6701 SDValue N11 = N1->getOperand(1); 6702 6703 if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, 6704 &DAG.getTarget().Options)) 6705 return GetNegatedExpression(N11, DAG, LegalOperations); 6706 6707 if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, 6708 &DAG.getTarget().Options)) 6709 return GetNegatedExpression(N10, DAG, LegalOperations); 6710 } 6711 } 6712 6713 // FSUB -> FMA combines: 6714 if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast || 6715 DAG.getTarget().Options.UnsafeFPMath) && 6716 DAG.getTarget().getTargetLowering()->isFMAFasterThanFMulAndFAdd(VT) && 6717 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) { 6718 6719 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z)) 6720 if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse()) 6721 return DAG.getNode(ISD::FMA, dl, VT, 6722 N0.getOperand(0), N0.getOperand(1), 6723 DAG.getNode(ISD::FNEG, dl, VT, N1)); 6724 6725 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x) 6726 // Note: Commutes FSUB operands. 6727 if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse()) 6728 return DAG.getNode(ISD::FMA, dl, VT, 6729 DAG.getNode(ISD::FNEG, dl, VT, 6730 N1.getOperand(0)), 6731 N1.getOperand(1), N0); 6732 6733 // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z)) 6734 if (N0.getOpcode() == ISD::FNEG && 6735 N0.getOperand(0).getOpcode() == ISD::FMUL && 6736 N0->hasOneUse() && N0.getOperand(0).hasOneUse()) { 6737 SDValue N00 = N0.getOperand(0).getOperand(0); 6738 SDValue N01 = N0.getOperand(0).getOperand(1); 6739 return DAG.getNode(ISD::FMA, dl, VT, 6740 DAG.getNode(ISD::FNEG, dl, VT, N00), N01, 6741 DAG.getNode(ISD::FNEG, dl, VT, N1)); 6742 } 6743 } 6744 6745 return SDValue(); 6746 } 6747 6748 SDValue DAGCombiner::visitFMUL(SDNode *N) { 6749 SDValue N0 = N->getOperand(0); 6750 SDValue N1 = N->getOperand(1); 6751 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 6752 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 6753 EVT VT = N->getValueType(0); 6754 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6755 6756 // fold vector ops 6757 if (VT.isVector()) { 6758 SDValue FoldedVOp = SimplifyVBinOp(N); 6759 if (FoldedVOp.getNode()) return FoldedVOp; 6760 } 6761 6762 // fold (fmul c1, c2) -> c1*c2 6763 if (N0CFP && N1CFP) 6764 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, N1); 6765 // canonicalize constant to RHS 6766 if (N0CFP && !N1CFP) 6767 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, N0); 6768 // fold (fmul A, 0) -> 0 6769 if (DAG.getTarget().Options.UnsafeFPMath && 6770 N1CFP && N1CFP->getValueAPF().isZero()) 6771 return N1; 6772 // fold (fmul A, 0) -> 0, vector edition. 6773 if (DAG.getTarget().Options.UnsafeFPMath && 6774 ISD::isBuildVectorAllZeros(N1.getNode())) 6775 return N1; 6776 // fold (fmul A, 1.0) -> A 6777 if (N1CFP && N1CFP->isExactlyValue(1.0)) 6778 return N0; 6779 // fold (fmul X, 2.0) -> (fadd X, X) 6780 if (N1CFP && N1CFP->isExactlyValue(+2.0)) 6781 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N0); 6782 // fold (fmul X, -1.0) -> (fneg X) 6783 if (N1CFP && N1CFP->isExactlyValue(-1.0)) 6784 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT)) 6785 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0); 6786 6787 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y) 6788 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, 6789 &DAG.getTarget().Options)) { 6790 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, 6791 &DAG.getTarget().Options)) { 6792 // Both can be negated for free, check to see if at least one is cheaper 6793 // negated. 6794 if (LHSNeg == 2 || RHSNeg == 2) 6795 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, 6796 GetNegatedExpression(N0, DAG, LegalOperations), 6797 GetNegatedExpression(N1, DAG, LegalOperations)); 6798 } 6799 } 6800 6801 // If allowed, fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2)) 6802 if (DAG.getTarget().Options.UnsafeFPMath && 6803 N1CFP && N0.getOpcode() == ISD::FMUL && 6804 N0.getNode()->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1))) 6805 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0), 6806 DAG.getNode(ISD::FMUL, SDLoc(N), VT, 6807 N0.getOperand(1), N1)); 6808 6809 return SDValue(); 6810 } 6811 6812 SDValue DAGCombiner::visitFMA(SDNode *N) { 6813 SDValue N0 = N->getOperand(0); 6814 SDValue N1 = N->getOperand(1); 6815 SDValue N2 = N->getOperand(2); 6816 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 6817 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 6818 EVT VT = N->getValueType(0); 6819 SDLoc dl(N); 6820 6821 if (DAG.getTarget().Options.UnsafeFPMath) { 6822 if (N0CFP && N0CFP->isZero()) 6823 return N2; 6824 if (N1CFP && N1CFP->isZero()) 6825 return N2; 6826 } 6827 if (N0CFP && N0CFP->isExactlyValue(1.0)) 6828 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2); 6829 if (N1CFP && N1CFP->isExactlyValue(1.0)) 6830 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2); 6831 6832 // Canonicalize (fma c, x, y) -> (fma x, c, y) 6833 if (N0CFP && !N1CFP) 6834 return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2); 6835 6836 // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2) 6837 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP && 6838 N2.getOpcode() == ISD::FMUL && 6839 N0 == N2.getOperand(0) && 6840 N2.getOperand(1).getOpcode() == ISD::ConstantFP) { 6841 return DAG.getNode(ISD::FMUL, dl, VT, N0, 6842 DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1))); 6843 } 6844 6845 6846 // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y) 6847 if (DAG.getTarget().Options.UnsafeFPMath && 6848 N0.getOpcode() == ISD::FMUL && N1CFP && 6849 N0.getOperand(1).getOpcode() == ISD::ConstantFP) { 6850 return DAG.getNode(ISD::FMA, dl, VT, 6851 N0.getOperand(0), 6852 DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)), 6853 N2); 6854 } 6855 6856 // (fma x, 1, y) -> (fadd x, y) 6857 // (fma x, -1, y) -> (fadd (fneg x), y) 6858 if (N1CFP) { 6859 if (N1CFP->isExactlyValue(1.0)) 6860 return DAG.getNode(ISD::FADD, dl, VT, N0, N2); 6861 6862 if (N1CFP->isExactlyValue(-1.0) && 6863 (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) { 6864 SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0); 6865 AddToWorkList(RHSNeg.getNode()); 6866 return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg); 6867 } 6868 } 6869 6870 // (fma x, c, x) -> (fmul x, (c+1)) 6871 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP && N0 == N2) 6872 return DAG.getNode(ISD::FMUL, dl, VT, N0, 6873 DAG.getNode(ISD::FADD, dl, VT, 6874 N1, DAG.getConstantFP(1.0, VT))); 6875 6876 // (fma x, c, (fneg x)) -> (fmul x, (c-1)) 6877 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP && 6878 N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0) 6879 return DAG.getNode(ISD::FMUL, dl, VT, N0, 6880 DAG.getNode(ISD::FADD, dl, VT, 6881 N1, DAG.getConstantFP(-1.0, VT))); 6882 6883 6884 return SDValue(); 6885 } 6886 6887 SDValue DAGCombiner::visitFDIV(SDNode *N) { 6888 SDValue N0 = N->getOperand(0); 6889 SDValue N1 = N->getOperand(1); 6890 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 6891 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 6892 EVT VT = N->getValueType(0); 6893 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6894 6895 // fold vector ops 6896 if (VT.isVector()) { 6897 SDValue FoldedVOp = SimplifyVBinOp(N); 6898 if (FoldedVOp.getNode()) return FoldedVOp; 6899 } 6900 6901 // fold (fdiv c1, c2) -> c1/c2 6902 if (N0CFP && N1CFP) 6903 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1); 6904 6905 // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable. 6906 if (N1CFP && DAG.getTarget().Options.UnsafeFPMath) { 6907 // Compute the reciprocal 1.0 / c2. 6908 APFloat N1APF = N1CFP->getValueAPF(); 6909 APFloat Recip(N1APF.getSemantics(), 1); // 1.0 6910 APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven); 6911 // Only do the transform if the reciprocal is a legal fp immediate that 6912 // isn't too nasty (eg NaN, denormal, ...). 6913 if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty 6914 (!LegalOperations || 6915 // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM 6916 // backend)... we should handle this gracefully after Legalize. 6917 // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) || 6918 TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) || 6919 TLI.isFPImmLegal(Recip, VT))) 6920 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, 6921 DAG.getConstantFP(Recip, VT)); 6922 } 6923 6924 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y) 6925 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, 6926 &DAG.getTarget().Options)) { 6927 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, 6928 &DAG.getTarget().Options)) { 6929 // Both can be negated for free, check to see if at least one is cheaper 6930 // negated. 6931 if (LHSNeg == 2 || RHSNeg == 2) 6932 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, 6933 GetNegatedExpression(N0, DAG, LegalOperations), 6934 GetNegatedExpression(N1, DAG, LegalOperations)); 6935 } 6936 } 6937 6938 return SDValue(); 6939 } 6940 6941 SDValue DAGCombiner::visitFREM(SDNode *N) { 6942 SDValue N0 = N->getOperand(0); 6943 SDValue N1 = N->getOperand(1); 6944 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 6945 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 6946 EVT VT = N->getValueType(0); 6947 6948 // fold (frem c1, c2) -> fmod(c1,c2) 6949 if (N0CFP && N1CFP) 6950 return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1); 6951 6952 return SDValue(); 6953 } 6954 6955 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) { 6956 SDValue N0 = N->getOperand(0); 6957 SDValue N1 = N->getOperand(1); 6958 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 6959 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 6960 EVT VT = N->getValueType(0); 6961 6962 if (N0CFP && N1CFP) // Constant fold 6963 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1); 6964 6965 if (N1CFP) { 6966 const APFloat& V = N1CFP->getValueAPF(); 6967 // copysign(x, c1) -> fabs(x) iff ispos(c1) 6968 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1) 6969 if (!V.isNegative()) { 6970 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT)) 6971 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0); 6972 } else { 6973 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT)) 6974 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, 6975 DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0)); 6976 } 6977 } 6978 6979 // copysign(fabs(x), y) -> copysign(x, y) 6980 // copysign(fneg(x), y) -> copysign(x, y) 6981 // copysign(copysign(x,z), y) -> copysign(x, y) 6982 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG || 6983 N0.getOpcode() == ISD::FCOPYSIGN) 6984 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, 6985 N0.getOperand(0), N1); 6986 6987 // copysign(x, abs(y)) -> abs(x) 6988 if (N1.getOpcode() == ISD::FABS) 6989 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0); 6990 6991 // copysign(x, copysign(y,z)) -> copysign(x, z) 6992 if (N1.getOpcode() == ISD::FCOPYSIGN) 6993 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, 6994 N0, N1.getOperand(1)); 6995 6996 // copysign(x, fp_extend(y)) -> copysign(x, y) 6997 // copysign(x, fp_round(y)) -> copysign(x, y) 6998 if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND) 6999 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, 7000 N0, N1.getOperand(0)); 7001 7002 return SDValue(); 7003 } 7004 7005 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) { 7006 SDValue N0 = N->getOperand(0); 7007 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 7008 EVT VT = N->getValueType(0); 7009 EVT OpVT = N0.getValueType(); 7010 7011 // fold (sint_to_fp c1) -> c1fp 7012 if (N0C && 7013 // ...but only if the target supports immediate floating-point values 7014 (!LegalOperations || 7015 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) 7016 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0); 7017 7018 // If the input is a legal type, and SINT_TO_FP is not legal on this target, 7019 // but UINT_TO_FP is legal on this target, try to convert. 7020 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) && 7021 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) { 7022 // If the sign bit is known to be zero, we can change this to UINT_TO_FP. 7023 if (DAG.SignBitIsZero(N0)) 7024 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0); 7025 } 7026 7027 // The next optimizations are desirable only if SELECT_CC can be lowered. 7028 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) { 7029 // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc) 7030 if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 && 7031 !VT.isVector() && 7032 (!LegalOperations || 7033 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) { 7034 SDValue Ops[] = 7035 { N0.getOperand(0), N0.getOperand(1), 7036 DAG.getConstantFP(-1.0, VT) , DAG.getConstantFP(0.0, VT), 7037 N0.getOperand(2) }; 7038 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops); 7039 } 7040 7041 // fold (sint_to_fp (zext (setcc x, y, cc))) -> 7042 // (select_cc x, y, 1.0, 0.0,, cc) 7043 if (N0.getOpcode() == ISD::ZERO_EXTEND && 7044 N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() && 7045 (!LegalOperations || 7046 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) { 7047 SDValue Ops[] = 7048 { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1), 7049 DAG.getConstantFP(1.0, VT) , DAG.getConstantFP(0.0, VT), 7050 N0.getOperand(0).getOperand(2) }; 7051 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops); 7052 } 7053 } 7054 7055 return SDValue(); 7056 } 7057 7058 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) { 7059 SDValue N0 = N->getOperand(0); 7060 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 7061 EVT VT = N->getValueType(0); 7062 EVT OpVT = N0.getValueType(); 7063 7064 // fold (uint_to_fp c1) -> c1fp 7065 if (N0C && 7066 // ...but only if the target supports immediate floating-point values 7067 (!LegalOperations || 7068 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) 7069 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0); 7070 7071 // If the input is a legal type, and UINT_TO_FP is not legal on this target, 7072 // but SINT_TO_FP is legal on this target, try to convert. 7073 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) && 7074 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) { 7075 // If the sign bit is known to be zero, we can change this to SINT_TO_FP. 7076 if (DAG.SignBitIsZero(N0)) 7077 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0); 7078 } 7079 7080 // The next optimizations are desirable only if SELECT_CC can be lowered. 7081 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) { 7082 // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc) 7083 7084 if (N0.getOpcode() == ISD::SETCC && !VT.isVector() && 7085 (!LegalOperations || 7086 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) { 7087 SDValue Ops[] = 7088 { N0.getOperand(0), N0.getOperand(1), 7089 DAG.getConstantFP(1.0, VT), DAG.getConstantFP(0.0, VT), 7090 N0.getOperand(2) }; 7091 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops); 7092 } 7093 } 7094 7095 return SDValue(); 7096 } 7097 7098 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) { 7099 SDValue N0 = N->getOperand(0); 7100 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 7101 EVT VT = N->getValueType(0); 7102 7103 // fold (fp_to_sint c1fp) -> c1 7104 if (N0CFP) 7105 return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0); 7106 7107 return SDValue(); 7108 } 7109 7110 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) { 7111 SDValue N0 = N->getOperand(0); 7112 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 7113 EVT VT = N->getValueType(0); 7114 7115 // fold (fp_to_uint c1fp) -> c1 7116 if (N0CFP) 7117 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0); 7118 7119 return SDValue(); 7120 } 7121 7122 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) { 7123 SDValue N0 = N->getOperand(0); 7124 SDValue N1 = N->getOperand(1); 7125 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 7126 EVT VT = N->getValueType(0); 7127 7128 // fold (fp_round c1fp) -> c1fp 7129 if (N0CFP) 7130 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1); 7131 7132 // fold (fp_round (fp_extend x)) -> x 7133 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType()) 7134 return N0.getOperand(0); 7135 7136 // fold (fp_round (fp_round x)) -> (fp_round x) 7137 if (N0.getOpcode() == ISD::FP_ROUND) { 7138 // This is a value preserving truncation if both round's are. 7139 bool IsTrunc = N->getConstantOperandVal(1) == 1 && 7140 N0.getNode()->getConstantOperandVal(1) == 1; 7141 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0.getOperand(0), 7142 DAG.getIntPtrConstant(IsTrunc)); 7143 } 7144 7145 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y) 7146 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) { 7147 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT, 7148 N0.getOperand(0), N1); 7149 AddToWorkList(Tmp.getNode()); 7150 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, 7151 Tmp, N0.getOperand(1)); 7152 } 7153 7154 return SDValue(); 7155 } 7156 7157 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) { 7158 SDValue N0 = N->getOperand(0); 7159 EVT VT = N->getValueType(0); 7160 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT(); 7161 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 7162 7163 // fold (fp_round_inreg c1fp) -> c1fp 7164 if (N0CFP && isTypeLegal(EVT)) { 7165 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT); 7166 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, Round); 7167 } 7168 7169 return SDValue(); 7170 } 7171 7172 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) { 7173 SDValue N0 = N->getOperand(0); 7174 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 7175 EVT VT = N->getValueType(0); 7176 7177 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded. 7178 if (N->hasOneUse() && 7179 N->use_begin()->getOpcode() == ISD::FP_ROUND) 7180 return SDValue(); 7181 7182 // fold (fp_extend c1fp) -> c1fp 7183 if (N0CFP) 7184 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0); 7185 7186 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the 7187 // value of X. 7188 if (N0.getOpcode() == ISD::FP_ROUND 7189 && N0.getNode()->getConstantOperandVal(1) == 1) { 7190 SDValue In = N0.getOperand(0); 7191 if (In.getValueType() == VT) return In; 7192 if (VT.bitsLT(In.getValueType())) 7193 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, 7194 In, N0.getOperand(1)); 7195 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In); 7196 } 7197 7198 // fold (fpext (load x)) -> (fpext (fptrunc (extload x))) 7199 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() && 7200 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) || 7201 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) { 7202 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 7203 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT, 7204 LN0->getChain(), 7205 LN0->getBasePtr(), N0.getValueType(), 7206 LN0->getMemOperand()); 7207 CombineTo(N, ExtLoad); 7208 CombineTo(N0.getNode(), 7209 DAG.getNode(ISD::FP_ROUND, SDLoc(N0), 7210 N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)), 7211 ExtLoad.getValue(1)); 7212 return SDValue(N, 0); // Return N so it doesn't get rechecked! 7213 } 7214 7215 return SDValue(); 7216 } 7217 7218 SDValue DAGCombiner::visitFNEG(SDNode *N) { 7219 SDValue N0 = N->getOperand(0); 7220 EVT VT = N->getValueType(0); 7221 7222 if (VT.isVector()) { 7223 SDValue FoldedVOp = SimplifyVUnaryOp(N); 7224 if (FoldedVOp.getNode()) return FoldedVOp; 7225 } 7226 7227 if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(), 7228 &DAG.getTarget().Options)) 7229 return GetNegatedExpression(N0, DAG, LegalOperations); 7230 7231 // Transform fneg(bitconvert(x)) -> bitconvert(x^sign) to avoid loading 7232 // constant pool values. 7233 if (!TLI.isFNegFree(VT) && N0.getOpcode() == ISD::BITCAST && 7234 !VT.isVector() && 7235 N0.getNode()->hasOneUse() && 7236 N0.getOperand(0).getValueType().isInteger()) { 7237 SDValue Int = N0.getOperand(0); 7238 EVT IntVT = Int.getValueType(); 7239 if (IntVT.isInteger() && !IntVT.isVector()) { 7240 Int = DAG.getNode(ISD::XOR, SDLoc(N0), IntVT, Int, 7241 DAG.getConstant(APInt::getSignBit(IntVT.getSizeInBits()), IntVT)); 7242 AddToWorkList(Int.getNode()); 7243 return DAG.getNode(ISD::BITCAST, SDLoc(N), 7244 VT, Int); 7245 } 7246 } 7247 7248 // (fneg (fmul c, x)) -> (fmul -c, x) 7249 if (N0.getOpcode() == ISD::FMUL) { 7250 ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1)); 7251 if (CFP1) { 7252 APFloat CVal = CFP1->getValueAPF(); 7253 CVal.changeSign(); 7254 if (Level >= AfterLegalizeDAG && 7255 (TLI.isFPImmLegal(CVal, N->getValueType(0)) || 7256 TLI.isOperationLegal(ISD::ConstantFP, N->getValueType(0)))) 7257 return DAG.getNode( 7258 ISD::FMUL, SDLoc(N), VT, N0.getOperand(0), 7259 DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0.getOperand(1))); 7260 } 7261 } 7262 7263 return SDValue(); 7264 } 7265 7266 SDValue DAGCombiner::visitFCEIL(SDNode *N) { 7267 SDValue N0 = N->getOperand(0); 7268 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 7269 EVT VT = N->getValueType(0); 7270 7271 // fold (fceil c1) -> fceil(c1) 7272 if (N0CFP) 7273 return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0); 7274 7275 return SDValue(); 7276 } 7277 7278 SDValue DAGCombiner::visitFTRUNC(SDNode *N) { 7279 SDValue N0 = N->getOperand(0); 7280 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 7281 EVT VT = N->getValueType(0); 7282 7283 // fold (ftrunc c1) -> ftrunc(c1) 7284 if (N0CFP) 7285 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0); 7286 7287 return SDValue(); 7288 } 7289 7290 SDValue DAGCombiner::visitFFLOOR(SDNode *N) { 7291 SDValue N0 = N->getOperand(0); 7292 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 7293 EVT VT = N->getValueType(0); 7294 7295 // fold (ffloor c1) -> ffloor(c1) 7296 if (N0CFP) 7297 return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0); 7298 7299 return SDValue(); 7300 } 7301 7302 SDValue DAGCombiner::visitFABS(SDNode *N) { 7303 SDValue N0 = N->getOperand(0); 7304 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 7305 EVT VT = N->getValueType(0); 7306 7307 if (VT.isVector()) { 7308 SDValue FoldedVOp = SimplifyVUnaryOp(N); 7309 if (FoldedVOp.getNode()) return FoldedVOp; 7310 } 7311 7312 // fold (fabs c1) -> fabs(c1) 7313 if (N0CFP) 7314 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0); 7315 // fold (fabs (fabs x)) -> (fabs x) 7316 if (N0.getOpcode() == ISD::FABS) 7317 return N->getOperand(0); 7318 // fold (fabs (fneg x)) -> (fabs x) 7319 // fold (fabs (fcopysign x, y)) -> (fabs x) 7320 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN) 7321 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0)); 7322 7323 // Transform fabs(bitconvert(x)) -> bitconvert(x&~sign) to avoid loading 7324 // constant pool values. 7325 if (!TLI.isFAbsFree(VT) && 7326 N0.getOpcode() == ISD::BITCAST && N0.getNode()->hasOneUse() && 7327 N0.getOperand(0).getValueType().isInteger() && 7328 !N0.getOperand(0).getValueType().isVector()) { 7329 SDValue Int = N0.getOperand(0); 7330 EVT IntVT = Int.getValueType(); 7331 if (IntVT.isInteger() && !IntVT.isVector()) { 7332 Int = DAG.getNode(ISD::AND, SDLoc(N0), IntVT, Int, 7333 DAG.getConstant(~APInt::getSignBit(IntVT.getSizeInBits()), IntVT)); 7334 AddToWorkList(Int.getNode()); 7335 return DAG.getNode(ISD::BITCAST, SDLoc(N), 7336 N->getValueType(0), Int); 7337 } 7338 } 7339 7340 return SDValue(); 7341 } 7342 7343 SDValue DAGCombiner::visitBRCOND(SDNode *N) { 7344 SDValue Chain = N->getOperand(0); 7345 SDValue N1 = N->getOperand(1); 7346 SDValue N2 = N->getOperand(2); 7347 7348 // If N is a constant we could fold this into a fallthrough or unconditional 7349 // branch. However that doesn't happen very often in normal code, because 7350 // Instcombine/SimplifyCFG should have handled the available opportunities. 7351 // If we did this folding here, it would be necessary to update the 7352 // MachineBasicBlock CFG, which is awkward. 7353 7354 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal 7355 // on the target. 7356 if (N1.getOpcode() == ISD::SETCC && 7357 TLI.isOperationLegalOrCustom(ISD::BR_CC, 7358 N1.getOperand(0).getValueType())) { 7359 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other, 7360 Chain, N1.getOperand(2), 7361 N1.getOperand(0), N1.getOperand(1), N2); 7362 } 7363 7364 if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) || 7365 ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) && 7366 (N1.getOperand(0).hasOneUse() && 7367 N1.getOperand(0).getOpcode() == ISD::SRL))) { 7368 SDNode *Trunc = nullptr; 7369 if (N1.getOpcode() == ISD::TRUNCATE) { 7370 // Look pass the truncate. 7371 Trunc = N1.getNode(); 7372 N1 = N1.getOperand(0); 7373 } 7374 7375 // Match this pattern so that we can generate simpler code: 7376 // 7377 // %a = ... 7378 // %b = and i32 %a, 2 7379 // %c = srl i32 %b, 1 7380 // brcond i32 %c ... 7381 // 7382 // into 7383 // 7384 // %a = ... 7385 // %b = and i32 %a, 2 7386 // %c = setcc eq %b, 0 7387 // brcond %c ... 7388 // 7389 // This applies only when the AND constant value has one bit set and the 7390 // SRL constant is equal to the log2 of the AND constant. The back-end is 7391 // smart enough to convert the result into a TEST/JMP sequence. 7392 SDValue Op0 = N1.getOperand(0); 7393 SDValue Op1 = N1.getOperand(1); 7394 7395 if (Op0.getOpcode() == ISD::AND && 7396 Op1.getOpcode() == ISD::Constant) { 7397 SDValue AndOp1 = Op0.getOperand(1); 7398 7399 if (AndOp1.getOpcode() == ISD::Constant) { 7400 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue(); 7401 7402 if (AndConst.isPowerOf2() && 7403 cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) { 7404 SDValue SetCC = 7405 DAG.getSetCC(SDLoc(N), 7406 getSetCCResultType(Op0.getValueType()), 7407 Op0, DAG.getConstant(0, Op0.getValueType()), 7408 ISD::SETNE); 7409 7410 SDValue NewBRCond = DAG.getNode(ISD::BRCOND, SDLoc(N), 7411 MVT::Other, Chain, SetCC, N2); 7412 // Don't add the new BRCond into the worklist or else SimplifySelectCC 7413 // will convert it back to (X & C1) >> C2. 7414 CombineTo(N, NewBRCond, false); 7415 // Truncate is dead. 7416 if (Trunc) { 7417 removeFromWorkList(Trunc); 7418 DAG.DeleteNode(Trunc); 7419 } 7420 // Replace the uses of SRL with SETCC 7421 WorkListRemover DeadNodes(*this); 7422 DAG.ReplaceAllUsesOfValueWith(N1, SetCC); 7423 removeFromWorkList(N1.getNode()); 7424 DAG.DeleteNode(N1.getNode()); 7425 return SDValue(N, 0); // Return N so it doesn't get rechecked! 7426 } 7427 } 7428 } 7429 7430 if (Trunc) 7431 // Restore N1 if the above transformation doesn't match. 7432 N1 = N->getOperand(1); 7433 } 7434 7435 // Transform br(xor(x, y)) -> br(x != y) 7436 // Transform br(xor(xor(x,y), 1)) -> br (x == y) 7437 if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) { 7438 SDNode *TheXor = N1.getNode(); 7439 SDValue Op0 = TheXor->getOperand(0); 7440 SDValue Op1 = TheXor->getOperand(1); 7441 if (Op0.getOpcode() == Op1.getOpcode()) { 7442 // Avoid missing important xor optimizations. 7443 SDValue Tmp = visitXOR(TheXor); 7444 if (Tmp.getNode()) { 7445 if (Tmp.getNode() != TheXor) { 7446 DEBUG(dbgs() << "\nReplacing.8 "; 7447 TheXor->dump(&DAG); 7448 dbgs() << "\nWith: "; 7449 Tmp.getNode()->dump(&DAG); 7450 dbgs() << '\n'); 7451 WorkListRemover DeadNodes(*this); 7452 DAG.ReplaceAllUsesOfValueWith(N1, Tmp); 7453 removeFromWorkList(TheXor); 7454 DAG.DeleteNode(TheXor); 7455 return DAG.getNode(ISD::BRCOND, SDLoc(N), 7456 MVT::Other, Chain, Tmp, N2); 7457 } 7458 7459 // visitXOR has changed XOR's operands or replaced the XOR completely, 7460 // bail out. 7461 return SDValue(N, 0); 7462 } 7463 } 7464 7465 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) { 7466 bool Equal = false; 7467 if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0)) 7468 if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() && 7469 Op0.getOpcode() == ISD::XOR) { 7470 TheXor = Op0.getNode(); 7471 Equal = true; 7472 } 7473 7474 EVT SetCCVT = N1.getValueType(); 7475 if (LegalTypes) 7476 SetCCVT = getSetCCResultType(SetCCVT); 7477 SDValue SetCC = DAG.getSetCC(SDLoc(TheXor), 7478 SetCCVT, 7479 Op0, Op1, 7480 Equal ? ISD::SETEQ : ISD::SETNE); 7481 // Replace the uses of XOR with SETCC 7482 WorkListRemover DeadNodes(*this); 7483 DAG.ReplaceAllUsesOfValueWith(N1, SetCC); 7484 removeFromWorkList(N1.getNode()); 7485 DAG.DeleteNode(N1.getNode()); 7486 return DAG.getNode(ISD::BRCOND, SDLoc(N), 7487 MVT::Other, Chain, SetCC, N2); 7488 } 7489 } 7490 7491 return SDValue(); 7492 } 7493 7494 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB. 7495 // 7496 SDValue DAGCombiner::visitBR_CC(SDNode *N) { 7497 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1)); 7498 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3); 7499 7500 // If N is a constant we could fold this into a fallthrough or unconditional 7501 // branch. However that doesn't happen very often in normal code, because 7502 // Instcombine/SimplifyCFG should have handled the available opportunities. 7503 // If we did this folding here, it would be necessary to update the 7504 // MachineBasicBlock CFG, which is awkward. 7505 7506 // Use SimplifySetCC to simplify SETCC's. 7507 SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()), 7508 CondLHS, CondRHS, CC->get(), SDLoc(N), 7509 false); 7510 if (Simp.getNode()) AddToWorkList(Simp.getNode()); 7511 7512 // fold to a simpler setcc 7513 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC) 7514 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other, 7515 N->getOperand(0), Simp.getOperand(2), 7516 Simp.getOperand(0), Simp.getOperand(1), 7517 N->getOperand(4)); 7518 7519 return SDValue(); 7520 } 7521 7522 /// canFoldInAddressingMode - Return true if 'Use' is a load or a store that 7523 /// uses N as its base pointer and that N may be folded in the load / store 7524 /// addressing mode. 7525 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use, 7526 SelectionDAG &DAG, 7527 const TargetLowering &TLI) { 7528 EVT VT; 7529 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) { 7530 if (LD->isIndexed() || LD->getBasePtr().getNode() != N) 7531 return false; 7532 VT = Use->getValueType(0); 7533 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) { 7534 if (ST->isIndexed() || ST->getBasePtr().getNode() != N) 7535 return false; 7536 VT = ST->getValue().getValueType(); 7537 } else 7538 return false; 7539 7540 TargetLowering::AddrMode AM; 7541 if (N->getOpcode() == ISD::ADD) { 7542 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1)); 7543 if (Offset) 7544 // [reg +/- imm] 7545 AM.BaseOffs = Offset->getSExtValue(); 7546 else 7547 // [reg +/- reg] 7548 AM.Scale = 1; 7549 } else if (N->getOpcode() == ISD::SUB) { 7550 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1)); 7551 if (Offset) 7552 // [reg +/- imm] 7553 AM.BaseOffs = -Offset->getSExtValue(); 7554 else 7555 // [reg +/- reg] 7556 AM.Scale = 1; 7557 } else 7558 return false; 7559 7560 return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext())); 7561 } 7562 7563 /// CombineToPreIndexedLoadStore - Try turning a load / store into a 7564 /// pre-indexed load / store when the base pointer is an add or subtract 7565 /// and it has other uses besides the load / store. After the 7566 /// transformation, the new indexed load / store has effectively folded 7567 /// the add / subtract in and all of its other uses are redirected to the 7568 /// new load / store. 7569 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) { 7570 if (Level < AfterLegalizeDAG) 7571 return false; 7572 7573 bool isLoad = true; 7574 SDValue Ptr; 7575 EVT VT; 7576 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 7577 if (LD->isIndexed()) 7578 return false; 7579 VT = LD->getMemoryVT(); 7580 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) && 7581 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT)) 7582 return false; 7583 Ptr = LD->getBasePtr(); 7584 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 7585 if (ST->isIndexed()) 7586 return false; 7587 VT = ST->getMemoryVT(); 7588 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) && 7589 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT)) 7590 return false; 7591 Ptr = ST->getBasePtr(); 7592 isLoad = false; 7593 } else { 7594 return false; 7595 } 7596 7597 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail 7598 // out. There is no reason to make this a preinc/predec. 7599 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) || 7600 Ptr.getNode()->hasOneUse()) 7601 return false; 7602 7603 // Ask the target to do addressing mode selection. 7604 SDValue BasePtr; 7605 SDValue Offset; 7606 ISD::MemIndexedMode AM = ISD::UNINDEXED; 7607 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG)) 7608 return false; 7609 7610 // Backends without true r+i pre-indexed forms may need to pass a 7611 // constant base with a variable offset so that constant coercion 7612 // will work with the patterns in canonical form. 7613 bool Swapped = false; 7614 if (isa<ConstantSDNode>(BasePtr)) { 7615 std::swap(BasePtr, Offset); 7616 Swapped = true; 7617 } 7618 7619 // Don't create a indexed load / store with zero offset. 7620 if (isa<ConstantSDNode>(Offset) && 7621 cast<ConstantSDNode>(Offset)->isNullValue()) 7622 return false; 7623 7624 // Try turning it into a pre-indexed load / store except when: 7625 // 1) The new base ptr is a frame index. 7626 // 2) If N is a store and the new base ptr is either the same as or is a 7627 // predecessor of the value being stored. 7628 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded 7629 // that would create a cycle. 7630 // 4) All uses are load / store ops that use it as old base ptr. 7631 7632 // Check #1. Preinc'ing a frame index would require copying the stack pointer 7633 // (plus the implicit offset) to a register to preinc anyway. 7634 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr)) 7635 return false; 7636 7637 // Check #2. 7638 if (!isLoad) { 7639 SDValue Val = cast<StoreSDNode>(N)->getValue(); 7640 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode())) 7641 return false; 7642 } 7643 7644 // If the offset is a constant, there may be other adds of constants that 7645 // can be folded with this one. We should do this to avoid having to keep 7646 // a copy of the original base pointer. 7647 SmallVector<SDNode *, 16> OtherUses; 7648 if (isa<ConstantSDNode>(Offset)) 7649 for (SDNode *Use : BasePtr.getNode()->uses()) { 7650 if (Use == Ptr.getNode()) 7651 continue; 7652 7653 if (Use->isPredecessorOf(N)) 7654 continue; 7655 7656 if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) { 7657 OtherUses.clear(); 7658 break; 7659 } 7660 7661 SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1); 7662 if (Op1.getNode() == BasePtr.getNode()) 7663 std::swap(Op0, Op1); 7664 assert(Op0.getNode() == BasePtr.getNode() && 7665 "Use of ADD/SUB but not an operand"); 7666 7667 if (!isa<ConstantSDNode>(Op1)) { 7668 OtherUses.clear(); 7669 break; 7670 } 7671 7672 // FIXME: In some cases, we can be smarter about this. 7673 if (Op1.getValueType() != Offset.getValueType()) { 7674 OtherUses.clear(); 7675 break; 7676 } 7677 7678 OtherUses.push_back(Use); 7679 } 7680 7681 if (Swapped) 7682 std::swap(BasePtr, Offset); 7683 7684 // Now check for #3 and #4. 7685 bool RealUse = false; 7686 7687 // Caches for hasPredecessorHelper 7688 SmallPtrSet<const SDNode *, 32> Visited; 7689 SmallVector<const SDNode *, 16> Worklist; 7690 7691 for (SDNode *Use : Ptr.getNode()->uses()) { 7692 if (Use == N) 7693 continue; 7694 if (N->hasPredecessorHelper(Use, Visited, Worklist)) 7695 return false; 7696 7697 // If Ptr may be folded in addressing mode of other use, then it's 7698 // not profitable to do this transformation. 7699 if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI)) 7700 RealUse = true; 7701 } 7702 7703 if (!RealUse) 7704 return false; 7705 7706 SDValue Result; 7707 if (isLoad) 7708 Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N), 7709 BasePtr, Offset, AM); 7710 else 7711 Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N), 7712 BasePtr, Offset, AM); 7713 ++PreIndexedNodes; 7714 ++NodesCombined; 7715 DEBUG(dbgs() << "\nReplacing.4 "; 7716 N->dump(&DAG); 7717 dbgs() << "\nWith: "; 7718 Result.getNode()->dump(&DAG); 7719 dbgs() << '\n'); 7720 WorkListRemover DeadNodes(*this); 7721 if (isLoad) { 7722 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0)); 7723 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2)); 7724 } else { 7725 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1)); 7726 } 7727 7728 // Finally, since the node is now dead, remove it from the graph. 7729 DAG.DeleteNode(N); 7730 7731 if (Swapped) 7732 std::swap(BasePtr, Offset); 7733 7734 // Replace other uses of BasePtr that can be updated to use Ptr 7735 for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) { 7736 unsigned OffsetIdx = 1; 7737 if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode()) 7738 OffsetIdx = 0; 7739 assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() == 7740 BasePtr.getNode() && "Expected BasePtr operand"); 7741 7742 // We need to replace ptr0 in the following expression: 7743 // x0 * offset0 + y0 * ptr0 = t0 7744 // knowing that 7745 // x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store) 7746 // 7747 // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the 7748 // indexed load/store and the expresion that needs to be re-written. 7749 // 7750 // Therefore, we have: 7751 // t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1 7752 7753 ConstantSDNode *CN = 7754 cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx)); 7755 int X0, X1, Y0, Y1; 7756 APInt Offset0 = CN->getAPIntValue(); 7757 APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue(); 7758 7759 X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1; 7760 Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1; 7761 X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1; 7762 Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1; 7763 7764 unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD; 7765 7766 APInt CNV = Offset0; 7767 if (X0 < 0) CNV = -CNV; 7768 if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1; 7769 else CNV = CNV - Offset1; 7770 7771 // We can now generate the new expression. 7772 SDValue NewOp1 = DAG.getConstant(CNV, CN->getValueType(0)); 7773 SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0); 7774 7775 SDValue NewUse = DAG.getNode(Opcode, 7776 SDLoc(OtherUses[i]), 7777 OtherUses[i]->getValueType(0), NewOp1, NewOp2); 7778 DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse); 7779 removeFromWorkList(OtherUses[i]); 7780 DAG.DeleteNode(OtherUses[i]); 7781 } 7782 7783 // Replace the uses of Ptr with uses of the updated base value. 7784 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0)); 7785 removeFromWorkList(Ptr.getNode()); 7786 DAG.DeleteNode(Ptr.getNode()); 7787 7788 return true; 7789 } 7790 7791 /// CombineToPostIndexedLoadStore - Try to combine a load / store with a 7792 /// add / sub of the base pointer node into a post-indexed load / store. 7793 /// The transformation folded the add / subtract into the new indexed 7794 /// load / store effectively and all of its uses are redirected to the 7795 /// new load / store. 7796 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) { 7797 if (Level < AfterLegalizeDAG) 7798 return false; 7799 7800 bool isLoad = true; 7801 SDValue Ptr; 7802 EVT VT; 7803 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 7804 if (LD->isIndexed()) 7805 return false; 7806 VT = LD->getMemoryVT(); 7807 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) && 7808 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT)) 7809 return false; 7810 Ptr = LD->getBasePtr(); 7811 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 7812 if (ST->isIndexed()) 7813 return false; 7814 VT = ST->getMemoryVT(); 7815 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) && 7816 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT)) 7817 return false; 7818 Ptr = ST->getBasePtr(); 7819 isLoad = false; 7820 } else { 7821 return false; 7822 } 7823 7824 if (Ptr.getNode()->hasOneUse()) 7825 return false; 7826 7827 for (SDNode *Op : Ptr.getNode()->uses()) { 7828 if (Op == N || 7829 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB)) 7830 continue; 7831 7832 SDValue BasePtr; 7833 SDValue Offset; 7834 ISD::MemIndexedMode AM = ISD::UNINDEXED; 7835 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) { 7836 // Don't create a indexed load / store with zero offset. 7837 if (isa<ConstantSDNode>(Offset) && 7838 cast<ConstantSDNode>(Offset)->isNullValue()) 7839 continue; 7840 7841 // Try turning it into a post-indexed load / store except when 7842 // 1) All uses are load / store ops that use it as base ptr (and 7843 // it may be folded as addressing mmode). 7844 // 2) Op must be independent of N, i.e. Op is neither a predecessor 7845 // nor a successor of N. Otherwise, if Op is folded that would 7846 // create a cycle. 7847 7848 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr)) 7849 continue; 7850 7851 // Check for #1. 7852 bool TryNext = false; 7853 for (SDNode *Use : BasePtr.getNode()->uses()) { 7854 if (Use == Ptr.getNode()) 7855 continue; 7856 7857 // If all the uses are load / store addresses, then don't do the 7858 // transformation. 7859 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){ 7860 bool RealUse = false; 7861 for (SDNode *UseUse : Use->uses()) { 7862 if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI)) 7863 RealUse = true; 7864 } 7865 7866 if (!RealUse) { 7867 TryNext = true; 7868 break; 7869 } 7870 } 7871 } 7872 7873 if (TryNext) 7874 continue; 7875 7876 // Check for #2 7877 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) { 7878 SDValue Result = isLoad 7879 ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N), 7880 BasePtr, Offset, AM) 7881 : DAG.getIndexedStore(SDValue(N,0), SDLoc(N), 7882 BasePtr, Offset, AM); 7883 ++PostIndexedNodes; 7884 ++NodesCombined; 7885 DEBUG(dbgs() << "\nReplacing.5 "; 7886 N->dump(&DAG); 7887 dbgs() << "\nWith: "; 7888 Result.getNode()->dump(&DAG); 7889 dbgs() << '\n'); 7890 WorkListRemover DeadNodes(*this); 7891 if (isLoad) { 7892 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0)); 7893 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2)); 7894 } else { 7895 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1)); 7896 } 7897 7898 // Finally, since the node is now dead, remove it from the graph. 7899 DAG.DeleteNode(N); 7900 7901 // Replace the uses of Use with uses of the updated base value. 7902 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0), 7903 Result.getValue(isLoad ? 1 : 0)); 7904 removeFromWorkList(Op); 7905 DAG.DeleteNode(Op); 7906 return true; 7907 } 7908 } 7909 } 7910 7911 return false; 7912 } 7913 7914 SDValue DAGCombiner::visitLOAD(SDNode *N) { 7915 LoadSDNode *LD = cast<LoadSDNode>(N); 7916 SDValue Chain = LD->getChain(); 7917 SDValue Ptr = LD->getBasePtr(); 7918 7919 // If load is not volatile and there are no uses of the loaded value (and 7920 // the updated indexed value in case of indexed loads), change uses of the 7921 // chain value into uses of the chain input (i.e. delete the dead load). 7922 if (!LD->isVolatile()) { 7923 if (N->getValueType(1) == MVT::Other) { 7924 // Unindexed loads. 7925 if (!N->hasAnyUseOfValue(0)) { 7926 // It's not safe to use the two value CombineTo variant here. e.g. 7927 // v1, chain2 = load chain1, loc 7928 // v2, chain3 = load chain2, loc 7929 // v3 = add v2, c 7930 // Now we replace use of chain2 with chain1. This makes the second load 7931 // isomorphic to the one we are deleting, and thus makes this load live. 7932 DEBUG(dbgs() << "\nReplacing.6 "; 7933 N->dump(&DAG); 7934 dbgs() << "\nWith chain: "; 7935 Chain.getNode()->dump(&DAG); 7936 dbgs() << "\n"); 7937 WorkListRemover DeadNodes(*this); 7938 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain); 7939 7940 if (N->use_empty()) { 7941 removeFromWorkList(N); 7942 DAG.DeleteNode(N); 7943 } 7944 7945 return SDValue(N, 0); // Return N so it doesn't get rechecked! 7946 } 7947 } else { 7948 // Indexed loads. 7949 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?"); 7950 if (!N->hasAnyUseOfValue(0) && !N->hasAnyUseOfValue(1)) { 7951 SDValue Undef = DAG.getUNDEF(N->getValueType(0)); 7952 DEBUG(dbgs() << "\nReplacing.7 "; 7953 N->dump(&DAG); 7954 dbgs() << "\nWith: "; 7955 Undef.getNode()->dump(&DAG); 7956 dbgs() << " and 2 other values\n"); 7957 WorkListRemover DeadNodes(*this); 7958 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef); 7959 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), 7960 DAG.getUNDEF(N->getValueType(1))); 7961 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain); 7962 removeFromWorkList(N); 7963 DAG.DeleteNode(N); 7964 return SDValue(N, 0); // Return N so it doesn't get rechecked! 7965 } 7966 } 7967 } 7968 7969 // If this load is directly stored, replace the load value with the stored 7970 // value. 7971 // TODO: Handle store large -> read small portion. 7972 // TODO: Handle TRUNCSTORE/LOADEXT 7973 if (ISD::isNormalLoad(N) && !LD->isVolatile()) { 7974 if (ISD::isNON_TRUNCStore(Chain.getNode())) { 7975 StoreSDNode *PrevST = cast<StoreSDNode>(Chain); 7976 if (PrevST->getBasePtr() == Ptr && 7977 PrevST->getValue().getValueType() == N->getValueType(0)) 7978 return CombineTo(N, Chain.getOperand(1), Chain); 7979 } 7980 } 7981 7982 // Try to infer better alignment information than the load already has. 7983 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) { 7984 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) { 7985 if (Align > LD->getMemOperand()->getBaseAlignment()) { 7986 SDValue NewLoad = 7987 DAG.getExtLoad(LD->getExtensionType(), SDLoc(N), 7988 LD->getValueType(0), 7989 Chain, Ptr, LD->getPointerInfo(), 7990 LD->getMemoryVT(), 7991 LD->isVolatile(), LD->isNonTemporal(), Align, 7992 LD->getTBAAInfo()); 7993 return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true); 7994 } 7995 } 7996 } 7997 7998 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA : 7999 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA(); 8000 #ifndef NDEBUG 8001 if (CombinerAAOnlyFunc.getNumOccurrences() && 8002 CombinerAAOnlyFunc != DAG.getMachineFunction().getName()) 8003 UseAA = false; 8004 #endif 8005 if (UseAA && LD->isUnindexed()) { 8006 // Walk up chain skipping non-aliasing memory nodes. 8007 SDValue BetterChain = FindBetterChain(N, Chain); 8008 8009 // If there is a better chain. 8010 if (Chain != BetterChain) { 8011 SDValue ReplLoad; 8012 8013 // Replace the chain to void dependency. 8014 if (LD->getExtensionType() == ISD::NON_EXTLOAD) { 8015 ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD), 8016 BetterChain, Ptr, LD->getMemOperand()); 8017 } else { 8018 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), 8019 LD->getValueType(0), 8020 BetterChain, Ptr, LD->getMemoryVT(), 8021 LD->getMemOperand()); 8022 } 8023 8024 // Create token factor to keep old chain connected. 8025 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N), 8026 MVT::Other, Chain, ReplLoad.getValue(1)); 8027 8028 // Make sure the new and old chains are cleaned up. 8029 AddToWorkList(Token.getNode()); 8030 8031 // Replace uses with load result and token factor. Don't add users 8032 // to work list. 8033 return CombineTo(N, ReplLoad.getValue(0), Token, false); 8034 } 8035 } 8036 8037 // Try transforming N to an indexed load. 8038 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N)) 8039 return SDValue(N, 0); 8040 8041 // Try to slice up N to more direct loads if the slices are mapped to 8042 // different register banks or pairing can take place. 8043 if (SliceUpLoad(N)) 8044 return SDValue(N, 0); 8045 8046 return SDValue(); 8047 } 8048 8049 namespace { 8050 /// \brief Helper structure used to slice a load in smaller loads. 8051 /// Basically a slice is obtained from the following sequence: 8052 /// Origin = load Ty1, Base 8053 /// Shift = srl Ty1 Origin, CstTy Amount 8054 /// Inst = trunc Shift to Ty2 8055 /// 8056 /// Then, it will be rewriten into: 8057 /// Slice = load SliceTy, Base + SliceOffset 8058 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2 8059 /// 8060 /// SliceTy is deduced from the number of bits that are actually used to 8061 /// build Inst. 8062 struct LoadedSlice { 8063 /// \brief Helper structure used to compute the cost of a slice. 8064 struct Cost { 8065 /// Are we optimizing for code size. 8066 bool ForCodeSize; 8067 /// Various cost. 8068 unsigned Loads; 8069 unsigned Truncates; 8070 unsigned CrossRegisterBanksCopies; 8071 unsigned ZExts; 8072 unsigned Shift; 8073 8074 Cost(bool ForCodeSize = false) 8075 : ForCodeSize(ForCodeSize), Loads(0), Truncates(0), 8076 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {} 8077 8078 /// \brief Get the cost of one isolated slice. 8079 Cost(const LoadedSlice &LS, bool ForCodeSize = false) 8080 : ForCodeSize(ForCodeSize), Loads(1), Truncates(0), 8081 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) { 8082 EVT TruncType = LS.Inst->getValueType(0); 8083 EVT LoadedType = LS.getLoadedType(); 8084 if (TruncType != LoadedType && 8085 !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType)) 8086 ZExts = 1; 8087 } 8088 8089 /// \brief Account for slicing gain in the current cost. 8090 /// Slicing provide a few gains like removing a shift or a 8091 /// truncate. This method allows to grow the cost of the original 8092 /// load with the gain from this slice. 8093 void addSliceGain(const LoadedSlice &LS) { 8094 // Each slice saves a truncate. 8095 const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo(); 8096 if (!TLI.isTruncateFree(LS.Inst->getValueType(0), 8097 LS.Inst->getOperand(0).getValueType())) 8098 ++Truncates; 8099 // If there is a shift amount, this slice gets rid of it. 8100 if (LS.Shift) 8101 ++Shift; 8102 // If this slice can merge a cross register bank copy, account for it. 8103 if (LS.canMergeExpensiveCrossRegisterBankCopy()) 8104 ++CrossRegisterBanksCopies; 8105 } 8106 8107 Cost &operator+=(const Cost &RHS) { 8108 Loads += RHS.Loads; 8109 Truncates += RHS.Truncates; 8110 CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies; 8111 ZExts += RHS.ZExts; 8112 Shift += RHS.Shift; 8113 return *this; 8114 } 8115 8116 bool operator==(const Cost &RHS) const { 8117 return Loads == RHS.Loads && Truncates == RHS.Truncates && 8118 CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies && 8119 ZExts == RHS.ZExts && Shift == RHS.Shift; 8120 } 8121 8122 bool operator!=(const Cost &RHS) const { return !(*this == RHS); } 8123 8124 bool operator<(const Cost &RHS) const { 8125 // Assume cross register banks copies are as expensive as loads. 8126 // FIXME: Do we want some more target hooks? 8127 unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies; 8128 unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies; 8129 // Unless we are optimizing for code size, consider the 8130 // expensive operation first. 8131 if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS) 8132 return ExpensiveOpsLHS < ExpensiveOpsRHS; 8133 return (Truncates + ZExts + Shift + ExpensiveOpsLHS) < 8134 (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS); 8135 } 8136 8137 bool operator>(const Cost &RHS) const { return RHS < *this; } 8138 8139 bool operator<=(const Cost &RHS) const { return !(RHS < *this); } 8140 8141 bool operator>=(const Cost &RHS) const { return !(*this < RHS); } 8142 }; 8143 // The last instruction that represent the slice. This should be a 8144 // truncate instruction. 8145 SDNode *Inst; 8146 // The original load instruction. 8147 LoadSDNode *Origin; 8148 // The right shift amount in bits from the original load. 8149 unsigned Shift; 8150 // The DAG from which Origin came from. 8151 // This is used to get some contextual information about legal types, etc. 8152 SelectionDAG *DAG; 8153 8154 LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr, 8155 unsigned Shift = 0, SelectionDAG *DAG = nullptr) 8156 : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {} 8157 8158 LoadedSlice(const LoadedSlice &LS) 8159 : Inst(LS.Inst), Origin(LS.Origin), Shift(LS.Shift), DAG(LS.DAG) {} 8160 8161 /// \brief Get the bits used in a chunk of bits \p BitWidth large. 8162 /// \return Result is \p BitWidth and has used bits set to 1 and 8163 /// not used bits set to 0. 8164 APInt getUsedBits() const { 8165 // Reproduce the trunc(lshr) sequence: 8166 // - Start from the truncated value. 8167 // - Zero extend to the desired bit width. 8168 // - Shift left. 8169 assert(Origin && "No original load to compare against."); 8170 unsigned BitWidth = Origin->getValueSizeInBits(0); 8171 assert(Inst && "This slice is not bound to an instruction"); 8172 assert(Inst->getValueSizeInBits(0) <= BitWidth && 8173 "Extracted slice is bigger than the whole type!"); 8174 APInt UsedBits(Inst->getValueSizeInBits(0), 0); 8175 UsedBits.setAllBits(); 8176 UsedBits = UsedBits.zext(BitWidth); 8177 UsedBits <<= Shift; 8178 return UsedBits; 8179 } 8180 8181 /// \brief Get the size of the slice to be loaded in bytes. 8182 unsigned getLoadedSize() const { 8183 unsigned SliceSize = getUsedBits().countPopulation(); 8184 assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte."); 8185 return SliceSize / 8; 8186 } 8187 8188 /// \brief Get the type that will be loaded for this slice. 8189 /// Note: This may not be the final type for the slice. 8190 EVT getLoadedType() const { 8191 assert(DAG && "Missing context"); 8192 LLVMContext &Ctxt = *DAG->getContext(); 8193 return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8); 8194 } 8195 8196 /// \brief Get the alignment of the load used for this slice. 8197 unsigned getAlignment() const { 8198 unsigned Alignment = Origin->getAlignment(); 8199 unsigned Offset = getOffsetFromBase(); 8200 if (Offset != 0) 8201 Alignment = MinAlign(Alignment, Alignment + Offset); 8202 return Alignment; 8203 } 8204 8205 /// \brief Check if this slice can be rewritten with legal operations. 8206 bool isLegal() const { 8207 // An invalid slice is not legal. 8208 if (!Origin || !Inst || !DAG) 8209 return false; 8210 8211 // Offsets are for indexed load only, we do not handle that. 8212 if (Origin->getOffset().getOpcode() != ISD::UNDEF) 8213 return false; 8214 8215 const TargetLowering &TLI = DAG->getTargetLoweringInfo(); 8216 8217 // Check that the type is legal. 8218 EVT SliceType = getLoadedType(); 8219 if (!TLI.isTypeLegal(SliceType)) 8220 return false; 8221 8222 // Check that the load is legal for this type. 8223 if (!TLI.isOperationLegal(ISD::LOAD, SliceType)) 8224 return false; 8225 8226 // Check that the offset can be computed. 8227 // 1. Check its type. 8228 EVT PtrType = Origin->getBasePtr().getValueType(); 8229 if (PtrType == MVT::Untyped || PtrType.isExtended()) 8230 return false; 8231 8232 // 2. Check that it fits in the immediate. 8233 if (!TLI.isLegalAddImmediate(getOffsetFromBase())) 8234 return false; 8235 8236 // 3. Check that the computation is legal. 8237 if (!TLI.isOperationLegal(ISD::ADD, PtrType)) 8238 return false; 8239 8240 // Check that the zext is legal if it needs one. 8241 EVT TruncateType = Inst->getValueType(0); 8242 if (TruncateType != SliceType && 8243 !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType)) 8244 return false; 8245 8246 return true; 8247 } 8248 8249 /// \brief Get the offset in bytes of this slice in the original chunk of 8250 /// bits. 8251 /// \pre DAG != nullptr. 8252 uint64_t getOffsetFromBase() const { 8253 assert(DAG && "Missing context."); 8254 bool IsBigEndian = 8255 DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian(); 8256 assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported."); 8257 uint64_t Offset = Shift / 8; 8258 unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8; 8259 assert(!(Origin->getValueSizeInBits(0) & 0x7) && 8260 "The size of the original loaded type is not a multiple of a" 8261 " byte."); 8262 // If Offset is bigger than TySizeInBytes, it means we are loading all 8263 // zeros. This should have been optimized before in the process. 8264 assert(TySizeInBytes > Offset && 8265 "Invalid shift amount for given loaded size"); 8266 if (IsBigEndian) 8267 Offset = TySizeInBytes - Offset - getLoadedSize(); 8268 return Offset; 8269 } 8270 8271 /// \brief Generate the sequence of instructions to load the slice 8272 /// represented by this object and redirect the uses of this slice to 8273 /// this new sequence of instructions. 8274 /// \pre this->Inst && this->Origin are valid Instructions and this 8275 /// object passed the legal check: LoadedSlice::isLegal returned true. 8276 /// \return The last instruction of the sequence used to load the slice. 8277 SDValue loadSlice() const { 8278 assert(Inst && Origin && "Unable to replace a non-existing slice."); 8279 const SDValue &OldBaseAddr = Origin->getBasePtr(); 8280 SDValue BaseAddr = OldBaseAddr; 8281 // Get the offset in that chunk of bytes w.r.t. the endianess. 8282 int64_t Offset = static_cast<int64_t>(getOffsetFromBase()); 8283 assert(Offset >= 0 && "Offset too big to fit in int64_t!"); 8284 if (Offset) { 8285 // BaseAddr = BaseAddr + Offset. 8286 EVT ArithType = BaseAddr.getValueType(); 8287 BaseAddr = DAG->getNode(ISD::ADD, SDLoc(Origin), ArithType, BaseAddr, 8288 DAG->getConstant(Offset, ArithType)); 8289 } 8290 8291 // Create the type of the loaded slice according to its size. 8292 EVT SliceType = getLoadedType(); 8293 8294 // Create the load for the slice. 8295 SDValue LastInst = DAG->getLoad( 8296 SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr, 8297 Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(), 8298 Origin->isNonTemporal(), Origin->isInvariant(), getAlignment()); 8299 // If the final type is not the same as the loaded type, this means that 8300 // we have to pad with zero. Create a zero extend for that. 8301 EVT FinalType = Inst->getValueType(0); 8302 if (SliceType != FinalType) 8303 LastInst = 8304 DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst); 8305 return LastInst; 8306 } 8307 8308 /// \brief Check if this slice can be merged with an expensive cross register 8309 /// bank copy. E.g., 8310 /// i = load i32 8311 /// f = bitcast i32 i to float 8312 bool canMergeExpensiveCrossRegisterBankCopy() const { 8313 if (!Inst || !Inst->hasOneUse()) 8314 return false; 8315 SDNode *Use = *Inst->use_begin(); 8316 if (Use->getOpcode() != ISD::BITCAST) 8317 return false; 8318 assert(DAG && "Missing context"); 8319 const TargetLowering &TLI = DAG->getTargetLoweringInfo(); 8320 EVT ResVT = Use->getValueType(0); 8321 const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT()); 8322 const TargetRegisterClass *ArgRC = 8323 TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT()); 8324 if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT)) 8325 return false; 8326 8327 // At this point, we know that we perform a cross-register-bank copy. 8328 // Check if it is expensive. 8329 const TargetRegisterInfo *TRI = TLI.getTargetMachine().getRegisterInfo(); 8330 // Assume bitcasts are cheap, unless both register classes do not 8331 // explicitly share a common sub class. 8332 if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC)) 8333 return false; 8334 8335 // Check if it will be merged with the load. 8336 // 1. Check the alignment constraint. 8337 unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment( 8338 ResVT.getTypeForEVT(*DAG->getContext())); 8339 8340 if (RequiredAlignment > getAlignment()) 8341 return false; 8342 8343 // 2. Check that the load is a legal operation for that type. 8344 if (!TLI.isOperationLegal(ISD::LOAD, ResVT)) 8345 return false; 8346 8347 // 3. Check that we do not have a zext in the way. 8348 if (Inst->getValueType(0) != getLoadedType()) 8349 return false; 8350 8351 return true; 8352 } 8353 }; 8354 } 8355 8356 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e., 8357 /// \p UsedBits looks like 0..0 1..1 0..0. 8358 static bool areUsedBitsDense(const APInt &UsedBits) { 8359 // If all the bits are one, this is dense! 8360 if (UsedBits.isAllOnesValue()) 8361 return true; 8362 8363 // Get rid of the unused bits on the right. 8364 APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros()); 8365 // Get rid of the unused bits on the left. 8366 if (NarrowedUsedBits.countLeadingZeros()) 8367 NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits()); 8368 // Check that the chunk of bits is completely used. 8369 return NarrowedUsedBits.isAllOnesValue(); 8370 } 8371 8372 /// \brief Check whether or not \p First and \p Second are next to each other 8373 /// in memory. This means that there is no hole between the bits loaded 8374 /// by \p First and the bits loaded by \p Second. 8375 static bool areSlicesNextToEachOther(const LoadedSlice &First, 8376 const LoadedSlice &Second) { 8377 assert(First.Origin == Second.Origin && First.Origin && 8378 "Unable to match different memory origins."); 8379 APInt UsedBits = First.getUsedBits(); 8380 assert((UsedBits & Second.getUsedBits()) == 0 && 8381 "Slices are not supposed to overlap."); 8382 UsedBits |= Second.getUsedBits(); 8383 return areUsedBitsDense(UsedBits); 8384 } 8385 8386 /// \brief Adjust the \p GlobalLSCost according to the target 8387 /// paring capabilities and the layout of the slices. 8388 /// \pre \p GlobalLSCost should account for at least as many loads as 8389 /// there is in the slices in \p LoadedSlices. 8390 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices, 8391 LoadedSlice::Cost &GlobalLSCost) { 8392 unsigned NumberOfSlices = LoadedSlices.size(); 8393 // If there is less than 2 elements, no pairing is possible. 8394 if (NumberOfSlices < 2) 8395 return; 8396 8397 // Sort the slices so that elements that are likely to be next to each 8398 // other in memory are next to each other in the list. 8399 std::sort(LoadedSlices.begin(), LoadedSlices.end(), 8400 [](const LoadedSlice &LHS, const LoadedSlice &RHS) { 8401 assert(LHS.Origin == RHS.Origin && "Different bases not implemented."); 8402 return LHS.getOffsetFromBase() < RHS.getOffsetFromBase(); 8403 }); 8404 const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo(); 8405 // First (resp. Second) is the first (resp. Second) potentially candidate 8406 // to be placed in a paired load. 8407 const LoadedSlice *First = nullptr; 8408 const LoadedSlice *Second = nullptr; 8409 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice, 8410 // Set the beginning of the pair. 8411 First = Second) { 8412 8413 Second = &LoadedSlices[CurrSlice]; 8414 8415 // If First is NULL, it means we start a new pair. 8416 // Get to the next slice. 8417 if (!First) 8418 continue; 8419 8420 EVT LoadedType = First->getLoadedType(); 8421 8422 // If the types of the slices are different, we cannot pair them. 8423 if (LoadedType != Second->getLoadedType()) 8424 continue; 8425 8426 // Check if the target supplies paired loads for this type. 8427 unsigned RequiredAlignment = 0; 8428 if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) { 8429 // move to the next pair, this type is hopeless. 8430 Second = nullptr; 8431 continue; 8432 } 8433 // Check if we meet the alignment requirement. 8434 if (RequiredAlignment > First->getAlignment()) 8435 continue; 8436 8437 // Check that both loads are next to each other in memory. 8438 if (!areSlicesNextToEachOther(*First, *Second)) 8439 continue; 8440 8441 assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!"); 8442 --GlobalLSCost.Loads; 8443 // Move to the next pair. 8444 Second = nullptr; 8445 } 8446 } 8447 8448 /// \brief Check the profitability of all involved LoadedSlice. 8449 /// Currently, it is considered profitable if there is exactly two 8450 /// involved slices (1) which are (2) next to each other in memory, and 8451 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3). 8452 /// 8453 /// Note: The order of the elements in \p LoadedSlices may be modified, but not 8454 /// the elements themselves. 8455 /// 8456 /// FIXME: When the cost model will be mature enough, we can relax 8457 /// constraints (1) and (2). 8458 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices, 8459 const APInt &UsedBits, bool ForCodeSize) { 8460 unsigned NumberOfSlices = LoadedSlices.size(); 8461 if (StressLoadSlicing) 8462 return NumberOfSlices > 1; 8463 8464 // Check (1). 8465 if (NumberOfSlices != 2) 8466 return false; 8467 8468 // Check (2). 8469 if (!areUsedBitsDense(UsedBits)) 8470 return false; 8471 8472 // Check (3). 8473 LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize); 8474 // The original code has one big load. 8475 OrigCost.Loads = 1; 8476 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) { 8477 const LoadedSlice &LS = LoadedSlices[CurrSlice]; 8478 // Accumulate the cost of all the slices. 8479 LoadedSlice::Cost SliceCost(LS, ForCodeSize); 8480 GlobalSlicingCost += SliceCost; 8481 8482 // Account as cost in the original configuration the gain obtained 8483 // with the current slices. 8484 OrigCost.addSliceGain(LS); 8485 } 8486 8487 // If the target supports paired load, adjust the cost accordingly. 8488 adjustCostForPairing(LoadedSlices, GlobalSlicingCost); 8489 return OrigCost > GlobalSlicingCost; 8490 } 8491 8492 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr) 8493 /// operations, split it in the various pieces being extracted. 8494 /// 8495 /// This sort of thing is introduced by SROA. 8496 /// This slicing takes care not to insert overlapping loads. 8497 /// \pre LI is a simple load (i.e., not an atomic or volatile load). 8498 bool DAGCombiner::SliceUpLoad(SDNode *N) { 8499 if (Level < AfterLegalizeDAG) 8500 return false; 8501 8502 LoadSDNode *LD = cast<LoadSDNode>(N); 8503 if (LD->isVolatile() || !ISD::isNormalLoad(LD) || 8504 !LD->getValueType(0).isInteger()) 8505 return false; 8506 8507 // Keep track of already used bits to detect overlapping values. 8508 // In that case, we will just abort the transformation. 8509 APInt UsedBits(LD->getValueSizeInBits(0), 0); 8510 8511 SmallVector<LoadedSlice, 4> LoadedSlices; 8512 8513 // Check if this load is used as several smaller chunks of bits. 8514 // Basically, look for uses in trunc or trunc(lshr) and record a new chain 8515 // of computation for each trunc. 8516 for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end(); 8517 UI != UIEnd; ++UI) { 8518 // Skip the uses of the chain. 8519 if (UI.getUse().getResNo() != 0) 8520 continue; 8521 8522 SDNode *User = *UI; 8523 unsigned Shift = 0; 8524 8525 // Check if this is a trunc(lshr). 8526 if (User->getOpcode() == ISD::SRL && User->hasOneUse() && 8527 isa<ConstantSDNode>(User->getOperand(1))) { 8528 Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue(); 8529 User = *User->use_begin(); 8530 } 8531 8532 // At this point, User is a Truncate, iff we encountered, trunc or 8533 // trunc(lshr). 8534 if (User->getOpcode() != ISD::TRUNCATE) 8535 return false; 8536 8537 // The width of the type must be a power of 2 and greater than 8-bits. 8538 // Otherwise the load cannot be represented in LLVM IR. 8539 // Moreover, if we shifted with a non-8-bits multiple, the slice 8540 // will be across several bytes. We do not support that. 8541 unsigned Width = User->getValueSizeInBits(0); 8542 if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7)) 8543 return 0; 8544 8545 // Build the slice for this chain of computations. 8546 LoadedSlice LS(User, LD, Shift, &DAG); 8547 APInt CurrentUsedBits = LS.getUsedBits(); 8548 8549 // Check if this slice overlaps with another. 8550 if ((CurrentUsedBits & UsedBits) != 0) 8551 return false; 8552 // Update the bits used globally. 8553 UsedBits |= CurrentUsedBits; 8554 8555 // Check if the new slice would be legal. 8556 if (!LS.isLegal()) 8557 return false; 8558 8559 // Record the slice. 8560 LoadedSlices.push_back(LS); 8561 } 8562 8563 // Abort slicing if it does not seem to be profitable. 8564 if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize)) 8565 return false; 8566 8567 ++SlicedLoads; 8568 8569 // Rewrite each chain to use an independent load. 8570 // By construction, each chain can be represented by a unique load. 8571 8572 // Prepare the argument for the new token factor for all the slices. 8573 SmallVector<SDValue, 8> ArgChains; 8574 for (SmallVectorImpl<LoadedSlice>::const_iterator 8575 LSIt = LoadedSlices.begin(), 8576 LSItEnd = LoadedSlices.end(); 8577 LSIt != LSItEnd; ++LSIt) { 8578 SDValue SliceInst = LSIt->loadSlice(); 8579 CombineTo(LSIt->Inst, SliceInst, true); 8580 if (SliceInst.getNode()->getOpcode() != ISD::LOAD) 8581 SliceInst = SliceInst.getOperand(0); 8582 assert(SliceInst->getOpcode() == ISD::LOAD && 8583 "It takes more than a zext to get to the loaded slice!!"); 8584 ArgChains.push_back(SliceInst.getValue(1)); 8585 } 8586 8587 SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other, 8588 ArgChains); 8589 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain); 8590 return true; 8591 } 8592 8593 /// CheckForMaskedLoad - Check to see if V is (and load (ptr), imm), where the 8594 /// load is having specific bytes cleared out. If so, return the byte size 8595 /// being masked out and the shift amount. 8596 static std::pair<unsigned, unsigned> 8597 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) { 8598 std::pair<unsigned, unsigned> Result(0, 0); 8599 8600 // Check for the structure we're looking for. 8601 if (V->getOpcode() != ISD::AND || 8602 !isa<ConstantSDNode>(V->getOperand(1)) || 8603 !ISD::isNormalLoad(V->getOperand(0).getNode())) 8604 return Result; 8605 8606 // Check the chain and pointer. 8607 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0)); 8608 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer. 8609 8610 // The store should be chained directly to the load or be an operand of a 8611 // tokenfactor. 8612 if (LD == Chain.getNode()) 8613 ; // ok. 8614 else if (Chain->getOpcode() != ISD::TokenFactor) 8615 return Result; // Fail. 8616 else { 8617 bool isOk = false; 8618 for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i) 8619 if (Chain->getOperand(i).getNode() == LD) { 8620 isOk = true; 8621 break; 8622 } 8623 if (!isOk) return Result; 8624 } 8625 8626 // This only handles simple types. 8627 if (V.getValueType() != MVT::i16 && 8628 V.getValueType() != MVT::i32 && 8629 V.getValueType() != MVT::i64) 8630 return Result; 8631 8632 // Check the constant mask. Invert it so that the bits being masked out are 8633 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits 8634 // follow the sign bit for uniformity. 8635 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue(); 8636 unsigned NotMaskLZ = countLeadingZeros(NotMask); 8637 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte. 8638 unsigned NotMaskTZ = countTrailingZeros(NotMask); 8639 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte. 8640 if (NotMaskLZ == 64) return Result; // All zero mask. 8641 8642 // See if we have a continuous run of bits. If so, we have 0*1+0* 8643 if (CountTrailingOnes_64(NotMask >> NotMaskTZ)+NotMaskTZ+NotMaskLZ != 64) 8644 return Result; 8645 8646 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64. 8647 if (V.getValueType() != MVT::i64 && NotMaskLZ) 8648 NotMaskLZ -= 64-V.getValueSizeInBits(); 8649 8650 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8; 8651 switch (MaskedBytes) { 8652 case 1: 8653 case 2: 8654 case 4: break; 8655 default: return Result; // All one mask, or 5-byte mask. 8656 } 8657 8658 // Verify that the first bit starts at a multiple of mask so that the access 8659 // is aligned the same as the access width. 8660 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result; 8661 8662 Result.first = MaskedBytes; 8663 Result.second = NotMaskTZ/8; 8664 return Result; 8665 } 8666 8667 8668 /// ShrinkLoadReplaceStoreWithStore - Check to see if IVal is something that 8669 /// provides a value as specified by MaskInfo. If so, replace the specified 8670 /// store with a narrower store of truncated IVal. 8671 static SDNode * 8672 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo, 8673 SDValue IVal, StoreSDNode *St, 8674 DAGCombiner *DC) { 8675 unsigned NumBytes = MaskInfo.first; 8676 unsigned ByteShift = MaskInfo.second; 8677 SelectionDAG &DAG = DC->getDAG(); 8678 8679 // Check to see if IVal is all zeros in the part being masked in by the 'or' 8680 // that uses this. If not, this is not a replacement. 8681 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(), 8682 ByteShift*8, (ByteShift+NumBytes)*8); 8683 if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr; 8684 8685 // Check that it is legal on the target to do this. It is legal if the new 8686 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type 8687 // legalization. 8688 MVT VT = MVT::getIntegerVT(NumBytes*8); 8689 if (!DC->isTypeLegal(VT)) 8690 return nullptr; 8691 8692 // Okay, we can do this! Replace the 'St' store with a store of IVal that is 8693 // shifted by ByteShift and truncated down to NumBytes. 8694 if (ByteShift) 8695 IVal = DAG.getNode(ISD::SRL, SDLoc(IVal), IVal.getValueType(), IVal, 8696 DAG.getConstant(ByteShift*8, 8697 DC->getShiftAmountTy(IVal.getValueType()))); 8698 8699 // Figure out the offset for the store and the alignment of the access. 8700 unsigned StOffset; 8701 unsigned NewAlign = St->getAlignment(); 8702 8703 if (DAG.getTargetLoweringInfo().isLittleEndian()) 8704 StOffset = ByteShift; 8705 else 8706 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes; 8707 8708 SDValue Ptr = St->getBasePtr(); 8709 if (StOffset) { 8710 Ptr = DAG.getNode(ISD::ADD, SDLoc(IVal), Ptr.getValueType(), 8711 Ptr, DAG.getConstant(StOffset, Ptr.getValueType())); 8712 NewAlign = MinAlign(NewAlign, StOffset); 8713 } 8714 8715 // Truncate down to the new size. 8716 IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal); 8717 8718 ++OpsNarrowed; 8719 return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr, 8720 St->getPointerInfo().getWithOffset(StOffset), 8721 false, false, NewAlign).getNode(); 8722 } 8723 8724 8725 /// ReduceLoadOpStoreWidth - Look for sequence of load / op / store where op is 8726 /// one of 'or', 'xor', and 'and' of immediates. If 'op' is only touching some 8727 /// of the loaded bits, try narrowing the load and store if it would end up 8728 /// being a win for performance or code size. 8729 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) { 8730 StoreSDNode *ST = cast<StoreSDNode>(N); 8731 if (ST->isVolatile()) 8732 return SDValue(); 8733 8734 SDValue Chain = ST->getChain(); 8735 SDValue Value = ST->getValue(); 8736 SDValue Ptr = ST->getBasePtr(); 8737 EVT VT = Value.getValueType(); 8738 8739 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse()) 8740 return SDValue(); 8741 8742 unsigned Opc = Value.getOpcode(); 8743 8744 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst 8745 // is a byte mask indicating a consecutive number of bytes, check to see if 8746 // Y is known to provide just those bytes. If so, we try to replace the 8747 // load + replace + store sequence with a single (narrower) store, which makes 8748 // the load dead. 8749 if (Opc == ISD::OR) { 8750 std::pair<unsigned, unsigned> MaskedLoad; 8751 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain); 8752 if (MaskedLoad.first) 8753 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad, 8754 Value.getOperand(1), ST,this)) 8755 return SDValue(NewST, 0); 8756 8757 // Or is commutative, so try swapping X and Y. 8758 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain); 8759 if (MaskedLoad.first) 8760 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad, 8761 Value.getOperand(0), ST,this)) 8762 return SDValue(NewST, 0); 8763 } 8764 8765 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) || 8766 Value.getOperand(1).getOpcode() != ISD::Constant) 8767 return SDValue(); 8768 8769 SDValue N0 = Value.getOperand(0); 8770 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() && 8771 Chain == SDValue(N0.getNode(), 1)) { 8772 LoadSDNode *LD = cast<LoadSDNode>(N0); 8773 if (LD->getBasePtr() != Ptr || 8774 LD->getPointerInfo().getAddrSpace() != 8775 ST->getPointerInfo().getAddrSpace()) 8776 return SDValue(); 8777 8778 // Find the type to narrow it the load / op / store to. 8779 SDValue N1 = Value.getOperand(1); 8780 unsigned BitWidth = N1.getValueSizeInBits(); 8781 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue(); 8782 if (Opc == ISD::AND) 8783 Imm ^= APInt::getAllOnesValue(BitWidth); 8784 if (Imm == 0 || Imm.isAllOnesValue()) 8785 return SDValue(); 8786 unsigned ShAmt = Imm.countTrailingZeros(); 8787 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1; 8788 unsigned NewBW = NextPowerOf2(MSB - ShAmt); 8789 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW); 8790 while (NewBW < BitWidth && 8791 !(TLI.isOperationLegalOrCustom(Opc, NewVT) && 8792 TLI.isNarrowingProfitable(VT, NewVT))) { 8793 NewBW = NextPowerOf2(NewBW); 8794 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW); 8795 } 8796 if (NewBW >= BitWidth) 8797 return SDValue(); 8798 8799 // If the lsb changed does not start at the type bitwidth boundary, 8800 // start at the previous one. 8801 if (ShAmt % NewBW) 8802 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW; 8803 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt, 8804 std::min(BitWidth, ShAmt + NewBW)); 8805 if ((Imm & Mask) == Imm) { 8806 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW); 8807 if (Opc == ISD::AND) 8808 NewImm ^= APInt::getAllOnesValue(NewBW); 8809 uint64_t PtrOff = ShAmt / 8; 8810 // For big endian targets, we need to adjust the offset to the pointer to 8811 // load the correct bytes. 8812 if (TLI.isBigEndian()) 8813 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff; 8814 8815 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff); 8816 Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext()); 8817 if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy)) 8818 return SDValue(); 8819 8820 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD), 8821 Ptr.getValueType(), Ptr, 8822 DAG.getConstant(PtrOff, Ptr.getValueType())); 8823 SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0), 8824 LD->getChain(), NewPtr, 8825 LD->getPointerInfo().getWithOffset(PtrOff), 8826 LD->isVolatile(), LD->isNonTemporal(), 8827 LD->isInvariant(), NewAlign, 8828 LD->getTBAAInfo()); 8829 SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD, 8830 DAG.getConstant(NewImm, NewVT)); 8831 SDValue NewST = DAG.getStore(Chain, SDLoc(N), 8832 NewVal, NewPtr, 8833 ST->getPointerInfo().getWithOffset(PtrOff), 8834 false, false, NewAlign); 8835 8836 AddToWorkList(NewPtr.getNode()); 8837 AddToWorkList(NewLD.getNode()); 8838 AddToWorkList(NewVal.getNode()); 8839 WorkListRemover DeadNodes(*this); 8840 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1)); 8841 ++OpsNarrowed; 8842 return NewST; 8843 } 8844 } 8845 8846 return SDValue(); 8847 } 8848 8849 /// TransformFPLoadStorePair - For a given floating point load / store pair, 8850 /// if the load value isn't used by any other operations, then consider 8851 /// transforming the pair to integer load / store operations if the target 8852 /// deems the transformation profitable. 8853 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) { 8854 StoreSDNode *ST = cast<StoreSDNode>(N); 8855 SDValue Chain = ST->getChain(); 8856 SDValue Value = ST->getValue(); 8857 if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) && 8858 Value.hasOneUse() && 8859 Chain == SDValue(Value.getNode(), 1)) { 8860 LoadSDNode *LD = cast<LoadSDNode>(Value); 8861 EVT VT = LD->getMemoryVT(); 8862 if (!VT.isFloatingPoint() || 8863 VT != ST->getMemoryVT() || 8864 LD->isNonTemporal() || 8865 ST->isNonTemporal() || 8866 LD->getPointerInfo().getAddrSpace() != 0 || 8867 ST->getPointerInfo().getAddrSpace() != 0) 8868 return SDValue(); 8869 8870 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits()); 8871 if (!TLI.isOperationLegal(ISD::LOAD, IntVT) || 8872 !TLI.isOperationLegal(ISD::STORE, IntVT) || 8873 !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) || 8874 !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT)) 8875 return SDValue(); 8876 8877 unsigned LDAlign = LD->getAlignment(); 8878 unsigned STAlign = ST->getAlignment(); 8879 Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext()); 8880 unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy); 8881 if (LDAlign < ABIAlign || STAlign < ABIAlign) 8882 return SDValue(); 8883 8884 SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value), 8885 LD->getChain(), LD->getBasePtr(), 8886 LD->getPointerInfo(), 8887 false, false, false, LDAlign); 8888 8889 SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N), 8890 NewLD, ST->getBasePtr(), 8891 ST->getPointerInfo(), 8892 false, false, STAlign); 8893 8894 AddToWorkList(NewLD.getNode()); 8895 AddToWorkList(NewST.getNode()); 8896 WorkListRemover DeadNodes(*this); 8897 DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1)); 8898 ++LdStFP2Int; 8899 return NewST; 8900 } 8901 8902 return SDValue(); 8903 } 8904 8905 /// Helper struct to parse and store a memory address as base + index + offset. 8906 /// We ignore sign extensions when it is safe to do so. 8907 /// The following two expressions are not equivalent. To differentiate we need 8908 /// to store whether there was a sign extension involved in the index 8909 /// computation. 8910 /// (load (i64 add (i64 copyfromreg %c) 8911 /// (i64 signextend (add (i8 load %index) 8912 /// (i8 1)))) 8913 /// vs 8914 /// 8915 /// (load (i64 add (i64 copyfromreg %c) 8916 /// (i64 signextend (i32 add (i32 signextend (i8 load %index)) 8917 /// (i32 1))))) 8918 struct BaseIndexOffset { 8919 SDValue Base; 8920 SDValue Index; 8921 int64_t Offset; 8922 bool IsIndexSignExt; 8923 8924 BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {} 8925 8926 BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset, 8927 bool IsIndexSignExt) : 8928 Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {} 8929 8930 bool equalBaseIndex(const BaseIndexOffset &Other) { 8931 return Other.Base == Base && Other.Index == Index && 8932 Other.IsIndexSignExt == IsIndexSignExt; 8933 } 8934 8935 /// Parses tree in Ptr for base, index, offset addresses. 8936 static BaseIndexOffset match(SDValue Ptr) { 8937 bool IsIndexSignExt = false; 8938 8939 // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD 8940 // instruction, then it could be just the BASE or everything else we don't 8941 // know how to handle. Just use Ptr as BASE and give up. 8942 if (Ptr->getOpcode() != ISD::ADD) 8943 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt); 8944 8945 // We know that we have at least an ADD instruction. Try to pattern match 8946 // the simple case of BASE + OFFSET. 8947 if (isa<ConstantSDNode>(Ptr->getOperand(1))) { 8948 int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue(); 8949 return BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset, 8950 IsIndexSignExt); 8951 } 8952 8953 // Inside a loop the current BASE pointer is calculated using an ADD and a 8954 // MUL instruction. In this case Ptr is the actual BASE pointer. 8955 // (i64 add (i64 %array_ptr) 8956 // (i64 mul (i64 %induction_var) 8957 // (i64 %element_size))) 8958 if (Ptr->getOperand(1)->getOpcode() == ISD::MUL) 8959 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt); 8960 8961 // Look at Base + Index + Offset cases. 8962 SDValue Base = Ptr->getOperand(0); 8963 SDValue IndexOffset = Ptr->getOperand(1); 8964 8965 // Skip signextends. 8966 if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) { 8967 IndexOffset = IndexOffset->getOperand(0); 8968 IsIndexSignExt = true; 8969 } 8970 8971 // Either the case of Base + Index (no offset) or something else. 8972 if (IndexOffset->getOpcode() != ISD::ADD) 8973 return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt); 8974 8975 // Now we have the case of Base + Index + offset. 8976 SDValue Index = IndexOffset->getOperand(0); 8977 SDValue Offset = IndexOffset->getOperand(1); 8978 8979 if (!isa<ConstantSDNode>(Offset)) 8980 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt); 8981 8982 // Ignore signextends. 8983 if (Index->getOpcode() == ISD::SIGN_EXTEND) { 8984 Index = Index->getOperand(0); 8985 IsIndexSignExt = true; 8986 } else IsIndexSignExt = false; 8987 8988 int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue(); 8989 return BaseIndexOffset(Base, Index, Off, IsIndexSignExt); 8990 } 8991 }; 8992 8993 /// Holds a pointer to an LSBaseSDNode as well as information on where it 8994 /// is located in a sequence of memory operations connected by a chain. 8995 struct MemOpLink { 8996 MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq): 8997 MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { } 8998 // Ptr to the mem node. 8999 LSBaseSDNode *MemNode; 9000 // Offset from the base ptr. 9001 int64_t OffsetFromBase; 9002 // What is the sequence number of this mem node. 9003 // Lowest mem operand in the DAG starts at zero. 9004 unsigned SequenceNum; 9005 }; 9006 9007 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) { 9008 EVT MemVT = St->getMemoryVT(); 9009 int64_t ElementSizeBytes = MemVT.getSizeInBits()/8; 9010 bool NoVectors = DAG.getMachineFunction().getFunction()->getAttributes(). 9011 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat); 9012 9013 // Don't merge vectors into wider inputs. 9014 if (MemVT.isVector() || !MemVT.isSimple()) 9015 return false; 9016 9017 // Perform an early exit check. Do not bother looking at stored values that 9018 // are not constants or loads. 9019 SDValue StoredVal = St->getValue(); 9020 bool IsLoadSrc = isa<LoadSDNode>(StoredVal); 9021 if (!isa<ConstantSDNode>(StoredVal) && !isa<ConstantFPSDNode>(StoredVal) && 9022 !IsLoadSrc) 9023 return false; 9024 9025 // Only look at ends of store sequences. 9026 SDValue Chain = SDValue(St, 1); 9027 if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE) 9028 return false; 9029 9030 // This holds the base pointer, index, and the offset in bytes from the base 9031 // pointer. 9032 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr()); 9033 9034 // We must have a base and an offset. 9035 if (!BasePtr.Base.getNode()) 9036 return false; 9037 9038 // Do not handle stores to undef base pointers. 9039 if (BasePtr.Base.getOpcode() == ISD::UNDEF) 9040 return false; 9041 9042 // Save the LoadSDNodes that we find in the chain. 9043 // We need to make sure that these nodes do not interfere with 9044 // any of the store nodes. 9045 SmallVector<LSBaseSDNode*, 8> AliasLoadNodes; 9046 9047 // Save the StoreSDNodes that we find in the chain. 9048 SmallVector<MemOpLink, 8> StoreNodes; 9049 9050 // Walk up the chain and look for nodes with offsets from the same 9051 // base pointer. Stop when reaching an instruction with a different kind 9052 // or instruction which has a different base pointer. 9053 unsigned Seq = 0; 9054 StoreSDNode *Index = St; 9055 while (Index) { 9056 // If the chain has more than one use, then we can't reorder the mem ops. 9057 if (Index != St && !SDValue(Index, 1)->hasOneUse()) 9058 break; 9059 9060 // Find the base pointer and offset for this memory node. 9061 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr()); 9062 9063 // Check that the base pointer is the same as the original one. 9064 if (!Ptr.equalBaseIndex(BasePtr)) 9065 break; 9066 9067 // Check that the alignment is the same. 9068 if (Index->getAlignment() != St->getAlignment()) 9069 break; 9070 9071 // The memory operands must not be volatile. 9072 if (Index->isVolatile() || Index->isIndexed()) 9073 break; 9074 9075 // No truncation. 9076 if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index)) 9077 if (St->isTruncatingStore()) 9078 break; 9079 9080 // The stored memory type must be the same. 9081 if (Index->getMemoryVT() != MemVT) 9082 break; 9083 9084 // We do not allow unaligned stores because we want to prevent overriding 9085 // stores. 9086 if (Index->getAlignment()*8 != MemVT.getSizeInBits()) 9087 break; 9088 9089 // We found a potential memory operand to merge. 9090 StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++)); 9091 9092 // Find the next memory operand in the chain. If the next operand in the 9093 // chain is a store then move up and continue the scan with the next 9094 // memory operand. If the next operand is a load save it and use alias 9095 // information to check if it interferes with anything. 9096 SDNode *NextInChain = Index->getChain().getNode(); 9097 while (1) { 9098 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) { 9099 // We found a store node. Use it for the next iteration. 9100 Index = STn; 9101 break; 9102 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) { 9103 if (Ldn->isVolatile()) { 9104 Index = nullptr; 9105 break; 9106 } 9107 9108 // Save the load node for later. Continue the scan. 9109 AliasLoadNodes.push_back(Ldn); 9110 NextInChain = Ldn->getChain().getNode(); 9111 continue; 9112 } else { 9113 Index = nullptr; 9114 break; 9115 } 9116 } 9117 } 9118 9119 // Check if there is anything to merge. 9120 if (StoreNodes.size() < 2) 9121 return false; 9122 9123 // Sort the memory operands according to their distance from the base pointer. 9124 std::sort(StoreNodes.begin(), StoreNodes.end(), 9125 [](MemOpLink LHS, MemOpLink RHS) { 9126 return LHS.OffsetFromBase < RHS.OffsetFromBase || 9127 (LHS.OffsetFromBase == RHS.OffsetFromBase && 9128 LHS.SequenceNum > RHS.SequenceNum); 9129 }); 9130 9131 // Scan the memory operations on the chain and find the first non-consecutive 9132 // store memory address. 9133 unsigned LastConsecutiveStore = 0; 9134 int64_t StartAddress = StoreNodes[0].OffsetFromBase; 9135 for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) { 9136 9137 // Check that the addresses are consecutive starting from the second 9138 // element in the list of stores. 9139 if (i > 0) { 9140 int64_t CurrAddress = StoreNodes[i].OffsetFromBase; 9141 if (CurrAddress - StartAddress != (ElementSizeBytes * i)) 9142 break; 9143 } 9144 9145 bool Alias = false; 9146 // Check if this store interferes with any of the loads that we found. 9147 for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld) 9148 if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) { 9149 Alias = true; 9150 break; 9151 } 9152 // We found a load that alias with this store. Stop the sequence. 9153 if (Alias) 9154 break; 9155 9156 // Mark this node as useful. 9157 LastConsecutiveStore = i; 9158 } 9159 9160 // The node with the lowest store address. 9161 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode; 9162 9163 // Store the constants into memory as one consecutive store. 9164 if (!IsLoadSrc) { 9165 unsigned LastLegalType = 0; 9166 unsigned LastLegalVectorType = 0; 9167 bool NonZero = false; 9168 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) { 9169 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 9170 SDValue StoredVal = St->getValue(); 9171 9172 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) { 9173 NonZero |= !C->isNullValue(); 9174 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) { 9175 NonZero |= !C->getConstantFPValue()->isNullValue(); 9176 } else { 9177 // Non-constant. 9178 break; 9179 } 9180 9181 // Find a legal type for the constant store. 9182 unsigned StoreBW = (i+1) * ElementSizeBytes * 8; 9183 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW); 9184 if (TLI.isTypeLegal(StoreTy)) 9185 LastLegalType = i+1; 9186 // Or check whether a truncstore is legal. 9187 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) == 9188 TargetLowering::TypePromoteInteger) { 9189 EVT LegalizedStoredValueTy = 9190 TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType()); 9191 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy)) 9192 LastLegalType = i+1; 9193 } 9194 9195 // Find a legal type for the vector store. 9196 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1); 9197 if (TLI.isTypeLegal(Ty)) 9198 LastLegalVectorType = i + 1; 9199 } 9200 9201 // We only use vectors if the constant is known to be zero and the 9202 // function is not marked with the noimplicitfloat attribute. 9203 if (NonZero || NoVectors) 9204 LastLegalVectorType = 0; 9205 9206 // Check if we found a legal integer type to store. 9207 if (LastLegalType == 0 && LastLegalVectorType == 0) 9208 return false; 9209 9210 bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors; 9211 unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType; 9212 9213 // Make sure we have something to merge. 9214 if (NumElem < 2) 9215 return false; 9216 9217 unsigned EarliestNodeUsed = 0; 9218 for (unsigned i=0; i < NumElem; ++i) { 9219 // Find a chain for the new wide-store operand. Notice that some 9220 // of the store nodes that we found may not be selected for inclusion 9221 // in the wide store. The chain we use needs to be the chain of the 9222 // earliest store node which is *used* and replaced by the wide store. 9223 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum) 9224 EarliestNodeUsed = i; 9225 } 9226 9227 // The earliest Node in the DAG. 9228 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode; 9229 SDLoc DL(StoreNodes[0].MemNode); 9230 9231 SDValue StoredVal; 9232 if (UseVector) { 9233 // Find a legal type for the vector store. 9234 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem); 9235 assert(TLI.isTypeLegal(Ty) && "Illegal vector store"); 9236 StoredVal = DAG.getConstant(0, Ty); 9237 } else { 9238 unsigned StoreBW = NumElem * ElementSizeBytes * 8; 9239 APInt StoreInt(StoreBW, 0); 9240 9241 // Construct a single integer constant which is made of the smaller 9242 // constant inputs. 9243 bool IsLE = TLI.isLittleEndian(); 9244 for (unsigned i = 0; i < NumElem ; ++i) { 9245 unsigned Idx = IsLE ?(NumElem - 1 - i) : i; 9246 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[Idx].MemNode); 9247 SDValue Val = St->getValue(); 9248 StoreInt<<=ElementSizeBytes*8; 9249 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) { 9250 StoreInt|=C->getAPIntValue().zext(StoreBW); 9251 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) { 9252 StoreInt|= C->getValueAPF().bitcastToAPInt().zext(StoreBW); 9253 } else { 9254 assert(false && "Invalid constant element type"); 9255 } 9256 } 9257 9258 // Create the new Load and Store operations. 9259 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW); 9260 StoredVal = DAG.getConstant(StoreInt, StoreTy); 9261 } 9262 9263 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), DL, StoredVal, 9264 FirstInChain->getBasePtr(), 9265 FirstInChain->getPointerInfo(), 9266 false, false, 9267 FirstInChain->getAlignment()); 9268 9269 // Replace the first store with the new store 9270 CombineTo(EarliestOp, NewStore); 9271 // Erase all other stores. 9272 for (unsigned i = 0; i < NumElem ; ++i) { 9273 if (StoreNodes[i].MemNode == EarliestOp) 9274 continue; 9275 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 9276 // ReplaceAllUsesWith will replace all uses that existed when it was 9277 // called, but graph optimizations may cause new ones to appear. For 9278 // example, the case in pr14333 looks like 9279 // 9280 // St's chain -> St -> another store -> X 9281 // 9282 // And the only difference from St to the other store is the chain. 9283 // When we change it's chain to be St's chain they become identical, 9284 // get CSEed and the net result is that X is now a use of St. 9285 // Since we know that St is redundant, just iterate. 9286 while (!St->use_empty()) 9287 DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain()); 9288 removeFromWorkList(St); 9289 DAG.DeleteNode(St); 9290 } 9291 9292 return true; 9293 } 9294 9295 // Below we handle the case of multiple consecutive stores that 9296 // come from multiple consecutive loads. We merge them into a single 9297 // wide load and a single wide store. 9298 9299 // Look for load nodes which are used by the stored values. 9300 SmallVector<MemOpLink, 8> LoadNodes; 9301 9302 // Find acceptable loads. Loads need to have the same chain (token factor), 9303 // must not be zext, volatile, indexed, and they must be consecutive. 9304 BaseIndexOffset LdBasePtr; 9305 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) { 9306 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 9307 LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue()); 9308 if (!Ld) break; 9309 9310 // Loads must only have one use. 9311 if (!Ld->hasNUsesOfValue(1, 0)) 9312 break; 9313 9314 // Check that the alignment is the same as the stores. 9315 if (Ld->getAlignment() != St->getAlignment()) 9316 break; 9317 9318 // The memory operands must not be volatile. 9319 if (Ld->isVolatile() || Ld->isIndexed()) 9320 break; 9321 9322 // We do not accept ext loads. 9323 if (Ld->getExtensionType() != ISD::NON_EXTLOAD) 9324 break; 9325 9326 // The stored memory type must be the same. 9327 if (Ld->getMemoryVT() != MemVT) 9328 break; 9329 9330 BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr()); 9331 // If this is not the first ptr that we check. 9332 if (LdBasePtr.Base.getNode()) { 9333 // The base ptr must be the same. 9334 if (!LdPtr.equalBaseIndex(LdBasePtr)) 9335 break; 9336 } else { 9337 // Check that all other base pointers are the same as this one. 9338 LdBasePtr = LdPtr; 9339 } 9340 9341 // We found a potential memory operand to merge. 9342 LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0)); 9343 } 9344 9345 if (LoadNodes.size() < 2) 9346 return false; 9347 9348 // Scan the memory operations on the chain and find the first non-consecutive 9349 // load memory address. These variables hold the index in the store node 9350 // array. 9351 unsigned LastConsecutiveLoad = 0; 9352 // This variable refers to the size and not index in the array. 9353 unsigned LastLegalVectorType = 0; 9354 unsigned LastLegalIntegerType = 0; 9355 StartAddress = LoadNodes[0].OffsetFromBase; 9356 SDValue FirstChain = LoadNodes[0].MemNode->getChain(); 9357 for (unsigned i = 1; i < LoadNodes.size(); ++i) { 9358 // All loads much share the same chain. 9359 if (LoadNodes[i].MemNode->getChain() != FirstChain) 9360 break; 9361 9362 int64_t CurrAddress = LoadNodes[i].OffsetFromBase; 9363 if (CurrAddress - StartAddress != (ElementSizeBytes * i)) 9364 break; 9365 LastConsecutiveLoad = i; 9366 9367 // Find a legal type for the vector store. 9368 EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1); 9369 if (TLI.isTypeLegal(StoreTy)) 9370 LastLegalVectorType = i + 1; 9371 9372 // Find a legal type for the integer store. 9373 unsigned StoreBW = (i+1) * ElementSizeBytes * 8; 9374 StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW); 9375 if (TLI.isTypeLegal(StoreTy)) 9376 LastLegalIntegerType = i + 1; 9377 // Or check whether a truncstore and extload is legal. 9378 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) == 9379 TargetLowering::TypePromoteInteger) { 9380 EVT LegalizedStoredValueTy = 9381 TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy); 9382 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) && 9383 TLI.isLoadExtLegal(ISD::ZEXTLOAD, StoreTy) && 9384 TLI.isLoadExtLegal(ISD::SEXTLOAD, StoreTy) && 9385 TLI.isLoadExtLegal(ISD::EXTLOAD, StoreTy)) 9386 LastLegalIntegerType = i+1; 9387 } 9388 } 9389 9390 // Only use vector types if the vector type is larger than the integer type. 9391 // If they are the same, use integers. 9392 bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors; 9393 unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType); 9394 9395 // We add +1 here because the LastXXX variables refer to location while 9396 // the NumElem refers to array/index size. 9397 unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1; 9398 NumElem = std::min(LastLegalType, NumElem); 9399 9400 if (NumElem < 2) 9401 return false; 9402 9403 // The earliest Node in the DAG. 9404 unsigned EarliestNodeUsed = 0; 9405 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode; 9406 for (unsigned i=1; i<NumElem; ++i) { 9407 // Find a chain for the new wide-store operand. Notice that some 9408 // of the store nodes that we found may not be selected for inclusion 9409 // in the wide store. The chain we use needs to be the chain of the 9410 // earliest store node which is *used* and replaced by the wide store. 9411 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum) 9412 EarliestNodeUsed = i; 9413 } 9414 9415 // Find if it is better to use vectors or integers to load and store 9416 // to memory. 9417 EVT JointMemOpVT; 9418 if (UseVectorTy) { 9419 JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem); 9420 } else { 9421 unsigned StoreBW = NumElem * ElementSizeBytes * 8; 9422 JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW); 9423 } 9424 9425 SDLoc LoadDL(LoadNodes[0].MemNode); 9426 SDLoc StoreDL(StoreNodes[0].MemNode); 9427 9428 LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode); 9429 SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL, 9430 FirstLoad->getChain(), 9431 FirstLoad->getBasePtr(), 9432 FirstLoad->getPointerInfo(), 9433 false, false, false, 9434 FirstLoad->getAlignment()); 9435 9436 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), StoreDL, NewLoad, 9437 FirstInChain->getBasePtr(), 9438 FirstInChain->getPointerInfo(), false, false, 9439 FirstInChain->getAlignment()); 9440 9441 // Replace one of the loads with the new load. 9442 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode); 9443 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), 9444 SDValue(NewLoad.getNode(), 1)); 9445 9446 // Remove the rest of the load chains. 9447 for (unsigned i = 1; i < NumElem ; ++i) { 9448 // Replace all chain users of the old load nodes with the chain of the new 9449 // load node. 9450 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode); 9451 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain()); 9452 } 9453 9454 // Replace the first store with the new store. 9455 CombineTo(EarliestOp, NewStore); 9456 // Erase all other stores. 9457 for (unsigned i = 0; i < NumElem ; ++i) { 9458 // Remove all Store nodes. 9459 if (StoreNodes[i].MemNode == EarliestOp) 9460 continue; 9461 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 9462 DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain()); 9463 removeFromWorkList(St); 9464 DAG.DeleteNode(St); 9465 } 9466 9467 return true; 9468 } 9469 9470 SDValue DAGCombiner::visitSTORE(SDNode *N) { 9471 StoreSDNode *ST = cast<StoreSDNode>(N); 9472 SDValue Chain = ST->getChain(); 9473 SDValue Value = ST->getValue(); 9474 SDValue Ptr = ST->getBasePtr(); 9475 9476 // If this is a store of a bit convert, store the input value if the 9477 // resultant store does not need a higher alignment than the original. 9478 if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() && 9479 ST->isUnindexed()) { 9480 unsigned OrigAlign = ST->getAlignment(); 9481 EVT SVT = Value.getOperand(0).getValueType(); 9482 unsigned Align = TLI.getDataLayout()-> 9483 getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext())); 9484 if (Align <= OrigAlign && 9485 ((!LegalOperations && !ST->isVolatile()) || 9486 TLI.isOperationLegalOrCustom(ISD::STORE, SVT))) 9487 return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0), 9488 Ptr, ST->getPointerInfo(), ST->isVolatile(), 9489 ST->isNonTemporal(), OrigAlign, 9490 ST->getTBAAInfo()); 9491 } 9492 9493 // Turn 'store undef, Ptr' -> nothing. 9494 if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed()) 9495 return Chain; 9496 9497 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr' 9498 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) { 9499 // NOTE: If the original store is volatile, this transform must not increase 9500 // the number of stores. For example, on x86-32 an f64 can be stored in one 9501 // processor operation but an i64 (which is not legal) requires two. So the 9502 // transform should not be done in this case. 9503 if (Value.getOpcode() != ISD::TargetConstantFP) { 9504 SDValue Tmp; 9505 switch (CFP->getSimpleValueType(0).SimpleTy) { 9506 default: llvm_unreachable("Unknown FP type"); 9507 case MVT::f16: // We don't do this for these yet. 9508 case MVT::f80: 9509 case MVT::f128: 9510 case MVT::ppcf128: 9511 break; 9512 case MVT::f32: 9513 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) || 9514 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) { 9515 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF(). 9516 bitcastToAPInt().getZExtValue(), MVT::i32); 9517 return DAG.getStore(Chain, SDLoc(N), Tmp, 9518 Ptr, ST->getMemOperand()); 9519 } 9520 break; 9521 case MVT::f64: 9522 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations && 9523 !ST->isVolatile()) || 9524 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) { 9525 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt(). 9526 getZExtValue(), MVT::i64); 9527 return DAG.getStore(Chain, SDLoc(N), Tmp, 9528 Ptr, ST->getMemOperand()); 9529 } 9530 9531 if (!ST->isVolatile() && 9532 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) { 9533 // Many FP stores are not made apparent until after legalize, e.g. for 9534 // argument passing. Since this is so common, custom legalize the 9535 // 64-bit integer store into two 32-bit stores. 9536 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue(); 9537 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32); 9538 SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32); 9539 if (TLI.isBigEndian()) std::swap(Lo, Hi); 9540 9541 unsigned Alignment = ST->getAlignment(); 9542 bool isVolatile = ST->isVolatile(); 9543 bool isNonTemporal = ST->isNonTemporal(); 9544 const MDNode *TBAAInfo = ST->getTBAAInfo(); 9545 9546 SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo, 9547 Ptr, ST->getPointerInfo(), 9548 isVolatile, isNonTemporal, 9549 ST->getAlignment(), TBAAInfo); 9550 Ptr = DAG.getNode(ISD::ADD, SDLoc(N), Ptr.getValueType(), Ptr, 9551 DAG.getConstant(4, Ptr.getValueType())); 9552 Alignment = MinAlign(Alignment, 4U); 9553 SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi, 9554 Ptr, ST->getPointerInfo().getWithOffset(4), 9555 isVolatile, isNonTemporal, 9556 Alignment, TBAAInfo); 9557 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, 9558 St0, St1); 9559 } 9560 9561 break; 9562 } 9563 } 9564 } 9565 9566 // Try to infer better alignment information than the store already has. 9567 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) { 9568 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) { 9569 if (Align > ST->getAlignment()) 9570 return DAG.getTruncStore(Chain, SDLoc(N), Value, 9571 Ptr, ST->getPointerInfo(), ST->getMemoryVT(), 9572 ST->isVolatile(), ST->isNonTemporal(), Align, 9573 ST->getTBAAInfo()); 9574 } 9575 } 9576 9577 // Try transforming a pair floating point load / store ops to integer 9578 // load / store ops. 9579 SDValue NewST = TransformFPLoadStorePair(N); 9580 if (NewST.getNode()) 9581 return NewST; 9582 9583 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA : 9584 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA(); 9585 #ifndef NDEBUG 9586 if (CombinerAAOnlyFunc.getNumOccurrences() && 9587 CombinerAAOnlyFunc != DAG.getMachineFunction().getName()) 9588 UseAA = false; 9589 #endif 9590 if (UseAA && ST->isUnindexed()) { 9591 // Walk up chain skipping non-aliasing memory nodes. 9592 SDValue BetterChain = FindBetterChain(N, Chain); 9593 9594 // If there is a better chain. 9595 if (Chain != BetterChain) { 9596 SDValue ReplStore; 9597 9598 // Replace the chain to avoid dependency. 9599 if (ST->isTruncatingStore()) { 9600 ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr, 9601 ST->getMemoryVT(), ST->getMemOperand()); 9602 } else { 9603 ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr, 9604 ST->getMemOperand()); 9605 } 9606 9607 // Create token to keep both nodes around. 9608 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N), 9609 MVT::Other, Chain, ReplStore); 9610 9611 // Make sure the new and old chains are cleaned up. 9612 AddToWorkList(Token.getNode()); 9613 9614 // Don't add users to work list. 9615 return CombineTo(N, Token, false); 9616 } 9617 } 9618 9619 // Try transforming N to an indexed store. 9620 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N)) 9621 return SDValue(N, 0); 9622 9623 // FIXME: is there such a thing as a truncating indexed store? 9624 if (ST->isTruncatingStore() && ST->isUnindexed() && 9625 Value.getValueType().isInteger()) { 9626 // See if we can simplify the input to this truncstore with knowledge that 9627 // only the low bits are being used. For example: 9628 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8" 9629 SDValue Shorter = 9630 GetDemandedBits(Value, 9631 APInt::getLowBitsSet( 9632 Value.getValueType().getScalarType().getSizeInBits(), 9633 ST->getMemoryVT().getScalarType().getSizeInBits())); 9634 AddToWorkList(Value.getNode()); 9635 if (Shorter.getNode()) 9636 return DAG.getTruncStore(Chain, SDLoc(N), Shorter, 9637 Ptr, ST->getMemoryVT(), ST->getMemOperand()); 9638 9639 // Otherwise, see if we can simplify the operation with 9640 // SimplifyDemandedBits, which only works if the value has a single use. 9641 if (SimplifyDemandedBits(Value, 9642 APInt::getLowBitsSet( 9643 Value.getValueType().getScalarType().getSizeInBits(), 9644 ST->getMemoryVT().getScalarType().getSizeInBits()))) 9645 return SDValue(N, 0); 9646 } 9647 9648 // If this is a load followed by a store to the same location, then the store 9649 // is dead/noop. 9650 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) { 9651 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() && 9652 ST->isUnindexed() && !ST->isVolatile() && 9653 // There can't be any side effects between the load and store, such as 9654 // a call or store. 9655 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) { 9656 // The store is dead, remove it. 9657 return Chain; 9658 } 9659 } 9660 9661 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a 9662 // truncating store. We can do this even if this is already a truncstore. 9663 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE) 9664 && Value.getNode()->hasOneUse() && ST->isUnindexed() && 9665 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(), 9666 ST->getMemoryVT())) { 9667 return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0), 9668 Ptr, ST->getMemoryVT(), ST->getMemOperand()); 9669 } 9670 9671 // Only perform this optimization before the types are legal, because we 9672 // don't want to perform this optimization on every DAGCombine invocation. 9673 if (!LegalTypes) { 9674 bool EverChanged = false; 9675 9676 do { 9677 // There can be multiple store sequences on the same chain. 9678 // Keep trying to merge store sequences until we are unable to do so 9679 // or until we merge the last store on the chain. 9680 bool Changed = MergeConsecutiveStores(ST); 9681 EverChanged |= Changed; 9682 if (!Changed) break; 9683 } while (ST->getOpcode() != ISD::DELETED_NODE); 9684 9685 if (EverChanged) 9686 return SDValue(N, 0); 9687 } 9688 9689 return ReduceLoadOpStoreWidth(N); 9690 } 9691 9692 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) { 9693 SDValue InVec = N->getOperand(0); 9694 SDValue InVal = N->getOperand(1); 9695 SDValue EltNo = N->getOperand(2); 9696 SDLoc dl(N); 9697 9698 // If the inserted element is an UNDEF, just use the input vector. 9699 if (InVal.getOpcode() == ISD::UNDEF) 9700 return InVec; 9701 9702 EVT VT = InVec.getValueType(); 9703 9704 // If we can't generate a legal BUILD_VECTOR, exit 9705 if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT)) 9706 return SDValue(); 9707 9708 // Check that we know which element is being inserted 9709 if (!isa<ConstantSDNode>(EltNo)) 9710 return SDValue(); 9711 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue(); 9712 9713 // Canonicalize insert_vector_elt dag nodes. 9714 // Example: 9715 // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1) 9716 // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0) 9717 // 9718 // Do this only if the child insert_vector node has one use; also 9719 // do this only if indices are both constants and Idx1 < Idx0. 9720 if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse() 9721 && isa<ConstantSDNode>(InVec.getOperand(2))) { 9722 unsigned OtherElt = 9723 cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue(); 9724 if (Elt < OtherElt) { 9725 // Swap nodes. 9726 SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT, 9727 InVec.getOperand(0), InVal, EltNo); 9728 AddToWorkList(NewOp.getNode()); 9729 return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()), 9730 VT, NewOp, InVec.getOperand(1), InVec.getOperand(2)); 9731 } 9732 } 9733 9734 // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially 9735 // be converted to a BUILD_VECTOR). Fill in the Ops vector with the 9736 // vector elements. 9737 SmallVector<SDValue, 8> Ops; 9738 // Do not combine these two vectors if the output vector will not replace 9739 // the input vector. 9740 if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) { 9741 Ops.append(InVec.getNode()->op_begin(), 9742 InVec.getNode()->op_end()); 9743 } else if (InVec.getOpcode() == ISD::UNDEF) { 9744 unsigned NElts = VT.getVectorNumElements(); 9745 Ops.append(NElts, DAG.getUNDEF(InVal.getValueType())); 9746 } else { 9747 return SDValue(); 9748 } 9749 9750 // Insert the element 9751 if (Elt < Ops.size()) { 9752 // All the operands of BUILD_VECTOR must have the same type; 9753 // we enforce that here. 9754 EVT OpVT = Ops[0].getValueType(); 9755 if (InVal.getValueType() != OpVT) 9756 InVal = OpVT.bitsGT(InVal.getValueType()) ? 9757 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) : 9758 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal); 9759 Ops[Elt] = InVal; 9760 } 9761 9762 // Return the new vector 9763 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops); 9764 } 9765 9766 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad( 9767 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) { 9768 EVT ResultVT = EVE->getValueType(0); 9769 EVT VecEltVT = InVecVT.getVectorElementType(); 9770 unsigned Align = OriginalLoad->getAlignment(); 9771 unsigned NewAlign = TLI.getDataLayout()->getABITypeAlignment( 9772 VecEltVT.getTypeForEVT(*DAG.getContext())); 9773 9774 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT)) 9775 return SDValue(); 9776 9777 Align = NewAlign; 9778 9779 SDValue NewPtr = OriginalLoad->getBasePtr(); 9780 SDValue Offset; 9781 EVT PtrType = NewPtr.getValueType(); 9782 MachinePointerInfo MPI; 9783 if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) { 9784 int Elt = ConstEltNo->getZExtValue(); 9785 unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8; 9786 if (TLI.isBigEndian()) 9787 PtrOff = InVecVT.getSizeInBits() / 8 - PtrOff; 9788 Offset = DAG.getConstant(PtrOff, PtrType); 9789 MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff); 9790 } else { 9791 Offset = DAG.getNode( 9792 ISD::MUL, SDLoc(EVE), EltNo.getValueType(), EltNo, 9793 DAG.getConstant(VecEltVT.getStoreSize(), EltNo.getValueType())); 9794 if (TLI.isBigEndian()) 9795 Offset = DAG.getNode( 9796 ISD::SUB, SDLoc(EVE), EltNo.getValueType(), 9797 DAG.getConstant(InVecVT.getStoreSize(), EltNo.getValueType()), Offset); 9798 MPI = OriginalLoad->getPointerInfo(); 9799 } 9800 NewPtr = DAG.getNode(ISD::ADD, SDLoc(EVE), PtrType, NewPtr, Offset); 9801 9802 // The replacement we need to do here is a little tricky: we need to 9803 // replace an extractelement of a load with a load. 9804 // Use ReplaceAllUsesOfValuesWith to do the replacement. 9805 // Note that this replacement assumes that the extractvalue is the only 9806 // use of the load; that's okay because we don't want to perform this 9807 // transformation in other cases anyway. 9808 SDValue Load; 9809 SDValue Chain; 9810 if (ResultVT.bitsGT(VecEltVT)) { 9811 // If the result type of vextract is wider than the load, then issue an 9812 // extending load instead. 9813 ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, VecEltVT) 9814 ? ISD::ZEXTLOAD 9815 : ISD::EXTLOAD; 9816 Load = DAG.getExtLoad(ExtType, SDLoc(EVE), ResultVT, OriginalLoad->getChain(), 9817 NewPtr, MPI, VecEltVT, OriginalLoad->isVolatile(), 9818 OriginalLoad->isNonTemporal(), Align, 9819 OriginalLoad->getTBAAInfo()); 9820 Chain = Load.getValue(1); 9821 } else { 9822 Load = DAG.getLoad( 9823 VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, MPI, 9824 OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(), 9825 OriginalLoad->isInvariant(), Align, OriginalLoad->getTBAAInfo()); 9826 Chain = Load.getValue(1); 9827 if (ResultVT.bitsLT(VecEltVT)) 9828 Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load); 9829 else 9830 Load = DAG.getNode(ISD::BITCAST, SDLoc(EVE), ResultVT, Load); 9831 } 9832 WorkListRemover DeadNodes(*this); 9833 SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) }; 9834 SDValue To[] = { Load, Chain }; 9835 DAG.ReplaceAllUsesOfValuesWith(From, To, 2); 9836 // Since we're explicitly calling ReplaceAllUses, add the new node to the 9837 // worklist explicitly as well. 9838 AddToWorkList(Load.getNode()); 9839 AddUsersToWorkList(Load.getNode()); // Add users too 9840 // Make sure to revisit this node to clean it up; it will usually be dead. 9841 AddToWorkList(EVE); 9842 ++OpsNarrowed; 9843 return SDValue(EVE, 0); 9844 } 9845 9846 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) { 9847 // (vextract (scalar_to_vector val, 0) -> val 9848 SDValue InVec = N->getOperand(0); 9849 EVT VT = InVec.getValueType(); 9850 EVT NVT = N->getValueType(0); 9851 9852 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) { 9853 // Check if the result type doesn't match the inserted element type. A 9854 // SCALAR_TO_VECTOR may truncate the inserted element and the 9855 // EXTRACT_VECTOR_ELT may widen the extracted vector. 9856 SDValue InOp = InVec.getOperand(0); 9857 if (InOp.getValueType() != NVT) { 9858 assert(InOp.getValueType().isInteger() && NVT.isInteger()); 9859 return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT); 9860 } 9861 return InOp; 9862 } 9863 9864 SDValue EltNo = N->getOperand(1); 9865 bool ConstEltNo = isa<ConstantSDNode>(EltNo); 9866 9867 // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT. 9868 // We only perform this optimization before the op legalization phase because 9869 // we may introduce new vector instructions which are not backed by TD 9870 // patterns. For example on AVX, extracting elements from a wide vector 9871 // without using extract_subvector. However, if we can find an underlying 9872 // scalar value, then we can always use that. 9873 if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE 9874 && ConstEltNo) { 9875 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue(); 9876 int NumElem = VT.getVectorNumElements(); 9877 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec); 9878 // Find the new index to extract from. 9879 int OrigElt = SVOp->getMaskElt(Elt); 9880 9881 // Extracting an undef index is undef. 9882 if (OrigElt == -1) 9883 return DAG.getUNDEF(NVT); 9884 9885 // Select the right vector half to extract from. 9886 SDValue SVInVec; 9887 if (OrigElt < NumElem) { 9888 SVInVec = InVec->getOperand(0); 9889 } else { 9890 SVInVec = InVec->getOperand(1); 9891 OrigElt -= NumElem; 9892 } 9893 9894 if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) { 9895 SDValue InOp = SVInVec.getOperand(OrigElt); 9896 if (InOp.getValueType() != NVT) { 9897 assert(InOp.getValueType().isInteger() && NVT.isInteger()); 9898 InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT); 9899 } 9900 9901 return InOp; 9902 } 9903 9904 // FIXME: We should handle recursing on other vector shuffles and 9905 // scalar_to_vector here as well. 9906 9907 if (!LegalOperations) { 9908 EVT IndexTy = TLI.getVectorIdxTy(); 9909 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT, 9910 SVInVec, DAG.getConstant(OrigElt, IndexTy)); 9911 } 9912 } 9913 9914 bool BCNumEltsChanged = false; 9915 EVT ExtVT = VT.getVectorElementType(); 9916 EVT LVT = ExtVT; 9917 9918 // If the result of load has to be truncated, then it's not necessarily 9919 // profitable. 9920 if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT)) 9921 return SDValue(); 9922 9923 if (InVec.getOpcode() == ISD::BITCAST) { 9924 // Don't duplicate a load with other uses. 9925 if (!InVec.hasOneUse()) 9926 return SDValue(); 9927 9928 EVT BCVT = InVec.getOperand(0).getValueType(); 9929 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType())) 9930 return SDValue(); 9931 if (VT.getVectorNumElements() != BCVT.getVectorNumElements()) 9932 BCNumEltsChanged = true; 9933 InVec = InVec.getOperand(0); 9934 ExtVT = BCVT.getVectorElementType(); 9935 } 9936 9937 // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size) 9938 if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() && 9939 ISD::isNormalLoad(InVec.getNode())) { 9940 SDValue Index = N->getOperand(1); 9941 if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec)) 9942 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index, 9943 OrigLoad); 9944 } 9945 9946 // Perform only after legalization to ensure build_vector / vector_shuffle 9947 // optimizations have already been done. 9948 if (!LegalOperations) return SDValue(); 9949 9950 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size) 9951 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size) 9952 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr) 9953 9954 if (ConstEltNo) { 9955 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue(); 9956 9957 LoadSDNode *LN0 = nullptr; 9958 const ShuffleVectorSDNode *SVN = nullptr; 9959 if (ISD::isNormalLoad(InVec.getNode())) { 9960 LN0 = cast<LoadSDNode>(InVec); 9961 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR && 9962 InVec.getOperand(0).getValueType() == ExtVT && 9963 ISD::isNormalLoad(InVec.getOperand(0).getNode())) { 9964 // Don't duplicate a load with other uses. 9965 if (!InVec.hasOneUse()) 9966 return SDValue(); 9967 9968 LN0 = cast<LoadSDNode>(InVec.getOperand(0)); 9969 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) { 9970 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1) 9971 // => 9972 // (load $addr+1*size) 9973 9974 // Don't duplicate a load with other uses. 9975 if (!InVec.hasOneUse()) 9976 return SDValue(); 9977 9978 // If the bit convert changed the number of elements, it is unsafe 9979 // to examine the mask. 9980 if (BCNumEltsChanged) 9981 return SDValue(); 9982 9983 // Select the input vector, guarding against out of range extract vector. 9984 unsigned NumElems = VT.getVectorNumElements(); 9985 int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt); 9986 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1); 9987 9988 if (InVec.getOpcode() == ISD::BITCAST) { 9989 // Don't duplicate a load with other uses. 9990 if (!InVec.hasOneUse()) 9991 return SDValue(); 9992 9993 InVec = InVec.getOperand(0); 9994 } 9995 if (ISD::isNormalLoad(InVec.getNode())) { 9996 LN0 = cast<LoadSDNode>(InVec); 9997 Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems; 9998 EltNo = DAG.getConstant(Elt, EltNo.getValueType()); 9999 } 10000 } 10001 10002 // Make sure we found a non-volatile load and the extractelement is 10003 // the only use. 10004 if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile()) 10005 return SDValue(); 10006 10007 // If Idx was -1 above, Elt is going to be -1, so just return undef. 10008 if (Elt == -1) 10009 return DAG.getUNDEF(LVT); 10010 10011 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0); 10012 } 10013 10014 return SDValue(); 10015 } 10016 10017 // Simplify (build_vec (ext )) to (bitcast (build_vec )) 10018 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) { 10019 // We perform this optimization post type-legalization because 10020 // the type-legalizer often scalarizes integer-promoted vectors. 10021 // Performing this optimization before may create bit-casts which 10022 // will be type-legalized to complex code sequences. 10023 // We perform this optimization only before the operation legalizer because we 10024 // may introduce illegal operations. 10025 if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes) 10026 return SDValue(); 10027 10028 unsigned NumInScalars = N->getNumOperands(); 10029 SDLoc dl(N); 10030 EVT VT = N->getValueType(0); 10031 10032 // Check to see if this is a BUILD_VECTOR of a bunch of values 10033 // which come from any_extend or zero_extend nodes. If so, we can create 10034 // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR 10035 // optimizations. We do not handle sign-extend because we can't fill the sign 10036 // using shuffles. 10037 EVT SourceType = MVT::Other; 10038 bool AllAnyExt = true; 10039 10040 for (unsigned i = 0; i != NumInScalars; ++i) { 10041 SDValue In = N->getOperand(i); 10042 // Ignore undef inputs. 10043 if (In.getOpcode() == ISD::UNDEF) continue; 10044 10045 bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND; 10046 bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND; 10047 10048 // Abort if the element is not an extension. 10049 if (!ZeroExt && !AnyExt) { 10050 SourceType = MVT::Other; 10051 break; 10052 } 10053 10054 // The input is a ZeroExt or AnyExt. Check the original type. 10055 EVT InTy = In.getOperand(0).getValueType(); 10056 10057 // Check that all of the widened source types are the same. 10058 if (SourceType == MVT::Other) 10059 // First time. 10060 SourceType = InTy; 10061 else if (InTy != SourceType) { 10062 // Multiple income types. Abort. 10063 SourceType = MVT::Other; 10064 break; 10065 } 10066 10067 // Check if all of the extends are ANY_EXTENDs. 10068 AllAnyExt &= AnyExt; 10069 } 10070 10071 // In order to have valid types, all of the inputs must be extended from the 10072 // same source type and all of the inputs must be any or zero extend. 10073 // Scalar sizes must be a power of two. 10074 EVT OutScalarTy = VT.getScalarType(); 10075 bool ValidTypes = SourceType != MVT::Other && 10076 isPowerOf2_32(OutScalarTy.getSizeInBits()) && 10077 isPowerOf2_32(SourceType.getSizeInBits()); 10078 10079 // Create a new simpler BUILD_VECTOR sequence which other optimizations can 10080 // turn into a single shuffle instruction. 10081 if (!ValidTypes) 10082 return SDValue(); 10083 10084 bool isLE = TLI.isLittleEndian(); 10085 unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits(); 10086 assert(ElemRatio > 1 && "Invalid element size ratio"); 10087 SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType): 10088 DAG.getConstant(0, SourceType); 10089 10090 unsigned NewBVElems = ElemRatio * VT.getVectorNumElements(); 10091 SmallVector<SDValue, 8> Ops(NewBVElems, Filler); 10092 10093 // Populate the new build_vector 10094 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 10095 SDValue Cast = N->getOperand(i); 10096 assert((Cast.getOpcode() == ISD::ANY_EXTEND || 10097 Cast.getOpcode() == ISD::ZERO_EXTEND || 10098 Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode"); 10099 SDValue In; 10100 if (Cast.getOpcode() == ISD::UNDEF) 10101 In = DAG.getUNDEF(SourceType); 10102 else 10103 In = Cast->getOperand(0); 10104 unsigned Index = isLE ? (i * ElemRatio) : 10105 (i * ElemRatio + (ElemRatio - 1)); 10106 10107 assert(Index < Ops.size() && "Invalid index"); 10108 Ops[Index] = In; 10109 } 10110 10111 // The type of the new BUILD_VECTOR node. 10112 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems); 10113 assert(VecVT.getSizeInBits() == VT.getSizeInBits() && 10114 "Invalid vector size"); 10115 // Check if the new vector type is legal. 10116 if (!isTypeLegal(VecVT)) return SDValue(); 10117 10118 // Make the new BUILD_VECTOR. 10119 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops); 10120 10121 // The new BUILD_VECTOR node has the potential to be further optimized. 10122 AddToWorkList(BV.getNode()); 10123 // Bitcast to the desired type. 10124 return DAG.getNode(ISD::BITCAST, dl, VT, BV); 10125 } 10126 10127 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) { 10128 EVT VT = N->getValueType(0); 10129 10130 unsigned NumInScalars = N->getNumOperands(); 10131 SDLoc dl(N); 10132 10133 EVT SrcVT = MVT::Other; 10134 unsigned Opcode = ISD::DELETED_NODE; 10135 unsigned NumDefs = 0; 10136 10137 for (unsigned i = 0; i != NumInScalars; ++i) { 10138 SDValue In = N->getOperand(i); 10139 unsigned Opc = In.getOpcode(); 10140 10141 if (Opc == ISD::UNDEF) 10142 continue; 10143 10144 // If all scalar values are floats and converted from integers. 10145 if (Opcode == ISD::DELETED_NODE && 10146 (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) { 10147 Opcode = Opc; 10148 } 10149 10150 if (Opc != Opcode) 10151 return SDValue(); 10152 10153 EVT InVT = In.getOperand(0).getValueType(); 10154 10155 // If all scalar values are typed differently, bail out. It's chosen to 10156 // simplify BUILD_VECTOR of integer types. 10157 if (SrcVT == MVT::Other) 10158 SrcVT = InVT; 10159 if (SrcVT != InVT) 10160 return SDValue(); 10161 NumDefs++; 10162 } 10163 10164 // If the vector has just one element defined, it's not worth to fold it into 10165 // a vectorized one. 10166 if (NumDefs < 2) 10167 return SDValue(); 10168 10169 assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP) 10170 && "Should only handle conversion from integer to float."); 10171 assert(SrcVT != MVT::Other && "Cannot determine source type!"); 10172 10173 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars); 10174 10175 if (!TLI.isOperationLegalOrCustom(Opcode, NVT)) 10176 return SDValue(); 10177 10178 SmallVector<SDValue, 8> Opnds; 10179 for (unsigned i = 0; i != NumInScalars; ++i) { 10180 SDValue In = N->getOperand(i); 10181 10182 if (In.getOpcode() == ISD::UNDEF) 10183 Opnds.push_back(DAG.getUNDEF(SrcVT)); 10184 else 10185 Opnds.push_back(In.getOperand(0)); 10186 } 10187 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds); 10188 AddToWorkList(BV.getNode()); 10189 10190 return DAG.getNode(Opcode, dl, VT, BV); 10191 } 10192 10193 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) { 10194 unsigned NumInScalars = N->getNumOperands(); 10195 SDLoc dl(N); 10196 EVT VT = N->getValueType(0); 10197 10198 // A vector built entirely of undefs is undef. 10199 if (ISD::allOperandsUndef(N)) 10200 return DAG.getUNDEF(VT); 10201 10202 SDValue V = reduceBuildVecExtToExtBuildVec(N); 10203 if (V.getNode()) 10204 return V; 10205 10206 V = reduceBuildVecConvertToConvertBuildVec(N); 10207 if (V.getNode()) 10208 return V; 10209 10210 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT 10211 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from 10212 // at most two distinct vectors, turn this into a shuffle node. 10213 10214 // May only combine to shuffle after legalize if shuffle is legal. 10215 if (LegalOperations && 10216 !TLI.isOperationLegalOrCustom(ISD::VECTOR_SHUFFLE, VT)) 10217 return SDValue(); 10218 10219 SDValue VecIn1, VecIn2; 10220 for (unsigned i = 0; i != NumInScalars; ++i) { 10221 // Ignore undef inputs. 10222 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue; 10223 10224 // If this input is something other than a EXTRACT_VECTOR_ELT with a 10225 // constant index, bail out. 10226 if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT || 10227 !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) { 10228 VecIn1 = VecIn2 = SDValue(nullptr, 0); 10229 break; 10230 } 10231 10232 // We allow up to two distinct input vectors. 10233 SDValue ExtractedFromVec = N->getOperand(i).getOperand(0); 10234 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2) 10235 continue; 10236 10237 if (!VecIn1.getNode()) { 10238 VecIn1 = ExtractedFromVec; 10239 } else if (!VecIn2.getNode()) { 10240 VecIn2 = ExtractedFromVec; 10241 } else { 10242 // Too many inputs. 10243 VecIn1 = VecIn2 = SDValue(nullptr, 0); 10244 break; 10245 } 10246 } 10247 10248 // If everything is good, we can make a shuffle operation. 10249 if (VecIn1.getNode()) { 10250 SmallVector<int, 8> Mask; 10251 for (unsigned i = 0; i != NumInScalars; ++i) { 10252 if (N->getOperand(i).getOpcode() == ISD::UNDEF) { 10253 Mask.push_back(-1); 10254 continue; 10255 } 10256 10257 // If extracting from the first vector, just use the index directly. 10258 SDValue Extract = N->getOperand(i); 10259 SDValue ExtVal = Extract.getOperand(1); 10260 if (Extract.getOperand(0) == VecIn1) { 10261 unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue(); 10262 if (ExtIndex > VT.getVectorNumElements()) 10263 return SDValue(); 10264 10265 Mask.push_back(ExtIndex); 10266 continue; 10267 } 10268 10269 // Otherwise, use InIdx + VecSize 10270 unsigned Idx = cast<ConstantSDNode>(ExtVal)->getZExtValue(); 10271 Mask.push_back(Idx+NumInScalars); 10272 } 10273 10274 // We can't generate a shuffle node with mismatched input and output types. 10275 // Attempt to transform a single input vector to the correct type. 10276 if ((VT != VecIn1.getValueType())) { 10277 // We don't support shuffeling between TWO values of different types. 10278 if (VecIn2.getNode()) 10279 return SDValue(); 10280 10281 // We only support widening of vectors which are half the size of the 10282 // output registers. For example XMM->YMM widening on X86 with AVX. 10283 if (VecIn1.getValueType().getSizeInBits()*2 != VT.getSizeInBits()) 10284 return SDValue(); 10285 10286 // If the input vector type has a different base type to the output 10287 // vector type, bail out. 10288 if (VecIn1.getValueType().getVectorElementType() != 10289 VT.getVectorElementType()) 10290 return SDValue(); 10291 10292 // Widen the input vector by adding undef values. 10293 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, 10294 VecIn1, DAG.getUNDEF(VecIn1.getValueType())); 10295 } 10296 10297 // If VecIn2 is unused then change it to undef. 10298 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT); 10299 10300 // Check that we were able to transform all incoming values to the same 10301 // type. 10302 if (VecIn2.getValueType() != VecIn1.getValueType() || 10303 VecIn1.getValueType() != VT) 10304 return SDValue(); 10305 10306 // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes. 10307 if (!isTypeLegal(VT)) 10308 return SDValue(); 10309 10310 // Return the new VECTOR_SHUFFLE node. 10311 SDValue Ops[2]; 10312 Ops[0] = VecIn1; 10313 Ops[1] = VecIn2; 10314 return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]); 10315 } 10316 10317 return SDValue(); 10318 } 10319 10320 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) { 10321 // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of 10322 // EXTRACT_SUBVECTOR operations. If so, and if the EXTRACT_SUBVECTOR vector 10323 // inputs come from at most two distinct vectors, turn this into a shuffle 10324 // node. 10325 10326 // If we only have one input vector, we don't need to do any concatenation. 10327 if (N->getNumOperands() == 1) 10328 return N->getOperand(0); 10329 10330 // Check if all of the operands are undefs. 10331 EVT VT = N->getValueType(0); 10332 if (ISD::allOperandsUndef(N)) 10333 return DAG.getUNDEF(VT); 10334 10335 // Optimize concat_vectors where one of the vectors is undef. 10336 if (N->getNumOperands() == 2 && 10337 N->getOperand(1)->getOpcode() == ISD::UNDEF) { 10338 SDValue In = N->getOperand(0); 10339 assert(In.getValueType().isVector() && "Must concat vectors"); 10340 10341 // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr). 10342 if (In->getOpcode() == ISD::BITCAST && 10343 !In->getOperand(0)->getValueType(0).isVector()) { 10344 SDValue Scalar = In->getOperand(0); 10345 EVT SclTy = Scalar->getValueType(0); 10346 10347 if (!SclTy.isFloatingPoint() && !SclTy.isInteger()) 10348 return SDValue(); 10349 10350 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy, 10351 VT.getSizeInBits() / SclTy.getSizeInBits()); 10352 if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType())) 10353 return SDValue(); 10354 10355 SDLoc dl = SDLoc(N); 10356 SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar); 10357 return DAG.getNode(ISD::BITCAST, dl, VT, Res); 10358 } 10359 } 10360 10361 // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...)) 10362 // -> (BUILD_VECTOR A, B, ..., C, D, ...) 10363 if (N->getNumOperands() == 2 && 10364 N->getOperand(0).getOpcode() == ISD::BUILD_VECTOR && 10365 N->getOperand(1).getOpcode() == ISD::BUILD_VECTOR) { 10366 EVT VT = N->getValueType(0); 10367 SDValue N0 = N->getOperand(0); 10368 SDValue N1 = N->getOperand(1); 10369 SmallVector<SDValue, 8> Opnds; 10370 unsigned BuildVecNumElts = N0.getNumOperands(); 10371 10372 for (unsigned i = 0; i != BuildVecNumElts; ++i) 10373 Opnds.push_back(N0.getOperand(i)); 10374 for (unsigned i = 0; i != BuildVecNumElts; ++i) 10375 Opnds.push_back(N1.getOperand(i)); 10376 10377 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds); 10378 } 10379 10380 // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR 10381 // nodes often generate nop CONCAT_VECTOR nodes. 10382 // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that 10383 // place the incoming vectors at the exact same location. 10384 SDValue SingleSource = SDValue(); 10385 unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements(); 10386 10387 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 10388 SDValue Op = N->getOperand(i); 10389 10390 if (Op.getOpcode() == ISD::UNDEF) 10391 continue; 10392 10393 // Check if this is the identity extract: 10394 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR) 10395 return SDValue(); 10396 10397 // Find the single incoming vector for the extract_subvector. 10398 if (SingleSource.getNode()) { 10399 if (Op.getOperand(0) != SingleSource) 10400 return SDValue(); 10401 } else { 10402 SingleSource = Op.getOperand(0); 10403 10404 // Check the source type is the same as the type of the result. 10405 // If not, this concat may extend the vector, so we can not 10406 // optimize it away. 10407 if (SingleSource.getValueType() != N->getValueType(0)) 10408 return SDValue(); 10409 } 10410 10411 unsigned IdentityIndex = i * PartNumElem; 10412 ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 10413 // The extract index must be constant. 10414 if (!CS) 10415 return SDValue(); 10416 10417 // Check that we are reading from the identity index. 10418 if (CS->getZExtValue() != IdentityIndex) 10419 return SDValue(); 10420 } 10421 10422 if (SingleSource.getNode()) 10423 return SingleSource; 10424 10425 return SDValue(); 10426 } 10427 10428 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) { 10429 EVT NVT = N->getValueType(0); 10430 SDValue V = N->getOperand(0); 10431 10432 if (V->getOpcode() == ISD::CONCAT_VECTORS) { 10433 // Combine: 10434 // (extract_subvec (concat V1, V2, ...), i) 10435 // Into: 10436 // Vi if possible 10437 // Only operand 0 is checked as 'concat' assumes all inputs of the same 10438 // type. 10439 if (V->getOperand(0).getValueType() != NVT) 10440 return SDValue(); 10441 unsigned Idx = dyn_cast<ConstantSDNode>(N->getOperand(1))->getZExtValue(); 10442 unsigned NumElems = NVT.getVectorNumElements(); 10443 assert((Idx % NumElems) == 0 && 10444 "IDX in concat is not a multiple of the result vector length."); 10445 return V->getOperand(Idx / NumElems); 10446 } 10447 10448 // Skip bitcasting 10449 if (V->getOpcode() == ISD::BITCAST) 10450 V = V.getOperand(0); 10451 10452 if (V->getOpcode() == ISD::INSERT_SUBVECTOR) { 10453 SDLoc dl(N); 10454 // Handle only simple case where vector being inserted and vector 10455 // being extracted are of same type, and are half size of larger vectors. 10456 EVT BigVT = V->getOperand(0).getValueType(); 10457 EVT SmallVT = V->getOperand(1).getValueType(); 10458 if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits()) 10459 return SDValue(); 10460 10461 // Only handle cases where both indexes are constants with the same type. 10462 ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1)); 10463 ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2)); 10464 10465 if (InsIdx && ExtIdx && 10466 InsIdx->getValueType(0).getSizeInBits() <= 64 && 10467 ExtIdx->getValueType(0).getSizeInBits() <= 64) { 10468 // Combine: 10469 // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx) 10470 // Into: 10471 // indices are equal or bit offsets are equal => V1 10472 // otherwise => (extract_subvec V1, ExtIdx) 10473 if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() == 10474 ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits()) 10475 return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1)); 10476 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT, 10477 DAG.getNode(ISD::BITCAST, dl, 10478 N->getOperand(0).getValueType(), 10479 V->getOperand(0)), N->getOperand(1)); 10480 } 10481 } 10482 10483 return SDValue(); 10484 } 10485 10486 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat. 10487 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) { 10488 EVT VT = N->getValueType(0); 10489 unsigned NumElts = VT.getVectorNumElements(); 10490 10491 SDValue N0 = N->getOperand(0); 10492 SDValue N1 = N->getOperand(1); 10493 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N); 10494 10495 SmallVector<SDValue, 4> Ops; 10496 EVT ConcatVT = N0.getOperand(0).getValueType(); 10497 unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements(); 10498 unsigned NumConcats = NumElts / NumElemsPerConcat; 10499 10500 // Look at every vector that's inserted. We're looking for exact 10501 // subvector-sized copies from a concatenated vector 10502 for (unsigned I = 0; I != NumConcats; ++I) { 10503 // Make sure we're dealing with a copy. 10504 unsigned Begin = I * NumElemsPerConcat; 10505 bool AllUndef = true, NoUndef = true; 10506 for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) { 10507 if (SVN->getMaskElt(J) >= 0) 10508 AllUndef = false; 10509 else 10510 NoUndef = false; 10511 } 10512 10513 if (NoUndef) { 10514 if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0) 10515 return SDValue(); 10516 10517 for (unsigned J = 1; J != NumElemsPerConcat; ++J) 10518 if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J)) 10519 return SDValue(); 10520 10521 unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat; 10522 if (FirstElt < N0.getNumOperands()) 10523 Ops.push_back(N0.getOperand(FirstElt)); 10524 else 10525 Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands())); 10526 10527 } else if (AllUndef) { 10528 Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType())); 10529 } else { // Mixed with general masks and undefs, can't do optimization. 10530 return SDValue(); 10531 } 10532 } 10533 10534 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops); 10535 } 10536 10537 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) { 10538 EVT VT = N->getValueType(0); 10539 unsigned NumElts = VT.getVectorNumElements(); 10540 10541 SDValue N0 = N->getOperand(0); 10542 SDValue N1 = N->getOperand(1); 10543 10544 assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG"); 10545 10546 // Canonicalize shuffle undef, undef -> undef 10547 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF) 10548 return DAG.getUNDEF(VT); 10549 10550 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N); 10551 10552 // Canonicalize shuffle v, v -> v, undef 10553 if (N0 == N1) { 10554 SmallVector<int, 8> NewMask; 10555 for (unsigned i = 0; i != NumElts; ++i) { 10556 int Idx = SVN->getMaskElt(i); 10557 if (Idx >= (int)NumElts) Idx -= NumElts; 10558 NewMask.push_back(Idx); 10559 } 10560 return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT), 10561 &NewMask[0]); 10562 } 10563 10564 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask. 10565 if (N0.getOpcode() == ISD::UNDEF) { 10566 SmallVector<int, 8> NewMask; 10567 for (unsigned i = 0; i != NumElts; ++i) { 10568 int Idx = SVN->getMaskElt(i); 10569 if (Idx >= 0) { 10570 if (Idx >= (int)NumElts) 10571 Idx -= NumElts; 10572 else 10573 Idx = -1; // remove reference to lhs 10574 } 10575 NewMask.push_back(Idx); 10576 } 10577 return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT), 10578 &NewMask[0]); 10579 } 10580 10581 // Remove references to rhs if it is undef 10582 if (N1.getOpcode() == ISD::UNDEF) { 10583 bool Changed = false; 10584 SmallVector<int, 8> NewMask; 10585 for (unsigned i = 0; i != NumElts; ++i) { 10586 int Idx = SVN->getMaskElt(i); 10587 if (Idx >= (int)NumElts) { 10588 Idx = -1; 10589 Changed = true; 10590 } 10591 NewMask.push_back(Idx); 10592 } 10593 if (Changed) 10594 return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]); 10595 } 10596 10597 // If it is a splat, check if the argument vector is another splat or a 10598 // build_vector with all scalar elements the same. 10599 if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) { 10600 SDNode *V = N0.getNode(); 10601 10602 // If this is a bit convert that changes the element type of the vector but 10603 // not the number of vector elements, look through it. Be careful not to 10604 // look though conversions that change things like v4f32 to v2f64. 10605 if (V->getOpcode() == ISD::BITCAST) { 10606 SDValue ConvInput = V->getOperand(0); 10607 if (ConvInput.getValueType().isVector() && 10608 ConvInput.getValueType().getVectorNumElements() == NumElts) 10609 V = ConvInput.getNode(); 10610 } 10611 10612 if (V->getOpcode() == ISD::BUILD_VECTOR) { 10613 assert(V->getNumOperands() == NumElts && 10614 "BUILD_VECTOR has wrong number of operands"); 10615 SDValue Base; 10616 bool AllSame = true; 10617 for (unsigned i = 0; i != NumElts; ++i) { 10618 if (V->getOperand(i).getOpcode() != ISD::UNDEF) { 10619 Base = V->getOperand(i); 10620 break; 10621 } 10622 } 10623 // Splat of <u, u, u, u>, return <u, u, u, u> 10624 if (!Base.getNode()) 10625 return N0; 10626 for (unsigned i = 0; i != NumElts; ++i) { 10627 if (V->getOperand(i) != Base) { 10628 AllSame = false; 10629 break; 10630 } 10631 } 10632 // Splat of <x, x, x, x>, return <x, x, x, x> 10633 if (AllSame) 10634 return N0; 10635 } 10636 } 10637 10638 if (N0.getOpcode() == ISD::CONCAT_VECTORS && 10639 Level < AfterLegalizeVectorOps && 10640 (N1.getOpcode() == ISD::UNDEF || 10641 (N1.getOpcode() == ISD::CONCAT_VECTORS && 10642 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) { 10643 SDValue V = partitionShuffleOfConcats(N, DAG); 10644 10645 if (V.getNode()) 10646 return V; 10647 } 10648 10649 // If this shuffle node is simply a swizzle of another shuffle node, 10650 // and it reverses the swizzle of the previous shuffle then we can 10651 // optimize shuffle(shuffle(x, undef), undef) -> x. 10652 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG && 10653 N1.getOpcode() == ISD::UNDEF) { 10654 10655 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0); 10656 10657 // Shuffle nodes can only reverse shuffles with a single non-undef value. 10658 if (N0.getOperand(1).getOpcode() != ISD::UNDEF) 10659 return SDValue(); 10660 10661 // The incoming shuffle must be of the same type as the result of the 10662 // current shuffle. 10663 assert(OtherSV->getOperand(0).getValueType() == VT && 10664 "Shuffle types don't match"); 10665 10666 for (unsigned i = 0; i != NumElts; ++i) { 10667 int Idx = SVN->getMaskElt(i); 10668 assert(Idx < (int)NumElts && "Index references undef operand"); 10669 // Next, this index comes from the first value, which is the incoming 10670 // shuffle. Adopt the incoming index. 10671 if (Idx >= 0) 10672 Idx = OtherSV->getMaskElt(Idx); 10673 10674 // The combined shuffle must map each index to itself. 10675 if (Idx >= 0 && (unsigned)Idx != i) 10676 return SDValue(); 10677 } 10678 10679 return OtherSV->getOperand(0); 10680 } 10681 10682 return SDValue(); 10683 } 10684 10685 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) { 10686 SDValue N0 = N->getOperand(0); 10687 SDValue N2 = N->getOperand(2); 10688 10689 // If the input vector is a concatenation, and the insert replaces 10690 // one of the halves, we can optimize into a single concat_vectors. 10691 if (N0.getOpcode() == ISD::CONCAT_VECTORS && 10692 N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) { 10693 APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue(); 10694 EVT VT = N->getValueType(0); 10695 10696 // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) -> 10697 // (concat_vectors Z, Y) 10698 if (InsIdx == 0) 10699 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, 10700 N->getOperand(1), N0.getOperand(1)); 10701 10702 // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) -> 10703 // (concat_vectors X, Z) 10704 if (InsIdx == VT.getVectorNumElements()/2) 10705 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, 10706 N0.getOperand(0), N->getOperand(1)); 10707 } 10708 10709 return SDValue(); 10710 } 10711 10712 /// XformToShuffleWithZero - Returns a vector_shuffle if it able to transform 10713 /// an AND to a vector_shuffle with the destination vector and a zero vector. 10714 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==> 10715 /// vector_shuffle V, Zero, <0, 4, 2, 4> 10716 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) { 10717 EVT VT = N->getValueType(0); 10718 SDLoc dl(N); 10719 SDValue LHS = N->getOperand(0); 10720 SDValue RHS = N->getOperand(1); 10721 if (N->getOpcode() == ISD::AND) { 10722 if (RHS.getOpcode() == ISD::BITCAST) 10723 RHS = RHS.getOperand(0); 10724 if (RHS.getOpcode() == ISD::BUILD_VECTOR) { 10725 SmallVector<int, 8> Indices; 10726 unsigned NumElts = RHS.getNumOperands(); 10727 for (unsigned i = 0; i != NumElts; ++i) { 10728 SDValue Elt = RHS.getOperand(i); 10729 if (!isa<ConstantSDNode>(Elt)) 10730 return SDValue(); 10731 10732 if (cast<ConstantSDNode>(Elt)->isAllOnesValue()) 10733 Indices.push_back(i); 10734 else if (cast<ConstantSDNode>(Elt)->isNullValue()) 10735 Indices.push_back(NumElts); 10736 else 10737 return SDValue(); 10738 } 10739 10740 // Let's see if the target supports this vector_shuffle. 10741 EVT RVT = RHS.getValueType(); 10742 if (!TLI.isVectorClearMaskLegal(Indices, RVT)) 10743 return SDValue(); 10744 10745 // Return the new VECTOR_SHUFFLE node. 10746 EVT EltVT = RVT.getVectorElementType(); 10747 SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(), 10748 DAG.getConstant(0, EltVT)); 10749 SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), RVT, ZeroOps); 10750 LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS); 10751 SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]); 10752 return DAG.getNode(ISD::BITCAST, dl, VT, Shuf); 10753 } 10754 } 10755 10756 return SDValue(); 10757 } 10758 10759 /// SimplifyVBinOp - Visit a binary vector operation, like ADD. 10760 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) { 10761 assert(N->getValueType(0).isVector() && 10762 "SimplifyVBinOp only works on vectors!"); 10763 10764 SDValue LHS = N->getOperand(0); 10765 SDValue RHS = N->getOperand(1); 10766 SDValue Shuffle = XformToShuffleWithZero(N); 10767 if (Shuffle.getNode()) return Shuffle; 10768 10769 // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold 10770 // this operation. 10771 if (LHS.getOpcode() == ISD::BUILD_VECTOR && 10772 RHS.getOpcode() == ISD::BUILD_VECTOR) { 10773 // Check if both vectors are constants. If not bail out. 10774 if (!(cast<BuildVectorSDNode>(LHS)->isConstant() && 10775 cast<BuildVectorSDNode>(RHS)->isConstant())) 10776 return SDValue(); 10777 10778 SmallVector<SDValue, 8> Ops; 10779 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) { 10780 SDValue LHSOp = LHS.getOperand(i); 10781 SDValue RHSOp = RHS.getOperand(i); 10782 10783 // Can't fold divide by zero. 10784 if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV || 10785 N->getOpcode() == ISD::FDIV) { 10786 if ((RHSOp.getOpcode() == ISD::Constant && 10787 cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) || 10788 (RHSOp.getOpcode() == ISD::ConstantFP && 10789 cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero())) 10790 break; 10791 } 10792 10793 EVT VT = LHSOp.getValueType(); 10794 EVT RVT = RHSOp.getValueType(); 10795 if (RVT != VT) { 10796 // Integer BUILD_VECTOR operands may have types larger than the element 10797 // size (e.g., when the element type is not legal). Prior to type 10798 // legalization, the types may not match between the two BUILD_VECTORS. 10799 // Truncate one of the operands to make them match. 10800 if (RVT.getSizeInBits() > VT.getSizeInBits()) { 10801 RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp); 10802 } else { 10803 LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp); 10804 VT = RVT; 10805 } 10806 } 10807 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT, 10808 LHSOp, RHSOp); 10809 if (FoldOp.getOpcode() != ISD::UNDEF && 10810 FoldOp.getOpcode() != ISD::Constant && 10811 FoldOp.getOpcode() != ISD::ConstantFP) 10812 break; 10813 Ops.push_back(FoldOp); 10814 AddToWorkList(FoldOp.getNode()); 10815 } 10816 10817 if (Ops.size() == LHS.getNumOperands()) 10818 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), LHS.getValueType(), Ops); 10819 } 10820 10821 // Type legalization might introduce new shuffles in the DAG. 10822 // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask))) 10823 // -> (shuffle (VBinOp (A, B)), Undef, Mask). 10824 if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) && 10825 isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() && 10826 LHS.getOperand(1).getOpcode() == ISD::UNDEF && 10827 RHS.getOperand(1).getOpcode() == ISD::UNDEF) { 10828 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS); 10829 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS); 10830 10831 if (SVN0->getMask().equals(SVN1->getMask())) { 10832 EVT VT = N->getValueType(0); 10833 SDValue UndefVector = LHS.getOperand(1); 10834 SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT, 10835 LHS.getOperand(0), RHS.getOperand(0)); 10836 AddUsersToWorkList(N); 10837 return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector, 10838 &SVN0->getMask()[0]); 10839 } 10840 } 10841 10842 return SDValue(); 10843 } 10844 10845 /// SimplifyVUnaryOp - Visit a binary vector operation, like FABS/FNEG. 10846 SDValue DAGCombiner::SimplifyVUnaryOp(SDNode *N) { 10847 assert(N->getValueType(0).isVector() && 10848 "SimplifyVUnaryOp only works on vectors!"); 10849 10850 SDValue N0 = N->getOperand(0); 10851 10852 if (N0.getOpcode() != ISD::BUILD_VECTOR) 10853 return SDValue(); 10854 10855 // Operand is a BUILD_VECTOR node, see if we can constant fold it. 10856 SmallVector<SDValue, 8> Ops; 10857 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) { 10858 SDValue Op = N0.getOperand(i); 10859 if (Op.getOpcode() != ISD::UNDEF && 10860 Op.getOpcode() != ISD::ConstantFP) 10861 break; 10862 EVT EltVT = Op.getValueType(); 10863 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(N0), EltVT, Op); 10864 if (FoldOp.getOpcode() != ISD::UNDEF && 10865 FoldOp.getOpcode() != ISD::ConstantFP) 10866 break; 10867 Ops.push_back(FoldOp); 10868 AddToWorkList(FoldOp.getNode()); 10869 } 10870 10871 if (Ops.size() != N0.getNumOperands()) 10872 return SDValue(); 10873 10874 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), N0.getValueType(), Ops); 10875 } 10876 10877 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0, 10878 SDValue N1, SDValue N2){ 10879 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!"); 10880 10881 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2, 10882 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 10883 10884 // If we got a simplified select_cc node back from SimplifySelectCC, then 10885 // break it down into a new SETCC node, and a new SELECT node, and then return 10886 // the SELECT node, since we were called with a SELECT node. 10887 if (SCC.getNode()) { 10888 // Check to see if we got a select_cc back (to turn into setcc/select). 10889 // Otherwise, just return whatever node we got back, like fabs. 10890 if (SCC.getOpcode() == ISD::SELECT_CC) { 10891 SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0), 10892 N0.getValueType(), 10893 SCC.getOperand(0), SCC.getOperand(1), 10894 SCC.getOperand(4)); 10895 AddToWorkList(SETCC.getNode()); 10896 return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), 10897 SCC.getOperand(2), SCC.getOperand(3), SETCC); 10898 } 10899 10900 return SCC; 10901 } 10902 return SDValue(); 10903 } 10904 10905 /// SimplifySelectOps - Given a SELECT or a SELECT_CC node, where LHS and RHS 10906 /// are the two values being selected between, see if we can simplify the 10907 /// select. Callers of this should assume that TheSelect is deleted if this 10908 /// returns true. As such, they should return the appropriate thing (e.g. the 10909 /// node) back to the top-level of the DAG combiner loop to avoid it being 10910 /// looked at. 10911 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS, 10912 SDValue RHS) { 10913 10914 // Cannot simplify select with vector condition 10915 if (TheSelect->getOperand(0).getValueType().isVector()) return false; 10916 10917 // If this is a select from two identical things, try to pull the operation 10918 // through the select. 10919 if (LHS.getOpcode() != RHS.getOpcode() || 10920 !LHS.hasOneUse() || !RHS.hasOneUse()) 10921 return false; 10922 10923 // If this is a load and the token chain is identical, replace the select 10924 // of two loads with a load through a select of the address to load from. 10925 // This triggers in things like "select bool X, 10.0, 123.0" after the FP 10926 // constants have been dropped into the constant pool. 10927 if (LHS.getOpcode() == ISD::LOAD) { 10928 LoadSDNode *LLD = cast<LoadSDNode>(LHS); 10929 LoadSDNode *RLD = cast<LoadSDNode>(RHS); 10930 10931 // Token chains must be identical. 10932 if (LHS.getOperand(0) != RHS.getOperand(0) || 10933 // Do not let this transformation reduce the number of volatile loads. 10934 LLD->isVolatile() || RLD->isVolatile() || 10935 // If this is an EXTLOAD, the VT's must match. 10936 LLD->getMemoryVT() != RLD->getMemoryVT() || 10937 // If this is an EXTLOAD, the kind of extension must match. 10938 (LLD->getExtensionType() != RLD->getExtensionType() && 10939 // The only exception is if one of the extensions is anyext. 10940 LLD->getExtensionType() != ISD::EXTLOAD && 10941 RLD->getExtensionType() != ISD::EXTLOAD) || 10942 // FIXME: this discards src value information. This is 10943 // over-conservative. It would be beneficial to be able to remember 10944 // both potential memory locations. Since we are discarding 10945 // src value info, don't do the transformation if the memory 10946 // locations are not in the default address space. 10947 LLD->getPointerInfo().getAddrSpace() != 0 || 10948 RLD->getPointerInfo().getAddrSpace() != 0 || 10949 !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(), 10950 LLD->getBasePtr().getValueType())) 10951 return false; 10952 10953 // Check that the select condition doesn't reach either load. If so, 10954 // folding this will induce a cycle into the DAG. If not, this is safe to 10955 // xform, so create a select of the addresses. 10956 SDValue Addr; 10957 if (TheSelect->getOpcode() == ISD::SELECT) { 10958 SDNode *CondNode = TheSelect->getOperand(0).getNode(); 10959 if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) || 10960 (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode))) 10961 return false; 10962 // The loads must not depend on one another. 10963 if (LLD->isPredecessorOf(RLD) || 10964 RLD->isPredecessorOf(LLD)) 10965 return false; 10966 Addr = DAG.getSelect(SDLoc(TheSelect), 10967 LLD->getBasePtr().getValueType(), 10968 TheSelect->getOperand(0), LLD->getBasePtr(), 10969 RLD->getBasePtr()); 10970 } else { // Otherwise SELECT_CC 10971 SDNode *CondLHS = TheSelect->getOperand(0).getNode(); 10972 SDNode *CondRHS = TheSelect->getOperand(1).getNode(); 10973 10974 if ((LLD->hasAnyUseOfValue(1) && 10975 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) || 10976 (RLD->hasAnyUseOfValue(1) && 10977 (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS)))) 10978 return false; 10979 10980 Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect), 10981 LLD->getBasePtr().getValueType(), 10982 TheSelect->getOperand(0), 10983 TheSelect->getOperand(1), 10984 LLD->getBasePtr(), RLD->getBasePtr(), 10985 TheSelect->getOperand(4)); 10986 } 10987 10988 SDValue Load; 10989 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) { 10990 Load = DAG.getLoad(TheSelect->getValueType(0), 10991 SDLoc(TheSelect), 10992 // FIXME: Discards pointer and TBAA info. 10993 LLD->getChain(), Addr, MachinePointerInfo(), 10994 LLD->isVolatile(), LLD->isNonTemporal(), 10995 LLD->isInvariant(), LLD->getAlignment()); 10996 } else { 10997 Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ? 10998 RLD->getExtensionType() : LLD->getExtensionType(), 10999 SDLoc(TheSelect), 11000 TheSelect->getValueType(0), 11001 // FIXME: Discards pointer and TBAA info. 11002 LLD->getChain(), Addr, MachinePointerInfo(), 11003 LLD->getMemoryVT(), LLD->isVolatile(), 11004 LLD->isNonTemporal(), LLD->getAlignment()); 11005 } 11006 11007 // Users of the select now use the result of the load. 11008 CombineTo(TheSelect, Load); 11009 11010 // Users of the old loads now use the new load's chain. We know the 11011 // old-load value is dead now. 11012 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1)); 11013 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1)); 11014 return true; 11015 } 11016 11017 return false; 11018 } 11019 11020 /// SimplifySelectCC - Simplify an expression of the form (N0 cond N1) ? N2 : N3 11021 /// where 'cond' is the comparison specified by CC. 11022 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, 11023 SDValue N2, SDValue N3, 11024 ISD::CondCode CC, bool NotExtCompare) { 11025 // (x ? y : y) -> y. 11026 if (N2 == N3) return N2; 11027 11028 EVT VT = N2.getValueType(); 11029 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode()); 11030 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode()); 11031 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode()); 11032 11033 // Determine if the condition we're dealing with is constant 11034 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()), 11035 N0, N1, CC, DL, false); 11036 if (SCC.getNode()) AddToWorkList(SCC.getNode()); 11037 ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode()); 11038 11039 // fold select_cc true, x, y -> x 11040 if (SCCC && !SCCC->isNullValue()) 11041 return N2; 11042 // fold select_cc false, x, y -> y 11043 if (SCCC && SCCC->isNullValue()) 11044 return N3; 11045 11046 // Check to see if we can simplify the select into an fabs node 11047 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) { 11048 // Allow either -0.0 or 0.0 11049 if (CFP->getValueAPF().isZero()) { 11050 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs 11051 if ((CC == ISD::SETGE || CC == ISD::SETGT) && 11052 N0 == N2 && N3.getOpcode() == ISD::FNEG && 11053 N2 == N3.getOperand(0)) 11054 return DAG.getNode(ISD::FABS, DL, VT, N0); 11055 11056 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs 11057 if ((CC == ISD::SETLT || CC == ISD::SETLE) && 11058 N0 == N3 && N2.getOpcode() == ISD::FNEG && 11059 N2.getOperand(0) == N3) 11060 return DAG.getNode(ISD::FABS, DL, VT, N3); 11061 } 11062 } 11063 11064 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)" 11065 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0 11066 // in it. This is a win when the constant is not otherwise available because 11067 // it replaces two constant pool loads with one. We only do this if the FP 11068 // type is known to be legal, because if it isn't, then we are before legalize 11069 // types an we want the other legalization to happen first (e.g. to avoid 11070 // messing with soft float) and if the ConstantFP is not legal, because if 11071 // it is legal, we may not need to store the FP constant in a constant pool. 11072 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2)) 11073 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) { 11074 if (TLI.isTypeLegal(N2.getValueType()) && 11075 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) != 11076 TargetLowering::Legal && 11077 !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) && 11078 !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) && 11079 // If both constants have multiple uses, then we won't need to do an 11080 // extra load, they are likely around in registers for other users. 11081 (TV->hasOneUse() || FV->hasOneUse())) { 11082 Constant *Elts[] = { 11083 const_cast<ConstantFP*>(FV->getConstantFPValue()), 11084 const_cast<ConstantFP*>(TV->getConstantFPValue()) 11085 }; 11086 Type *FPTy = Elts[0]->getType(); 11087 const DataLayout &TD = *TLI.getDataLayout(); 11088 11089 // Create a ConstantArray of the two constants. 11090 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts); 11091 SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(), 11092 TD.getPrefTypeAlignment(FPTy)); 11093 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment(); 11094 11095 // Get the offsets to the 0 and 1 element of the array so that we can 11096 // select between them. 11097 SDValue Zero = DAG.getIntPtrConstant(0); 11098 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType()); 11099 SDValue One = DAG.getIntPtrConstant(EltSize); 11100 11101 SDValue Cond = DAG.getSetCC(DL, 11102 getSetCCResultType(N0.getValueType()), 11103 N0, N1, CC); 11104 AddToWorkList(Cond.getNode()); 11105 SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(), 11106 Cond, One, Zero); 11107 AddToWorkList(CstOffset.getNode()); 11108 CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx, 11109 CstOffset); 11110 AddToWorkList(CPIdx.getNode()); 11111 return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx, 11112 MachinePointerInfo::getConstantPool(), false, 11113 false, false, Alignment); 11114 11115 } 11116 } 11117 11118 // Check to see if we can perform the "gzip trick", transforming 11119 // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A) 11120 if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT && 11121 (N1C->isNullValue() || // (a < 0) ? b : 0 11122 (N1C->getAPIntValue() == 1 && N0 == N2))) { // (a < 1) ? a : 0 11123 EVT XType = N0.getValueType(); 11124 EVT AType = N2.getValueType(); 11125 if (XType.bitsGE(AType)) { 11126 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a 11127 // single-bit constant. 11128 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) { 11129 unsigned ShCtV = N2C->getAPIntValue().logBase2(); 11130 ShCtV = XType.getSizeInBits()-ShCtV-1; 11131 SDValue ShCt = DAG.getConstant(ShCtV, 11132 getShiftAmountTy(N0.getValueType())); 11133 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), 11134 XType, N0, ShCt); 11135 AddToWorkList(Shift.getNode()); 11136 11137 if (XType.bitsGT(AType)) { 11138 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift); 11139 AddToWorkList(Shift.getNode()); 11140 } 11141 11142 return DAG.getNode(ISD::AND, DL, AType, Shift, N2); 11143 } 11144 11145 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), 11146 XType, N0, 11147 DAG.getConstant(XType.getSizeInBits()-1, 11148 getShiftAmountTy(N0.getValueType()))); 11149 AddToWorkList(Shift.getNode()); 11150 11151 if (XType.bitsGT(AType)) { 11152 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift); 11153 AddToWorkList(Shift.getNode()); 11154 } 11155 11156 return DAG.getNode(ISD::AND, DL, AType, Shift, N2); 11157 } 11158 } 11159 11160 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A) 11161 // where y is has a single bit set. 11162 // A plaintext description would be, we can turn the SELECT_CC into an AND 11163 // when the condition can be materialized as an all-ones register. Any 11164 // single bit-test can be materialized as an all-ones register with 11165 // shift-left and shift-right-arith. 11166 if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND && 11167 N0->getValueType(0) == VT && 11168 N1C && N1C->isNullValue() && 11169 N2C && N2C->isNullValue()) { 11170 SDValue AndLHS = N0->getOperand(0); 11171 ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 11172 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) { 11173 // Shift the tested bit over the sign bit. 11174 APInt AndMask = ConstAndRHS->getAPIntValue(); 11175 SDValue ShlAmt = 11176 DAG.getConstant(AndMask.countLeadingZeros(), 11177 getShiftAmountTy(AndLHS.getValueType())); 11178 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt); 11179 11180 // Now arithmetic right shift it all the way over, so the result is either 11181 // all-ones, or zero. 11182 SDValue ShrAmt = 11183 DAG.getConstant(AndMask.getBitWidth()-1, 11184 getShiftAmountTy(Shl.getValueType())); 11185 SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt); 11186 11187 return DAG.getNode(ISD::AND, DL, VT, Shr, N3); 11188 } 11189 } 11190 11191 // fold select C, 16, 0 -> shl C, 4 11192 if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() && 11193 TLI.getBooleanContents(N0.getValueType().isVector()) == 11194 TargetLowering::ZeroOrOneBooleanContent) { 11195 11196 // If the caller doesn't want us to simplify this into a zext of a compare, 11197 // don't do it. 11198 if (NotExtCompare && N2C->getAPIntValue() == 1) 11199 return SDValue(); 11200 11201 // Get a SetCC of the condition 11202 // NOTE: Don't create a SETCC if it's not legal on this target. 11203 if (!LegalOperations || 11204 TLI.isOperationLegal(ISD::SETCC, 11205 LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) { 11206 SDValue Temp, SCC; 11207 // cast from setcc result type to select result type 11208 if (LegalTypes) { 11209 SCC = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()), 11210 N0, N1, CC); 11211 if (N2.getValueType().bitsLT(SCC.getValueType())) 11212 Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2), 11213 N2.getValueType()); 11214 else 11215 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2), 11216 N2.getValueType(), SCC); 11217 } else { 11218 SCC = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC); 11219 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2), 11220 N2.getValueType(), SCC); 11221 } 11222 11223 AddToWorkList(SCC.getNode()); 11224 AddToWorkList(Temp.getNode()); 11225 11226 if (N2C->getAPIntValue() == 1) 11227 return Temp; 11228 11229 // shl setcc result by log2 n2c 11230 return DAG.getNode( 11231 ISD::SHL, DL, N2.getValueType(), Temp, 11232 DAG.getConstant(N2C->getAPIntValue().logBase2(), 11233 getShiftAmountTy(Temp.getValueType()))); 11234 } 11235 } 11236 11237 // Check to see if this is the equivalent of setcc 11238 // FIXME: Turn all of these into setcc if setcc if setcc is legal 11239 // otherwise, go ahead with the folds. 11240 if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) { 11241 EVT XType = N0.getValueType(); 11242 if (!LegalOperations || 11243 TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) { 11244 SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC); 11245 if (Res.getValueType() != VT) 11246 Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res); 11247 return Res; 11248 } 11249 11250 // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X)))) 11251 if (N1C && N1C->isNullValue() && CC == ISD::SETEQ && 11252 (!LegalOperations || 11253 TLI.isOperationLegal(ISD::CTLZ, XType))) { 11254 SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0); 11255 return DAG.getNode(ISD::SRL, DL, XType, Ctlz, 11256 DAG.getConstant(Log2_32(XType.getSizeInBits()), 11257 getShiftAmountTy(Ctlz.getValueType()))); 11258 } 11259 // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1)) 11260 if (N1C && N1C->isNullValue() && CC == ISD::SETGT) { 11261 SDValue NegN0 = DAG.getNode(ISD::SUB, SDLoc(N0), 11262 XType, DAG.getConstant(0, XType), N0); 11263 SDValue NotN0 = DAG.getNOT(SDLoc(N0), N0, XType); 11264 return DAG.getNode(ISD::SRL, DL, XType, 11265 DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0), 11266 DAG.getConstant(XType.getSizeInBits()-1, 11267 getShiftAmountTy(XType))); 11268 } 11269 // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1)) 11270 if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) { 11271 SDValue Sign = DAG.getNode(ISD::SRL, SDLoc(N0), XType, N0, 11272 DAG.getConstant(XType.getSizeInBits()-1, 11273 getShiftAmountTy(N0.getValueType()))); 11274 return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType)); 11275 } 11276 } 11277 11278 // Check to see if this is an integer abs. 11279 // select_cc setg[te] X, 0, X, -X -> 11280 // select_cc setgt X, -1, X, -X -> 11281 // select_cc setl[te] X, 0, -X, X -> 11282 // select_cc setlt X, 1, -X, X -> 11283 // Y = sra (X, size(X)-1); xor (add (X, Y), Y) 11284 if (N1C) { 11285 ConstantSDNode *SubC = nullptr; 11286 if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) || 11287 (N1C->isAllOnesValue() && CC == ISD::SETGT)) && 11288 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1)) 11289 SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0)); 11290 else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) || 11291 (N1C->isOne() && CC == ISD::SETLT)) && 11292 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1)) 11293 SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0)); 11294 11295 EVT XType = N0.getValueType(); 11296 if (SubC && SubC->isNullValue() && XType.isInteger()) { 11297 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), XType, 11298 N0, 11299 DAG.getConstant(XType.getSizeInBits()-1, 11300 getShiftAmountTy(N0.getValueType()))); 11301 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0), 11302 XType, N0, Shift); 11303 AddToWorkList(Shift.getNode()); 11304 AddToWorkList(Add.getNode()); 11305 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift); 11306 } 11307 } 11308 11309 return SDValue(); 11310 } 11311 11312 /// SimplifySetCC - This is a stub for TargetLowering::SimplifySetCC. 11313 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0, 11314 SDValue N1, ISD::CondCode Cond, 11315 SDLoc DL, bool foldBooleans) { 11316 TargetLowering::DAGCombinerInfo 11317 DagCombineInfo(DAG, Level, false, this); 11318 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL); 11319 } 11320 11321 /// BuildSDIVSequence - Given an ISD::SDIV node expressing a divide by constant, 11322 /// return a DAG expression to select that will generate the same value by 11323 /// multiplying by a magic number. See: 11324 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html> 11325 SDValue DAGCombiner::BuildSDIV(SDNode *N) { 11326 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1)); 11327 if (!C) 11328 return SDValue(); 11329 11330 // Avoid division by zero. 11331 if (!C->getAPIntValue()) 11332 return SDValue(); 11333 11334 std::vector<SDNode*> Built; 11335 SDValue S = 11336 TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built); 11337 11338 for (SDNode *N : Built) 11339 AddToWorkList(N); 11340 return S; 11341 } 11342 11343 /// BuildUDIV - Given an ISD::UDIV node expressing a divide by constant, 11344 /// return a DAG expression to select that will generate the same value by 11345 /// multiplying by a magic number. See: 11346 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html> 11347 SDValue DAGCombiner::BuildUDIV(SDNode *N) { 11348 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1)); 11349 if (!C) 11350 return SDValue(); 11351 11352 // Avoid division by zero. 11353 if (!C->getAPIntValue()) 11354 return SDValue(); 11355 11356 std::vector<SDNode*> Built; 11357 SDValue S = 11358 TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built); 11359 11360 for (SDNode *N : Built) 11361 AddToWorkList(N); 11362 return S; 11363 } 11364 11365 /// FindBaseOffset - Return true if base is a frame index, which is known not 11366 // to alias with anything but itself. Provides base object and offset as 11367 // results. 11368 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset, 11369 const GlobalValue *&GV, const void *&CV) { 11370 // Assume it is a primitive operation. 11371 Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr; 11372 11373 // If it's an adding a simple constant then integrate the offset. 11374 if (Base.getOpcode() == ISD::ADD) { 11375 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) { 11376 Base = Base.getOperand(0); 11377 Offset += C->getZExtValue(); 11378 } 11379 } 11380 11381 // Return the underlying GlobalValue, and update the Offset. Return false 11382 // for GlobalAddressSDNode since the same GlobalAddress may be represented 11383 // by multiple nodes with different offsets. 11384 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) { 11385 GV = G->getGlobal(); 11386 Offset += G->getOffset(); 11387 return false; 11388 } 11389 11390 // Return the underlying Constant value, and update the Offset. Return false 11391 // for ConstantSDNodes since the same constant pool entry may be represented 11392 // by multiple nodes with different offsets. 11393 if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) { 11394 CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal() 11395 : (const void *)C->getConstVal(); 11396 Offset += C->getOffset(); 11397 return false; 11398 } 11399 // If it's any of the following then it can't alias with anything but itself. 11400 return isa<FrameIndexSDNode>(Base); 11401 } 11402 11403 /// isAlias - Return true if there is any possibility that the two addresses 11404 /// overlap. 11405 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const { 11406 // If they are the same then they must be aliases. 11407 if (Op0->getBasePtr() == Op1->getBasePtr()) return true; 11408 11409 // If they are both volatile then they cannot be reordered. 11410 if (Op0->isVolatile() && Op1->isVolatile()) return true; 11411 11412 // Gather base node and offset information. 11413 SDValue Base1, Base2; 11414 int64_t Offset1, Offset2; 11415 const GlobalValue *GV1, *GV2; 11416 const void *CV1, *CV2; 11417 bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(), 11418 Base1, Offset1, GV1, CV1); 11419 bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(), 11420 Base2, Offset2, GV2, CV2); 11421 11422 // If they have a same base address then check to see if they overlap. 11423 if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2))) 11424 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 || 11425 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1); 11426 11427 // It is possible for different frame indices to alias each other, mostly 11428 // when tail call optimization reuses return address slots for arguments. 11429 // To catch this case, look up the actual index of frame indices to compute 11430 // the real alias relationship. 11431 if (isFrameIndex1 && isFrameIndex2) { 11432 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo(); 11433 Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex()); 11434 Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex()); 11435 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 || 11436 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1); 11437 } 11438 11439 // Otherwise, if we know what the bases are, and they aren't identical, then 11440 // we know they cannot alias. 11441 if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2)) 11442 return false; 11443 11444 // If we know required SrcValue1 and SrcValue2 have relatively large alignment 11445 // compared to the size and offset of the access, we may be able to prove they 11446 // do not alias. This check is conservative for now to catch cases created by 11447 // splitting vector types. 11448 if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) && 11449 (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) && 11450 (Op0->getMemoryVT().getSizeInBits() >> 3 == 11451 Op1->getMemoryVT().getSizeInBits() >> 3) && 11452 (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) { 11453 int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment(); 11454 int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment(); 11455 11456 // There is no overlap between these relatively aligned accesses of similar 11457 // size, return no alias. 11458 if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 || 11459 (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1) 11460 return false; 11461 } 11462 11463 bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0 ? CombinerGlobalAA : 11464 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA(); 11465 #ifndef NDEBUG 11466 if (CombinerAAOnlyFunc.getNumOccurrences() && 11467 CombinerAAOnlyFunc != DAG.getMachineFunction().getName()) 11468 UseAA = false; 11469 #endif 11470 if (UseAA && 11471 Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) { 11472 // Use alias analysis information. 11473 int64_t MinOffset = std::min(Op0->getSrcValueOffset(), 11474 Op1->getSrcValueOffset()); 11475 int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) + 11476 Op0->getSrcValueOffset() - MinOffset; 11477 int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) + 11478 Op1->getSrcValueOffset() - MinOffset; 11479 AliasAnalysis::AliasResult AAResult = 11480 AA.alias(AliasAnalysis::Location(Op0->getMemOperand()->getValue(), 11481 Overlap1, 11482 UseTBAA ? Op0->getTBAAInfo() : nullptr), 11483 AliasAnalysis::Location(Op1->getMemOperand()->getValue(), 11484 Overlap2, 11485 UseTBAA ? Op1->getTBAAInfo() : nullptr)); 11486 if (AAResult == AliasAnalysis::NoAlias) 11487 return false; 11488 } 11489 11490 // Otherwise we have to assume they alias. 11491 return true; 11492 } 11493 11494 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes, 11495 /// looking for aliasing nodes and adding them to the Aliases vector. 11496 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain, 11497 SmallVectorImpl<SDValue> &Aliases) { 11498 SmallVector<SDValue, 8> Chains; // List of chains to visit. 11499 SmallPtrSet<SDNode *, 16> Visited; // Visited node set. 11500 11501 // Get alias information for node. 11502 bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile(); 11503 11504 // Starting off. 11505 Chains.push_back(OriginalChain); 11506 unsigned Depth = 0; 11507 11508 // Look at each chain and determine if it is an alias. If so, add it to the 11509 // aliases list. If not, then continue up the chain looking for the next 11510 // candidate. 11511 while (!Chains.empty()) { 11512 SDValue Chain = Chains.back(); 11513 Chains.pop_back(); 11514 11515 // For TokenFactor nodes, look at each operand and only continue up the 11516 // chain until we find two aliases. If we've seen two aliases, assume we'll 11517 // find more and revert to original chain since the xform is unlikely to be 11518 // profitable. 11519 // 11520 // FIXME: The depth check could be made to return the last non-aliasing 11521 // chain we found before we hit a tokenfactor rather than the original 11522 // chain. 11523 if (Depth > 6 || Aliases.size() == 2) { 11524 Aliases.clear(); 11525 Aliases.push_back(OriginalChain); 11526 return; 11527 } 11528 11529 // Don't bother if we've been before. 11530 if (!Visited.insert(Chain.getNode())) 11531 continue; 11532 11533 switch (Chain.getOpcode()) { 11534 case ISD::EntryToken: 11535 // Entry token is ideal chain operand, but handled in FindBetterChain. 11536 break; 11537 11538 case ISD::LOAD: 11539 case ISD::STORE: { 11540 // Get alias information for Chain. 11541 bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) && 11542 !cast<LSBaseSDNode>(Chain.getNode())->isVolatile(); 11543 11544 // If chain is alias then stop here. 11545 if (!(IsLoad && IsOpLoad) && 11546 isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) { 11547 Aliases.push_back(Chain); 11548 } else { 11549 // Look further up the chain. 11550 Chains.push_back(Chain.getOperand(0)); 11551 ++Depth; 11552 } 11553 break; 11554 } 11555 11556 case ISD::TokenFactor: 11557 // We have to check each of the operands of the token factor for "small" 11558 // token factors, so we queue them up. Adding the operands to the queue 11559 // (stack) in reverse order maintains the original order and increases the 11560 // likelihood that getNode will find a matching token factor (CSE.) 11561 if (Chain.getNumOperands() > 16) { 11562 Aliases.push_back(Chain); 11563 break; 11564 } 11565 for (unsigned n = Chain.getNumOperands(); n;) 11566 Chains.push_back(Chain.getOperand(--n)); 11567 ++Depth; 11568 break; 11569 11570 default: 11571 // For all other instructions we will just have to take what we can get. 11572 Aliases.push_back(Chain); 11573 break; 11574 } 11575 } 11576 11577 // We need to be careful here to also search for aliases through the 11578 // value operand of a store, etc. Consider the following situation: 11579 // Token1 = ... 11580 // L1 = load Token1, %52 11581 // S1 = store Token1, L1, %51 11582 // L2 = load Token1, %52+8 11583 // S2 = store Token1, L2, %51+8 11584 // Token2 = Token(S1, S2) 11585 // L3 = load Token2, %53 11586 // S3 = store Token2, L3, %52 11587 // L4 = load Token2, %53+8 11588 // S4 = store Token2, L4, %52+8 11589 // If we search for aliases of S3 (which loads address %52), and we look 11590 // only through the chain, then we'll miss the trivial dependence on L1 11591 // (which also loads from %52). We then might change all loads and 11592 // stores to use Token1 as their chain operand, which could result in 11593 // copying %53 into %52 before copying %52 into %51 (which should 11594 // happen first). 11595 // 11596 // The problem is, however, that searching for such data dependencies 11597 // can become expensive, and the cost is not directly related to the 11598 // chain depth. Instead, we'll rule out such configurations here by 11599 // insisting that we've visited all chain users (except for users 11600 // of the original chain, which is not necessary). When doing this, 11601 // we need to look through nodes we don't care about (otherwise, things 11602 // like register copies will interfere with trivial cases). 11603 11604 SmallVector<const SDNode *, 16> Worklist; 11605 for (SmallPtrSet<SDNode *, 16>::iterator I = Visited.begin(), 11606 IE = Visited.end(); I != IE; ++I) 11607 if (*I != OriginalChain.getNode()) 11608 Worklist.push_back(*I); 11609 11610 while (!Worklist.empty()) { 11611 const SDNode *M = Worklist.pop_back_val(); 11612 11613 // We have already visited M, and want to make sure we've visited any uses 11614 // of M that we care about. For uses that we've not visisted, and don't 11615 // care about, queue them to the worklist. 11616 11617 for (SDNode::use_iterator UI = M->use_begin(), 11618 UIE = M->use_end(); UI != UIE; ++UI) 11619 if (UI.getUse().getValueType() == MVT::Other && Visited.insert(*UI)) { 11620 if (isa<MemIntrinsicSDNode>(*UI) || isa<MemSDNode>(*UI)) { 11621 // We've not visited this use, and we care about it (it could have an 11622 // ordering dependency with the original node). 11623 Aliases.clear(); 11624 Aliases.push_back(OriginalChain); 11625 return; 11626 } 11627 11628 // We've not visited this use, but we don't care about it. Mark it as 11629 // visited and enqueue it to the worklist. 11630 Worklist.push_back(*UI); 11631 } 11632 } 11633 } 11634 11635 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes, looking 11636 /// for a better chain (aliasing node.) 11637 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) { 11638 SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor. 11639 11640 // Accumulate all the aliases to this node. 11641 GatherAllAliases(N, OldChain, Aliases); 11642 11643 // If no operands then chain to entry token. 11644 if (Aliases.size() == 0) 11645 return DAG.getEntryNode(); 11646 11647 // If a single operand then chain to it. We don't need to revisit it. 11648 if (Aliases.size() == 1) 11649 return Aliases[0]; 11650 11651 // Construct a custom tailored token factor. 11652 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases); 11653 } 11654 11655 // SelectionDAG::Combine - This is the entry point for the file. 11656 // 11657 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA, 11658 CodeGenOpt::Level OptLevel) { 11659 /// run - This is the main entry point to this class. 11660 /// 11661 DAGCombiner(*this, AA, OptLevel).Run(Level); 11662 } 11663