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 #define DEBUG_TYPE "dagcombine" 20 #include "llvm/CodeGen/SelectionDAG.h" 21 #include "llvm/ADT/SmallPtrSet.h" 22 #include "llvm/ADT/Statistic.h" 23 #include "llvm/Analysis/AliasAnalysis.h" 24 #include "llvm/CodeGen/MachineFrameInfo.h" 25 #include "llvm/CodeGen/MachineFunction.h" 26 #include "llvm/IR/DataLayout.h" 27 #include "llvm/IR/DerivedTypes.h" 28 #include "llvm/IR/Function.h" 29 #include "llvm/IR/LLVMContext.h" 30 #include "llvm/Support/CommandLine.h" 31 #include "llvm/Support/Debug.h" 32 #include "llvm/Support/ErrorHandling.h" 33 #include "llvm/Support/MathExtras.h" 34 #include "llvm/Support/raw_ostream.h" 35 #include "llvm/Target/TargetLowering.h" 36 #include "llvm/Target/TargetMachine.h" 37 #include "llvm/Target/TargetOptions.h" 38 #include "llvm/Target/TargetRegisterInfo.h" 39 #include "llvm/Target/TargetSubtargetInfo.h" 40 #include <algorithm> 41 using namespace llvm; 42 43 STATISTIC(NodesCombined , "Number of dag nodes combined"); 44 STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created"); 45 STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created"); 46 STATISTIC(OpsNarrowed , "Number of load/op/store narrowed"); 47 STATISTIC(LdStFP2Int , "Number of fp load/store pairs transformed to int"); 48 STATISTIC(SlicedLoads, "Number of load sliced"); 49 50 namespace { 51 static cl::opt<bool> 52 CombinerAA("combiner-alias-analysis", cl::Hidden, 53 cl::desc("Enable DAG combiner alias-analysis heuristics")); 54 55 static cl::opt<bool> 56 CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden, 57 cl::desc("Enable DAG combiner's use of IR alias analysis")); 58 59 static cl::opt<bool> 60 UseTBAA("combiner-use-tbaa", cl::Hidden, cl::init(true), 61 cl::desc("Enable DAG combiner's use of TBAA")); 62 63 #ifndef NDEBUG 64 static cl::opt<std::string> 65 CombinerAAOnlyFunc("combiner-aa-only-func", cl::Hidden, 66 cl::desc("Only use DAG-combiner alias analysis in this" 67 " function")); 68 #endif 69 70 /// Hidden option to stress test load slicing, i.e., when this option 71 /// is enabled, load slicing bypasses most of its profitability guards. 72 static cl::opt<bool> 73 StressLoadSlicing("combiner-stress-load-slicing", cl::Hidden, 74 cl::desc("Bypass the profitability model of load " 75 "slicing"), 76 cl::init(false)); 77 78 //------------------------------ DAGCombiner ---------------------------------// 79 80 class DAGCombiner { 81 SelectionDAG &DAG; 82 const TargetLowering &TLI; 83 CombineLevel Level; 84 CodeGenOpt::Level OptLevel; 85 bool LegalOperations; 86 bool LegalTypes; 87 bool ForCodeSize; 88 89 // Worklist of all of the nodes that need to be simplified. 90 // 91 // This has the semantics that when adding to the worklist, 92 // the item added must be next to be processed. It should 93 // also only appear once. The naive approach to this takes 94 // linear time. 95 // 96 // To reduce the insert/remove time to logarithmic, we use 97 // a set and a vector to maintain our worklist. 98 // 99 // The set contains the items on the worklist, but does not 100 // maintain the order they should be visited. 101 // 102 // The vector maintains the order nodes should be visited, but may 103 // contain duplicate or removed nodes. When choosing a node to 104 // visit, we pop off the order stack until we find an item that is 105 // also in the contents set. All operations are O(log N). 106 SmallPtrSet<SDNode*, 64> WorkListContents; 107 SmallVector<SDNode*, 64> WorkListOrder; 108 109 // AA - Used for DAG load/store alias analysis. 110 AliasAnalysis &AA; 111 112 /// AddUsersToWorkList - When an instruction is simplified, add all users of 113 /// the instruction to the work lists because they might get more simplified 114 /// now. 115 /// 116 void AddUsersToWorkList(SDNode *N) { 117 for (SDNode *Node : N->uses()) 118 AddToWorkList(Node); 119 } 120 121 /// visit - call the node-specific routine that knows how to fold each 122 /// particular type of node. 123 SDValue visit(SDNode *N); 124 125 public: 126 /// AddToWorkList - Add to the work list making sure its instance is at the 127 /// back (next to be processed.) 128 void AddToWorkList(SDNode *N) { 129 WorkListContents.insert(N); 130 WorkListOrder.push_back(N); 131 } 132 133 /// removeFromWorkList - remove all instances of N from the worklist. 134 /// 135 void removeFromWorkList(SDNode *N) { 136 WorkListContents.erase(N); 137 } 138 139 SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo, 140 bool AddTo = true); 141 142 SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) { 143 return CombineTo(N, &Res, 1, AddTo); 144 } 145 146 SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1, 147 bool AddTo = true) { 148 SDValue To[] = { Res0, Res1 }; 149 return CombineTo(N, To, 2, AddTo); 150 } 151 152 void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO); 153 154 private: 155 156 /// SimplifyDemandedBits - Check the specified integer node value to see if 157 /// it can be simplified or if things it uses can be simplified by bit 158 /// propagation. If so, return true. 159 bool SimplifyDemandedBits(SDValue Op) { 160 unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits(); 161 APInt Demanded = APInt::getAllOnesValue(BitWidth); 162 return SimplifyDemandedBits(Op, Demanded); 163 } 164 165 bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded); 166 167 bool CombineToPreIndexedLoadStore(SDNode *N); 168 bool CombineToPostIndexedLoadStore(SDNode *N); 169 bool SliceUpLoad(SDNode *N); 170 171 void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad); 172 SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace); 173 SDValue SExtPromoteOperand(SDValue Op, EVT PVT); 174 SDValue ZExtPromoteOperand(SDValue Op, EVT PVT); 175 SDValue PromoteIntBinOp(SDValue Op); 176 SDValue PromoteIntShiftOp(SDValue Op); 177 SDValue PromoteExtend(SDValue Op); 178 bool PromoteLoad(SDValue Op); 179 180 void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs, 181 SDValue Trunc, SDValue ExtLoad, SDLoc DL, 182 ISD::NodeType ExtType); 183 184 /// combine - call the node-specific routine that knows how to fold each 185 /// particular type of node. If that doesn't do anything, try the 186 /// target-specific DAG combines. 187 SDValue combine(SDNode *N); 188 189 // Visitation implementation - Implement dag node combining for different 190 // node types. The semantics are as follows: 191 // Return Value: 192 // SDValue.getNode() == 0 - No change was made 193 // SDValue.getNode() == N - N was replaced, is dead and has been handled. 194 // otherwise - N should be replaced by the returned Operand. 195 // 196 SDValue visitTokenFactor(SDNode *N); 197 SDValue visitMERGE_VALUES(SDNode *N); 198 SDValue visitADD(SDNode *N); 199 SDValue visitSUB(SDNode *N); 200 SDValue visitADDC(SDNode *N); 201 SDValue visitSUBC(SDNode *N); 202 SDValue visitADDE(SDNode *N); 203 SDValue visitSUBE(SDNode *N); 204 SDValue visitMUL(SDNode *N); 205 SDValue visitSDIV(SDNode *N); 206 SDValue visitUDIV(SDNode *N); 207 SDValue visitSREM(SDNode *N); 208 SDValue visitUREM(SDNode *N); 209 SDValue visitMULHU(SDNode *N); 210 SDValue visitMULHS(SDNode *N); 211 SDValue visitSMUL_LOHI(SDNode *N); 212 SDValue visitUMUL_LOHI(SDNode *N); 213 SDValue visitSMULO(SDNode *N); 214 SDValue visitUMULO(SDNode *N); 215 SDValue visitSDIVREM(SDNode *N); 216 SDValue visitUDIVREM(SDNode *N); 217 SDValue visitAND(SDNode *N); 218 SDValue visitOR(SDNode *N); 219 SDValue visitXOR(SDNode *N); 220 SDValue SimplifyVBinOp(SDNode *N); 221 SDValue SimplifyVUnaryOp(SDNode *N); 222 SDValue visitSHL(SDNode *N); 223 SDValue visitSRA(SDNode *N); 224 SDValue visitSRL(SDNode *N); 225 SDValue visitRotate(SDNode *N); 226 SDValue visitCTLZ(SDNode *N); 227 SDValue visitCTLZ_ZERO_UNDEF(SDNode *N); 228 SDValue visitCTTZ(SDNode *N); 229 SDValue visitCTTZ_ZERO_UNDEF(SDNode *N); 230 SDValue visitCTPOP(SDNode *N); 231 SDValue visitSELECT(SDNode *N); 232 SDValue visitVSELECT(SDNode *N); 233 SDValue visitSELECT_CC(SDNode *N); 234 SDValue visitSETCC(SDNode *N); 235 SDValue visitSIGN_EXTEND(SDNode *N); 236 SDValue visitZERO_EXTEND(SDNode *N); 237 SDValue visitANY_EXTEND(SDNode *N); 238 SDValue visitSIGN_EXTEND_INREG(SDNode *N); 239 SDValue visitTRUNCATE(SDNode *N); 240 SDValue visitBITCAST(SDNode *N); 241 SDValue visitBUILD_PAIR(SDNode *N); 242 SDValue visitFADD(SDNode *N); 243 SDValue visitFSUB(SDNode *N); 244 SDValue visitFMUL(SDNode *N); 245 SDValue visitFMA(SDNode *N); 246 SDValue visitFDIV(SDNode *N); 247 SDValue visitFREM(SDNode *N); 248 SDValue visitFCOPYSIGN(SDNode *N); 249 SDValue visitSINT_TO_FP(SDNode *N); 250 SDValue visitUINT_TO_FP(SDNode *N); 251 SDValue visitFP_TO_SINT(SDNode *N); 252 SDValue visitFP_TO_UINT(SDNode *N); 253 SDValue visitFP_ROUND(SDNode *N); 254 SDValue visitFP_ROUND_INREG(SDNode *N); 255 SDValue visitFP_EXTEND(SDNode *N); 256 SDValue visitFNEG(SDNode *N); 257 SDValue visitFABS(SDNode *N); 258 SDValue visitFCEIL(SDNode *N); 259 SDValue visitFTRUNC(SDNode *N); 260 SDValue visitFFLOOR(SDNode *N); 261 SDValue visitBRCOND(SDNode *N); 262 SDValue visitBR_CC(SDNode *N); 263 SDValue visitLOAD(SDNode *N); 264 SDValue visitSTORE(SDNode *N); 265 SDValue visitINSERT_VECTOR_ELT(SDNode *N); 266 SDValue visitEXTRACT_VECTOR_ELT(SDNode *N); 267 SDValue visitBUILD_VECTOR(SDNode *N); 268 SDValue visitCONCAT_VECTORS(SDNode *N); 269 SDValue visitEXTRACT_SUBVECTOR(SDNode *N); 270 SDValue visitVECTOR_SHUFFLE(SDNode *N); 271 SDValue visitINSERT_SUBVECTOR(SDNode *N); 272 273 SDValue XformToShuffleWithZero(SDNode *N); 274 SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS); 275 276 SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt); 277 278 bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS); 279 SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N); 280 SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2); 281 SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2, 282 SDValue N3, ISD::CondCode CC, 283 bool NotExtCompare = false); 284 SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond, 285 SDLoc DL, bool foldBooleans = true); 286 287 bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS, 288 SDValue &CC) const; 289 bool isOneUseSetCC(SDValue N) const; 290 291 SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp, 292 unsigned HiOp); 293 SDValue CombineConsecutiveLoads(SDNode *N, EVT VT); 294 SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT); 295 SDValue BuildSDIV(SDNode *N); 296 SDValue BuildUDIV(SDNode *N); 297 SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1, 298 bool DemandHighBits = true); 299 SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1); 300 SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg, 301 SDValue InnerPos, SDValue InnerNeg, 302 unsigned PosOpcode, unsigned NegOpcode, 303 SDLoc DL); 304 SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL); 305 SDValue ReduceLoadWidth(SDNode *N); 306 SDValue ReduceLoadOpStoreWidth(SDNode *N); 307 SDValue TransformFPLoadStorePair(SDNode *N); 308 SDValue reduceBuildVecExtToExtBuildVec(SDNode *N); 309 SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N); 310 311 SDValue GetDemandedBits(SDValue V, const APInt &Mask); 312 313 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes, 314 /// looking for aliasing nodes and adding them to the Aliases vector. 315 void GatherAllAliases(SDNode *N, SDValue OriginalChain, 316 SmallVectorImpl<SDValue> &Aliases); 317 318 /// isAlias - Return true if there is any possibility that the two addresses 319 /// overlap. 320 bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const; 321 322 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes, 323 /// looking for a better chain (aliasing node.) 324 SDValue FindBetterChain(SDNode *N, SDValue Chain); 325 326 /// Merge consecutive store operations into a wide store. 327 /// This optimization uses wide integers or vectors when possible. 328 /// \return True if some memory operations were changed. 329 bool MergeConsecutiveStores(StoreSDNode *N); 330 331 /// \brief Try to transform a truncation where C is a constant: 332 /// (trunc (and X, C)) -> (and (trunc X), (trunc C)) 333 /// 334 /// \p N needs to be a truncation and its first operand an AND. Other 335 /// requirements are checked by the function (e.g. that trunc is 336 /// single-use) and if missed an empty SDValue is returned. 337 SDValue distributeTruncateThroughAnd(SDNode *N); 338 339 public: 340 DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL) 341 : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes), 342 OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) { 343 AttributeSet FnAttrs = 344 DAG.getMachineFunction().getFunction()->getAttributes(); 345 ForCodeSize = 346 FnAttrs.hasAttribute(AttributeSet::FunctionIndex, 347 Attribute::OptimizeForSize) || 348 FnAttrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::MinSize); 349 } 350 351 /// Run - runs the dag combiner on all nodes in the work list 352 void Run(CombineLevel AtLevel); 353 354 SelectionDAG &getDAG() const { return DAG; } 355 356 /// getShiftAmountTy - Returns a type large enough to hold any valid 357 /// shift amount - before type legalization these can be huge. 358 EVT getShiftAmountTy(EVT LHSTy) { 359 assert(LHSTy.isInteger() && "Shift amount is not an integer type!"); 360 if (LHSTy.isVector()) 361 return LHSTy; 362 return LegalTypes ? TLI.getScalarShiftAmountTy(LHSTy) 363 : TLI.getPointerTy(); 364 } 365 366 /// isTypeLegal - This method returns true if we are running before type 367 /// legalization or if the specified VT is legal. 368 bool isTypeLegal(const EVT &VT) { 369 if (!LegalTypes) return true; 370 return TLI.isTypeLegal(VT); 371 } 372 373 /// getSetCCResultType - Convenience wrapper around 374 /// TargetLowering::getSetCCResultType 375 EVT getSetCCResultType(EVT VT) const { 376 return TLI.getSetCCResultType(*DAG.getContext(), VT); 377 } 378 }; 379 } 380 381 382 namespace { 383 /// WorkListRemover - This class is a DAGUpdateListener that removes any deleted 384 /// nodes from the worklist. 385 class WorkListRemover : public SelectionDAG::DAGUpdateListener { 386 DAGCombiner &DC; 387 public: 388 explicit WorkListRemover(DAGCombiner &dc) 389 : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {} 390 391 void NodeDeleted(SDNode *N, SDNode *E) override { 392 DC.removeFromWorkList(N); 393 } 394 }; 395 } 396 397 //===----------------------------------------------------------------------===// 398 // TargetLowering::DAGCombinerInfo implementation 399 //===----------------------------------------------------------------------===// 400 401 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) { 402 ((DAGCombiner*)DC)->AddToWorkList(N); 403 } 404 405 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) { 406 ((DAGCombiner*)DC)->removeFromWorkList(N); 407 } 408 409 SDValue TargetLowering::DAGCombinerInfo:: 410 CombineTo(SDNode *N, const std::vector<SDValue> &To, bool AddTo) { 411 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo); 412 } 413 414 SDValue TargetLowering::DAGCombinerInfo:: 415 CombineTo(SDNode *N, SDValue Res, bool AddTo) { 416 return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo); 417 } 418 419 420 SDValue TargetLowering::DAGCombinerInfo:: 421 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) { 422 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo); 423 } 424 425 void TargetLowering::DAGCombinerInfo:: 426 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) { 427 return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO); 428 } 429 430 //===----------------------------------------------------------------------===// 431 // Helper Functions 432 //===----------------------------------------------------------------------===// 433 434 /// isNegatibleForFree - Return 1 if we can compute the negated form of the 435 /// specified expression for the same cost as the expression itself, or 2 if we 436 /// can compute the negated form more cheaply than the expression itself. 437 static char isNegatibleForFree(SDValue Op, bool LegalOperations, 438 const TargetLowering &TLI, 439 const TargetOptions *Options, 440 unsigned Depth = 0) { 441 // fneg is removable even if it has multiple uses. 442 if (Op.getOpcode() == ISD::FNEG) return 2; 443 444 // Don't allow anything with multiple uses. 445 if (!Op.hasOneUse()) return 0; 446 447 // Don't recurse exponentially. 448 if (Depth > 6) return 0; 449 450 switch (Op.getOpcode()) { 451 default: return false; 452 case ISD::ConstantFP: 453 // Don't invert constant FP values after legalize. The negated constant 454 // isn't necessarily legal. 455 return LegalOperations ? 0 : 1; 456 case ISD::FADD: 457 // FIXME: determine better conditions for this xform. 458 if (!Options->UnsafeFPMath) return 0; 459 460 // After operation legalization, it might not be legal to create new FSUBs. 461 if (LegalOperations && 462 !TLI.isOperationLegalOrCustom(ISD::FSUB, Op.getValueType())) 463 return 0; 464 465 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B) 466 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, 467 Options, Depth + 1)) 468 return V; 469 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A) 470 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options, 471 Depth + 1); 472 case ISD::FSUB: 473 // We can't turn -(A-B) into B-A when we honor signed zeros. 474 if (!Options->UnsafeFPMath) return 0; 475 476 // fold (fneg (fsub A, B)) -> (fsub B, A) 477 return 1; 478 479 case ISD::FMUL: 480 case ISD::FDIV: 481 if (Options->HonorSignDependentRoundingFPMath()) return 0; 482 483 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y)) 484 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, 485 Options, Depth + 1)) 486 return V; 487 488 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options, 489 Depth + 1); 490 491 case ISD::FP_EXTEND: 492 case ISD::FP_ROUND: 493 case ISD::FSIN: 494 return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options, 495 Depth + 1); 496 } 497 } 498 499 /// GetNegatedExpression - If isNegatibleForFree returns true, this function 500 /// returns the newly negated expression. 501 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG, 502 bool LegalOperations, unsigned Depth = 0) { 503 // fneg is removable even if it has multiple uses. 504 if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0); 505 506 // Don't allow anything with multiple uses. 507 assert(Op.hasOneUse() && "Unknown reuse!"); 508 509 assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree"); 510 switch (Op.getOpcode()) { 511 default: llvm_unreachable("Unknown code"); 512 case ISD::ConstantFP: { 513 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF(); 514 V.changeSign(); 515 return DAG.getConstantFP(V, Op.getValueType()); 516 } 517 case ISD::FADD: 518 // FIXME: determine better conditions for this xform. 519 assert(DAG.getTarget().Options.UnsafeFPMath); 520 521 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B) 522 if (isNegatibleForFree(Op.getOperand(0), LegalOperations, 523 DAG.getTargetLoweringInfo(), 524 &DAG.getTarget().Options, Depth+1)) 525 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(), 526 GetNegatedExpression(Op.getOperand(0), DAG, 527 LegalOperations, Depth+1), 528 Op.getOperand(1)); 529 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A) 530 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(), 531 GetNegatedExpression(Op.getOperand(1), DAG, 532 LegalOperations, Depth+1), 533 Op.getOperand(0)); 534 case ISD::FSUB: 535 // We can't turn -(A-B) into B-A when we honor signed zeros. 536 assert(DAG.getTarget().Options.UnsafeFPMath); 537 538 // fold (fneg (fsub 0, B)) -> B 539 if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0))) 540 if (N0CFP->getValueAPF().isZero()) 541 return Op.getOperand(1); 542 543 // fold (fneg (fsub A, B)) -> (fsub B, A) 544 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(), 545 Op.getOperand(1), Op.getOperand(0)); 546 547 case ISD::FMUL: 548 case ISD::FDIV: 549 assert(!DAG.getTarget().Options.HonorSignDependentRoundingFPMath()); 550 551 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) 552 if (isNegatibleForFree(Op.getOperand(0), LegalOperations, 553 DAG.getTargetLoweringInfo(), 554 &DAG.getTarget().Options, Depth+1)) 555 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(), 556 GetNegatedExpression(Op.getOperand(0), DAG, 557 LegalOperations, Depth+1), 558 Op.getOperand(1)); 559 560 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y)) 561 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(), 562 Op.getOperand(0), 563 GetNegatedExpression(Op.getOperand(1), DAG, 564 LegalOperations, Depth+1)); 565 566 case ISD::FP_EXTEND: 567 case ISD::FSIN: 568 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(), 569 GetNegatedExpression(Op.getOperand(0), DAG, 570 LegalOperations, Depth+1)); 571 case ISD::FP_ROUND: 572 return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(), 573 GetNegatedExpression(Op.getOperand(0), DAG, 574 LegalOperations, Depth+1), 575 Op.getOperand(1)); 576 } 577 } 578 579 // isSetCCEquivalent - Return true if this node is a setcc, or is a select_cc 580 // that selects between the target values used for true and false, making it 581 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to 582 // the appropriate nodes based on the type of node we are checking. This 583 // simplifies life a bit for the callers. 584 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS, 585 SDValue &CC) const { 586 if (N.getOpcode() == ISD::SETCC) { 587 LHS = N.getOperand(0); 588 RHS = N.getOperand(1); 589 CC = N.getOperand(2); 590 return true; 591 } 592 593 if (N.getOpcode() != ISD::SELECT_CC || 594 !TLI.isConstTrueVal(N.getOperand(2).getNode()) || 595 !TLI.isConstFalseVal(N.getOperand(3).getNode())) 596 return false; 597 598 LHS = N.getOperand(0); 599 RHS = N.getOperand(1); 600 CC = N.getOperand(4); 601 return true; 602 } 603 604 // isOneUseSetCC - Return true if this is a SetCC-equivalent operation with only 605 // one use. If this is true, it allows the users to invert the operation for 606 // free when it is profitable to do so. 607 bool DAGCombiner::isOneUseSetCC(SDValue N) const { 608 SDValue N0, N1, N2; 609 if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse()) 610 return true; 611 return false; 612 } 613 614 /// isConstantSplatVector - Returns true if N is a BUILD_VECTOR node whose 615 /// elements are all the same constant or undefined. 616 static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) { 617 BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N); 618 if (!C) 619 return false; 620 621 APInt SplatUndef; 622 unsigned SplatBitSize; 623 bool HasAnyUndefs; 624 EVT EltVT = N->getValueType(0).getVectorElementType(); 625 return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize, 626 HasAnyUndefs) && 627 EltVT.getSizeInBits() >= SplatBitSize); 628 } 629 630 // \brief Returns the SDNode if it is a constant BuildVector or constant. 631 static SDNode *isConstantBuildVectorOrConstantInt(SDValue N) { 632 if (isa<ConstantSDNode>(N)) 633 return N.getNode(); 634 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N); 635 if(BV && BV->isConstant()) 636 return BV; 637 return nullptr; 638 } 639 640 // \brief Returns the SDNode if it is a constant splat BuildVector or constant 641 // int. 642 static ConstantSDNode *isConstOrConstSplat(SDValue N) { 643 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) 644 return CN; 645 646 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) 647 return BV->getConstantSplatValue(); 648 649 return nullptr; 650 } 651 652 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL, 653 SDValue N0, SDValue N1) { 654 EVT VT = N0.getValueType(); 655 if (N0.getOpcode() == Opc) { 656 if (SDNode *L = isConstantBuildVectorOrConstantInt(N0.getOperand(1))) { 657 if (SDNode *R = isConstantBuildVectorOrConstantInt(N1)) { 658 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2)) 659 SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, L, R); 660 if (!OpNode.getNode()) 661 return SDValue(); 662 return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode); 663 } 664 if (N0.hasOneUse()) { 665 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one 666 // use 667 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1); 668 if (!OpNode.getNode()) 669 return SDValue(); 670 AddToWorkList(OpNode.getNode()); 671 return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1)); 672 } 673 } 674 } 675 676 if (N1.getOpcode() == Opc) { 677 if (SDNode *R = isConstantBuildVectorOrConstantInt(N1.getOperand(1))) { 678 if (SDNode *L = isConstantBuildVectorOrConstantInt(N0)) { 679 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2)) 680 SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, R, L); 681 if (!OpNode.getNode()) 682 return SDValue(); 683 return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode); 684 } 685 if (N1.hasOneUse()) { 686 // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one 687 // use 688 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0); 689 if (!OpNode.getNode()) 690 return SDValue(); 691 AddToWorkList(OpNode.getNode()); 692 return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1)); 693 } 694 } 695 } 696 697 return SDValue(); 698 } 699 700 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo, 701 bool AddTo) { 702 assert(N->getNumValues() == NumTo && "Broken CombineTo call!"); 703 ++NodesCombined; 704 DEBUG(dbgs() << "\nReplacing.1 "; 705 N->dump(&DAG); 706 dbgs() << "\nWith: "; 707 To[0].getNode()->dump(&DAG); 708 dbgs() << " and " << NumTo-1 << " other values\n"; 709 for (unsigned i = 0, e = NumTo; i != e; ++i) 710 assert((!To[i].getNode() || 711 N->getValueType(i) == To[i].getValueType()) && 712 "Cannot combine value to value of different type!")); 713 WorkListRemover DeadNodes(*this); 714 DAG.ReplaceAllUsesWith(N, To); 715 if (AddTo) { 716 // Push the new nodes and any users onto the worklist 717 for (unsigned i = 0, e = NumTo; i != e; ++i) { 718 if (To[i].getNode()) { 719 AddToWorkList(To[i].getNode()); 720 AddUsersToWorkList(To[i].getNode()); 721 } 722 } 723 } 724 725 // Finally, if the node is now dead, remove it from the graph. The node 726 // may not be dead if the replacement process recursively simplified to 727 // something else needing this node. 728 if (N->use_empty()) { 729 // Nodes can be reintroduced into the worklist. Make sure we do not 730 // process a node that has been replaced. 731 removeFromWorkList(N); 732 733 // Finally, since the node is now dead, remove it from the graph. 734 DAG.DeleteNode(N); 735 } 736 return SDValue(N, 0); 737 } 738 739 void DAGCombiner:: 740 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) { 741 // Replace all uses. If any nodes become isomorphic to other nodes and 742 // are deleted, make sure to remove them from our worklist. 743 WorkListRemover DeadNodes(*this); 744 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New); 745 746 // Push the new node and any (possibly new) users onto the worklist. 747 AddToWorkList(TLO.New.getNode()); 748 AddUsersToWorkList(TLO.New.getNode()); 749 750 // Finally, if the node is now dead, remove it from the graph. The node 751 // may not be dead if the replacement process recursively simplified to 752 // something else needing this node. 753 if (TLO.Old.getNode()->use_empty()) { 754 removeFromWorkList(TLO.Old.getNode()); 755 756 // If the operands of this node are only used by the node, they will now 757 // be dead. Make sure to visit them first to delete dead nodes early. 758 for (unsigned i = 0, e = TLO.Old.getNode()->getNumOperands(); i != e; ++i) 759 if (TLO.Old.getNode()->getOperand(i).getNode()->hasOneUse()) 760 AddToWorkList(TLO.Old.getNode()->getOperand(i).getNode()); 761 762 DAG.DeleteNode(TLO.Old.getNode()); 763 } 764 } 765 766 /// SimplifyDemandedBits - Check the specified integer node value to see if 767 /// it can be simplified or if things it uses can be simplified by bit 768 /// propagation. If so, return true. 769 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) { 770 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations); 771 APInt KnownZero, KnownOne; 772 if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO)) 773 return false; 774 775 // Revisit the node. 776 AddToWorkList(Op.getNode()); 777 778 // Replace the old value with the new one. 779 ++NodesCombined; 780 DEBUG(dbgs() << "\nReplacing.2 "; 781 TLO.Old.getNode()->dump(&DAG); 782 dbgs() << "\nWith: "; 783 TLO.New.getNode()->dump(&DAG); 784 dbgs() << '\n'); 785 786 CommitTargetLoweringOpt(TLO); 787 return true; 788 } 789 790 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) { 791 SDLoc dl(Load); 792 EVT VT = Load->getValueType(0); 793 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0)); 794 795 DEBUG(dbgs() << "\nReplacing.9 "; 796 Load->dump(&DAG); 797 dbgs() << "\nWith: "; 798 Trunc.getNode()->dump(&DAG); 799 dbgs() << '\n'); 800 WorkListRemover DeadNodes(*this); 801 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc); 802 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1)); 803 removeFromWorkList(Load); 804 DAG.DeleteNode(Load); 805 AddToWorkList(Trunc.getNode()); 806 } 807 808 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) { 809 Replace = false; 810 SDLoc dl(Op); 811 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) { 812 EVT MemVT = LD->getMemoryVT(); 813 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD) 814 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD 815 : ISD::EXTLOAD) 816 : LD->getExtensionType(); 817 Replace = true; 818 return DAG.getExtLoad(ExtType, dl, PVT, 819 LD->getChain(), LD->getBasePtr(), 820 MemVT, LD->getMemOperand()); 821 } 822 823 unsigned Opc = Op.getOpcode(); 824 switch (Opc) { 825 default: break; 826 case ISD::AssertSext: 827 return DAG.getNode(ISD::AssertSext, dl, PVT, 828 SExtPromoteOperand(Op.getOperand(0), PVT), 829 Op.getOperand(1)); 830 case ISD::AssertZext: 831 return DAG.getNode(ISD::AssertZext, dl, PVT, 832 ZExtPromoteOperand(Op.getOperand(0), PVT), 833 Op.getOperand(1)); 834 case ISD::Constant: { 835 unsigned ExtOpc = 836 Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 837 return DAG.getNode(ExtOpc, dl, PVT, Op); 838 } 839 } 840 841 if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT)) 842 return SDValue(); 843 return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op); 844 } 845 846 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) { 847 if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT)) 848 return SDValue(); 849 EVT OldVT = Op.getValueType(); 850 SDLoc dl(Op); 851 bool Replace = false; 852 SDValue NewOp = PromoteOperand(Op, PVT, Replace); 853 if (!NewOp.getNode()) 854 return SDValue(); 855 AddToWorkList(NewOp.getNode()); 856 857 if (Replace) 858 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode()); 859 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp, 860 DAG.getValueType(OldVT)); 861 } 862 863 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) { 864 EVT OldVT = Op.getValueType(); 865 SDLoc dl(Op); 866 bool Replace = false; 867 SDValue NewOp = PromoteOperand(Op, PVT, Replace); 868 if (!NewOp.getNode()) 869 return SDValue(); 870 AddToWorkList(NewOp.getNode()); 871 872 if (Replace) 873 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode()); 874 return DAG.getZeroExtendInReg(NewOp, dl, OldVT); 875 } 876 877 /// PromoteIntBinOp - Promote the specified integer binary operation if the 878 /// target indicates it is beneficial. e.g. On x86, it's usually better to 879 /// promote i16 operations to i32 since i16 instructions are longer. 880 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) { 881 if (!LegalOperations) 882 return SDValue(); 883 884 EVT VT = Op.getValueType(); 885 if (VT.isVector() || !VT.isInteger()) 886 return SDValue(); 887 888 // If operation type is 'undesirable', e.g. i16 on x86, consider 889 // promoting it. 890 unsigned Opc = Op.getOpcode(); 891 if (TLI.isTypeDesirableForOp(Opc, VT)) 892 return SDValue(); 893 894 EVT PVT = VT; 895 // Consult target whether it is a good idea to promote this operation and 896 // what's the right type to promote it to. 897 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 898 assert(PVT != VT && "Don't know what type to promote to!"); 899 900 bool Replace0 = false; 901 SDValue N0 = Op.getOperand(0); 902 SDValue NN0 = PromoteOperand(N0, PVT, Replace0); 903 if (!NN0.getNode()) 904 return SDValue(); 905 906 bool Replace1 = false; 907 SDValue N1 = Op.getOperand(1); 908 SDValue NN1; 909 if (N0 == N1) 910 NN1 = NN0; 911 else { 912 NN1 = PromoteOperand(N1, PVT, Replace1); 913 if (!NN1.getNode()) 914 return SDValue(); 915 } 916 917 AddToWorkList(NN0.getNode()); 918 if (NN1.getNode()) 919 AddToWorkList(NN1.getNode()); 920 921 if (Replace0) 922 ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode()); 923 if (Replace1) 924 ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode()); 925 926 DEBUG(dbgs() << "\nPromoting "; 927 Op.getNode()->dump(&DAG)); 928 SDLoc dl(Op); 929 return DAG.getNode(ISD::TRUNCATE, dl, VT, 930 DAG.getNode(Opc, dl, PVT, NN0, NN1)); 931 } 932 return SDValue(); 933 } 934 935 /// PromoteIntShiftOp - Promote the specified integer shift operation if the 936 /// target indicates it is beneficial. e.g. On x86, it's usually better to 937 /// promote i16 operations to i32 since i16 instructions are longer. 938 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) { 939 if (!LegalOperations) 940 return SDValue(); 941 942 EVT VT = Op.getValueType(); 943 if (VT.isVector() || !VT.isInteger()) 944 return SDValue(); 945 946 // If operation type is 'undesirable', e.g. i16 on x86, consider 947 // promoting it. 948 unsigned Opc = Op.getOpcode(); 949 if (TLI.isTypeDesirableForOp(Opc, VT)) 950 return SDValue(); 951 952 EVT PVT = VT; 953 // Consult target whether it is a good idea to promote this operation and 954 // what's the right type to promote it to. 955 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 956 assert(PVT != VT && "Don't know what type to promote to!"); 957 958 bool Replace = false; 959 SDValue N0 = Op.getOperand(0); 960 if (Opc == ISD::SRA) 961 N0 = SExtPromoteOperand(Op.getOperand(0), PVT); 962 else if (Opc == ISD::SRL) 963 N0 = ZExtPromoteOperand(Op.getOperand(0), PVT); 964 else 965 N0 = PromoteOperand(N0, PVT, Replace); 966 if (!N0.getNode()) 967 return SDValue(); 968 969 AddToWorkList(N0.getNode()); 970 if (Replace) 971 ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode()); 972 973 DEBUG(dbgs() << "\nPromoting "; 974 Op.getNode()->dump(&DAG)); 975 SDLoc dl(Op); 976 return DAG.getNode(ISD::TRUNCATE, dl, VT, 977 DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1))); 978 } 979 return SDValue(); 980 } 981 982 SDValue DAGCombiner::PromoteExtend(SDValue Op) { 983 if (!LegalOperations) 984 return SDValue(); 985 986 EVT VT = Op.getValueType(); 987 if (VT.isVector() || !VT.isInteger()) 988 return SDValue(); 989 990 // If operation type is 'undesirable', e.g. i16 on x86, consider 991 // promoting it. 992 unsigned Opc = Op.getOpcode(); 993 if (TLI.isTypeDesirableForOp(Opc, VT)) 994 return SDValue(); 995 996 EVT PVT = VT; 997 // Consult target whether it is a good idea to promote this operation and 998 // what's the right type to promote it to. 999 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 1000 assert(PVT != VT && "Don't know what type to promote to!"); 1001 // fold (aext (aext x)) -> (aext x) 1002 // fold (aext (zext x)) -> (zext x) 1003 // fold (aext (sext x)) -> (sext x) 1004 DEBUG(dbgs() << "\nPromoting "; 1005 Op.getNode()->dump(&DAG)); 1006 return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0)); 1007 } 1008 return SDValue(); 1009 } 1010 1011 bool DAGCombiner::PromoteLoad(SDValue Op) { 1012 if (!LegalOperations) 1013 return false; 1014 1015 EVT VT = Op.getValueType(); 1016 if (VT.isVector() || !VT.isInteger()) 1017 return false; 1018 1019 // If operation type is 'undesirable', e.g. i16 on x86, consider 1020 // promoting it. 1021 unsigned Opc = Op.getOpcode(); 1022 if (TLI.isTypeDesirableForOp(Opc, VT)) 1023 return false; 1024 1025 EVT PVT = VT; 1026 // Consult target whether it is a good idea to promote this operation and 1027 // what's the right type to promote it to. 1028 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 1029 assert(PVT != VT && "Don't know what type to promote to!"); 1030 1031 SDLoc dl(Op); 1032 SDNode *N = Op.getNode(); 1033 LoadSDNode *LD = cast<LoadSDNode>(N); 1034 EVT MemVT = LD->getMemoryVT(); 1035 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD) 1036 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD 1037 : ISD::EXTLOAD) 1038 : LD->getExtensionType(); 1039 SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT, 1040 LD->getChain(), LD->getBasePtr(), 1041 MemVT, LD->getMemOperand()); 1042 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD); 1043 1044 DEBUG(dbgs() << "\nPromoting "; 1045 N->dump(&DAG); 1046 dbgs() << "\nTo: "; 1047 Result.getNode()->dump(&DAG); 1048 dbgs() << '\n'); 1049 WorkListRemover DeadNodes(*this); 1050 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result); 1051 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1)); 1052 removeFromWorkList(N); 1053 DAG.DeleteNode(N); 1054 AddToWorkList(Result.getNode()); 1055 return true; 1056 } 1057 return false; 1058 } 1059 1060 1061 //===----------------------------------------------------------------------===// 1062 // Main DAG Combiner implementation 1063 //===----------------------------------------------------------------------===// 1064 1065 void DAGCombiner::Run(CombineLevel AtLevel) { 1066 // set the instance variables, so that the various visit routines may use it. 1067 Level = AtLevel; 1068 LegalOperations = Level >= AfterLegalizeVectorOps; 1069 LegalTypes = Level >= AfterLegalizeTypes; 1070 1071 // Add all the dag nodes to the worklist. 1072 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(), 1073 E = DAG.allnodes_end(); I != E; ++I) 1074 AddToWorkList(I); 1075 1076 // Create a dummy node (which is not added to allnodes), that adds a reference 1077 // to the root node, preventing it from being deleted, and tracking any 1078 // changes of the root. 1079 HandleSDNode Dummy(DAG.getRoot()); 1080 1081 // The root of the dag may dangle to deleted nodes until the dag combiner is 1082 // done. Set it to null to avoid confusion. 1083 DAG.setRoot(SDValue()); 1084 1085 // while the worklist isn't empty, find a node and 1086 // try and combine it. 1087 while (!WorkListContents.empty()) { 1088 SDNode *N; 1089 // The WorkListOrder holds the SDNodes in order, but it may contain 1090 // duplicates. 1091 // In order to avoid a linear scan, we use a set (O(log N)) to hold what the 1092 // worklist *should* contain, and check the node we want to visit is should 1093 // actually be visited. 1094 do { 1095 N = WorkListOrder.pop_back_val(); 1096 } while (!WorkListContents.erase(N)); 1097 1098 // If N has no uses, it is dead. Make sure to revisit all N's operands once 1099 // N is deleted from the DAG, since they too may now be dead or may have a 1100 // reduced number of uses, allowing other xforms. 1101 if (N->use_empty() && N != &Dummy) { 1102 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) 1103 AddToWorkList(N->getOperand(i).getNode()); 1104 1105 DAG.DeleteNode(N); 1106 continue; 1107 } 1108 1109 SDValue RV = combine(N); 1110 1111 if (!RV.getNode()) 1112 continue; 1113 1114 ++NodesCombined; 1115 1116 // If we get back the same node we passed in, rather than a new node or 1117 // zero, we know that the node must have defined multiple values and 1118 // CombineTo was used. Since CombineTo takes care of the worklist 1119 // mechanics for us, we have no work to do in this case. 1120 if (RV.getNode() == N) 1121 continue; 1122 1123 assert(N->getOpcode() != ISD::DELETED_NODE && 1124 RV.getNode()->getOpcode() != ISD::DELETED_NODE && 1125 "Node was deleted but visit returned new node!"); 1126 1127 DEBUG(dbgs() << "\nReplacing.3 "; 1128 N->dump(&DAG); 1129 dbgs() << "\nWith: "; 1130 RV.getNode()->dump(&DAG); 1131 dbgs() << '\n'); 1132 1133 // Transfer debug value. 1134 DAG.TransferDbgValues(SDValue(N, 0), RV); 1135 WorkListRemover DeadNodes(*this); 1136 if (N->getNumValues() == RV.getNode()->getNumValues()) 1137 DAG.ReplaceAllUsesWith(N, RV.getNode()); 1138 else { 1139 assert(N->getValueType(0) == RV.getValueType() && 1140 N->getNumValues() == 1 && "Type mismatch"); 1141 SDValue OpV = RV; 1142 DAG.ReplaceAllUsesWith(N, &OpV); 1143 } 1144 1145 // Push the new node and any users onto the worklist 1146 AddToWorkList(RV.getNode()); 1147 AddUsersToWorkList(RV.getNode()); 1148 1149 // Add any uses of the old node to the worklist in case this node is the 1150 // last one that uses them. They may become dead after this node is 1151 // deleted. 1152 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) 1153 AddToWorkList(N->getOperand(i).getNode()); 1154 1155 // Finally, if the node is now dead, remove it from the graph. The node 1156 // may not be dead if the replacement process recursively simplified to 1157 // something else needing this node. 1158 if (N->use_empty()) { 1159 // Nodes can be reintroduced into the worklist. Make sure we do not 1160 // process a node that has been replaced. 1161 removeFromWorkList(N); 1162 1163 // Finally, since the node is now dead, remove it from the graph. 1164 DAG.DeleteNode(N); 1165 } 1166 } 1167 1168 // If the root changed (e.g. it was a dead load, update the root). 1169 DAG.setRoot(Dummy.getValue()); 1170 DAG.RemoveDeadNodes(); 1171 } 1172 1173 SDValue DAGCombiner::visit(SDNode *N) { 1174 switch (N->getOpcode()) { 1175 default: break; 1176 case ISD::TokenFactor: return visitTokenFactor(N); 1177 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N); 1178 case ISD::ADD: return visitADD(N); 1179 case ISD::SUB: return visitSUB(N); 1180 case ISD::ADDC: return visitADDC(N); 1181 case ISD::SUBC: return visitSUBC(N); 1182 case ISD::ADDE: return visitADDE(N); 1183 case ISD::SUBE: return visitSUBE(N); 1184 case ISD::MUL: return visitMUL(N); 1185 case ISD::SDIV: return visitSDIV(N); 1186 case ISD::UDIV: return visitUDIV(N); 1187 case ISD::SREM: return visitSREM(N); 1188 case ISD::UREM: return visitUREM(N); 1189 case ISD::MULHU: return visitMULHU(N); 1190 case ISD::MULHS: return visitMULHS(N); 1191 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N); 1192 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N); 1193 case ISD::SMULO: return visitSMULO(N); 1194 case ISD::UMULO: return visitUMULO(N); 1195 case ISD::SDIVREM: return visitSDIVREM(N); 1196 case ISD::UDIVREM: return visitUDIVREM(N); 1197 case ISD::AND: return visitAND(N); 1198 case ISD::OR: return visitOR(N); 1199 case ISD::XOR: return visitXOR(N); 1200 case ISD::SHL: return visitSHL(N); 1201 case ISD::SRA: return visitSRA(N); 1202 case ISD::SRL: return visitSRL(N); 1203 case ISD::ROTR: 1204 case ISD::ROTL: return visitRotate(N); 1205 case ISD::CTLZ: return visitCTLZ(N); 1206 case ISD::CTLZ_ZERO_UNDEF: return visitCTLZ_ZERO_UNDEF(N); 1207 case ISD::CTTZ: return visitCTTZ(N); 1208 case ISD::CTTZ_ZERO_UNDEF: return visitCTTZ_ZERO_UNDEF(N); 1209 case ISD::CTPOP: return visitCTPOP(N); 1210 case ISD::SELECT: return visitSELECT(N); 1211 case ISD::VSELECT: return visitVSELECT(N); 1212 case ISD::SELECT_CC: return visitSELECT_CC(N); 1213 case ISD::SETCC: return visitSETCC(N); 1214 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N); 1215 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N); 1216 case ISD::ANY_EXTEND: return visitANY_EXTEND(N); 1217 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N); 1218 case ISD::TRUNCATE: return visitTRUNCATE(N); 1219 case ISD::BITCAST: return visitBITCAST(N); 1220 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N); 1221 case ISD::FADD: return visitFADD(N); 1222 case ISD::FSUB: return visitFSUB(N); 1223 case ISD::FMUL: return visitFMUL(N); 1224 case ISD::FMA: return visitFMA(N); 1225 case ISD::FDIV: return visitFDIV(N); 1226 case ISD::FREM: return visitFREM(N); 1227 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N); 1228 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N); 1229 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N); 1230 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N); 1231 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N); 1232 case ISD::FP_ROUND: return visitFP_ROUND(N); 1233 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N); 1234 case ISD::FP_EXTEND: return visitFP_EXTEND(N); 1235 case ISD::FNEG: return visitFNEG(N); 1236 case ISD::FABS: return visitFABS(N); 1237 case ISD::FFLOOR: return visitFFLOOR(N); 1238 case ISD::FCEIL: return visitFCEIL(N); 1239 case ISD::FTRUNC: return visitFTRUNC(N); 1240 case ISD::BRCOND: return visitBRCOND(N); 1241 case ISD::BR_CC: return visitBR_CC(N); 1242 case ISD::LOAD: return visitLOAD(N); 1243 case ISD::STORE: return visitSTORE(N); 1244 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N); 1245 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N); 1246 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N); 1247 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N); 1248 case ISD::EXTRACT_SUBVECTOR: return visitEXTRACT_SUBVECTOR(N); 1249 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N); 1250 case ISD::INSERT_SUBVECTOR: return visitINSERT_SUBVECTOR(N); 1251 } 1252 return SDValue(); 1253 } 1254 1255 SDValue DAGCombiner::combine(SDNode *N) { 1256 SDValue RV = visit(N); 1257 1258 // If nothing happened, try a target-specific DAG combine. 1259 if (!RV.getNode()) { 1260 assert(N->getOpcode() != ISD::DELETED_NODE && 1261 "Node was deleted but visit returned NULL!"); 1262 1263 if (N->getOpcode() >= ISD::BUILTIN_OP_END || 1264 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) { 1265 1266 // Expose the DAG combiner to the target combiner impls. 1267 TargetLowering::DAGCombinerInfo 1268 DagCombineInfo(DAG, Level, false, this); 1269 1270 RV = TLI.PerformDAGCombine(N, DagCombineInfo); 1271 } 1272 } 1273 1274 // If nothing happened still, try promoting the operation. 1275 if (!RV.getNode()) { 1276 switch (N->getOpcode()) { 1277 default: break; 1278 case ISD::ADD: 1279 case ISD::SUB: 1280 case ISD::MUL: 1281 case ISD::AND: 1282 case ISD::OR: 1283 case ISD::XOR: 1284 RV = PromoteIntBinOp(SDValue(N, 0)); 1285 break; 1286 case ISD::SHL: 1287 case ISD::SRA: 1288 case ISD::SRL: 1289 RV = PromoteIntShiftOp(SDValue(N, 0)); 1290 break; 1291 case ISD::SIGN_EXTEND: 1292 case ISD::ZERO_EXTEND: 1293 case ISD::ANY_EXTEND: 1294 RV = PromoteExtend(SDValue(N, 0)); 1295 break; 1296 case ISD::LOAD: 1297 if (PromoteLoad(SDValue(N, 0))) 1298 RV = SDValue(N, 0); 1299 break; 1300 } 1301 } 1302 1303 // If N is a commutative binary node, try commuting it to enable more 1304 // sdisel CSE. 1305 if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) && 1306 N->getNumValues() == 1) { 1307 SDValue N0 = N->getOperand(0); 1308 SDValue N1 = N->getOperand(1); 1309 1310 // Constant operands are canonicalized to RHS. 1311 if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) { 1312 SDValue Ops[] = { N1, N0 }; 1313 SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), 1314 Ops, 2); 1315 if (CSENode) 1316 return SDValue(CSENode, 0); 1317 } 1318 } 1319 1320 return RV; 1321 } 1322 1323 /// getInputChainForNode - Given a node, return its input chain if it has one, 1324 /// otherwise return a null sd operand. 1325 static SDValue getInputChainForNode(SDNode *N) { 1326 if (unsigned NumOps = N->getNumOperands()) { 1327 if (N->getOperand(0).getValueType() == MVT::Other) 1328 return N->getOperand(0); 1329 if (N->getOperand(NumOps-1).getValueType() == MVT::Other) 1330 return N->getOperand(NumOps-1); 1331 for (unsigned i = 1; i < NumOps-1; ++i) 1332 if (N->getOperand(i).getValueType() == MVT::Other) 1333 return N->getOperand(i); 1334 } 1335 return SDValue(); 1336 } 1337 1338 SDValue DAGCombiner::visitTokenFactor(SDNode *N) { 1339 // If N has two operands, where one has an input chain equal to the other, 1340 // the 'other' chain is redundant. 1341 if (N->getNumOperands() == 2) { 1342 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1)) 1343 return N->getOperand(0); 1344 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0)) 1345 return N->getOperand(1); 1346 } 1347 1348 SmallVector<SDNode *, 8> TFs; // List of token factors to visit. 1349 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor. 1350 SmallPtrSet<SDNode*, 16> SeenOps; 1351 bool Changed = false; // If we should replace this token factor. 1352 1353 // Start out with this token factor. 1354 TFs.push_back(N); 1355 1356 // Iterate through token factors. The TFs grows when new token factors are 1357 // encountered. 1358 for (unsigned i = 0; i < TFs.size(); ++i) { 1359 SDNode *TF = TFs[i]; 1360 1361 // Check each of the operands. 1362 for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) { 1363 SDValue Op = TF->getOperand(i); 1364 1365 switch (Op.getOpcode()) { 1366 case ISD::EntryToken: 1367 // Entry tokens don't need to be added to the list. They are 1368 // rededundant. 1369 Changed = true; 1370 break; 1371 1372 case ISD::TokenFactor: 1373 if (Op.hasOneUse() && 1374 std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) { 1375 // Queue up for processing. 1376 TFs.push_back(Op.getNode()); 1377 // Clean up in case the token factor is removed. 1378 AddToWorkList(Op.getNode()); 1379 Changed = true; 1380 break; 1381 } 1382 // Fall thru 1383 1384 default: 1385 // Only add if it isn't already in the list. 1386 if (SeenOps.insert(Op.getNode())) 1387 Ops.push_back(Op); 1388 else 1389 Changed = true; 1390 break; 1391 } 1392 } 1393 } 1394 1395 SDValue Result; 1396 1397 // If we've change things around then replace token factor. 1398 if (Changed) { 1399 if (Ops.empty()) { 1400 // The entry token is the only possible outcome. 1401 Result = DAG.getEntryNode(); 1402 } else { 1403 // New and improved token factor. 1404 Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), 1405 MVT::Other, &Ops[0], Ops.size()); 1406 } 1407 1408 // Don't add users to work list. 1409 return CombineTo(N, Result, false); 1410 } 1411 1412 return Result; 1413 } 1414 1415 /// MERGE_VALUES can always be eliminated. 1416 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) { 1417 WorkListRemover DeadNodes(*this); 1418 // Replacing results may cause a different MERGE_VALUES to suddenly 1419 // be CSE'd with N, and carry its uses with it. Iterate until no 1420 // uses remain, to ensure that the node can be safely deleted. 1421 // First add the users of this node to the work list so that they 1422 // can be tried again once they have new operands. 1423 AddUsersToWorkList(N); 1424 do { 1425 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) 1426 DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i)); 1427 } while (!N->use_empty()); 1428 removeFromWorkList(N); 1429 DAG.DeleteNode(N); 1430 return SDValue(N, 0); // Return N so it doesn't get rechecked! 1431 } 1432 1433 static 1434 SDValue combineShlAddConstant(SDLoc DL, SDValue N0, SDValue N1, 1435 SelectionDAG &DAG) { 1436 EVT VT = N0.getValueType(); 1437 SDValue N00 = N0.getOperand(0); 1438 SDValue N01 = N0.getOperand(1); 1439 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N01); 1440 1441 if (N01C && N00.getOpcode() == ISD::ADD && N00.getNode()->hasOneUse() && 1442 isa<ConstantSDNode>(N00.getOperand(1))) { 1443 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), ) 1444 N0 = DAG.getNode(ISD::ADD, SDLoc(N0), VT, 1445 DAG.getNode(ISD::SHL, SDLoc(N00), VT, 1446 N00.getOperand(0), N01), 1447 DAG.getNode(ISD::SHL, SDLoc(N01), VT, 1448 N00.getOperand(1), N01)); 1449 return DAG.getNode(ISD::ADD, DL, VT, N0, N1); 1450 } 1451 1452 return SDValue(); 1453 } 1454 1455 SDValue DAGCombiner::visitADD(SDNode *N) { 1456 SDValue N0 = N->getOperand(0); 1457 SDValue N1 = N->getOperand(1); 1458 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 1459 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 1460 EVT VT = N0.getValueType(); 1461 1462 // fold vector ops 1463 if (VT.isVector()) { 1464 SDValue FoldedVOp = SimplifyVBinOp(N); 1465 if (FoldedVOp.getNode()) return FoldedVOp; 1466 1467 // fold (add x, 0) -> x, vector edition 1468 if (ISD::isBuildVectorAllZeros(N1.getNode())) 1469 return N0; 1470 if (ISD::isBuildVectorAllZeros(N0.getNode())) 1471 return N1; 1472 } 1473 1474 // fold (add x, undef) -> undef 1475 if (N0.getOpcode() == ISD::UNDEF) 1476 return N0; 1477 if (N1.getOpcode() == ISD::UNDEF) 1478 return N1; 1479 // fold (add c1, c2) -> c1+c2 1480 if (N0C && N1C) 1481 return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C); 1482 // canonicalize constant to RHS 1483 if (N0C && !N1C) 1484 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0); 1485 // fold (add x, 0) -> x 1486 if (N1C && N1C->isNullValue()) 1487 return N0; 1488 // fold (add Sym, c) -> Sym+c 1489 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0)) 1490 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C && 1491 GA->getOpcode() == ISD::GlobalAddress) 1492 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT, 1493 GA->getOffset() + 1494 (uint64_t)N1C->getSExtValue()); 1495 // fold ((c1-A)+c2) -> (c1+c2)-A 1496 if (N1C && N0.getOpcode() == ISD::SUB) 1497 if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0))) 1498 return DAG.getNode(ISD::SUB, SDLoc(N), VT, 1499 DAG.getConstant(N1C->getAPIntValue()+ 1500 N0C->getAPIntValue(), VT), 1501 N0.getOperand(1)); 1502 // reassociate add 1503 SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1); 1504 if (RADD.getNode()) 1505 return RADD; 1506 // fold ((0-A) + B) -> B-A 1507 if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) && 1508 cast<ConstantSDNode>(N0.getOperand(0))->isNullValue()) 1509 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1)); 1510 // fold (A + (0-B)) -> A-B 1511 if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) && 1512 cast<ConstantSDNode>(N1.getOperand(0))->isNullValue()) 1513 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1)); 1514 // fold (A+(B-A)) -> B 1515 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1)) 1516 return N1.getOperand(0); 1517 // fold ((B-A)+A) -> B 1518 if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1)) 1519 return N0.getOperand(0); 1520 // fold (A+(B-(A+C))) to (B-C) 1521 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD && 1522 N0 == N1.getOperand(1).getOperand(0)) 1523 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0), 1524 N1.getOperand(1).getOperand(1)); 1525 // fold (A+(B-(C+A))) to (B-C) 1526 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD && 1527 N0 == N1.getOperand(1).getOperand(1)) 1528 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0), 1529 N1.getOperand(1).getOperand(0)); 1530 // fold (A+((B-A)+or-C)) to (B+or-C) 1531 if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) && 1532 N1.getOperand(0).getOpcode() == ISD::SUB && 1533 N0 == N1.getOperand(0).getOperand(1)) 1534 return DAG.getNode(N1.getOpcode(), SDLoc(N), VT, 1535 N1.getOperand(0).getOperand(0), N1.getOperand(1)); 1536 1537 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant 1538 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) { 1539 SDValue N00 = N0.getOperand(0); 1540 SDValue N01 = N0.getOperand(1); 1541 SDValue N10 = N1.getOperand(0); 1542 SDValue N11 = N1.getOperand(1); 1543 1544 if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10)) 1545 return DAG.getNode(ISD::SUB, SDLoc(N), VT, 1546 DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10), 1547 DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11)); 1548 } 1549 1550 if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0))) 1551 return SDValue(N, 0); 1552 1553 // fold (a+b) -> (a|b) iff a and b share no bits. 1554 if (VT.isInteger() && !VT.isVector()) { 1555 APInt LHSZero, LHSOne; 1556 APInt RHSZero, RHSOne; 1557 DAG.ComputeMaskedBits(N0, LHSZero, LHSOne); 1558 1559 if (LHSZero.getBoolValue()) { 1560 DAG.ComputeMaskedBits(N1, RHSZero, RHSOne); 1561 1562 // If all possibly-set bits on the LHS are clear on the RHS, return an OR. 1563 // If all possibly-set bits on the RHS are clear on the LHS, return an OR. 1564 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){ 1565 if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT)) 1566 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1); 1567 } 1568 } 1569 } 1570 1571 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), ) 1572 if (N0.getOpcode() == ISD::SHL && N0.getNode()->hasOneUse()) { 1573 SDValue Result = combineShlAddConstant(SDLoc(N), N0, N1, DAG); 1574 if (Result.getNode()) return Result; 1575 } 1576 if (N1.getOpcode() == ISD::SHL && N1.getNode()->hasOneUse()) { 1577 SDValue Result = combineShlAddConstant(SDLoc(N), N1, N0, DAG); 1578 if (Result.getNode()) return Result; 1579 } 1580 1581 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n)) 1582 if (N1.getOpcode() == ISD::SHL && 1583 N1.getOperand(0).getOpcode() == ISD::SUB) 1584 if (ConstantSDNode *C = 1585 dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0))) 1586 if (C->getAPIntValue() == 0) 1587 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, 1588 DAG.getNode(ISD::SHL, SDLoc(N), VT, 1589 N1.getOperand(0).getOperand(1), 1590 N1.getOperand(1))); 1591 if (N0.getOpcode() == ISD::SHL && 1592 N0.getOperand(0).getOpcode() == ISD::SUB) 1593 if (ConstantSDNode *C = 1594 dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0))) 1595 if (C->getAPIntValue() == 0) 1596 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, 1597 DAG.getNode(ISD::SHL, SDLoc(N), VT, 1598 N0.getOperand(0).getOperand(1), 1599 N0.getOperand(1))); 1600 1601 if (N1.getOpcode() == ISD::AND) { 1602 SDValue AndOp0 = N1.getOperand(0); 1603 ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1)); 1604 unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0); 1605 unsigned DestBits = VT.getScalarType().getSizeInBits(); 1606 1607 // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x)) 1608 // and similar xforms where the inner op is either ~0 or 0. 1609 if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) { 1610 SDLoc DL(N); 1611 return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0); 1612 } 1613 } 1614 1615 // add (sext i1), X -> sub X, (zext i1) 1616 if (N0.getOpcode() == ISD::SIGN_EXTEND && 1617 N0.getOperand(0).getValueType() == MVT::i1 && 1618 !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) { 1619 SDLoc DL(N); 1620 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)); 1621 return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt); 1622 } 1623 1624 return SDValue(); 1625 } 1626 1627 SDValue DAGCombiner::visitADDC(SDNode *N) { 1628 SDValue N0 = N->getOperand(0); 1629 SDValue N1 = N->getOperand(1); 1630 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 1631 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 1632 EVT VT = N0.getValueType(); 1633 1634 // If the flag result is dead, turn this into an ADD. 1635 if (!N->hasAnyUseOfValue(1)) 1636 return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1), 1637 DAG.getNode(ISD::CARRY_FALSE, 1638 SDLoc(N), MVT::Glue)); 1639 1640 // canonicalize constant to RHS. 1641 if (N0C && !N1C) 1642 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0); 1643 1644 // fold (addc x, 0) -> x + no carry out 1645 if (N1C && N1C->isNullValue()) 1646 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, 1647 SDLoc(N), MVT::Glue)); 1648 1649 // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits. 1650 APInt LHSZero, LHSOne; 1651 APInt RHSZero, RHSOne; 1652 DAG.ComputeMaskedBits(N0, LHSZero, LHSOne); 1653 1654 if (LHSZero.getBoolValue()) { 1655 DAG.ComputeMaskedBits(N1, RHSZero, RHSOne); 1656 1657 // If all possibly-set bits on the LHS are clear on the RHS, return an OR. 1658 // If all possibly-set bits on the RHS are clear on the LHS, return an OR. 1659 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero) 1660 return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1), 1661 DAG.getNode(ISD::CARRY_FALSE, 1662 SDLoc(N), MVT::Glue)); 1663 } 1664 1665 return SDValue(); 1666 } 1667 1668 SDValue DAGCombiner::visitADDE(SDNode *N) { 1669 SDValue N0 = N->getOperand(0); 1670 SDValue N1 = N->getOperand(1); 1671 SDValue CarryIn = N->getOperand(2); 1672 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 1673 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 1674 1675 // canonicalize constant to RHS 1676 if (N0C && !N1C) 1677 return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(), 1678 N1, N0, CarryIn); 1679 1680 // fold (adde x, y, false) -> (addc x, y) 1681 if (CarryIn.getOpcode() == ISD::CARRY_FALSE) 1682 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1); 1683 1684 return SDValue(); 1685 } 1686 1687 // Since it may not be valid to emit a fold to zero for vector initializers 1688 // check if we can before folding. 1689 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT, 1690 SelectionDAG &DAG, 1691 bool LegalOperations, bool LegalTypes) { 1692 if (!VT.isVector()) 1693 return DAG.getConstant(0, VT); 1694 if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT)) 1695 return DAG.getConstant(0, VT); 1696 return SDValue(); 1697 } 1698 1699 SDValue DAGCombiner::visitSUB(SDNode *N) { 1700 SDValue N0 = N->getOperand(0); 1701 SDValue N1 = N->getOperand(1); 1702 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode()); 1703 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode()); 1704 ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr : 1705 dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode()); 1706 EVT VT = N0.getValueType(); 1707 1708 // fold vector ops 1709 if (VT.isVector()) { 1710 SDValue FoldedVOp = SimplifyVBinOp(N); 1711 if (FoldedVOp.getNode()) return FoldedVOp; 1712 1713 // fold (sub x, 0) -> x, vector edition 1714 if (ISD::isBuildVectorAllZeros(N1.getNode())) 1715 return N0; 1716 } 1717 1718 // fold (sub x, x) -> 0 1719 // FIXME: Refactor this and xor and other similar operations together. 1720 if (N0 == N1) 1721 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes); 1722 // fold (sub c1, c2) -> c1-c2 1723 if (N0C && N1C) 1724 return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C); 1725 // fold (sub x, c) -> (add x, -c) 1726 if (N1C) 1727 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, 1728 DAG.getConstant(-N1C->getAPIntValue(), VT)); 1729 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) 1730 if (N0C && N0C->isAllOnesValue()) 1731 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0); 1732 // fold A-(A-B) -> B 1733 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0)) 1734 return N1.getOperand(1); 1735 // fold (A+B)-A -> B 1736 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1) 1737 return N0.getOperand(1); 1738 // fold (A+B)-B -> A 1739 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1) 1740 return N0.getOperand(0); 1741 // fold C2-(A+C1) -> (C2-C1)-A 1742 if (N1.getOpcode() == ISD::ADD && N0C && N1C1) { 1743 SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(), 1744 VT); 1745 return DAG.getNode(ISD::SUB, SDLoc(N), VT, NewC, 1746 N1.getOperand(0)); 1747 } 1748 // fold ((A+(B+or-C))-B) -> A+or-C 1749 if (N0.getOpcode() == ISD::ADD && 1750 (N0.getOperand(1).getOpcode() == ISD::SUB || 1751 N0.getOperand(1).getOpcode() == ISD::ADD) && 1752 N0.getOperand(1).getOperand(0) == N1) 1753 return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT, 1754 N0.getOperand(0), N0.getOperand(1).getOperand(1)); 1755 // fold ((A+(C+B))-B) -> A+C 1756 if (N0.getOpcode() == ISD::ADD && 1757 N0.getOperand(1).getOpcode() == ISD::ADD && 1758 N0.getOperand(1).getOperand(1) == N1) 1759 return DAG.getNode(ISD::ADD, SDLoc(N), VT, 1760 N0.getOperand(0), N0.getOperand(1).getOperand(0)); 1761 // fold ((A-(B-C))-C) -> A-B 1762 if (N0.getOpcode() == ISD::SUB && 1763 N0.getOperand(1).getOpcode() == ISD::SUB && 1764 N0.getOperand(1).getOperand(1) == N1) 1765 return DAG.getNode(ISD::SUB, SDLoc(N), VT, 1766 N0.getOperand(0), N0.getOperand(1).getOperand(0)); 1767 1768 // If either operand of a sub is undef, the result is undef 1769 if (N0.getOpcode() == ISD::UNDEF) 1770 return N0; 1771 if (N1.getOpcode() == ISD::UNDEF) 1772 return N1; 1773 1774 // If the relocation model supports it, consider symbol offsets. 1775 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0)) 1776 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) { 1777 // fold (sub Sym, c) -> Sym-c 1778 if (N1C && GA->getOpcode() == ISD::GlobalAddress) 1779 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT, 1780 GA->getOffset() - 1781 (uint64_t)N1C->getSExtValue()); 1782 // fold (sub Sym+c1, Sym+c2) -> c1-c2 1783 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1)) 1784 if (GA->getGlobal() == GB->getGlobal()) 1785 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(), 1786 VT); 1787 } 1788 1789 return SDValue(); 1790 } 1791 1792 SDValue DAGCombiner::visitSUBC(SDNode *N) { 1793 SDValue N0 = N->getOperand(0); 1794 SDValue N1 = N->getOperand(1); 1795 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 1796 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 1797 EVT VT = N0.getValueType(); 1798 1799 // If the flag result is dead, turn this into an SUB. 1800 if (!N->hasAnyUseOfValue(1)) 1801 return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1), 1802 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N), 1803 MVT::Glue)); 1804 1805 // fold (subc x, x) -> 0 + no borrow 1806 if (N0 == N1) 1807 return CombineTo(N, DAG.getConstant(0, VT), 1808 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N), 1809 MVT::Glue)); 1810 1811 // fold (subc x, 0) -> x + no borrow 1812 if (N1C && N1C->isNullValue()) 1813 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N), 1814 MVT::Glue)); 1815 1816 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow 1817 if (N0C && N0C->isAllOnesValue()) 1818 return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0), 1819 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N), 1820 MVT::Glue)); 1821 1822 return SDValue(); 1823 } 1824 1825 SDValue DAGCombiner::visitSUBE(SDNode *N) { 1826 SDValue N0 = N->getOperand(0); 1827 SDValue N1 = N->getOperand(1); 1828 SDValue CarryIn = N->getOperand(2); 1829 1830 // fold (sube x, y, false) -> (subc x, y) 1831 if (CarryIn.getOpcode() == ISD::CARRY_FALSE) 1832 return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1); 1833 1834 return SDValue(); 1835 } 1836 1837 SDValue DAGCombiner::visitMUL(SDNode *N) { 1838 SDValue N0 = N->getOperand(0); 1839 SDValue N1 = N->getOperand(1); 1840 EVT VT = N0.getValueType(); 1841 1842 // fold (mul x, undef) -> 0 1843 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF) 1844 return DAG.getConstant(0, VT); 1845 1846 bool N0IsConst = false; 1847 bool N1IsConst = false; 1848 APInt ConstValue0, ConstValue1; 1849 // fold vector ops 1850 if (VT.isVector()) { 1851 SDValue FoldedVOp = SimplifyVBinOp(N); 1852 if (FoldedVOp.getNode()) return FoldedVOp; 1853 1854 N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0); 1855 N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1); 1856 } else { 1857 N0IsConst = dyn_cast<ConstantSDNode>(N0) != nullptr; 1858 ConstValue0 = N0IsConst ? (dyn_cast<ConstantSDNode>(N0))->getAPIntValue() 1859 : APInt(); 1860 N1IsConst = dyn_cast<ConstantSDNode>(N1) != nullptr; 1861 ConstValue1 = N1IsConst ? (dyn_cast<ConstantSDNode>(N1))->getAPIntValue() 1862 : APInt(); 1863 } 1864 1865 // fold (mul c1, c2) -> c1*c2 1866 if (N0IsConst && N1IsConst) 1867 return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0.getNode(), N1.getNode()); 1868 1869 // canonicalize constant to RHS 1870 if (N0IsConst && !N1IsConst) 1871 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0); 1872 // fold (mul x, 0) -> 0 1873 if (N1IsConst && ConstValue1 == 0) 1874 return N1; 1875 // We require a splat of the entire scalar bit width for non-contiguous 1876 // bit patterns. 1877 bool IsFullSplat = 1878 ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits(); 1879 // fold (mul x, 1) -> x 1880 if (N1IsConst && ConstValue1 == 1 && IsFullSplat) 1881 return N0; 1882 // fold (mul x, -1) -> 0-x 1883 if (N1IsConst && ConstValue1.isAllOnesValue()) 1884 return DAG.getNode(ISD::SUB, SDLoc(N), VT, 1885 DAG.getConstant(0, VT), N0); 1886 // fold (mul x, (1 << c)) -> x << c 1887 if (N1IsConst && ConstValue1.isPowerOf2() && IsFullSplat) 1888 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, 1889 DAG.getConstant(ConstValue1.logBase2(), 1890 getShiftAmountTy(N0.getValueType()))); 1891 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c 1892 if (N1IsConst && (-ConstValue1).isPowerOf2() && IsFullSplat) { 1893 unsigned Log2Val = (-ConstValue1).logBase2(); 1894 // FIXME: If the input is something that is easily negated (e.g. a 1895 // single-use add), we should put the negate there. 1896 return DAG.getNode(ISD::SUB, SDLoc(N), VT, 1897 DAG.getConstant(0, VT), 1898 DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, 1899 DAG.getConstant(Log2Val, 1900 getShiftAmountTy(N0.getValueType())))); 1901 } 1902 1903 APInt Val; 1904 // (mul (shl X, c1), c2) -> (mul X, c2 << c1) 1905 if (N1IsConst && N0.getOpcode() == ISD::SHL && 1906 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) || 1907 isa<ConstantSDNode>(N0.getOperand(1)))) { 1908 SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT, 1909 N1, N0.getOperand(1)); 1910 AddToWorkList(C3.getNode()); 1911 return DAG.getNode(ISD::MUL, SDLoc(N), VT, 1912 N0.getOperand(0), C3); 1913 } 1914 1915 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one 1916 // use. 1917 { 1918 SDValue Sh(nullptr,0), Y(nullptr,0); 1919 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)). 1920 if (N0.getOpcode() == ISD::SHL && 1921 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) || 1922 isa<ConstantSDNode>(N0.getOperand(1))) && 1923 N0.getNode()->hasOneUse()) { 1924 Sh = N0; Y = N1; 1925 } else if (N1.getOpcode() == ISD::SHL && 1926 isa<ConstantSDNode>(N1.getOperand(1)) && 1927 N1.getNode()->hasOneUse()) { 1928 Sh = N1; Y = N0; 1929 } 1930 1931 if (Sh.getNode()) { 1932 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT, 1933 Sh.getOperand(0), Y); 1934 return DAG.getNode(ISD::SHL, SDLoc(N), VT, 1935 Mul, Sh.getOperand(1)); 1936 } 1937 } 1938 1939 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2) 1940 if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() && 1941 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) || 1942 isa<ConstantSDNode>(N0.getOperand(1)))) 1943 return DAG.getNode(ISD::ADD, SDLoc(N), VT, 1944 DAG.getNode(ISD::MUL, SDLoc(N0), VT, 1945 N0.getOperand(0), N1), 1946 DAG.getNode(ISD::MUL, SDLoc(N1), VT, 1947 N0.getOperand(1), N1)); 1948 1949 // reassociate mul 1950 SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1); 1951 if (RMUL.getNode()) 1952 return RMUL; 1953 1954 return SDValue(); 1955 } 1956 1957 SDValue DAGCombiner::visitSDIV(SDNode *N) { 1958 SDValue N0 = N->getOperand(0); 1959 SDValue N1 = N->getOperand(1); 1960 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode()); 1961 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode()); 1962 EVT VT = N->getValueType(0); 1963 1964 // fold vector ops 1965 if (VT.isVector()) { 1966 SDValue FoldedVOp = SimplifyVBinOp(N); 1967 if (FoldedVOp.getNode()) return FoldedVOp; 1968 } 1969 1970 // fold (sdiv c1, c2) -> c1/c2 1971 if (N0C && N1C && !N1C->isNullValue()) 1972 return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C); 1973 // fold (sdiv X, 1) -> X 1974 if (N1C && N1C->getAPIntValue() == 1LL) 1975 return N0; 1976 // fold (sdiv X, -1) -> 0-X 1977 if (N1C && N1C->isAllOnesValue()) 1978 return DAG.getNode(ISD::SUB, SDLoc(N), VT, 1979 DAG.getConstant(0, VT), N0); 1980 // If we know the sign bits of both operands are zero, strength reduce to a 1981 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2 1982 if (!VT.isVector()) { 1983 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0)) 1984 return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(), 1985 N0, N1); 1986 } 1987 // fold (sdiv X, pow2) -> simple ops after legalize 1988 if (N1C && !N1C->isNullValue() && 1989 (N1C->getAPIntValue().isPowerOf2() || 1990 (-N1C->getAPIntValue()).isPowerOf2())) { 1991 // If dividing by powers of two is cheap, then don't perform the following 1992 // fold. 1993 if (TLI.isPow2DivCheap()) 1994 return SDValue(); 1995 1996 unsigned lg2 = N1C->getAPIntValue().countTrailingZeros(); 1997 1998 // Splat the sign bit into the register 1999 SDValue SGN = DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, 2000 DAG.getConstant(VT.getSizeInBits()-1, 2001 getShiftAmountTy(N0.getValueType()))); 2002 AddToWorkList(SGN.getNode()); 2003 2004 // Add (N0 < 0) ? abs2 - 1 : 0; 2005 SDValue SRL = DAG.getNode(ISD::SRL, SDLoc(N), VT, SGN, 2006 DAG.getConstant(VT.getSizeInBits() - lg2, 2007 getShiftAmountTy(SGN.getValueType()))); 2008 SDValue ADD = DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, SRL); 2009 AddToWorkList(SRL.getNode()); 2010 AddToWorkList(ADD.getNode()); // Divide by pow2 2011 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), VT, ADD, 2012 DAG.getConstant(lg2, getShiftAmountTy(ADD.getValueType()))); 2013 2014 // If we're dividing by a positive value, we're done. Otherwise, we must 2015 // negate the result. 2016 if (N1C->getAPIntValue().isNonNegative()) 2017 return SRA; 2018 2019 AddToWorkList(SRA.getNode()); 2020 return DAG.getNode(ISD::SUB, SDLoc(N), VT, 2021 DAG.getConstant(0, VT), SRA); 2022 } 2023 2024 // if integer divide is expensive and we satisfy the requirements, emit an 2025 // alternate sequence. 2026 if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap()) { 2027 SDValue Op = BuildSDIV(N); 2028 if (Op.getNode()) return Op; 2029 } 2030 2031 // undef / X -> 0 2032 if (N0.getOpcode() == ISD::UNDEF) 2033 return DAG.getConstant(0, VT); 2034 // X / undef -> undef 2035 if (N1.getOpcode() == ISD::UNDEF) 2036 return N1; 2037 2038 return SDValue(); 2039 } 2040 2041 SDValue DAGCombiner::visitUDIV(SDNode *N) { 2042 SDValue N0 = N->getOperand(0); 2043 SDValue N1 = N->getOperand(1); 2044 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode()); 2045 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode()); 2046 EVT VT = N->getValueType(0); 2047 2048 // fold vector ops 2049 if (VT.isVector()) { 2050 SDValue FoldedVOp = SimplifyVBinOp(N); 2051 if (FoldedVOp.getNode()) return FoldedVOp; 2052 } 2053 2054 // fold (udiv c1, c2) -> c1/c2 2055 if (N0C && N1C && !N1C->isNullValue()) 2056 return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C); 2057 // fold (udiv x, (1 << c)) -> x >>u c 2058 if (N1C && N1C->getAPIntValue().isPowerOf2()) 2059 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, 2060 DAG.getConstant(N1C->getAPIntValue().logBase2(), 2061 getShiftAmountTy(N0.getValueType()))); 2062 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2 2063 if (N1.getOpcode() == ISD::SHL) { 2064 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) { 2065 if (SHC->getAPIntValue().isPowerOf2()) { 2066 EVT ADDVT = N1.getOperand(1).getValueType(); 2067 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N), ADDVT, 2068 N1.getOperand(1), 2069 DAG.getConstant(SHC->getAPIntValue() 2070 .logBase2(), 2071 ADDVT)); 2072 AddToWorkList(Add.getNode()); 2073 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, Add); 2074 } 2075 } 2076 } 2077 // fold (udiv x, c) -> alternate 2078 if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap()) { 2079 SDValue Op = BuildUDIV(N); 2080 if (Op.getNode()) return Op; 2081 } 2082 2083 // undef / X -> 0 2084 if (N0.getOpcode() == ISD::UNDEF) 2085 return DAG.getConstant(0, VT); 2086 // X / undef -> undef 2087 if (N1.getOpcode() == ISD::UNDEF) 2088 return N1; 2089 2090 return SDValue(); 2091 } 2092 2093 SDValue DAGCombiner::visitSREM(SDNode *N) { 2094 SDValue N0 = N->getOperand(0); 2095 SDValue N1 = N->getOperand(1); 2096 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 2097 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 2098 EVT VT = N->getValueType(0); 2099 2100 // fold (srem c1, c2) -> c1%c2 2101 if (N0C && N1C && !N1C->isNullValue()) 2102 return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C); 2103 // If we know the sign bits of both operands are zero, strength reduce to a 2104 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15 2105 if (!VT.isVector()) { 2106 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0)) 2107 return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1); 2108 } 2109 2110 // If X/C can be simplified by the division-by-constant logic, lower 2111 // X%C to the equivalent of X-X/C*C. 2112 if (N1C && !N1C->isNullValue()) { 2113 SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1); 2114 AddToWorkList(Div.getNode()); 2115 SDValue OptimizedDiv = combine(Div.getNode()); 2116 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) { 2117 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT, 2118 OptimizedDiv, N1); 2119 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul); 2120 AddToWorkList(Mul.getNode()); 2121 return Sub; 2122 } 2123 } 2124 2125 // undef % X -> 0 2126 if (N0.getOpcode() == ISD::UNDEF) 2127 return DAG.getConstant(0, VT); 2128 // X % undef -> undef 2129 if (N1.getOpcode() == ISD::UNDEF) 2130 return N1; 2131 2132 return SDValue(); 2133 } 2134 2135 SDValue DAGCombiner::visitUREM(SDNode *N) { 2136 SDValue N0 = N->getOperand(0); 2137 SDValue N1 = N->getOperand(1); 2138 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 2139 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 2140 EVT VT = N->getValueType(0); 2141 2142 // fold (urem c1, c2) -> c1%c2 2143 if (N0C && N1C && !N1C->isNullValue()) 2144 return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C); 2145 // fold (urem x, pow2) -> (and x, pow2-1) 2146 if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2()) 2147 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, 2148 DAG.getConstant(N1C->getAPIntValue()-1,VT)); 2149 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1)) 2150 if (N1.getOpcode() == ISD::SHL) { 2151 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) { 2152 if (SHC->getAPIntValue().isPowerOf2()) { 2153 SDValue Add = 2154 DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, 2155 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), 2156 VT)); 2157 AddToWorkList(Add.getNode()); 2158 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, Add); 2159 } 2160 } 2161 } 2162 2163 // If X/C can be simplified by the division-by-constant logic, lower 2164 // X%C to the equivalent of X-X/C*C. 2165 if (N1C && !N1C->isNullValue()) { 2166 SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1); 2167 AddToWorkList(Div.getNode()); 2168 SDValue OptimizedDiv = combine(Div.getNode()); 2169 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) { 2170 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT, 2171 OptimizedDiv, N1); 2172 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul); 2173 AddToWorkList(Mul.getNode()); 2174 return Sub; 2175 } 2176 } 2177 2178 // undef % X -> 0 2179 if (N0.getOpcode() == ISD::UNDEF) 2180 return DAG.getConstant(0, VT); 2181 // X % undef -> undef 2182 if (N1.getOpcode() == ISD::UNDEF) 2183 return N1; 2184 2185 return SDValue(); 2186 } 2187 2188 SDValue DAGCombiner::visitMULHS(SDNode *N) { 2189 SDValue N0 = N->getOperand(0); 2190 SDValue N1 = N->getOperand(1); 2191 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 2192 EVT VT = N->getValueType(0); 2193 SDLoc DL(N); 2194 2195 // fold (mulhs x, 0) -> 0 2196 if (N1C && N1C->isNullValue()) 2197 return N1; 2198 // fold (mulhs x, 1) -> (sra x, size(x)-1) 2199 if (N1C && N1C->getAPIntValue() == 1) 2200 return DAG.getNode(ISD::SRA, SDLoc(N), N0.getValueType(), N0, 2201 DAG.getConstant(N0.getValueType().getSizeInBits() - 1, 2202 getShiftAmountTy(N0.getValueType()))); 2203 // fold (mulhs x, undef) -> 0 2204 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF) 2205 return DAG.getConstant(0, VT); 2206 2207 // If the type twice as wide is legal, transform the mulhs to a wider multiply 2208 // plus a shift. 2209 if (VT.isSimple() && !VT.isVector()) { 2210 MVT Simple = VT.getSimpleVT(); 2211 unsigned SimpleSize = Simple.getSizeInBits(); 2212 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 2213 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 2214 N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0); 2215 N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1); 2216 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1); 2217 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1, 2218 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType()))); 2219 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1); 2220 } 2221 } 2222 2223 return SDValue(); 2224 } 2225 2226 SDValue DAGCombiner::visitMULHU(SDNode *N) { 2227 SDValue N0 = N->getOperand(0); 2228 SDValue N1 = N->getOperand(1); 2229 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 2230 EVT VT = N->getValueType(0); 2231 SDLoc DL(N); 2232 2233 // fold (mulhu x, 0) -> 0 2234 if (N1C && N1C->isNullValue()) 2235 return N1; 2236 // fold (mulhu x, 1) -> 0 2237 if (N1C && N1C->getAPIntValue() == 1) 2238 return DAG.getConstant(0, N0.getValueType()); 2239 // fold (mulhu x, undef) -> 0 2240 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF) 2241 return DAG.getConstant(0, VT); 2242 2243 // If the type twice as wide is legal, transform the mulhu to a wider multiply 2244 // plus a shift. 2245 if (VT.isSimple() && !VT.isVector()) { 2246 MVT Simple = VT.getSimpleVT(); 2247 unsigned SimpleSize = Simple.getSizeInBits(); 2248 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 2249 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 2250 N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0); 2251 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1); 2252 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1); 2253 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1, 2254 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType()))); 2255 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1); 2256 } 2257 } 2258 2259 return SDValue(); 2260 } 2261 2262 /// SimplifyNodeWithTwoResults - Perform optimizations common to nodes that 2263 /// compute two values. LoOp and HiOp give the opcodes for the two computations 2264 /// that are being performed. Return true if a simplification was made. 2265 /// 2266 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp, 2267 unsigned HiOp) { 2268 // If the high half is not needed, just compute the low half. 2269 bool HiExists = N->hasAnyUseOfValue(1); 2270 if (!HiExists && 2271 (!LegalOperations || 2272 TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) { 2273 SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), 2274 N->op_begin(), N->getNumOperands()); 2275 return CombineTo(N, Res, Res); 2276 } 2277 2278 // If the low half is not needed, just compute the high half. 2279 bool LoExists = N->hasAnyUseOfValue(0); 2280 if (!LoExists && 2281 (!LegalOperations || 2282 TLI.isOperationLegal(HiOp, N->getValueType(1)))) { 2283 SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), 2284 N->op_begin(), N->getNumOperands()); 2285 return CombineTo(N, Res, Res); 2286 } 2287 2288 // If both halves are used, return as it is. 2289 if (LoExists && HiExists) 2290 return SDValue(); 2291 2292 // If the two computed results can be simplified separately, separate them. 2293 if (LoExists) { 2294 SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), 2295 N->op_begin(), N->getNumOperands()); 2296 AddToWorkList(Lo.getNode()); 2297 SDValue LoOpt = combine(Lo.getNode()); 2298 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() && 2299 (!LegalOperations || 2300 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType()))) 2301 return CombineTo(N, LoOpt, LoOpt); 2302 } 2303 2304 if (HiExists) { 2305 SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), 2306 N->op_begin(), N->getNumOperands()); 2307 AddToWorkList(Hi.getNode()); 2308 SDValue HiOpt = combine(Hi.getNode()); 2309 if (HiOpt.getNode() && HiOpt != Hi && 2310 (!LegalOperations || 2311 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType()))) 2312 return CombineTo(N, HiOpt, HiOpt); 2313 } 2314 2315 return SDValue(); 2316 } 2317 2318 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) { 2319 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS); 2320 if (Res.getNode()) return Res; 2321 2322 EVT VT = N->getValueType(0); 2323 SDLoc DL(N); 2324 2325 // If the type twice as wide is legal, transform the mulhu to a wider multiply 2326 // plus a shift. 2327 if (VT.isSimple() && !VT.isVector()) { 2328 MVT Simple = VT.getSimpleVT(); 2329 unsigned SimpleSize = Simple.getSizeInBits(); 2330 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 2331 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 2332 SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0)); 2333 SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1)); 2334 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi); 2335 // Compute the high part as N1. 2336 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo, 2337 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType()))); 2338 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi); 2339 // Compute the low part as N0. 2340 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo); 2341 return CombineTo(N, Lo, Hi); 2342 } 2343 } 2344 2345 return SDValue(); 2346 } 2347 2348 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) { 2349 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU); 2350 if (Res.getNode()) return Res; 2351 2352 EVT VT = N->getValueType(0); 2353 SDLoc DL(N); 2354 2355 // If the type twice as wide is legal, transform the mulhu to a wider multiply 2356 // plus a shift. 2357 if (VT.isSimple() && !VT.isVector()) { 2358 MVT Simple = VT.getSimpleVT(); 2359 unsigned SimpleSize = Simple.getSizeInBits(); 2360 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 2361 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 2362 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0)); 2363 SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1)); 2364 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi); 2365 // Compute the high part as N1. 2366 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo, 2367 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType()))); 2368 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi); 2369 // Compute the low part as N0. 2370 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo); 2371 return CombineTo(N, Lo, Hi); 2372 } 2373 } 2374 2375 return SDValue(); 2376 } 2377 2378 SDValue DAGCombiner::visitSMULO(SDNode *N) { 2379 // (smulo x, 2) -> (saddo x, x) 2380 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1))) 2381 if (C2->getAPIntValue() == 2) 2382 return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(), 2383 N->getOperand(0), N->getOperand(0)); 2384 2385 return SDValue(); 2386 } 2387 2388 SDValue DAGCombiner::visitUMULO(SDNode *N) { 2389 // (umulo x, 2) -> (uaddo x, x) 2390 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1))) 2391 if (C2->getAPIntValue() == 2) 2392 return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(), 2393 N->getOperand(0), N->getOperand(0)); 2394 2395 return SDValue(); 2396 } 2397 2398 SDValue DAGCombiner::visitSDIVREM(SDNode *N) { 2399 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM); 2400 if (Res.getNode()) return Res; 2401 2402 return SDValue(); 2403 } 2404 2405 SDValue DAGCombiner::visitUDIVREM(SDNode *N) { 2406 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM); 2407 if (Res.getNode()) return Res; 2408 2409 return SDValue(); 2410 } 2411 2412 /// SimplifyBinOpWithSameOpcodeHands - If this is a binary operator with 2413 /// two operands of the same opcode, try to simplify it. 2414 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) { 2415 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1); 2416 EVT VT = N0.getValueType(); 2417 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!"); 2418 2419 // Bail early if none of these transforms apply. 2420 if (N0.getNode()->getNumOperands() == 0) return SDValue(); 2421 2422 // For each of OP in AND/OR/XOR: 2423 // fold (OP (zext x), (zext y)) -> (zext (OP x, y)) 2424 // fold (OP (sext x), (sext y)) -> (sext (OP x, y)) 2425 // fold (OP (aext x), (aext y)) -> (aext (OP x, y)) 2426 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free) 2427 // 2428 // do not sink logical op inside of a vector extend, since it may combine 2429 // into a vsetcc. 2430 EVT Op0VT = N0.getOperand(0).getValueType(); 2431 if ((N0.getOpcode() == ISD::ZERO_EXTEND || 2432 N0.getOpcode() == ISD::SIGN_EXTEND || 2433 // Avoid infinite looping with PromoteIntBinOp. 2434 (N0.getOpcode() == ISD::ANY_EXTEND && 2435 (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) || 2436 (N0.getOpcode() == ISD::TRUNCATE && 2437 (!TLI.isZExtFree(VT, Op0VT) || 2438 !TLI.isTruncateFree(Op0VT, VT)) && 2439 TLI.isTypeLegal(Op0VT))) && 2440 !VT.isVector() && 2441 Op0VT == N1.getOperand(0).getValueType() && 2442 (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) { 2443 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0), 2444 N0.getOperand(0).getValueType(), 2445 N0.getOperand(0), N1.getOperand(0)); 2446 AddToWorkList(ORNode.getNode()); 2447 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode); 2448 } 2449 2450 // For each of OP in SHL/SRL/SRA/AND... 2451 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z) 2452 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z) 2453 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z) 2454 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL || 2455 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) && 2456 N0.getOperand(1) == N1.getOperand(1)) { 2457 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0), 2458 N0.getOperand(0).getValueType(), 2459 N0.getOperand(0), N1.getOperand(0)); 2460 AddToWorkList(ORNode.getNode()); 2461 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, 2462 ORNode, N0.getOperand(1)); 2463 } 2464 2465 // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B)) 2466 // Only perform this optimization after type legalization and before 2467 // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by 2468 // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and 2469 // we don't want to undo this promotion. 2470 // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper 2471 // on scalars. 2472 if ((N0.getOpcode() == ISD::BITCAST || 2473 N0.getOpcode() == ISD::SCALAR_TO_VECTOR) && 2474 Level == AfterLegalizeTypes) { 2475 SDValue In0 = N0.getOperand(0); 2476 SDValue In1 = N1.getOperand(0); 2477 EVT In0Ty = In0.getValueType(); 2478 EVT In1Ty = In1.getValueType(); 2479 SDLoc DL(N); 2480 // If both incoming values are integers, and the original types are the 2481 // same. 2482 if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) { 2483 SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1); 2484 SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op); 2485 AddToWorkList(Op.getNode()); 2486 return BC; 2487 } 2488 } 2489 2490 // Xor/and/or are indifferent to the swizzle operation (shuffle of one value). 2491 // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B)) 2492 // If both shuffles use the same mask, and both shuffle within a single 2493 // vector, then it is worthwhile to move the swizzle after the operation. 2494 // The type-legalizer generates this pattern when loading illegal 2495 // vector types from memory. In many cases this allows additional shuffle 2496 // optimizations. 2497 // There are other cases where moving the shuffle after the xor/and/or 2498 // is profitable even if shuffles don't perform a swizzle. 2499 // If both shuffles use the same mask, and both shuffles have the same first 2500 // or second operand, then it might still be profitable to move the shuffle 2501 // after the xor/and/or operation. 2502 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) { 2503 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0); 2504 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1); 2505 2506 assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() && 2507 "Inputs to shuffles are not the same type"); 2508 2509 // Check that both shuffles use the same mask. The masks are known to be of 2510 // the same length because the result vector type is the same. 2511 // Check also that shuffles have only one use to avoid introducing extra 2512 // instructions. 2513 if (SVN0->hasOneUse() && SVN1->hasOneUse() && 2514 SVN0->getMask().equals(SVN1->getMask())) { 2515 SDValue ShOp = N0->getOperand(1); 2516 2517 // Don't try to fold this node if it requires introducing a 2518 // build vector of all zeros that might be illegal at this stage. 2519 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) { 2520 if (!LegalTypes) 2521 ShOp = DAG.getConstant(0, VT); 2522 else 2523 ShOp = SDValue(); 2524 } 2525 2526 // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C) 2527 // (OR (shuf (A, C), shuf (B, C)) -> shuf (OR (A, B), C) 2528 // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0) 2529 if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) { 2530 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT, 2531 N0->getOperand(0), N1->getOperand(0)); 2532 AddToWorkList(NewNode.getNode()); 2533 return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp, 2534 &SVN0->getMask()[0]); 2535 } 2536 2537 // Don't try to fold this node if it requires introducing a 2538 // build vector of all zeros that might be illegal at this stage. 2539 ShOp = N0->getOperand(0); 2540 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) { 2541 if (!LegalTypes) 2542 ShOp = DAG.getConstant(0, VT); 2543 else 2544 ShOp = SDValue(); 2545 } 2546 2547 // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B)) 2548 // (OR (shuf (C, A), shuf (C, B)) -> shuf (C, OR (A, B)) 2549 // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B)) 2550 if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) { 2551 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT, 2552 N0->getOperand(1), N1->getOperand(1)); 2553 AddToWorkList(NewNode.getNode()); 2554 return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode, 2555 &SVN0->getMask()[0]); 2556 } 2557 } 2558 } 2559 2560 return SDValue(); 2561 } 2562 2563 SDValue DAGCombiner::visitAND(SDNode *N) { 2564 SDValue N0 = N->getOperand(0); 2565 SDValue N1 = N->getOperand(1); 2566 SDValue LL, LR, RL, RR, CC0, CC1; 2567 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 2568 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 2569 EVT VT = N1.getValueType(); 2570 unsigned BitWidth = VT.getScalarType().getSizeInBits(); 2571 2572 // fold vector ops 2573 if (VT.isVector()) { 2574 SDValue FoldedVOp = SimplifyVBinOp(N); 2575 if (FoldedVOp.getNode()) return FoldedVOp; 2576 2577 // fold (and x, 0) -> 0, vector edition 2578 if (ISD::isBuildVectorAllZeros(N0.getNode())) 2579 return N0; 2580 if (ISD::isBuildVectorAllZeros(N1.getNode())) 2581 return N1; 2582 2583 // fold (and x, -1) -> x, vector edition 2584 if (ISD::isBuildVectorAllOnes(N0.getNode())) 2585 return N1; 2586 if (ISD::isBuildVectorAllOnes(N1.getNode())) 2587 return N0; 2588 } 2589 2590 // fold (and x, undef) -> 0 2591 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF) 2592 return DAG.getConstant(0, VT); 2593 // fold (and c1, c2) -> c1&c2 2594 if (N0C && N1C) 2595 return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C); 2596 // canonicalize constant to RHS 2597 if (N0C && !N1C) 2598 return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0); 2599 // fold (and x, -1) -> x 2600 if (N1C && N1C->isAllOnesValue()) 2601 return N0; 2602 // if (and x, c) is known to be zero, return 0 2603 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0), 2604 APInt::getAllOnesValue(BitWidth))) 2605 return DAG.getConstant(0, VT); 2606 // reassociate and 2607 SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1); 2608 if (RAND.getNode()) 2609 return RAND; 2610 // fold (and (or x, C), D) -> D if (C & D) == D 2611 if (N1C && N0.getOpcode() == ISD::OR) 2612 if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) 2613 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue()) 2614 return N1; 2615 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits. 2616 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) { 2617 SDValue N0Op0 = N0.getOperand(0); 2618 APInt Mask = ~N1C->getAPIntValue(); 2619 Mask = Mask.trunc(N0Op0.getValueSizeInBits()); 2620 if (DAG.MaskedValueIsZero(N0Op0, Mask)) { 2621 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), 2622 N0.getValueType(), N0Op0); 2623 2624 // Replace uses of the AND with uses of the Zero extend node. 2625 CombineTo(N, Zext); 2626 2627 // We actually want to replace all uses of the any_extend with the 2628 // zero_extend, to avoid duplicating things. This will later cause this 2629 // AND to be folded. 2630 CombineTo(N0.getNode(), Zext); 2631 return SDValue(N, 0); // Return N so it doesn't get rechecked! 2632 } 2633 } 2634 // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) -> 2635 // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must 2636 // already be zero by virtue of the width of the base type of the load. 2637 // 2638 // the 'X' node here can either be nothing or an extract_vector_elt to catch 2639 // more cases. 2640 if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT && 2641 N0.getOperand(0).getOpcode() == ISD::LOAD) || 2642 N0.getOpcode() == ISD::LOAD) { 2643 LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ? 2644 N0 : N0.getOperand(0) ); 2645 2646 // Get the constant (if applicable) the zero'th operand is being ANDed with. 2647 // This can be a pure constant or a vector splat, in which case we treat the 2648 // vector as a scalar and use the splat value. 2649 APInt Constant = APInt::getNullValue(1); 2650 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) { 2651 Constant = C->getAPIntValue(); 2652 } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) { 2653 APInt SplatValue, SplatUndef; 2654 unsigned SplatBitSize; 2655 bool HasAnyUndefs; 2656 bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef, 2657 SplatBitSize, HasAnyUndefs); 2658 if (IsSplat) { 2659 // Undef bits can contribute to a possible optimisation if set, so 2660 // set them. 2661 SplatValue |= SplatUndef; 2662 2663 // The splat value may be something like "0x00FFFFFF", which means 0 for 2664 // the first vector value and FF for the rest, repeating. We need a mask 2665 // that will apply equally to all members of the vector, so AND all the 2666 // lanes of the constant together. 2667 EVT VT = Vector->getValueType(0); 2668 unsigned BitWidth = VT.getVectorElementType().getSizeInBits(); 2669 2670 // If the splat value has been compressed to a bitlength lower 2671 // than the size of the vector lane, we need to re-expand it to 2672 // the lane size. 2673 if (BitWidth > SplatBitSize) 2674 for (SplatValue = SplatValue.zextOrTrunc(BitWidth); 2675 SplatBitSize < BitWidth; 2676 SplatBitSize = SplatBitSize * 2) 2677 SplatValue |= SplatValue.shl(SplatBitSize); 2678 2679 Constant = APInt::getAllOnesValue(BitWidth); 2680 for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i) 2681 Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth); 2682 } 2683 } 2684 2685 // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is 2686 // actually legal and isn't going to get expanded, else this is a false 2687 // optimisation. 2688 bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD, 2689 Load->getMemoryVT()); 2690 2691 // Resize the constant to the same size as the original memory access before 2692 // extension. If it is still the AllOnesValue then this AND is completely 2693 // unneeded. 2694 Constant = 2695 Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits()); 2696 2697 bool B; 2698 switch (Load->getExtensionType()) { 2699 default: B = false; break; 2700 case ISD::EXTLOAD: B = CanZextLoadProfitably; break; 2701 case ISD::ZEXTLOAD: 2702 case ISD::NON_EXTLOAD: B = true; break; 2703 } 2704 2705 if (B && Constant.isAllOnesValue()) { 2706 // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to 2707 // preserve semantics once we get rid of the AND. 2708 SDValue NewLoad(Load, 0); 2709 if (Load->getExtensionType() == ISD::EXTLOAD) { 2710 NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD, 2711 Load->getValueType(0), SDLoc(Load), 2712 Load->getChain(), Load->getBasePtr(), 2713 Load->getOffset(), Load->getMemoryVT(), 2714 Load->getMemOperand()); 2715 // Replace uses of the EXTLOAD with the new ZEXTLOAD. 2716 if (Load->getNumValues() == 3) { 2717 // PRE/POST_INC loads have 3 values. 2718 SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1), 2719 NewLoad.getValue(2) }; 2720 CombineTo(Load, To, 3, true); 2721 } else { 2722 CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1)); 2723 } 2724 } 2725 2726 // Fold the AND away, taking care not to fold to the old load node if we 2727 // replaced it. 2728 CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0); 2729 2730 return SDValue(N, 0); // Return N so it doesn't get rechecked! 2731 } 2732 } 2733 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y)) 2734 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){ 2735 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get(); 2736 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get(); 2737 2738 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 && 2739 LL.getValueType().isInteger()) { 2740 // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0) 2741 if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) { 2742 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0), 2743 LR.getValueType(), LL, RL); 2744 AddToWorkList(ORNode.getNode()); 2745 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1); 2746 } 2747 // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1) 2748 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) { 2749 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0), 2750 LR.getValueType(), LL, RL); 2751 AddToWorkList(ANDNode.getNode()); 2752 return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1); 2753 } 2754 // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1) 2755 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) { 2756 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0), 2757 LR.getValueType(), LL, RL); 2758 AddToWorkList(ORNode.getNode()); 2759 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1); 2760 } 2761 } 2762 // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2) 2763 if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) && 2764 Op0 == Op1 && LL.getValueType().isInteger() && 2765 Op0 == ISD::SETNE && ((cast<ConstantSDNode>(LR)->isNullValue() && 2766 cast<ConstantSDNode>(RR)->isAllOnesValue()) || 2767 (cast<ConstantSDNode>(LR)->isAllOnesValue() && 2768 cast<ConstantSDNode>(RR)->isNullValue()))) { 2769 SDValue ADDNode = DAG.getNode(ISD::ADD, SDLoc(N0), LL.getValueType(), 2770 LL, DAG.getConstant(1, LL.getValueType())); 2771 AddToWorkList(ADDNode.getNode()); 2772 return DAG.getSetCC(SDLoc(N), VT, ADDNode, 2773 DAG.getConstant(2, LL.getValueType()), ISD::SETUGE); 2774 } 2775 // canonicalize equivalent to ll == rl 2776 if (LL == RR && LR == RL) { 2777 Op1 = ISD::getSetCCSwappedOperands(Op1); 2778 std::swap(RL, RR); 2779 } 2780 if (LL == RL && LR == RR) { 2781 bool isInteger = LL.getValueType().isInteger(); 2782 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger); 2783 if (Result != ISD::SETCC_INVALID && 2784 (!LegalOperations || 2785 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) && 2786 TLI.isOperationLegal(ISD::SETCC, 2787 getSetCCResultType(N0.getSimpleValueType()))))) 2788 return DAG.getSetCC(SDLoc(N), N0.getValueType(), 2789 LL, LR, Result); 2790 } 2791 } 2792 2793 // Simplify: (and (op x...), (op y...)) -> (op (and x, y)) 2794 if (N0.getOpcode() == N1.getOpcode()) { 2795 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N); 2796 if (Tmp.getNode()) return Tmp; 2797 } 2798 2799 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1) 2800 // fold (and (sra)) -> (and (srl)) when possible. 2801 if (!VT.isVector() && 2802 SimplifyDemandedBits(SDValue(N, 0))) 2803 return SDValue(N, 0); 2804 2805 // fold (zext_inreg (extload x)) -> (zextload x) 2806 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) { 2807 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 2808 EVT MemVT = LN0->getMemoryVT(); 2809 // If we zero all the possible extended bits, then we can turn this into 2810 // a zextload if we are running before legalize or the operation is legal. 2811 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits(); 2812 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth, 2813 BitWidth - MemVT.getScalarType().getSizeInBits())) && 2814 ((!LegalOperations && !LN0->isVolatile()) || 2815 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) { 2816 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT, 2817 LN0->getChain(), LN0->getBasePtr(), 2818 MemVT, LN0->getMemOperand()); 2819 AddToWorkList(N); 2820 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 2821 return SDValue(N, 0); // Return N so it doesn't get rechecked! 2822 } 2823 } 2824 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use 2825 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 2826 N0.hasOneUse()) { 2827 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 2828 EVT MemVT = LN0->getMemoryVT(); 2829 // If we zero all the possible extended bits, then we can turn this into 2830 // a zextload if we are running before legalize or the operation is legal. 2831 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits(); 2832 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth, 2833 BitWidth - MemVT.getScalarType().getSizeInBits())) && 2834 ((!LegalOperations && !LN0->isVolatile()) || 2835 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) { 2836 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT, 2837 LN0->getChain(), LN0->getBasePtr(), 2838 MemVT, LN0->getMemOperand()); 2839 AddToWorkList(N); 2840 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 2841 return SDValue(N, 0); // Return N so it doesn't get rechecked! 2842 } 2843 } 2844 2845 // fold (and (load x), 255) -> (zextload x, i8) 2846 // fold (and (extload x, i16), 255) -> (zextload x, i8) 2847 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8) 2848 if (N1C && (N0.getOpcode() == ISD::LOAD || 2849 (N0.getOpcode() == ISD::ANY_EXTEND && 2850 N0.getOperand(0).getOpcode() == ISD::LOAD))) { 2851 bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND; 2852 LoadSDNode *LN0 = HasAnyExt 2853 ? cast<LoadSDNode>(N0.getOperand(0)) 2854 : cast<LoadSDNode>(N0); 2855 if (LN0->getExtensionType() != ISD::SEXTLOAD && 2856 LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) { 2857 uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits(); 2858 if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){ 2859 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits); 2860 EVT LoadedVT = LN0->getMemoryVT(); 2861 2862 if (ExtVT == LoadedVT && 2863 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) { 2864 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT; 2865 2866 SDValue NewLoad = 2867 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy, 2868 LN0->getChain(), LN0->getBasePtr(), ExtVT, 2869 LN0->getMemOperand()); 2870 AddToWorkList(N); 2871 CombineTo(LN0, NewLoad, NewLoad.getValue(1)); 2872 return SDValue(N, 0); // Return N so it doesn't get rechecked! 2873 } 2874 2875 // Do not change the width of a volatile load. 2876 // Do not generate loads of non-round integer types since these can 2877 // be expensive (and would be wrong if the type is not byte sized). 2878 if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() && 2879 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) { 2880 EVT PtrType = LN0->getOperand(1).getValueType(); 2881 2882 unsigned Alignment = LN0->getAlignment(); 2883 SDValue NewPtr = LN0->getBasePtr(); 2884 2885 // For big endian targets, we need to add an offset to the pointer 2886 // to load the correct bytes. For little endian systems, we merely 2887 // need to read fewer bytes from the same pointer. 2888 if (TLI.isBigEndian()) { 2889 unsigned LVTStoreBytes = LoadedVT.getStoreSize(); 2890 unsigned EVTStoreBytes = ExtVT.getStoreSize(); 2891 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes; 2892 NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0), PtrType, 2893 NewPtr, DAG.getConstant(PtrOff, PtrType)); 2894 Alignment = MinAlign(Alignment, PtrOff); 2895 } 2896 2897 AddToWorkList(NewPtr.getNode()); 2898 2899 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT; 2900 SDValue Load = 2901 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy, 2902 LN0->getChain(), NewPtr, 2903 LN0->getPointerInfo(), 2904 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(), 2905 Alignment, LN0->getTBAAInfo()); 2906 AddToWorkList(N); 2907 CombineTo(LN0, Load, Load.getValue(1)); 2908 return SDValue(N, 0); // Return N so it doesn't get rechecked! 2909 } 2910 } 2911 } 2912 } 2913 2914 if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL && 2915 VT.getSizeInBits() <= 64) { 2916 if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 2917 APInt ADDC = ADDI->getAPIntValue(); 2918 if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) { 2919 // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal 2920 // immediate for an add, but it is legal if its top c2 bits are set, 2921 // transform the ADD so the immediate doesn't need to be materialized 2922 // in a register. 2923 if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) { 2924 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(), 2925 SRLI->getZExtValue()); 2926 if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) { 2927 ADDC |= Mask; 2928 if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) { 2929 SDValue NewAdd = 2930 DAG.getNode(ISD::ADD, SDLoc(N0), VT, 2931 N0.getOperand(0), DAG.getConstant(ADDC, VT)); 2932 CombineTo(N0.getNode(), NewAdd); 2933 return SDValue(N, 0); // Return N so it doesn't get rechecked! 2934 } 2935 } 2936 } 2937 } 2938 } 2939 } 2940 2941 // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const) 2942 if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) { 2943 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0), 2944 N0.getOperand(1), false); 2945 if (BSwap.getNode()) 2946 return BSwap; 2947 } 2948 2949 return SDValue(); 2950 } 2951 2952 /// MatchBSwapHWord - Match (a >> 8) | (a << 8) as (bswap a) >> 16 2953 /// 2954 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1, 2955 bool DemandHighBits) { 2956 if (!LegalOperations) 2957 return SDValue(); 2958 2959 EVT VT = N->getValueType(0); 2960 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16) 2961 return SDValue(); 2962 if (!TLI.isOperationLegal(ISD::BSWAP, VT)) 2963 return SDValue(); 2964 2965 // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00) 2966 bool LookPassAnd0 = false; 2967 bool LookPassAnd1 = false; 2968 if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL) 2969 std::swap(N0, N1); 2970 if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL) 2971 std::swap(N0, N1); 2972 if (N0.getOpcode() == ISD::AND) { 2973 if (!N0.getNode()->hasOneUse()) 2974 return SDValue(); 2975 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 2976 if (!N01C || N01C->getZExtValue() != 0xFF00) 2977 return SDValue(); 2978 N0 = N0.getOperand(0); 2979 LookPassAnd0 = true; 2980 } 2981 2982 if (N1.getOpcode() == ISD::AND) { 2983 if (!N1.getNode()->hasOneUse()) 2984 return SDValue(); 2985 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 2986 if (!N11C || N11C->getZExtValue() != 0xFF) 2987 return SDValue(); 2988 N1 = N1.getOperand(0); 2989 LookPassAnd1 = true; 2990 } 2991 2992 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL) 2993 std::swap(N0, N1); 2994 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL) 2995 return SDValue(); 2996 if (!N0.getNode()->hasOneUse() || 2997 !N1.getNode()->hasOneUse()) 2998 return SDValue(); 2999 3000 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 3001 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 3002 if (!N01C || !N11C) 3003 return SDValue(); 3004 if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8) 3005 return SDValue(); 3006 3007 // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8) 3008 SDValue N00 = N0->getOperand(0); 3009 if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) { 3010 if (!N00.getNode()->hasOneUse()) 3011 return SDValue(); 3012 ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1)); 3013 if (!N001C || N001C->getZExtValue() != 0xFF) 3014 return SDValue(); 3015 N00 = N00.getOperand(0); 3016 LookPassAnd0 = true; 3017 } 3018 3019 SDValue N10 = N1->getOperand(0); 3020 if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) { 3021 if (!N10.getNode()->hasOneUse()) 3022 return SDValue(); 3023 ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1)); 3024 if (!N101C || N101C->getZExtValue() != 0xFF00) 3025 return SDValue(); 3026 N10 = N10.getOperand(0); 3027 LookPassAnd1 = true; 3028 } 3029 3030 if (N00 != N10) 3031 return SDValue(); 3032 3033 // Make sure everything beyond the low halfword gets set to zero since the SRL 3034 // 16 will clear the top bits. 3035 unsigned OpSizeInBits = VT.getSizeInBits(); 3036 if (DemandHighBits && OpSizeInBits > 16) { 3037 // If the left-shift isn't masked out then the only way this is a bswap is 3038 // if all bits beyond the low 8 are 0. In that case the entire pattern 3039 // reduces to a left shift anyway: leave it for other parts of the combiner. 3040 if (!LookPassAnd0) 3041 return SDValue(); 3042 3043 // However, if the right shift isn't masked out then it might be because 3044 // it's not needed. See if we can spot that too. 3045 if (!LookPassAnd1 && 3046 !DAG.MaskedValueIsZero( 3047 N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16))) 3048 return SDValue(); 3049 } 3050 3051 SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00); 3052 if (OpSizeInBits > 16) 3053 Res = DAG.getNode(ISD::SRL, SDLoc(N), VT, Res, 3054 DAG.getConstant(OpSizeInBits-16, getShiftAmountTy(VT))); 3055 return Res; 3056 } 3057 3058 /// isBSwapHWordElement - Return true if the specified node is an element 3059 /// that makes up a 32-bit packed halfword byteswap. i.e. 3060 /// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8) 3061 static bool isBSwapHWordElement(SDValue N, SmallVectorImpl<SDNode *> &Parts) { 3062 if (!N.getNode()->hasOneUse()) 3063 return false; 3064 3065 unsigned Opc = N.getOpcode(); 3066 if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL) 3067 return false; 3068 3069 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1)); 3070 if (!N1C) 3071 return false; 3072 3073 unsigned Num; 3074 switch (N1C->getZExtValue()) { 3075 default: 3076 return false; 3077 case 0xFF: Num = 0; break; 3078 case 0xFF00: Num = 1; break; 3079 case 0xFF0000: Num = 2; break; 3080 case 0xFF000000: Num = 3; break; 3081 } 3082 3083 // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00). 3084 SDValue N0 = N.getOperand(0); 3085 if (Opc == ISD::AND) { 3086 if (Num == 0 || Num == 2) { 3087 // (x >> 8) & 0xff 3088 // (x >> 8) & 0xff0000 3089 if (N0.getOpcode() != ISD::SRL) 3090 return false; 3091 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 3092 if (!C || C->getZExtValue() != 8) 3093 return false; 3094 } else { 3095 // (x << 8) & 0xff00 3096 // (x << 8) & 0xff000000 3097 if (N0.getOpcode() != ISD::SHL) 3098 return false; 3099 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 3100 if (!C || C->getZExtValue() != 8) 3101 return false; 3102 } 3103 } else if (Opc == ISD::SHL) { 3104 // (x & 0xff) << 8 3105 // (x & 0xff0000) << 8 3106 if (Num != 0 && Num != 2) 3107 return false; 3108 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1)); 3109 if (!C || C->getZExtValue() != 8) 3110 return false; 3111 } else { // Opc == ISD::SRL 3112 // (x & 0xff00) >> 8 3113 // (x & 0xff000000) >> 8 3114 if (Num != 1 && Num != 3) 3115 return false; 3116 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1)); 3117 if (!C || C->getZExtValue() != 8) 3118 return false; 3119 } 3120 3121 if (Parts[Num]) 3122 return false; 3123 3124 Parts[Num] = N0.getOperand(0).getNode(); 3125 return true; 3126 } 3127 3128 /// MatchBSwapHWord - Match a 32-bit packed halfword bswap. That is 3129 /// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8) 3130 /// => (rotl (bswap x), 16) 3131 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) { 3132 if (!LegalOperations) 3133 return SDValue(); 3134 3135 EVT VT = N->getValueType(0); 3136 if (VT != MVT::i32) 3137 return SDValue(); 3138 if (!TLI.isOperationLegal(ISD::BSWAP, VT)) 3139 return SDValue(); 3140 3141 SmallVector<SDNode*,4> Parts(4, (SDNode*)nullptr); 3142 // Look for either 3143 // (or (or (and), (and)), (or (and), (and))) 3144 // (or (or (or (and), (and)), (and)), (and)) 3145 if (N0.getOpcode() != ISD::OR) 3146 return SDValue(); 3147 SDValue N00 = N0.getOperand(0); 3148 SDValue N01 = N0.getOperand(1); 3149 3150 if (N1.getOpcode() == ISD::OR && 3151 N00.getNumOperands() == 2 && N01.getNumOperands() == 2) { 3152 // (or (or (and), (and)), (or (and), (and))) 3153 SDValue N000 = N00.getOperand(0); 3154 if (!isBSwapHWordElement(N000, Parts)) 3155 return SDValue(); 3156 3157 SDValue N001 = N00.getOperand(1); 3158 if (!isBSwapHWordElement(N001, Parts)) 3159 return SDValue(); 3160 SDValue N010 = N01.getOperand(0); 3161 if (!isBSwapHWordElement(N010, Parts)) 3162 return SDValue(); 3163 SDValue N011 = N01.getOperand(1); 3164 if (!isBSwapHWordElement(N011, Parts)) 3165 return SDValue(); 3166 } else { 3167 // (or (or (or (and), (and)), (and)), (and)) 3168 if (!isBSwapHWordElement(N1, Parts)) 3169 return SDValue(); 3170 if (!isBSwapHWordElement(N01, Parts)) 3171 return SDValue(); 3172 if (N00.getOpcode() != ISD::OR) 3173 return SDValue(); 3174 SDValue N000 = N00.getOperand(0); 3175 if (!isBSwapHWordElement(N000, Parts)) 3176 return SDValue(); 3177 SDValue N001 = N00.getOperand(1); 3178 if (!isBSwapHWordElement(N001, Parts)) 3179 return SDValue(); 3180 } 3181 3182 // Make sure the parts are all coming from the same node. 3183 if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3]) 3184 return SDValue(); 3185 3186 SDValue BSwap = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, 3187 SDValue(Parts[0],0)); 3188 3189 // Result of the bswap should be rotated by 16. If it's not legal, then 3190 // do (x << 16) | (x >> 16). 3191 SDValue ShAmt = DAG.getConstant(16, getShiftAmountTy(VT)); 3192 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT)) 3193 return DAG.getNode(ISD::ROTL, SDLoc(N), VT, BSwap, ShAmt); 3194 if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT)) 3195 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, BSwap, ShAmt); 3196 return DAG.getNode(ISD::OR, SDLoc(N), VT, 3197 DAG.getNode(ISD::SHL, SDLoc(N), VT, BSwap, ShAmt), 3198 DAG.getNode(ISD::SRL, SDLoc(N), VT, BSwap, ShAmt)); 3199 } 3200 3201 SDValue DAGCombiner::visitOR(SDNode *N) { 3202 SDValue N0 = N->getOperand(0); 3203 SDValue N1 = N->getOperand(1); 3204 SDValue LL, LR, RL, RR, CC0, CC1; 3205 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 3206 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 3207 EVT VT = N1.getValueType(); 3208 3209 // fold vector ops 3210 if (VT.isVector()) { 3211 SDValue FoldedVOp = SimplifyVBinOp(N); 3212 if (FoldedVOp.getNode()) return FoldedVOp; 3213 3214 // fold (or x, 0) -> x, vector edition 3215 if (ISD::isBuildVectorAllZeros(N0.getNode())) 3216 return N1; 3217 if (ISD::isBuildVectorAllZeros(N1.getNode())) 3218 return N0; 3219 3220 // fold (or x, -1) -> -1, vector edition 3221 if (ISD::isBuildVectorAllOnes(N0.getNode())) 3222 return N0; 3223 if (ISD::isBuildVectorAllOnes(N1.getNode())) 3224 return N1; 3225 3226 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1) 3227 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2) 3228 // Do this only if the resulting shuffle is legal. 3229 if (isa<ShuffleVectorSDNode>(N0) && 3230 isa<ShuffleVectorSDNode>(N1) && 3231 N0->getOperand(1) == N1->getOperand(1) && 3232 ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) { 3233 bool CanFold = true; 3234 unsigned NumElts = VT.getVectorNumElements(); 3235 const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0); 3236 const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1); 3237 // We construct two shuffle masks: 3238 // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand 3239 // and N1 as the second operand. 3240 // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand 3241 // and N0 as the second operand. 3242 // We do this because OR is commutable and therefore there might be 3243 // two ways to fold this node into a shuffle. 3244 SmallVector<int,4> Mask1; 3245 SmallVector<int,4> Mask2; 3246 3247 for (unsigned i = 0; i != NumElts && CanFold; ++i) { 3248 int M0 = SV0->getMaskElt(i); 3249 int M1 = SV1->getMaskElt(i); 3250 3251 // Both shuffle indexes are undef. Propagate Undef. 3252 if (M0 < 0 && M1 < 0) { 3253 Mask1.push_back(M0); 3254 Mask2.push_back(M0); 3255 continue; 3256 } 3257 3258 if (M0 < 0 || M1 < 0 || 3259 (M0 < (int)NumElts && M1 < (int)NumElts) || 3260 (M0 >= (int)NumElts && M1 >= (int)NumElts)) { 3261 CanFold = false; 3262 break; 3263 } 3264 3265 Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts); 3266 Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts); 3267 } 3268 3269 if (CanFold) { 3270 // Fold this sequence only if the resulting shuffle is 'legal'. 3271 if (TLI.isShuffleMaskLegal(Mask1, VT)) 3272 return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0), 3273 N1->getOperand(0), &Mask1[0]); 3274 if (TLI.isShuffleMaskLegal(Mask2, VT)) 3275 return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0), 3276 N0->getOperand(0), &Mask2[0]); 3277 } 3278 } 3279 } 3280 3281 // fold (or x, undef) -> -1 3282 if (!LegalOperations && 3283 (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) { 3284 EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT; 3285 return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT); 3286 } 3287 // fold (or c1, c2) -> c1|c2 3288 if (N0C && N1C) 3289 return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C); 3290 // canonicalize constant to RHS 3291 if (N0C && !N1C) 3292 return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0); 3293 // fold (or x, 0) -> x 3294 if (N1C && N1C->isNullValue()) 3295 return N0; 3296 // fold (or x, -1) -> -1 3297 if (N1C && N1C->isAllOnesValue()) 3298 return N1; 3299 // fold (or x, c) -> c iff (x & ~c) == 0 3300 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue())) 3301 return N1; 3302 3303 // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16) 3304 SDValue BSwap = MatchBSwapHWord(N, N0, N1); 3305 if (BSwap.getNode()) 3306 return BSwap; 3307 BSwap = MatchBSwapHWordLow(N, N0, N1); 3308 if (BSwap.getNode()) 3309 return BSwap; 3310 3311 // reassociate or 3312 SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1); 3313 if (ROR.getNode()) 3314 return ROR; 3315 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2) 3316 // iff (c1 & c2) == 0. 3317 if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() && 3318 isa<ConstantSDNode>(N0.getOperand(1))) { 3319 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1)); 3320 if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) { 3321 SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1); 3322 if (!COR.getNode()) 3323 return SDValue(); 3324 return DAG.getNode(ISD::AND, SDLoc(N), VT, 3325 DAG.getNode(ISD::OR, SDLoc(N0), VT, 3326 N0.getOperand(0), N1), COR); 3327 } 3328 } 3329 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y)) 3330 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){ 3331 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get(); 3332 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get(); 3333 3334 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 && 3335 LL.getValueType().isInteger()) { 3336 // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0) 3337 // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0) 3338 if (cast<ConstantSDNode>(LR)->isNullValue() && 3339 (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) { 3340 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR), 3341 LR.getValueType(), LL, RL); 3342 AddToWorkList(ORNode.getNode()); 3343 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1); 3344 } 3345 // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1) 3346 // fold (or (setgt X, -1), (setgt Y -1)) -> (setgt (and X, Y), -1) 3347 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && 3348 (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) { 3349 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR), 3350 LR.getValueType(), LL, RL); 3351 AddToWorkList(ANDNode.getNode()); 3352 return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1); 3353 } 3354 } 3355 // canonicalize equivalent to ll == rl 3356 if (LL == RR && LR == RL) { 3357 Op1 = ISD::getSetCCSwappedOperands(Op1); 3358 std::swap(RL, RR); 3359 } 3360 if (LL == RL && LR == RR) { 3361 bool isInteger = LL.getValueType().isInteger(); 3362 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger); 3363 if (Result != ISD::SETCC_INVALID && 3364 (!LegalOperations || 3365 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) && 3366 TLI.isOperationLegal(ISD::SETCC, 3367 getSetCCResultType(N0.getValueType()))))) 3368 return DAG.getSetCC(SDLoc(N), N0.getValueType(), 3369 LL, LR, Result); 3370 } 3371 } 3372 3373 // Simplify: (or (op x...), (op y...)) -> (op (or x, y)) 3374 if (N0.getOpcode() == N1.getOpcode()) { 3375 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N); 3376 if (Tmp.getNode()) return Tmp; 3377 } 3378 3379 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible. 3380 if (N0.getOpcode() == ISD::AND && 3381 N1.getOpcode() == ISD::AND && 3382 N0.getOperand(1).getOpcode() == ISD::Constant && 3383 N1.getOperand(1).getOpcode() == ISD::Constant && 3384 // Don't increase # computations. 3385 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) { 3386 // We can only do this xform if we know that bits from X that are set in C2 3387 // but not in C1 are already zero. Likewise for Y. 3388 const APInt &LHSMask = 3389 cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 3390 const APInt &RHSMask = 3391 cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue(); 3392 3393 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) && 3394 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) { 3395 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT, 3396 N0.getOperand(0), N1.getOperand(0)); 3397 return DAG.getNode(ISD::AND, SDLoc(N), VT, X, 3398 DAG.getConstant(LHSMask | RHSMask, VT)); 3399 } 3400 } 3401 3402 // See if this is some rotate idiom. 3403 if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N))) 3404 return SDValue(Rot, 0); 3405 3406 // Simplify the operands using demanded-bits information. 3407 if (!VT.isVector() && 3408 SimplifyDemandedBits(SDValue(N, 0))) 3409 return SDValue(N, 0); 3410 3411 return SDValue(); 3412 } 3413 3414 /// MatchRotateHalf - Match "(X shl/srl V1) & V2" where V2 may not be present. 3415 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) { 3416 if (Op.getOpcode() == ISD::AND) { 3417 if (isa<ConstantSDNode>(Op.getOperand(1))) { 3418 Mask = Op.getOperand(1); 3419 Op = Op.getOperand(0); 3420 } else { 3421 return false; 3422 } 3423 } 3424 3425 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) { 3426 Shift = Op; 3427 return true; 3428 } 3429 3430 return false; 3431 } 3432 3433 // Return true if we can prove that, whenever Neg and Pos are both in the 3434 // range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos). This means that 3435 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits: 3436 // 3437 // (or (shift1 X, Neg), (shift2 X, Pos)) 3438 // 3439 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate 3440 // in direction shift1 by Neg. The range [0, OpSize) means that we only need 3441 // to consider shift amounts with defined behavior. 3442 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) { 3443 // If OpSize is a power of 2 then: 3444 // 3445 // (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1) 3446 // (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize). 3447 // 3448 // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check 3449 // for the stronger condition: 3450 // 3451 // Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1) [A] 3452 // 3453 // for all Neg and Pos. Since Neg & (OpSize - 1) == Neg' & (OpSize - 1) 3454 // we can just replace Neg with Neg' for the rest of the function. 3455 // 3456 // In other cases we check for the even stronger condition: 3457 // 3458 // Neg == OpSize - Pos [B] 3459 // 3460 // for all Neg and Pos. Note that the (or ...) then invokes undefined 3461 // behavior if Pos == 0 (and consequently Neg == OpSize). 3462 // 3463 // We could actually use [A] whenever OpSize is a power of 2, but the 3464 // only extra cases that it would match are those uninteresting ones 3465 // where Neg and Pos are never in range at the same time. E.g. for 3466 // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos) 3467 // as well as (sub 32, Pos), but: 3468 // 3469 // (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos)) 3470 // 3471 // always invokes undefined behavior for 32-bit X. 3472 // 3473 // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise. 3474 unsigned MaskLoBits = 0; 3475 if (Neg.getOpcode() == ISD::AND && 3476 isPowerOf2_64(OpSize) && 3477 Neg.getOperand(1).getOpcode() == ISD::Constant && 3478 cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) { 3479 Neg = Neg.getOperand(0); 3480 MaskLoBits = Log2_64(OpSize); 3481 } 3482 3483 // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1. 3484 if (Neg.getOpcode() != ISD::SUB) 3485 return 0; 3486 ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0)); 3487 if (!NegC) 3488 return 0; 3489 SDValue NegOp1 = Neg.getOperand(1); 3490 3491 // On the RHS of [A], if Pos is Pos' & (OpSize - 1), just replace Pos with 3492 // Pos'. The truncation is redundant for the purpose of the equality. 3493 if (MaskLoBits && 3494 Pos.getOpcode() == ISD::AND && 3495 Pos.getOperand(1).getOpcode() == ISD::Constant && 3496 cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() == OpSize - 1) 3497 Pos = Pos.getOperand(0); 3498 3499 // The condition we need is now: 3500 // 3501 // (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask 3502 // 3503 // If NegOp1 == Pos then we need: 3504 // 3505 // OpSize & Mask == NegC & Mask 3506 // 3507 // (because "x & Mask" is a truncation and distributes through subtraction). 3508 APInt Width; 3509 if (Pos == NegOp1) 3510 Width = NegC->getAPIntValue(); 3511 // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC. 3512 // Then the condition we want to prove becomes: 3513 // 3514 // (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask 3515 // 3516 // which, again because "x & Mask" is a truncation, becomes: 3517 // 3518 // NegC & Mask == (OpSize - PosC) & Mask 3519 // OpSize & Mask == (NegC + PosC) & Mask 3520 else if (Pos.getOpcode() == ISD::ADD && 3521 Pos.getOperand(0) == NegOp1 && 3522 Pos.getOperand(1).getOpcode() == ISD::Constant) 3523 Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() + 3524 NegC->getAPIntValue()); 3525 else 3526 return false; 3527 3528 // Now we just need to check that OpSize & Mask == Width & Mask. 3529 if (MaskLoBits) 3530 // Opsize & Mask is 0 since Mask is Opsize - 1. 3531 return Width.getLoBits(MaskLoBits) == 0; 3532 return Width == OpSize; 3533 } 3534 3535 // A subroutine of MatchRotate used once we have found an OR of two opposite 3536 // shifts of Shifted. If Neg == <operand size> - Pos then the OR reduces 3537 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the 3538 // former being preferred if supported. InnerPos and InnerNeg are Pos and 3539 // Neg with outer conversions stripped away. 3540 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos, 3541 SDValue Neg, SDValue InnerPos, 3542 SDValue InnerNeg, unsigned PosOpcode, 3543 unsigned NegOpcode, SDLoc DL) { 3544 // fold (or (shl x, (*ext y)), 3545 // (srl x, (*ext (sub 32, y)))) -> 3546 // (rotl x, y) or (rotr x, (sub 32, y)) 3547 // 3548 // fold (or (shl x, (*ext (sub 32, y))), 3549 // (srl x, (*ext y))) -> 3550 // (rotr x, y) or (rotl x, (sub 32, y)) 3551 EVT VT = Shifted.getValueType(); 3552 if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) { 3553 bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT); 3554 return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted, 3555 HasPos ? Pos : Neg).getNode(); 3556 } 3557 3558 return nullptr; 3559 } 3560 3561 // MatchRotate - Handle an 'or' of two operands. If this is one of the many 3562 // idioms for rotate, and if the target supports rotation instructions, generate 3563 // a rot[lr]. 3564 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) { 3565 // Must be a legal type. Expanded 'n promoted things won't work with rotates. 3566 EVT VT = LHS.getValueType(); 3567 if (!TLI.isTypeLegal(VT)) return nullptr; 3568 3569 // The target must have at least one rotate flavor. 3570 bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT); 3571 bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT); 3572 if (!HasROTL && !HasROTR) return nullptr; 3573 3574 // Match "(X shl/srl V1) & V2" where V2 may not be present. 3575 SDValue LHSShift; // The shift. 3576 SDValue LHSMask; // AND value if any. 3577 if (!MatchRotateHalf(LHS, LHSShift, LHSMask)) 3578 return nullptr; // Not part of a rotate. 3579 3580 SDValue RHSShift; // The shift. 3581 SDValue RHSMask; // AND value if any. 3582 if (!MatchRotateHalf(RHS, RHSShift, RHSMask)) 3583 return nullptr; // Not part of a rotate. 3584 3585 if (LHSShift.getOperand(0) != RHSShift.getOperand(0)) 3586 return nullptr; // Not shifting the same value. 3587 3588 if (LHSShift.getOpcode() == RHSShift.getOpcode()) 3589 return nullptr; // Shifts must disagree. 3590 3591 // Canonicalize shl to left side in a shl/srl pair. 3592 if (RHSShift.getOpcode() == ISD::SHL) { 3593 std::swap(LHS, RHS); 3594 std::swap(LHSShift, RHSShift); 3595 std::swap(LHSMask , RHSMask ); 3596 } 3597 3598 unsigned OpSizeInBits = VT.getSizeInBits(); 3599 SDValue LHSShiftArg = LHSShift.getOperand(0); 3600 SDValue LHSShiftAmt = LHSShift.getOperand(1); 3601 SDValue RHSShiftArg = RHSShift.getOperand(0); 3602 SDValue RHSShiftAmt = RHSShift.getOperand(1); 3603 3604 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1) 3605 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2) 3606 if (LHSShiftAmt.getOpcode() == ISD::Constant && 3607 RHSShiftAmt.getOpcode() == ISD::Constant) { 3608 uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue(); 3609 uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue(); 3610 if ((LShVal + RShVal) != OpSizeInBits) 3611 return nullptr; 3612 3613 SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT, 3614 LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt); 3615 3616 // If there is an AND of either shifted operand, apply it to the result. 3617 if (LHSMask.getNode() || RHSMask.getNode()) { 3618 APInt Mask = APInt::getAllOnesValue(OpSizeInBits); 3619 3620 if (LHSMask.getNode()) { 3621 APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal); 3622 Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits; 3623 } 3624 if (RHSMask.getNode()) { 3625 APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal); 3626 Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits; 3627 } 3628 3629 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT)); 3630 } 3631 3632 return Rot.getNode(); 3633 } 3634 3635 // If there is a mask here, and we have a variable shift, we can't be sure 3636 // that we're masking out the right stuff. 3637 if (LHSMask.getNode() || RHSMask.getNode()) 3638 return nullptr; 3639 3640 // If the shift amount is sign/zext/any-extended just peel it off. 3641 SDValue LExtOp0 = LHSShiftAmt; 3642 SDValue RExtOp0 = RHSShiftAmt; 3643 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND || 3644 LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND || 3645 LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND || 3646 LHSShiftAmt.getOpcode() == ISD::TRUNCATE) && 3647 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND || 3648 RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND || 3649 RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND || 3650 RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) { 3651 LExtOp0 = LHSShiftAmt.getOperand(0); 3652 RExtOp0 = RHSShiftAmt.getOperand(0); 3653 } 3654 3655 SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt, 3656 LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL); 3657 if (TryL) 3658 return TryL; 3659 3660 SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt, 3661 RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL); 3662 if (TryR) 3663 return TryR; 3664 3665 return nullptr; 3666 } 3667 3668 SDValue DAGCombiner::visitXOR(SDNode *N) { 3669 SDValue N0 = N->getOperand(0); 3670 SDValue N1 = N->getOperand(1); 3671 SDValue LHS, RHS, CC; 3672 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 3673 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 3674 EVT VT = N0.getValueType(); 3675 3676 // fold vector ops 3677 if (VT.isVector()) { 3678 SDValue FoldedVOp = SimplifyVBinOp(N); 3679 if (FoldedVOp.getNode()) return FoldedVOp; 3680 3681 // fold (xor x, 0) -> x, vector edition 3682 if (ISD::isBuildVectorAllZeros(N0.getNode())) 3683 return N1; 3684 if (ISD::isBuildVectorAllZeros(N1.getNode())) 3685 return N0; 3686 } 3687 3688 // fold (xor undef, undef) -> 0. This is a common idiom (misuse). 3689 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF) 3690 return DAG.getConstant(0, VT); 3691 // fold (xor x, undef) -> undef 3692 if (N0.getOpcode() == ISD::UNDEF) 3693 return N0; 3694 if (N1.getOpcode() == ISD::UNDEF) 3695 return N1; 3696 // fold (xor c1, c2) -> c1^c2 3697 if (N0C && N1C) 3698 return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C); 3699 // canonicalize constant to RHS 3700 if (N0C && !N1C) 3701 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0); 3702 // fold (xor x, 0) -> x 3703 if (N1C && N1C->isNullValue()) 3704 return N0; 3705 // reassociate xor 3706 SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1); 3707 if (RXOR.getNode()) 3708 return RXOR; 3709 3710 // fold !(x cc y) -> (x !cc y) 3711 if (N1C && N1C->getAPIntValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) { 3712 bool isInt = LHS.getValueType().isInteger(); 3713 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(), 3714 isInt); 3715 3716 if (!LegalOperations || 3717 TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) { 3718 switch (N0.getOpcode()) { 3719 default: 3720 llvm_unreachable("Unhandled SetCC Equivalent!"); 3721 case ISD::SETCC: 3722 return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC); 3723 case ISD::SELECT_CC: 3724 return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2), 3725 N0.getOperand(3), NotCC); 3726 } 3727 } 3728 } 3729 3730 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y))) 3731 if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND && 3732 N0.getNode()->hasOneUse() && 3733 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){ 3734 SDValue V = N0.getOperand(0); 3735 V = DAG.getNode(ISD::XOR, SDLoc(N0), V.getValueType(), V, 3736 DAG.getConstant(1, V.getValueType())); 3737 AddToWorkList(V.getNode()); 3738 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V); 3739 } 3740 3741 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc 3742 if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 && 3743 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) { 3744 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1); 3745 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) { 3746 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND; 3747 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS 3748 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS 3749 AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode()); 3750 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS); 3751 } 3752 } 3753 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants 3754 if (N1C && N1C->isAllOnesValue() && 3755 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) { 3756 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1); 3757 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) { 3758 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND; 3759 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS 3760 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS 3761 AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode()); 3762 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS); 3763 } 3764 } 3765 // fold (xor (and x, y), y) -> (and (not x), y) 3766 if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() && 3767 N0->getOperand(1) == N1) { 3768 SDValue X = N0->getOperand(0); 3769 SDValue NotX = DAG.getNOT(SDLoc(X), X, VT); 3770 AddToWorkList(NotX.getNode()); 3771 return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1); 3772 } 3773 // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2)) 3774 if (N1C && N0.getOpcode() == ISD::XOR) { 3775 ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0)); 3776 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 3777 if (N00C) 3778 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(1), 3779 DAG.getConstant(N1C->getAPIntValue() ^ 3780 N00C->getAPIntValue(), VT)); 3781 if (N01C) 3782 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(0), 3783 DAG.getConstant(N1C->getAPIntValue() ^ 3784 N01C->getAPIntValue(), VT)); 3785 } 3786 // fold (xor x, x) -> 0 3787 if (N0 == N1) 3788 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes); 3789 3790 // Simplify: xor (op x...), (op y...) -> (op (xor x, y)) 3791 if (N0.getOpcode() == N1.getOpcode()) { 3792 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N); 3793 if (Tmp.getNode()) return Tmp; 3794 } 3795 3796 // Simplify the expression using non-local knowledge. 3797 if (!VT.isVector() && 3798 SimplifyDemandedBits(SDValue(N, 0))) 3799 return SDValue(N, 0); 3800 3801 return SDValue(); 3802 } 3803 3804 /// visitShiftByConstant - Handle transforms common to the three shifts, when 3805 /// the shift amount is a constant. 3806 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) { 3807 // We can't and shouldn't fold opaque constants. 3808 if (Amt->isOpaque()) 3809 return SDValue(); 3810 3811 SDNode *LHS = N->getOperand(0).getNode(); 3812 if (!LHS->hasOneUse()) return SDValue(); 3813 3814 // We want to pull some binops through shifts, so that we have (and (shift)) 3815 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of 3816 // thing happens with address calculations, so it's important to canonicalize 3817 // it. 3818 bool HighBitSet = false; // Can we transform this if the high bit is set? 3819 3820 switch (LHS->getOpcode()) { 3821 default: return SDValue(); 3822 case ISD::OR: 3823 case ISD::XOR: 3824 HighBitSet = false; // We can only transform sra if the high bit is clear. 3825 break; 3826 case ISD::AND: 3827 HighBitSet = true; // We can only transform sra if the high bit is set. 3828 break; 3829 case ISD::ADD: 3830 if (N->getOpcode() != ISD::SHL) 3831 return SDValue(); // only shl(add) not sr[al](add). 3832 HighBitSet = false; // We can only transform sra if the high bit is clear. 3833 break; 3834 } 3835 3836 // We require the RHS of the binop to be a constant and not opaque as well. 3837 ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1)); 3838 if (!BinOpCst || BinOpCst->isOpaque()) return SDValue(); 3839 3840 // FIXME: disable this unless the input to the binop is a shift by a constant. 3841 // If it is not a shift, it pessimizes some common cases like: 3842 // 3843 // void foo(int *X, int i) { X[i & 1235] = 1; } 3844 // int bar(int *X, int i) { return X[i & 255]; } 3845 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode(); 3846 if ((BinOpLHSVal->getOpcode() != ISD::SHL && 3847 BinOpLHSVal->getOpcode() != ISD::SRA && 3848 BinOpLHSVal->getOpcode() != ISD::SRL) || 3849 !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1))) 3850 return SDValue(); 3851 3852 EVT VT = N->getValueType(0); 3853 3854 // If this is a signed shift right, and the high bit is modified by the 3855 // logical operation, do not perform the transformation. The highBitSet 3856 // boolean indicates the value of the high bit of the constant which would 3857 // cause it to be modified for this operation. 3858 if (N->getOpcode() == ISD::SRA) { 3859 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative(); 3860 if (BinOpRHSSignSet != HighBitSet) 3861 return SDValue(); 3862 } 3863 3864 // Fold the constants, shifting the binop RHS by the shift amount. 3865 SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)), 3866 N->getValueType(0), 3867 LHS->getOperand(1), N->getOperand(1)); 3868 assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!"); 3869 3870 // Create the new shift. 3871 SDValue NewShift = DAG.getNode(N->getOpcode(), 3872 SDLoc(LHS->getOperand(0)), 3873 VT, LHS->getOperand(0), N->getOperand(1)); 3874 3875 // Create the new binop. 3876 return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS); 3877 } 3878 3879 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) { 3880 assert(N->getOpcode() == ISD::TRUNCATE); 3881 assert(N->getOperand(0).getOpcode() == ISD::AND); 3882 3883 // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC) 3884 if (N->hasOneUse() && N->getOperand(0).hasOneUse()) { 3885 SDValue N01 = N->getOperand(0).getOperand(1); 3886 3887 if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) { 3888 EVT TruncVT = N->getValueType(0); 3889 SDValue N00 = N->getOperand(0).getOperand(0); 3890 APInt TruncC = N01C->getAPIntValue(); 3891 TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits()); 3892 3893 return DAG.getNode(ISD::AND, SDLoc(N), TruncVT, 3894 DAG.getNode(ISD::TRUNCATE, SDLoc(N), TruncVT, N00), 3895 DAG.getConstant(TruncC, TruncVT)); 3896 } 3897 } 3898 3899 return SDValue(); 3900 } 3901 3902 SDValue DAGCombiner::visitRotate(SDNode *N) { 3903 // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))). 3904 if (N->getOperand(1).getOpcode() == ISD::TRUNCATE && 3905 N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) { 3906 SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode()); 3907 if (NewOp1.getNode()) 3908 return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0), 3909 N->getOperand(0), NewOp1); 3910 } 3911 return SDValue(); 3912 } 3913 3914 SDValue DAGCombiner::visitSHL(SDNode *N) { 3915 SDValue N0 = N->getOperand(0); 3916 SDValue N1 = N->getOperand(1); 3917 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 3918 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 3919 EVT VT = N0.getValueType(); 3920 unsigned OpSizeInBits = VT.getScalarSizeInBits(); 3921 3922 // fold vector ops 3923 if (VT.isVector()) { 3924 SDValue FoldedVOp = SimplifyVBinOp(N); 3925 if (FoldedVOp.getNode()) return FoldedVOp; 3926 3927 BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1); 3928 // If setcc produces all-one true value then: 3929 // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV) 3930 if (N1CV && N1CV->isConstant()) { 3931 if (N0.getOpcode() == ISD::AND && 3932 TLI.getBooleanContents(true) == 3933 TargetLowering::ZeroOrNegativeOneBooleanContent) { 3934 SDValue N00 = N0->getOperand(0); 3935 SDValue N01 = N0->getOperand(1); 3936 BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01); 3937 3938 if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC) { 3939 SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, VT, N01CV, N1CV); 3940 if (C.getNode()) 3941 return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C); 3942 } 3943 } else { 3944 N1C = isConstOrConstSplat(N1); 3945 } 3946 } 3947 } 3948 3949 // fold (shl c1, c2) -> c1<<c2 3950 if (N0C && N1C) 3951 return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C); 3952 // fold (shl 0, x) -> 0 3953 if (N0C && N0C->isNullValue()) 3954 return N0; 3955 // fold (shl x, c >= size(x)) -> undef 3956 if (N1C && N1C->getZExtValue() >= OpSizeInBits) 3957 return DAG.getUNDEF(VT); 3958 // fold (shl x, 0) -> x 3959 if (N1C && N1C->isNullValue()) 3960 return N0; 3961 // fold (shl undef, x) -> 0 3962 if (N0.getOpcode() == ISD::UNDEF) 3963 return DAG.getConstant(0, VT); 3964 // if (shl x, c) is known to be zero, return 0 3965 if (DAG.MaskedValueIsZero(SDValue(N, 0), 3966 APInt::getAllOnesValue(OpSizeInBits))) 3967 return DAG.getConstant(0, VT); 3968 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))). 3969 if (N1.getOpcode() == ISD::TRUNCATE && 3970 N1.getOperand(0).getOpcode() == ISD::AND) { 3971 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()); 3972 if (NewOp1.getNode()) 3973 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1); 3974 } 3975 3976 if (N1C && SimplifyDemandedBits(SDValue(N, 0))) 3977 return SDValue(N, 0); 3978 3979 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2)) 3980 if (N1C && N0.getOpcode() == ISD::SHL) { 3981 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) { 3982 uint64_t c1 = N0C1->getZExtValue(); 3983 uint64_t c2 = N1C->getZExtValue(); 3984 if (c1 + c2 >= OpSizeInBits) 3985 return DAG.getConstant(0, VT); 3986 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0), 3987 DAG.getConstant(c1 + c2, N1.getValueType())); 3988 } 3989 } 3990 3991 // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2))) 3992 // For this to be valid, the second form must not preserve any of the bits 3993 // that are shifted out by the inner shift in the first form. This means 3994 // the outer shift size must be >= the number of bits added by the ext. 3995 // As a corollary, we don't care what kind of ext it is. 3996 if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND || 3997 N0.getOpcode() == ISD::ANY_EXTEND || 3998 N0.getOpcode() == ISD::SIGN_EXTEND) && 3999 N0.getOperand(0).getOpcode() == ISD::SHL) { 4000 SDValue N0Op0 = N0.getOperand(0); 4001 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) { 4002 uint64_t c1 = N0Op0C1->getZExtValue(); 4003 uint64_t c2 = N1C->getZExtValue(); 4004 EVT InnerShiftVT = N0Op0.getValueType(); 4005 uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits(); 4006 if (c2 >= OpSizeInBits - InnerShiftSize) { 4007 if (c1 + c2 >= OpSizeInBits) 4008 return DAG.getConstant(0, VT); 4009 return DAG.getNode(ISD::SHL, SDLoc(N0), VT, 4010 DAG.getNode(N0.getOpcode(), SDLoc(N0), VT, 4011 N0Op0->getOperand(0)), 4012 DAG.getConstant(c1 + c2, N1.getValueType())); 4013 } 4014 } 4015 } 4016 4017 // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C)) 4018 // Only fold this if the inner zext has no other uses to avoid increasing 4019 // the total number of instructions. 4020 if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() && 4021 N0.getOperand(0).getOpcode() == ISD::SRL) { 4022 SDValue N0Op0 = N0.getOperand(0); 4023 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) { 4024 uint64_t c1 = N0Op0C1->getZExtValue(); 4025 if (c1 < VT.getScalarSizeInBits()) { 4026 uint64_t c2 = N1C->getZExtValue(); 4027 if (c1 == c2) { 4028 SDValue NewOp0 = N0.getOperand(0); 4029 EVT CountVT = NewOp0.getOperand(1).getValueType(); 4030 SDValue NewSHL = DAG.getNode(ISD::SHL, SDLoc(N), NewOp0.getValueType(), 4031 NewOp0, DAG.getConstant(c2, CountVT)); 4032 AddToWorkList(NewSHL.getNode()); 4033 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL); 4034 } 4035 } 4036 } 4037 } 4038 4039 // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or 4040 // (and (srl x, (sub c1, c2), MASK) 4041 // Only fold this if the inner shift has no other uses -- if it does, folding 4042 // this will increase the total number of instructions. 4043 if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) { 4044 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) { 4045 uint64_t c1 = N0C1->getZExtValue(); 4046 if (c1 < OpSizeInBits) { 4047 uint64_t c2 = N1C->getZExtValue(); 4048 APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1); 4049 SDValue Shift; 4050 if (c2 > c1) { 4051 Mask = Mask.shl(c2 - c1); 4052 Shift = DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0), 4053 DAG.getConstant(c2 - c1, N1.getValueType())); 4054 } else { 4055 Mask = Mask.lshr(c1 - c2); 4056 Shift = DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), 4057 DAG.getConstant(c1 - c2, N1.getValueType())); 4058 } 4059 return DAG.getNode(ISD::AND, SDLoc(N0), VT, Shift, 4060 DAG.getConstant(Mask, VT)); 4061 } 4062 } 4063 } 4064 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1)) 4065 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) { 4066 unsigned BitSize = VT.getScalarSizeInBits(); 4067 SDValue HiBitsMask = 4068 DAG.getConstant(APInt::getHighBitsSet(BitSize, 4069 BitSize - N1C->getZExtValue()), VT); 4070 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0), 4071 HiBitsMask); 4072 } 4073 4074 if (N1C) { 4075 SDValue NewSHL = visitShiftByConstant(N, N1C); 4076 if (NewSHL.getNode()) 4077 return NewSHL; 4078 } 4079 4080 return SDValue(); 4081 } 4082 4083 SDValue DAGCombiner::visitSRA(SDNode *N) { 4084 SDValue N0 = N->getOperand(0); 4085 SDValue N1 = N->getOperand(1); 4086 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 4087 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 4088 EVT VT = N0.getValueType(); 4089 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits(); 4090 4091 // fold vector ops 4092 if (VT.isVector()) { 4093 SDValue FoldedVOp = SimplifyVBinOp(N); 4094 if (FoldedVOp.getNode()) return FoldedVOp; 4095 4096 N1C = isConstOrConstSplat(N1); 4097 } 4098 4099 // fold (sra c1, c2) -> (sra c1, c2) 4100 if (N0C && N1C) 4101 return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C); 4102 // fold (sra 0, x) -> 0 4103 if (N0C && N0C->isNullValue()) 4104 return N0; 4105 // fold (sra -1, x) -> -1 4106 if (N0C && N0C->isAllOnesValue()) 4107 return N0; 4108 // fold (sra x, (setge c, size(x))) -> undef 4109 if (N1C && N1C->getZExtValue() >= OpSizeInBits) 4110 return DAG.getUNDEF(VT); 4111 // fold (sra x, 0) -> x 4112 if (N1C && N1C->isNullValue()) 4113 return N0; 4114 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports 4115 // sext_inreg. 4116 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) { 4117 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue(); 4118 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits); 4119 if (VT.isVector()) 4120 ExtVT = EVT::getVectorVT(*DAG.getContext(), 4121 ExtVT, VT.getVectorNumElements()); 4122 if ((!LegalOperations || 4123 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT))) 4124 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, 4125 N0.getOperand(0), DAG.getValueType(ExtVT)); 4126 } 4127 4128 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2)) 4129 if (N1C && N0.getOpcode() == ISD::SRA) { 4130 if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) { 4131 unsigned Sum = N1C->getZExtValue() + C1->getZExtValue(); 4132 if (Sum >= OpSizeInBits) 4133 Sum = OpSizeInBits - 1; 4134 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0.getOperand(0), 4135 DAG.getConstant(Sum, N1.getValueType())); 4136 } 4137 } 4138 4139 // fold (sra (shl X, m), (sub result_size, n)) 4140 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for 4141 // result_size - n != m. 4142 // If truncate is free for the target sext(shl) is likely to result in better 4143 // code. 4144 if (N0.getOpcode() == ISD::SHL && N1C) { 4145 // Get the two constanst of the shifts, CN0 = m, CN = n. 4146 const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1)); 4147 if (N01C) { 4148 LLVMContext &Ctx = *DAG.getContext(); 4149 // Determine what the truncate's result bitsize and type would be. 4150 EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue()); 4151 4152 if (VT.isVector()) 4153 TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements()); 4154 4155 // Determine the residual right-shift amount. 4156 signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue(); 4157 4158 // If the shift is not a no-op (in which case this should be just a sign 4159 // extend already), the truncated to type is legal, sign_extend is legal 4160 // on that type, and the truncate to that type is both legal and free, 4161 // perform the transform. 4162 if ((ShiftAmt > 0) && 4163 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) && 4164 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) && 4165 TLI.isTruncateFree(VT, TruncVT)) { 4166 4167 SDValue Amt = DAG.getConstant(ShiftAmt, 4168 getShiftAmountTy(N0.getOperand(0).getValueType())); 4169 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), VT, 4170 N0.getOperand(0), Amt); 4171 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), TruncVT, 4172 Shift); 4173 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), 4174 N->getValueType(0), Trunc); 4175 } 4176 } 4177 } 4178 4179 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))). 4180 if (N1.getOpcode() == ISD::TRUNCATE && 4181 N1.getOperand(0).getOpcode() == ISD::AND) { 4182 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()); 4183 if (NewOp1.getNode()) 4184 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1); 4185 } 4186 4187 // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2)) 4188 // if c1 is equal to the number of bits the trunc removes 4189 if (N0.getOpcode() == ISD::TRUNCATE && 4190 (N0.getOperand(0).getOpcode() == ISD::SRL || 4191 N0.getOperand(0).getOpcode() == ISD::SRA) && 4192 N0.getOperand(0).hasOneUse() && 4193 N0.getOperand(0).getOperand(1).hasOneUse() && 4194 N1C) { 4195 SDValue N0Op0 = N0.getOperand(0); 4196 if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) { 4197 unsigned LargeShiftVal = LargeShift->getZExtValue(); 4198 EVT LargeVT = N0Op0.getValueType(); 4199 4200 if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) { 4201 SDValue Amt = 4202 DAG.getConstant(LargeShiftVal + N1C->getZExtValue(), 4203 getShiftAmountTy(N0Op0.getOperand(0).getValueType())); 4204 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), LargeVT, 4205 N0Op0.getOperand(0), Amt); 4206 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, SRA); 4207 } 4208 } 4209 } 4210 4211 // Simplify, based on bits shifted out of the LHS. 4212 if (N1C && SimplifyDemandedBits(SDValue(N, 0))) 4213 return SDValue(N, 0); 4214 4215 4216 // If the sign bit is known to be zero, switch this to a SRL. 4217 if (DAG.SignBitIsZero(N0)) 4218 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1); 4219 4220 if (N1C) { 4221 SDValue NewSRA = visitShiftByConstant(N, N1C); 4222 if (NewSRA.getNode()) 4223 return NewSRA; 4224 } 4225 4226 return SDValue(); 4227 } 4228 4229 SDValue DAGCombiner::visitSRL(SDNode *N) { 4230 SDValue N0 = N->getOperand(0); 4231 SDValue N1 = N->getOperand(1); 4232 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 4233 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 4234 EVT VT = N0.getValueType(); 4235 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits(); 4236 4237 // fold vector ops 4238 if (VT.isVector()) { 4239 SDValue FoldedVOp = SimplifyVBinOp(N); 4240 if (FoldedVOp.getNode()) return FoldedVOp; 4241 4242 N1C = isConstOrConstSplat(N1); 4243 } 4244 4245 // fold (srl c1, c2) -> c1 >>u c2 4246 if (N0C && N1C) 4247 return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C); 4248 // fold (srl 0, x) -> 0 4249 if (N0C && N0C->isNullValue()) 4250 return N0; 4251 // fold (srl x, c >= size(x)) -> undef 4252 if (N1C && N1C->getZExtValue() >= OpSizeInBits) 4253 return DAG.getUNDEF(VT); 4254 // fold (srl x, 0) -> x 4255 if (N1C && N1C->isNullValue()) 4256 return N0; 4257 // if (srl x, c) is known to be zero, return 0 4258 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0), 4259 APInt::getAllOnesValue(OpSizeInBits))) 4260 return DAG.getConstant(0, VT); 4261 4262 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2)) 4263 if (N1C && N0.getOpcode() == ISD::SRL) { 4264 if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) { 4265 uint64_t c1 = N01C->getZExtValue(); 4266 uint64_t c2 = N1C->getZExtValue(); 4267 if (c1 + c2 >= OpSizeInBits) 4268 return DAG.getConstant(0, VT); 4269 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), 4270 DAG.getConstant(c1 + c2, N1.getValueType())); 4271 } 4272 } 4273 4274 // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2))) 4275 if (N1C && N0.getOpcode() == ISD::TRUNCATE && 4276 N0.getOperand(0).getOpcode() == ISD::SRL && 4277 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) { 4278 uint64_t c1 = 4279 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue(); 4280 uint64_t c2 = N1C->getZExtValue(); 4281 EVT InnerShiftVT = N0.getOperand(0).getValueType(); 4282 EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType(); 4283 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits(); 4284 // This is only valid if the OpSizeInBits + c1 = size of inner shift. 4285 if (c1 + OpSizeInBits == InnerShiftSize) { 4286 if (c1 + c2 >= InnerShiftSize) 4287 return DAG.getConstant(0, VT); 4288 return DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, 4289 DAG.getNode(ISD::SRL, SDLoc(N0), InnerShiftVT, 4290 N0.getOperand(0)->getOperand(0), 4291 DAG.getConstant(c1 + c2, ShiftCountVT))); 4292 } 4293 } 4294 4295 // fold (srl (shl x, c), c) -> (and x, cst2) 4296 if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) { 4297 unsigned BitSize = N0.getScalarValueSizeInBits(); 4298 if (BitSize <= 64) { 4299 uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize; 4300 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0), 4301 DAG.getConstant(~0ULL >> ShAmt, VT)); 4302 } 4303 } 4304 4305 // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask) 4306 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) { 4307 // Shifting in all undef bits? 4308 EVT SmallVT = N0.getOperand(0).getValueType(); 4309 unsigned BitSize = SmallVT.getScalarSizeInBits(); 4310 if (N1C->getZExtValue() >= BitSize) 4311 return DAG.getUNDEF(VT); 4312 4313 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) { 4314 uint64_t ShiftAmt = N1C->getZExtValue(); 4315 SDValue SmallShift = DAG.getNode(ISD::SRL, SDLoc(N0), SmallVT, 4316 N0.getOperand(0), 4317 DAG.getConstant(ShiftAmt, getShiftAmountTy(SmallVT))); 4318 AddToWorkList(SmallShift.getNode()); 4319 APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt); 4320 return DAG.getNode(ISD::AND, SDLoc(N), VT, 4321 DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, SmallShift), 4322 DAG.getConstant(Mask, VT)); 4323 } 4324 } 4325 4326 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign 4327 // bit, which is unmodified by sra. 4328 if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) { 4329 if (N0.getOpcode() == ISD::SRA) 4330 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1); 4331 } 4332 4333 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit). 4334 if (N1C && N0.getOpcode() == ISD::CTLZ && 4335 N1C->getAPIntValue() == Log2_32(OpSizeInBits)) { 4336 APInt KnownZero, KnownOne; 4337 DAG.ComputeMaskedBits(N0.getOperand(0), KnownZero, KnownOne); 4338 4339 // If any of the input bits are KnownOne, then the input couldn't be all 4340 // zeros, thus the result of the srl will always be zero. 4341 if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT); 4342 4343 // If all of the bits input the to ctlz node are known to be zero, then 4344 // the result of the ctlz is "32" and the result of the shift is one. 4345 APInt UnknownBits = ~KnownZero; 4346 if (UnknownBits == 0) return DAG.getConstant(1, VT); 4347 4348 // Otherwise, check to see if there is exactly one bit input to the ctlz. 4349 if ((UnknownBits & (UnknownBits - 1)) == 0) { 4350 // Okay, we know that only that the single bit specified by UnknownBits 4351 // could be set on input to the CTLZ node. If this bit is set, the SRL 4352 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair 4353 // to an SRL/XOR pair, which is likely to simplify more. 4354 unsigned ShAmt = UnknownBits.countTrailingZeros(); 4355 SDValue Op = N0.getOperand(0); 4356 4357 if (ShAmt) { 4358 Op = DAG.getNode(ISD::SRL, SDLoc(N0), VT, Op, 4359 DAG.getConstant(ShAmt, getShiftAmountTy(Op.getValueType()))); 4360 AddToWorkList(Op.getNode()); 4361 } 4362 4363 return DAG.getNode(ISD::XOR, SDLoc(N), VT, 4364 Op, DAG.getConstant(1, VT)); 4365 } 4366 } 4367 4368 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))). 4369 if (N1.getOpcode() == ISD::TRUNCATE && 4370 N1.getOperand(0).getOpcode() == ISD::AND) { 4371 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()); 4372 if (NewOp1.getNode()) 4373 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1); 4374 } 4375 4376 // fold operands of srl based on knowledge that the low bits are not 4377 // demanded. 4378 if (N1C && SimplifyDemandedBits(SDValue(N, 0))) 4379 return SDValue(N, 0); 4380 4381 if (N1C) { 4382 SDValue NewSRL = visitShiftByConstant(N, N1C); 4383 if (NewSRL.getNode()) 4384 return NewSRL; 4385 } 4386 4387 // Attempt to convert a srl of a load into a narrower zero-extending load. 4388 SDValue NarrowLoad = ReduceLoadWidth(N); 4389 if (NarrowLoad.getNode()) 4390 return NarrowLoad; 4391 4392 // Here is a common situation. We want to optimize: 4393 // 4394 // %a = ... 4395 // %b = and i32 %a, 2 4396 // %c = srl i32 %b, 1 4397 // brcond i32 %c ... 4398 // 4399 // into 4400 // 4401 // %a = ... 4402 // %b = and %a, 2 4403 // %c = setcc eq %b, 0 4404 // brcond %c ... 4405 // 4406 // However when after the source operand of SRL is optimized into AND, the SRL 4407 // itself may not be optimized further. Look for it and add the BRCOND into 4408 // the worklist. 4409 if (N->hasOneUse()) { 4410 SDNode *Use = *N->use_begin(); 4411 if (Use->getOpcode() == ISD::BRCOND) 4412 AddToWorkList(Use); 4413 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) { 4414 // Also look pass the truncate. 4415 Use = *Use->use_begin(); 4416 if (Use->getOpcode() == ISD::BRCOND) 4417 AddToWorkList(Use); 4418 } 4419 } 4420 4421 return SDValue(); 4422 } 4423 4424 SDValue DAGCombiner::visitCTLZ(SDNode *N) { 4425 SDValue N0 = N->getOperand(0); 4426 EVT VT = N->getValueType(0); 4427 4428 // fold (ctlz c1) -> c2 4429 if (isa<ConstantSDNode>(N0)) 4430 return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0); 4431 return SDValue(); 4432 } 4433 4434 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) { 4435 SDValue N0 = N->getOperand(0); 4436 EVT VT = N->getValueType(0); 4437 4438 // fold (ctlz_zero_undef c1) -> c2 4439 if (isa<ConstantSDNode>(N0)) 4440 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0); 4441 return SDValue(); 4442 } 4443 4444 SDValue DAGCombiner::visitCTTZ(SDNode *N) { 4445 SDValue N0 = N->getOperand(0); 4446 EVT VT = N->getValueType(0); 4447 4448 // fold (cttz c1) -> c2 4449 if (isa<ConstantSDNode>(N0)) 4450 return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0); 4451 return SDValue(); 4452 } 4453 4454 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) { 4455 SDValue N0 = N->getOperand(0); 4456 EVT VT = N->getValueType(0); 4457 4458 // fold (cttz_zero_undef c1) -> c2 4459 if (isa<ConstantSDNode>(N0)) 4460 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0); 4461 return SDValue(); 4462 } 4463 4464 SDValue DAGCombiner::visitCTPOP(SDNode *N) { 4465 SDValue N0 = N->getOperand(0); 4466 EVT VT = N->getValueType(0); 4467 4468 // fold (ctpop c1) -> c2 4469 if (isa<ConstantSDNode>(N0)) 4470 return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0); 4471 return SDValue(); 4472 } 4473 4474 SDValue DAGCombiner::visitSELECT(SDNode *N) { 4475 SDValue N0 = N->getOperand(0); 4476 SDValue N1 = N->getOperand(1); 4477 SDValue N2 = N->getOperand(2); 4478 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 4479 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 4480 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2); 4481 EVT VT = N->getValueType(0); 4482 EVT VT0 = N0.getValueType(); 4483 4484 // fold (select C, X, X) -> X 4485 if (N1 == N2) 4486 return N1; 4487 // fold (select true, X, Y) -> X 4488 if (N0C && !N0C->isNullValue()) 4489 return N1; 4490 // fold (select false, X, Y) -> Y 4491 if (N0C && N0C->isNullValue()) 4492 return N2; 4493 // fold (select C, 1, X) -> (or C, X) 4494 if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1) 4495 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2); 4496 // fold (select C, 0, 1) -> (xor C, 1) 4497 if (VT.isInteger() && 4498 (VT0 == MVT::i1 || 4499 (VT0.isInteger() && 4500 TLI.getBooleanContents(false) == 4501 TargetLowering::ZeroOrOneBooleanContent)) && 4502 N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) { 4503 SDValue XORNode; 4504 if (VT == VT0) 4505 return DAG.getNode(ISD::XOR, SDLoc(N), VT0, 4506 N0, DAG.getConstant(1, VT0)); 4507 XORNode = DAG.getNode(ISD::XOR, SDLoc(N0), VT0, 4508 N0, DAG.getConstant(1, VT0)); 4509 AddToWorkList(XORNode.getNode()); 4510 if (VT.bitsGT(VT0)) 4511 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode); 4512 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode); 4513 } 4514 // fold (select C, 0, X) -> (and (not C), X) 4515 if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) { 4516 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT); 4517 AddToWorkList(NOTNode.getNode()); 4518 return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2); 4519 } 4520 // fold (select C, X, 1) -> (or (not C), X) 4521 if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) { 4522 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT); 4523 AddToWorkList(NOTNode.getNode()); 4524 return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1); 4525 } 4526 // fold (select C, X, 0) -> (and C, X) 4527 if (VT == MVT::i1 && N2C && N2C->isNullValue()) 4528 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1); 4529 // fold (select X, X, Y) -> (or X, Y) 4530 // fold (select X, 1, Y) -> (or X, Y) 4531 if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1))) 4532 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2); 4533 // fold (select X, Y, X) -> (and X, Y) 4534 // fold (select X, Y, 0) -> (and X, Y) 4535 if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0))) 4536 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1); 4537 4538 // If we can fold this based on the true/false value, do so. 4539 if (SimplifySelectOps(N, N1, N2)) 4540 return SDValue(N, 0); // Don't revisit N. 4541 4542 // fold selects based on a setcc into other things, such as min/max/abs 4543 if (N0.getOpcode() == ISD::SETCC) { 4544 // FIXME: 4545 // Check against MVT::Other for SELECT_CC, which is a workaround for targets 4546 // having to say they don't support SELECT_CC on every type the DAG knows 4547 // about, since there is no way to mark an opcode illegal at all value types 4548 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other) && 4549 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) 4550 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, 4551 N0.getOperand(0), N0.getOperand(1), 4552 N1, N2, N0.getOperand(2)); 4553 return SimplifySelect(SDLoc(N), N0, N1, N2); 4554 } 4555 4556 return SDValue(); 4557 } 4558 4559 static 4560 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) { 4561 SDLoc DL(N); 4562 EVT LoVT, HiVT; 4563 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0)); 4564 4565 // Split the inputs. 4566 SDValue Lo, Hi, LL, LH, RL, RH; 4567 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0); 4568 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1); 4569 4570 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2)); 4571 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2)); 4572 4573 return std::make_pair(Lo, Hi); 4574 } 4575 4576 SDValue DAGCombiner::visitVSELECT(SDNode *N) { 4577 SDValue N0 = N->getOperand(0); 4578 SDValue N1 = N->getOperand(1); 4579 SDValue N2 = N->getOperand(2); 4580 SDLoc DL(N); 4581 4582 // Canonicalize integer abs. 4583 // vselect (setg[te] X, 0), X, -X -> 4584 // vselect (setgt X, -1), X, -X -> 4585 // vselect (setl[te] X, 0), -X, X -> 4586 // Y = sra (X, size(X)-1); xor (add (X, Y), Y) 4587 if (N0.getOpcode() == ISD::SETCC) { 4588 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1); 4589 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get(); 4590 bool isAbs = false; 4591 bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode()); 4592 4593 if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) || 4594 (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) && 4595 N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1)) 4596 isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode()); 4597 else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) && 4598 N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1)) 4599 isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode()); 4600 4601 if (isAbs) { 4602 EVT VT = LHS.getValueType(); 4603 SDValue Shift = DAG.getNode( 4604 ISD::SRA, DL, VT, LHS, 4605 DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, VT)); 4606 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift); 4607 AddToWorkList(Shift.getNode()); 4608 AddToWorkList(Add.getNode()); 4609 return DAG.getNode(ISD::XOR, DL, VT, Add, Shift); 4610 } 4611 } 4612 4613 // If the VSELECT result requires splitting and the mask is provided by a 4614 // SETCC, then split both nodes and its operands before legalization. This 4615 // prevents the type legalizer from unrolling SETCC into scalar comparisons 4616 // and enables future optimizations (e.g. min/max pattern matching on X86). 4617 if (N0.getOpcode() == ISD::SETCC) { 4618 EVT VT = N->getValueType(0); 4619 4620 // Check if any splitting is required. 4621 if (TLI.getTypeAction(*DAG.getContext(), VT) != 4622 TargetLowering::TypeSplitVector) 4623 return SDValue(); 4624 4625 SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH; 4626 std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG); 4627 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1); 4628 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2); 4629 4630 Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL); 4631 Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH); 4632 4633 // Add the new VSELECT nodes to the work list in case they need to be split 4634 // again. 4635 AddToWorkList(Lo.getNode()); 4636 AddToWorkList(Hi.getNode()); 4637 4638 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi); 4639 } 4640 4641 // Fold (vselect (build_vector all_ones), N1, N2) -> N1 4642 if (ISD::isBuildVectorAllOnes(N0.getNode())) 4643 return N1; 4644 // Fold (vselect (build_vector all_zeros), N1, N2) -> N2 4645 if (ISD::isBuildVectorAllZeros(N0.getNode())) 4646 return N2; 4647 4648 return SDValue(); 4649 } 4650 4651 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) { 4652 SDValue N0 = N->getOperand(0); 4653 SDValue N1 = N->getOperand(1); 4654 SDValue N2 = N->getOperand(2); 4655 SDValue N3 = N->getOperand(3); 4656 SDValue N4 = N->getOperand(4); 4657 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get(); 4658 4659 // fold select_cc lhs, rhs, x, x, cc -> x 4660 if (N2 == N3) 4661 return N2; 4662 4663 // Determine if the condition we're dealing with is constant 4664 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()), 4665 N0, N1, CC, SDLoc(N), false); 4666 if (SCC.getNode()) { 4667 AddToWorkList(SCC.getNode()); 4668 4669 if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) { 4670 if (!SCCC->isNullValue()) 4671 return N2; // cond always true -> true val 4672 else 4673 return N3; // cond always false -> false val 4674 } 4675 4676 // Fold to a simpler select_cc 4677 if (SCC.getOpcode() == ISD::SETCC) 4678 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(), 4679 SCC.getOperand(0), SCC.getOperand(1), N2, N3, 4680 SCC.getOperand(2)); 4681 } 4682 4683 // If we can fold this based on the true/false value, do so. 4684 if (SimplifySelectOps(N, N2, N3)) 4685 return SDValue(N, 0); // Don't revisit N. 4686 4687 // fold select_cc into other things, such as min/max/abs 4688 return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC); 4689 } 4690 4691 SDValue DAGCombiner::visitSETCC(SDNode *N) { 4692 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1), 4693 cast<CondCodeSDNode>(N->getOperand(2))->get(), 4694 SDLoc(N)); 4695 } 4696 4697 // tryToFoldExtendOfConstant - Try to fold a sext/zext/aext 4698 // dag node into a ConstantSDNode or a build_vector of constants. 4699 // This function is called by the DAGCombiner when visiting sext/zext/aext 4700 // dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND). 4701 // Vector extends are not folded if operations are legal; this is to 4702 // avoid introducing illegal build_vector dag nodes. 4703 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI, 4704 SelectionDAG &DAG, bool LegalTypes, 4705 bool LegalOperations) { 4706 unsigned Opcode = N->getOpcode(); 4707 SDValue N0 = N->getOperand(0); 4708 EVT VT = N->getValueType(0); 4709 4710 assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND || 4711 Opcode == ISD::ANY_EXTEND) && "Expected EXTEND dag node in input!"); 4712 4713 // fold (sext c1) -> c1 4714 // fold (zext c1) -> c1 4715 // fold (aext c1) -> c1 4716 if (isa<ConstantSDNode>(N0)) 4717 return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode(); 4718 4719 // fold (sext (build_vector AllConstants) -> (build_vector AllConstants) 4720 // fold (zext (build_vector AllConstants) -> (build_vector AllConstants) 4721 // fold (aext (build_vector AllConstants) -> (build_vector AllConstants) 4722 EVT SVT = VT.getScalarType(); 4723 if (!(VT.isVector() && 4724 (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) && 4725 ISD::isBuildVectorOfConstantSDNodes(N0.getNode()))) 4726 return nullptr; 4727 4728 // We can fold this node into a build_vector. 4729 unsigned VTBits = SVT.getSizeInBits(); 4730 unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits(); 4731 unsigned ShAmt = VTBits - EVTBits; 4732 SmallVector<SDValue, 8> Elts; 4733 unsigned NumElts = N0->getNumOperands(); 4734 SDLoc DL(N); 4735 4736 for (unsigned i=0; i != NumElts; ++i) { 4737 SDValue Op = N0->getOperand(i); 4738 if (Op->getOpcode() == ISD::UNDEF) { 4739 Elts.push_back(DAG.getUNDEF(SVT)); 4740 continue; 4741 } 4742 4743 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op); 4744 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue()); 4745 if (Opcode == ISD::SIGN_EXTEND) 4746 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(), 4747 SVT)); 4748 else 4749 Elts.push_back(DAG.getConstant(C.shl(ShAmt).lshr(ShAmt).getZExtValue(), 4750 SVT)); 4751 } 4752 4753 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, &Elts[0], NumElts).getNode(); 4754 } 4755 4756 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this: 4757 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))" 4758 // transformation. Returns true if extension are possible and the above 4759 // mentioned transformation is profitable. 4760 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0, 4761 unsigned ExtOpc, 4762 SmallVectorImpl<SDNode *> &ExtendNodes, 4763 const TargetLowering &TLI) { 4764 bool HasCopyToRegUses = false; 4765 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType()); 4766 for (SDNode::use_iterator UI = N0.getNode()->use_begin(), 4767 UE = N0.getNode()->use_end(); 4768 UI != UE; ++UI) { 4769 SDNode *User = *UI; 4770 if (User == N) 4771 continue; 4772 if (UI.getUse().getResNo() != N0.getResNo()) 4773 continue; 4774 // FIXME: Only extend SETCC N, N and SETCC N, c for now. 4775 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) { 4776 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get(); 4777 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC)) 4778 // Sign bits will be lost after a zext. 4779 return false; 4780 bool Add = false; 4781 for (unsigned i = 0; i != 2; ++i) { 4782 SDValue UseOp = User->getOperand(i); 4783 if (UseOp == N0) 4784 continue; 4785 if (!isa<ConstantSDNode>(UseOp)) 4786 return false; 4787 Add = true; 4788 } 4789 if (Add) 4790 ExtendNodes.push_back(User); 4791 continue; 4792 } 4793 // If truncates aren't free and there are users we can't 4794 // extend, it isn't worthwhile. 4795 if (!isTruncFree) 4796 return false; 4797 // Remember if this value is live-out. 4798 if (User->getOpcode() == ISD::CopyToReg) 4799 HasCopyToRegUses = true; 4800 } 4801 4802 if (HasCopyToRegUses) { 4803 bool BothLiveOut = false; 4804 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end(); 4805 UI != UE; ++UI) { 4806 SDUse &Use = UI.getUse(); 4807 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) { 4808 BothLiveOut = true; 4809 break; 4810 } 4811 } 4812 if (BothLiveOut) 4813 // Both unextended and extended values are live out. There had better be 4814 // a good reason for the transformation. 4815 return ExtendNodes.size(); 4816 } 4817 return true; 4818 } 4819 4820 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs, 4821 SDValue Trunc, SDValue ExtLoad, SDLoc DL, 4822 ISD::NodeType ExtType) { 4823 // Extend SetCC uses if necessary. 4824 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) { 4825 SDNode *SetCC = SetCCs[i]; 4826 SmallVector<SDValue, 4> Ops; 4827 4828 for (unsigned j = 0; j != 2; ++j) { 4829 SDValue SOp = SetCC->getOperand(j); 4830 if (SOp == Trunc) 4831 Ops.push_back(ExtLoad); 4832 else 4833 Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp)); 4834 } 4835 4836 Ops.push_back(SetCC->getOperand(2)); 4837 CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), 4838 &Ops[0], Ops.size())); 4839 } 4840 } 4841 4842 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) { 4843 SDValue N0 = N->getOperand(0); 4844 EVT VT = N->getValueType(0); 4845 4846 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes, 4847 LegalOperations)) 4848 return SDValue(Res, 0); 4849 4850 // fold (sext (sext x)) -> (sext x) 4851 // fold (sext (aext x)) -> (sext x) 4852 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) 4853 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, 4854 N0.getOperand(0)); 4855 4856 if (N0.getOpcode() == ISD::TRUNCATE) { 4857 // fold (sext (truncate (load x))) -> (sext (smaller load x)) 4858 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n))) 4859 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode()); 4860 if (NarrowLoad.getNode()) { 4861 SDNode* oye = N0.getNode()->getOperand(0).getNode(); 4862 if (NarrowLoad.getNode() != N0.getNode()) { 4863 CombineTo(N0.getNode(), NarrowLoad); 4864 // CombineTo deleted the truncate, if needed, but not what's under it. 4865 AddToWorkList(oye); 4866 } 4867 return SDValue(N, 0); // Return N so it doesn't get rechecked! 4868 } 4869 4870 // See if the value being truncated is already sign extended. If so, just 4871 // eliminate the trunc/sext pair. 4872 SDValue Op = N0.getOperand(0); 4873 unsigned OpBits = Op.getValueType().getScalarType().getSizeInBits(); 4874 unsigned MidBits = N0.getValueType().getScalarType().getSizeInBits(); 4875 unsigned DestBits = VT.getScalarType().getSizeInBits(); 4876 unsigned NumSignBits = DAG.ComputeNumSignBits(Op); 4877 4878 if (OpBits == DestBits) { 4879 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign 4880 // bits, it is already ready. 4881 if (NumSignBits > DestBits-MidBits) 4882 return Op; 4883 } else if (OpBits < DestBits) { 4884 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign 4885 // bits, just sext from i32. 4886 if (NumSignBits > OpBits-MidBits) 4887 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op); 4888 } else { 4889 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign 4890 // bits, just truncate to i32. 4891 if (NumSignBits > OpBits-MidBits) 4892 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op); 4893 } 4894 4895 // fold (sext (truncate x)) -> (sextinreg x). 4896 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, 4897 N0.getValueType())) { 4898 if (OpBits < DestBits) 4899 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op); 4900 else if (OpBits > DestBits) 4901 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op); 4902 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op, 4903 DAG.getValueType(N0.getValueType())); 4904 } 4905 } 4906 4907 // fold (sext (load x)) -> (sext (truncate (sextload x))) 4908 // None of the supported targets knows how to perform load and sign extend 4909 // on vectors in one instruction. We only perform this transformation on 4910 // scalars. 4911 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() && 4912 ISD::isUNINDEXEDLoad(N0.getNode()) && 4913 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) || 4914 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()))) { 4915 bool DoXform = true; 4916 SmallVector<SDNode*, 4> SetCCs; 4917 if (!N0.hasOneUse()) 4918 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI); 4919 if (DoXform) { 4920 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 4921 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT, 4922 LN0->getChain(), 4923 LN0->getBasePtr(), N0.getValueType(), 4924 LN0->getMemOperand()); 4925 CombineTo(N, ExtLoad); 4926 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 4927 N0.getValueType(), ExtLoad); 4928 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1)); 4929 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N), 4930 ISD::SIGN_EXTEND); 4931 return SDValue(N, 0); // Return N so it doesn't get rechecked! 4932 } 4933 } 4934 4935 // fold (sext (sextload x)) -> (sext (truncate (sextload x))) 4936 // fold (sext ( extload x)) -> (sext (truncate (sextload x))) 4937 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) && 4938 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) { 4939 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 4940 EVT MemVT = LN0->getMemoryVT(); 4941 if ((!LegalOperations && !LN0->isVolatile()) || 4942 TLI.isLoadExtLegal(ISD::SEXTLOAD, MemVT)) { 4943 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT, 4944 LN0->getChain(), 4945 LN0->getBasePtr(), MemVT, 4946 LN0->getMemOperand()); 4947 CombineTo(N, ExtLoad); 4948 CombineTo(N0.getNode(), 4949 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 4950 N0.getValueType(), ExtLoad), 4951 ExtLoad.getValue(1)); 4952 return SDValue(N, 0); // Return N so it doesn't get rechecked! 4953 } 4954 } 4955 4956 // fold (sext (and/or/xor (load x), cst)) -> 4957 // (and/or/xor (sextload x), (sext cst)) 4958 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR || 4959 N0.getOpcode() == ISD::XOR) && 4960 isa<LoadSDNode>(N0.getOperand(0)) && 4961 N0.getOperand(1).getOpcode() == ISD::Constant && 4962 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()) && 4963 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) { 4964 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0)); 4965 if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) { 4966 bool DoXform = true; 4967 SmallVector<SDNode*, 4> SetCCs; 4968 if (!N0.hasOneUse()) 4969 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND, 4970 SetCCs, TLI); 4971 if (DoXform) { 4972 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT, 4973 LN0->getChain(), LN0->getBasePtr(), 4974 LN0->getMemoryVT(), 4975 LN0->getMemOperand()); 4976 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 4977 Mask = Mask.sext(VT.getSizeInBits()); 4978 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT, 4979 ExtLoad, DAG.getConstant(Mask, VT)); 4980 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, 4981 SDLoc(N0.getOperand(0)), 4982 N0.getOperand(0).getValueType(), ExtLoad); 4983 CombineTo(N, And); 4984 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1)); 4985 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N), 4986 ISD::SIGN_EXTEND); 4987 return SDValue(N, 0); // Return N so it doesn't get rechecked! 4988 } 4989 } 4990 } 4991 4992 if (N0.getOpcode() == ISD::SETCC) { 4993 // sext(setcc) -> sext_in_reg(vsetcc) for vectors. 4994 // Only do this before legalize for now. 4995 if (VT.isVector() && !LegalOperations && 4996 TLI.getBooleanContents(true) == 4997 TargetLowering::ZeroOrNegativeOneBooleanContent) { 4998 EVT N0VT = N0.getOperand(0).getValueType(); 4999 // On some architectures (such as SSE/NEON/etc) the SETCC result type is 5000 // of the same size as the compared operands. Only optimize sext(setcc()) 5001 // if this is the case. 5002 EVT SVT = getSetCCResultType(N0VT); 5003 5004 // We know that the # elements of the results is the same as the 5005 // # elements of the compare (and the # elements of the compare result 5006 // for that matter). Check to see that they are the same size. If so, 5007 // we know that the element size of the sext'd result matches the 5008 // element size of the compare operands. 5009 if (VT.getSizeInBits() == SVT.getSizeInBits()) 5010 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0), 5011 N0.getOperand(1), 5012 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 5013 5014 // If the desired elements are smaller or larger than the source 5015 // elements we can use a matching integer vector type and then 5016 // truncate/sign extend 5017 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger(); 5018 if (SVT == MatchingVectorType) { 5019 SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType, 5020 N0.getOperand(0), N0.getOperand(1), 5021 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 5022 return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT); 5023 } 5024 } 5025 5026 // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0) 5027 unsigned ElementWidth = VT.getScalarType().getSizeInBits(); 5028 SDValue NegOne = 5029 DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT); 5030 SDValue SCC = 5031 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1), 5032 NegOne, DAG.getConstant(0, VT), 5033 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true); 5034 if (SCC.getNode()) return SCC; 5035 5036 if (!VT.isVector()) { 5037 EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType()); 5038 if (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, SetCCVT)) { 5039 SDLoc DL(N); 5040 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get(); 5041 SDValue SetCC = DAG.getSetCC(DL, 5042 SetCCVT, 5043 N0.getOperand(0), N0.getOperand(1), CC); 5044 EVT SelectVT = getSetCCResultType(VT); 5045 return DAG.getSelect(DL, VT, 5046 DAG.getSExtOrTrunc(SetCC, DL, SelectVT), 5047 NegOne, DAG.getConstant(0, VT)); 5048 5049 } 5050 } 5051 } 5052 5053 // fold (sext x) -> (zext x) if the sign bit is known zero. 5054 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) && 5055 DAG.SignBitIsZero(N0)) 5056 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0); 5057 5058 return SDValue(); 5059 } 5060 5061 // isTruncateOf - If N is a truncate of some other value, return true, record 5062 // the value being truncated in Op and which of Op's bits are zero in KnownZero. 5063 // This function computes KnownZero to avoid a duplicated call to 5064 // ComputeMaskedBits in the caller. 5065 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op, 5066 APInt &KnownZero) { 5067 APInt KnownOne; 5068 if (N->getOpcode() == ISD::TRUNCATE) { 5069 Op = N->getOperand(0); 5070 DAG.ComputeMaskedBits(Op, KnownZero, KnownOne); 5071 return true; 5072 } 5073 5074 if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 || 5075 cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE) 5076 return false; 5077 5078 SDValue Op0 = N->getOperand(0); 5079 SDValue Op1 = N->getOperand(1); 5080 assert(Op0.getValueType() == Op1.getValueType()); 5081 5082 ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0); 5083 ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1); 5084 if (COp0 && COp0->isNullValue()) 5085 Op = Op1; 5086 else if (COp1 && COp1->isNullValue()) 5087 Op = Op0; 5088 else 5089 return false; 5090 5091 DAG.ComputeMaskedBits(Op, KnownZero, KnownOne); 5092 5093 if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue()) 5094 return false; 5095 5096 return true; 5097 } 5098 5099 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) { 5100 SDValue N0 = N->getOperand(0); 5101 EVT VT = N->getValueType(0); 5102 5103 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes, 5104 LegalOperations)) 5105 return SDValue(Res, 0); 5106 5107 // fold (zext (zext x)) -> (zext x) 5108 // fold (zext (aext x)) -> (zext x) 5109 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) 5110 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, 5111 N0.getOperand(0)); 5112 5113 // fold (zext (truncate x)) -> (zext x) or 5114 // (zext (truncate x)) -> (truncate x) 5115 // This is valid when the truncated bits of x are already zero. 5116 // FIXME: We should extend this to work for vectors too. 5117 SDValue Op; 5118 APInt KnownZero; 5119 if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) { 5120 APInt TruncatedBits = 5121 (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ? 5122 APInt(Op.getValueSizeInBits(), 0) : 5123 APInt::getBitsSet(Op.getValueSizeInBits(), 5124 N0.getValueSizeInBits(), 5125 std::min(Op.getValueSizeInBits(), 5126 VT.getSizeInBits())); 5127 if (TruncatedBits == (KnownZero & TruncatedBits)) { 5128 if (VT.bitsGT(Op.getValueType())) 5129 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op); 5130 if (VT.bitsLT(Op.getValueType())) 5131 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op); 5132 5133 return Op; 5134 } 5135 } 5136 5137 // fold (zext (truncate (load x))) -> (zext (smaller load x)) 5138 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n))) 5139 if (N0.getOpcode() == ISD::TRUNCATE) { 5140 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode()); 5141 if (NarrowLoad.getNode()) { 5142 SDNode* oye = N0.getNode()->getOperand(0).getNode(); 5143 if (NarrowLoad.getNode() != N0.getNode()) { 5144 CombineTo(N0.getNode(), NarrowLoad); 5145 // CombineTo deleted the truncate, if needed, but not what's under it. 5146 AddToWorkList(oye); 5147 } 5148 return SDValue(N, 0); // Return N so it doesn't get rechecked! 5149 } 5150 } 5151 5152 // fold (zext (truncate x)) -> (and x, mask) 5153 if (N0.getOpcode() == ISD::TRUNCATE && 5154 (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) { 5155 5156 // fold (zext (truncate (load x))) -> (zext (smaller load x)) 5157 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n))) 5158 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode()); 5159 if (NarrowLoad.getNode()) { 5160 SDNode* oye = N0.getNode()->getOperand(0).getNode(); 5161 if (NarrowLoad.getNode() != N0.getNode()) { 5162 CombineTo(N0.getNode(), NarrowLoad); 5163 // CombineTo deleted the truncate, if needed, but not what's under it. 5164 AddToWorkList(oye); 5165 } 5166 return SDValue(N, 0); // Return N so it doesn't get rechecked! 5167 } 5168 5169 SDValue Op = N0.getOperand(0); 5170 if (Op.getValueType().bitsLT(VT)) { 5171 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op); 5172 AddToWorkList(Op.getNode()); 5173 } else if (Op.getValueType().bitsGT(VT)) { 5174 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op); 5175 AddToWorkList(Op.getNode()); 5176 } 5177 return DAG.getZeroExtendInReg(Op, SDLoc(N), 5178 N0.getValueType().getScalarType()); 5179 } 5180 5181 // Fold (zext (and (trunc x), cst)) -> (and x, cst), 5182 // if either of the casts is not free. 5183 if (N0.getOpcode() == ISD::AND && 5184 N0.getOperand(0).getOpcode() == ISD::TRUNCATE && 5185 N0.getOperand(1).getOpcode() == ISD::Constant && 5186 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(), 5187 N0.getValueType()) || 5188 !TLI.isZExtFree(N0.getValueType(), VT))) { 5189 SDValue X = N0.getOperand(0).getOperand(0); 5190 if (X.getValueType().bitsLT(VT)) { 5191 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X); 5192 } else if (X.getValueType().bitsGT(VT)) { 5193 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X); 5194 } 5195 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 5196 Mask = Mask.zext(VT.getSizeInBits()); 5197 return DAG.getNode(ISD::AND, SDLoc(N), VT, 5198 X, DAG.getConstant(Mask, VT)); 5199 } 5200 5201 // fold (zext (load x)) -> (zext (truncate (zextload x))) 5202 // None of the supported targets knows how to perform load and vector_zext 5203 // on vectors in one instruction. We only perform this transformation on 5204 // scalars. 5205 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() && 5206 ISD::isUNINDEXEDLoad(N0.getNode()) && 5207 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) || 5208 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()))) { 5209 bool DoXform = true; 5210 SmallVector<SDNode*, 4> SetCCs; 5211 if (!N0.hasOneUse()) 5212 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI); 5213 if (DoXform) { 5214 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 5215 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT, 5216 LN0->getChain(), 5217 LN0->getBasePtr(), N0.getValueType(), 5218 LN0->getMemOperand()); 5219 CombineTo(N, ExtLoad); 5220 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 5221 N0.getValueType(), ExtLoad); 5222 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1)); 5223 5224 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N), 5225 ISD::ZERO_EXTEND); 5226 return SDValue(N, 0); // Return N so it doesn't get rechecked! 5227 } 5228 } 5229 5230 // fold (zext (and/or/xor (load x), cst)) -> 5231 // (and/or/xor (zextload x), (zext cst)) 5232 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR || 5233 N0.getOpcode() == ISD::XOR) && 5234 isa<LoadSDNode>(N0.getOperand(0)) && 5235 N0.getOperand(1).getOpcode() == ISD::Constant && 5236 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()) && 5237 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) { 5238 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0)); 5239 if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) { 5240 bool DoXform = true; 5241 SmallVector<SDNode*, 4> SetCCs; 5242 if (!N0.hasOneUse()) 5243 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND, 5244 SetCCs, TLI); 5245 if (DoXform) { 5246 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT, 5247 LN0->getChain(), LN0->getBasePtr(), 5248 LN0->getMemoryVT(), 5249 LN0->getMemOperand()); 5250 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 5251 Mask = Mask.zext(VT.getSizeInBits()); 5252 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT, 5253 ExtLoad, DAG.getConstant(Mask, VT)); 5254 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, 5255 SDLoc(N0.getOperand(0)), 5256 N0.getOperand(0).getValueType(), ExtLoad); 5257 CombineTo(N, And); 5258 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1)); 5259 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N), 5260 ISD::ZERO_EXTEND); 5261 return SDValue(N, 0); // Return N so it doesn't get rechecked! 5262 } 5263 } 5264 } 5265 5266 // fold (zext (zextload x)) -> (zext (truncate (zextload x))) 5267 // fold (zext ( extload x)) -> (zext (truncate (zextload x))) 5268 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) && 5269 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) { 5270 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 5271 EVT MemVT = LN0->getMemoryVT(); 5272 if ((!LegalOperations && !LN0->isVolatile()) || 5273 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT)) { 5274 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT, 5275 LN0->getChain(), 5276 LN0->getBasePtr(), MemVT, 5277 LN0->getMemOperand()); 5278 CombineTo(N, ExtLoad); 5279 CombineTo(N0.getNode(), 5280 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), 5281 ExtLoad), 5282 ExtLoad.getValue(1)); 5283 return SDValue(N, 0); // Return N so it doesn't get rechecked! 5284 } 5285 } 5286 5287 if (N0.getOpcode() == ISD::SETCC) { 5288 if (!LegalOperations && VT.isVector() && 5289 N0.getValueType().getVectorElementType() == MVT::i1) { 5290 EVT N0VT = N0.getOperand(0).getValueType(); 5291 if (getSetCCResultType(N0VT) == N0.getValueType()) 5292 return SDValue(); 5293 5294 // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors. 5295 // Only do this before legalize for now. 5296 EVT EltVT = VT.getVectorElementType(); 5297 SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(), 5298 DAG.getConstant(1, EltVT)); 5299 if (VT.getSizeInBits() == N0VT.getSizeInBits()) 5300 // We know that the # elements of the results is the same as the 5301 // # elements of the compare (and the # elements of the compare result 5302 // for that matter). Check to see that they are the same size. If so, 5303 // we know that the element size of the sext'd result matches the 5304 // element size of the compare operands. 5305 return DAG.getNode(ISD::AND, SDLoc(N), VT, 5306 DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0), 5307 N0.getOperand(1), 5308 cast<CondCodeSDNode>(N0.getOperand(2))->get()), 5309 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, 5310 &OneOps[0], OneOps.size())); 5311 5312 // If the desired elements are smaller or larger than the source 5313 // elements we can use a matching integer vector type and then 5314 // truncate/sign extend 5315 EVT MatchingElementType = 5316 EVT::getIntegerVT(*DAG.getContext(), 5317 N0VT.getScalarType().getSizeInBits()); 5318 EVT MatchingVectorType = 5319 EVT::getVectorVT(*DAG.getContext(), MatchingElementType, 5320 N0VT.getVectorNumElements()); 5321 SDValue VsetCC = 5322 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0), 5323 N0.getOperand(1), 5324 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 5325 return DAG.getNode(ISD::AND, SDLoc(N), VT, 5326 DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT), 5327 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, 5328 &OneOps[0], OneOps.size())); 5329 } 5330 5331 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc 5332 SDValue SCC = 5333 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1), 5334 DAG.getConstant(1, VT), DAG.getConstant(0, VT), 5335 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true); 5336 if (SCC.getNode()) return SCC; 5337 } 5338 5339 // (zext (shl (zext x), cst)) -> (shl (zext x), cst) 5340 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) && 5341 isa<ConstantSDNode>(N0.getOperand(1)) && 5342 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND && 5343 N0.hasOneUse()) { 5344 SDValue ShAmt = N0.getOperand(1); 5345 unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue(); 5346 if (N0.getOpcode() == ISD::SHL) { 5347 SDValue InnerZExt = N0.getOperand(0); 5348 // If the original shl may be shifting out bits, do not perform this 5349 // transformation. 5350 unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() - 5351 InnerZExt.getOperand(0).getValueType().getSizeInBits(); 5352 if (ShAmtVal > KnownZeroBits) 5353 return SDValue(); 5354 } 5355 5356 SDLoc DL(N); 5357 5358 // Ensure that the shift amount is wide enough for the shifted value. 5359 if (VT.getSizeInBits() >= 256) 5360 ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt); 5361 5362 return DAG.getNode(N0.getOpcode(), DL, VT, 5363 DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)), 5364 ShAmt); 5365 } 5366 5367 return SDValue(); 5368 } 5369 5370 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) { 5371 SDValue N0 = N->getOperand(0); 5372 EVT VT = N->getValueType(0); 5373 5374 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes, 5375 LegalOperations)) 5376 return SDValue(Res, 0); 5377 5378 // fold (aext (aext x)) -> (aext x) 5379 // fold (aext (zext x)) -> (zext x) 5380 // fold (aext (sext x)) -> (sext x) 5381 if (N0.getOpcode() == ISD::ANY_EXTEND || 5382 N0.getOpcode() == ISD::ZERO_EXTEND || 5383 N0.getOpcode() == ISD::SIGN_EXTEND) 5384 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0)); 5385 5386 // fold (aext (truncate (load x))) -> (aext (smaller load x)) 5387 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n))) 5388 if (N0.getOpcode() == ISD::TRUNCATE) { 5389 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode()); 5390 if (NarrowLoad.getNode()) { 5391 SDNode* oye = N0.getNode()->getOperand(0).getNode(); 5392 if (NarrowLoad.getNode() != N0.getNode()) { 5393 CombineTo(N0.getNode(), NarrowLoad); 5394 // CombineTo deleted the truncate, if needed, but not what's under it. 5395 AddToWorkList(oye); 5396 } 5397 return SDValue(N, 0); // Return N so it doesn't get rechecked! 5398 } 5399 } 5400 5401 // fold (aext (truncate x)) 5402 if (N0.getOpcode() == ISD::TRUNCATE) { 5403 SDValue TruncOp = N0.getOperand(0); 5404 if (TruncOp.getValueType() == VT) 5405 return TruncOp; // x iff x size == zext size. 5406 if (TruncOp.getValueType().bitsGT(VT)) 5407 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp); 5408 return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp); 5409 } 5410 5411 // Fold (aext (and (trunc x), cst)) -> (and x, cst) 5412 // if the trunc is not free. 5413 if (N0.getOpcode() == ISD::AND && 5414 N0.getOperand(0).getOpcode() == ISD::TRUNCATE && 5415 N0.getOperand(1).getOpcode() == ISD::Constant && 5416 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(), 5417 N0.getValueType())) { 5418 SDValue X = N0.getOperand(0).getOperand(0); 5419 if (X.getValueType().bitsLT(VT)) { 5420 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X); 5421 } else if (X.getValueType().bitsGT(VT)) { 5422 X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X); 5423 } 5424 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 5425 Mask = Mask.zext(VT.getSizeInBits()); 5426 return DAG.getNode(ISD::AND, SDLoc(N), VT, 5427 X, DAG.getConstant(Mask, VT)); 5428 } 5429 5430 // fold (aext (load x)) -> (aext (truncate (extload x))) 5431 // None of the supported targets knows how to perform load and any_ext 5432 // on vectors in one instruction. We only perform this transformation on 5433 // scalars. 5434 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() && 5435 ISD::isUNINDEXEDLoad(N0.getNode()) && 5436 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) || 5437 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) { 5438 bool DoXform = true; 5439 SmallVector<SDNode*, 4> SetCCs; 5440 if (!N0.hasOneUse()) 5441 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI); 5442 if (DoXform) { 5443 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 5444 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT, 5445 LN0->getChain(), 5446 LN0->getBasePtr(), N0.getValueType(), 5447 LN0->getMemOperand()); 5448 CombineTo(N, ExtLoad); 5449 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 5450 N0.getValueType(), ExtLoad); 5451 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1)); 5452 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N), 5453 ISD::ANY_EXTEND); 5454 return SDValue(N, 0); // Return N so it doesn't get rechecked! 5455 } 5456 } 5457 5458 // fold (aext (zextload x)) -> (aext (truncate (zextload x))) 5459 // fold (aext (sextload x)) -> (aext (truncate (sextload x))) 5460 // fold (aext ( extload x)) -> (aext (truncate (extload x))) 5461 if (N0.getOpcode() == ISD::LOAD && 5462 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 5463 N0.hasOneUse()) { 5464 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 5465 ISD::LoadExtType ExtType = LN0->getExtensionType(); 5466 EVT MemVT = LN0->getMemoryVT(); 5467 if (!LegalOperations || TLI.isLoadExtLegal(ExtType, MemVT)) { 5468 SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N), 5469 VT, LN0->getChain(), LN0->getBasePtr(), 5470 MemVT, LN0->getMemOperand()); 5471 CombineTo(N, ExtLoad); 5472 CombineTo(N0.getNode(), 5473 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 5474 N0.getValueType(), ExtLoad), 5475 ExtLoad.getValue(1)); 5476 return SDValue(N, 0); // Return N so it doesn't get rechecked! 5477 } 5478 } 5479 5480 if (N0.getOpcode() == ISD::SETCC) { 5481 // aext(setcc) -> sext_in_reg(vsetcc) for vectors. 5482 // Only do this before legalize for now. 5483 if (VT.isVector() && !LegalOperations) { 5484 EVT N0VT = N0.getOperand(0).getValueType(); 5485 // We know that the # elements of the results is the same as the 5486 // # elements of the compare (and the # elements of the compare result 5487 // for that matter). Check to see that they are the same size. If so, 5488 // we know that the element size of the sext'd result matches the 5489 // element size of the compare operands. 5490 if (VT.getSizeInBits() == N0VT.getSizeInBits()) 5491 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0), 5492 N0.getOperand(1), 5493 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 5494 // If the desired elements are smaller or larger than the source 5495 // elements we can use a matching integer vector type and then 5496 // truncate/sign extend 5497 else { 5498 EVT MatchingElementType = 5499 EVT::getIntegerVT(*DAG.getContext(), 5500 N0VT.getScalarType().getSizeInBits()); 5501 EVT MatchingVectorType = 5502 EVT::getVectorVT(*DAG.getContext(), MatchingElementType, 5503 N0VT.getVectorNumElements()); 5504 SDValue VsetCC = 5505 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0), 5506 N0.getOperand(1), 5507 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 5508 return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT); 5509 } 5510 } 5511 5512 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc 5513 SDValue SCC = 5514 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1), 5515 DAG.getConstant(1, VT), DAG.getConstant(0, VT), 5516 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true); 5517 if (SCC.getNode()) 5518 return SCC; 5519 } 5520 5521 return SDValue(); 5522 } 5523 5524 /// GetDemandedBits - See if the specified operand can be simplified with the 5525 /// knowledge that only the bits specified by Mask are used. If so, return the 5526 /// simpler operand, otherwise return a null SDValue. 5527 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) { 5528 switch (V.getOpcode()) { 5529 default: break; 5530 case ISD::Constant: { 5531 const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode()); 5532 assert(CV && "Const value should be ConstSDNode."); 5533 const APInt &CVal = CV->getAPIntValue(); 5534 APInt NewVal = CVal & Mask; 5535 if (NewVal != CVal) 5536 return DAG.getConstant(NewVal, V.getValueType()); 5537 break; 5538 } 5539 case ISD::OR: 5540 case ISD::XOR: 5541 // If the LHS or RHS don't contribute bits to the or, drop them. 5542 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask)) 5543 return V.getOperand(1); 5544 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask)) 5545 return V.getOperand(0); 5546 break; 5547 case ISD::SRL: 5548 // Only look at single-use SRLs. 5549 if (!V.getNode()->hasOneUse()) 5550 break; 5551 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) { 5552 // See if we can recursively simplify the LHS. 5553 unsigned Amt = RHSC->getZExtValue(); 5554 5555 // Watch out for shift count overflow though. 5556 if (Amt >= Mask.getBitWidth()) break; 5557 APInt NewMask = Mask << Amt; 5558 SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask); 5559 if (SimplifyLHS.getNode()) 5560 return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(), 5561 SimplifyLHS, V.getOperand(1)); 5562 } 5563 } 5564 return SDValue(); 5565 } 5566 5567 /// ReduceLoadWidth - If the result of a wider load is shifted to right of N 5568 /// bits and then truncated to a narrower type and where N is a multiple 5569 /// of number of bits of the narrower type, transform it to a narrower load 5570 /// from address + N / num of bits of new type. If the result is to be 5571 /// extended, also fold the extension to form a extending load. 5572 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) { 5573 unsigned Opc = N->getOpcode(); 5574 5575 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD; 5576 SDValue N0 = N->getOperand(0); 5577 EVT VT = N->getValueType(0); 5578 EVT ExtVT = VT; 5579 5580 // This transformation isn't valid for vector loads. 5581 if (VT.isVector()) 5582 return SDValue(); 5583 5584 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then 5585 // extended to VT. 5586 if (Opc == ISD::SIGN_EXTEND_INREG) { 5587 ExtType = ISD::SEXTLOAD; 5588 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT(); 5589 } else if (Opc == ISD::SRL) { 5590 // Another special-case: SRL is basically zero-extending a narrower value. 5591 ExtType = ISD::ZEXTLOAD; 5592 N0 = SDValue(N, 0); 5593 ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 5594 if (!N01) return SDValue(); 5595 ExtVT = EVT::getIntegerVT(*DAG.getContext(), 5596 VT.getSizeInBits() - N01->getZExtValue()); 5597 } 5598 if (LegalOperations && !TLI.isLoadExtLegal(ExtType, ExtVT)) 5599 return SDValue(); 5600 5601 unsigned EVTBits = ExtVT.getSizeInBits(); 5602 5603 // Do not generate loads of non-round integer types since these can 5604 // be expensive (and would be wrong if the type is not byte sized). 5605 if (!ExtVT.isRound()) 5606 return SDValue(); 5607 5608 unsigned ShAmt = 0; 5609 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) { 5610 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 5611 ShAmt = N01->getZExtValue(); 5612 // Is the shift amount a multiple of size of VT? 5613 if ((ShAmt & (EVTBits-1)) == 0) { 5614 N0 = N0.getOperand(0); 5615 // Is the load width a multiple of size of VT? 5616 if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0) 5617 return SDValue(); 5618 } 5619 5620 // At this point, we must have a load or else we can't do the transform. 5621 if (!isa<LoadSDNode>(N0)) return SDValue(); 5622 5623 // Because a SRL must be assumed to *need* to zero-extend the high bits 5624 // (as opposed to anyext the high bits), we can't combine the zextload 5625 // lowering of SRL and an sextload. 5626 if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD) 5627 return SDValue(); 5628 5629 // If the shift amount is larger than the input type then we're not 5630 // accessing any of the loaded bytes. If the load was a zextload/extload 5631 // then the result of the shift+trunc is zero/undef (handled elsewhere). 5632 if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits()) 5633 return SDValue(); 5634 } 5635 } 5636 5637 // If the load is shifted left (and the result isn't shifted back right), 5638 // we can fold the truncate through the shift. 5639 unsigned ShLeftAmt = 0; 5640 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() && 5641 ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) { 5642 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 5643 ShLeftAmt = N01->getZExtValue(); 5644 N0 = N0.getOperand(0); 5645 } 5646 } 5647 5648 // If we haven't found a load, we can't narrow it. Don't transform one with 5649 // multiple uses, this would require adding a new load. 5650 if (!isa<LoadSDNode>(N0) || !N0.hasOneUse()) 5651 return SDValue(); 5652 5653 // Don't change the width of a volatile load. 5654 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 5655 if (LN0->isVolatile()) 5656 return SDValue(); 5657 5658 // Verify that we are actually reducing a load width here. 5659 if (LN0->getMemoryVT().getSizeInBits() < EVTBits) 5660 return SDValue(); 5661 5662 // For the transform to be legal, the load must produce only two values 5663 // (the value loaded and the chain). Don't transform a pre-increment 5664 // load, for example, which produces an extra value. Otherwise the 5665 // transformation is not equivalent, and the downstream logic to replace 5666 // uses gets things wrong. 5667 if (LN0->getNumValues() > 2) 5668 return SDValue(); 5669 5670 // If the load that we're shrinking is an extload and we're not just 5671 // discarding the extension we can't simply shrink the load. Bail. 5672 // TODO: It would be possible to merge the extensions in some cases. 5673 if (LN0->getExtensionType() != ISD::NON_EXTLOAD && 5674 LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt) 5675 return SDValue(); 5676 5677 EVT PtrType = N0.getOperand(1).getValueType(); 5678 5679 if (PtrType == MVT::Untyped || PtrType.isExtended()) 5680 // It's not possible to generate a constant of extended or untyped type. 5681 return SDValue(); 5682 5683 // For big endian targets, we need to adjust the offset to the pointer to 5684 // load the correct bytes. 5685 if (TLI.isBigEndian()) { 5686 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits(); 5687 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits(); 5688 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt; 5689 } 5690 5691 uint64_t PtrOff = ShAmt / 8; 5692 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff); 5693 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0), 5694 PtrType, LN0->getBasePtr(), 5695 DAG.getConstant(PtrOff, PtrType)); 5696 AddToWorkList(NewPtr.getNode()); 5697 5698 SDValue Load; 5699 if (ExtType == ISD::NON_EXTLOAD) 5700 Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr, 5701 LN0->getPointerInfo().getWithOffset(PtrOff), 5702 LN0->isVolatile(), LN0->isNonTemporal(), 5703 LN0->isInvariant(), NewAlign, LN0->getTBAAInfo()); 5704 else 5705 Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr, 5706 LN0->getPointerInfo().getWithOffset(PtrOff), 5707 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(), 5708 NewAlign, LN0->getTBAAInfo()); 5709 5710 // Replace the old load's chain with the new load's chain. 5711 WorkListRemover DeadNodes(*this); 5712 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1)); 5713 5714 // Shift the result left, if we've swallowed a left shift. 5715 SDValue Result = Load; 5716 if (ShLeftAmt != 0) { 5717 EVT ShImmTy = getShiftAmountTy(Result.getValueType()); 5718 if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt)) 5719 ShImmTy = VT; 5720 // If the shift amount is as large as the result size (but, presumably, 5721 // no larger than the source) then the useful bits of the result are 5722 // zero; we can't simply return the shortened shift, because the result 5723 // of that operation is undefined. 5724 if (ShLeftAmt >= VT.getSizeInBits()) 5725 Result = DAG.getConstant(0, VT); 5726 else 5727 Result = DAG.getNode(ISD::SHL, SDLoc(N0), VT, 5728 Result, DAG.getConstant(ShLeftAmt, ShImmTy)); 5729 } 5730 5731 // Return the new loaded value. 5732 return Result; 5733 } 5734 5735 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) { 5736 SDValue N0 = N->getOperand(0); 5737 SDValue N1 = N->getOperand(1); 5738 EVT VT = N->getValueType(0); 5739 EVT EVT = cast<VTSDNode>(N1)->getVT(); 5740 unsigned VTBits = VT.getScalarType().getSizeInBits(); 5741 unsigned EVTBits = EVT.getScalarType().getSizeInBits(); 5742 5743 // fold (sext_in_reg c1) -> c1 5744 if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF) 5745 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1); 5746 5747 // If the input is already sign extended, just drop the extension. 5748 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1) 5749 return N0; 5750 5751 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2 5752 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG && 5753 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT())) 5754 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, 5755 N0.getOperand(0), N1); 5756 5757 // fold (sext_in_reg (sext x)) -> (sext x) 5758 // fold (sext_in_reg (aext x)) -> (sext x) 5759 // if x is small enough. 5760 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) { 5761 SDValue N00 = N0.getOperand(0); 5762 if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits && 5763 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT))) 5764 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1); 5765 } 5766 5767 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero. 5768 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits))) 5769 return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT); 5770 5771 // fold operands of sext_in_reg based on knowledge that the top bits are not 5772 // demanded. 5773 if (SimplifyDemandedBits(SDValue(N, 0))) 5774 return SDValue(N, 0); 5775 5776 // fold (sext_in_reg (load x)) -> (smaller sextload x) 5777 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits)) 5778 SDValue NarrowLoad = ReduceLoadWidth(N); 5779 if (NarrowLoad.getNode()) 5780 return NarrowLoad; 5781 5782 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24) 5783 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible. 5784 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above. 5785 if (N0.getOpcode() == ISD::SRL) { 5786 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1))) 5787 if (ShAmt->getZExtValue()+EVTBits <= VTBits) { 5788 // We can turn this into an SRA iff the input to the SRL is already sign 5789 // extended enough. 5790 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0)); 5791 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits) 5792 return DAG.getNode(ISD::SRA, SDLoc(N), VT, 5793 N0.getOperand(0), N0.getOperand(1)); 5794 } 5795 } 5796 5797 // fold (sext_inreg (extload x)) -> (sextload x) 5798 if (ISD::isEXTLoad(N0.getNode()) && 5799 ISD::isUNINDEXEDLoad(N0.getNode()) && 5800 EVT == cast<LoadSDNode>(N0)->getMemoryVT() && 5801 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) || 5802 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) { 5803 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 5804 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT, 5805 LN0->getChain(), 5806 LN0->getBasePtr(), EVT, 5807 LN0->getMemOperand()); 5808 CombineTo(N, ExtLoad); 5809 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 5810 AddToWorkList(ExtLoad.getNode()); 5811 return SDValue(N, 0); // Return N so it doesn't get rechecked! 5812 } 5813 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use 5814 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 5815 N0.hasOneUse() && 5816 EVT == cast<LoadSDNode>(N0)->getMemoryVT() && 5817 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) || 5818 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) { 5819 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 5820 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT, 5821 LN0->getChain(), 5822 LN0->getBasePtr(), EVT, 5823 LN0->getMemOperand()); 5824 CombineTo(N, ExtLoad); 5825 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 5826 return SDValue(N, 0); // Return N so it doesn't get rechecked! 5827 } 5828 5829 // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16)) 5830 if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) { 5831 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0), 5832 N0.getOperand(1), false); 5833 if (BSwap.getNode()) 5834 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, 5835 BSwap, N1); 5836 } 5837 5838 // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs 5839 // into a build_vector. 5840 if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) { 5841 SmallVector<SDValue, 8> Elts; 5842 unsigned NumElts = N0->getNumOperands(); 5843 unsigned ShAmt = VTBits - EVTBits; 5844 5845 for (unsigned i = 0; i != NumElts; ++i) { 5846 SDValue Op = N0->getOperand(i); 5847 if (Op->getOpcode() == ISD::UNDEF) { 5848 Elts.push_back(Op); 5849 continue; 5850 } 5851 5852 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op); 5853 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue()); 5854 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(), 5855 Op.getValueType())); 5856 } 5857 5858 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, &Elts[0], NumElts); 5859 } 5860 5861 return SDValue(); 5862 } 5863 5864 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) { 5865 SDValue N0 = N->getOperand(0); 5866 EVT VT = N->getValueType(0); 5867 bool isLE = TLI.isLittleEndian(); 5868 5869 // noop truncate 5870 if (N0.getValueType() == N->getValueType(0)) 5871 return N0; 5872 // fold (truncate c1) -> c1 5873 if (isa<ConstantSDNode>(N0)) 5874 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0); 5875 // fold (truncate (truncate x)) -> (truncate x) 5876 if (N0.getOpcode() == ISD::TRUNCATE) 5877 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0)); 5878 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x 5879 if (N0.getOpcode() == ISD::ZERO_EXTEND || 5880 N0.getOpcode() == ISD::SIGN_EXTEND || 5881 N0.getOpcode() == ISD::ANY_EXTEND) { 5882 if (N0.getOperand(0).getValueType().bitsLT(VT)) 5883 // if the source is smaller than the dest, we still need an extend 5884 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, 5885 N0.getOperand(0)); 5886 if (N0.getOperand(0).getValueType().bitsGT(VT)) 5887 // if the source is larger than the dest, than we just need the truncate 5888 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0)); 5889 // if the source and dest are the same type, we can drop both the extend 5890 // and the truncate. 5891 return N0.getOperand(0); 5892 } 5893 5894 // Fold extract-and-trunc into a narrow extract. For example: 5895 // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1) 5896 // i32 y = TRUNCATE(i64 x) 5897 // -- becomes -- 5898 // v16i8 b = BITCAST (v2i64 val) 5899 // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8) 5900 // 5901 // Note: We only run this optimization after type legalization (which often 5902 // creates this pattern) and before operation legalization after which 5903 // we need to be more careful about the vector instructions that we generate. 5904 if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT && 5905 LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) { 5906 5907 EVT VecTy = N0.getOperand(0).getValueType(); 5908 EVT ExTy = N0.getValueType(); 5909 EVT TrTy = N->getValueType(0); 5910 5911 unsigned NumElem = VecTy.getVectorNumElements(); 5912 unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits(); 5913 5914 EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem); 5915 assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size"); 5916 5917 SDValue EltNo = N0->getOperand(1); 5918 if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) { 5919 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue(); 5920 EVT IndexTy = TLI.getVectorIdxTy(); 5921 int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1)); 5922 5923 SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N), 5924 NVT, N0.getOperand(0)); 5925 5926 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, 5927 SDLoc(N), TrTy, V, 5928 DAG.getConstant(Index, IndexTy)); 5929 } 5930 } 5931 5932 // Fold a series of buildvector, bitcast, and truncate if possible. 5933 // For example fold 5934 // (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to 5935 // (2xi32 (buildvector x, y)). 5936 if (Level == AfterLegalizeVectorOps && VT.isVector() && 5937 N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() && 5938 N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR && 5939 N0.getOperand(0).hasOneUse()) { 5940 5941 SDValue BuildVect = N0.getOperand(0); 5942 EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType(); 5943 EVT TruncVecEltTy = VT.getVectorElementType(); 5944 5945 // Check that the element types match. 5946 if (BuildVectEltTy == TruncVecEltTy) { 5947 // Now we only need to compute the offset of the truncated elements. 5948 unsigned BuildVecNumElts = BuildVect.getNumOperands(); 5949 unsigned TruncVecNumElts = VT.getVectorNumElements(); 5950 unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts; 5951 5952 assert((BuildVecNumElts % TruncVecNumElts) == 0 && 5953 "Invalid number of elements"); 5954 5955 SmallVector<SDValue, 8> Opnds; 5956 for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset) 5957 Opnds.push_back(BuildVect.getOperand(i)); 5958 5959 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, &Opnds[0], 5960 Opnds.size()); 5961 } 5962 } 5963 5964 // See if we can simplify the input to this truncate through knowledge that 5965 // only the low bits are being used. 5966 // For example "trunc (or (shl x, 8), y)" // -> trunc y 5967 // Currently we only perform this optimization on scalars because vectors 5968 // may have different active low bits. 5969 if (!VT.isVector()) { 5970 SDValue Shorter = 5971 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(), 5972 VT.getSizeInBits())); 5973 if (Shorter.getNode()) 5974 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter); 5975 } 5976 // fold (truncate (load x)) -> (smaller load x) 5977 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits)) 5978 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) { 5979 SDValue Reduced = ReduceLoadWidth(N); 5980 if (Reduced.getNode()) 5981 return Reduced; 5982 // Handle the case where the load remains an extending load even 5983 // after truncation. 5984 if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) { 5985 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 5986 if (!LN0->isVolatile() && 5987 LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) { 5988 SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0), 5989 VT, LN0->getChain(), LN0->getBasePtr(), 5990 LN0->getMemoryVT(), 5991 LN0->getMemOperand()); 5992 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1)); 5993 return NewLoad; 5994 } 5995 } 5996 } 5997 // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)), 5998 // where ... are all 'undef'. 5999 if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) { 6000 SmallVector<EVT, 8> VTs; 6001 SDValue V; 6002 unsigned Idx = 0; 6003 unsigned NumDefs = 0; 6004 6005 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) { 6006 SDValue X = N0.getOperand(i); 6007 if (X.getOpcode() != ISD::UNDEF) { 6008 V = X; 6009 Idx = i; 6010 NumDefs++; 6011 } 6012 // Stop if more than one members are non-undef. 6013 if (NumDefs > 1) 6014 break; 6015 VTs.push_back(EVT::getVectorVT(*DAG.getContext(), 6016 VT.getVectorElementType(), 6017 X.getValueType().getVectorNumElements())); 6018 } 6019 6020 if (NumDefs == 0) 6021 return DAG.getUNDEF(VT); 6022 6023 if (NumDefs == 1) { 6024 assert(V.getNode() && "The single defined operand is empty!"); 6025 SmallVector<SDValue, 8> Opnds; 6026 for (unsigned i = 0, e = VTs.size(); i != e; ++i) { 6027 if (i != Idx) { 6028 Opnds.push_back(DAG.getUNDEF(VTs[i])); 6029 continue; 6030 } 6031 SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V); 6032 AddToWorkList(NV.getNode()); 6033 Opnds.push_back(NV); 6034 } 6035 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, 6036 &Opnds[0], Opnds.size()); 6037 } 6038 } 6039 6040 // Simplify the operands using demanded-bits information. 6041 if (!VT.isVector() && 6042 SimplifyDemandedBits(SDValue(N, 0))) 6043 return SDValue(N, 0); 6044 6045 return SDValue(); 6046 } 6047 6048 static SDNode *getBuildPairElt(SDNode *N, unsigned i) { 6049 SDValue Elt = N->getOperand(i); 6050 if (Elt.getOpcode() != ISD::MERGE_VALUES) 6051 return Elt.getNode(); 6052 return Elt.getOperand(Elt.getResNo()).getNode(); 6053 } 6054 6055 /// CombineConsecutiveLoads - build_pair (load, load) -> load 6056 /// if load locations are consecutive. 6057 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) { 6058 assert(N->getOpcode() == ISD::BUILD_PAIR); 6059 6060 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0)); 6061 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1)); 6062 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() || 6063 LD1->getAddressSpace() != LD2->getAddressSpace()) 6064 return SDValue(); 6065 EVT LD1VT = LD1->getValueType(0); 6066 6067 if (ISD::isNON_EXTLoad(LD2) && 6068 LD2->hasOneUse() && 6069 // If both are volatile this would reduce the number of volatile loads. 6070 // If one is volatile it might be ok, but play conservative and bail out. 6071 !LD1->isVolatile() && 6072 !LD2->isVolatile() && 6073 DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) { 6074 unsigned Align = LD1->getAlignment(); 6075 unsigned NewAlign = TLI.getDataLayout()-> 6076 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext())); 6077 6078 if (NewAlign <= Align && 6079 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT))) 6080 return DAG.getLoad(VT, SDLoc(N), LD1->getChain(), 6081 LD1->getBasePtr(), LD1->getPointerInfo(), 6082 false, false, false, Align); 6083 } 6084 6085 return SDValue(); 6086 } 6087 6088 SDValue DAGCombiner::visitBITCAST(SDNode *N) { 6089 SDValue N0 = N->getOperand(0); 6090 EVT VT = N->getValueType(0); 6091 6092 // If the input is a BUILD_VECTOR with all constant elements, fold this now. 6093 // Only do this before legalize, since afterward the target may be depending 6094 // on the bitconvert. 6095 // First check to see if this is all constant. 6096 if (!LegalTypes && 6097 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() && 6098 VT.isVector()) { 6099 bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant(); 6100 6101 EVT DestEltVT = N->getValueType(0).getVectorElementType(); 6102 assert(!DestEltVT.isVector() && 6103 "Element type of vector ValueType must not be vector!"); 6104 if (isSimple) 6105 return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT); 6106 } 6107 6108 // If the input is a constant, let getNode fold it. 6109 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) { 6110 SDValue Res = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0); 6111 if (Res.getNode() != N) { 6112 if (!LegalOperations || 6113 TLI.isOperationLegal(Res.getNode()->getOpcode(), VT)) 6114 return Res; 6115 6116 // Folding it resulted in an illegal node, and it's too late to 6117 // do that. Clean up the old node and forego the transformation. 6118 // Ideally this won't happen very often, because instcombine 6119 // and the earlier dagcombine runs (where illegal nodes are 6120 // permitted) should have folded most of them already. 6121 DAG.DeleteNode(Res.getNode()); 6122 } 6123 } 6124 6125 // (conv (conv x, t1), t2) -> (conv x, t2) 6126 if (N0.getOpcode() == ISD::BITCAST) 6127 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, 6128 N0.getOperand(0)); 6129 6130 // fold (conv (load x)) -> (load (conv*)x) 6131 // If the resultant load doesn't need a higher alignment than the original! 6132 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() && 6133 // Do not change the width of a volatile load. 6134 !cast<LoadSDNode>(N0)->isVolatile() && 6135 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) && 6136 TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) { 6137 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6138 unsigned Align = TLI.getDataLayout()-> 6139 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext())); 6140 unsigned OrigAlign = LN0->getAlignment(); 6141 6142 if (Align <= OrigAlign) { 6143 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(), 6144 LN0->getBasePtr(), LN0->getPointerInfo(), 6145 LN0->isVolatile(), LN0->isNonTemporal(), 6146 LN0->isInvariant(), OrigAlign, 6147 LN0->getTBAAInfo()); 6148 AddToWorkList(N); 6149 CombineTo(N0.getNode(), 6150 DAG.getNode(ISD::BITCAST, SDLoc(N0), 6151 N0.getValueType(), Load), 6152 Load.getValue(1)); 6153 return Load; 6154 } 6155 } 6156 6157 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit) 6158 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit)) 6159 // This often reduces constant pool loads. 6160 if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) || 6161 (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) && 6162 N0.getNode()->hasOneUse() && VT.isInteger() && 6163 !VT.isVector() && !N0.getValueType().isVector()) { 6164 SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT, 6165 N0.getOperand(0)); 6166 AddToWorkList(NewConv.getNode()); 6167 6168 APInt SignBit = APInt::getSignBit(VT.getSizeInBits()); 6169 if (N0.getOpcode() == ISD::FNEG) 6170 return DAG.getNode(ISD::XOR, SDLoc(N), VT, 6171 NewConv, DAG.getConstant(SignBit, VT)); 6172 assert(N0.getOpcode() == ISD::FABS); 6173 return DAG.getNode(ISD::AND, SDLoc(N), VT, 6174 NewConv, DAG.getConstant(~SignBit, VT)); 6175 } 6176 6177 // fold (bitconvert (fcopysign cst, x)) -> 6178 // (or (and (bitconvert x), sign), (and cst, (not sign))) 6179 // Note that we don't handle (copysign x, cst) because this can always be 6180 // folded to an fneg or fabs. 6181 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() && 6182 isa<ConstantFPSDNode>(N0.getOperand(0)) && 6183 VT.isInteger() && !VT.isVector()) { 6184 unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits(); 6185 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth); 6186 if (isTypeLegal(IntXVT)) { 6187 SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0), 6188 IntXVT, N0.getOperand(1)); 6189 AddToWorkList(X.getNode()); 6190 6191 // If X has a different width than the result/lhs, sext it or truncate it. 6192 unsigned VTWidth = VT.getSizeInBits(); 6193 if (OrigXWidth < VTWidth) { 6194 X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X); 6195 AddToWorkList(X.getNode()); 6196 } else if (OrigXWidth > VTWidth) { 6197 // To get the sign bit in the right place, we have to shift it right 6198 // before truncating. 6199 X = DAG.getNode(ISD::SRL, SDLoc(X), 6200 X.getValueType(), X, 6201 DAG.getConstant(OrigXWidth-VTWidth, X.getValueType())); 6202 AddToWorkList(X.getNode()); 6203 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X); 6204 AddToWorkList(X.getNode()); 6205 } 6206 6207 APInt SignBit = APInt::getSignBit(VT.getSizeInBits()); 6208 X = DAG.getNode(ISD::AND, SDLoc(X), VT, 6209 X, DAG.getConstant(SignBit, VT)); 6210 AddToWorkList(X.getNode()); 6211 6212 SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0), 6213 VT, N0.getOperand(0)); 6214 Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT, 6215 Cst, DAG.getConstant(~SignBit, VT)); 6216 AddToWorkList(Cst.getNode()); 6217 6218 return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst); 6219 } 6220 } 6221 6222 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive. 6223 if (N0.getOpcode() == ISD::BUILD_PAIR) { 6224 SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT); 6225 if (CombineLD.getNode()) 6226 return CombineLD; 6227 } 6228 6229 return SDValue(); 6230 } 6231 6232 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) { 6233 EVT VT = N->getValueType(0); 6234 return CombineConsecutiveLoads(N, VT); 6235 } 6236 6237 /// ConstantFoldBITCASTofBUILD_VECTOR - We know that BV is a build_vector 6238 /// node with Constant, ConstantFP or Undef operands. DstEltVT indicates the 6239 /// destination element value type. 6240 SDValue DAGCombiner:: 6241 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) { 6242 EVT SrcEltVT = BV->getValueType(0).getVectorElementType(); 6243 6244 // If this is already the right type, we're done. 6245 if (SrcEltVT == DstEltVT) return SDValue(BV, 0); 6246 6247 unsigned SrcBitSize = SrcEltVT.getSizeInBits(); 6248 unsigned DstBitSize = DstEltVT.getSizeInBits(); 6249 6250 // If this is a conversion of N elements of one type to N elements of another 6251 // type, convert each element. This handles FP<->INT cases. 6252 if (SrcBitSize == DstBitSize) { 6253 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, 6254 BV->getValueType(0).getVectorNumElements()); 6255 6256 // Due to the FP element handling below calling this routine recursively, 6257 // we can end up with a scalar-to-vector node here. 6258 if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR) 6259 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT, 6260 DAG.getNode(ISD::BITCAST, SDLoc(BV), 6261 DstEltVT, BV->getOperand(0))); 6262 6263 SmallVector<SDValue, 8> Ops; 6264 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) { 6265 SDValue Op = BV->getOperand(i); 6266 // If the vector element type is not legal, the BUILD_VECTOR operands 6267 // are promoted and implicitly truncated. Make that explicit here. 6268 if (Op.getValueType() != SrcEltVT) 6269 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op); 6270 Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV), 6271 DstEltVT, Op)); 6272 AddToWorkList(Ops.back().getNode()); 6273 } 6274 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, 6275 &Ops[0], Ops.size()); 6276 } 6277 6278 // Otherwise, we're growing or shrinking the elements. To avoid having to 6279 // handle annoying details of growing/shrinking FP values, we convert them to 6280 // int first. 6281 if (SrcEltVT.isFloatingPoint()) { 6282 // Convert the input float vector to a int vector where the elements are the 6283 // same sizes. 6284 assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!"); 6285 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits()); 6286 BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode(); 6287 SrcEltVT = IntVT; 6288 } 6289 6290 // Now we know the input is an integer vector. If the output is a FP type, 6291 // convert to integer first, then to FP of the right size. 6292 if (DstEltVT.isFloatingPoint()) { 6293 assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!"); 6294 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits()); 6295 SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode(); 6296 6297 // Next, convert to FP elements of the same size. 6298 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT); 6299 } 6300 6301 // Okay, we know the src/dst types are both integers of differing types. 6302 // Handling growing first. 6303 assert(SrcEltVT.isInteger() && DstEltVT.isInteger()); 6304 if (SrcBitSize < DstBitSize) { 6305 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize; 6306 6307 SmallVector<SDValue, 8> Ops; 6308 for (unsigned i = 0, e = BV->getNumOperands(); i != e; 6309 i += NumInputsPerOutput) { 6310 bool isLE = TLI.isLittleEndian(); 6311 APInt NewBits = APInt(DstBitSize, 0); 6312 bool EltIsUndef = true; 6313 for (unsigned j = 0; j != NumInputsPerOutput; ++j) { 6314 // Shift the previously computed bits over. 6315 NewBits <<= SrcBitSize; 6316 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j)); 6317 if (Op.getOpcode() == ISD::UNDEF) continue; 6318 EltIsUndef = false; 6319 6320 NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue(). 6321 zextOrTrunc(SrcBitSize).zext(DstBitSize); 6322 } 6323 6324 if (EltIsUndef) 6325 Ops.push_back(DAG.getUNDEF(DstEltVT)); 6326 else 6327 Ops.push_back(DAG.getConstant(NewBits, DstEltVT)); 6328 } 6329 6330 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size()); 6331 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, 6332 &Ops[0], Ops.size()); 6333 } 6334 6335 // Finally, this must be the case where we are shrinking elements: each input 6336 // turns into multiple outputs. 6337 bool isS2V = ISD::isScalarToVector(BV); 6338 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize; 6339 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, 6340 NumOutputsPerInput*BV->getNumOperands()); 6341 SmallVector<SDValue, 8> Ops; 6342 6343 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) { 6344 if (BV->getOperand(i).getOpcode() == ISD::UNDEF) { 6345 for (unsigned j = 0; j != NumOutputsPerInput; ++j) 6346 Ops.push_back(DAG.getUNDEF(DstEltVT)); 6347 continue; 6348 } 6349 6350 APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))-> 6351 getAPIntValue().zextOrTrunc(SrcBitSize); 6352 6353 for (unsigned j = 0; j != NumOutputsPerInput; ++j) { 6354 APInt ThisVal = OpVal.trunc(DstBitSize); 6355 Ops.push_back(DAG.getConstant(ThisVal, DstEltVT)); 6356 if (isS2V && i == 0 && j == 0 && ThisVal.zext(SrcBitSize) == OpVal) 6357 // Simply turn this into a SCALAR_TO_VECTOR of the new type. 6358 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT, 6359 Ops[0]); 6360 OpVal = OpVal.lshr(DstBitSize); 6361 } 6362 6363 // For big endian targets, swap the order of the pieces of each element. 6364 if (TLI.isBigEndian()) 6365 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end()); 6366 } 6367 6368 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, 6369 &Ops[0], Ops.size()); 6370 } 6371 6372 SDValue DAGCombiner::visitFADD(SDNode *N) { 6373 SDValue N0 = N->getOperand(0); 6374 SDValue N1 = N->getOperand(1); 6375 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 6376 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 6377 EVT VT = N->getValueType(0); 6378 6379 // fold vector ops 6380 if (VT.isVector()) { 6381 SDValue FoldedVOp = SimplifyVBinOp(N); 6382 if (FoldedVOp.getNode()) return FoldedVOp; 6383 } 6384 6385 // fold (fadd c1, c2) -> c1 + c2 6386 if (N0CFP && N1CFP) 6387 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N1); 6388 // canonicalize constant to RHS 6389 if (N0CFP && !N1CFP) 6390 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N0); 6391 // fold (fadd A, 0) -> A 6392 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP && 6393 N1CFP->getValueAPF().isZero()) 6394 return N0; 6395 // fold (fadd A, (fneg B)) -> (fsub A, B) 6396 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) && 6397 isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options) == 2) 6398 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0, 6399 GetNegatedExpression(N1, DAG, LegalOperations)); 6400 // fold (fadd (fneg A), B) -> (fsub B, A) 6401 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) && 6402 isNegatibleForFree(N0, LegalOperations, TLI, &DAG.getTarget().Options) == 2) 6403 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N1, 6404 GetNegatedExpression(N0, DAG, LegalOperations)); 6405 6406 // If allowed, fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2)) 6407 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP && 6408 N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() && 6409 isa<ConstantFPSDNode>(N0.getOperand(1))) 6410 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0.getOperand(0), 6411 DAG.getNode(ISD::FADD, SDLoc(N), VT, 6412 N0.getOperand(1), N1)); 6413 6414 // No FP constant should be created after legalization as Instruction 6415 // Selection pass has hard time in dealing with FP constant. 6416 // 6417 // We don't need test this condition for transformation like following, as 6418 // the DAG being transformed implies it is legal to take FP constant as 6419 // operand. 6420 // 6421 // (fadd (fmul c, x), x) -> (fmul c+1, x) 6422 // 6423 bool AllowNewFpConst = (Level < AfterLegalizeDAG); 6424 6425 // If allow, fold (fadd (fneg x), x) -> 0.0 6426 if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath && 6427 N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1) 6428 return DAG.getConstantFP(0.0, VT); 6429 6430 // If allow, fold (fadd x, (fneg x)) -> 0.0 6431 if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath && 6432 N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0) 6433 return DAG.getConstantFP(0.0, VT); 6434 6435 // In unsafe math mode, we can fold chains of FADD's of the same value 6436 // into multiplications. This transform is not safe in general because 6437 // we are reducing the number of rounding steps. 6438 if (DAG.getTarget().Options.UnsafeFPMath && 6439 TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && 6440 !N0CFP && !N1CFP) { 6441 if (N0.getOpcode() == ISD::FMUL) { 6442 ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0)); 6443 ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1)); 6444 6445 // (fadd (fmul c, x), x) -> (fmul x, c+1) 6446 if (CFP00 && !CFP01 && N0.getOperand(1) == N1) { 6447 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT, 6448 SDValue(CFP00, 0), 6449 DAG.getConstantFP(1.0, VT)); 6450 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, 6451 N1, NewCFP); 6452 } 6453 6454 // (fadd (fmul x, c), x) -> (fmul x, c+1) 6455 if (CFP01 && !CFP00 && N0.getOperand(0) == N1) { 6456 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT, 6457 SDValue(CFP01, 0), 6458 DAG.getConstantFP(1.0, VT)); 6459 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, 6460 N1, NewCFP); 6461 } 6462 6463 // (fadd (fmul c, x), (fadd x, x)) -> (fmul x, c+2) 6464 if (CFP00 && !CFP01 && N1.getOpcode() == ISD::FADD && 6465 N1.getOperand(0) == N1.getOperand(1) && 6466 N0.getOperand(1) == N1.getOperand(0)) { 6467 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT, 6468 SDValue(CFP00, 0), 6469 DAG.getConstantFP(2.0, VT)); 6470 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, 6471 N0.getOperand(1), NewCFP); 6472 } 6473 6474 // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2) 6475 if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD && 6476 N1.getOperand(0) == N1.getOperand(1) && 6477 N0.getOperand(0) == N1.getOperand(0)) { 6478 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT, 6479 SDValue(CFP01, 0), 6480 DAG.getConstantFP(2.0, VT)); 6481 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, 6482 N0.getOperand(0), NewCFP); 6483 } 6484 } 6485 6486 if (N1.getOpcode() == ISD::FMUL) { 6487 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0)); 6488 ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1)); 6489 6490 // (fadd x, (fmul c, x)) -> (fmul x, c+1) 6491 if (CFP10 && !CFP11 && N1.getOperand(1) == N0) { 6492 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT, 6493 SDValue(CFP10, 0), 6494 DAG.getConstantFP(1.0, VT)); 6495 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, 6496 N0, NewCFP); 6497 } 6498 6499 // (fadd x, (fmul x, c)) -> (fmul x, c+1) 6500 if (CFP11 && !CFP10 && N1.getOperand(0) == N0) { 6501 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT, 6502 SDValue(CFP11, 0), 6503 DAG.getConstantFP(1.0, VT)); 6504 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, 6505 N0, NewCFP); 6506 } 6507 6508 6509 // (fadd (fadd x, x), (fmul c, x)) -> (fmul x, c+2) 6510 if (CFP10 && !CFP11 && N0.getOpcode() == ISD::FADD && 6511 N0.getOperand(0) == N0.getOperand(1) && 6512 N1.getOperand(1) == N0.getOperand(0)) { 6513 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT, 6514 SDValue(CFP10, 0), 6515 DAG.getConstantFP(2.0, VT)); 6516 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, 6517 N1.getOperand(1), NewCFP); 6518 } 6519 6520 // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2) 6521 if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD && 6522 N0.getOperand(0) == N0.getOperand(1) && 6523 N1.getOperand(0) == N0.getOperand(0)) { 6524 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT, 6525 SDValue(CFP11, 0), 6526 DAG.getConstantFP(2.0, VT)); 6527 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, 6528 N1.getOperand(0), NewCFP); 6529 } 6530 } 6531 6532 if (N0.getOpcode() == ISD::FADD && AllowNewFpConst) { 6533 ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0)); 6534 // (fadd (fadd x, x), x) -> (fmul x, 3.0) 6535 if (!CFP && N0.getOperand(0) == N0.getOperand(1) && 6536 (N0.getOperand(0) == N1)) 6537 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, 6538 N1, DAG.getConstantFP(3.0, VT)); 6539 } 6540 6541 if (N1.getOpcode() == ISD::FADD && AllowNewFpConst) { 6542 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0)); 6543 // (fadd x, (fadd x, x)) -> (fmul x, 3.0) 6544 if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) && 6545 N1.getOperand(0) == N0) 6546 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, 6547 N0, DAG.getConstantFP(3.0, VT)); 6548 } 6549 6550 // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0) 6551 if (AllowNewFpConst && 6552 N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD && 6553 N0.getOperand(0) == N0.getOperand(1) && 6554 N1.getOperand(0) == N1.getOperand(1) && 6555 N0.getOperand(0) == N1.getOperand(0)) 6556 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, 6557 N0.getOperand(0), 6558 DAG.getConstantFP(4.0, VT)); 6559 } 6560 6561 // FADD -> FMA combines: 6562 if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast || 6563 DAG.getTarget().Options.UnsafeFPMath) && 6564 DAG.getTarget().getTargetLowering()->isFMAFasterThanFMulAndFAdd(VT) && 6565 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) { 6566 6567 // fold (fadd (fmul x, y), z) -> (fma x, y, z) 6568 if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse()) 6569 return DAG.getNode(ISD::FMA, SDLoc(N), VT, 6570 N0.getOperand(0), N0.getOperand(1), N1); 6571 6572 // fold (fadd x, (fmul y, z)) -> (fma y, z, x) 6573 // Note: Commutes FADD operands. 6574 if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse()) 6575 return DAG.getNode(ISD::FMA, SDLoc(N), VT, 6576 N1.getOperand(0), N1.getOperand(1), N0); 6577 } 6578 6579 return SDValue(); 6580 } 6581 6582 SDValue DAGCombiner::visitFSUB(SDNode *N) { 6583 SDValue N0 = N->getOperand(0); 6584 SDValue N1 = N->getOperand(1); 6585 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 6586 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 6587 EVT VT = N->getValueType(0); 6588 SDLoc dl(N); 6589 6590 // fold vector ops 6591 if (VT.isVector()) { 6592 SDValue FoldedVOp = SimplifyVBinOp(N); 6593 if (FoldedVOp.getNode()) return FoldedVOp; 6594 } 6595 6596 // fold (fsub c1, c2) -> c1-c2 6597 if (N0CFP && N1CFP) 6598 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0, N1); 6599 // fold (fsub A, 0) -> A 6600 if (DAG.getTarget().Options.UnsafeFPMath && 6601 N1CFP && N1CFP->getValueAPF().isZero()) 6602 return N0; 6603 // fold (fsub 0, B) -> -B 6604 if (DAG.getTarget().Options.UnsafeFPMath && 6605 N0CFP && N0CFP->getValueAPF().isZero()) { 6606 if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options)) 6607 return GetNegatedExpression(N1, DAG, LegalOperations); 6608 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT)) 6609 return DAG.getNode(ISD::FNEG, dl, VT, N1); 6610 } 6611 // fold (fsub A, (fneg B)) -> (fadd A, B) 6612 if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options)) 6613 return DAG.getNode(ISD::FADD, dl, VT, N0, 6614 GetNegatedExpression(N1, DAG, LegalOperations)); 6615 6616 // If 'unsafe math' is enabled, fold 6617 // (fsub x, x) -> 0.0 & 6618 // (fsub x, (fadd x, y)) -> (fneg y) & 6619 // (fsub x, (fadd y, x)) -> (fneg y) 6620 if (DAG.getTarget().Options.UnsafeFPMath) { 6621 if (N0 == N1) 6622 return DAG.getConstantFP(0.0f, VT); 6623 6624 if (N1.getOpcode() == ISD::FADD) { 6625 SDValue N10 = N1->getOperand(0); 6626 SDValue N11 = N1->getOperand(1); 6627 6628 if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, 6629 &DAG.getTarget().Options)) 6630 return GetNegatedExpression(N11, DAG, LegalOperations); 6631 6632 if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, 6633 &DAG.getTarget().Options)) 6634 return GetNegatedExpression(N10, DAG, LegalOperations); 6635 } 6636 } 6637 6638 // FSUB -> FMA combines: 6639 if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast || 6640 DAG.getTarget().Options.UnsafeFPMath) && 6641 DAG.getTarget().getTargetLowering()->isFMAFasterThanFMulAndFAdd(VT) && 6642 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) { 6643 6644 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z)) 6645 if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse()) 6646 return DAG.getNode(ISD::FMA, dl, VT, 6647 N0.getOperand(0), N0.getOperand(1), 6648 DAG.getNode(ISD::FNEG, dl, VT, N1)); 6649 6650 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x) 6651 // Note: Commutes FSUB operands. 6652 if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse()) 6653 return DAG.getNode(ISD::FMA, dl, VT, 6654 DAG.getNode(ISD::FNEG, dl, VT, 6655 N1.getOperand(0)), 6656 N1.getOperand(1), N0); 6657 6658 // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z)) 6659 if (N0.getOpcode() == ISD::FNEG && 6660 N0.getOperand(0).getOpcode() == ISD::FMUL && 6661 N0->hasOneUse() && N0.getOperand(0).hasOneUse()) { 6662 SDValue N00 = N0.getOperand(0).getOperand(0); 6663 SDValue N01 = N0.getOperand(0).getOperand(1); 6664 return DAG.getNode(ISD::FMA, dl, VT, 6665 DAG.getNode(ISD::FNEG, dl, VT, N00), N01, 6666 DAG.getNode(ISD::FNEG, dl, VT, N1)); 6667 } 6668 } 6669 6670 return SDValue(); 6671 } 6672 6673 SDValue DAGCombiner::visitFMUL(SDNode *N) { 6674 SDValue N0 = N->getOperand(0); 6675 SDValue N1 = N->getOperand(1); 6676 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 6677 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 6678 EVT VT = N->getValueType(0); 6679 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6680 6681 // fold vector ops 6682 if (VT.isVector()) { 6683 SDValue FoldedVOp = SimplifyVBinOp(N); 6684 if (FoldedVOp.getNode()) return FoldedVOp; 6685 } 6686 6687 // fold (fmul c1, c2) -> c1*c2 6688 if (N0CFP && N1CFP) 6689 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, N1); 6690 // canonicalize constant to RHS 6691 if (N0CFP && !N1CFP) 6692 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, N0); 6693 // fold (fmul A, 0) -> 0 6694 if (DAG.getTarget().Options.UnsafeFPMath && 6695 N1CFP && N1CFP->getValueAPF().isZero()) 6696 return N1; 6697 // fold (fmul A, 0) -> 0, vector edition. 6698 if (DAG.getTarget().Options.UnsafeFPMath && 6699 ISD::isBuildVectorAllZeros(N1.getNode())) 6700 return N1; 6701 // fold (fmul A, 1.0) -> A 6702 if (N1CFP && N1CFP->isExactlyValue(1.0)) 6703 return N0; 6704 // fold (fmul X, 2.0) -> (fadd X, X) 6705 if (N1CFP && N1CFP->isExactlyValue(+2.0)) 6706 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N0); 6707 // fold (fmul X, -1.0) -> (fneg X) 6708 if (N1CFP && N1CFP->isExactlyValue(-1.0)) 6709 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT)) 6710 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0); 6711 6712 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y) 6713 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, 6714 &DAG.getTarget().Options)) { 6715 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, 6716 &DAG.getTarget().Options)) { 6717 // Both can be negated for free, check to see if at least one is cheaper 6718 // negated. 6719 if (LHSNeg == 2 || RHSNeg == 2) 6720 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, 6721 GetNegatedExpression(N0, DAG, LegalOperations), 6722 GetNegatedExpression(N1, DAG, LegalOperations)); 6723 } 6724 } 6725 6726 // If allowed, fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2)) 6727 if (DAG.getTarget().Options.UnsafeFPMath && 6728 N1CFP && N0.getOpcode() == ISD::FMUL && 6729 N0.getNode()->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1))) 6730 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0), 6731 DAG.getNode(ISD::FMUL, SDLoc(N), VT, 6732 N0.getOperand(1), N1)); 6733 6734 return SDValue(); 6735 } 6736 6737 SDValue DAGCombiner::visitFMA(SDNode *N) { 6738 SDValue N0 = N->getOperand(0); 6739 SDValue N1 = N->getOperand(1); 6740 SDValue N2 = N->getOperand(2); 6741 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 6742 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 6743 EVT VT = N->getValueType(0); 6744 SDLoc dl(N); 6745 6746 if (DAG.getTarget().Options.UnsafeFPMath) { 6747 if (N0CFP && N0CFP->isZero()) 6748 return N2; 6749 if (N1CFP && N1CFP->isZero()) 6750 return N2; 6751 } 6752 if (N0CFP && N0CFP->isExactlyValue(1.0)) 6753 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2); 6754 if (N1CFP && N1CFP->isExactlyValue(1.0)) 6755 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2); 6756 6757 // Canonicalize (fma c, x, y) -> (fma x, c, y) 6758 if (N0CFP && !N1CFP) 6759 return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2); 6760 6761 // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2) 6762 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP && 6763 N2.getOpcode() == ISD::FMUL && 6764 N0 == N2.getOperand(0) && 6765 N2.getOperand(1).getOpcode() == ISD::ConstantFP) { 6766 return DAG.getNode(ISD::FMUL, dl, VT, N0, 6767 DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1))); 6768 } 6769 6770 6771 // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y) 6772 if (DAG.getTarget().Options.UnsafeFPMath && 6773 N0.getOpcode() == ISD::FMUL && N1CFP && 6774 N0.getOperand(1).getOpcode() == ISD::ConstantFP) { 6775 return DAG.getNode(ISD::FMA, dl, VT, 6776 N0.getOperand(0), 6777 DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)), 6778 N2); 6779 } 6780 6781 // (fma x, 1, y) -> (fadd x, y) 6782 // (fma x, -1, y) -> (fadd (fneg x), y) 6783 if (N1CFP) { 6784 if (N1CFP->isExactlyValue(1.0)) 6785 return DAG.getNode(ISD::FADD, dl, VT, N0, N2); 6786 6787 if (N1CFP->isExactlyValue(-1.0) && 6788 (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) { 6789 SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0); 6790 AddToWorkList(RHSNeg.getNode()); 6791 return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg); 6792 } 6793 } 6794 6795 // (fma x, c, x) -> (fmul x, (c+1)) 6796 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP && N0 == N2) 6797 return DAG.getNode(ISD::FMUL, dl, VT, N0, 6798 DAG.getNode(ISD::FADD, dl, VT, 6799 N1, DAG.getConstantFP(1.0, VT))); 6800 6801 // (fma x, c, (fneg x)) -> (fmul x, (c-1)) 6802 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP && 6803 N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0) 6804 return DAG.getNode(ISD::FMUL, dl, VT, N0, 6805 DAG.getNode(ISD::FADD, dl, VT, 6806 N1, DAG.getConstantFP(-1.0, VT))); 6807 6808 6809 return SDValue(); 6810 } 6811 6812 SDValue DAGCombiner::visitFDIV(SDNode *N) { 6813 SDValue N0 = N->getOperand(0); 6814 SDValue N1 = N->getOperand(1); 6815 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 6816 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 6817 EVT VT = N->getValueType(0); 6818 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6819 6820 // fold vector ops 6821 if (VT.isVector()) { 6822 SDValue FoldedVOp = SimplifyVBinOp(N); 6823 if (FoldedVOp.getNode()) return FoldedVOp; 6824 } 6825 6826 // fold (fdiv c1, c2) -> c1/c2 6827 if (N0CFP && N1CFP) 6828 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1); 6829 6830 // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable. 6831 if (N1CFP && DAG.getTarget().Options.UnsafeFPMath) { 6832 // Compute the reciprocal 1.0 / c2. 6833 APFloat N1APF = N1CFP->getValueAPF(); 6834 APFloat Recip(N1APF.getSemantics(), 1); // 1.0 6835 APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven); 6836 // Only do the transform if the reciprocal is a legal fp immediate that 6837 // isn't too nasty (eg NaN, denormal, ...). 6838 if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty 6839 (!LegalOperations || 6840 // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM 6841 // backend)... we should handle this gracefully after Legalize. 6842 // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) || 6843 TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) || 6844 TLI.isFPImmLegal(Recip, VT))) 6845 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, 6846 DAG.getConstantFP(Recip, VT)); 6847 } 6848 6849 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y) 6850 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, 6851 &DAG.getTarget().Options)) { 6852 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, 6853 &DAG.getTarget().Options)) { 6854 // Both can be negated for free, check to see if at least one is cheaper 6855 // negated. 6856 if (LHSNeg == 2 || RHSNeg == 2) 6857 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, 6858 GetNegatedExpression(N0, DAG, LegalOperations), 6859 GetNegatedExpression(N1, DAG, LegalOperations)); 6860 } 6861 } 6862 6863 return SDValue(); 6864 } 6865 6866 SDValue DAGCombiner::visitFREM(SDNode *N) { 6867 SDValue N0 = N->getOperand(0); 6868 SDValue N1 = N->getOperand(1); 6869 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 6870 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 6871 EVT VT = N->getValueType(0); 6872 6873 // fold (frem c1, c2) -> fmod(c1,c2) 6874 if (N0CFP && N1CFP) 6875 return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1); 6876 6877 return SDValue(); 6878 } 6879 6880 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) { 6881 SDValue N0 = N->getOperand(0); 6882 SDValue N1 = N->getOperand(1); 6883 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 6884 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 6885 EVT VT = N->getValueType(0); 6886 6887 if (N0CFP && N1CFP) // Constant fold 6888 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1); 6889 6890 if (N1CFP) { 6891 const APFloat& V = N1CFP->getValueAPF(); 6892 // copysign(x, c1) -> fabs(x) iff ispos(c1) 6893 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1) 6894 if (!V.isNegative()) { 6895 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT)) 6896 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0); 6897 } else { 6898 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT)) 6899 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, 6900 DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0)); 6901 } 6902 } 6903 6904 // copysign(fabs(x), y) -> copysign(x, y) 6905 // copysign(fneg(x), y) -> copysign(x, y) 6906 // copysign(copysign(x,z), y) -> copysign(x, y) 6907 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG || 6908 N0.getOpcode() == ISD::FCOPYSIGN) 6909 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, 6910 N0.getOperand(0), N1); 6911 6912 // copysign(x, abs(y)) -> abs(x) 6913 if (N1.getOpcode() == ISD::FABS) 6914 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0); 6915 6916 // copysign(x, copysign(y,z)) -> copysign(x, z) 6917 if (N1.getOpcode() == ISD::FCOPYSIGN) 6918 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, 6919 N0, N1.getOperand(1)); 6920 6921 // copysign(x, fp_extend(y)) -> copysign(x, y) 6922 // copysign(x, fp_round(y)) -> copysign(x, y) 6923 if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND) 6924 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, 6925 N0, N1.getOperand(0)); 6926 6927 return SDValue(); 6928 } 6929 6930 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) { 6931 SDValue N0 = N->getOperand(0); 6932 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 6933 EVT VT = N->getValueType(0); 6934 EVT OpVT = N0.getValueType(); 6935 6936 // fold (sint_to_fp c1) -> c1fp 6937 if (N0C && 6938 // ...but only if the target supports immediate floating-point values 6939 (!LegalOperations || 6940 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) 6941 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0); 6942 6943 // If the input is a legal type, and SINT_TO_FP is not legal on this target, 6944 // but UINT_TO_FP is legal on this target, try to convert. 6945 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) && 6946 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) { 6947 // If the sign bit is known to be zero, we can change this to UINT_TO_FP. 6948 if (DAG.SignBitIsZero(N0)) 6949 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0); 6950 } 6951 6952 // The next optimizations are desirable only if SELECT_CC can be lowered. 6953 // Check against MVT::Other for SELECT_CC, which is a workaround for targets 6954 // having to say they don't support SELECT_CC on every type the DAG knows 6955 // about, since there is no way to mark an opcode illegal at all value types 6956 // (See also visitSELECT) 6957 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other)) { 6958 // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc) 6959 if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 && 6960 !VT.isVector() && 6961 (!LegalOperations || 6962 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) { 6963 SDValue Ops[] = 6964 { N0.getOperand(0), N0.getOperand(1), 6965 DAG.getConstantFP(-1.0, VT) , DAG.getConstantFP(0.0, VT), 6966 N0.getOperand(2) }; 6967 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops, 5); 6968 } 6969 6970 // fold (sint_to_fp (zext (setcc x, y, cc))) -> 6971 // (select_cc x, y, 1.0, 0.0,, cc) 6972 if (N0.getOpcode() == ISD::ZERO_EXTEND && 6973 N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() && 6974 (!LegalOperations || 6975 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) { 6976 SDValue Ops[] = 6977 { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1), 6978 DAG.getConstantFP(1.0, VT) , DAG.getConstantFP(0.0, VT), 6979 N0.getOperand(0).getOperand(2) }; 6980 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops, 5); 6981 } 6982 } 6983 6984 return SDValue(); 6985 } 6986 6987 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) { 6988 SDValue N0 = N->getOperand(0); 6989 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 6990 EVT VT = N->getValueType(0); 6991 EVT OpVT = N0.getValueType(); 6992 6993 // fold (uint_to_fp c1) -> c1fp 6994 if (N0C && 6995 // ...but only if the target supports immediate floating-point values 6996 (!LegalOperations || 6997 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) 6998 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0); 6999 7000 // If the input is a legal type, and UINT_TO_FP is not legal on this target, 7001 // but SINT_TO_FP is legal on this target, try to convert. 7002 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) && 7003 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) { 7004 // If the sign bit is known to be zero, we can change this to SINT_TO_FP. 7005 if (DAG.SignBitIsZero(N0)) 7006 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0); 7007 } 7008 7009 // The next optimizations are desirable only if SELECT_CC can be lowered. 7010 // Check against MVT::Other for SELECT_CC, which is a workaround for targets 7011 // having to say they don't support SELECT_CC on every type the DAG knows 7012 // about, since there is no way to mark an opcode illegal at all value types 7013 // (See also visitSELECT) 7014 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other)) { 7015 // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc) 7016 7017 if (N0.getOpcode() == ISD::SETCC && !VT.isVector() && 7018 (!LegalOperations || 7019 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) { 7020 SDValue Ops[] = 7021 { N0.getOperand(0), N0.getOperand(1), 7022 DAG.getConstantFP(1.0, VT), DAG.getConstantFP(0.0, VT), 7023 N0.getOperand(2) }; 7024 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops, 5); 7025 } 7026 } 7027 7028 return SDValue(); 7029 } 7030 7031 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) { 7032 SDValue N0 = N->getOperand(0); 7033 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 7034 EVT VT = N->getValueType(0); 7035 7036 // fold (fp_to_sint c1fp) -> c1 7037 if (N0CFP) 7038 return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0); 7039 7040 return SDValue(); 7041 } 7042 7043 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) { 7044 SDValue N0 = N->getOperand(0); 7045 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 7046 EVT VT = N->getValueType(0); 7047 7048 // fold (fp_to_uint c1fp) -> c1 7049 if (N0CFP) 7050 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0); 7051 7052 return SDValue(); 7053 } 7054 7055 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) { 7056 SDValue N0 = N->getOperand(0); 7057 SDValue N1 = N->getOperand(1); 7058 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 7059 EVT VT = N->getValueType(0); 7060 7061 // fold (fp_round c1fp) -> c1fp 7062 if (N0CFP) 7063 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1); 7064 7065 // fold (fp_round (fp_extend x)) -> x 7066 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType()) 7067 return N0.getOperand(0); 7068 7069 // fold (fp_round (fp_round x)) -> (fp_round x) 7070 if (N0.getOpcode() == ISD::FP_ROUND) { 7071 // This is a value preserving truncation if both round's are. 7072 bool IsTrunc = N->getConstantOperandVal(1) == 1 && 7073 N0.getNode()->getConstantOperandVal(1) == 1; 7074 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0.getOperand(0), 7075 DAG.getIntPtrConstant(IsTrunc)); 7076 } 7077 7078 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y) 7079 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) { 7080 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT, 7081 N0.getOperand(0), N1); 7082 AddToWorkList(Tmp.getNode()); 7083 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, 7084 Tmp, N0.getOperand(1)); 7085 } 7086 7087 return SDValue(); 7088 } 7089 7090 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) { 7091 SDValue N0 = N->getOperand(0); 7092 EVT VT = N->getValueType(0); 7093 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT(); 7094 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 7095 7096 // fold (fp_round_inreg c1fp) -> c1fp 7097 if (N0CFP && isTypeLegal(EVT)) { 7098 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT); 7099 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, Round); 7100 } 7101 7102 return SDValue(); 7103 } 7104 7105 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) { 7106 SDValue N0 = N->getOperand(0); 7107 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 7108 EVT VT = N->getValueType(0); 7109 7110 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded. 7111 if (N->hasOneUse() && 7112 N->use_begin()->getOpcode() == ISD::FP_ROUND) 7113 return SDValue(); 7114 7115 // fold (fp_extend c1fp) -> c1fp 7116 if (N0CFP) 7117 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0); 7118 7119 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the 7120 // value of X. 7121 if (N0.getOpcode() == ISD::FP_ROUND 7122 && N0.getNode()->getConstantOperandVal(1) == 1) { 7123 SDValue In = N0.getOperand(0); 7124 if (In.getValueType() == VT) return In; 7125 if (VT.bitsLT(In.getValueType())) 7126 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, 7127 In, N0.getOperand(1)); 7128 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In); 7129 } 7130 7131 // fold (fpext (load x)) -> (fpext (fptrunc (extload x))) 7132 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() && 7133 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) || 7134 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) { 7135 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 7136 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT, 7137 LN0->getChain(), 7138 LN0->getBasePtr(), N0.getValueType(), 7139 LN0->getMemOperand()); 7140 CombineTo(N, ExtLoad); 7141 CombineTo(N0.getNode(), 7142 DAG.getNode(ISD::FP_ROUND, SDLoc(N0), 7143 N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)), 7144 ExtLoad.getValue(1)); 7145 return SDValue(N, 0); // Return N so it doesn't get rechecked! 7146 } 7147 7148 return SDValue(); 7149 } 7150 7151 SDValue DAGCombiner::visitFNEG(SDNode *N) { 7152 SDValue N0 = N->getOperand(0); 7153 EVT VT = N->getValueType(0); 7154 7155 if (VT.isVector()) { 7156 SDValue FoldedVOp = SimplifyVUnaryOp(N); 7157 if (FoldedVOp.getNode()) return FoldedVOp; 7158 } 7159 7160 if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(), 7161 &DAG.getTarget().Options)) 7162 return GetNegatedExpression(N0, DAG, LegalOperations); 7163 7164 // Transform fneg(bitconvert(x)) -> bitconvert(x^sign) to avoid loading 7165 // constant pool values. 7166 if (!TLI.isFNegFree(VT) && N0.getOpcode() == ISD::BITCAST && 7167 !VT.isVector() && 7168 N0.getNode()->hasOneUse() && 7169 N0.getOperand(0).getValueType().isInteger()) { 7170 SDValue Int = N0.getOperand(0); 7171 EVT IntVT = Int.getValueType(); 7172 if (IntVT.isInteger() && !IntVT.isVector()) { 7173 Int = DAG.getNode(ISD::XOR, SDLoc(N0), IntVT, Int, 7174 DAG.getConstant(APInt::getSignBit(IntVT.getSizeInBits()), IntVT)); 7175 AddToWorkList(Int.getNode()); 7176 return DAG.getNode(ISD::BITCAST, SDLoc(N), 7177 VT, Int); 7178 } 7179 } 7180 7181 // (fneg (fmul c, x)) -> (fmul -c, x) 7182 if (N0.getOpcode() == ISD::FMUL) { 7183 ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1)); 7184 if (CFP1) 7185 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, 7186 N0.getOperand(0), 7187 DAG.getNode(ISD::FNEG, SDLoc(N), VT, 7188 N0.getOperand(1))); 7189 } 7190 7191 return SDValue(); 7192 } 7193 7194 SDValue DAGCombiner::visitFCEIL(SDNode *N) { 7195 SDValue N0 = N->getOperand(0); 7196 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 7197 EVT VT = N->getValueType(0); 7198 7199 // fold (fceil c1) -> fceil(c1) 7200 if (N0CFP) 7201 return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0); 7202 7203 return SDValue(); 7204 } 7205 7206 SDValue DAGCombiner::visitFTRUNC(SDNode *N) { 7207 SDValue N0 = N->getOperand(0); 7208 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 7209 EVT VT = N->getValueType(0); 7210 7211 // fold (ftrunc c1) -> ftrunc(c1) 7212 if (N0CFP) 7213 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0); 7214 7215 return SDValue(); 7216 } 7217 7218 SDValue DAGCombiner::visitFFLOOR(SDNode *N) { 7219 SDValue N0 = N->getOperand(0); 7220 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 7221 EVT VT = N->getValueType(0); 7222 7223 // fold (ffloor c1) -> ffloor(c1) 7224 if (N0CFP) 7225 return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0); 7226 7227 return SDValue(); 7228 } 7229 7230 SDValue DAGCombiner::visitFABS(SDNode *N) { 7231 SDValue N0 = N->getOperand(0); 7232 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 7233 EVT VT = N->getValueType(0); 7234 7235 if (VT.isVector()) { 7236 SDValue FoldedVOp = SimplifyVUnaryOp(N); 7237 if (FoldedVOp.getNode()) return FoldedVOp; 7238 } 7239 7240 // fold (fabs c1) -> fabs(c1) 7241 if (N0CFP) 7242 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0); 7243 // fold (fabs (fabs x)) -> (fabs x) 7244 if (N0.getOpcode() == ISD::FABS) 7245 return N->getOperand(0); 7246 // fold (fabs (fneg x)) -> (fabs x) 7247 // fold (fabs (fcopysign x, y)) -> (fabs x) 7248 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN) 7249 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0)); 7250 7251 // Transform fabs(bitconvert(x)) -> bitconvert(x&~sign) to avoid loading 7252 // constant pool values. 7253 if (!TLI.isFAbsFree(VT) && 7254 N0.getOpcode() == ISD::BITCAST && N0.getNode()->hasOneUse() && 7255 N0.getOperand(0).getValueType().isInteger() && 7256 !N0.getOperand(0).getValueType().isVector()) { 7257 SDValue Int = N0.getOperand(0); 7258 EVT IntVT = Int.getValueType(); 7259 if (IntVT.isInteger() && !IntVT.isVector()) { 7260 Int = DAG.getNode(ISD::AND, SDLoc(N0), IntVT, Int, 7261 DAG.getConstant(~APInt::getSignBit(IntVT.getSizeInBits()), IntVT)); 7262 AddToWorkList(Int.getNode()); 7263 return DAG.getNode(ISD::BITCAST, SDLoc(N), 7264 N->getValueType(0), Int); 7265 } 7266 } 7267 7268 return SDValue(); 7269 } 7270 7271 SDValue DAGCombiner::visitBRCOND(SDNode *N) { 7272 SDValue Chain = N->getOperand(0); 7273 SDValue N1 = N->getOperand(1); 7274 SDValue N2 = N->getOperand(2); 7275 7276 // If N is a constant we could fold this into a fallthrough or unconditional 7277 // branch. However that doesn't happen very often in normal code, because 7278 // Instcombine/SimplifyCFG should have handled the available opportunities. 7279 // If we did this folding here, it would be necessary to update the 7280 // MachineBasicBlock CFG, which is awkward. 7281 7282 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal 7283 // on the target. 7284 if (N1.getOpcode() == ISD::SETCC && 7285 TLI.isOperationLegalOrCustom(ISD::BR_CC, 7286 N1.getOperand(0).getValueType())) { 7287 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other, 7288 Chain, N1.getOperand(2), 7289 N1.getOperand(0), N1.getOperand(1), N2); 7290 } 7291 7292 if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) || 7293 ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) && 7294 (N1.getOperand(0).hasOneUse() && 7295 N1.getOperand(0).getOpcode() == ISD::SRL))) { 7296 SDNode *Trunc = nullptr; 7297 if (N1.getOpcode() == ISD::TRUNCATE) { 7298 // Look pass the truncate. 7299 Trunc = N1.getNode(); 7300 N1 = N1.getOperand(0); 7301 } 7302 7303 // Match this pattern so that we can generate simpler code: 7304 // 7305 // %a = ... 7306 // %b = and i32 %a, 2 7307 // %c = srl i32 %b, 1 7308 // brcond i32 %c ... 7309 // 7310 // into 7311 // 7312 // %a = ... 7313 // %b = and i32 %a, 2 7314 // %c = setcc eq %b, 0 7315 // brcond %c ... 7316 // 7317 // This applies only when the AND constant value has one bit set and the 7318 // SRL constant is equal to the log2 of the AND constant. The back-end is 7319 // smart enough to convert the result into a TEST/JMP sequence. 7320 SDValue Op0 = N1.getOperand(0); 7321 SDValue Op1 = N1.getOperand(1); 7322 7323 if (Op0.getOpcode() == ISD::AND && 7324 Op1.getOpcode() == ISD::Constant) { 7325 SDValue AndOp1 = Op0.getOperand(1); 7326 7327 if (AndOp1.getOpcode() == ISD::Constant) { 7328 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue(); 7329 7330 if (AndConst.isPowerOf2() && 7331 cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) { 7332 SDValue SetCC = 7333 DAG.getSetCC(SDLoc(N), 7334 getSetCCResultType(Op0.getValueType()), 7335 Op0, DAG.getConstant(0, Op0.getValueType()), 7336 ISD::SETNE); 7337 7338 SDValue NewBRCond = DAG.getNode(ISD::BRCOND, SDLoc(N), 7339 MVT::Other, Chain, SetCC, N2); 7340 // Don't add the new BRCond into the worklist or else SimplifySelectCC 7341 // will convert it back to (X & C1) >> C2. 7342 CombineTo(N, NewBRCond, false); 7343 // Truncate is dead. 7344 if (Trunc) { 7345 removeFromWorkList(Trunc); 7346 DAG.DeleteNode(Trunc); 7347 } 7348 // Replace the uses of SRL with SETCC 7349 WorkListRemover DeadNodes(*this); 7350 DAG.ReplaceAllUsesOfValueWith(N1, SetCC); 7351 removeFromWorkList(N1.getNode()); 7352 DAG.DeleteNode(N1.getNode()); 7353 return SDValue(N, 0); // Return N so it doesn't get rechecked! 7354 } 7355 } 7356 } 7357 7358 if (Trunc) 7359 // Restore N1 if the above transformation doesn't match. 7360 N1 = N->getOperand(1); 7361 } 7362 7363 // Transform br(xor(x, y)) -> br(x != y) 7364 // Transform br(xor(xor(x,y), 1)) -> br (x == y) 7365 if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) { 7366 SDNode *TheXor = N1.getNode(); 7367 SDValue Op0 = TheXor->getOperand(0); 7368 SDValue Op1 = TheXor->getOperand(1); 7369 if (Op0.getOpcode() == Op1.getOpcode()) { 7370 // Avoid missing important xor optimizations. 7371 SDValue Tmp = visitXOR(TheXor); 7372 if (Tmp.getNode()) { 7373 if (Tmp.getNode() != TheXor) { 7374 DEBUG(dbgs() << "\nReplacing.8 "; 7375 TheXor->dump(&DAG); 7376 dbgs() << "\nWith: "; 7377 Tmp.getNode()->dump(&DAG); 7378 dbgs() << '\n'); 7379 WorkListRemover DeadNodes(*this); 7380 DAG.ReplaceAllUsesOfValueWith(N1, Tmp); 7381 removeFromWorkList(TheXor); 7382 DAG.DeleteNode(TheXor); 7383 return DAG.getNode(ISD::BRCOND, SDLoc(N), 7384 MVT::Other, Chain, Tmp, N2); 7385 } 7386 7387 // visitXOR has changed XOR's operands or replaced the XOR completely, 7388 // bail out. 7389 return SDValue(N, 0); 7390 } 7391 } 7392 7393 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) { 7394 bool Equal = false; 7395 if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0)) 7396 if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() && 7397 Op0.getOpcode() == ISD::XOR) { 7398 TheXor = Op0.getNode(); 7399 Equal = true; 7400 } 7401 7402 EVT SetCCVT = N1.getValueType(); 7403 if (LegalTypes) 7404 SetCCVT = getSetCCResultType(SetCCVT); 7405 SDValue SetCC = DAG.getSetCC(SDLoc(TheXor), 7406 SetCCVT, 7407 Op0, Op1, 7408 Equal ? ISD::SETEQ : ISD::SETNE); 7409 // Replace the uses of XOR with SETCC 7410 WorkListRemover DeadNodes(*this); 7411 DAG.ReplaceAllUsesOfValueWith(N1, SetCC); 7412 removeFromWorkList(N1.getNode()); 7413 DAG.DeleteNode(N1.getNode()); 7414 return DAG.getNode(ISD::BRCOND, SDLoc(N), 7415 MVT::Other, Chain, SetCC, N2); 7416 } 7417 } 7418 7419 return SDValue(); 7420 } 7421 7422 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB. 7423 // 7424 SDValue DAGCombiner::visitBR_CC(SDNode *N) { 7425 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1)); 7426 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3); 7427 7428 // If N is a constant we could fold this into a fallthrough or unconditional 7429 // branch. However that doesn't happen very often in normal code, because 7430 // Instcombine/SimplifyCFG should have handled the available opportunities. 7431 // If we did this folding here, it would be necessary to update the 7432 // MachineBasicBlock CFG, which is awkward. 7433 7434 // Use SimplifySetCC to simplify SETCC's. 7435 SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()), 7436 CondLHS, CondRHS, CC->get(), SDLoc(N), 7437 false); 7438 if (Simp.getNode()) AddToWorkList(Simp.getNode()); 7439 7440 // fold to a simpler setcc 7441 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC) 7442 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other, 7443 N->getOperand(0), Simp.getOperand(2), 7444 Simp.getOperand(0), Simp.getOperand(1), 7445 N->getOperand(4)); 7446 7447 return SDValue(); 7448 } 7449 7450 /// canFoldInAddressingMode - Return true if 'Use' is a load or a store that 7451 /// uses N as its base pointer and that N may be folded in the load / store 7452 /// addressing mode. 7453 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use, 7454 SelectionDAG &DAG, 7455 const TargetLowering &TLI) { 7456 EVT VT; 7457 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) { 7458 if (LD->isIndexed() || LD->getBasePtr().getNode() != N) 7459 return false; 7460 VT = Use->getValueType(0); 7461 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) { 7462 if (ST->isIndexed() || ST->getBasePtr().getNode() != N) 7463 return false; 7464 VT = ST->getValue().getValueType(); 7465 } else 7466 return false; 7467 7468 TargetLowering::AddrMode AM; 7469 if (N->getOpcode() == ISD::ADD) { 7470 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1)); 7471 if (Offset) 7472 // [reg +/- imm] 7473 AM.BaseOffs = Offset->getSExtValue(); 7474 else 7475 // [reg +/- reg] 7476 AM.Scale = 1; 7477 } else if (N->getOpcode() == ISD::SUB) { 7478 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1)); 7479 if (Offset) 7480 // [reg +/- imm] 7481 AM.BaseOffs = -Offset->getSExtValue(); 7482 else 7483 // [reg +/- reg] 7484 AM.Scale = 1; 7485 } else 7486 return false; 7487 7488 return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext())); 7489 } 7490 7491 /// CombineToPreIndexedLoadStore - Try turning a load / store into a 7492 /// pre-indexed load / store when the base pointer is an add or subtract 7493 /// and it has other uses besides the load / store. After the 7494 /// transformation, the new indexed load / store has effectively folded 7495 /// the add / subtract in and all of its other uses are redirected to the 7496 /// new load / store. 7497 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) { 7498 if (Level < AfterLegalizeDAG) 7499 return false; 7500 7501 bool isLoad = true; 7502 SDValue Ptr; 7503 EVT VT; 7504 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 7505 if (LD->isIndexed()) 7506 return false; 7507 VT = LD->getMemoryVT(); 7508 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) && 7509 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT)) 7510 return false; 7511 Ptr = LD->getBasePtr(); 7512 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 7513 if (ST->isIndexed()) 7514 return false; 7515 VT = ST->getMemoryVT(); 7516 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) && 7517 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT)) 7518 return false; 7519 Ptr = ST->getBasePtr(); 7520 isLoad = false; 7521 } else { 7522 return false; 7523 } 7524 7525 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail 7526 // out. There is no reason to make this a preinc/predec. 7527 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) || 7528 Ptr.getNode()->hasOneUse()) 7529 return false; 7530 7531 // Ask the target to do addressing mode selection. 7532 SDValue BasePtr; 7533 SDValue Offset; 7534 ISD::MemIndexedMode AM = ISD::UNINDEXED; 7535 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG)) 7536 return false; 7537 7538 // Backends without true r+i pre-indexed forms may need to pass a 7539 // constant base with a variable offset so that constant coercion 7540 // will work with the patterns in canonical form. 7541 bool Swapped = false; 7542 if (isa<ConstantSDNode>(BasePtr)) { 7543 std::swap(BasePtr, Offset); 7544 Swapped = true; 7545 } 7546 7547 // Don't create a indexed load / store with zero offset. 7548 if (isa<ConstantSDNode>(Offset) && 7549 cast<ConstantSDNode>(Offset)->isNullValue()) 7550 return false; 7551 7552 // Try turning it into a pre-indexed load / store except when: 7553 // 1) The new base ptr is a frame index. 7554 // 2) If N is a store and the new base ptr is either the same as or is a 7555 // predecessor of the value being stored. 7556 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded 7557 // that would create a cycle. 7558 // 4) All uses are load / store ops that use it as old base ptr. 7559 7560 // Check #1. Preinc'ing a frame index would require copying the stack pointer 7561 // (plus the implicit offset) to a register to preinc anyway. 7562 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr)) 7563 return false; 7564 7565 // Check #2. 7566 if (!isLoad) { 7567 SDValue Val = cast<StoreSDNode>(N)->getValue(); 7568 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode())) 7569 return false; 7570 } 7571 7572 // If the offset is a constant, there may be other adds of constants that 7573 // can be folded with this one. We should do this to avoid having to keep 7574 // a copy of the original base pointer. 7575 SmallVector<SDNode *, 16> OtherUses; 7576 if (isa<ConstantSDNode>(Offset)) 7577 for (SDNode *Use : BasePtr.getNode()->uses()) { 7578 if (Use == Ptr.getNode()) 7579 continue; 7580 7581 if (Use->isPredecessorOf(N)) 7582 continue; 7583 7584 if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) { 7585 OtherUses.clear(); 7586 break; 7587 } 7588 7589 SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1); 7590 if (Op1.getNode() == BasePtr.getNode()) 7591 std::swap(Op0, Op1); 7592 assert(Op0.getNode() == BasePtr.getNode() && 7593 "Use of ADD/SUB but not an operand"); 7594 7595 if (!isa<ConstantSDNode>(Op1)) { 7596 OtherUses.clear(); 7597 break; 7598 } 7599 7600 // FIXME: In some cases, we can be smarter about this. 7601 if (Op1.getValueType() != Offset.getValueType()) { 7602 OtherUses.clear(); 7603 break; 7604 } 7605 7606 OtherUses.push_back(Use); 7607 } 7608 7609 if (Swapped) 7610 std::swap(BasePtr, Offset); 7611 7612 // Now check for #3 and #4. 7613 bool RealUse = false; 7614 7615 // Caches for hasPredecessorHelper 7616 SmallPtrSet<const SDNode *, 32> Visited; 7617 SmallVector<const SDNode *, 16> Worklist; 7618 7619 for (SDNode *Use : Ptr.getNode()->uses()) { 7620 if (Use == N) 7621 continue; 7622 if (N->hasPredecessorHelper(Use, Visited, Worklist)) 7623 return false; 7624 7625 // If Ptr may be folded in addressing mode of other use, then it's 7626 // not profitable to do this transformation. 7627 if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI)) 7628 RealUse = true; 7629 } 7630 7631 if (!RealUse) 7632 return false; 7633 7634 SDValue Result; 7635 if (isLoad) 7636 Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N), 7637 BasePtr, Offset, AM); 7638 else 7639 Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N), 7640 BasePtr, Offset, AM); 7641 ++PreIndexedNodes; 7642 ++NodesCombined; 7643 DEBUG(dbgs() << "\nReplacing.4 "; 7644 N->dump(&DAG); 7645 dbgs() << "\nWith: "; 7646 Result.getNode()->dump(&DAG); 7647 dbgs() << '\n'); 7648 WorkListRemover DeadNodes(*this); 7649 if (isLoad) { 7650 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0)); 7651 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2)); 7652 } else { 7653 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1)); 7654 } 7655 7656 // Finally, since the node is now dead, remove it from the graph. 7657 DAG.DeleteNode(N); 7658 7659 if (Swapped) 7660 std::swap(BasePtr, Offset); 7661 7662 // Replace other uses of BasePtr that can be updated to use Ptr 7663 for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) { 7664 unsigned OffsetIdx = 1; 7665 if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode()) 7666 OffsetIdx = 0; 7667 assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() == 7668 BasePtr.getNode() && "Expected BasePtr operand"); 7669 7670 // We need to replace ptr0 in the following expression: 7671 // x0 * offset0 + y0 * ptr0 = t0 7672 // knowing that 7673 // x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store) 7674 // 7675 // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the 7676 // indexed load/store and the expresion that needs to be re-written. 7677 // 7678 // Therefore, we have: 7679 // t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1 7680 7681 ConstantSDNode *CN = 7682 cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx)); 7683 int X0, X1, Y0, Y1; 7684 APInt Offset0 = CN->getAPIntValue(); 7685 APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue(); 7686 7687 X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1; 7688 Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1; 7689 X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1; 7690 Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1; 7691 7692 unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD; 7693 7694 APInt CNV = Offset0; 7695 if (X0 < 0) CNV = -CNV; 7696 if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1; 7697 else CNV = CNV - Offset1; 7698 7699 // We can now generate the new expression. 7700 SDValue NewOp1 = DAG.getConstant(CNV, CN->getValueType(0)); 7701 SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0); 7702 7703 SDValue NewUse = DAG.getNode(Opcode, 7704 SDLoc(OtherUses[i]), 7705 OtherUses[i]->getValueType(0), NewOp1, NewOp2); 7706 DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse); 7707 removeFromWorkList(OtherUses[i]); 7708 DAG.DeleteNode(OtherUses[i]); 7709 } 7710 7711 // Replace the uses of Ptr with uses of the updated base value. 7712 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0)); 7713 removeFromWorkList(Ptr.getNode()); 7714 DAG.DeleteNode(Ptr.getNode()); 7715 7716 return true; 7717 } 7718 7719 /// CombineToPostIndexedLoadStore - Try to combine a load / store with a 7720 /// add / sub of the base pointer node into a post-indexed load / store. 7721 /// The transformation folded the add / subtract into the new indexed 7722 /// load / store effectively and all of its uses are redirected to the 7723 /// new load / store. 7724 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) { 7725 if (Level < AfterLegalizeDAG) 7726 return false; 7727 7728 bool isLoad = true; 7729 SDValue Ptr; 7730 EVT VT; 7731 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 7732 if (LD->isIndexed()) 7733 return false; 7734 VT = LD->getMemoryVT(); 7735 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) && 7736 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT)) 7737 return false; 7738 Ptr = LD->getBasePtr(); 7739 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 7740 if (ST->isIndexed()) 7741 return false; 7742 VT = ST->getMemoryVT(); 7743 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) && 7744 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT)) 7745 return false; 7746 Ptr = ST->getBasePtr(); 7747 isLoad = false; 7748 } else { 7749 return false; 7750 } 7751 7752 if (Ptr.getNode()->hasOneUse()) 7753 return false; 7754 7755 for (SDNode *Op : Ptr.getNode()->uses()) { 7756 if (Op == N || 7757 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB)) 7758 continue; 7759 7760 SDValue BasePtr; 7761 SDValue Offset; 7762 ISD::MemIndexedMode AM = ISD::UNINDEXED; 7763 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) { 7764 // Don't create a indexed load / store with zero offset. 7765 if (isa<ConstantSDNode>(Offset) && 7766 cast<ConstantSDNode>(Offset)->isNullValue()) 7767 continue; 7768 7769 // Try turning it into a post-indexed load / store except when 7770 // 1) All uses are load / store ops that use it as base ptr (and 7771 // it may be folded as addressing mmode). 7772 // 2) Op must be independent of N, i.e. Op is neither a predecessor 7773 // nor a successor of N. Otherwise, if Op is folded that would 7774 // create a cycle. 7775 7776 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr)) 7777 continue; 7778 7779 // Check for #1. 7780 bool TryNext = false; 7781 for (SDNode *Use : BasePtr.getNode()->uses()) { 7782 if (Use == Ptr.getNode()) 7783 continue; 7784 7785 // If all the uses are load / store addresses, then don't do the 7786 // transformation. 7787 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){ 7788 bool RealUse = false; 7789 for (SDNode *UseUse : Use->uses()) { 7790 if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI)) 7791 RealUse = true; 7792 } 7793 7794 if (!RealUse) { 7795 TryNext = true; 7796 break; 7797 } 7798 } 7799 } 7800 7801 if (TryNext) 7802 continue; 7803 7804 // Check for #2 7805 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) { 7806 SDValue Result = isLoad 7807 ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N), 7808 BasePtr, Offset, AM) 7809 : DAG.getIndexedStore(SDValue(N,0), SDLoc(N), 7810 BasePtr, Offset, AM); 7811 ++PostIndexedNodes; 7812 ++NodesCombined; 7813 DEBUG(dbgs() << "\nReplacing.5 "; 7814 N->dump(&DAG); 7815 dbgs() << "\nWith: "; 7816 Result.getNode()->dump(&DAG); 7817 dbgs() << '\n'); 7818 WorkListRemover DeadNodes(*this); 7819 if (isLoad) { 7820 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0)); 7821 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2)); 7822 } else { 7823 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1)); 7824 } 7825 7826 // Finally, since the node is now dead, remove it from the graph. 7827 DAG.DeleteNode(N); 7828 7829 // Replace the uses of Use with uses of the updated base value. 7830 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0), 7831 Result.getValue(isLoad ? 1 : 0)); 7832 removeFromWorkList(Op); 7833 DAG.DeleteNode(Op); 7834 return true; 7835 } 7836 } 7837 } 7838 7839 return false; 7840 } 7841 7842 SDValue DAGCombiner::visitLOAD(SDNode *N) { 7843 LoadSDNode *LD = cast<LoadSDNode>(N); 7844 SDValue Chain = LD->getChain(); 7845 SDValue Ptr = LD->getBasePtr(); 7846 7847 // If load is not volatile and there are no uses of the loaded value (and 7848 // the updated indexed value in case of indexed loads), change uses of the 7849 // chain value into uses of the chain input (i.e. delete the dead load). 7850 if (!LD->isVolatile()) { 7851 if (N->getValueType(1) == MVT::Other) { 7852 // Unindexed loads. 7853 if (!N->hasAnyUseOfValue(0)) { 7854 // It's not safe to use the two value CombineTo variant here. e.g. 7855 // v1, chain2 = load chain1, loc 7856 // v2, chain3 = load chain2, loc 7857 // v3 = add v2, c 7858 // Now we replace use of chain2 with chain1. This makes the second load 7859 // isomorphic to the one we are deleting, and thus makes this load live. 7860 DEBUG(dbgs() << "\nReplacing.6 "; 7861 N->dump(&DAG); 7862 dbgs() << "\nWith chain: "; 7863 Chain.getNode()->dump(&DAG); 7864 dbgs() << "\n"); 7865 WorkListRemover DeadNodes(*this); 7866 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain); 7867 7868 if (N->use_empty()) { 7869 removeFromWorkList(N); 7870 DAG.DeleteNode(N); 7871 } 7872 7873 return SDValue(N, 0); // Return N so it doesn't get rechecked! 7874 } 7875 } else { 7876 // Indexed loads. 7877 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?"); 7878 if (!N->hasAnyUseOfValue(0) && !N->hasAnyUseOfValue(1)) { 7879 SDValue Undef = DAG.getUNDEF(N->getValueType(0)); 7880 DEBUG(dbgs() << "\nReplacing.7 "; 7881 N->dump(&DAG); 7882 dbgs() << "\nWith: "; 7883 Undef.getNode()->dump(&DAG); 7884 dbgs() << " and 2 other values\n"); 7885 WorkListRemover DeadNodes(*this); 7886 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef); 7887 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), 7888 DAG.getUNDEF(N->getValueType(1))); 7889 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain); 7890 removeFromWorkList(N); 7891 DAG.DeleteNode(N); 7892 return SDValue(N, 0); // Return N so it doesn't get rechecked! 7893 } 7894 } 7895 } 7896 7897 // If this load is directly stored, replace the load value with the stored 7898 // value. 7899 // TODO: Handle store large -> read small portion. 7900 // TODO: Handle TRUNCSTORE/LOADEXT 7901 if (ISD::isNormalLoad(N) && !LD->isVolatile()) { 7902 if (ISD::isNON_TRUNCStore(Chain.getNode())) { 7903 StoreSDNode *PrevST = cast<StoreSDNode>(Chain); 7904 if (PrevST->getBasePtr() == Ptr && 7905 PrevST->getValue().getValueType() == N->getValueType(0)) 7906 return CombineTo(N, Chain.getOperand(1), Chain); 7907 } 7908 } 7909 7910 // Try to infer better alignment information than the load already has. 7911 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) { 7912 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) { 7913 if (Align > LD->getMemOperand()->getBaseAlignment()) { 7914 SDValue NewLoad = 7915 DAG.getExtLoad(LD->getExtensionType(), SDLoc(N), 7916 LD->getValueType(0), 7917 Chain, Ptr, LD->getPointerInfo(), 7918 LD->getMemoryVT(), 7919 LD->isVolatile(), LD->isNonTemporal(), Align, 7920 LD->getTBAAInfo()); 7921 return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true); 7922 } 7923 } 7924 } 7925 7926 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA : 7927 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA(); 7928 #ifndef NDEBUG 7929 if (CombinerAAOnlyFunc.getNumOccurrences() && 7930 CombinerAAOnlyFunc != DAG.getMachineFunction().getName()) 7931 UseAA = false; 7932 #endif 7933 if (UseAA && LD->isUnindexed()) { 7934 // Walk up chain skipping non-aliasing memory nodes. 7935 SDValue BetterChain = FindBetterChain(N, Chain); 7936 7937 // If there is a better chain. 7938 if (Chain != BetterChain) { 7939 SDValue ReplLoad; 7940 7941 // Replace the chain to void dependency. 7942 if (LD->getExtensionType() == ISD::NON_EXTLOAD) { 7943 ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD), 7944 BetterChain, Ptr, LD->getMemOperand()); 7945 } else { 7946 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), 7947 LD->getValueType(0), 7948 BetterChain, Ptr, LD->getMemoryVT(), 7949 LD->getMemOperand()); 7950 } 7951 7952 // Create token factor to keep old chain connected. 7953 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N), 7954 MVT::Other, Chain, ReplLoad.getValue(1)); 7955 7956 // Make sure the new and old chains are cleaned up. 7957 AddToWorkList(Token.getNode()); 7958 7959 // Replace uses with load result and token factor. Don't add users 7960 // to work list. 7961 return CombineTo(N, ReplLoad.getValue(0), Token, false); 7962 } 7963 } 7964 7965 // Try transforming N to an indexed load. 7966 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N)) 7967 return SDValue(N, 0); 7968 7969 // Try to slice up N to more direct loads if the slices are mapped to 7970 // different register banks or pairing can take place. 7971 if (SliceUpLoad(N)) 7972 return SDValue(N, 0); 7973 7974 return SDValue(); 7975 } 7976 7977 namespace { 7978 /// \brief Helper structure used to slice a load in smaller loads. 7979 /// Basically a slice is obtained from the following sequence: 7980 /// Origin = load Ty1, Base 7981 /// Shift = srl Ty1 Origin, CstTy Amount 7982 /// Inst = trunc Shift to Ty2 7983 /// 7984 /// Then, it will be rewriten into: 7985 /// Slice = load SliceTy, Base + SliceOffset 7986 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2 7987 /// 7988 /// SliceTy is deduced from the number of bits that are actually used to 7989 /// build Inst. 7990 struct LoadedSlice { 7991 /// \brief Helper structure used to compute the cost of a slice. 7992 struct Cost { 7993 /// Are we optimizing for code size. 7994 bool ForCodeSize; 7995 /// Various cost. 7996 unsigned Loads; 7997 unsigned Truncates; 7998 unsigned CrossRegisterBanksCopies; 7999 unsigned ZExts; 8000 unsigned Shift; 8001 8002 Cost(bool ForCodeSize = false) 8003 : ForCodeSize(ForCodeSize), Loads(0), Truncates(0), 8004 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {} 8005 8006 /// \brief Get the cost of one isolated slice. 8007 Cost(const LoadedSlice &LS, bool ForCodeSize = false) 8008 : ForCodeSize(ForCodeSize), Loads(1), Truncates(0), 8009 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) { 8010 EVT TruncType = LS.Inst->getValueType(0); 8011 EVT LoadedType = LS.getLoadedType(); 8012 if (TruncType != LoadedType && 8013 !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType)) 8014 ZExts = 1; 8015 } 8016 8017 /// \brief Account for slicing gain in the current cost. 8018 /// Slicing provide a few gains like removing a shift or a 8019 /// truncate. This method allows to grow the cost of the original 8020 /// load with the gain from this slice. 8021 void addSliceGain(const LoadedSlice &LS) { 8022 // Each slice saves a truncate. 8023 const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo(); 8024 if (!TLI.isTruncateFree(LS.Inst->getValueType(0), 8025 LS.Inst->getOperand(0).getValueType())) 8026 ++Truncates; 8027 // If there is a shift amount, this slice gets rid of it. 8028 if (LS.Shift) 8029 ++Shift; 8030 // If this slice can merge a cross register bank copy, account for it. 8031 if (LS.canMergeExpensiveCrossRegisterBankCopy()) 8032 ++CrossRegisterBanksCopies; 8033 } 8034 8035 Cost &operator+=(const Cost &RHS) { 8036 Loads += RHS.Loads; 8037 Truncates += RHS.Truncates; 8038 CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies; 8039 ZExts += RHS.ZExts; 8040 Shift += RHS.Shift; 8041 return *this; 8042 } 8043 8044 bool operator==(const Cost &RHS) const { 8045 return Loads == RHS.Loads && Truncates == RHS.Truncates && 8046 CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies && 8047 ZExts == RHS.ZExts && Shift == RHS.Shift; 8048 } 8049 8050 bool operator!=(const Cost &RHS) const { return !(*this == RHS); } 8051 8052 bool operator<(const Cost &RHS) const { 8053 // Assume cross register banks copies are as expensive as loads. 8054 // FIXME: Do we want some more target hooks? 8055 unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies; 8056 unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies; 8057 // Unless we are optimizing for code size, consider the 8058 // expensive operation first. 8059 if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS) 8060 return ExpensiveOpsLHS < ExpensiveOpsRHS; 8061 return (Truncates + ZExts + Shift + ExpensiveOpsLHS) < 8062 (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS); 8063 } 8064 8065 bool operator>(const Cost &RHS) const { return RHS < *this; } 8066 8067 bool operator<=(const Cost &RHS) const { return !(RHS < *this); } 8068 8069 bool operator>=(const Cost &RHS) const { return !(*this < RHS); } 8070 }; 8071 // The last instruction that represent the slice. This should be a 8072 // truncate instruction. 8073 SDNode *Inst; 8074 // The original load instruction. 8075 LoadSDNode *Origin; 8076 // The right shift amount in bits from the original load. 8077 unsigned Shift; 8078 // The DAG from which Origin came from. 8079 // This is used to get some contextual information about legal types, etc. 8080 SelectionDAG *DAG; 8081 8082 LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr, 8083 unsigned Shift = 0, SelectionDAG *DAG = nullptr) 8084 : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {} 8085 8086 LoadedSlice(const LoadedSlice &LS) 8087 : Inst(LS.Inst), Origin(LS.Origin), Shift(LS.Shift), DAG(LS.DAG) {} 8088 8089 /// \brief Get the bits used in a chunk of bits \p BitWidth large. 8090 /// \return Result is \p BitWidth and has used bits set to 1 and 8091 /// not used bits set to 0. 8092 APInt getUsedBits() const { 8093 // Reproduce the trunc(lshr) sequence: 8094 // - Start from the truncated value. 8095 // - Zero extend to the desired bit width. 8096 // - Shift left. 8097 assert(Origin && "No original load to compare against."); 8098 unsigned BitWidth = Origin->getValueSizeInBits(0); 8099 assert(Inst && "This slice is not bound to an instruction"); 8100 assert(Inst->getValueSizeInBits(0) <= BitWidth && 8101 "Extracted slice is bigger than the whole type!"); 8102 APInt UsedBits(Inst->getValueSizeInBits(0), 0); 8103 UsedBits.setAllBits(); 8104 UsedBits = UsedBits.zext(BitWidth); 8105 UsedBits <<= Shift; 8106 return UsedBits; 8107 } 8108 8109 /// \brief Get the size of the slice to be loaded in bytes. 8110 unsigned getLoadedSize() const { 8111 unsigned SliceSize = getUsedBits().countPopulation(); 8112 assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte."); 8113 return SliceSize / 8; 8114 } 8115 8116 /// \brief Get the type that will be loaded for this slice. 8117 /// Note: This may not be the final type for the slice. 8118 EVT getLoadedType() const { 8119 assert(DAG && "Missing context"); 8120 LLVMContext &Ctxt = *DAG->getContext(); 8121 return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8); 8122 } 8123 8124 /// \brief Get the alignment of the load used for this slice. 8125 unsigned getAlignment() const { 8126 unsigned Alignment = Origin->getAlignment(); 8127 unsigned Offset = getOffsetFromBase(); 8128 if (Offset != 0) 8129 Alignment = MinAlign(Alignment, Alignment + Offset); 8130 return Alignment; 8131 } 8132 8133 /// \brief Check if this slice can be rewritten with legal operations. 8134 bool isLegal() const { 8135 // An invalid slice is not legal. 8136 if (!Origin || !Inst || !DAG) 8137 return false; 8138 8139 // Offsets are for indexed load only, we do not handle that. 8140 if (Origin->getOffset().getOpcode() != ISD::UNDEF) 8141 return false; 8142 8143 const TargetLowering &TLI = DAG->getTargetLoweringInfo(); 8144 8145 // Check that the type is legal. 8146 EVT SliceType = getLoadedType(); 8147 if (!TLI.isTypeLegal(SliceType)) 8148 return false; 8149 8150 // Check that the load is legal for this type. 8151 if (!TLI.isOperationLegal(ISD::LOAD, SliceType)) 8152 return false; 8153 8154 // Check that the offset can be computed. 8155 // 1. Check its type. 8156 EVT PtrType = Origin->getBasePtr().getValueType(); 8157 if (PtrType == MVT::Untyped || PtrType.isExtended()) 8158 return false; 8159 8160 // 2. Check that it fits in the immediate. 8161 if (!TLI.isLegalAddImmediate(getOffsetFromBase())) 8162 return false; 8163 8164 // 3. Check that the computation is legal. 8165 if (!TLI.isOperationLegal(ISD::ADD, PtrType)) 8166 return false; 8167 8168 // Check that the zext is legal if it needs one. 8169 EVT TruncateType = Inst->getValueType(0); 8170 if (TruncateType != SliceType && 8171 !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType)) 8172 return false; 8173 8174 return true; 8175 } 8176 8177 /// \brief Get the offset in bytes of this slice in the original chunk of 8178 /// bits. 8179 /// \pre DAG != nullptr. 8180 uint64_t getOffsetFromBase() const { 8181 assert(DAG && "Missing context."); 8182 bool IsBigEndian = 8183 DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian(); 8184 assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported."); 8185 uint64_t Offset = Shift / 8; 8186 unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8; 8187 assert(!(Origin->getValueSizeInBits(0) & 0x7) && 8188 "The size of the original loaded type is not a multiple of a" 8189 " byte."); 8190 // If Offset is bigger than TySizeInBytes, it means we are loading all 8191 // zeros. This should have been optimized before in the process. 8192 assert(TySizeInBytes > Offset && 8193 "Invalid shift amount for given loaded size"); 8194 if (IsBigEndian) 8195 Offset = TySizeInBytes - Offset - getLoadedSize(); 8196 return Offset; 8197 } 8198 8199 /// \brief Generate the sequence of instructions to load the slice 8200 /// represented by this object and redirect the uses of this slice to 8201 /// this new sequence of instructions. 8202 /// \pre this->Inst && this->Origin are valid Instructions and this 8203 /// object passed the legal check: LoadedSlice::isLegal returned true. 8204 /// \return The last instruction of the sequence used to load the slice. 8205 SDValue loadSlice() const { 8206 assert(Inst && Origin && "Unable to replace a non-existing slice."); 8207 const SDValue &OldBaseAddr = Origin->getBasePtr(); 8208 SDValue BaseAddr = OldBaseAddr; 8209 // Get the offset in that chunk of bytes w.r.t. the endianess. 8210 int64_t Offset = static_cast<int64_t>(getOffsetFromBase()); 8211 assert(Offset >= 0 && "Offset too big to fit in int64_t!"); 8212 if (Offset) { 8213 // BaseAddr = BaseAddr + Offset. 8214 EVT ArithType = BaseAddr.getValueType(); 8215 BaseAddr = DAG->getNode(ISD::ADD, SDLoc(Origin), ArithType, BaseAddr, 8216 DAG->getConstant(Offset, ArithType)); 8217 } 8218 8219 // Create the type of the loaded slice according to its size. 8220 EVT SliceType = getLoadedType(); 8221 8222 // Create the load for the slice. 8223 SDValue LastInst = DAG->getLoad( 8224 SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr, 8225 Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(), 8226 Origin->isNonTemporal(), Origin->isInvariant(), getAlignment()); 8227 // If the final type is not the same as the loaded type, this means that 8228 // we have to pad with zero. Create a zero extend for that. 8229 EVT FinalType = Inst->getValueType(0); 8230 if (SliceType != FinalType) 8231 LastInst = 8232 DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst); 8233 return LastInst; 8234 } 8235 8236 /// \brief Check if this slice can be merged with an expensive cross register 8237 /// bank copy. E.g., 8238 /// i = load i32 8239 /// f = bitcast i32 i to float 8240 bool canMergeExpensiveCrossRegisterBankCopy() const { 8241 if (!Inst || !Inst->hasOneUse()) 8242 return false; 8243 SDNode *Use = *Inst->use_begin(); 8244 if (Use->getOpcode() != ISD::BITCAST) 8245 return false; 8246 assert(DAG && "Missing context"); 8247 const TargetLowering &TLI = DAG->getTargetLoweringInfo(); 8248 EVT ResVT = Use->getValueType(0); 8249 const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT()); 8250 const TargetRegisterClass *ArgRC = 8251 TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT()); 8252 if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT)) 8253 return false; 8254 8255 // At this point, we know that we perform a cross-register-bank copy. 8256 // Check if it is expensive. 8257 const TargetRegisterInfo *TRI = TLI.getTargetMachine().getRegisterInfo(); 8258 // Assume bitcasts are cheap, unless both register classes do not 8259 // explicitly share a common sub class. 8260 if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC)) 8261 return false; 8262 8263 // Check if it will be merged with the load. 8264 // 1. Check the alignment constraint. 8265 unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment( 8266 ResVT.getTypeForEVT(*DAG->getContext())); 8267 8268 if (RequiredAlignment > getAlignment()) 8269 return false; 8270 8271 // 2. Check that the load is a legal operation for that type. 8272 if (!TLI.isOperationLegal(ISD::LOAD, ResVT)) 8273 return false; 8274 8275 // 3. Check that we do not have a zext in the way. 8276 if (Inst->getValueType(0) != getLoadedType()) 8277 return false; 8278 8279 return true; 8280 } 8281 }; 8282 } 8283 8284 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e., 8285 /// \p UsedBits looks like 0..0 1..1 0..0. 8286 static bool areUsedBitsDense(const APInt &UsedBits) { 8287 // If all the bits are one, this is dense! 8288 if (UsedBits.isAllOnesValue()) 8289 return true; 8290 8291 // Get rid of the unused bits on the right. 8292 APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros()); 8293 // Get rid of the unused bits on the left. 8294 if (NarrowedUsedBits.countLeadingZeros()) 8295 NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits()); 8296 // Check that the chunk of bits is completely used. 8297 return NarrowedUsedBits.isAllOnesValue(); 8298 } 8299 8300 /// \brief Check whether or not \p First and \p Second are next to each other 8301 /// in memory. This means that there is no hole between the bits loaded 8302 /// by \p First and the bits loaded by \p Second. 8303 static bool areSlicesNextToEachOther(const LoadedSlice &First, 8304 const LoadedSlice &Second) { 8305 assert(First.Origin == Second.Origin && First.Origin && 8306 "Unable to match different memory origins."); 8307 APInt UsedBits = First.getUsedBits(); 8308 assert((UsedBits & Second.getUsedBits()) == 0 && 8309 "Slices are not supposed to overlap."); 8310 UsedBits |= Second.getUsedBits(); 8311 return areUsedBitsDense(UsedBits); 8312 } 8313 8314 /// \brief Adjust the \p GlobalLSCost according to the target 8315 /// paring capabilities and the layout of the slices. 8316 /// \pre \p GlobalLSCost should account for at least as many loads as 8317 /// there is in the slices in \p LoadedSlices. 8318 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices, 8319 LoadedSlice::Cost &GlobalLSCost) { 8320 unsigned NumberOfSlices = LoadedSlices.size(); 8321 // If there is less than 2 elements, no pairing is possible. 8322 if (NumberOfSlices < 2) 8323 return; 8324 8325 // Sort the slices so that elements that are likely to be next to each 8326 // other in memory are next to each other in the list. 8327 std::sort(LoadedSlices.begin(), LoadedSlices.end(), 8328 [](const LoadedSlice &LHS, const LoadedSlice &RHS) { 8329 assert(LHS.Origin == RHS.Origin && "Different bases not implemented."); 8330 return LHS.getOffsetFromBase() < RHS.getOffsetFromBase(); 8331 }); 8332 const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo(); 8333 // First (resp. Second) is the first (resp. Second) potentially candidate 8334 // to be placed in a paired load. 8335 const LoadedSlice *First = nullptr; 8336 const LoadedSlice *Second = nullptr; 8337 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice, 8338 // Set the beginning of the pair. 8339 First = Second) { 8340 8341 Second = &LoadedSlices[CurrSlice]; 8342 8343 // If First is NULL, it means we start a new pair. 8344 // Get to the next slice. 8345 if (!First) 8346 continue; 8347 8348 EVT LoadedType = First->getLoadedType(); 8349 8350 // If the types of the slices are different, we cannot pair them. 8351 if (LoadedType != Second->getLoadedType()) 8352 continue; 8353 8354 // Check if the target supplies paired loads for this type. 8355 unsigned RequiredAlignment = 0; 8356 if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) { 8357 // move to the next pair, this type is hopeless. 8358 Second = nullptr; 8359 continue; 8360 } 8361 // Check if we meet the alignment requirement. 8362 if (RequiredAlignment > First->getAlignment()) 8363 continue; 8364 8365 // Check that both loads are next to each other in memory. 8366 if (!areSlicesNextToEachOther(*First, *Second)) 8367 continue; 8368 8369 assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!"); 8370 --GlobalLSCost.Loads; 8371 // Move to the next pair. 8372 Second = nullptr; 8373 } 8374 } 8375 8376 /// \brief Check the profitability of all involved LoadedSlice. 8377 /// Currently, it is considered profitable if there is exactly two 8378 /// involved slices (1) which are (2) next to each other in memory, and 8379 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3). 8380 /// 8381 /// Note: The order of the elements in \p LoadedSlices may be modified, but not 8382 /// the elements themselves. 8383 /// 8384 /// FIXME: When the cost model will be mature enough, we can relax 8385 /// constraints (1) and (2). 8386 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices, 8387 const APInt &UsedBits, bool ForCodeSize) { 8388 unsigned NumberOfSlices = LoadedSlices.size(); 8389 if (StressLoadSlicing) 8390 return NumberOfSlices > 1; 8391 8392 // Check (1). 8393 if (NumberOfSlices != 2) 8394 return false; 8395 8396 // Check (2). 8397 if (!areUsedBitsDense(UsedBits)) 8398 return false; 8399 8400 // Check (3). 8401 LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize); 8402 // The original code has one big load. 8403 OrigCost.Loads = 1; 8404 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) { 8405 const LoadedSlice &LS = LoadedSlices[CurrSlice]; 8406 // Accumulate the cost of all the slices. 8407 LoadedSlice::Cost SliceCost(LS, ForCodeSize); 8408 GlobalSlicingCost += SliceCost; 8409 8410 // Account as cost in the original configuration the gain obtained 8411 // with the current slices. 8412 OrigCost.addSliceGain(LS); 8413 } 8414 8415 // If the target supports paired load, adjust the cost accordingly. 8416 adjustCostForPairing(LoadedSlices, GlobalSlicingCost); 8417 return OrigCost > GlobalSlicingCost; 8418 } 8419 8420 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr) 8421 /// operations, split it in the various pieces being extracted. 8422 /// 8423 /// This sort of thing is introduced by SROA. 8424 /// This slicing takes care not to insert overlapping loads. 8425 /// \pre LI is a simple load (i.e., not an atomic or volatile load). 8426 bool DAGCombiner::SliceUpLoad(SDNode *N) { 8427 if (Level < AfterLegalizeDAG) 8428 return false; 8429 8430 LoadSDNode *LD = cast<LoadSDNode>(N); 8431 if (LD->isVolatile() || !ISD::isNormalLoad(LD) || 8432 !LD->getValueType(0).isInteger()) 8433 return false; 8434 8435 // Keep track of already used bits to detect overlapping values. 8436 // In that case, we will just abort the transformation. 8437 APInt UsedBits(LD->getValueSizeInBits(0), 0); 8438 8439 SmallVector<LoadedSlice, 4> LoadedSlices; 8440 8441 // Check if this load is used as several smaller chunks of bits. 8442 // Basically, look for uses in trunc or trunc(lshr) and record a new chain 8443 // of computation for each trunc. 8444 for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end(); 8445 UI != UIEnd; ++UI) { 8446 // Skip the uses of the chain. 8447 if (UI.getUse().getResNo() != 0) 8448 continue; 8449 8450 SDNode *User = *UI; 8451 unsigned Shift = 0; 8452 8453 // Check if this is a trunc(lshr). 8454 if (User->getOpcode() == ISD::SRL && User->hasOneUse() && 8455 isa<ConstantSDNode>(User->getOperand(1))) { 8456 Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue(); 8457 User = *User->use_begin(); 8458 } 8459 8460 // At this point, User is a Truncate, iff we encountered, trunc or 8461 // trunc(lshr). 8462 if (User->getOpcode() != ISD::TRUNCATE) 8463 return false; 8464 8465 // The width of the type must be a power of 2 and greater than 8-bits. 8466 // Otherwise the load cannot be represented in LLVM IR. 8467 // Moreover, if we shifted with a non-8-bits multiple, the slice 8468 // will be across several bytes. We do not support that. 8469 unsigned Width = User->getValueSizeInBits(0); 8470 if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7)) 8471 return 0; 8472 8473 // Build the slice for this chain of computations. 8474 LoadedSlice LS(User, LD, Shift, &DAG); 8475 APInt CurrentUsedBits = LS.getUsedBits(); 8476 8477 // Check if this slice overlaps with another. 8478 if ((CurrentUsedBits & UsedBits) != 0) 8479 return false; 8480 // Update the bits used globally. 8481 UsedBits |= CurrentUsedBits; 8482 8483 // Check if the new slice would be legal. 8484 if (!LS.isLegal()) 8485 return false; 8486 8487 // Record the slice. 8488 LoadedSlices.push_back(LS); 8489 } 8490 8491 // Abort slicing if it does not seem to be profitable. 8492 if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize)) 8493 return false; 8494 8495 ++SlicedLoads; 8496 8497 // Rewrite each chain to use an independent load. 8498 // By construction, each chain can be represented by a unique load. 8499 8500 // Prepare the argument for the new token factor for all the slices. 8501 SmallVector<SDValue, 8> ArgChains; 8502 for (SmallVectorImpl<LoadedSlice>::const_iterator 8503 LSIt = LoadedSlices.begin(), 8504 LSItEnd = LoadedSlices.end(); 8505 LSIt != LSItEnd; ++LSIt) { 8506 SDValue SliceInst = LSIt->loadSlice(); 8507 CombineTo(LSIt->Inst, SliceInst, true); 8508 if (SliceInst.getNode()->getOpcode() != ISD::LOAD) 8509 SliceInst = SliceInst.getOperand(0); 8510 assert(SliceInst->getOpcode() == ISD::LOAD && 8511 "It takes more than a zext to get to the loaded slice!!"); 8512 ArgChains.push_back(SliceInst.getValue(1)); 8513 } 8514 8515 SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other, 8516 &ArgChains[0], ArgChains.size()); 8517 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain); 8518 return true; 8519 } 8520 8521 /// CheckForMaskedLoad - Check to see if V is (and load (ptr), imm), where the 8522 /// load is having specific bytes cleared out. If so, return the byte size 8523 /// being masked out and the shift amount. 8524 static std::pair<unsigned, unsigned> 8525 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) { 8526 std::pair<unsigned, unsigned> Result(0, 0); 8527 8528 // Check for the structure we're looking for. 8529 if (V->getOpcode() != ISD::AND || 8530 !isa<ConstantSDNode>(V->getOperand(1)) || 8531 !ISD::isNormalLoad(V->getOperand(0).getNode())) 8532 return Result; 8533 8534 // Check the chain and pointer. 8535 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0)); 8536 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer. 8537 8538 // The store should be chained directly to the load or be an operand of a 8539 // tokenfactor. 8540 if (LD == Chain.getNode()) 8541 ; // ok. 8542 else if (Chain->getOpcode() != ISD::TokenFactor) 8543 return Result; // Fail. 8544 else { 8545 bool isOk = false; 8546 for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i) 8547 if (Chain->getOperand(i).getNode() == LD) { 8548 isOk = true; 8549 break; 8550 } 8551 if (!isOk) return Result; 8552 } 8553 8554 // This only handles simple types. 8555 if (V.getValueType() != MVT::i16 && 8556 V.getValueType() != MVT::i32 && 8557 V.getValueType() != MVT::i64) 8558 return Result; 8559 8560 // Check the constant mask. Invert it so that the bits being masked out are 8561 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits 8562 // follow the sign bit for uniformity. 8563 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue(); 8564 unsigned NotMaskLZ = countLeadingZeros(NotMask); 8565 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte. 8566 unsigned NotMaskTZ = countTrailingZeros(NotMask); 8567 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte. 8568 if (NotMaskLZ == 64) return Result; // All zero mask. 8569 8570 // See if we have a continuous run of bits. If so, we have 0*1+0* 8571 if (CountTrailingOnes_64(NotMask >> NotMaskTZ)+NotMaskTZ+NotMaskLZ != 64) 8572 return Result; 8573 8574 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64. 8575 if (V.getValueType() != MVT::i64 && NotMaskLZ) 8576 NotMaskLZ -= 64-V.getValueSizeInBits(); 8577 8578 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8; 8579 switch (MaskedBytes) { 8580 case 1: 8581 case 2: 8582 case 4: break; 8583 default: return Result; // All one mask, or 5-byte mask. 8584 } 8585 8586 // Verify that the first bit starts at a multiple of mask so that the access 8587 // is aligned the same as the access width. 8588 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result; 8589 8590 Result.first = MaskedBytes; 8591 Result.second = NotMaskTZ/8; 8592 return Result; 8593 } 8594 8595 8596 /// ShrinkLoadReplaceStoreWithStore - Check to see if IVal is something that 8597 /// provides a value as specified by MaskInfo. If so, replace the specified 8598 /// store with a narrower store of truncated IVal. 8599 static SDNode * 8600 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo, 8601 SDValue IVal, StoreSDNode *St, 8602 DAGCombiner *DC) { 8603 unsigned NumBytes = MaskInfo.first; 8604 unsigned ByteShift = MaskInfo.second; 8605 SelectionDAG &DAG = DC->getDAG(); 8606 8607 // Check to see if IVal is all zeros in the part being masked in by the 'or' 8608 // that uses this. If not, this is not a replacement. 8609 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(), 8610 ByteShift*8, (ByteShift+NumBytes)*8); 8611 if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr; 8612 8613 // Check that it is legal on the target to do this. It is legal if the new 8614 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type 8615 // legalization. 8616 MVT VT = MVT::getIntegerVT(NumBytes*8); 8617 if (!DC->isTypeLegal(VT)) 8618 return nullptr; 8619 8620 // Okay, we can do this! Replace the 'St' store with a store of IVal that is 8621 // shifted by ByteShift and truncated down to NumBytes. 8622 if (ByteShift) 8623 IVal = DAG.getNode(ISD::SRL, SDLoc(IVal), IVal.getValueType(), IVal, 8624 DAG.getConstant(ByteShift*8, 8625 DC->getShiftAmountTy(IVal.getValueType()))); 8626 8627 // Figure out the offset for the store and the alignment of the access. 8628 unsigned StOffset; 8629 unsigned NewAlign = St->getAlignment(); 8630 8631 if (DAG.getTargetLoweringInfo().isLittleEndian()) 8632 StOffset = ByteShift; 8633 else 8634 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes; 8635 8636 SDValue Ptr = St->getBasePtr(); 8637 if (StOffset) { 8638 Ptr = DAG.getNode(ISD::ADD, SDLoc(IVal), Ptr.getValueType(), 8639 Ptr, DAG.getConstant(StOffset, Ptr.getValueType())); 8640 NewAlign = MinAlign(NewAlign, StOffset); 8641 } 8642 8643 // Truncate down to the new size. 8644 IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal); 8645 8646 ++OpsNarrowed; 8647 return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr, 8648 St->getPointerInfo().getWithOffset(StOffset), 8649 false, false, NewAlign).getNode(); 8650 } 8651 8652 8653 /// ReduceLoadOpStoreWidth - Look for sequence of load / op / store where op is 8654 /// one of 'or', 'xor', and 'and' of immediates. If 'op' is only touching some 8655 /// of the loaded bits, try narrowing the load and store if it would end up 8656 /// being a win for performance or code size. 8657 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) { 8658 StoreSDNode *ST = cast<StoreSDNode>(N); 8659 if (ST->isVolatile()) 8660 return SDValue(); 8661 8662 SDValue Chain = ST->getChain(); 8663 SDValue Value = ST->getValue(); 8664 SDValue Ptr = ST->getBasePtr(); 8665 EVT VT = Value.getValueType(); 8666 8667 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse()) 8668 return SDValue(); 8669 8670 unsigned Opc = Value.getOpcode(); 8671 8672 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst 8673 // is a byte mask indicating a consecutive number of bytes, check to see if 8674 // Y is known to provide just those bytes. If so, we try to replace the 8675 // load + replace + store sequence with a single (narrower) store, which makes 8676 // the load dead. 8677 if (Opc == ISD::OR) { 8678 std::pair<unsigned, unsigned> MaskedLoad; 8679 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain); 8680 if (MaskedLoad.first) 8681 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad, 8682 Value.getOperand(1), ST,this)) 8683 return SDValue(NewST, 0); 8684 8685 // Or is commutative, so try swapping X and Y. 8686 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain); 8687 if (MaskedLoad.first) 8688 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad, 8689 Value.getOperand(0), ST,this)) 8690 return SDValue(NewST, 0); 8691 } 8692 8693 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) || 8694 Value.getOperand(1).getOpcode() != ISD::Constant) 8695 return SDValue(); 8696 8697 SDValue N0 = Value.getOperand(0); 8698 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() && 8699 Chain == SDValue(N0.getNode(), 1)) { 8700 LoadSDNode *LD = cast<LoadSDNode>(N0); 8701 if (LD->getBasePtr() != Ptr || 8702 LD->getPointerInfo().getAddrSpace() != 8703 ST->getPointerInfo().getAddrSpace()) 8704 return SDValue(); 8705 8706 // Find the type to narrow it the load / op / store to. 8707 SDValue N1 = Value.getOperand(1); 8708 unsigned BitWidth = N1.getValueSizeInBits(); 8709 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue(); 8710 if (Opc == ISD::AND) 8711 Imm ^= APInt::getAllOnesValue(BitWidth); 8712 if (Imm == 0 || Imm.isAllOnesValue()) 8713 return SDValue(); 8714 unsigned ShAmt = Imm.countTrailingZeros(); 8715 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1; 8716 unsigned NewBW = NextPowerOf2(MSB - ShAmt); 8717 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW); 8718 while (NewBW < BitWidth && 8719 !(TLI.isOperationLegalOrCustom(Opc, NewVT) && 8720 TLI.isNarrowingProfitable(VT, NewVT))) { 8721 NewBW = NextPowerOf2(NewBW); 8722 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW); 8723 } 8724 if (NewBW >= BitWidth) 8725 return SDValue(); 8726 8727 // If the lsb changed does not start at the type bitwidth boundary, 8728 // start at the previous one. 8729 if (ShAmt % NewBW) 8730 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW; 8731 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt, 8732 std::min(BitWidth, ShAmt + NewBW)); 8733 if ((Imm & Mask) == Imm) { 8734 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW); 8735 if (Opc == ISD::AND) 8736 NewImm ^= APInt::getAllOnesValue(NewBW); 8737 uint64_t PtrOff = ShAmt / 8; 8738 // For big endian targets, we need to adjust the offset to the pointer to 8739 // load the correct bytes. 8740 if (TLI.isBigEndian()) 8741 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff; 8742 8743 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff); 8744 Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext()); 8745 if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy)) 8746 return SDValue(); 8747 8748 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD), 8749 Ptr.getValueType(), Ptr, 8750 DAG.getConstant(PtrOff, Ptr.getValueType())); 8751 SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0), 8752 LD->getChain(), NewPtr, 8753 LD->getPointerInfo().getWithOffset(PtrOff), 8754 LD->isVolatile(), LD->isNonTemporal(), 8755 LD->isInvariant(), NewAlign, 8756 LD->getTBAAInfo()); 8757 SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD, 8758 DAG.getConstant(NewImm, NewVT)); 8759 SDValue NewST = DAG.getStore(Chain, SDLoc(N), 8760 NewVal, NewPtr, 8761 ST->getPointerInfo().getWithOffset(PtrOff), 8762 false, false, NewAlign); 8763 8764 AddToWorkList(NewPtr.getNode()); 8765 AddToWorkList(NewLD.getNode()); 8766 AddToWorkList(NewVal.getNode()); 8767 WorkListRemover DeadNodes(*this); 8768 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1)); 8769 ++OpsNarrowed; 8770 return NewST; 8771 } 8772 } 8773 8774 return SDValue(); 8775 } 8776 8777 /// TransformFPLoadStorePair - For a given floating point load / store pair, 8778 /// if the load value isn't used by any other operations, then consider 8779 /// transforming the pair to integer load / store operations if the target 8780 /// deems the transformation profitable. 8781 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) { 8782 StoreSDNode *ST = cast<StoreSDNode>(N); 8783 SDValue Chain = ST->getChain(); 8784 SDValue Value = ST->getValue(); 8785 if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) && 8786 Value.hasOneUse() && 8787 Chain == SDValue(Value.getNode(), 1)) { 8788 LoadSDNode *LD = cast<LoadSDNode>(Value); 8789 EVT VT = LD->getMemoryVT(); 8790 if (!VT.isFloatingPoint() || 8791 VT != ST->getMemoryVT() || 8792 LD->isNonTemporal() || 8793 ST->isNonTemporal() || 8794 LD->getPointerInfo().getAddrSpace() != 0 || 8795 ST->getPointerInfo().getAddrSpace() != 0) 8796 return SDValue(); 8797 8798 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits()); 8799 if (!TLI.isOperationLegal(ISD::LOAD, IntVT) || 8800 !TLI.isOperationLegal(ISD::STORE, IntVT) || 8801 !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) || 8802 !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT)) 8803 return SDValue(); 8804 8805 unsigned LDAlign = LD->getAlignment(); 8806 unsigned STAlign = ST->getAlignment(); 8807 Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext()); 8808 unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy); 8809 if (LDAlign < ABIAlign || STAlign < ABIAlign) 8810 return SDValue(); 8811 8812 SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value), 8813 LD->getChain(), LD->getBasePtr(), 8814 LD->getPointerInfo(), 8815 false, false, false, LDAlign); 8816 8817 SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N), 8818 NewLD, ST->getBasePtr(), 8819 ST->getPointerInfo(), 8820 false, false, STAlign); 8821 8822 AddToWorkList(NewLD.getNode()); 8823 AddToWorkList(NewST.getNode()); 8824 WorkListRemover DeadNodes(*this); 8825 DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1)); 8826 ++LdStFP2Int; 8827 return NewST; 8828 } 8829 8830 return SDValue(); 8831 } 8832 8833 /// Helper struct to parse and store a memory address as base + index + offset. 8834 /// We ignore sign extensions when it is safe to do so. 8835 /// The following two expressions are not equivalent. To differentiate we need 8836 /// to store whether there was a sign extension involved in the index 8837 /// computation. 8838 /// (load (i64 add (i64 copyfromreg %c) 8839 /// (i64 signextend (add (i8 load %index) 8840 /// (i8 1)))) 8841 /// vs 8842 /// 8843 /// (load (i64 add (i64 copyfromreg %c) 8844 /// (i64 signextend (i32 add (i32 signextend (i8 load %index)) 8845 /// (i32 1))))) 8846 struct BaseIndexOffset { 8847 SDValue Base; 8848 SDValue Index; 8849 int64_t Offset; 8850 bool IsIndexSignExt; 8851 8852 BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {} 8853 8854 BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset, 8855 bool IsIndexSignExt) : 8856 Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {} 8857 8858 bool equalBaseIndex(const BaseIndexOffset &Other) { 8859 return Other.Base == Base && Other.Index == Index && 8860 Other.IsIndexSignExt == IsIndexSignExt; 8861 } 8862 8863 /// Parses tree in Ptr for base, index, offset addresses. 8864 static BaseIndexOffset match(SDValue Ptr) { 8865 bool IsIndexSignExt = false; 8866 8867 // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD 8868 // instruction, then it could be just the BASE or everything else we don't 8869 // know how to handle. Just use Ptr as BASE and give up. 8870 if (Ptr->getOpcode() != ISD::ADD) 8871 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt); 8872 8873 // We know that we have at least an ADD instruction. Try to pattern match 8874 // the simple case of BASE + OFFSET. 8875 if (isa<ConstantSDNode>(Ptr->getOperand(1))) { 8876 int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue(); 8877 return BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset, 8878 IsIndexSignExt); 8879 } 8880 8881 // Inside a loop the current BASE pointer is calculated using an ADD and a 8882 // MUL instruction. In this case Ptr is the actual BASE pointer. 8883 // (i64 add (i64 %array_ptr) 8884 // (i64 mul (i64 %induction_var) 8885 // (i64 %element_size))) 8886 if (Ptr->getOperand(1)->getOpcode() == ISD::MUL) 8887 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt); 8888 8889 // Look at Base + Index + Offset cases. 8890 SDValue Base = Ptr->getOperand(0); 8891 SDValue IndexOffset = Ptr->getOperand(1); 8892 8893 // Skip signextends. 8894 if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) { 8895 IndexOffset = IndexOffset->getOperand(0); 8896 IsIndexSignExt = true; 8897 } 8898 8899 // Either the case of Base + Index (no offset) or something else. 8900 if (IndexOffset->getOpcode() != ISD::ADD) 8901 return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt); 8902 8903 // Now we have the case of Base + Index + offset. 8904 SDValue Index = IndexOffset->getOperand(0); 8905 SDValue Offset = IndexOffset->getOperand(1); 8906 8907 if (!isa<ConstantSDNode>(Offset)) 8908 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt); 8909 8910 // Ignore signextends. 8911 if (Index->getOpcode() == ISD::SIGN_EXTEND) { 8912 Index = Index->getOperand(0); 8913 IsIndexSignExt = true; 8914 } else IsIndexSignExt = false; 8915 8916 int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue(); 8917 return BaseIndexOffset(Base, Index, Off, IsIndexSignExt); 8918 } 8919 }; 8920 8921 /// Holds a pointer to an LSBaseSDNode as well as information on where it 8922 /// is located in a sequence of memory operations connected by a chain. 8923 struct MemOpLink { 8924 MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq): 8925 MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { } 8926 // Ptr to the mem node. 8927 LSBaseSDNode *MemNode; 8928 // Offset from the base ptr. 8929 int64_t OffsetFromBase; 8930 // What is the sequence number of this mem node. 8931 // Lowest mem operand in the DAG starts at zero. 8932 unsigned SequenceNum; 8933 }; 8934 8935 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) { 8936 EVT MemVT = St->getMemoryVT(); 8937 int64_t ElementSizeBytes = MemVT.getSizeInBits()/8; 8938 bool NoVectors = DAG.getMachineFunction().getFunction()->getAttributes(). 8939 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat); 8940 8941 // Don't merge vectors into wider inputs. 8942 if (MemVT.isVector() || !MemVT.isSimple()) 8943 return false; 8944 8945 // Perform an early exit check. Do not bother looking at stored values that 8946 // are not constants or loads. 8947 SDValue StoredVal = St->getValue(); 8948 bool IsLoadSrc = isa<LoadSDNode>(StoredVal); 8949 if (!isa<ConstantSDNode>(StoredVal) && !isa<ConstantFPSDNode>(StoredVal) && 8950 !IsLoadSrc) 8951 return false; 8952 8953 // Only look at ends of store sequences. 8954 SDValue Chain = SDValue(St, 1); 8955 if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE) 8956 return false; 8957 8958 // This holds the base pointer, index, and the offset in bytes from the base 8959 // pointer. 8960 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr()); 8961 8962 // We must have a base and an offset. 8963 if (!BasePtr.Base.getNode()) 8964 return false; 8965 8966 // Do not handle stores to undef base pointers. 8967 if (BasePtr.Base.getOpcode() == ISD::UNDEF) 8968 return false; 8969 8970 // Save the LoadSDNodes that we find in the chain. 8971 // We need to make sure that these nodes do not interfere with 8972 // any of the store nodes. 8973 SmallVector<LSBaseSDNode*, 8> AliasLoadNodes; 8974 8975 // Save the StoreSDNodes that we find in the chain. 8976 SmallVector<MemOpLink, 8> StoreNodes; 8977 8978 // Walk up the chain and look for nodes with offsets from the same 8979 // base pointer. Stop when reaching an instruction with a different kind 8980 // or instruction which has a different base pointer. 8981 unsigned Seq = 0; 8982 StoreSDNode *Index = St; 8983 while (Index) { 8984 // If the chain has more than one use, then we can't reorder the mem ops. 8985 if (Index != St && !SDValue(Index, 1)->hasOneUse()) 8986 break; 8987 8988 // Find the base pointer and offset for this memory node. 8989 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr()); 8990 8991 // Check that the base pointer is the same as the original one. 8992 if (!Ptr.equalBaseIndex(BasePtr)) 8993 break; 8994 8995 // Check that the alignment is the same. 8996 if (Index->getAlignment() != St->getAlignment()) 8997 break; 8998 8999 // The memory operands must not be volatile. 9000 if (Index->isVolatile() || Index->isIndexed()) 9001 break; 9002 9003 // No truncation. 9004 if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index)) 9005 if (St->isTruncatingStore()) 9006 break; 9007 9008 // The stored memory type must be the same. 9009 if (Index->getMemoryVT() != MemVT) 9010 break; 9011 9012 // We do not allow unaligned stores because we want to prevent overriding 9013 // stores. 9014 if (Index->getAlignment()*8 != MemVT.getSizeInBits()) 9015 break; 9016 9017 // We found a potential memory operand to merge. 9018 StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++)); 9019 9020 // Find the next memory operand in the chain. If the next operand in the 9021 // chain is a store then move up and continue the scan with the next 9022 // memory operand. If the next operand is a load save it and use alias 9023 // information to check if it interferes with anything. 9024 SDNode *NextInChain = Index->getChain().getNode(); 9025 while (1) { 9026 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) { 9027 // We found a store node. Use it for the next iteration. 9028 Index = STn; 9029 break; 9030 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) { 9031 if (Ldn->isVolatile()) { 9032 Index = nullptr; 9033 break; 9034 } 9035 9036 // Save the load node for later. Continue the scan. 9037 AliasLoadNodes.push_back(Ldn); 9038 NextInChain = Ldn->getChain().getNode(); 9039 continue; 9040 } else { 9041 Index = nullptr; 9042 break; 9043 } 9044 } 9045 } 9046 9047 // Check if there is anything to merge. 9048 if (StoreNodes.size() < 2) 9049 return false; 9050 9051 // Sort the memory operands according to their distance from the base pointer. 9052 std::sort(StoreNodes.begin(), StoreNodes.end(), 9053 [](MemOpLink LHS, MemOpLink RHS) { 9054 return LHS.OffsetFromBase < RHS.OffsetFromBase || 9055 (LHS.OffsetFromBase == RHS.OffsetFromBase && 9056 LHS.SequenceNum > RHS.SequenceNum); 9057 }); 9058 9059 // Scan the memory operations on the chain and find the first non-consecutive 9060 // store memory address. 9061 unsigned LastConsecutiveStore = 0; 9062 int64_t StartAddress = StoreNodes[0].OffsetFromBase; 9063 for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) { 9064 9065 // Check that the addresses are consecutive starting from the second 9066 // element in the list of stores. 9067 if (i > 0) { 9068 int64_t CurrAddress = StoreNodes[i].OffsetFromBase; 9069 if (CurrAddress - StartAddress != (ElementSizeBytes * i)) 9070 break; 9071 } 9072 9073 bool Alias = false; 9074 // Check if this store interferes with any of the loads that we found. 9075 for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld) 9076 if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) { 9077 Alias = true; 9078 break; 9079 } 9080 // We found a load that alias with this store. Stop the sequence. 9081 if (Alias) 9082 break; 9083 9084 // Mark this node as useful. 9085 LastConsecutiveStore = i; 9086 } 9087 9088 // The node with the lowest store address. 9089 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode; 9090 9091 // Store the constants into memory as one consecutive store. 9092 if (!IsLoadSrc) { 9093 unsigned LastLegalType = 0; 9094 unsigned LastLegalVectorType = 0; 9095 bool NonZero = false; 9096 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) { 9097 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 9098 SDValue StoredVal = St->getValue(); 9099 9100 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) { 9101 NonZero |= !C->isNullValue(); 9102 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) { 9103 NonZero |= !C->getConstantFPValue()->isNullValue(); 9104 } else { 9105 // Non-constant. 9106 break; 9107 } 9108 9109 // Find a legal type for the constant store. 9110 unsigned StoreBW = (i+1) * ElementSizeBytes * 8; 9111 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW); 9112 if (TLI.isTypeLegal(StoreTy)) 9113 LastLegalType = i+1; 9114 // Or check whether a truncstore is legal. 9115 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) == 9116 TargetLowering::TypePromoteInteger) { 9117 EVT LegalizedStoredValueTy = 9118 TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType()); 9119 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy)) 9120 LastLegalType = i+1; 9121 } 9122 9123 // Find a legal type for the vector store. 9124 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1); 9125 if (TLI.isTypeLegal(Ty)) 9126 LastLegalVectorType = i + 1; 9127 } 9128 9129 // We only use vectors if the constant is known to be zero and the 9130 // function is not marked with the noimplicitfloat attribute. 9131 if (NonZero || NoVectors) 9132 LastLegalVectorType = 0; 9133 9134 // Check if we found a legal integer type to store. 9135 if (LastLegalType == 0 && LastLegalVectorType == 0) 9136 return false; 9137 9138 bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors; 9139 unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType; 9140 9141 // Make sure we have something to merge. 9142 if (NumElem < 2) 9143 return false; 9144 9145 unsigned EarliestNodeUsed = 0; 9146 for (unsigned i=0; i < NumElem; ++i) { 9147 // Find a chain for the new wide-store operand. Notice that some 9148 // of the store nodes that we found may not be selected for inclusion 9149 // in the wide store. The chain we use needs to be the chain of the 9150 // earliest store node which is *used* and replaced by the wide store. 9151 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum) 9152 EarliestNodeUsed = i; 9153 } 9154 9155 // The earliest Node in the DAG. 9156 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode; 9157 SDLoc DL(StoreNodes[0].MemNode); 9158 9159 SDValue StoredVal; 9160 if (UseVector) { 9161 // Find a legal type for the vector store. 9162 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem); 9163 assert(TLI.isTypeLegal(Ty) && "Illegal vector store"); 9164 StoredVal = DAG.getConstant(0, Ty); 9165 } else { 9166 unsigned StoreBW = NumElem * ElementSizeBytes * 8; 9167 APInt StoreInt(StoreBW, 0); 9168 9169 // Construct a single integer constant which is made of the smaller 9170 // constant inputs. 9171 bool IsLE = TLI.isLittleEndian(); 9172 for (unsigned i = 0; i < NumElem ; ++i) { 9173 unsigned Idx = IsLE ?(NumElem - 1 - i) : i; 9174 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[Idx].MemNode); 9175 SDValue Val = St->getValue(); 9176 StoreInt<<=ElementSizeBytes*8; 9177 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) { 9178 StoreInt|=C->getAPIntValue().zext(StoreBW); 9179 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) { 9180 StoreInt|= C->getValueAPF().bitcastToAPInt().zext(StoreBW); 9181 } else { 9182 assert(false && "Invalid constant element type"); 9183 } 9184 } 9185 9186 // Create the new Load and Store operations. 9187 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW); 9188 StoredVal = DAG.getConstant(StoreInt, StoreTy); 9189 } 9190 9191 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), DL, StoredVal, 9192 FirstInChain->getBasePtr(), 9193 FirstInChain->getPointerInfo(), 9194 false, false, 9195 FirstInChain->getAlignment()); 9196 9197 // Replace the first store with the new store 9198 CombineTo(EarliestOp, NewStore); 9199 // Erase all other stores. 9200 for (unsigned i = 0; i < NumElem ; ++i) { 9201 if (StoreNodes[i].MemNode == EarliestOp) 9202 continue; 9203 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 9204 // ReplaceAllUsesWith will replace all uses that existed when it was 9205 // called, but graph optimizations may cause new ones to appear. For 9206 // example, the case in pr14333 looks like 9207 // 9208 // St's chain -> St -> another store -> X 9209 // 9210 // And the only difference from St to the other store is the chain. 9211 // When we change it's chain to be St's chain they become identical, 9212 // get CSEed and the net result is that X is now a use of St. 9213 // Since we know that St is redundant, just iterate. 9214 while (!St->use_empty()) 9215 DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain()); 9216 removeFromWorkList(St); 9217 DAG.DeleteNode(St); 9218 } 9219 9220 return true; 9221 } 9222 9223 // Below we handle the case of multiple consecutive stores that 9224 // come from multiple consecutive loads. We merge them into a single 9225 // wide load and a single wide store. 9226 9227 // Look for load nodes which are used by the stored values. 9228 SmallVector<MemOpLink, 8> LoadNodes; 9229 9230 // Find acceptable loads. Loads need to have the same chain (token factor), 9231 // must not be zext, volatile, indexed, and they must be consecutive. 9232 BaseIndexOffset LdBasePtr; 9233 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) { 9234 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 9235 LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue()); 9236 if (!Ld) break; 9237 9238 // Loads must only have one use. 9239 if (!Ld->hasNUsesOfValue(1, 0)) 9240 break; 9241 9242 // Check that the alignment is the same as the stores. 9243 if (Ld->getAlignment() != St->getAlignment()) 9244 break; 9245 9246 // The memory operands must not be volatile. 9247 if (Ld->isVolatile() || Ld->isIndexed()) 9248 break; 9249 9250 // We do not accept ext loads. 9251 if (Ld->getExtensionType() != ISD::NON_EXTLOAD) 9252 break; 9253 9254 // The stored memory type must be the same. 9255 if (Ld->getMemoryVT() != MemVT) 9256 break; 9257 9258 BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr()); 9259 // If this is not the first ptr that we check. 9260 if (LdBasePtr.Base.getNode()) { 9261 // The base ptr must be the same. 9262 if (!LdPtr.equalBaseIndex(LdBasePtr)) 9263 break; 9264 } else { 9265 // Check that all other base pointers are the same as this one. 9266 LdBasePtr = LdPtr; 9267 } 9268 9269 // We found a potential memory operand to merge. 9270 LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0)); 9271 } 9272 9273 if (LoadNodes.size() < 2) 9274 return false; 9275 9276 // Scan the memory operations on the chain and find the first non-consecutive 9277 // load memory address. These variables hold the index in the store node 9278 // array. 9279 unsigned LastConsecutiveLoad = 0; 9280 // This variable refers to the size and not index in the array. 9281 unsigned LastLegalVectorType = 0; 9282 unsigned LastLegalIntegerType = 0; 9283 StartAddress = LoadNodes[0].OffsetFromBase; 9284 SDValue FirstChain = LoadNodes[0].MemNode->getChain(); 9285 for (unsigned i = 1; i < LoadNodes.size(); ++i) { 9286 // All loads much share the same chain. 9287 if (LoadNodes[i].MemNode->getChain() != FirstChain) 9288 break; 9289 9290 int64_t CurrAddress = LoadNodes[i].OffsetFromBase; 9291 if (CurrAddress - StartAddress != (ElementSizeBytes * i)) 9292 break; 9293 LastConsecutiveLoad = i; 9294 9295 // Find a legal type for the vector store. 9296 EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1); 9297 if (TLI.isTypeLegal(StoreTy)) 9298 LastLegalVectorType = i + 1; 9299 9300 // Find a legal type for the integer store. 9301 unsigned StoreBW = (i+1) * ElementSizeBytes * 8; 9302 StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW); 9303 if (TLI.isTypeLegal(StoreTy)) 9304 LastLegalIntegerType = i + 1; 9305 // Or check whether a truncstore and extload is legal. 9306 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) == 9307 TargetLowering::TypePromoteInteger) { 9308 EVT LegalizedStoredValueTy = 9309 TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy); 9310 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) && 9311 TLI.isLoadExtLegal(ISD::ZEXTLOAD, StoreTy) && 9312 TLI.isLoadExtLegal(ISD::SEXTLOAD, StoreTy) && 9313 TLI.isLoadExtLegal(ISD::EXTLOAD, StoreTy)) 9314 LastLegalIntegerType = i+1; 9315 } 9316 } 9317 9318 // Only use vector types if the vector type is larger than the integer type. 9319 // If they are the same, use integers. 9320 bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors; 9321 unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType); 9322 9323 // We add +1 here because the LastXXX variables refer to location while 9324 // the NumElem refers to array/index size. 9325 unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1; 9326 NumElem = std::min(LastLegalType, NumElem); 9327 9328 if (NumElem < 2) 9329 return false; 9330 9331 // The earliest Node in the DAG. 9332 unsigned EarliestNodeUsed = 0; 9333 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode; 9334 for (unsigned i=1; i<NumElem; ++i) { 9335 // Find a chain for the new wide-store operand. Notice that some 9336 // of the store nodes that we found may not be selected for inclusion 9337 // in the wide store. The chain we use needs to be the chain of the 9338 // earliest store node which is *used* and replaced by the wide store. 9339 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum) 9340 EarliestNodeUsed = i; 9341 } 9342 9343 // Find if it is better to use vectors or integers to load and store 9344 // to memory. 9345 EVT JointMemOpVT; 9346 if (UseVectorTy) { 9347 JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem); 9348 } else { 9349 unsigned StoreBW = NumElem * ElementSizeBytes * 8; 9350 JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW); 9351 } 9352 9353 SDLoc LoadDL(LoadNodes[0].MemNode); 9354 SDLoc StoreDL(StoreNodes[0].MemNode); 9355 9356 LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode); 9357 SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL, 9358 FirstLoad->getChain(), 9359 FirstLoad->getBasePtr(), 9360 FirstLoad->getPointerInfo(), 9361 false, false, false, 9362 FirstLoad->getAlignment()); 9363 9364 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), StoreDL, NewLoad, 9365 FirstInChain->getBasePtr(), 9366 FirstInChain->getPointerInfo(), false, false, 9367 FirstInChain->getAlignment()); 9368 9369 // Replace one of the loads with the new load. 9370 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode); 9371 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), 9372 SDValue(NewLoad.getNode(), 1)); 9373 9374 // Remove the rest of the load chains. 9375 for (unsigned i = 1; i < NumElem ; ++i) { 9376 // Replace all chain users of the old load nodes with the chain of the new 9377 // load node. 9378 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode); 9379 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain()); 9380 } 9381 9382 // Replace the first store with the new store. 9383 CombineTo(EarliestOp, NewStore); 9384 // Erase all other stores. 9385 for (unsigned i = 0; i < NumElem ; ++i) { 9386 // Remove all Store nodes. 9387 if (StoreNodes[i].MemNode == EarliestOp) 9388 continue; 9389 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 9390 DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain()); 9391 removeFromWorkList(St); 9392 DAG.DeleteNode(St); 9393 } 9394 9395 return true; 9396 } 9397 9398 SDValue DAGCombiner::visitSTORE(SDNode *N) { 9399 StoreSDNode *ST = cast<StoreSDNode>(N); 9400 SDValue Chain = ST->getChain(); 9401 SDValue Value = ST->getValue(); 9402 SDValue Ptr = ST->getBasePtr(); 9403 9404 // If this is a store of a bit convert, store the input value if the 9405 // resultant store does not need a higher alignment than the original. 9406 if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() && 9407 ST->isUnindexed()) { 9408 unsigned OrigAlign = ST->getAlignment(); 9409 EVT SVT = Value.getOperand(0).getValueType(); 9410 unsigned Align = TLI.getDataLayout()-> 9411 getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext())); 9412 if (Align <= OrigAlign && 9413 ((!LegalOperations && !ST->isVolatile()) || 9414 TLI.isOperationLegalOrCustom(ISD::STORE, SVT))) 9415 return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0), 9416 Ptr, ST->getPointerInfo(), ST->isVolatile(), 9417 ST->isNonTemporal(), OrigAlign, 9418 ST->getTBAAInfo()); 9419 } 9420 9421 // Turn 'store undef, Ptr' -> nothing. 9422 if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed()) 9423 return Chain; 9424 9425 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr' 9426 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) { 9427 // NOTE: If the original store is volatile, this transform must not increase 9428 // the number of stores. For example, on x86-32 an f64 can be stored in one 9429 // processor operation but an i64 (which is not legal) requires two. So the 9430 // transform should not be done in this case. 9431 if (Value.getOpcode() != ISD::TargetConstantFP) { 9432 SDValue Tmp; 9433 switch (CFP->getSimpleValueType(0).SimpleTy) { 9434 default: llvm_unreachable("Unknown FP type"); 9435 case MVT::f16: // We don't do this for these yet. 9436 case MVT::f80: 9437 case MVT::f128: 9438 case MVT::ppcf128: 9439 break; 9440 case MVT::f32: 9441 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) || 9442 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) { 9443 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF(). 9444 bitcastToAPInt().getZExtValue(), MVT::i32); 9445 return DAG.getStore(Chain, SDLoc(N), Tmp, 9446 Ptr, ST->getMemOperand()); 9447 } 9448 break; 9449 case MVT::f64: 9450 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations && 9451 !ST->isVolatile()) || 9452 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) { 9453 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt(). 9454 getZExtValue(), MVT::i64); 9455 return DAG.getStore(Chain, SDLoc(N), Tmp, 9456 Ptr, ST->getMemOperand()); 9457 } 9458 9459 if (!ST->isVolatile() && 9460 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) { 9461 // Many FP stores are not made apparent until after legalize, e.g. for 9462 // argument passing. Since this is so common, custom legalize the 9463 // 64-bit integer store into two 32-bit stores. 9464 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue(); 9465 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32); 9466 SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32); 9467 if (TLI.isBigEndian()) std::swap(Lo, Hi); 9468 9469 unsigned Alignment = ST->getAlignment(); 9470 bool isVolatile = ST->isVolatile(); 9471 bool isNonTemporal = ST->isNonTemporal(); 9472 const MDNode *TBAAInfo = ST->getTBAAInfo(); 9473 9474 SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo, 9475 Ptr, ST->getPointerInfo(), 9476 isVolatile, isNonTemporal, 9477 ST->getAlignment(), TBAAInfo); 9478 Ptr = DAG.getNode(ISD::ADD, SDLoc(N), Ptr.getValueType(), Ptr, 9479 DAG.getConstant(4, Ptr.getValueType())); 9480 Alignment = MinAlign(Alignment, 4U); 9481 SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi, 9482 Ptr, ST->getPointerInfo().getWithOffset(4), 9483 isVolatile, isNonTemporal, 9484 Alignment, TBAAInfo); 9485 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, 9486 St0, St1); 9487 } 9488 9489 break; 9490 } 9491 } 9492 } 9493 9494 // Try to infer better alignment information than the store already has. 9495 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) { 9496 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) { 9497 if (Align > ST->getAlignment()) 9498 return DAG.getTruncStore(Chain, SDLoc(N), Value, 9499 Ptr, ST->getPointerInfo(), ST->getMemoryVT(), 9500 ST->isVolatile(), ST->isNonTemporal(), Align, 9501 ST->getTBAAInfo()); 9502 } 9503 } 9504 9505 // Try transforming a pair floating point load / store ops to integer 9506 // load / store ops. 9507 SDValue NewST = TransformFPLoadStorePair(N); 9508 if (NewST.getNode()) 9509 return NewST; 9510 9511 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA : 9512 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA(); 9513 #ifndef NDEBUG 9514 if (CombinerAAOnlyFunc.getNumOccurrences() && 9515 CombinerAAOnlyFunc != DAG.getMachineFunction().getName()) 9516 UseAA = false; 9517 #endif 9518 if (UseAA && ST->isUnindexed()) { 9519 // Walk up chain skipping non-aliasing memory nodes. 9520 SDValue BetterChain = FindBetterChain(N, Chain); 9521 9522 // If there is a better chain. 9523 if (Chain != BetterChain) { 9524 SDValue ReplStore; 9525 9526 // Replace the chain to avoid dependency. 9527 if (ST->isTruncatingStore()) { 9528 ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr, 9529 ST->getMemoryVT(), ST->getMemOperand()); 9530 } else { 9531 ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr, 9532 ST->getMemOperand()); 9533 } 9534 9535 // Create token to keep both nodes around. 9536 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N), 9537 MVT::Other, Chain, ReplStore); 9538 9539 // Make sure the new and old chains are cleaned up. 9540 AddToWorkList(Token.getNode()); 9541 9542 // Don't add users to work list. 9543 return CombineTo(N, Token, false); 9544 } 9545 } 9546 9547 // Try transforming N to an indexed store. 9548 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N)) 9549 return SDValue(N, 0); 9550 9551 // FIXME: is there such a thing as a truncating indexed store? 9552 if (ST->isTruncatingStore() && ST->isUnindexed() && 9553 Value.getValueType().isInteger()) { 9554 // See if we can simplify the input to this truncstore with knowledge that 9555 // only the low bits are being used. For example: 9556 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8" 9557 SDValue Shorter = 9558 GetDemandedBits(Value, 9559 APInt::getLowBitsSet( 9560 Value.getValueType().getScalarType().getSizeInBits(), 9561 ST->getMemoryVT().getScalarType().getSizeInBits())); 9562 AddToWorkList(Value.getNode()); 9563 if (Shorter.getNode()) 9564 return DAG.getTruncStore(Chain, SDLoc(N), Shorter, 9565 Ptr, ST->getMemoryVT(), ST->getMemOperand()); 9566 9567 // Otherwise, see if we can simplify the operation with 9568 // SimplifyDemandedBits, which only works if the value has a single use. 9569 if (SimplifyDemandedBits(Value, 9570 APInt::getLowBitsSet( 9571 Value.getValueType().getScalarType().getSizeInBits(), 9572 ST->getMemoryVT().getScalarType().getSizeInBits()))) 9573 return SDValue(N, 0); 9574 } 9575 9576 // If this is a load followed by a store to the same location, then the store 9577 // is dead/noop. 9578 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) { 9579 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() && 9580 ST->isUnindexed() && !ST->isVolatile() && 9581 // There can't be any side effects between the load and store, such as 9582 // a call or store. 9583 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) { 9584 // The store is dead, remove it. 9585 return Chain; 9586 } 9587 } 9588 9589 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a 9590 // truncating store. We can do this even if this is already a truncstore. 9591 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE) 9592 && Value.getNode()->hasOneUse() && ST->isUnindexed() && 9593 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(), 9594 ST->getMemoryVT())) { 9595 return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0), 9596 Ptr, ST->getMemoryVT(), ST->getMemOperand()); 9597 } 9598 9599 // Only perform this optimization before the types are legal, because we 9600 // don't want to perform this optimization on every DAGCombine invocation. 9601 if (!LegalTypes) { 9602 bool EverChanged = false; 9603 9604 do { 9605 // There can be multiple store sequences on the same chain. 9606 // Keep trying to merge store sequences until we are unable to do so 9607 // or until we merge the last store on the chain. 9608 bool Changed = MergeConsecutiveStores(ST); 9609 EverChanged |= Changed; 9610 if (!Changed) break; 9611 } while (ST->getOpcode() != ISD::DELETED_NODE); 9612 9613 if (EverChanged) 9614 return SDValue(N, 0); 9615 } 9616 9617 return ReduceLoadOpStoreWidth(N); 9618 } 9619 9620 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) { 9621 SDValue InVec = N->getOperand(0); 9622 SDValue InVal = N->getOperand(1); 9623 SDValue EltNo = N->getOperand(2); 9624 SDLoc dl(N); 9625 9626 // If the inserted element is an UNDEF, just use the input vector. 9627 if (InVal.getOpcode() == ISD::UNDEF) 9628 return InVec; 9629 9630 EVT VT = InVec.getValueType(); 9631 9632 // If we can't generate a legal BUILD_VECTOR, exit 9633 if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT)) 9634 return SDValue(); 9635 9636 // Check that we know which element is being inserted 9637 if (!isa<ConstantSDNode>(EltNo)) 9638 return SDValue(); 9639 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue(); 9640 9641 // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially 9642 // be converted to a BUILD_VECTOR). Fill in the Ops vector with the 9643 // vector elements. 9644 SmallVector<SDValue, 8> Ops; 9645 // Do not combine these two vectors if the output vector will not replace 9646 // the input vector. 9647 if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) { 9648 Ops.append(InVec.getNode()->op_begin(), 9649 InVec.getNode()->op_end()); 9650 } else if (InVec.getOpcode() == ISD::UNDEF) { 9651 unsigned NElts = VT.getVectorNumElements(); 9652 Ops.append(NElts, DAG.getUNDEF(InVal.getValueType())); 9653 } else { 9654 return SDValue(); 9655 } 9656 9657 // Insert the element 9658 if (Elt < Ops.size()) { 9659 // All the operands of BUILD_VECTOR must have the same type; 9660 // we enforce that here. 9661 EVT OpVT = Ops[0].getValueType(); 9662 if (InVal.getValueType() != OpVT) 9663 InVal = OpVT.bitsGT(InVal.getValueType()) ? 9664 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) : 9665 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal); 9666 Ops[Elt] = InVal; 9667 } 9668 9669 // Return the new vector 9670 return DAG.getNode(ISD::BUILD_VECTOR, dl, 9671 VT, &Ops[0], Ops.size()); 9672 } 9673 9674 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) { 9675 // (vextract (scalar_to_vector val, 0) -> val 9676 SDValue InVec = N->getOperand(0); 9677 EVT VT = InVec.getValueType(); 9678 EVT NVT = N->getValueType(0); 9679 9680 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) { 9681 // Check if the result type doesn't match the inserted element type. A 9682 // SCALAR_TO_VECTOR may truncate the inserted element and the 9683 // EXTRACT_VECTOR_ELT may widen the extracted vector. 9684 SDValue InOp = InVec.getOperand(0); 9685 if (InOp.getValueType() != NVT) { 9686 assert(InOp.getValueType().isInteger() && NVT.isInteger()); 9687 return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT); 9688 } 9689 return InOp; 9690 } 9691 9692 SDValue EltNo = N->getOperand(1); 9693 bool ConstEltNo = isa<ConstantSDNode>(EltNo); 9694 9695 // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT. 9696 // We only perform this optimization before the op legalization phase because 9697 // we may introduce new vector instructions which are not backed by TD 9698 // patterns. For example on AVX, extracting elements from a wide vector 9699 // without using extract_subvector. However, if we can find an underlying 9700 // scalar value, then we can always use that. 9701 if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE 9702 && ConstEltNo) { 9703 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue(); 9704 int NumElem = VT.getVectorNumElements(); 9705 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec); 9706 // Find the new index to extract from. 9707 int OrigElt = SVOp->getMaskElt(Elt); 9708 9709 // Extracting an undef index is undef. 9710 if (OrigElt == -1) 9711 return DAG.getUNDEF(NVT); 9712 9713 // Select the right vector half to extract from. 9714 SDValue SVInVec; 9715 if (OrigElt < NumElem) { 9716 SVInVec = InVec->getOperand(0); 9717 } else { 9718 SVInVec = InVec->getOperand(1); 9719 OrigElt -= NumElem; 9720 } 9721 9722 if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) { 9723 SDValue InOp = SVInVec.getOperand(OrigElt); 9724 if (InOp.getValueType() != NVT) { 9725 assert(InOp.getValueType().isInteger() && NVT.isInteger()); 9726 InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT); 9727 } 9728 9729 return InOp; 9730 } 9731 9732 // FIXME: We should handle recursing on other vector shuffles and 9733 // scalar_to_vector here as well. 9734 9735 if (!LegalOperations) { 9736 EVT IndexTy = TLI.getVectorIdxTy(); 9737 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT, 9738 SVInVec, DAG.getConstant(OrigElt, IndexTy)); 9739 } 9740 } 9741 9742 // Perform only after legalization to ensure build_vector / vector_shuffle 9743 // optimizations have already been done. 9744 if (!LegalOperations) return SDValue(); 9745 9746 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size) 9747 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size) 9748 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr) 9749 9750 if (ConstEltNo) { 9751 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue(); 9752 bool NewLoad = false; 9753 bool BCNumEltsChanged = false; 9754 EVT ExtVT = VT.getVectorElementType(); 9755 EVT LVT = ExtVT; 9756 9757 // If the result of load has to be truncated, then it's not necessarily 9758 // profitable. 9759 if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT)) 9760 return SDValue(); 9761 9762 if (InVec.getOpcode() == ISD::BITCAST) { 9763 // Don't duplicate a load with other uses. 9764 if (!InVec.hasOneUse()) 9765 return SDValue(); 9766 9767 EVT BCVT = InVec.getOperand(0).getValueType(); 9768 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType())) 9769 return SDValue(); 9770 if (VT.getVectorNumElements() != BCVT.getVectorNumElements()) 9771 BCNumEltsChanged = true; 9772 InVec = InVec.getOperand(0); 9773 ExtVT = BCVT.getVectorElementType(); 9774 NewLoad = true; 9775 } 9776 9777 LoadSDNode *LN0 = nullptr; 9778 const ShuffleVectorSDNode *SVN = nullptr; 9779 if (ISD::isNormalLoad(InVec.getNode())) { 9780 LN0 = cast<LoadSDNode>(InVec); 9781 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR && 9782 InVec.getOperand(0).getValueType() == ExtVT && 9783 ISD::isNormalLoad(InVec.getOperand(0).getNode())) { 9784 // Don't duplicate a load with other uses. 9785 if (!InVec.hasOneUse()) 9786 return SDValue(); 9787 9788 LN0 = cast<LoadSDNode>(InVec.getOperand(0)); 9789 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) { 9790 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1) 9791 // => 9792 // (load $addr+1*size) 9793 9794 // Don't duplicate a load with other uses. 9795 if (!InVec.hasOneUse()) 9796 return SDValue(); 9797 9798 // If the bit convert changed the number of elements, it is unsafe 9799 // to examine the mask. 9800 if (BCNumEltsChanged) 9801 return SDValue(); 9802 9803 // Select the input vector, guarding against out of range extract vector. 9804 unsigned NumElems = VT.getVectorNumElements(); 9805 int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt); 9806 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1); 9807 9808 if (InVec.getOpcode() == ISD::BITCAST) { 9809 // Don't duplicate a load with other uses. 9810 if (!InVec.hasOneUse()) 9811 return SDValue(); 9812 9813 InVec = InVec.getOperand(0); 9814 } 9815 if (ISD::isNormalLoad(InVec.getNode())) { 9816 LN0 = cast<LoadSDNode>(InVec); 9817 Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems; 9818 } 9819 } 9820 9821 // Make sure we found a non-volatile load and the extractelement is 9822 // the only use. 9823 if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile()) 9824 return SDValue(); 9825 9826 // If Idx was -1 above, Elt is going to be -1, so just return undef. 9827 if (Elt == -1) 9828 return DAG.getUNDEF(LVT); 9829 9830 unsigned Align = LN0->getAlignment(); 9831 if (NewLoad) { 9832 // Check the resultant load doesn't need a higher alignment than the 9833 // original load. 9834 unsigned NewAlign = 9835 TLI.getDataLayout() 9836 ->getABITypeAlignment(LVT.getTypeForEVT(*DAG.getContext())); 9837 9838 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, LVT)) 9839 return SDValue(); 9840 9841 Align = NewAlign; 9842 } 9843 9844 SDValue NewPtr = LN0->getBasePtr(); 9845 unsigned PtrOff = 0; 9846 9847 if (Elt) { 9848 PtrOff = LVT.getSizeInBits() * Elt / 8; 9849 EVT PtrType = NewPtr.getValueType(); 9850 if (TLI.isBigEndian()) 9851 PtrOff = VT.getSizeInBits() / 8 - PtrOff; 9852 NewPtr = DAG.getNode(ISD::ADD, SDLoc(N), PtrType, NewPtr, 9853 DAG.getConstant(PtrOff, PtrType)); 9854 } 9855 9856 // The replacement we need to do here is a little tricky: we need to 9857 // replace an extractelement of a load with a load. 9858 // Use ReplaceAllUsesOfValuesWith to do the replacement. 9859 // Note that this replacement assumes that the extractvalue is the only 9860 // use of the load; that's okay because we don't want to perform this 9861 // transformation in other cases anyway. 9862 SDValue Load; 9863 SDValue Chain; 9864 if (NVT.bitsGT(LVT)) { 9865 // If the result type of vextract is wider than the load, then issue an 9866 // extending load instead. 9867 ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, LVT) 9868 ? ISD::ZEXTLOAD : ISD::EXTLOAD; 9869 Load = DAG.getExtLoad(ExtType, SDLoc(N), NVT, LN0->getChain(), 9870 NewPtr, LN0->getPointerInfo().getWithOffset(PtrOff), 9871 LVT, LN0->isVolatile(), LN0->isNonTemporal(), 9872 Align, LN0->getTBAAInfo()); 9873 Chain = Load.getValue(1); 9874 } else { 9875 Load = DAG.getLoad(LVT, SDLoc(N), LN0->getChain(), NewPtr, 9876 LN0->getPointerInfo().getWithOffset(PtrOff), 9877 LN0->isVolatile(), LN0->isNonTemporal(), 9878 LN0->isInvariant(), Align, LN0->getTBAAInfo()); 9879 Chain = Load.getValue(1); 9880 if (NVT.bitsLT(LVT)) 9881 Load = DAG.getNode(ISD::TRUNCATE, SDLoc(N), NVT, Load); 9882 else 9883 Load = DAG.getNode(ISD::BITCAST, SDLoc(N), NVT, Load); 9884 } 9885 WorkListRemover DeadNodes(*this); 9886 SDValue From[] = { SDValue(N, 0), SDValue(LN0,1) }; 9887 SDValue To[] = { Load, Chain }; 9888 DAG.ReplaceAllUsesOfValuesWith(From, To, 2); 9889 // Since we're explcitly calling ReplaceAllUses, add the new node to the 9890 // worklist explicitly as well. 9891 AddToWorkList(Load.getNode()); 9892 AddUsersToWorkList(Load.getNode()); // Add users too 9893 // Make sure to revisit this node to clean it up; it will usually be dead. 9894 AddToWorkList(N); 9895 return SDValue(N, 0); 9896 } 9897 9898 return SDValue(); 9899 } 9900 9901 // Simplify (build_vec (ext )) to (bitcast (build_vec )) 9902 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) { 9903 // We perform this optimization post type-legalization because 9904 // the type-legalizer often scalarizes integer-promoted vectors. 9905 // Performing this optimization before may create bit-casts which 9906 // will be type-legalized to complex code sequences. 9907 // We perform this optimization only before the operation legalizer because we 9908 // may introduce illegal operations. 9909 if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes) 9910 return SDValue(); 9911 9912 unsigned NumInScalars = N->getNumOperands(); 9913 SDLoc dl(N); 9914 EVT VT = N->getValueType(0); 9915 9916 // Check to see if this is a BUILD_VECTOR of a bunch of values 9917 // which come from any_extend or zero_extend nodes. If so, we can create 9918 // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR 9919 // optimizations. We do not handle sign-extend because we can't fill the sign 9920 // using shuffles. 9921 EVT SourceType = MVT::Other; 9922 bool AllAnyExt = true; 9923 9924 for (unsigned i = 0; i != NumInScalars; ++i) { 9925 SDValue In = N->getOperand(i); 9926 // Ignore undef inputs. 9927 if (In.getOpcode() == ISD::UNDEF) continue; 9928 9929 bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND; 9930 bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND; 9931 9932 // Abort if the element is not an extension. 9933 if (!ZeroExt && !AnyExt) { 9934 SourceType = MVT::Other; 9935 break; 9936 } 9937 9938 // The input is a ZeroExt or AnyExt. Check the original type. 9939 EVT InTy = In.getOperand(0).getValueType(); 9940 9941 // Check that all of the widened source types are the same. 9942 if (SourceType == MVT::Other) 9943 // First time. 9944 SourceType = InTy; 9945 else if (InTy != SourceType) { 9946 // Multiple income types. Abort. 9947 SourceType = MVT::Other; 9948 break; 9949 } 9950 9951 // Check if all of the extends are ANY_EXTENDs. 9952 AllAnyExt &= AnyExt; 9953 } 9954 9955 // In order to have valid types, all of the inputs must be extended from the 9956 // same source type and all of the inputs must be any or zero extend. 9957 // Scalar sizes must be a power of two. 9958 EVT OutScalarTy = VT.getScalarType(); 9959 bool ValidTypes = SourceType != MVT::Other && 9960 isPowerOf2_32(OutScalarTy.getSizeInBits()) && 9961 isPowerOf2_32(SourceType.getSizeInBits()); 9962 9963 // Create a new simpler BUILD_VECTOR sequence which other optimizations can 9964 // turn into a single shuffle instruction. 9965 if (!ValidTypes) 9966 return SDValue(); 9967 9968 bool isLE = TLI.isLittleEndian(); 9969 unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits(); 9970 assert(ElemRatio > 1 && "Invalid element size ratio"); 9971 SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType): 9972 DAG.getConstant(0, SourceType); 9973 9974 unsigned NewBVElems = ElemRatio * VT.getVectorNumElements(); 9975 SmallVector<SDValue, 8> Ops(NewBVElems, Filler); 9976 9977 // Populate the new build_vector 9978 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 9979 SDValue Cast = N->getOperand(i); 9980 assert((Cast.getOpcode() == ISD::ANY_EXTEND || 9981 Cast.getOpcode() == ISD::ZERO_EXTEND || 9982 Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode"); 9983 SDValue In; 9984 if (Cast.getOpcode() == ISD::UNDEF) 9985 In = DAG.getUNDEF(SourceType); 9986 else 9987 In = Cast->getOperand(0); 9988 unsigned Index = isLE ? (i * ElemRatio) : 9989 (i * ElemRatio + (ElemRatio - 1)); 9990 9991 assert(Index < Ops.size() && "Invalid index"); 9992 Ops[Index] = In; 9993 } 9994 9995 // The type of the new BUILD_VECTOR node. 9996 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems); 9997 assert(VecVT.getSizeInBits() == VT.getSizeInBits() && 9998 "Invalid vector size"); 9999 // Check if the new vector type is legal. 10000 if (!isTypeLegal(VecVT)) return SDValue(); 10001 10002 // Make the new BUILD_VECTOR. 10003 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, &Ops[0], Ops.size()); 10004 10005 // The new BUILD_VECTOR node has the potential to be further optimized. 10006 AddToWorkList(BV.getNode()); 10007 // Bitcast to the desired type. 10008 return DAG.getNode(ISD::BITCAST, dl, VT, BV); 10009 } 10010 10011 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) { 10012 EVT VT = N->getValueType(0); 10013 10014 unsigned NumInScalars = N->getNumOperands(); 10015 SDLoc dl(N); 10016 10017 EVT SrcVT = MVT::Other; 10018 unsigned Opcode = ISD::DELETED_NODE; 10019 unsigned NumDefs = 0; 10020 10021 for (unsigned i = 0; i != NumInScalars; ++i) { 10022 SDValue In = N->getOperand(i); 10023 unsigned Opc = In.getOpcode(); 10024 10025 if (Opc == ISD::UNDEF) 10026 continue; 10027 10028 // If all scalar values are floats and converted from integers. 10029 if (Opcode == ISD::DELETED_NODE && 10030 (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) { 10031 Opcode = Opc; 10032 } 10033 10034 if (Opc != Opcode) 10035 return SDValue(); 10036 10037 EVT InVT = In.getOperand(0).getValueType(); 10038 10039 // If all scalar values are typed differently, bail out. It's chosen to 10040 // simplify BUILD_VECTOR of integer types. 10041 if (SrcVT == MVT::Other) 10042 SrcVT = InVT; 10043 if (SrcVT != InVT) 10044 return SDValue(); 10045 NumDefs++; 10046 } 10047 10048 // If the vector has just one element defined, it's not worth to fold it into 10049 // a vectorized one. 10050 if (NumDefs < 2) 10051 return SDValue(); 10052 10053 assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP) 10054 && "Should only handle conversion from integer to float."); 10055 assert(SrcVT != MVT::Other && "Cannot determine source type!"); 10056 10057 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars); 10058 10059 if (!TLI.isOperationLegalOrCustom(Opcode, NVT)) 10060 return SDValue(); 10061 10062 SmallVector<SDValue, 8> Opnds; 10063 for (unsigned i = 0; i != NumInScalars; ++i) { 10064 SDValue In = N->getOperand(i); 10065 10066 if (In.getOpcode() == ISD::UNDEF) 10067 Opnds.push_back(DAG.getUNDEF(SrcVT)); 10068 else 10069 Opnds.push_back(In.getOperand(0)); 10070 } 10071 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, 10072 &Opnds[0], Opnds.size()); 10073 AddToWorkList(BV.getNode()); 10074 10075 return DAG.getNode(Opcode, dl, VT, BV); 10076 } 10077 10078 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) { 10079 unsigned NumInScalars = N->getNumOperands(); 10080 SDLoc dl(N); 10081 EVT VT = N->getValueType(0); 10082 10083 // A vector built entirely of undefs is undef. 10084 if (ISD::allOperandsUndef(N)) 10085 return DAG.getUNDEF(VT); 10086 10087 SDValue V = reduceBuildVecExtToExtBuildVec(N); 10088 if (V.getNode()) 10089 return V; 10090 10091 V = reduceBuildVecConvertToConvertBuildVec(N); 10092 if (V.getNode()) 10093 return V; 10094 10095 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT 10096 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from 10097 // at most two distinct vectors, turn this into a shuffle node. 10098 10099 // May only combine to shuffle after legalize if shuffle is legal. 10100 if (LegalOperations && 10101 !TLI.isOperationLegalOrCustom(ISD::VECTOR_SHUFFLE, VT)) 10102 return SDValue(); 10103 10104 SDValue VecIn1, VecIn2; 10105 for (unsigned i = 0; i != NumInScalars; ++i) { 10106 // Ignore undef inputs. 10107 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue; 10108 10109 // If this input is something other than a EXTRACT_VECTOR_ELT with a 10110 // constant index, bail out. 10111 if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT || 10112 !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) { 10113 VecIn1 = VecIn2 = SDValue(nullptr, 0); 10114 break; 10115 } 10116 10117 // We allow up to two distinct input vectors. 10118 SDValue ExtractedFromVec = N->getOperand(i).getOperand(0); 10119 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2) 10120 continue; 10121 10122 if (!VecIn1.getNode()) { 10123 VecIn1 = ExtractedFromVec; 10124 } else if (!VecIn2.getNode()) { 10125 VecIn2 = ExtractedFromVec; 10126 } else { 10127 // Too many inputs. 10128 VecIn1 = VecIn2 = SDValue(nullptr, 0); 10129 break; 10130 } 10131 } 10132 10133 // If everything is good, we can make a shuffle operation. 10134 if (VecIn1.getNode()) { 10135 SmallVector<int, 8> Mask; 10136 for (unsigned i = 0; i != NumInScalars; ++i) { 10137 if (N->getOperand(i).getOpcode() == ISD::UNDEF) { 10138 Mask.push_back(-1); 10139 continue; 10140 } 10141 10142 // If extracting from the first vector, just use the index directly. 10143 SDValue Extract = N->getOperand(i); 10144 SDValue ExtVal = Extract.getOperand(1); 10145 if (Extract.getOperand(0) == VecIn1) { 10146 unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue(); 10147 if (ExtIndex > VT.getVectorNumElements()) 10148 return SDValue(); 10149 10150 Mask.push_back(ExtIndex); 10151 continue; 10152 } 10153 10154 // Otherwise, use InIdx + VecSize 10155 unsigned Idx = cast<ConstantSDNode>(ExtVal)->getZExtValue(); 10156 Mask.push_back(Idx+NumInScalars); 10157 } 10158 10159 // We can't generate a shuffle node with mismatched input and output types. 10160 // Attempt to transform a single input vector to the correct type. 10161 if ((VT != VecIn1.getValueType())) { 10162 // We don't support shuffeling between TWO values of different types. 10163 if (VecIn2.getNode()) 10164 return SDValue(); 10165 10166 // We only support widening of vectors which are half the size of the 10167 // output registers. For example XMM->YMM widening on X86 with AVX. 10168 if (VecIn1.getValueType().getSizeInBits()*2 != VT.getSizeInBits()) 10169 return SDValue(); 10170 10171 // If the input vector type has a different base type to the output 10172 // vector type, bail out. 10173 if (VecIn1.getValueType().getVectorElementType() != 10174 VT.getVectorElementType()) 10175 return SDValue(); 10176 10177 // Widen the input vector by adding undef values. 10178 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, 10179 VecIn1, DAG.getUNDEF(VecIn1.getValueType())); 10180 } 10181 10182 // If VecIn2 is unused then change it to undef. 10183 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT); 10184 10185 // Check that we were able to transform all incoming values to the same 10186 // type. 10187 if (VecIn2.getValueType() != VecIn1.getValueType() || 10188 VecIn1.getValueType() != VT) 10189 return SDValue(); 10190 10191 // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes. 10192 if (!isTypeLegal(VT)) 10193 return SDValue(); 10194 10195 // Return the new VECTOR_SHUFFLE node. 10196 SDValue Ops[2]; 10197 Ops[0] = VecIn1; 10198 Ops[1] = VecIn2; 10199 return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]); 10200 } 10201 10202 return SDValue(); 10203 } 10204 10205 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) { 10206 // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of 10207 // EXTRACT_SUBVECTOR operations. If so, and if the EXTRACT_SUBVECTOR vector 10208 // inputs come from at most two distinct vectors, turn this into a shuffle 10209 // node. 10210 10211 // If we only have one input vector, we don't need to do any concatenation. 10212 if (N->getNumOperands() == 1) 10213 return N->getOperand(0); 10214 10215 // Check if all of the operands are undefs. 10216 EVT VT = N->getValueType(0); 10217 if (ISD::allOperandsUndef(N)) 10218 return DAG.getUNDEF(VT); 10219 10220 // Optimize concat_vectors where one of the vectors is undef. 10221 if (N->getNumOperands() == 2 && 10222 N->getOperand(1)->getOpcode() == ISD::UNDEF) { 10223 SDValue In = N->getOperand(0); 10224 assert(In.getValueType().isVector() && "Must concat vectors"); 10225 10226 // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr). 10227 if (In->getOpcode() == ISD::BITCAST && 10228 !In->getOperand(0)->getValueType(0).isVector()) { 10229 SDValue Scalar = In->getOperand(0); 10230 EVT SclTy = Scalar->getValueType(0); 10231 10232 if (!SclTy.isFloatingPoint() && !SclTy.isInteger()) 10233 return SDValue(); 10234 10235 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy, 10236 VT.getSizeInBits() / SclTy.getSizeInBits()); 10237 if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType())) 10238 return SDValue(); 10239 10240 SDLoc dl = SDLoc(N); 10241 SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar); 10242 return DAG.getNode(ISD::BITCAST, dl, VT, Res); 10243 } 10244 } 10245 10246 // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...)) 10247 // -> (BUILD_VECTOR A, B, ..., C, D, ...) 10248 if (N->getNumOperands() == 2 && 10249 N->getOperand(0).getOpcode() == ISD::BUILD_VECTOR && 10250 N->getOperand(1).getOpcode() == ISD::BUILD_VECTOR) { 10251 EVT VT = N->getValueType(0); 10252 SDValue N0 = N->getOperand(0); 10253 SDValue N1 = N->getOperand(1); 10254 SmallVector<SDValue, 8> Opnds; 10255 unsigned BuildVecNumElts = N0.getNumOperands(); 10256 10257 for (unsigned i = 0; i != BuildVecNumElts; ++i) 10258 Opnds.push_back(N0.getOperand(i)); 10259 for (unsigned i = 0; i != BuildVecNumElts; ++i) 10260 Opnds.push_back(N1.getOperand(i)); 10261 10262 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, &Opnds[0], 10263 Opnds.size()); 10264 } 10265 10266 // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR 10267 // nodes often generate nop CONCAT_VECTOR nodes. 10268 // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that 10269 // place the incoming vectors at the exact same location. 10270 SDValue SingleSource = SDValue(); 10271 unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements(); 10272 10273 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 10274 SDValue Op = N->getOperand(i); 10275 10276 if (Op.getOpcode() == ISD::UNDEF) 10277 continue; 10278 10279 // Check if this is the identity extract: 10280 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR) 10281 return SDValue(); 10282 10283 // Find the single incoming vector for the extract_subvector. 10284 if (SingleSource.getNode()) { 10285 if (Op.getOperand(0) != SingleSource) 10286 return SDValue(); 10287 } else { 10288 SingleSource = Op.getOperand(0); 10289 10290 // Check the source type is the same as the type of the result. 10291 // If not, this concat may extend the vector, so we can not 10292 // optimize it away. 10293 if (SingleSource.getValueType() != N->getValueType(0)) 10294 return SDValue(); 10295 } 10296 10297 unsigned IdentityIndex = i * PartNumElem; 10298 ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 10299 // The extract index must be constant. 10300 if (!CS) 10301 return SDValue(); 10302 10303 // Check that we are reading from the identity index. 10304 if (CS->getZExtValue() != IdentityIndex) 10305 return SDValue(); 10306 } 10307 10308 if (SingleSource.getNode()) 10309 return SingleSource; 10310 10311 return SDValue(); 10312 } 10313 10314 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) { 10315 EVT NVT = N->getValueType(0); 10316 SDValue V = N->getOperand(0); 10317 10318 if (V->getOpcode() == ISD::CONCAT_VECTORS) { 10319 // Combine: 10320 // (extract_subvec (concat V1, V2, ...), i) 10321 // Into: 10322 // Vi if possible 10323 // Only operand 0 is checked as 'concat' assumes all inputs of the same 10324 // type. 10325 if (V->getOperand(0).getValueType() != NVT) 10326 return SDValue(); 10327 unsigned Idx = dyn_cast<ConstantSDNode>(N->getOperand(1))->getZExtValue(); 10328 unsigned NumElems = NVT.getVectorNumElements(); 10329 assert((Idx % NumElems) == 0 && 10330 "IDX in concat is not a multiple of the result vector length."); 10331 return V->getOperand(Idx / NumElems); 10332 } 10333 10334 // Skip bitcasting 10335 if (V->getOpcode() == ISD::BITCAST) 10336 V = V.getOperand(0); 10337 10338 if (V->getOpcode() == ISD::INSERT_SUBVECTOR) { 10339 SDLoc dl(N); 10340 // Handle only simple case where vector being inserted and vector 10341 // being extracted are of same type, and are half size of larger vectors. 10342 EVT BigVT = V->getOperand(0).getValueType(); 10343 EVT SmallVT = V->getOperand(1).getValueType(); 10344 if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits()) 10345 return SDValue(); 10346 10347 // Only handle cases where both indexes are constants with the same type. 10348 ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1)); 10349 ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2)); 10350 10351 if (InsIdx && ExtIdx && 10352 InsIdx->getValueType(0).getSizeInBits() <= 64 && 10353 ExtIdx->getValueType(0).getSizeInBits() <= 64) { 10354 // Combine: 10355 // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx) 10356 // Into: 10357 // indices are equal or bit offsets are equal => V1 10358 // otherwise => (extract_subvec V1, ExtIdx) 10359 if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() == 10360 ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits()) 10361 return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1)); 10362 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT, 10363 DAG.getNode(ISD::BITCAST, dl, 10364 N->getOperand(0).getValueType(), 10365 V->getOperand(0)), N->getOperand(1)); 10366 } 10367 } 10368 10369 return SDValue(); 10370 } 10371 10372 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat. 10373 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) { 10374 EVT VT = N->getValueType(0); 10375 unsigned NumElts = VT.getVectorNumElements(); 10376 10377 SDValue N0 = N->getOperand(0); 10378 SDValue N1 = N->getOperand(1); 10379 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N); 10380 10381 SmallVector<SDValue, 4> Ops; 10382 EVT ConcatVT = N0.getOperand(0).getValueType(); 10383 unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements(); 10384 unsigned NumConcats = NumElts / NumElemsPerConcat; 10385 10386 // Look at every vector that's inserted. We're looking for exact 10387 // subvector-sized copies from a concatenated vector 10388 for (unsigned I = 0; I != NumConcats; ++I) { 10389 // Make sure we're dealing with a copy. 10390 unsigned Begin = I * NumElemsPerConcat; 10391 bool AllUndef = true, NoUndef = true; 10392 for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) { 10393 if (SVN->getMaskElt(J) >= 0) 10394 AllUndef = false; 10395 else 10396 NoUndef = false; 10397 } 10398 10399 if (NoUndef) { 10400 if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0) 10401 return SDValue(); 10402 10403 for (unsigned J = 1; J != NumElemsPerConcat; ++J) 10404 if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J)) 10405 return SDValue(); 10406 10407 unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat; 10408 if (FirstElt < N0.getNumOperands()) 10409 Ops.push_back(N0.getOperand(FirstElt)); 10410 else 10411 Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands())); 10412 10413 } else if (AllUndef) { 10414 Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType())); 10415 } else { // Mixed with general masks and undefs, can't do optimization. 10416 return SDValue(); 10417 } 10418 } 10419 10420 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops.data(), 10421 Ops.size()); 10422 } 10423 10424 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) { 10425 EVT VT = N->getValueType(0); 10426 unsigned NumElts = VT.getVectorNumElements(); 10427 10428 SDValue N0 = N->getOperand(0); 10429 SDValue N1 = N->getOperand(1); 10430 10431 assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG"); 10432 10433 // Canonicalize shuffle undef, undef -> undef 10434 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF) 10435 return DAG.getUNDEF(VT); 10436 10437 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N); 10438 10439 // Canonicalize shuffle v, v -> v, undef 10440 if (N0 == N1) { 10441 SmallVector<int, 8> NewMask; 10442 for (unsigned i = 0; i != NumElts; ++i) { 10443 int Idx = SVN->getMaskElt(i); 10444 if (Idx >= (int)NumElts) Idx -= NumElts; 10445 NewMask.push_back(Idx); 10446 } 10447 return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT), 10448 &NewMask[0]); 10449 } 10450 10451 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask. 10452 if (N0.getOpcode() == ISD::UNDEF) { 10453 SmallVector<int, 8> NewMask; 10454 for (unsigned i = 0; i != NumElts; ++i) { 10455 int Idx = SVN->getMaskElt(i); 10456 if (Idx >= 0) { 10457 if (Idx >= (int)NumElts) 10458 Idx -= NumElts; 10459 else 10460 Idx = -1; // remove reference to lhs 10461 } 10462 NewMask.push_back(Idx); 10463 } 10464 return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT), 10465 &NewMask[0]); 10466 } 10467 10468 // Remove references to rhs if it is undef 10469 if (N1.getOpcode() == ISD::UNDEF) { 10470 bool Changed = false; 10471 SmallVector<int, 8> NewMask; 10472 for (unsigned i = 0; i != NumElts; ++i) { 10473 int Idx = SVN->getMaskElt(i); 10474 if (Idx >= (int)NumElts) { 10475 Idx = -1; 10476 Changed = true; 10477 } 10478 NewMask.push_back(Idx); 10479 } 10480 if (Changed) 10481 return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]); 10482 } 10483 10484 // If it is a splat, check if the argument vector is another splat or a 10485 // build_vector with all scalar elements the same. 10486 if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) { 10487 SDNode *V = N0.getNode(); 10488 10489 // If this is a bit convert that changes the element type of the vector but 10490 // not the number of vector elements, look through it. Be careful not to 10491 // look though conversions that change things like v4f32 to v2f64. 10492 if (V->getOpcode() == ISD::BITCAST) { 10493 SDValue ConvInput = V->getOperand(0); 10494 if (ConvInput.getValueType().isVector() && 10495 ConvInput.getValueType().getVectorNumElements() == NumElts) 10496 V = ConvInput.getNode(); 10497 } 10498 10499 if (V->getOpcode() == ISD::BUILD_VECTOR) { 10500 assert(V->getNumOperands() == NumElts && 10501 "BUILD_VECTOR has wrong number of operands"); 10502 SDValue Base; 10503 bool AllSame = true; 10504 for (unsigned i = 0; i != NumElts; ++i) { 10505 if (V->getOperand(i).getOpcode() != ISD::UNDEF) { 10506 Base = V->getOperand(i); 10507 break; 10508 } 10509 } 10510 // Splat of <u, u, u, u>, return <u, u, u, u> 10511 if (!Base.getNode()) 10512 return N0; 10513 for (unsigned i = 0; i != NumElts; ++i) { 10514 if (V->getOperand(i) != Base) { 10515 AllSame = false; 10516 break; 10517 } 10518 } 10519 // Splat of <x, x, x, x>, return <x, x, x, x> 10520 if (AllSame) 10521 return N0; 10522 } 10523 } 10524 10525 if (N0.getOpcode() == ISD::CONCAT_VECTORS && 10526 Level < AfterLegalizeVectorOps && 10527 (N1.getOpcode() == ISD::UNDEF || 10528 (N1.getOpcode() == ISD::CONCAT_VECTORS && 10529 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) { 10530 SDValue V = partitionShuffleOfConcats(N, DAG); 10531 10532 if (V.getNode()) 10533 return V; 10534 } 10535 10536 // If this shuffle node is simply a swizzle of another shuffle node, 10537 // and it reverses the swizzle of the previous shuffle then we can 10538 // optimize shuffle(shuffle(x, undef), undef) -> x. 10539 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG && 10540 N1.getOpcode() == ISD::UNDEF) { 10541 10542 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0); 10543 10544 // Shuffle nodes can only reverse shuffles with a single non-undef value. 10545 if (N0.getOperand(1).getOpcode() != ISD::UNDEF) 10546 return SDValue(); 10547 10548 // The incoming shuffle must be of the same type as the result of the 10549 // current shuffle. 10550 assert(OtherSV->getOperand(0).getValueType() == VT && 10551 "Shuffle types don't match"); 10552 10553 for (unsigned i = 0; i != NumElts; ++i) { 10554 int Idx = SVN->getMaskElt(i); 10555 assert(Idx < (int)NumElts && "Index references undef operand"); 10556 // Next, this index comes from the first value, which is the incoming 10557 // shuffle. Adopt the incoming index. 10558 if (Idx >= 0) 10559 Idx = OtherSV->getMaskElt(Idx); 10560 10561 // The combined shuffle must map each index to itself. 10562 if (Idx >= 0 && (unsigned)Idx != i) 10563 return SDValue(); 10564 } 10565 10566 return OtherSV->getOperand(0); 10567 } 10568 10569 return SDValue(); 10570 } 10571 10572 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) { 10573 SDValue N0 = N->getOperand(0); 10574 SDValue N2 = N->getOperand(2); 10575 10576 // If the input vector is a concatenation, and the insert replaces 10577 // one of the halves, we can optimize into a single concat_vectors. 10578 if (N0.getOpcode() == ISD::CONCAT_VECTORS && 10579 N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) { 10580 APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue(); 10581 EVT VT = N->getValueType(0); 10582 10583 // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) -> 10584 // (concat_vectors Z, Y) 10585 if (InsIdx == 0) 10586 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, 10587 N->getOperand(1), N0.getOperand(1)); 10588 10589 // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) -> 10590 // (concat_vectors X, Z) 10591 if (InsIdx == VT.getVectorNumElements()/2) 10592 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, 10593 N0.getOperand(0), N->getOperand(1)); 10594 } 10595 10596 return SDValue(); 10597 } 10598 10599 /// XformToShuffleWithZero - Returns a vector_shuffle if it able to transform 10600 /// an AND to a vector_shuffle with the destination vector and a zero vector. 10601 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==> 10602 /// vector_shuffle V, Zero, <0, 4, 2, 4> 10603 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) { 10604 EVT VT = N->getValueType(0); 10605 SDLoc dl(N); 10606 SDValue LHS = N->getOperand(0); 10607 SDValue RHS = N->getOperand(1); 10608 if (N->getOpcode() == ISD::AND) { 10609 if (RHS.getOpcode() == ISD::BITCAST) 10610 RHS = RHS.getOperand(0); 10611 if (RHS.getOpcode() == ISD::BUILD_VECTOR) { 10612 SmallVector<int, 8> Indices; 10613 unsigned NumElts = RHS.getNumOperands(); 10614 for (unsigned i = 0; i != NumElts; ++i) { 10615 SDValue Elt = RHS.getOperand(i); 10616 if (!isa<ConstantSDNode>(Elt)) 10617 return SDValue(); 10618 10619 if (cast<ConstantSDNode>(Elt)->isAllOnesValue()) 10620 Indices.push_back(i); 10621 else if (cast<ConstantSDNode>(Elt)->isNullValue()) 10622 Indices.push_back(NumElts); 10623 else 10624 return SDValue(); 10625 } 10626 10627 // Let's see if the target supports this vector_shuffle. 10628 EVT RVT = RHS.getValueType(); 10629 if (!TLI.isVectorClearMaskLegal(Indices, RVT)) 10630 return SDValue(); 10631 10632 // Return the new VECTOR_SHUFFLE node. 10633 EVT EltVT = RVT.getVectorElementType(); 10634 SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(), 10635 DAG.getConstant(0, EltVT)); 10636 SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), 10637 RVT, &ZeroOps[0], ZeroOps.size()); 10638 LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS); 10639 SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]); 10640 return DAG.getNode(ISD::BITCAST, dl, VT, Shuf); 10641 } 10642 } 10643 10644 return SDValue(); 10645 } 10646 10647 /// SimplifyVBinOp - Visit a binary vector operation, like ADD. 10648 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) { 10649 assert(N->getValueType(0).isVector() && 10650 "SimplifyVBinOp only works on vectors!"); 10651 10652 SDValue LHS = N->getOperand(0); 10653 SDValue RHS = N->getOperand(1); 10654 SDValue Shuffle = XformToShuffleWithZero(N); 10655 if (Shuffle.getNode()) return Shuffle; 10656 10657 // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold 10658 // this operation. 10659 if (LHS.getOpcode() == ISD::BUILD_VECTOR && 10660 RHS.getOpcode() == ISD::BUILD_VECTOR) { 10661 // Check if both vectors are constants. If not bail out. 10662 if (!(cast<BuildVectorSDNode>(LHS)->isConstant() && 10663 cast<BuildVectorSDNode>(RHS)->isConstant())) 10664 return SDValue(); 10665 10666 SmallVector<SDValue, 8> Ops; 10667 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) { 10668 SDValue LHSOp = LHS.getOperand(i); 10669 SDValue RHSOp = RHS.getOperand(i); 10670 10671 // Can't fold divide by zero. 10672 if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV || 10673 N->getOpcode() == ISD::FDIV) { 10674 if ((RHSOp.getOpcode() == ISD::Constant && 10675 cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) || 10676 (RHSOp.getOpcode() == ISD::ConstantFP && 10677 cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero())) 10678 break; 10679 } 10680 10681 EVT VT = LHSOp.getValueType(); 10682 EVT RVT = RHSOp.getValueType(); 10683 if (RVT != VT) { 10684 // Integer BUILD_VECTOR operands may have types larger than the element 10685 // size (e.g., when the element type is not legal). Prior to type 10686 // legalization, the types may not match between the two BUILD_VECTORS. 10687 // Truncate one of the operands to make them match. 10688 if (RVT.getSizeInBits() > VT.getSizeInBits()) { 10689 RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp); 10690 } else { 10691 LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp); 10692 VT = RVT; 10693 } 10694 } 10695 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT, 10696 LHSOp, RHSOp); 10697 if (FoldOp.getOpcode() != ISD::UNDEF && 10698 FoldOp.getOpcode() != ISD::Constant && 10699 FoldOp.getOpcode() != ISD::ConstantFP) 10700 break; 10701 Ops.push_back(FoldOp); 10702 AddToWorkList(FoldOp.getNode()); 10703 } 10704 10705 if (Ops.size() == LHS.getNumOperands()) 10706 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), 10707 LHS.getValueType(), &Ops[0], Ops.size()); 10708 } 10709 10710 return SDValue(); 10711 } 10712 10713 /// SimplifyVUnaryOp - Visit a binary vector operation, like FABS/FNEG. 10714 SDValue DAGCombiner::SimplifyVUnaryOp(SDNode *N) { 10715 assert(N->getValueType(0).isVector() && 10716 "SimplifyVUnaryOp only works on vectors!"); 10717 10718 SDValue N0 = N->getOperand(0); 10719 10720 if (N0.getOpcode() != ISD::BUILD_VECTOR) 10721 return SDValue(); 10722 10723 // Operand is a BUILD_VECTOR node, see if we can constant fold it. 10724 SmallVector<SDValue, 8> Ops; 10725 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) { 10726 SDValue Op = N0.getOperand(i); 10727 if (Op.getOpcode() != ISD::UNDEF && 10728 Op.getOpcode() != ISD::ConstantFP) 10729 break; 10730 EVT EltVT = Op.getValueType(); 10731 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(N0), EltVT, Op); 10732 if (FoldOp.getOpcode() != ISD::UNDEF && 10733 FoldOp.getOpcode() != ISD::ConstantFP) 10734 break; 10735 Ops.push_back(FoldOp); 10736 AddToWorkList(FoldOp.getNode()); 10737 } 10738 10739 if (Ops.size() != N0.getNumOperands()) 10740 return SDValue(); 10741 10742 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), 10743 N0.getValueType(), &Ops[0], Ops.size()); 10744 } 10745 10746 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0, 10747 SDValue N1, SDValue N2){ 10748 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!"); 10749 10750 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2, 10751 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 10752 10753 // If we got a simplified select_cc node back from SimplifySelectCC, then 10754 // break it down into a new SETCC node, and a new SELECT node, and then return 10755 // the SELECT node, since we were called with a SELECT node. 10756 if (SCC.getNode()) { 10757 // Check to see if we got a select_cc back (to turn into setcc/select). 10758 // Otherwise, just return whatever node we got back, like fabs. 10759 if (SCC.getOpcode() == ISD::SELECT_CC) { 10760 SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0), 10761 N0.getValueType(), 10762 SCC.getOperand(0), SCC.getOperand(1), 10763 SCC.getOperand(4)); 10764 AddToWorkList(SETCC.getNode()); 10765 return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), 10766 SCC.getOperand(2), SCC.getOperand(3), SETCC); 10767 } 10768 10769 return SCC; 10770 } 10771 return SDValue(); 10772 } 10773 10774 /// SimplifySelectOps - Given a SELECT or a SELECT_CC node, where LHS and RHS 10775 /// are the two values being selected between, see if we can simplify the 10776 /// select. Callers of this should assume that TheSelect is deleted if this 10777 /// returns true. As such, they should return the appropriate thing (e.g. the 10778 /// node) back to the top-level of the DAG combiner loop to avoid it being 10779 /// looked at. 10780 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS, 10781 SDValue RHS) { 10782 10783 // Cannot simplify select with vector condition 10784 if (TheSelect->getOperand(0).getValueType().isVector()) return false; 10785 10786 // If this is a select from two identical things, try to pull the operation 10787 // through the select. 10788 if (LHS.getOpcode() != RHS.getOpcode() || 10789 !LHS.hasOneUse() || !RHS.hasOneUse()) 10790 return false; 10791 10792 // If this is a load and the token chain is identical, replace the select 10793 // of two loads with a load through a select of the address to load from. 10794 // This triggers in things like "select bool X, 10.0, 123.0" after the FP 10795 // constants have been dropped into the constant pool. 10796 if (LHS.getOpcode() == ISD::LOAD) { 10797 LoadSDNode *LLD = cast<LoadSDNode>(LHS); 10798 LoadSDNode *RLD = cast<LoadSDNode>(RHS); 10799 10800 // Token chains must be identical. 10801 if (LHS.getOperand(0) != RHS.getOperand(0) || 10802 // Do not let this transformation reduce the number of volatile loads. 10803 LLD->isVolatile() || RLD->isVolatile() || 10804 // If this is an EXTLOAD, the VT's must match. 10805 LLD->getMemoryVT() != RLD->getMemoryVT() || 10806 // If this is an EXTLOAD, the kind of extension must match. 10807 (LLD->getExtensionType() != RLD->getExtensionType() && 10808 // The only exception is if one of the extensions is anyext. 10809 LLD->getExtensionType() != ISD::EXTLOAD && 10810 RLD->getExtensionType() != ISD::EXTLOAD) || 10811 // FIXME: this discards src value information. This is 10812 // over-conservative. It would be beneficial to be able to remember 10813 // both potential memory locations. Since we are discarding 10814 // src value info, don't do the transformation if the memory 10815 // locations are not in the default address space. 10816 LLD->getPointerInfo().getAddrSpace() != 0 || 10817 RLD->getPointerInfo().getAddrSpace() != 0 || 10818 !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(), 10819 LLD->getBasePtr().getValueType())) 10820 return false; 10821 10822 // Check that the select condition doesn't reach either load. If so, 10823 // folding this will induce a cycle into the DAG. If not, this is safe to 10824 // xform, so create a select of the addresses. 10825 SDValue Addr; 10826 if (TheSelect->getOpcode() == ISD::SELECT) { 10827 SDNode *CondNode = TheSelect->getOperand(0).getNode(); 10828 if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) || 10829 (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode))) 10830 return false; 10831 // The loads must not depend on one another. 10832 if (LLD->isPredecessorOf(RLD) || 10833 RLD->isPredecessorOf(LLD)) 10834 return false; 10835 Addr = DAG.getSelect(SDLoc(TheSelect), 10836 LLD->getBasePtr().getValueType(), 10837 TheSelect->getOperand(0), LLD->getBasePtr(), 10838 RLD->getBasePtr()); 10839 } else { // Otherwise SELECT_CC 10840 SDNode *CondLHS = TheSelect->getOperand(0).getNode(); 10841 SDNode *CondRHS = TheSelect->getOperand(1).getNode(); 10842 10843 if ((LLD->hasAnyUseOfValue(1) && 10844 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) || 10845 (RLD->hasAnyUseOfValue(1) && 10846 (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS)))) 10847 return false; 10848 10849 Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect), 10850 LLD->getBasePtr().getValueType(), 10851 TheSelect->getOperand(0), 10852 TheSelect->getOperand(1), 10853 LLD->getBasePtr(), RLD->getBasePtr(), 10854 TheSelect->getOperand(4)); 10855 } 10856 10857 SDValue Load; 10858 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) { 10859 Load = DAG.getLoad(TheSelect->getValueType(0), 10860 SDLoc(TheSelect), 10861 // FIXME: Discards pointer and TBAA info. 10862 LLD->getChain(), Addr, MachinePointerInfo(), 10863 LLD->isVolatile(), LLD->isNonTemporal(), 10864 LLD->isInvariant(), LLD->getAlignment()); 10865 } else { 10866 Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ? 10867 RLD->getExtensionType() : LLD->getExtensionType(), 10868 SDLoc(TheSelect), 10869 TheSelect->getValueType(0), 10870 // FIXME: Discards pointer and TBAA info. 10871 LLD->getChain(), Addr, MachinePointerInfo(), 10872 LLD->getMemoryVT(), LLD->isVolatile(), 10873 LLD->isNonTemporal(), LLD->getAlignment()); 10874 } 10875 10876 // Users of the select now use the result of the load. 10877 CombineTo(TheSelect, Load); 10878 10879 // Users of the old loads now use the new load's chain. We know the 10880 // old-load value is dead now. 10881 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1)); 10882 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1)); 10883 return true; 10884 } 10885 10886 return false; 10887 } 10888 10889 /// SimplifySelectCC - Simplify an expression of the form (N0 cond N1) ? N2 : N3 10890 /// where 'cond' is the comparison specified by CC. 10891 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, 10892 SDValue N2, SDValue N3, 10893 ISD::CondCode CC, bool NotExtCompare) { 10894 // (x ? y : y) -> y. 10895 if (N2 == N3) return N2; 10896 10897 EVT VT = N2.getValueType(); 10898 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode()); 10899 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode()); 10900 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode()); 10901 10902 // Determine if the condition we're dealing with is constant 10903 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()), 10904 N0, N1, CC, DL, false); 10905 if (SCC.getNode()) AddToWorkList(SCC.getNode()); 10906 ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode()); 10907 10908 // fold select_cc true, x, y -> x 10909 if (SCCC && !SCCC->isNullValue()) 10910 return N2; 10911 // fold select_cc false, x, y -> y 10912 if (SCCC && SCCC->isNullValue()) 10913 return N3; 10914 10915 // Check to see if we can simplify the select into an fabs node 10916 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) { 10917 // Allow either -0.0 or 0.0 10918 if (CFP->getValueAPF().isZero()) { 10919 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs 10920 if ((CC == ISD::SETGE || CC == ISD::SETGT) && 10921 N0 == N2 && N3.getOpcode() == ISD::FNEG && 10922 N2 == N3.getOperand(0)) 10923 return DAG.getNode(ISD::FABS, DL, VT, N0); 10924 10925 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs 10926 if ((CC == ISD::SETLT || CC == ISD::SETLE) && 10927 N0 == N3 && N2.getOpcode() == ISD::FNEG && 10928 N2.getOperand(0) == N3) 10929 return DAG.getNode(ISD::FABS, DL, VT, N3); 10930 } 10931 } 10932 10933 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)" 10934 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0 10935 // in it. This is a win when the constant is not otherwise available because 10936 // it replaces two constant pool loads with one. We only do this if the FP 10937 // type is known to be legal, because if it isn't, then we are before legalize 10938 // types an we want the other legalization to happen first (e.g. to avoid 10939 // messing with soft float) and if the ConstantFP is not legal, because if 10940 // it is legal, we may not need to store the FP constant in a constant pool. 10941 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2)) 10942 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) { 10943 if (TLI.isTypeLegal(N2.getValueType()) && 10944 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) != 10945 TargetLowering::Legal && 10946 !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) && 10947 !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) && 10948 // If both constants have multiple uses, then we won't need to do an 10949 // extra load, they are likely around in registers for other users. 10950 (TV->hasOneUse() || FV->hasOneUse())) { 10951 Constant *Elts[] = { 10952 const_cast<ConstantFP*>(FV->getConstantFPValue()), 10953 const_cast<ConstantFP*>(TV->getConstantFPValue()) 10954 }; 10955 Type *FPTy = Elts[0]->getType(); 10956 const DataLayout &TD = *TLI.getDataLayout(); 10957 10958 // Create a ConstantArray of the two constants. 10959 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts); 10960 SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(), 10961 TD.getPrefTypeAlignment(FPTy)); 10962 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment(); 10963 10964 // Get the offsets to the 0 and 1 element of the array so that we can 10965 // select between them. 10966 SDValue Zero = DAG.getIntPtrConstant(0); 10967 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType()); 10968 SDValue One = DAG.getIntPtrConstant(EltSize); 10969 10970 SDValue Cond = DAG.getSetCC(DL, 10971 getSetCCResultType(N0.getValueType()), 10972 N0, N1, CC); 10973 AddToWorkList(Cond.getNode()); 10974 SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(), 10975 Cond, One, Zero); 10976 AddToWorkList(CstOffset.getNode()); 10977 CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx, 10978 CstOffset); 10979 AddToWorkList(CPIdx.getNode()); 10980 return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx, 10981 MachinePointerInfo::getConstantPool(), false, 10982 false, false, Alignment); 10983 10984 } 10985 } 10986 10987 // Check to see if we can perform the "gzip trick", transforming 10988 // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A) 10989 if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT && 10990 (N1C->isNullValue() || // (a < 0) ? b : 0 10991 (N1C->getAPIntValue() == 1 && N0 == N2))) { // (a < 1) ? a : 0 10992 EVT XType = N0.getValueType(); 10993 EVT AType = N2.getValueType(); 10994 if (XType.bitsGE(AType)) { 10995 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a 10996 // single-bit constant. 10997 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) { 10998 unsigned ShCtV = N2C->getAPIntValue().logBase2(); 10999 ShCtV = XType.getSizeInBits()-ShCtV-1; 11000 SDValue ShCt = DAG.getConstant(ShCtV, 11001 getShiftAmountTy(N0.getValueType())); 11002 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), 11003 XType, N0, ShCt); 11004 AddToWorkList(Shift.getNode()); 11005 11006 if (XType.bitsGT(AType)) { 11007 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift); 11008 AddToWorkList(Shift.getNode()); 11009 } 11010 11011 return DAG.getNode(ISD::AND, DL, AType, Shift, N2); 11012 } 11013 11014 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), 11015 XType, N0, 11016 DAG.getConstant(XType.getSizeInBits()-1, 11017 getShiftAmountTy(N0.getValueType()))); 11018 AddToWorkList(Shift.getNode()); 11019 11020 if (XType.bitsGT(AType)) { 11021 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift); 11022 AddToWorkList(Shift.getNode()); 11023 } 11024 11025 return DAG.getNode(ISD::AND, DL, AType, Shift, N2); 11026 } 11027 } 11028 11029 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A) 11030 // where y is has a single bit set. 11031 // A plaintext description would be, we can turn the SELECT_CC into an AND 11032 // when the condition can be materialized as an all-ones register. Any 11033 // single bit-test can be materialized as an all-ones register with 11034 // shift-left and shift-right-arith. 11035 if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND && 11036 N0->getValueType(0) == VT && 11037 N1C && N1C->isNullValue() && 11038 N2C && N2C->isNullValue()) { 11039 SDValue AndLHS = N0->getOperand(0); 11040 ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 11041 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) { 11042 // Shift the tested bit over the sign bit. 11043 APInt AndMask = ConstAndRHS->getAPIntValue(); 11044 SDValue ShlAmt = 11045 DAG.getConstant(AndMask.countLeadingZeros(), 11046 getShiftAmountTy(AndLHS.getValueType())); 11047 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt); 11048 11049 // Now arithmetic right shift it all the way over, so the result is either 11050 // all-ones, or zero. 11051 SDValue ShrAmt = 11052 DAG.getConstant(AndMask.getBitWidth()-1, 11053 getShiftAmountTy(Shl.getValueType())); 11054 SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt); 11055 11056 return DAG.getNode(ISD::AND, DL, VT, Shr, N3); 11057 } 11058 } 11059 11060 // fold select C, 16, 0 -> shl C, 4 11061 if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() && 11062 TLI.getBooleanContents(N0.getValueType().isVector()) == 11063 TargetLowering::ZeroOrOneBooleanContent) { 11064 11065 // If the caller doesn't want us to simplify this into a zext of a compare, 11066 // don't do it. 11067 if (NotExtCompare && N2C->getAPIntValue() == 1) 11068 return SDValue(); 11069 11070 // Get a SetCC of the condition 11071 // NOTE: Don't create a SETCC if it's not legal on this target. 11072 if (!LegalOperations || 11073 TLI.isOperationLegal(ISD::SETCC, 11074 LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) { 11075 SDValue Temp, SCC; 11076 // cast from setcc result type to select result type 11077 if (LegalTypes) { 11078 SCC = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()), 11079 N0, N1, CC); 11080 if (N2.getValueType().bitsLT(SCC.getValueType())) 11081 Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2), 11082 N2.getValueType()); 11083 else 11084 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2), 11085 N2.getValueType(), SCC); 11086 } else { 11087 SCC = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC); 11088 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2), 11089 N2.getValueType(), SCC); 11090 } 11091 11092 AddToWorkList(SCC.getNode()); 11093 AddToWorkList(Temp.getNode()); 11094 11095 if (N2C->getAPIntValue() == 1) 11096 return Temp; 11097 11098 // shl setcc result by log2 n2c 11099 return DAG.getNode( 11100 ISD::SHL, DL, N2.getValueType(), Temp, 11101 DAG.getConstant(N2C->getAPIntValue().logBase2(), 11102 getShiftAmountTy(Temp.getValueType()))); 11103 } 11104 } 11105 11106 // Check to see if this is the equivalent of setcc 11107 // FIXME: Turn all of these into setcc if setcc if setcc is legal 11108 // otherwise, go ahead with the folds. 11109 if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) { 11110 EVT XType = N0.getValueType(); 11111 if (!LegalOperations || 11112 TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) { 11113 SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC); 11114 if (Res.getValueType() != VT) 11115 Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res); 11116 return Res; 11117 } 11118 11119 // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X)))) 11120 if (N1C && N1C->isNullValue() && CC == ISD::SETEQ && 11121 (!LegalOperations || 11122 TLI.isOperationLegal(ISD::CTLZ, XType))) { 11123 SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0); 11124 return DAG.getNode(ISD::SRL, DL, XType, Ctlz, 11125 DAG.getConstant(Log2_32(XType.getSizeInBits()), 11126 getShiftAmountTy(Ctlz.getValueType()))); 11127 } 11128 // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1)) 11129 if (N1C && N1C->isNullValue() && CC == ISD::SETGT) { 11130 SDValue NegN0 = DAG.getNode(ISD::SUB, SDLoc(N0), 11131 XType, DAG.getConstant(0, XType), N0); 11132 SDValue NotN0 = DAG.getNOT(SDLoc(N0), N0, XType); 11133 return DAG.getNode(ISD::SRL, DL, XType, 11134 DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0), 11135 DAG.getConstant(XType.getSizeInBits()-1, 11136 getShiftAmountTy(XType))); 11137 } 11138 // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1)) 11139 if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) { 11140 SDValue Sign = DAG.getNode(ISD::SRL, SDLoc(N0), XType, N0, 11141 DAG.getConstant(XType.getSizeInBits()-1, 11142 getShiftAmountTy(N0.getValueType()))); 11143 return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType)); 11144 } 11145 } 11146 11147 // Check to see if this is an integer abs. 11148 // select_cc setg[te] X, 0, X, -X -> 11149 // select_cc setgt X, -1, X, -X -> 11150 // select_cc setl[te] X, 0, -X, X -> 11151 // select_cc setlt X, 1, -X, X -> 11152 // Y = sra (X, size(X)-1); xor (add (X, Y), Y) 11153 if (N1C) { 11154 ConstantSDNode *SubC = nullptr; 11155 if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) || 11156 (N1C->isAllOnesValue() && CC == ISD::SETGT)) && 11157 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1)) 11158 SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0)); 11159 else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) || 11160 (N1C->isOne() && CC == ISD::SETLT)) && 11161 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1)) 11162 SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0)); 11163 11164 EVT XType = N0.getValueType(); 11165 if (SubC && SubC->isNullValue() && XType.isInteger()) { 11166 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), XType, 11167 N0, 11168 DAG.getConstant(XType.getSizeInBits()-1, 11169 getShiftAmountTy(N0.getValueType()))); 11170 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0), 11171 XType, N0, Shift); 11172 AddToWorkList(Shift.getNode()); 11173 AddToWorkList(Add.getNode()); 11174 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift); 11175 } 11176 } 11177 11178 return SDValue(); 11179 } 11180 11181 /// SimplifySetCC - This is a stub for TargetLowering::SimplifySetCC. 11182 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0, 11183 SDValue N1, ISD::CondCode Cond, 11184 SDLoc DL, bool foldBooleans) { 11185 TargetLowering::DAGCombinerInfo 11186 DagCombineInfo(DAG, Level, false, this); 11187 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL); 11188 } 11189 11190 /// BuildSDIVSequence - Given an ISD::SDIV node expressing a divide by constant, 11191 /// return a DAG expression to select that will generate the same value by 11192 /// multiplying by a magic number. See: 11193 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html> 11194 SDValue DAGCombiner::BuildSDIV(SDNode *N) { 11195 std::vector<SDNode*> Built; 11196 SDValue S = TLI.BuildSDIV(N, DAG, LegalOperations, &Built); 11197 11198 for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end(); 11199 ii != ee; ++ii) 11200 AddToWorkList(*ii); 11201 return S; 11202 } 11203 11204 /// BuildUDIVSequence - Given an ISD::UDIV node expressing a divide by constant, 11205 /// return a DAG expression to select that will generate the same value by 11206 /// multiplying by a magic number. See: 11207 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html> 11208 SDValue DAGCombiner::BuildUDIV(SDNode *N) { 11209 std::vector<SDNode*> Built; 11210 SDValue S = TLI.BuildUDIV(N, DAG, LegalOperations, &Built); 11211 11212 for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end(); 11213 ii != ee; ++ii) 11214 AddToWorkList(*ii); 11215 return S; 11216 } 11217 11218 /// FindBaseOffset - Return true if base is a frame index, which is known not 11219 // to alias with anything but itself. Provides base object and offset as 11220 // results. 11221 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset, 11222 const GlobalValue *&GV, const void *&CV) { 11223 // Assume it is a primitive operation. 11224 Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr; 11225 11226 // If it's an adding a simple constant then integrate the offset. 11227 if (Base.getOpcode() == ISD::ADD) { 11228 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) { 11229 Base = Base.getOperand(0); 11230 Offset += C->getZExtValue(); 11231 } 11232 } 11233 11234 // Return the underlying GlobalValue, and update the Offset. Return false 11235 // for GlobalAddressSDNode since the same GlobalAddress may be represented 11236 // by multiple nodes with different offsets. 11237 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) { 11238 GV = G->getGlobal(); 11239 Offset += G->getOffset(); 11240 return false; 11241 } 11242 11243 // Return the underlying Constant value, and update the Offset. Return false 11244 // for ConstantSDNodes since the same constant pool entry may be represented 11245 // by multiple nodes with different offsets. 11246 if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) { 11247 CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal() 11248 : (const void *)C->getConstVal(); 11249 Offset += C->getOffset(); 11250 return false; 11251 } 11252 // If it's any of the following then it can't alias with anything but itself. 11253 return isa<FrameIndexSDNode>(Base); 11254 } 11255 11256 /// isAlias - Return true if there is any possibility that the two addresses 11257 /// overlap. 11258 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const { 11259 // If they are the same then they must be aliases. 11260 if (Op0->getBasePtr() == Op1->getBasePtr()) return true; 11261 11262 // If they are both volatile then they cannot be reordered. 11263 if (Op0->isVolatile() && Op1->isVolatile()) return true; 11264 11265 // Gather base node and offset information. 11266 SDValue Base1, Base2; 11267 int64_t Offset1, Offset2; 11268 const GlobalValue *GV1, *GV2; 11269 const void *CV1, *CV2; 11270 bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(), 11271 Base1, Offset1, GV1, CV1); 11272 bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(), 11273 Base2, Offset2, GV2, CV2); 11274 11275 // If they have a same base address then check to see if they overlap. 11276 if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2))) 11277 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 || 11278 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1); 11279 11280 // It is possible for different frame indices to alias each other, mostly 11281 // when tail call optimization reuses return address slots for arguments. 11282 // To catch this case, look up the actual index of frame indices to compute 11283 // the real alias relationship. 11284 if (isFrameIndex1 && isFrameIndex2) { 11285 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo(); 11286 Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex()); 11287 Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex()); 11288 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 || 11289 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1); 11290 } 11291 11292 // Otherwise, if we know what the bases are, and they aren't identical, then 11293 // we know they cannot alias. 11294 if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2)) 11295 return false; 11296 11297 // If we know required SrcValue1 and SrcValue2 have relatively large alignment 11298 // compared to the size and offset of the access, we may be able to prove they 11299 // do not alias. This check is conservative for now to catch cases created by 11300 // splitting vector types. 11301 if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) && 11302 (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) && 11303 (Op0->getMemoryVT().getSizeInBits() >> 3 == 11304 Op1->getMemoryVT().getSizeInBits() >> 3) && 11305 (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) { 11306 int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment(); 11307 int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment(); 11308 11309 // There is no overlap between these relatively aligned accesses of similar 11310 // size, return no alias. 11311 if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 || 11312 (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1) 11313 return false; 11314 } 11315 11316 bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0 ? CombinerGlobalAA : 11317 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA(); 11318 #ifndef NDEBUG 11319 if (CombinerAAOnlyFunc.getNumOccurrences() && 11320 CombinerAAOnlyFunc != DAG.getMachineFunction().getName()) 11321 UseAA = false; 11322 #endif 11323 if (UseAA && 11324 Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) { 11325 // Use alias analysis information. 11326 int64_t MinOffset = std::min(Op0->getSrcValueOffset(), 11327 Op1->getSrcValueOffset()); 11328 int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) + 11329 Op0->getSrcValueOffset() - MinOffset; 11330 int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) + 11331 Op1->getSrcValueOffset() - MinOffset; 11332 AliasAnalysis::AliasResult AAResult = 11333 AA.alias(AliasAnalysis::Location(Op0->getMemOperand()->getValue(), 11334 Overlap1, 11335 UseTBAA ? Op0->getTBAAInfo() : nullptr), 11336 AliasAnalysis::Location(Op1->getMemOperand()->getValue(), 11337 Overlap2, 11338 UseTBAA ? Op1->getTBAAInfo() : nullptr)); 11339 if (AAResult == AliasAnalysis::NoAlias) 11340 return false; 11341 } 11342 11343 // Otherwise we have to assume they alias. 11344 return true; 11345 } 11346 11347 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes, 11348 /// looking for aliasing nodes and adding them to the Aliases vector. 11349 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain, 11350 SmallVectorImpl<SDValue> &Aliases) { 11351 SmallVector<SDValue, 8> Chains; // List of chains to visit. 11352 SmallPtrSet<SDNode *, 16> Visited; // Visited node set. 11353 11354 // Get alias information for node. 11355 bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile(); 11356 11357 // Starting off. 11358 Chains.push_back(OriginalChain); 11359 unsigned Depth = 0; 11360 11361 // Look at each chain and determine if it is an alias. If so, add it to the 11362 // aliases list. If not, then continue up the chain looking for the next 11363 // candidate. 11364 while (!Chains.empty()) { 11365 SDValue Chain = Chains.back(); 11366 Chains.pop_back(); 11367 11368 // For TokenFactor nodes, look at each operand and only continue up the 11369 // chain until we find two aliases. If we've seen two aliases, assume we'll 11370 // find more and revert to original chain since the xform is unlikely to be 11371 // profitable. 11372 // 11373 // FIXME: The depth check could be made to return the last non-aliasing 11374 // chain we found before we hit a tokenfactor rather than the original 11375 // chain. 11376 if (Depth > 6 || Aliases.size() == 2) { 11377 Aliases.clear(); 11378 Aliases.push_back(OriginalChain); 11379 return; 11380 } 11381 11382 // Don't bother if we've been before. 11383 if (!Visited.insert(Chain.getNode())) 11384 continue; 11385 11386 switch (Chain.getOpcode()) { 11387 case ISD::EntryToken: 11388 // Entry token is ideal chain operand, but handled in FindBetterChain. 11389 break; 11390 11391 case ISD::LOAD: 11392 case ISD::STORE: { 11393 // Get alias information for Chain. 11394 bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) && 11395 !cast<LSBaseSDNode>(Chain.getNode())->isVolatile(); 11396 11397 // If chain is alias then stop here. 11398 if (!(IsLoad && IsOpLoad) && 11399 isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) { 11400 Aliases.push_back(Chain); 11401 } else { 11402 // Look further up the chain. 11403 Chains.push_back(Chain.getOperand(0)); 11404 ++Depth; 11405 } 11406 break; 11407 } 11408 11409 case ISD::TokenFactor: 11410 // We have to check each of the operands of the token factor for "small" 11411 // token factors, so we queue them up. Adding the operands to the queue 11412 // (stack) in reverse order maintains the original order and increases the 11413 // likelihood that getNode will find a matching token factor (CSE.) 11414 if (Chain.getNumOperands() > 16) { 11415 Aliases.push_back(Chain); 11416 break; 11417 } 11418 for (unsigned n = Chain.getNumOperands(); n;) 11419 Chains.push_back(Chain.getOperand(--n)); 11420 ++Depth; 11421 break; 11422 11423 default: 11424 // For all other instructions we will just have to take what we can get. 11425 Aliases.push_back(Chain); 11426 break; 11427 } 11428 } 11429 11430 // We need to be careful here to also search for aliases through the 11431 // value operand of a store, etc. Consider the following situation: 11432 // Token1 = ... 11433 // L1 = load Token1, %52 11434 // S1 = store Token1, L1, %51 11435 // L2 = load Token1, %52+8 11436 // S2 = store Token1, L2, %51+8 11437 // Token2 = Token(S1, S2) 11438 // L3 = load Token2, %53 11439 // S3 = store Token2, L3, %52 11440 // L4 = load Token2, %53+8 11441 // S4 = store Token2, L4, %52+8 11442 // If we search for aliases of S3 (which loads address %52), and we look 11443 // only through the chain, then we'll miss the trivial dependence on L1 11444 // (which also loads from %52). We then might change all loads and 11445 // stores to use Token1 as their chain operand, which could result in 11446 // copying %53 into %52 before copying %52 into %51 (which should 11447 // happen first). 11448 // 11449 // The problem is, however, that searching for such data dependencies 11450 // can become expensive, and the cost is not directly related to the 11451 // chain depth. Instead, we'll rule out such configurations here by 11452 // insisting that we've visited all chain users (except for users 11453 // of the original chain, which is not necessary). When doing this, 11454 // we need to look through nodes we don't care about (otherwise, things 11455 // like register copies will interfere with trivial cases). 11456 11457 SmallVector<const SDNode *, 16> Worklist; 11458 for (SmallPtrSet<SDNode *, 16>::iterator I = Visited.begin(), 11459 IE = Visited.end(); I != IE; ++I) 11460 if (*I != OriginalChain.getNode()) 11461 Worklist.push_back(*I); 11462 11463 while (!Worklist.empty()) { 11464 const SDNode *M = Worklist.pop_back_val(); 11465 11466 // We have already visited M, and want to make sure we've visited any uses 11467 // of M that we care about. For uses that we've not visisted, and don't 11468 // care about, queue them to the worklist. 11469 11470 for (SDNode::use_iterator UI = M->use_begin(), 11471 UIE = M->use_end(); UI != UIE; ++UI) 11472 if (UI.getUse().getValueType() == MVT::Other && Visited.insert(*UI)) { 11473 if (isa<MemIntrinsicSDNode>(*UI) || isa<MemSDNode>(*UI)) { 11474 // We've not visited this use, and we care about it (it could have an 11475 // ordering dependency with the original node). 11476 Aliases.clear(); 11477 Aliases.push_back(OriginalChain); 11478 return; 11479 } 11480 11481 // We've not visited this use, but we don't care about it. Mark it as 11482 // visited and enqueue it to the worklist. 11483 Worklist.push_back(*UI); 11484 } 11485 } 11486 } 11487 11488 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes, looking 11489 /// for a better chain (aliasing node.) 11490 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) { 11491 SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor. 11492 11493 // Accumulate all the aliases to this node. 11494 GatherAllAliases(N, OldChain, Aliases); 11495 11496 // If no operands then chain to entry token. 11497 if (Aliases.size() == 0) 11498 return DAG.getEntryNode(); 11499 11500 // If a single operand then chain to it. We don't need to revisit it. 11501 if (Aliases.size() == 1) 11502 return Aliases[0]; 11503 11504 // Construct a custom tailored token factor. 11505 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, 11506 &Aliases[0], Aliases.size()); 11507 } 11508 11509 // SelectionDAG::Combine - This is the entry point for the file. 11510 // 11511 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA, 11512 CodeGenOpt::Level OptLevel) { 11513 /// run - This is the main entry point to this class. 11514 /// 11515 DAGCombiner(*this, AA, OptLevel).Run(Level); 11516 } 11517