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/DerivedTypes.h" 22 #include "llvm/LLVMContext.h" 23 #include "llvm/CodeGen/MachineFunction.h" 24 #include "llvm/CodeGen/MachineFrameInfo.h" 25 #include "llvm/CodeGen/PseudoSourceValue.h" 26 #include "llvm/Analysis/AliasAnalysis.h" 27 #include "llvm/Target/TargetData.h" 28 #include "llvm/Target/TargetFrameInfo.h" 29 #include "llvm/Target/TargetLowering.h" 30 #include "llvm/Target/TargetMachine.h" 31 #include "llvm/Target/TargetOptions.h" 32 #include "llvm/ADT/SmallPtrSet.h" 33 #include "llvm/ADT/Statistic.h" 34 #include "llvm/Support/CommandLine.h" 35 #include "llvm/Support/Debug.h" 36 #include "llvm/Support/ErrorHandling.h" 37 #include "llvm/Support/MathExtras.h" 38 #include "llvm/Support/raw_ostream.h" 39 #include <algorithm> 40 using namespace llvm; 41 42 STATISTIC(NodesCombined , "Number of dag nodes combined"); 43 STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created"); 44 STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created"); 45 STATISTIC(OpsNarrowed , "Number of load/op/store narrowed"); 46 47 namespace { 48 static cl::opt<bool> 49 CombinerAA("combiner-alias-analysis", cl::Hidden, 50 cl::desc("Turn on alias analysis during testing")); 51 52 static cl::opt<bool> 53 CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden, 54 cl::desc("Include global information in alias analysis")); 55 56 //------------------------------ DAGCombiner ---------------------------------// 57 58 class DAGCombiner { 59 SelectionDAG &DAG; 60 const TargetLowering &TLI; 61 CombineLevel Level; 62 CodeGenOpt::Level OptLevel; 63 bool LegalOperations; 64 bool LegalTypes; 65 66 // Worklist of all of the nodes that need to be simplified. 67 std::vector<SDNode*> WorkList; 68 69 // AA - Used for DAG load/store alias analysis. 70 AliasAnalysis &AA; 71 72 /// AddUsersToWorkList - When an instruction is simplified, add all users of 73 /// the instruction to the work lists because they might get more simplified 74 /// now. 75 /// 76 void AddUsersToWorkList(SDNode *N) { 77 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end(); 78 UI != UE; ++UI) 79 AddToWorkList(*UI); 80 } 81 82 /// visit - call the node-specific routine that knows how to fold each 83 /// particular type of node. 84 SDValue visit(SDNode *N); 85 86 public: 87 /// AddToWorkList - Add to the work list making sure it's instance is at the 88 /// the back (next to be processed.) 89 void AddToWorkList(SDNode *N) { 90 removeFromWorkList(N); 91 WorkList.push_back(N); 92 } 93 94 /// removeFromWorkList - remove all instances of N from the worklist. 95 /// 96 void removeFromWorkList(SDNode *N) { 97 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), N), 98 WorkList.end()); 99 } 100 101 SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo, 102 bool AddTo = true); 103 104 SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) { 105 return CombineTo(N, &Res, 1, AddTo); 106 } 107 108 SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1, 109 bool AddTo = true) { 110 SDValue To[] = { Res0, Res1 }; 111 return CombineTo(N, To, 2, AddTo); 112 } 113 114 void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO); 115 116 private: 117 118 /// SimplifyDemandedBits - Check the specified integer node value to see if 119 /// it can be simplified or if things it uses can be simplified by bit 120 /// propagation. If so, return true. 121 bool SimplifyDemandedBits(SDValue Op) { 122 unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits(); 123 APInt Demanded = APInt::getAllOnesValue(BitWidth); 124 return SimplifyDemandedBits(Op, Demanded); 125 } 126 127 bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded); 128 129 bool CombineToPreIndexedLoadStore(SDNode *N); 130 bool CombineToPostIndexedLoadStore(SDNode *N); 131 132 void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad); 133 SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace); 134 SDValue SExtPromoteOperand(SDValue Op, EVT PVT); 135 SDValue ZExtPromoteOperand(SDValue Op, EVT PVT); 136 SDValue PromoteIntBinOp(SDValue Op); 137 SDValue PromoteIntShiftOp(SDValue Op); 138 SDValue PromoteExtend(SDValue Op); 139 bool PromoteLoad(SDValue Op); 140 141 /// combine - call the node-specific routine that knows how to fold each 142 /// particular type of node. If that doesn't do anything, try the 143 /// target-specific DAG combines. 144 SDValue combine(SDNode *N); 145 146 // Visitation implementation - Implement dag node combining for different 147 // node types. The semantics are as follows: 148 // Return Value: 149 // SDValue.getNode() == 0 - No change was made 150 // SDValue.getNode() == N - N was replaced, is dead and has been handled. 151 // otherwise - N should be replaced by the returned Operand. 152 // 153 SDValue visitTokenFactor(SDNode *N); 154 SDValue visitMERGE_VALUES(SDNode *N); 155 SDValue visitADD(SDNode *N); 156 SDValue visitSUB(SDNode *N); 157 SDValue visitADDC(SDNode *N); 158 SDValue visitADDE(SDNode *N); 159 SDValue visitMUL(SDNode *N); 160 SDValue visitSDIV(SDNode *N); 161 SDValue visitUDIV(SDNode *N); 162 SDValue visitSREM(SDNode *N); 163 SDValue visitUREM(SDNode *N); 164 SDValue visitMULHU(SDNode *N); 165 SDValue visitMULHS(SDNode *N); 166 SDValue visitSMUL_LOHI(SDNode *N); 167 SDValue visitUMUL_LOHI(SDNode *N); 168 SDValue visitSDIVREM(SDNode *N); 169 SDValue visitUDIVREM(SDNode *N); 170 SDValue visitAND(SDNode *N); 171 SDValue visitOR(SDNode *N); 172 SDValue visitXOR(SDNode *N); 173 SDValue SimplifyVBinOp(SDNode *N); 174 SDValue visitSHL(SDNode *N); 175 SDValue visitSRA(SDNode *N); 176 SDValue visitSRL(SDNode *N); 177 SDValue visitCTLZ(SDNode *N); 178 SDValue visitCTTZ(SDNode *N); 179 SDValue visitCTPOP(SDNode *N); 180 SDValue visitSELECT(SDNode *N); 181 SDValue visitSELECT_CC(SDNode *N); 182 SDValue visitSETCC(SDNode *N); 183 SDValue visitSIGN_EXTEND(SDNode *N); 184 SDValue visitZERO_EXTEND(SDNode *N); 185 SDValue visitANY_EXTEND(SDNode *N); 186 SDValue visitSIGN_EXTEND_INREG(SDNode *N); 187 SDValue visitTRUNCATE(SDNode *N); 188 SDValue visitBIT_CONVERT(SDNode *N); 189 SDValue visitBUILD_PAIR(SDNode *N); 190 SDValue visitFADD(SDNode *N); 191 SDValue visitFSUB(SDNode *N); 192 SDValue visitFMUL(SDNode *N); 193 SDValue visitFDIV(SDNode *N); 194 SDValue visitFREM(SDNode *N); 195 SDValue visitFCOPYSIGN(SDNode *N); 196 SDValue visitSINT_TO_FP(SDNode *N); 197 SDValue visitUINT_TO_FP(SDNode *N); 198 SDValue visitFP_TO_SINT(SDNode *N); 199 SDValue visitFP_TO_UINT(SDNode *N); 200 SDValue visitFP_ROUND(SDNode *N); 201 SDValue visitFP_ROUND_INREG(SDNode *N); 202 SDValue visitFP_EXTEND(SDNode *N); 203 SDValue visitFNEG(SDNode *N); 204 SDValue visitFABS(SDNode *N); 205 SDValue visitBRCOND(SDNode *N); 206 SDValue visitBR_CC(SDNode *N); 207 SDValue visitLOAD(SDNode *N); 208 SDValue visitSTORE(SDNode *N); 209 SDValue visitINSERT_VECTOR_ELT(SDNode *N); 210 SDValue visitEXTRACT_VECTOR_ELT(SDNode *N); 211 SDValue visitBUILD_VECTOR(SDNode *N); 212 SDValue visitCONCAT_VECTORS(SDNode *N); 213 SDValue visitVECTOR_SHUFFLE(SDNode *N); 214 215 SDValue XformToShuffleWithZero(SDNode *N); 216 SDValue ReassociateOps(unsigned Opc, DebugLoc DL, SDValue LHS, SDValue RHS); 217 218 SDValue visitShiftByConstant(SDNode *N, unsigned Amt); 219 220 bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS); 221 SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N); 222 SDValue SimplifySelect(DebugLoc DL, SDValue N0, SDValue N1, SDValue N2); 223 SDValue SimplifySelectCC(DebugLoc DL, SDValue N0, SDValue N1, SDValue N2, 224 SDValue N3, ISD::CondCode CC, 225 bool NotExtCompare = false); 226 SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond, 227 DebugLoc DL, bool foldBooleans = true); 228 SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp, 229 unsigned HiOp); 230 SDValue CombineConsecutiveLoads(SDNode *N, EVT VT); 231 SDValue ConstantFoldBIT_CONVERTofBUILD_VECTOR(SDNode *, EVT); 232 SDValue BuildSDIV(SDNode *N); 233 SDValue BuildUDIV(SDNode *N); 234 SDNode *MatchRotate(SDValue LHS, SDValue RHS, DebugLoc DL); 235 SDValue ReduceLoadWidth(SDNode *N); 236 SDValue ReduceLoadOpStoreWidth(SDNode *N); 237 238 SDValue GetDemandedBits(SDValue V, const APInt &Mask); 239 240 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes, 241 /// looking for aliasing nodes and adding them to the Aliases vector. 242 void GatherAllAliases(SDNode *N, SDValue OriginalChain, 243 SmallVector<SDValue, 8> &Aliases); 244 245 /// isAlias - Return true if there is any possibility that the two addresses 246 /// overlap. 247 bool isAlias(SDValue Ptr1, int64_t Size1, 248 const Value *SrcValue1, int SrcValueOffset1, 249 unsigned SrcValueAlign1, 250 SDValue Ptr2, int64_t Size2, 251 const Value *SrcValue2, int SrcValueOffset2, 252 unsigned SrcValueAlign2) const; 253 254 /// FindAliasInfo - Extracts the relevant alias information from the memory 255 /// node. Returns true if the operand was a load. 256 bool FindAliasInfo(SDNode *N, 257 SDValue &Ptr, int64_t &Size, 258 const Value *&SrcValue, int &SrcValueOffset, 259 unsigned &SrcValueAlignment) const; 260 261 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes, 262 /// looking for a better chain (aliasing node.) 263 SDValue FindBetterChain(SDNode *N, SDValue Chain); 264 265 public: 266 DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL) 267 : DAG(D), TLI(D.getTargetLoweringInfo()), Level(Unrestricted), 268 OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {} 269 270 /// Run - runs the dag combiner on all nodes in the work list 271 void Run(CombineLevel AtLevel); 272 273 SelectionDAG &getDAG() const { return DAG; } 274 275 /// getShiftAmountTy - Returns a type large enough to hold any valid 276 /// shift amount - before type legalization these can be huge. 277 EVT getShiftAmountTy() { 278 return LegalTypes ? TLI.getShiftAmountTy() : TLI.getPointerTy(); 279 } 280 281 /// isTypeLegal - This method returns true if we are running before type 282 /// legalization or if the specified VT is legal. 283 bool isTypeLegal(const EVT &VT) { 284 if (!LegalTypes) return true; 285 return TLI.isTypeLegal(VT); 286 } 287 }; 288 } 289 290 291 namespace { 292 /// WorkListRemover - This class is a DAGUpdateListener that removes any deleted 293 /// nodes from the worklist. 294 class WorkListRemover : public SelectionDAG::DAGUpdateListener { 295 DAGCombiner &DC; 296 public: 297 explicit WorkListRemover(DAGCombiner &dc) : DC(dc) {} 298 299 virtual void NodeDeleted(SDNode *N, SDNode *E) { 300 DC.removeFromWorkList(N); 301 } 302 303 virtual void NodeUpdated(SDNode *N) { 304 // Ignore updates. 305 } 306 }; 307 } 308 309 //===----------------------------------------------------------------------===// 310 // TargetLowering::DAGCombinerInfo implementation 311 //===----------------------------------------------------------------------===// 312 313 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) { 314 ((DAGCombiner*)DC)->AddToWorkList(N); 315 } 316 317 SDValue TargetLowering::DAGCombinerInfo:: 318 CombineTo(SDNode *N, const std::vector<SDValue> &To, bool AddTo) { 319 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo); 320 } 321 322 SDValue TargetLowering::DAGCombinerInfo:: 323 CombineTo(SDNode *N, SDValue Res, bool AddTo) { 324 return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo); 325 } 326 327 328 SDValue TargetLowering::DAGCombinerInfo:: 329 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) { 330 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo); 331 } 332 333 void TargetLowering::DAGCombinerInfo:: 334 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) { 335 return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO); 336 } 337 338 //===----------------------------------------------------------------------===// 339 // Helper Functions 340 //===----------------------------------------------------------------------===// 341 342 /// isNegatibleForFree - Return 1 if we can compute the negated form of the 343 /// specified expression for the same cost as the expression itself, or 2 if we 344 /// can compute the negated form more cheaply than the expression itself. 345 static char isNegatibleForFree(SDValue Op, bool LegalOperations, 346 unsigned Depth = 0) { 347 // No compile time optimizations on this type. 348 if (Op.getValueType() == MVT::ppcf128) 349 return 0; 350 351 // fneg is removable even if it has multiple uses. 352 if (Op.getOpcode() == ISD::FNEG) return 2; 353 354 // Don't allow anything with multiple uses. 355 if (!Op.hasOneUse()) return 0; 356 357 // Don't recurse exponentially. 358 if (Depth > 6) return 0; 359 360 switch (Op.getOpcode()) { 361 default: return false; 362 case ISD::ConstantFP: 363 // Don't invert constant FP values after legalize. The negated constant 364 // isn't necessarily legal. 365 return LegalOperations ? 0 : 1; 366 case ISD::FADD: 367 // FIXME: determine better conditions for this xform. 368 if (!UnsafeFPMath) return 0; 369 370 // fold (fsub (fadd A, B)) -> (fsub (fneg A), B) 371 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, Depth+1)) 372 return V; 373 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A) 374 return isNegatibleForFree(Op.getOperand(1), LegalOperations, Depth+1); 375 case ISD::FSUB: 376 // We can't turn -(A-B) into B-A when we honor signed zeros. 377 if (!UnsafeFPMath) return 0; 378 379 // fold (fneg (fsub A, B)) -> (fsub B, A) 380 return 1; 381 382 case ISD::FMUL: 383 case ISD::FDIV: 384 if (HonorSignDependentRoundingFPMath()) return 0; 385 386 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y)) 387 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, Depth+1)) 388 return V; 389 390 return isNegatibleForFree(Op.getOperand(1), LegalOperations, Depth+1); 391 392 case ISD::FP_EXTEND: 393 case ISD::FP_ROUND: 394 case ISD::FSIN: 395 return isNegatibleForFree(Op.getOperand(0), LegalOperations, Depth+1); 396 } 397 } 398 399 /// GetNegatedExpression - If isNegatibleForFree returns true, this function 400 /// returns the newly negated expression. 401 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG, 402 bool LegalOperations, unsigned Depth = 0) { 403 // fneg is removable even if it has multiple uses. 404 if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0); 405 406 // Don't allow anything with multiple uses. 407 assert(Op.hasOneUse() && "Unknown reuse!"); 408 409 assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree"); 410 switch (Op.getOpcode()) { 411 default: llvm_unreachable("Unknown code"); 412 case ISD::ConstantFP: { 413 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF(); 414 V.changeSign(); 415 return DAG.getConstantFP(V, Op.getValueType()); 416 } 417 case ISD::FADD: 418 // FIXME: determine better conditions for this xform. 419 assert(UnsafeFPMath); 420 421 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B) 422 if (isNegatibleForFree(Op.getOperand(0), LegalOperations, Depth+1)) 423 return DAG.getNode(ISD::FSUB, Op.getDebugLoc(), Op.getValueType(), 424 GetNegatedExpression(Op.getOperand(0), DAG, 425 LegalOperations, Depth+1), 426 Op.getOperand(1)); 427 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A) 428 return DAG.getNode(ISD::FSUB, Op.getDebugLoc(), Op.getValueType(), 429 GetNegatedExpression(Op.getOperand(1), DAG, 430 LegalOperations, Depth+1), 431 Op.getOperand(0)); 432 case ISD::FSUB: 433 // We can't turn -(A-B) into B-A when we honor signed zeros. 434 assert(UnsafeFPMath); 435 436 // fold (fneg (fsub 0, B)) -> B 437 if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0))) 438 if (N0CFP->getValueAPF().isZero()) 439 return Op.getOperand(1); 440 441 // fold (fneg (fsub A, B)) -> (fsub B, A) 442 return DAG.getNode(ISD::FSUB, Op.getDebugLoc(), Op.getValueType(), 443 Op.getOperand(1), Op.getOperand(0)); 444 445 case ISD::FMUL: 446 case ISD::FDIV: 447 assert(!HonorSignDependentRoundingFPMath()); 448 449 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) 450 if (isNegatibleForFree(Op.getOperand(0), LegalOperations, Depth+1)) 451 return DAG.getNode(Op.getOpcode(), Op.getDebugLoc(), Op.getValueType(), 452 GetNegatedExpression(Op.getOperand(0), DAG, 453 LegalOperations, Depth+1), 454 Op.getOperand(1)); 455 456 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y)) 457 return DAG.getNode(Op.getOpcode(), Op.getDebugLoc(), Op.getValueType(), 458 Op.getOperand(0), 459 GetNegatedExpression(Op.getOperand(1), DAG, 460 LegalOperations, Depth+1)); 461 462 case ISD::FP_EXTEND: 463 case ISD::FSIN: 464 return DAG.getNode(Op.getOpcode(), Op.getDebugLoc(), Op.getValueType(), 465 GetNegatedExpression(Op.getOperand(0), DAG, 466 LegalOperations, Depth+1)); 467 case ISD::FP_ROUND: 468 return DAG.getNode(ISD::FP_ROUND, Op.getDebugLoc(), Op.getValueType(), 469 GetNegatedExpression(Op.getOperand(0), DAG, 470 LegalOperations, Depth+1), 471 Op.getOperand(1)); 472 } 473 } 474 475 476 // isSetCCEquivalent - Return true if this node is a setcc, or is a select_cc 477 // that selects between the values 1 and 0, making it equivalent to a setcc. 478 // Also, set the incoming LHS, RHS, and CC references to the appropriate 479 // nodes based on the type of node we are checking. This simplifies life a 480 // bit for the callers. 481 static bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS, 482 SDValue &CC) { 483 if (N.getOpcode() == ISD::SETCC) { 484 LHS = N.getOperand(0); 485 RHS = N.getOperand(1); 486 CC = N.getOperand(2); 487 return true; 488 } 489 if (N.getOpcode() == ISD::SELECT_CC && 490 N.getOperand(2).getOpcode() == ISD::Constant && 491 N.getOperand(3).getOpcode() == ISD::Constant && 492 cast<ConstantSDNode>(N.getOperand(2))->getAPIntValue() == 1 && 493 cast<ConstantSDNode>(N.getOperand(3))->isNullValue()) { 494 LHS = N.getOperand(0); 495 RHS = N.getOperand(1); 496 CC = N.getOperand(4); 497 return true; 498 } 499 return false; 500 } 501 502 // isOneUseSetCC - Return true if this is a SetCC-equivalent operation with only 503 // one use. If this is true, it allows the users to invert the operation for 504 // free when it is profitable to do so. 505 static bool isOneUseSetCC(SDValue N) { 506 SDValue N0, N1, N2; 507 if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse()) 508 return true; 509 return false; 510 } 511 512 SDValue DAGCombiner::ReassociateOps(unsigned Opc, DebugLoc DL, 513 SDValue N0, SDValue N1) { 514 EVT VT = N0.getValueType(); 515 if (N0.getOpcode() == Opc && isa<ConstantSDNode>(N0.getOperand(1))) { 516 if (isa<ConstantSDNode>(N1)) { 517 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2)) 518 SDValue OpNode = 519 DAG.FoldConstantArithmetic(Opc, VT, 520 cast<ConstantSDNode>(N0.getOperand(1)), 521 cast<ConstantSDNode>(N1)); 522 return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode); 523 } else if (N0.hasOneUse()) { 524 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one use 525 SDValue OpNode = DAG.getNode(Opc, N0.getDebugLoc(), VT, 526 N0.getOperand(0), N1); 527 AddToWorkList(OpNode.getNode()); 528 return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1)); 529 } 530 } 531 532 if (N1.getOpcode() == Opc && isa<ConstantSDNode>(N1.getOperand(1))) { 533 if (isa<ConstantSDNode>(N0)) { 534 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2)) 535 SDValue OpNode = 536 DAG.FoldConstantArithmetic(Opc, VT, 537 cast<ConstantSDNode>(N1.getOperand(1)), 538 cast<ConstantSDNode>(N0)); 539 return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode); 540 } else if (N1.hasOneUse()) { 541 // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one use 542 SDValue OpNode = DAG.getNode(Opc, N0.getDebugLoc(), VT, 543 N1.getOperand(0), N0); 544 AddToWorkList(OpNode.getNode()); 545 return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1)); 546 } 547 } 548 549 return SDValue(); 550 } 551 552 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo, 553 bool AddTo) { 554 assert(N->getNumValues() == NumTo && "Broken CombineTo call!"); 555 ++NodesCombined; 556 DEBUG(dbgs() << "\nReplacing.1 "; 557 N->dump(&DAG); 558 dbgs() << "\nWith: "; 559 To[0].getNode()->dump(&DAG); 560 dbgs() << " and " << NumTo-1 << " other values\n"; 561 for (unsigned i = 0, e = NumTo; i != e; ++i) 562 assert((!To[i].getNode() || 563 N->getValueType(i) == To[i].getValueType()) && 564 "Cannot combine value to value of different type!")); 565 WorkListRemover DeadNodes(*this); 566 DAG.ReplaceAllUsesWith(N, To, &DeadNodes); 567 568 if (AddTo) { 569 // Push the new nodes and any users onto the worklist 570 for (unsigned i = 0, e = NumTo; i != e; ++i) { 571 if (To[i].getNode()) { 572 AddToWorkList(To[i].getNode()); 573 AddUsersToWorkList(To[i].getNode()); 574 } 575 } 576 } 577 578 // Finally, if the node is now dead, remove it from the graph. The node 579 // may not be dead if the replacement process recursively simplified to 580 // something else needing this node. 581 if (N->use_empty()) { 582 // Nodes can be reintroduced into the worklist. Make sure we do not 583 // process a node that has been replaced. 584 removeFromWorkList(N); 585 586 // Finally, since the node is now dead, remove it from the graph. 587 DAG.DeleteNode(N); 588 } 589 return SDValue(N, 0); 590 } 591 592 void DAGCombiner:: 593 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) { 594 // Replace all uses. If any nodes become isomorphic to other nodes and 595 // are deleted, make sure to remove them from our worklist. 596 WorkListRemover DeadNodes(*this); 597 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New, &DeadNodes); 598 599 // Push the new node and any (possibly new) users onto the worklist. 600 AddToWorkList(TLO.New.getNode()); 601 AddUsersToWorkList(TLO.New.getNode()); 602 603 // Finally, if the node is now dead, remove it from the graph. The node 604 // may not be dead if the replacement process recursively simplified to 605 // something else needing this node. 606 if (TLO.Old.getNode()->use_empty()) { 607 removeFromWorkList(TLO.Old.getNode()); 608 609 // If the operands of this node are only used by the node, they will now 610 // be dead. Make sure to visit them first to delete dead nodes early. 611 for (unsigned i = 0, e = TLO.Old.getNode()->getNumOperands(); i != e; ++i) 612 if (TLO.Old.getNode()->getOperand(i).getNode()->hasOneUse()) 613 AddToWorkList(TLO.Old.getNode()->getOperand(i).getNode()); 614 615 DAG.DeleteNode(TLO.Old.getNode()); 616 } 617 } 618 619 /// SimplifyDemandedBits - Check the specified integer node value to see if 620 /// it can be simplified or if things it uses can be simplified by bit 621 /// propagation. If so, return true. 622 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) { 623 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations); 624 APInt KnownZero, KnownOne; 625 if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO)) 626 return false; 627 628 // Revisit the node. 629 AddToWorkList(Op.getNode()); 630 631 // Replace the old value with the new one. 632 ++NodesCombined; 633 DEBUG(dbgs() << "\nReplacing.2 "; 634 TLO.Old.getNode()->dump(&DAG); 635 dbgs() << "\nWith: "; 636 TLO.New.getNode()->dump(&DAG); 637 dbgs() << '\n'); 638 639 CommitTargetLoweringOpt(TLO); 640 return true; 641 } 642 643 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) { 644 DebugLoc dl = Load->getDebugLoc(); 645 EVT VT = Load->getValueType(0); 646 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0)); 647 648 DEBUG(dbgs() << "\nReplacing.9 "; 649 Load->dump(&DAG); 650 dbgs() << "\nWith: "; 651 Trunc.getNode()->dump(&DAG); 652 dbgs() << '\n'); 653 WorkListRemover DeadNodes(*this); 654 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc, &DeadNodes); 655 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1), 656 &DeadNodes); 657 removeFromWorkList(Load); 658 DAG.DeleteNode(Load); 659 AddToWorkList(Trunc.getNode()); 660 } 661 662 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) { 663 Replace = false; 664 DebugLoc dl = Op.getDebugLoc(); 665 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) { 666 EVT MemVT = LD->getMemoryVT(); 667 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD) 668 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD : ISD::EXTLOAD) 669 : LD->getExtensionType(); 670 Replace = true; 671 return DAG.getExtLoad(ExtType, dl, PVT, 672 LD->getChain(), LD->getBasePtr(), 673 LD->getSrcValue(), LD->getSrcValueOffset(), 674 MemVT, LD->isVolatile(), 675 LD->isNonTemporal(), LD->getAlignment()); 676 } 677 678 unsigned Opc = Op.getOpcode(); 679 switch (Opc) { 680 default: break; 681 case ISD::AssertSext: 682 return DAG.getNode(ISD::AssertSext, dl, PVT, 683 SExtPromoteOperand(Op.getOperand(0), PVT), 684 Op.getOperand(1)); 685 case ISD::AssertZext: 686 return DAG.getNode(ISD::AssertZext, dl, PVT, 687 ZExtPromoteOperand(Op.getOperand(0), PVT), 688 Op.getOperand(1)); 689 case ISD::Constant: { 690 unsigned ExtOpc = 691 Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 692 return DAG.getNode(ExtOpc, dl, PVT, Op); 693 } 694 } 695 696 if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT)) 697 return SDValue(); 698 return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op); 699 } 700 701 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) { 702 if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT)) 703 return SDValue(); 704 EVT OldVT = Op.getValueType(); 705 DebugLoc dl = Op.getDebugLoc(); 706 bool Replace = false; 707 SDValue NewOp = PromoteOperand(Op, PVT, Replace); 708 if (NewOp.getNode() == 0) 709 return SDValue(); 710 AddToWorkList(NewOp.getNode()); 711 712 if (Replace) 713 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode()); 714 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp, 715 DAG.getValueType(OldVT)); 716 } 717 718 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) { 719 EVT OldVT = Op.getValueType(); 720 DebugLoc dl = Op.getDebugLoc(); 721 bool Replace = false; 722 SDValue NewOp = PromoteOperand(Op, PVT, Replace); 723 if (NewOp.getNode() == 0) 724 return SDValue(); 725 AddToWorkList(NewOp.getNode()); 726 727 if (Replace) 728 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode()); 729 return DAG.getZeroExtendInReg(NewOp, dl, OldVT); 730 } 731 732 /// PromoteIntBinOp - Promote the specified integer binary operation if the 733 /// target indicates it is beneficial. e.g. On x86, it's usually better to 734 /// promote i16 operations to i32 since i16 instructions are longer. 735 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) { 736 if (!LegalOperations) 737 return SDValue(); 738 739 EVT VT = Op.getValueType(); 740 if (VT.isVector() || !VT.isInteger()) 741 return SDValue(); 742 743 // If operation type is 'undesirable', e.g. i16 on x86, consider 744 // promoting it. 745 unsigned Opc = Op.getOpcode(); 746 if (TLI.isTypeDesirableForOp(Opc, VT)) 747 return SDValue(); 748 749 EVT PVT = VT; 750 // Consult target whether it is a good idea to promote this operation and 751 // what's the right type to promote it to. 752 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 753 assert(PVT != VT && "Don't know what type to promote to!"); 754 755 bool Replace0 = false; 756 SDValue N0 = Op.getOperand(0); 757 SDValue NN0 = PromoteOperand(N0, PVT, Replace0); 758 if (NN0.getNode() == 0) 759 return SDValue(); 760 761 bool Replace1 = false; 762 SDValue N1 = Op.getOperand(1); 763 SDValue NN1 = PromoteOperand(N1, PVT, Replace1); 764 if (NN1.getNode() == 0) 765 return SDValue(); 766 767 AddToWorkList(NN0.getNode()); 768 AddToWorkList(NN1.getNode()); 769 770 if (Replace0) 771 ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode()); 772 if (Replace1) 773 ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode()); 774 775 DEBUG(dbgs() << "\nPromoting "; 776 Op.getNode()->dump(&DAG)); 777 DebugLoc dl = Op.getDebugLoc(); 778 return DAG.getNode(ISD::TRUNCATE, dl, VT, 779 DAG.getNode(Opc, dl, PVT, NN0, NN1)); 780 } 781 return SDValue(); 782 } 783 784 /// PromoteIntShiftOp - Promote the specified integer shift operation if the 785 /// target indicates it is beneficial. e.g. On x86, it's usually better to 786 /// promote i16 operations to i32 since i16 instructions are longer. 787 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) { 788 if (!LegalOperations) 789 return SDValue(); 790 791 EVT VT = Op.getValueType(); 792 if (VT.isVector() || !VT.isInteger()) 793 return SDValue(); 794 795 // If operation type is 'undesirable', e.g. i16 on x86, consider 796 // promoting it. 797 unsigned Opc = Op.getOpcode(); 798 if (TLI.isTypeDesirableForOp(Opc, VT)) 799 return SDValue(); 800 801 EVT PVT = VT; 802 // Consult target whether it is a good idea to promote this operation and 803 // what's the right type to promote it to. 804 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 805 assert(PVT != VT && "Don't know what type to promote to!"); 806 807 bool Replace = false; 808 SDValue N0 = Op.getOperand(0); 809 if (Opc == ISD::SRA) 810 N0 = SExtPromoteOperand(Op.getOperand(0), PVT); 811 else if (Opc == ISD::SRL) 812 N0 = ZExtPromoteOperand(Op.getOperand(0), PVT); 813 else 814 N0 = PromoteOperand(N0, PVT, Replace); 815 if (N0.getNode() == 0) 816 return SDValue(); 817 818 AddToWorkList(N0.getNode()); 819 if (Replace) 820 ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode()); 821 822 DEBUG(dbgs() << "\nPromoting "; 823 Op.getNode()->dump(&DAG)); 824 DebugLoc dl = Op.getDebugLoc(); 825 return DAG.getNode(ISD::TRUNCATE, dl, VT, 826 DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1))); 827 } 828 return SDValue(); 829 } 830 831 SDValue DAGCombiner::PromoteExtend(SDValue Op) { 832 if (!LegalOperations) 833 return SDValue(); 834 835 EVT VT = Op.getValueType(); 836 if (VT.isVector() || !VT.isInteger()) 837 return SDValue(); 838 839 // If operation type is 'undesirable', e.g. i16 on x86, consider 840 // promoting it. 841 unsigned Opc = Op.getOpcode(); 842 if (TLI.isTypeDesirableForOp(Opc, VT)) 843 return SDValue(); 844 845 EVT PVT = VT; 846 // Consult target whether it is a good idea to promote this operation and 847 // what's the right type to promote it to. 848 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 849 assert(PVT != VT && "Don't know what type to promote to!"); 850 // fold (aext (aext x)) -> (aext x) 851 // fold (aext (zext x)) -> (zext x) 852 // fold (aext (sext x)) -> (sext x) 853 DEBUG(dbgs() << "\nPromoting "; 854 Op.getNode()->dump(&DAG)); 855 return DAG.getNode(Op.getOpcode(), Op.getDebugLoc(), VT, Op.getOperand(0)); 856 } 857 return SDValue(); 858 } 859 860 bool DAGCombiner::PromoteLoad(SDValue Op) { 861 if (!LegalOperations) 862 return false; 863 864 EVT VT = Op.getValueType(); 865 if (VT.isVector() || !VT.isInteger()) 866 return false; 867 868 // If operation type is 'undesirable', e.g. i16 on x86, consider 869 // promoting it. 870 unsigned Opc = Op.getOpcode(); 871 if (TLI.isTypeDesirableForOp(Opc, VT)) 872 return false; 873 874 EVT PVT = VT; 875 // Consult target whether it is a good idea to promote this operation and 876 // what's the right type to promote it to. 877 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 878 assert(PVT != VT && "Don't know what type to promote to!"); 879 880 DebugLoc dl = Op.getDebugLoc(); 881 SDNode *N = Op.getNode(); 882 LoadSDNode *LD = cast<LoadSDNode>(N); 883 EVT MemVT = LD->getMemoryVT(); 884 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD) 885 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD : ISD::EXTLOAD) 886 : LD->getExtensionType(); 887 SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT, 888 LD->getChain(), LD->getBasePtr(), 889 LD->getSrcValue(), LD->getSrcValueOffset(), 890 MemVT, LD->isVolatile(), 891 LD->isNonTemporal(), LD->getAlignment()); 892 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD); 893 894 DEBUG(dbgs() << "\nPromoting "; 895 N->dump(&DAG); 896 dbgs() << "\nTo: "; 897 Result.getNode()->dump(&DAG); 898 dbgs() << '\n'); 899 WorkListRemover DeadNodes(*this); 900 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result, &DeadNodes); 901 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1), &DeadNodes); 902 removeFromWorkList(N); 903 DAG.DeleteNode(N); 904 AddToWorkList(Result.getNode()); 905 return true; 906 } 907 return false; 908 } 909 910 911 //===----------------------------------------------------------------------===// 912 // Main DAG Combiner implementation 913 //===----------------------------------------------------------------------===// 914 915 void DAGCombiner::Run(CombineLevel AtLevel) { 916 // set the instance variables, so that the various visit routines may use it. 917 Level = AtLevel; 918 LegalOperations = Level >= NoIllegalOperations; 919 LegalTypes = Level >= NoIllegalTypes; 920 921 // Add all the dag nodes to the worklist. 922 WorkList.reserve(DAG.allnodes_size()); 923 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(), 924 E = DAG.allnodes_end(); I != E; ++I) 925 WorkList.push_back(I); 926 927 // Create a dummy node (which is not added to allnodes), that adds a reference 928 // to the root node, preventing it from being deleted, and tracking any 929 // changes of the root. 930 HandleSDNode Dummy(DAG.getRoot()); 931 932 // The root of the dag may dangle to deleted nodes until the dag combiner is 933 // done. Set it to null to avoid confusion. 934 DAG.setRoot(SDValue()); 935 936 // while the worklist isn't empty, inspect the node on the end of it and 937 // try and combine it. 938 while (!WorkList.empty()) { 939 SDNode *N = WorkList.back(); 940 WorkList.pop_back(); 941 942 // If N has no uses, it is dead. Make sure to revisit all N's operands once 943 // N is deleted from the DAG, since they too may now be dead or may have a 944 // reduced number of uses, allowing other xforms. 945 if (N->use_empty() && N != &Dummy) { 946 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) 947 AddToWorkList(N->getOperand(i).getNode()); 948 949 DAG.DeleteNode(N); 950 continue; 951 } 952 953 SDValue RV = combine(N); 954 955 if (RV.getNode() == 0) 956 continue; 957 958 ++NodesCombined; 959 960 // If we get back the same node we passed in, rather than a new node or 961 // zero, we know that the node must have defined multiple values and 962 // CombineTo was used. Since CombineTo takes care of the worklist 963 // mechanics for us, we have no work to do in this case. 964 if (RV.getNode() == N) 965 continue; 966 967 assert(N->getOpcode() != ISD::DELETED_NODE && 968 RV.getNode()->getOpcode() != ISD::DELETED_NODE && 969 "Node was deleted but visit returned new node!"); 970 971 DEBUG(dbgs() << "\nReplacing.3 "; 972 N->dump(&DAG); 973 dbgs() << "\nWith: "; 974 RV.getNode()->dump(&DAG); 975 dbgs() << '\n'); 976 WorkListRemover DeadNodes(*this); 977 if (N->getNumValues() == RV.getNode()->getNumValues()) 978 DAG.ReplaceAllUsesWith(N, RV.getNode(), &DeadNodes); 979 else { 980 assert(N->getValueType(0) == RV.getValueType() && 981 N->getNumValues() == 1 && "Type mismatch"); 982 SDValue OpV = RV; 983 DAG.ReplaceAllUsesWith(N, &OpV, &DeadNodes); 984 } 985 986 // Push the new node and any users onto the worklist 987 AddToWorkList(RV.getNode()); 988 AddUsersToWorkList(RV.getNode()); 989 990 // Add any uses of the old node to the worklist in case this node is the 991 // last one that uses them. They may become dead after this node is 992 // deleted. 993 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) 994 AddToWorkList(N->getOperand(i).getNode()); 995 996 // Finally, if the node is now dead, remove it from the graph. The node 997 // may not be dead if the replacement process recursively simplified to 998 // something else needing this node. 999 if (N->use_empty()) { 1000 // Nodes can be reintroduced into the worklist. Make sure we do not 1001 // process a node that has been replaced. 1002 removeFromWorkList(N); 1003 1004 // Finally, since the node is now dead, remove it from the graph. 1005 DAG.DeleteNode(N); 1006 } 1007 } 1008 1009 // If the root changed (e.g. it was a dead load, update the root). 1010 DAG.setRoot(Dummy.getValue()); 1011 } 1012 1013 SDValue DAGCombiner::visit(SDNode *N) { 1014 switch (N->getOpcode()) { 1015 default: break; 1016 case ISD::TokenFactor: return visitTokenFactor(N); 1017 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N); 1018 case ISD::ADD: return visitADD(N); 1019 case ISD::SUB: return visitSUB(N); 1020 case ISD::ADDC: return visitADDC(N); 1021 case ISD::ADDE: return visitADDE(N); 1022 case ISD::MUL: return visitMUL(N); 1023 case ISD::SDIV: return visitSDIV(N); 1024 case ISD::UDIV: return visitUDIV(N); 1025 case ISD::SREM: return visitSREM(N); 1026 case ISD::UREM: return visitUREM(N); 1027 case ISD::MULHU: return visitMULHU(N); 1028 case ISD::MULHS: return visitMULHS(N); 1029 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N); 1030 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N); 1031 case ISD::SDIVREM: return visitSDIVREM(N); 1032 case ISD::UDIVREM: return visitUDIVREM(N); 1033 case ISD::AND: return visitAND(N); 1034 case ISD::OR: return visitOR(N); 1035 case ISD::XOR: return visitXOR(N); 1036 case ISD::SHL: return visitSHL(N); 1037 case ISD::SRA: return visitSRA(N); 1038 case ISD::SRL: return visitSRL(N); 1039 case ISD::CTLZ: return visitCTLZ(N); 1040 case ISD::CTTZ: return visitCTTZ(N); 1041 case ISD::CTPOP: return visitCTPOP(N); 1042 case ISD::SELECT: return visitSELECT(N); 1043 case ISD::SELECT_CC: return visitSELECT_CC(N); 1044 case ISD::SETCC: return visitSETCC(N); 1045 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N); 1046 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N); 1047 case ISD::ANY_EXTEND: return visitANY_EXTEND(N); 1048 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N); 1049 case ISD::TRUNCATE: return visitTRUNCATE(N); 1050 case ISD::BIT_CONVERT: return visitBIT_CONVERT(N); 1051 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N); 1052 case ISD::FADD: return visitFADD(N); 1053 case ISD::FSUB: return visitFSUB(N); 1054 case ISD::FMUL: return visitFMUL(N); 1055 case ISD::FDIV: return visitFDIV(N); 1056 case ISD::FREM: return visitFREM(N); 1057 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N); 1058 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N); 1059 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N); 1060 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N); 1061 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N); 1062 case ISD::FP_ROUND: return visitFP_ROUND(N); 1063 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N); 1064 case ISD::FP_EXTEND: return visitFP_EXTEND(N); 1065 case ISD::FNEG: return visitFNEG(N); 1066 case ISD::FABS: return visitFABS(N); 1067 case ISD::BRCOND: return visitBRCOND(N); 1068 case ISD::BR_CC: return visitBR_CC(N); 1069 case ISD::LOAD: return visitLOAD(N); 1070 case ISD::STORE: return visitSTORE(N); 1071 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N); 1072 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N); 1073 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N); 1074 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N); 1075 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N); 1076 } 1077 return SDValue(); 1078 } 1079 1080 SDValue DAGCombiner::combine(SDNode *N) { 1081 SDValue RV = visit(N); 1082 1083 // If nothing happened, try a target-specific DAG combine. 1084 if (RV.getNode() == 0) { 1085 assert(N->getOpcode() != ISD::DELETED_NODE && 1086 "Node was deleted but visit returned NULL!"); 1087 1088 if (N->getOpcode() >= ISD::BUILTIN_OP_END || 1089 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) { 1090 1091 // Expose the DAG combiner to the target combiner impls. 1092 TargetLowering::DAGCombinerInfo 1093 DagCombineInfo(DAG, !LegalTypes, !LegalOperations, false, this); 1094 1095 RV = TLI.PerformDAGCombine(N, DagCombineInfo); 1096 } 1097 } 1098 1099 // If nothing happened still, try promoting the operation. 1100 if (RV.getNode() == 0) { 1101 switch (N->getOpcode()) { 1102 default: break; 1103 case ISD::ADD: 1104 case ISD::SUB: 1105 case ISD::MUL: 1106 case ISD::AND: 1107 case ISD::OR: 1108 case ISD::XOR: 1109 RV = PromoteIntBinOp(SDValue(N, 0)); 1110 break; 1111 case ISD::SHL: 1112 case ISD::SRA: 1113 case ISD::SRL: 1114 RV = PromoteIntShiftOp(SDValue(N, 0)); 1115 break; 1116 case ISD::SIGN_EXTEND: 1117 case ISD::ZERO_EXTEND: 1118 case ISD::ANY_EXTEND: 1119 RV = PromoteExtend(SDValue(N, 0)); 1120 break; 1121 case ISD::LOAD: 1122 if (PromoteLoad(SDValue(N, 0))) 1123 RV = SDValue(N, 0); 1124 break; 1125 } 1126 } 1127 1128 // If N is a commutative binary node, try commuting it to enable more 1129 // sdisel CSE. 1130 if (RV.getNode() == 0 && 1131 SelectionDAG::isCommutativeBinOp(N->getOpcode()) && 1132 N->getNumValues() == 1) { 1133 SDValue N0 = N->getOperand(0); 1134 SDValue N1 = N->getOperand(1); 1135 1136 // Constant operands are canonicalized to RHS. 1137 if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) { 1138 SDValue Ops[] = { N1, N0 }; 1139 SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), 1140 Ops, 2); 1141 if (CSENode) 1142 return SDValue(CSENode, 0); 1143 } 1144 } 1145 1146 return RV; 1147 } 1148 1149 /// getInputChainForNode - Given a node, return its input chain if it has one, 1150 /// otherwise return a null sd operand. 1151 static SDValue getInputChainForNode(SDNode *N) { 1152 if (unsigned NumOps = N->getNumOperands()) { 1153 if (N->getOperand(0).getValueType() == MVT::Other) 1154 return N->getOperand(0); 1155 else if (N->getOperand(NumOps-1).getValueType() == MVT::Other) 1156 return N->getOperand(NumOps-1); 1157 for (unsigned i = 1; i < NumOps-1; ++i) 1158 if (N->getOperand(i).getValueType() == MVT::Other) 1159 return N->getOperand(i); 1160 } 1161 return SDValue(); 1162 } 1163 1164 SDValue DAGCombiner::visitTokenFactor(SDNode *N) { 1165 // If N has two operands, where one has an input chain equal to the other, 1166 // the 'other' chain is redundant. 1167 if (N->getNumOperands() == 2) { 1168 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1)) 1169 return N->getOperand(0); 1170 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0)) 1171 return N->getOperand(1); 1172 } 1173 1174 SmallVector<SDNode *, 8> TFs; // List of token factors to visit. 1175 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor. 1176 SmallPtrSet<SDNode*, 16> SeenOps; 1177 bool Changed = false; // If we should replace this token factor. 1178 1179 // Start out with this token factor. 1180 TFs.push_back(N); 1181 1182 // Iterate through token factors. The TFs grows when new token factors are 1183 // encountered. 1184 for (unsigned i = 0; i < TFs.size(); ++i) { 1185 SDNode *TF = TFs[i]; 1186 1187 // Check each of the operands. 1188 for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) { 1189 SDValue Op = TF->getOperand(i); 1190 1191 switch (Op.getOpcode()) { 1192 case ISD::EntryToken: 1193 // Entry tokens don't need to be added to the list. They are 1194 // rededundant. 1195 Changed = true; 1196 break; 1197 1198 case ISD::TokenFactor: 1199 if (Op.hasOneUse() && 1200 std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) { 1201 // Queue up for processing. 1202 TFs.push_back(Op.getNode()); 1203 // Clean up in case the token factor is removed. 1204 AddToWorkList(Op.getNode()); 1205 Changed = true; 1206 break; 1207 } 1208 // Fall thru 1209 1210 default: 1211 // Only add if it isn't already in the list. 1212 if (SeenOps.insert(Op.getNode())) 1213 Ops.push_back(Op); 1214 else 1215 Changed = true; 1216 break; 1217 } 1218 } 1219 } 1220 1221 SDValue Result; 1222 1223 // If we've change things around then replace token factor. 1224 if (Changed) { 1225 if (Ops.empty()) { 1226 // The entry token is the only possible outcome. 1227 Result = DAG.getEntryNode(); 1228 } else { 1229 // New and improved token factor. 1230 Result = DAG.getNode(ISD::TokenFactor, N->getDebugLoc(), 1231 MVT::Other, &Ops[0], Ops.size()); 1232 } 1233 1234 // Don't add users to work list. 1235 return CombineTo(N, Result, false); 1236 } 1237 1238 return Result; 1239 } 1240 1241 /// MERGE_VALUES can always be eliminated. 1242 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) { 1243 WorkListRemover DeadNodes(*this); 1244 // Replacing results may cause a different MERGE_VALUES to suddenly 1245 // be CSE'd with N, and carry its uses with it. Iterate until no 1246 // uses remain, to ensure that the node can be safely deleted. 1247 do { 1248 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) 1249 DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i), 1250 &DeadNodes); 1251 } while (!N->use_empty()); 1252 removeFromWorkList(N); 1253 DAG.DeleteNode(N); 1254 return SDValue(N, 0); // Return N so it doesn't get rechecked! 1255 } 1256 1257 static 1258 SDValue combineShlAddConstant(DebugLoc DL, SDValue N0, SDValue N1, 1259 SelectionDAG &DAG) { 1260 EVT VT = N0.getValueType(); 1261 SDValue N00 = N0.getOperand(0); 1262 SDValue N01 = N0.getOperand(1); 1263 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N01); 1264 1265 if (N01C && N00.getOpcode() == ISD::ADD && N00.getNode()->hasOneUse() && 1266 isa<ConstantSDNode>(N00.getOperand(1))) { 1267 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), ) 1268 N0 = DAG.getNode(ISD::ADD, N0.getDebugLoc(), VT, 1269 DAG.getNode(ISD::SHL, N00.getDebugLoc(), VT, 1270 N00.getOperand(0), N01), 1271 DAG.getNode(ISD::SHL, N01.getDebugLoc(), VT, 1272 N00.getOperand(1), N01)); 1273 return DAG.getNode(ISD::ADD, DL, VT, N0, N1); 1274 } 1275 1276 return SDValue(); 1277 } 1278 1279 SDValue DAGCombiner::visitADD(SDNode *N) { 1280 SDValue N0 = N->getOperand(0); 1281 SDValue N1 = N->getOperand(1); 1282 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 1283 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 1284 EVT VT = N0.getValueType(); 1285 1286 // fold vector ops 1287 if (VT.isVector()) { 1288 SDValue FoldedVOp = SimplifyVBinOp(N); 1289 if (FoldedVOp.getNode()) return FoldedVOp; 1290 } 1291 1292 // fold (add x, undef) -> undef 1293 if (N0.getOpcode() == ISD::UNDEF) 1294 return N0; 1295 if (N1.getOpcode() == ISD::UNDEF) 1296 return N1; 1297 // fold (add c1, c2) -> c1+c2 1298 if (N0C && N1C) 1299 return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C); 1300 // canonicalize constant to RHS 1301 if (N0C && !N1C) 1302 return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N1, N0); 1303 // fold (add x, 0) -> x 1304 if (N1C && N1C->isNullValue()) 1305 return N0; 1306 // fold (add Sym, c) -> Sym+c 1307 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0)) 1308 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C && 1309 GA->getOpcode() == ISD::GlobalAddress) 1310 return DAG.getGlobalAddress(GA->getGlobal(), VT, 1311 GA->getOffset() + 1312 (uint64_t)N1C->getSExtValue()); 1313 // fold ((c1-A)+c2) -> (c1+c2)-A 1314 if (N1C && N0.getOpcode() == ISD::SUB) 1315 if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0))) 1316 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, 1317 DAG.getConstant(N1C->getAPIntValue()+ 1318 N0C->getAPIntValue(), VT), 1319 N0.getOperand(1)); 1320 // reassociate add 1321 SDValue RADD = ReassociateOps(ISD::ADD, N->getDebugLoc(), N0, N1); 1322 if (RADD.getNode() != 0) 1323 return RADD; 1324 // fold ((0-A) + B) -> B-A 1325 if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) && 1326 cast<ConstantSDNode>(N0.getOperand(0))->isNullValue()) 1327 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N1, N0.getOperand(1)); 1328 // fold (A + (0-B)) -> A-B 1329 if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) && 1330 cast<ConstantSDNode>(N1.getOperand(0))->isNullValue()) 1331 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N0, N1.getOperand(1)); 1332 // fold (A+(B-A)) -> B 1333 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1)) 1334 return N1.getOperand(0); 1335 // fold ((B-A)+A) -> B 1336 if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1)) 1337 return N0.getOperand(0); 1338 // fold (A+(B-(A+C))) to (B-C) 1339 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD && 1340 N0 == N1.getOperand(1).getOperand(0)) 1341 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N1.getOperand(0), 1342 N1.getOperand(1).getOperand(1)); 1343 // fold (A+(B-(C+A))) to (B-C) 1344 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD && 1345 N0 == N1.getOperand(1).getOperand(1)) 1346 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N1.getOperand(0), 1347 N1.getOperand(1).getOperand(0)); 1348 // fold (A+((B-A)+or-C)) to (B+or-C) 1349 if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) && 1350 N1.getOperand(0).getOpcode() == ISD::SUB && 1351 N0 == N1.getOperand(0).getOperand(1)) 1352 return DAG.getNode(N1.getOpcode(), N->getDebugLoc(), VT, 1353 N1.getOperand(0).getOperand(0), N1.getOperand(1)); 1354 1355 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant 1356 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) { 1357 SDValue N00 = N0.getOperand(0); 1358 SDValue N01 = N0.getOperand(1); 1359 SDValue N10 = N1.getOperand(0); 1360 SDValue N11 = N1.getOperand(1); 1361 1362 if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10)) 1363 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, 1364 DAG.getNode(ISD::ADD, N0.getDebugLoc(), VT, N00, N10), 1365 DAG.getNode(ISD::ADD, N1.getDebugLoc(), VT, N01, N11)); 1366 } 1367 1368 if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0))) 1369 return SDValue(N, 0); 1370 1371 // fold (a+b) -> (a|b) iff a and b share no bits. 1372 if (VT.isInteger() && !VT.isVector()) { 1373 APInt LHSZero, LHSOne; 1374 APInt RHSZero, RHSOne; 1375 APInt Mask = APInt::getAllOnesValue(VT.getScalarType().getSizeInBits()); 1376 DAG.ComputeMaskedBits(N0, Mask, LHSZero, LHSOne); 1377 1378 if (LHSZero.getBoolValue()) { 1379 DAG.ComputeMaskedBits(N1, Mask, RHSZero, RHSOne); 1380 1381 // If all possibly-set bits on the LHS are clear on the RHS, return an OR. 1382 // If all possibly-set bits on the RHS are clear on the LHS, return an OR. 1383 if ((RHSZero & (~LHSZero & Mask)) == (~LHSZero & Mask) || 1384 (LHSZero & (~RHSZero & Mask)) == (~RHSZero & Mask)) 1385 return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, N0, N1); 1386 } 1387 } 1388 1389 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), ) 1390 if (N0.getOpcode() == ISD::SHL && N0.getNode()->hasOneUse()) { 1391 SDValue Result = combineShlAddConstant(N->getDebugLoc(), N0, N1, DAG); 1392 if (Result.getNode()) return Result; 1393 } 1394 if (N1.getOpcode() == ISD::SHL && N1.getNode()->hasOneUse()) { 1395 SDValue Result = combineShlAddConstant(N->getDebugLoc(), N1, N0, DAG); 1396 if (Result.getNode()) return Result; 1397 } 1398 1399 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n)) 1400 if (N1.getOpcode() == ISD::SHL && 1401 N1.getOperand(0).getOpcode() == ISD::SUB) 1402 if (ConstantSDNode *C = 1403 dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0))) 1404 if (C->getAPIntValue() == 0) 1405 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N0, 1406 DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, 1407 N1.getOperand(0).getOperand(1), 1408 N1.getOperand(1))); 1409 if (N0.getOpcode() == ISD::SHL && 1410 N0.getOperand(0).getOpcode() == ISD::SUB) 1411 if (ConstantSDNode *C = 1412 dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0))) 1413 if (C->getAPIntValue() == 0) 1414 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N1, 1415 DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, 1416 N0.getOperand(0).getOperand(1), 1417 N0.getOperand(1))); 1418 1419 return SDValue(); 1420 } 1421 1422 SDValue DAGCombiner::visitADDC(SDNode *N) { 1423 SDValue N0 = N->getOperand(0); 1424 SDValue N1 = N->getOperand(1); 1425 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 1426 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 1427 EVT VT = N0.getValueType(); 1428 1429 // If the flag result is dead, turn this into an ADD. 1430 if (N->hasNUsesOfValue(0, 1)) 1431 return CombineTo(N, DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N1, N0), 1432 DAG.getNode(ISD::CARRY_FALSE, 1433 N->getDebugLoc(), MVT::Flag)); 1434 1435 // canonicalize constant to RHS. 1436 if (N0C && !N1C) 1437 return DAG.getNode(ISD::ADDC, N->getDebugLoc(), N->getVTList(), N1, N0); 1438 1439 // fold (addc x, 0) -> x + no carry out 1440 if (N1C && N1C->isNullValue()) 1441 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, 1442 N->getDebugLoc(), MVT::Flag)); 1443 1444 // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits. 1445 APInt LHSZero, LHSOne; 1446 APInt RHSZero, RHSOne; 1447 APInt Mask = APInt::getAllOnesValue(VT.getScalarType().getSizeInBits()); 1448 DAG.ComputeMaskedBits(N0, Mask, LHSZero, LHSOne); 1449 1450 if (LHSZero.getBoolValue()) { 1451 DAG.ComputeMaskedBits(N1, Mask, RHSZero, RHSOne); 1452 1453 // If all possibly-set bits on the LHS are clear on the RHS, return an OR. 1454 // If all possibly-set bits on the RHS are clear on the LHS, return an OR. 1455 if ((RHSZero & (~LHSZero & Mask)) == (~LHSZero & Mask) || 1456 (LHSZero & (~RHSZero & Mask)) == (~RHSZero & Mask)) 1457 return CombineTo(N, DAG.getNode(ISD::OR, N->getDebugLoc(), VT, N0, N1), 1458 DAG.getNode(ISD::CARRY_FALSE, 1459 N->getDebugLoc(), MVT::Flag)); 1460 } 1461 1462 return SDValue(); 1463 } 1464 1465 SDValue DAGCombiner::visitADDE(SDNode *N) { 1466 SDValue N0 = N->getOperand(0); 1467 SDValue N1 = N->getOperand(1); 1468 SDValue CarryIn = N->getOperand(2); 1469 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 1470 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 1471 1472 // canonicalize constant to RHS 1473 if (N0C && !N1C) 1474 return DAG.getNode(ISD::ADDE, N->getDebugLoc(), N->getVTList(), 1475 N1, N0, CarryIn); 1476 1477 // fold (adde x, y, false) -> (addc x, y) 1478 if (CarryIn.getOpcode() == ISD::CARRY_FALSE) 1479 return DAG.getNode(ISD::ADDC, N->getDebugLoc(), N->getVTList(), N1, N0); 1480 1481 return SDValue(); 1482 } 1483 1484 SDValue DAGCombiner::visitSUB(SDNode *N) { 1485 SDValue N0 = N->getOperand(0); 1486 SDValue N1 = N->getOperand(1); 1487 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode()); 1488 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode()); 1489 EVT VT = N0.getValueType(); 1490 1491 // fold vector ops 1492 if (VT.isVector()) { 1493 SDValue FoldedVOp = SimplifyVBinOp(N); 1494 if (FoldedVOp.getNode()) return FoldedVOp; 1495 } 1496 1497 // fold (sub x, x) -> 0 1498 if (N0 == N1) 1499 return DAG.getConstant(0, N->getValueType(0)); 1500 // fold (sub c1, c2) -> c1-c2 1501 if (N0C && N1C) 1502 return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C); 1503 // fold (sub x, c) -> (add x, -c) 1504 if (N1C) 1505 return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0, 1506 DAG.getConstant(-N1C->getAPIntValue(), VT)); 1507 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) 1508 if (N0C && N0C->isAllOnesValue()) 1509 return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT, N1, N0); 1510 // fold (A+B)-A -> B 1511 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1) 1512 return N0.getOperand(1); 1513 // fold (A+B)-B -> A 1514 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1) 1515 return N0.getOperand(0); 1516 // fold ((A+(B+or-C))-B) -> A+or-C 1517 if (N0.getOpcode() == ISD::ADD && 1518 (N0.getOperand(1).getOpcode() == ISD::SUB || 1519 N0.getOperand(1).getOpcode() == ISD::ADD) && 1520 N0.getOperand(1).getOperand(0) == N1) 1521 return DAG.getNode(N0.getOperand(1).getOpcode(), N->getDebugLoc(), VT, 1522 N0.getOperand(0), N0.getOperand(1).getOperand(1)); 1523 // fold ((A+(C+B))-B) -> A+C 1524 if (N0.getOpcode() == ISD::ADD && 1525 N0.getOperand(1).getOpcode() == ISD::ADD && 1526 N0.getOperand(1).getOperand(1) == N1) 1527 return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, 1528 N0.getOperand(0), N0.getOperand(1).getOperand(0)); 1529 // fold ((A-(B-C))-C) -> A-B 1530 if (N0.getOpcode() == ISD::SUB && 1531 N0.getOperand(1).getOpcode() == ISD::SUB && 1532 N0.getOperand(1).getOperand(1) == N1) 1533 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, 1534 N0.getOperand(0), N0.getOperand(1).getOperand(0)); 1535 1536 // If either operand of a sub is undef, the result is undef 1537 if (N0.getOpcode() == ISD::UNDEF) 1538 return N0; 1539 if (N1.getOpcode() == ISD::UNDEF) 1540 return N1; 1541 1542 // If the relocation model supports it, consider symbol offsets. 1543 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0)) 1544 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) { 1545 // fold (sub Sym, c) -> Sym-c 1546 if (N1C && GA->getOpcode() == ISD::GlobalAddress) 1547 return DAG.getGlobalAddress(GA->getGlobal(), VT, 1548 GA->getOffset() - 1549 (uint64_t)N1C->getSExtValue()); 1550 // fold (sub Sym+c1, Sym+c2) -> c1-c2 1551 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1)) 1552 if (GA->getGlobal() == GB->getGlobal()) 1553 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(), 1554 VT); 1555 } 1556 1557 return SDValue(); 1558 } 1559 1560 SDValue DAGCombiner::visitMUL(SDNode *N) { 1561 SDValue N0 = N->getOperand(0); 1562 SDValue N1 = N->getOperand(1); 1563 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 1564 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 1565 EVT VT = N0.getValueType(); 1566 1567 // fold vector ops 1568 if (VT.isVector()) { 1569 SDValue FoldedVOp = SimplifyVBinOp(N); 1570 if (FoldedVOp.getNode()) return FoldedVOp; 1571 } 1572 1573 // fold (mul x, undef) -> 0 1574 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF) 1575 return DAG.getConstant(0, VT); 1576 // fold (mul c1, c2) -> c1*c2 1577 if (N0C && N1C) 1578 return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0C, N1C); 1579 // canonicalize constant to RHS 1580 if (N0C && !N1C) 1581 return DAG.getNode(ISD::MUL, N->getDebugLoc(), VT, N1, N0); 1582 // fold (mul x, 0) -> 0 1583 if (N1C && N1C->isNullValue()) 1584 return N1; 1585 // fold (mul x, -1) -> 0-x 1586 if (N1C && N1C->isAllOnesValue()) 1587 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, 1588 DAG.getConstant(0, VT), N0); 1589 // fold (mul x, (1 << c)) -> x << c 1590 if (N1C && N1C->getAPIntValue().isPowerOf2()) 1591 return DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, N0, 1592 DAG.getConstant(N1C->getAPIntValue().logBase2(), 1593 getShiftAmountTy())); 1594 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c 1595 if (N1C && (-N1C->getAPIntValue()).isPowerOf2()) { 1596 unsigned Log2Val = (-N1C->getAPIntValue()).logBase2(); 1597 // FIXME: If the input is something that is easily negated (e.g. a 1598 // single-use add), we should put the negate there. 1599 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, 1600 DAG.getConstant(0, VT), 1601 DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, N0, 1602 DAG.getConstant(Log2Val, getShiftAmountTy()))); 1603 } 1604 // (mul (shl X, c1), c2) -> (mul X, c2 << c1) 1605 if (N1C && N0.getOpcode() == ISD::SHL && 1606 isa<ConstantSDNode>(N0.getOperand(1))) { 1607 SDValue C3 = DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, 1608 N1, N0.getOperand(1)); 1609 AddToWorkList(C3.getNode()); 1610 return DAG.getNode(ISD::MUL, N->getDebugLoc(), VT, 1611 N0.getOperand(0), C3); 1612 } 1613 1614 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one 1615 // use. 1616 { 1617 SDValue Sh(0,0), Y(0,0); 1618 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)). 1619 if (N0.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N0.getOperand(1)) && 1620 N0.getNode()->hasOneUse()) { 1621 Sh = N0; Y = N1; 1622 } else if (N1.getOpcode() == ISD::SHL && 1623 isa<ConstantSDNode>(N1.getOperand(1)) && 1624 N1.getNode()->hasOneUse()) { 1625 Sh = N1; Y = N0; 1626 } 1627 1628 if (Sh.getNode()) { 1629 SDValue Mul = DAG.getNode(ISD::MUL, N->getDebugLoc(), VT, 1630 Sh.getOperand(0), Y); 1631 return DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, 1632 Mul, Sh.getOperand(1)); 1633 } 1634 } 1635 1636 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2) 1637 if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() && 1638 isa<ConstantSDNode>(N0.getOperand(1))) 1639 return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, 1640 DAG.getNode(ISD::MUL, N0.getDebugLoc(), VT, 1641 N0.getOperand(0), N1), 1642 DAG.getNode(ISD::MUL, N1.getDebugLoc(), VT, 1643 N0.getOperand(1), N1)); 1644 1645 // reassociate mul 1646 SDValue RMUL = ReassociateOps(ISD::MUL, N->getDebugLoc(), N0, N1); 1647 if (RMUL.getNode() != 0) 1648 return RMUL; 1649 1650 return SDValue(); 1651 } 1652 1653 SDValue DAGCombiner::visitSDIV(SDNode *N) { 1654 SDValue N0 = N->getOperand(0); 1655 SDValue N1 = N->getOperand(1); 1656 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode()); 1657 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode()); 1658 EVT VT = N->getValueType(0); 1659 1660 // fold vector ops 1661 if (VT.isVector()) { 1662 SDValue FoldedVOp = SimplifyVBinOp(N); 1663 if (FoldedVOp.getNode()) return FoldedVOp; 1664 } 1665 1666 // fold (sdiv c1, c2) -> c1/c2 1667 if (N0C && N1C && !N1C->isNullValue()) 1668 return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C); 1669 // fold (sdiv X, 1) -> X 1670 if (N1C && N1C->getSExtValue() == 1LL) 1671 return N0; 1672 // fold (sdiv X, -1) -> 0-X 1673 if (N1C && N1C->isAllOnesValue()) 1674 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, 1675 DAG.getConstant(0, VT), N0); 1676 // If we know the sign bits of both operands are zero, strength reduce to a 1677 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2 1678 if (!VT.isVector()) { 1679 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0)) 1680 return DAG.getNode(ISD::UDIV, N->getDebugLoc(), N1.getValueType(), 1681 N0, N1); 1682 } 1683 // fold (sdiv X, pow2) -> simple ops after legalize 1684 if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap() && 1685 (isPowerOf2_64(N1C->getSExtValue()) || 1686 isPowerOf2_64(-N1C->getSExtValue()))) { 1687 // If dividing by powers of two is cheap, then don't perform the following 1688 // fold. 1689 if (TLI.isPow2DivCheap()) 1690 return SDValue(); 1691 1692 int64_t pow2 = N1C->getSExtValue(); 1693 int64_t abs2 = pow2 > 0 ? pow2 : -pow2; 1694 unsigned lg2 = Log2_64(abs2); 1695 1696 // Splat the sign bit into the register 1697 SDValue SGN = DAG.getNode(ISD::SRA, N->getDebugLoc(), VT, N0, 1698 DAG.getConstant(VT.getSizeInBits()-1, 1699 getShiftAmountTy())); 1700 AddToWorkList(SGN.getNode()); 1701 1702 // Add (N0 < 0) ? abs2 - 1 : 0; 1703 SDValue SRL = DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, SGN, 1704 DAG.getConstant(VT.getSizeInBits() - lg2, 1705 getShiftAmountTy())); 1706 SDValue ADD = DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0, SRL); 1707 AddToWorkList(SRL.getNode()); 1708 AddToWorkList(ADD.getNode()); // Divide by pow2 1709 SDValue SRA = DAG.getNode(ISD::SRA, N->getDebugLoc(), VT, ADD, 1710 DAG.getConstant(lg2, getShiftAmountTy())); 1711 1712 // If we're dividing by a positive value, we're done. Otherwise, we must 1713 // negate the result. 1714 if (pow2 > 0) 1715 return SRA; 1716 1717 AddToWorkList(SRA.getNode()); 1718 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, 1719 DAG.getConstant(0, VT), SRA); 1720 } 1721 1722 // if integer divide is expensive and we satisfy the requirements, emit an 1723 // alternate sequence. 1724 if (N1C && (N1C->getSExtValue() < -1 || N1C->getSExtValue() > 1) && 1725 !TLI.isIntDivCheap()) { 1726 SDValue Op = BuildSDIV(N); 1727 if (Op.getNode()) return Op; 1728 } 1729 1730 // undef / X -> 0 1731 if (N0.getOpcode() == ISD::UNDEF) 1732 return DAG.getConstant(0, VT); 1733 // X / undef -> undef 1734 if (N1.getOpcode() == ISD::UNDEF) 1735 return N1; 1736 1737 return SDValue(); 1738 } 1739 1740 SDValue DAGCombiner::visitUDIV(SDNode *N) { 1741 SDValue N0 = N->getOperand(0); 1742 SDValue N1 = N->getOperand(1); 1743 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode()); 1744 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode()); 1745 EVT VT = N->getValueType(0); 1746 1747 // fold vector ops 1748 if (VT.isVector()) { 1749 SDValue FoldedVOp = SimplifyVBinOp(N); 1750 if (FoldedVOp.getNode()) return FoldedVOp; 1751 } 1752 1753 // fold (udiv c1, c2) -> c1/c2 1754 if (N0C && N1C && !N1C->isNullValue()) 1755 return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C); 1756 // fold (udiv x, (1 << c)) -> x >>u c 1757 if (N1C && N1C->getAPIntValue().isPowerOf2()) 1758 return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0, 1759 DAG.getConstant(N1C->getAPIntValue().logBase2(), 1760 getShiftAmountTy())); 1761 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2 1762 if (N1.getOpcode() == ISD::SHL) { 1763 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) { 1764 if (SHC->getAPIntValue().isPowerOf2()) { 1765 EVT ADDVT = N1.getOperand(1).getValueType(); 1766 SDValue Add = DAG.getNode(ISD::ADD, N->getDebugLoc(), ADDVT, 1767 N1.getOperand(1), 1768 DAG.getConstant(SHC->getAPIntValue() 1769 .logBase2(), 1770 ADDVT)); 1771 AddToWorkList(Add.getNode()); 1772 return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0, Add); 1773 } 1774 } 1775 } 1776 // fold (udiv x, c) -> alternate 1777 if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap()) { 1778 SDValue Op = BuildUDIV(N); 1779 if (Op.getNode()) return Op; 1780 } 1781 1782 // undef / X -> 0 1783 if (N0.getOpcode() == ISD::UNDEF) 1784 return DAG.getConstant(0, VT); 1785 // X / undef -> undef 1786 if (N1.getOpcode() == ISD::UNDEF) 1787 return N1; 1788 1789 return SDValue(); 1790 } 1791 1792 SDValue DAGCombiner::visitSREM(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 = N->getValueType(0); 1798 1799 // fold (srem c1, c2) -> c1%c2 1800 if (N0C && N1C && !N1C->isNullValue()) 1801 return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C); 1802 // If we know the sign bits of both operands are zero, strength reduce to a 1803 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15 1804 if (!VT.isVector()) { 1805 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0)) 1806 return DAG.getNode(ISD::UREM, N->getDebugLoc(), VT, N0, N1); 1807 } 1808 1809 // If X/C can be simplified by the division-by-constant logic, lower 1810 // X%C to the equivalent of X-X/C*C. 1811 if (N1C && !N1C->isNullValue()) { 1812 SDValue Div = DAG.getNode(ISD::SDIV, N->getDebugLoc(), VT, N0, N1); 1813 AddToWorkList(Div.getNode()); 1814 SDValue OptimizedDiv = combine(Div.getNode()); 1815 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) { 1816 SDValue Mul = DAG.getNode(ISD::MUL, N->getDebugLoc(), VT, 1817 OptimizedDiv, N1); 1818 SDValue Sub = DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N0, Mul); 1819 AddToWorkList(Mul.getNode()); 1820 return Sub; 1821 } 1822 } 1823 1824 // undef % X -> 0 1825 if (N0.getOpcode() == ISD::UNDEF) 1826 return DAG.getConstant(0, VT); 1827 // X % undef -> undef 1828 if (N1.getOpcode() == ISD::UNDEF) 1829 return N1; 1830 1831 return SDValue(); 1832 } 1833 1834 SDValue DAGCombiner::visitUREM(SDNode *N) { 1835 SDValue N0 = N->getOperand(0); 1836 SDValue N1 = N->getOperand(1); 1837 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 1838 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 1839 EVT VT = N->getValueType(0); 1840 1841 // fold (urem c1, c2) -> c1%c2 1842 if (N0C && N1C && !N1C->isNullValue()) 1843 return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C); 1844 // fold (urem x, pow2) -> (and x, pow2-1) 1845 if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2()) 1846 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0, 1847 DAG.getConstant(N1C->getAPIntValue()-1,VT)); 1848 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1)) 1849 if (N1.getOpcode() == ISD::SHL) { 1850 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) { 1851 if (SHC->getAPIntValue().isPowerOf2()) { 1852 SDValue Add = 1853 DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N1, 1854 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), 1855 VT)); 1856 AddToWorkList(Add.getNode()); 1857 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0, Add); 1858 } 1859 } 1860 } 1861 1862 // If X/C can be simplified by the division-by-constant logic, lower 1863 // X%C to the equivalent of X-X/C*C. 1864 if (N1C && !N1C->isNullValue()) { 1865 SDValue Div = DAG.getNode(ISD::UDIV, N->getDebugLoc(), VT, N0, N1); 1866 AddToWorkList(Div.getNode()); 1867 SDValue OptimizedDiv = combine(Div.getNode()); 1868 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) { 1869 SDValue Mul = DAG.getNode(ISD::MUL, N->getDebugLoc(), VT, 1870 OptimizedDiv, N1); 1871 SDValue Sub = DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N0, Mul); 1872 AddToWorkList(Mul.getNode()); 1873 return Sub; 1874 } 1875 } 1876 1877 // undef % X -> 0 1878 if (N0.getOpcode() == ISD::UNDEF) 1879 return DAG.getConstant(0, VT); 1880 // X % undef -> undef 1881 if (N1.getOpcode() == ISD::UNDEF) 1882 return N1; 1883 1884 return SDValue(); 1885 } 1886 1887 SDValue DAGCombiner::visitMULHS(SDNode *N) { 1888 SDValue N0 = N->getOperand(0); 1889 SDValue N1 = N->getOperand(1); 1890 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 1891 EVT VT = N->getValueType(0); 1892 1893 // fold (mulhs x, 0) -> 0 1894 if (N1C && N1C->isNullValue()) 1895 return N1; 1896 // fold (mulhs x, 1) -> (sra x, size(x)-1) 1897 if (N1C && N1C->getAPIntValue() == 1) 1898 return DAG.getNode(ISD::SRA, N->getDebugLoc(), N0.getValueType(), N0, 1899 DAG.getConstant(N0.getValueType().getSizeInBits() - 1, 1900 getShiftAmountTy())); 1901 // fold (mulhs x, undef) -> 0 1902 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF) 1903 return DAG.getConstant(0, VT); 1904 1905 return SDValue(); 1906 } 1907 1908 SDValue DAGCombiner::visitMULHU(SDNode *N) { 1909 SDValue N0 = N->getOperand(0); 1910 SDValue N1 = N->getOperand(1); 1911 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 1912 EVT VT = N->getValueType(0); 1913 1914 // fold (mulhu x, 0) -> 0 1915 if (N1C && N1C->isNullValue()) 1916 return N1; 1917 // fold (mulhu x, 1) -> 0 1918 if (N1C && N1C->getAPIntValue() == 1) 1919 return DAG.getConstant(0, N0.getValueType()); 1920 // fold (mulhu x, undef) -> 0 1921 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF) 1922 return DAG.getConstant(0, VT); 1923 1924 return SDValue(); 1925 } 1926 1927 /// SimplifyNodeWithTwoResults - Perform optimizations common to nodes that 1928 /// compute two values. LoOp and HiOp give the opcodes for the two computations 1929 /// that are being performed. Return true if a simplification was made. 1930 /// 1931 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp, 1932 unsigned HiOp) { 1933 // If the high half is not needed, just compute the low half. 1934 bool HiExists = N->hasAnyUseOfValue(1); 1935 if (!HiExists && 1936 (!LegalOperations || 1937 TLI.isOperationLegal(LoOp, N->getValueType(0)))) { 1938 SDValue Res = DAG.getNode(LoOp, N->getDebugLoc(), N->getValueType(0), 1939 N->op_begin(), N->getNumOperands()); 1940 return CombineTo(N, Res, Res); 1941 } 1942 1943 // If the low half is not needed, just compute the high half. 1944 bool LoExists = N->hasAnyUseOfValue(0); 1945 if (!LoExists && 1946 (!LegalOperations || 1947 TLI.isOperationLegal(HiOp, N->getValueType(1)))) { 1948 SDValue Res = DAG.getNode(HiOp, N->getDebugLoc(), N->getValueType(1), 1949 N->op_begin(), N->getNumOperands()); 1950 return CombineTo(N, Res, Res); 1951 } 1952 1953 // If both halves are used, return as it is. 1954 if (LoExists && HiExists) 1955 return SDValue(); 1956 1957 // If the two computed results can be simplified separately, separate them. 1958 if (LoExists) { 1959 SDValue Lo = DAG.getNode(LoOp, N->getDebugLoc(), N->getValueType(0), 1960 N->op_begin(), N->getNumOperands()); 1961 AddToWorkList(Lo.getNode()); 1962 SDValue LoOpt = combine(Lo.getNode()); 1963 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() && 1964 (!LegalOperations || 1965 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType()))) 1966 return CombineTo(N, LoOpt, LoOpt); 1967 } 1968 1969 if (HiExists) { 1970 SDValue Hi = DAG.getNode(HiOp, N->getDebugLoc(), N->getValueType(1), 1971 N->op_begin(), N->getNumOperands()); 1972 AddToWorkList(Hi.getNode()); 1973 SDValue HiOpt = combine(Hi.getNode()); 1974 if (HiOpt.getNode() && HiOpt != Hi && 1975 (!LegalOperations || 1976 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType()))) 1977 return CombineTo(N, HiOpt, HiOpt); 1978 } 1979 1980 return SDValue(); 1981 } 1982 1983 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) { 1984 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS); 1985 if (Res.getNode()) return Res; 1986 1987 return SDValue(); 1988 } 1989 1990 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) { 1991 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU); 1992 if (Res.getNode()) return Res; 1993 1994 return SDValue(); 1995 } 1996 1997 SDValue DAGCombiner::visitSDIVREM(SDNode *N) { 1998 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM); 1999 if (Res.getNode()) return Res; 2000 2001 return SDValue(); 2002 } 2003 2004 SDValue DAGCombiner::visitUDIVREM(SDNode *N) { 2005 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM); 2006 if (Res.getNode()) return Res; 2007 2008 return SDValue(); 2009 } 2010 2011 /// SimplifyBinOpWithSameOpcodeHands - If this is a binary operator with 2012 /// two operands of the same opcode, try to simplify it. 2013 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) { 2014 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1); 2015 EVT VT = N0.getValueType(); 2016 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!"); 2017 2018 // Bail early if none of these transforms apply. 2019 if (N0.getNode()->getNumOperands() == 0) return SDValue(); 2020 2021 // For each of OP in AND/OR/XOR: 2022 // fold (OP (zext x), (zext y)) -> (zext (OP x, y)) 2023 // fold (OP (sext x), (sext y)) -> (sext (OP x, y)) 2024 // fold (OP (aext x), (aext y)) -> (aext (OP x, y)) 2025 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) 2026 // 2027 // do not sink logical op inside of a vector extend, since it may combine 2028 // into a vsetcc. 2029 EVT Op0VT = N0.getOperand(0).getValueType(); 2030 if ((N0.getOpcode() == ISD::ZERO_EXTEND || 2031 N0.getOpcode() == ISD::SIGN_EXTEND || 2032 // Avoid infinite looping with PromoteIntBinOp. 2033 (N0.getOpcode() == ISD::ANY_EXTEND && 2034 (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) || 2035 (N0.getOpcode() == ISD::TRUNCATE && TLI.isTypeLegal(Op0VT))) && 2036 !VT.isVector() && 2037 Op0VT == N1.getOperand(0).getValueType() && 2038 (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) { 2039 SDValue ORNode = DAG.getNode(N->getOpcode(), N0.getDebugLoc(), 2040 N0.getOperand(0).getValueType(), 2041 N0.getOperand(0), N1.getOperand(0)); 2042 AddToWorkList(ORNode.getNode()); 2043 return DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT, ORNode); 2044 } 2045 2046 // For each of OP in SHL/SRL/SRA/AND... 2047 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z) 2048 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z) 2049 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z) 2050 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL || 2051 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) && 2052 N0.getOperand(1) == N1.getOperand(1)) { 2053 SDValue ORNode = DAG.getNode(N->getOpcode(), N0.getDebugLoc(), 2054 N0.getOperand(0).getValueType(), 2055 N0.getOperand(0), N1.getOperand(0)); 2056 AddToWorkList(ORNode.getNode()); 2057 return DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT, 2058 ORNode, N0.getOperand(1)); 2059 } 2060 2061 return SDValue(); 2062 } 2063 2064 SDValue DAGCombiner::visitAND(SDNode *N) { 2065 SDValue N0 = N->getOperand(0); 2066 SDValue N1 = N->getOperand(1); 2067 SDValue LL, LR, RL, RR, CC0, CC1; 2068 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 2069 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 2070 EVT VT = N1.getValueType(); 2071 unsigned BitWidth = VT.getScalarType().getSizeInBits(); 2072 2073 // fold vector ops 2074 if (VT.isVector()) { 2075 SDValue FoldedVOp = SimplifyVBinOp(N); 2076 if (FoldedVOp.getNode()) return FoldedVOp; 2077 } 2078 2079 // fold (and x, undef) -> 0 2080 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF) 2081 return DAG.getConstant(0, VT); 2082 // fold (and c1, c2) -> c1&c2 2083 if (N0C && N1C) 2084 return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C); 2085 // canonicalize constant to RHS 2086 if (N0C && !N1C) 2087 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N1, N0); 2088 // fold (and x, -1) -> x 2089 if (N1C && N1C->isAllOnesValue()) 2090 return N0; 2091 // if (and x, c) is known to be zero, return 0 2092 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0), 2093 APInt::getAllOnesValue(BitWidth))) 2094 return DAG.getConstant(0, VT); 2095 // reassociate and 2096 SDValue RAND = ReassociateOps(ISD::AND, N->getDebugLoc(), N0, N1); 2097 if (RAND.getNode() != 0) 2098 return RAND; 2099 // fold (and (or x, C), D) -> D if (C & D) == D 2100 if (N1C && N0.getOpcode() == ISD::OR) 2101 if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) 2102 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue()) 2103 return N1; 2104 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits. 2105 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) { 2106 SDValue N0Op0 = N0.getOperand(0); 2107 APInt Mask = ~N1C->getAPIntValue(); 2108 Mask.trunc(N0Op0.getValueSizeInBits()); 2109 if (DAG.MaskedValueIsZero(N0Op0, Mask)) { 2110 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), 2111 N0.getValueType(), N0Op0); 2112 2113 // Replace uses of the AND with uses of the Zero extend node. 2114 CombineTo(N, Zext); 2115 2116 // We actually want to replace all uses of the any_extend with the 2117 // zero_extend, to avoid duplicating things. This will later cause this 2118 // AND to be folded. 2119 CombineTo(N0.getNode(), Zext); 2120 return SDValue(N, 0); // Return N so it doesn't get rechecked! 2121 } 2122 } 2123 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y)) 2124 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){ 2125 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get(); 2126 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get(); 2127 2128 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 && 2129 LL.getValueType().isInteger()) { 2130 // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0) 2131 if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) { 2132 SDValue ORNode = DAG.getNode(ISD::OR, N0.getDebugLoc(), 2133 LR.getValueType(), LL, RL); 2134 AddToWorkList(ORNode.getNode()); 2135 return DAG.getSetCC(N->getDebugLoc(), VT, ORNode, LR, Op1); 2136 } 2137 // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1) 2138 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) { 2139 SDValue ANDNode = DAG.getNode(ISD::AND, N0.getDebugLoc(), 2140 LR.getValueType(), LL, RL); 2141 AddToWorkList(ANDNode.getNode()); 2142 return DAG.getSetCC(N->getDebugLoc(), VT, ANDNode, LR, Op1); 2143 } 2144 // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1) 2145 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) { 2146 SDValue ORNode = DAG.getNode(ISD::OR, N0.getDebugLoc(), 2147 LR.getValueType(), LL, RL); 2148 AddToWorkList(ORNode.getNode()); 2149 return DAG.getSetCC(N->getDebugLoc(), VT, ORNode, LR, Op1); 2150 } 2151 } 2152 // canonicalize equivalent to ll == rl 2153 if (LL == RR && LR == RL) { 2154 Op1 = ISD::getSetCCSwappedOperands(Op1); 2155 std::swap(RL, RR); 2156 } 2157 if (LL == RL && LR == RR) { 2158 bool isInteger = LL.getValueType().isInteger(); 2159 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger); 2160 if (Result != ISD::SETCC_INVALID && 2161 (!LegalOperations || TLI.isCondCodeLegal(Result, LL.getValueType()))) 2162 return DAG.getSetCC(N->getDebugLoc(), N0.getValueType(), 2163 LL, LR, Result); 2164 } 2165 } 2166 2167 // Simplify: (and (op x...), (op y...)) -> (op (and x, y)) 2168 if (N0.getOpcode() == N1.getOpcode()) { 2169 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N); 2170 if (Tmp.getNode()) return Tmp; 2171 } 2172 2173 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1) 2174 // fold (and (sra)) -> (and (srl)) when possible. 2175 if (!VT.isVector() && 2176 SimplifyDemandedBits(SDValue(N, 0))) 2177 return SDValue(N, 0); 2178 2179 // fold (zext_inreg (extload x)) -> (zextload x) 2180 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) { 2181 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 2182 EVT MemVT = LN0->getMemoryVT(); 2183 // If we zero all the possible extended bits, then we can turn this into 2184 // a zextload if we are running before legalize or the operation is legal. 2185 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits(); 2186 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth, 2187 BitWidth - MemVT.getScalarType().getSizeInBits())) && 2188 ((!LegalOperations && !LN0->isVolatile()) || 2189 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) { 2190 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, N0.getDebugLoc(), VT, 2191 LN0->getChain(), LN0->getBasePtr(), 2192 LN0->getSrcValue(), 2193 LN0->getSrcValueOffset(), MemVT, 2194 LN0->isVolatile(), LN0->isNonTemporal(), 2195 LN0->getAlignment()); 2196 AddToWorkList(N); 2197 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 2198 return SDValue(N, 0); // Return N so it doesn't get rechecked! 2199 } 2200 } 2201 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use 2202 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 2203 N0.hasOneUse()) { 2204 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 2205 EVT MemVT = LN0->getMemoryVT(); 2206 // If we zero all the possible extended bits, then we can turn this into 2207 // a zextload if we are running before legalize or the operation is legal. 2208 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits(); 2209 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth, 2210 BitWidth - MemVT.getScalarType().getSizeInBits())) && 2211 ((!LegalOperations && !LN0->isVolatile()) || 2212 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) { 2213 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, N0.getDebugLoc(), VT, 2214 LN0->getChain(), 2215 LN0->getBasePtr(), LN0->getSrcValue(), 2216 LN0->getSrcValueOffset(), MemVT, 2217 LN0->isVolatile(), LN0->isNonTemporal(), 2218 LN0->getAlignment()); 2219 AddToWorkList(N); 2220 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 2221 return SDValue(N, 0); // Return N so it doesn't get rechecked! 2222 } 2223 } 2224 2225 // fold (and (load x), 255) -> (zextload x, i8) 2226 // fold (and (extload x, i16), 255) -> (zextload x, i8) 2227 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8) 2228 if (N1C && (N0.getOpcode() == ISD::LOAD || 2229 (N0.getOpcode() == ISD::ANY_EXTEND && 2230 N0.getOperand(0).getOpcode() == ISD::LOAD))) { 2231 bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND; 2232 LoadSDNode *LN0 = HasAnyExt 2233 ? cast<LoadSDNode>(N0.getOperand(0)) 2234 : cast<LoadSDNode>(N0); 2235 if (LN0->getExtensionType() != ISD::SEXTLOAD && 2236 LN0->isUnindexed() && N0.hasOneUse() && LN0->hasOneUse()) { 2237 uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits(); 2238 if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){ 2239 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits); 2240 EVT LoadedVT = LN0->getMemoryVT(); 2241 2242 if (ExtVT == LoadedVT && 2243 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) { 2244 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT; 2245 2246 SDValue NewLoad = 2247 DAG.getExtLoad(ISD::ZEXTLOAD, LN0->getDebugLoc(), LoadResultTy, 2248 LN0->getChain(), LN0->getBasePtr(), 2249 LN0->getSrcValue(), LN0->getSrcValueOffset(), 2250 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(), 2251 LN0->getAlignment()); 2252 AddToWorkList(N); 2253 CombineTo(LN0, NewLoad, NewLoad.getValue(1)); 2254 return SDValue(N, 0); // Return N so it doesn't get rechecked! 2255 } 2256 2257 // Do not change the width of a volatile load. 2258 // Do not generate loads of non-round integer types since these can 2259 // be expensive (and would be wrong if the type is not byte sized). 2260 if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() && 2261 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) { 2262 EVT PtrType = LN0->getOperand(1).getValueType(); 2263 2264 unsigned Alignment = LN0->getAlignment(); 2265 SDValue NewPtr = LN0->getBasePtr(); 2266 2267 // For big endian targets, we need to add an offset to the pointer 2268 // to load the correct bytes. For little endian systems, we merely 2269 // need to read fewer bytes from the same pointer. 2270 if (TLI.isBigEndian()) { 2271 unsigned LVTStoreBytes = LoadedVT.getStoreSize(); 2272 unsigned EVTStoreBytes = ExtVT.getStoreSize(); 2273 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes; 2274 NewPtr = DAG.getNode(ISD::ADD, LN0->getDebugLoc(), PtrType, 2275 NewPtr, DAG.getConstant(PtrOff, PtrType)); 2276 Alignment = MinAlign(Alignment, PtrOff); 2277 } 2278 2279 AddToWorkList(NewPtr.getNode()); 2280 2281 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT; 2282 SDValue Load = 2283 DAG.getExtLoad(ISD::ZEXTLOAD, LN0->getDebugLoc(), LoadResultTy, 2284 LN0->getChain(), NewPtr, 2285 LN0->getSrcValue(), LN0->getSrcValueOffset(), 2286 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(), 2287 Alignment); 2288 AddToWorkList(N); 2289 CombineTo(LN0, Load, Load.getValue(1)); 2290 return SDValue(N, 0); // Return N so it doesn't get rechecked! 2291 } 2292 } 2293 } 2294 } 2295 2296 return SDValue(); 2297 } 2298 2299 SDValue DAGCombiner::visitOR(SDNode *N) { 2300 SDValue N0 = N->getOperand(0); 2301 SDValue N1 = N->getOperand(1); 2302 SDValue LL, LR, RL, RR, CC0, CC1; 2303 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 2304 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 2305 EVT VT = N1.getValueType(); 2306 2307 // fold vector ops 2308 if (VT.isVector()) { 2309 SDValue FoldedVOp = SimplifyVBinOp(N); 2310 if (FoldedVOp.getNode()) return FoldedVOp; 2311 } 2312 2313 // fold (or x, undef) -> -1 2314 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF) { 2315 EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT; 2316 return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT); 2317 } 2318 // fold (or c1, c2) -> c1|c2 2319 if (N0C && N1C) 2320 return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C); 2321 // canonicalize constant to RHS 2322 if (N0C && !N1C) 2323 return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, N1, N0); 2324 // fold (or x, 0) -> x 2325 if (N1C && N1C->isNullValue()) 2326 return N0; 2327 // fold (or x, -1) -> -1 2328 if (N1C && N1C->isAllOnesValue()) 2329 return N1; 2330 // fold (or x, c) -> c iff (x & ~c) == 0 2331 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue())) 2332 return N1; 2333 // reassociate or 2334 SDValue ROR = ReassociateOps(ISD::OR, N->getDebugLoc(), N0, N1); 2335 if (ROR.getNode() != 0) 2336 return ROR; 2337 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2) 2338 // iff (c1 & c2) == 0. 2339 if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() && 2340 isa<ConstantSDNode>(N0.getOperand(1))) { 2341 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1)); 2342 if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) 2343 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, 2344 DAG.getNode(ISD::OR, N0.getDebugLoc(), VT, 2345 N0.getOperand(0), N1), 2346 DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1)); 2347 } 2348 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y)) 2349 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){ 2350 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get(); 2351 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get(); 2352 2353 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 && 2354 LL.getValueType().isInteger()) { 2355 // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0) 2356 // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0) 2357 if (cast<ConstantSDNode>(LR)->isNullValue() && 2358 (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) { 2359 SDValue ORNode = DAG.getNode(ISD::OR, LR.getDebugLoc(), 2360 LR.getValueType(), LL, RL); 2361 AddToWorkList(ORNode.getNode()); 2362 return DAG.getSetCC(N->getDebugLoc(), VT, ORNode, LR, Op1); 2363 } 2364 // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1) 2365 // fold (or (setgt X, -1), (setgt Y -1)) -> (setgt (and X, Y), -1) 2366 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && 2367 (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) { 2368 SDValue ANDNode = DAG.getNode(ISD::AND, LR.getDebugLoc(), 2369 LR.getValueType(), LL, RL); 2370 AddToWorkList(ANDNode.getNode()); 2371 return DAG.getSetCC(N->getDebugLoc(), VT, ANDNode, LR, Op1); 2372 } 2373 } 2374 // canonicalize equivalent to ll == rl 2375 if (LL == RR && LR == RL) { 2376 Op1 = ISD::getSetCCSwappedOperands(Op1); 2377 std::swap(RL, RR); 2378 } 2379 if (LL == RL && LR == RR) { 2380 bool isInteger = LL.getValueType().isInteger(); 2381 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger); 2382 if (Result != ISD::SETCC_INVALID && 2383 (!LegalOperations || TLI.isCondCodeLegal(Result, LL.getValueType()))) 2384 return DAG.getSetCC(N->getDebugLoc(), N0.getValueType(), 2385 LL, LR, Result); 2386 } 2387 } 2388 2389 // Simplify: (or (op x...), (op y...)) -> (op (or x, y)) 2390 if (N0.getOpcode() == N1.getOpcode()) { 2391 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N); 2392 if (Tmp.getNode()) return Tmp; 2393 } 2394 2395 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible. 2396 if (N0.getOpcode() == ISD::AND && 2397 N1.getOpcode() == ISD::AND && 2398 N0.getOperand(1).getOpcode() == ISD::Constant && 2399 N1.getOperand(1).getOpcode() == ISD::Constant && 2400 // Don't increase # computations. 2401 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) { 2402 // We can only do this xform if we know that bits from X that are set in C2 2403 // but not in C1 are already zero. Likewise for Y. 2404 const APInt &LHSMask = 2405 cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 2406 const APInt &RHSMask = 2407 cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue(); 2408 2409 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) && 2410 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) { 2411 SDValue X = DAG.getNode(ISD::OR, N0.getDebugLoc(), VT, 2412 N0.getOperand(0), N1.getOperand(0)); 2413 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, X, 2414 DAG.getConstant(LHSMask | RHSMask, VT)); 2415 } 2416 } 2417 2418 // See if this is some rotate idiom. 2419 if (SDNode *Rot = MatchRotate(N0, N1, N->getDebugLoc())) 2420 return SDValue(Rot, 0); 2421 2422 return SDValue(); 2423 } 2424 2425 /// MatchRotateHalf - Match "(X shl/srl V1) & V2" where V2 may not be present. 2426 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) { 2427 if (Op.getOpcode() == ISD::AND) { 2428 if (isa<ConstantSDNode>(Op.getOperand(1))) { 2429 Mask = Op.getOperand(1); 2430 Op = Op.getOperand(0); 2431 } else { 2432 return false; 2433 } 2434 } 2435 2436 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) { 2437 Shift = Op; 2438 return true; 2439 } 2440 2441 return false; 2442 } 2443 2444 // MatchRotate - Handle an 'or' of two operands. If this is one of the many 2445 // idioms for rotate, and if the target supports rotation instructions, generate 2446 // a rot[lr]. 2447 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, DebugLoc DL) { 2448 // Must be a legal type. Expanded 'n promoted things won't work with rotates. 2449 EVT VT = LHS.getValueType(); 2450 if (!TLI.isTypeLegal(VT)) return 0; 2451 2452 // The target must have at least one rotate flavor. 2453 bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT); 2454 bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT); 2455 if (!HasROTL && !HasROTR) return 0; 2456 2457 // Match "(X shl/srl V1) & V2" where V2 may not be present. 2458 SDValue LHSShift; // The shift. 2459 SDValue LHSMask; // AND value if any. 2460 if (!MatchRotateHalf(LHS, LHSShift, LHSMask)) 2461 return 0; // Not part of a rotate. 2462 2463 SDValue RHSShift; // The shift. 2464 SDValue RHSMask; // AND value if any. 2465 if (!MatchRotateHalf(RHS, RHSShift, RHSMask)) 2466 return 0; // Not part of a rotate. 2467 2468 if (LHSShift.getOperand(0) != RHSShift.getOperand(0)) 2469 return 0; // Not shifting the same value. 2470 2471 if (LHSShift.getOpcode() == RHSShift.getOpcode()) 2472 return 0; // Shifts must disagree. 2473 2474 // Canonicalize shl to left side in a shl/srl pair. 2475 if (RHSShift.getOpcode() == ISD::SHL) { 2476 std::swap(LHS, RHS); 2477 std::swap(LHSShift, RHSShift); 2478 std::swap(LHSMask , RHSMask ); 2479 } 2480 2481 unsigned OpSizeInBits = VT.getSizeInBits(); 2482 SDValue LHSShiftArg = LHSShift.getOperand(0); 2483 SDValue LHSShiftAmt = LHSShift.getOperand(1); 2484 SDValue RHSShiftAmt = RHSShift.getOperand(1); 2485 2486 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1) 2487 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2) 2488 if (LHSShiftAmt.getOpcode() == ISD::Constant && 2489 RHSShiftAmt.getOpcode() == ISD::Constant) { 2490 uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue(); 2491 uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue(); 2492 if ((LShVal + RShVal) != OpSizeInBits) 2493 return 0; 2494 2495 SDValue Rot; 2496 if (HasROTL) 2497 Rot = DAG.getNode(ISD::ROTL, DL, VT, LHSShiftArg, LHSShiftAmt); 2498 else 2499 Rot = DAG.getNode(ISD::ROTR, DL, VT, LHSShiftArg, RHSShiftAmt); 2500 2501 // If there is an AND of either shifted operand, apply it to the result. 2502 if (LHSMask.getNode() || RHSMask.getNode()) { 2503 APInt Mask = APInt::getAllOnesValue(OpSizeInBits); 2504 2505 if (LHSMask.getNode()) { 2506 APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal); 2507 Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits; 2508 } 2509 if (RHSMask.getNode()) { 2510 APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal); 2511 Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits; 2512 } 2513 2514 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT)); 2515 } 2516 2517 return Rot.getNode(); 2518 } 2519 2520 // If there is a mask here, and we have a variable shift, we can't be sure 2521 // that we're masking out the right stuff. 2522 if (LHSMask.getNode() || RHSMask.getNode()) 2523 return 0; 2524 2525 // fold (or (shl x, y), (srl x, (sub 32, y))) -> (rotl x, y) 2526 // fold (or (shl x, y), (srl x, (sub 32, y))) -> (rotr x, (sub 32, y)) 2527 if (RHSShiftAmt.getOpcode() == ISD::SUB && 2528 LHSShiftAmt == RHSShiftAmt.getOperand(1)) { 2529 if (ConstantSDNode *SUBC = 2530 dyn_cast<ConstantSDNode>(RHSShiftAmt.getOperand(0))) { 2531 if (SUBC->getAPIntValue() == OpSizeInBits) { 2532 if (HasROTL) 2533 return DAG.getNode(ISD::ROTL, DL, VT, 2534 LHSShiftArg, LHSShiftAmt).getNode(); 2535 else 2536 return DAG.getNode(ISD::ROTR, DL, VT, 2537 LHSShiftArg, RHSShiftAmt).getNode(); 2538 } 2539 } 2540 } 2541 2542 // fold (or (shl x, (sub 32, y)), (srl x, r)) -> (rotr x, y) 2543 // fold (or (shl x, (sub 32, y)), (srl x, r)) -> (rotl x, (sub 32, y)) 2544 if (LHSShiftAmt.getOpcode() == ISD::SUB && 2545 RHSShiftAmt == LHSShiftAmt.getOperand(1)) { 2546 if (ConstantSDNode *SUBC = 2547 dyn_cast<ConstantSDNode>(LHSShiftAmt.getOperand(0))) { 2548 if (SUBC->getAPIntValue() == OpSizeInBits) { 2549 if (HasROTR) 2550 return DAG.getNode(ISD::ROTR, DL, VT, 2551 LHSShiftArg, RHSShiftAmt).getNode(); 2552 else 2553 return DAG.getNode(ISD::ROTL, DL, VT, 2554 LHSShiftArg, LHSShiftAmt).getNode(); 2555 } 2556 } 2557 } 2558 2559 // Look for sign/zext/any-extended or truncate cases: 2560 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND 2561 || LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND 2562 || LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND 2563 || LHSShiftAmt.getOpcode() == ISD::TRUNCATE) && 2564 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND 2565 || RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND 2566 || RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND 2567 || RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) { 2568 SDValue LExtOp0 = LHSShiftAmt.getOperand(0); 2569 SDValue RExtOp0 = RHSShiftAmt.getOperand(0); 2570 if (RExtOp0.getOpcode() == ISD::SUB && 2571 RExtOp0.getOperand(1) == LExtOp0) { 2572 // fold (or (shl x, (*ext y)), (srl x, (*ext (sub 32, y)))) -> 2573 // (rotl x, y) 2574 // fold (or (shl x, (*ext y)), (srl x, (*ext (sub 32, y)))) -> 2575 // (rotr x, (sub 32, y)) 2576 if (ConstantSDNode *SUBC = 2577 dyn_cast<ConstantSDNode>(RExtOp0.getOperand(0))) { 2578 if (SUBC->getAPIntValue() == OpSizeInBits) { 2579 return DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT, 2580 LHSShiftArg, 2581 HasROTL ? LHSShiftAmt : RHSShiftAmt).getNode(); 2582 } 2583 } 2584 } else if (LExtOp0.getOpcode() == ISD::SUB && 2585 RExtOp0 == LExtOp0.getOperand(1)) { 2586 // fold (or (shl x, (*ext (sub 32, y))), (srl x, (*ext y))) -> 2587 // (rotr x, y) 2588 // fold (or (shl x, (*ext (sub 32, y))), (srl x, (*ext y))) -> 2589 // (rotl x, (sub 32, y)) 2590 if (ConstantSDNode *SUBC = 2591 dyn_cast<ConstantSDNode>(LExtOp0.getOperand(0))) { 2592 if (SUBC->getAPIntValue() == OpSizeInBits) { 2593 return DAG.getNode(HasROTR ? ISD::ROTR : ISD::ROTL, DL, VT, 2594 LHSShiftArg, 2595 HasROTR ? RHSShiftAmt : LHSShiftAmt).getNode(); 2596 } 2597 } 2598 } 2599 } 2600 2601 return 0; 2602 } 2603 2604 SDValue DAGCombiner::visitXOR(SDNode *N) { 2605 SDValue N0 = N->getOperand(0); 2606 SDValue N1 = N->getOperand(1); 2607 SDValue LHS, RHS, CC; 2608 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 2609 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 2610 EVT VT = N0.getValueType(); 2611 2612 // fold vector ops 2613 if (VT.isVector()) { 2614 SDValue FoldedVOp = SimplifyVBinOp(N); 2615 if (FoldedVOp.getNode()) return FoldedVOp; 2616 } 2617 2618 // fold (xor undef, undef) -> 0. This is a common idiom (misuse). 2619 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF) 2620 return DAG.getConstant(0, VT); 2621 // fold (xor x, undef) -> undef 2622 if (N0.getOpcode() == ISD::UNDEF) 2623 return N0; 2624 if (N1.getOpcode() == ISD::UNDEF) 2625 return N1; 2626 // fold (xor c1, c2) -> c1^c2 2627 if (N0C && N1C) 2628 return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C); 2629 // canonicalize constant to RHS 2630 if (N0C && !N1C) 2631 return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT, N1, N0); 2632 // fold (xor x, 0) -> x 2633 if (N1C && N1C->isNullValue()) 2634 return N0; 2635 // reassociate xor 2636 SDValue RXOR = ReassociateOps(ISD::XOR, N->getDebugLoc(), N0, N1); 2637 if (RXOR.getNode() != 0) 2638 return RXOR; 2639 2640 // fold !(x cc y) -> (x !cc y) 2641 if (N1C && N1C->getAPIntValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) { 2642 bool isInt = LHS.getValueType().isInteger(); 2643 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(), 2644 isInt); 2645 2646 if (!LegalOperations || TLI.isCondCodeLegal(NotCC, LHS.getValueType())) { 2647 switch (N0.getOpcode()) { 2648 default: 2649 llvm_unreachable("Unhandled SetCC Equivalent!"); 2650 case ISD::SETCC: 2651 return DAG.getSetCC(N->getDebugLoc(), VT, LHS, RHS, NotCC); 2652 case ISD::SELECT_CC: 2653 return DAG.getSelectCC(N->getDebugLoc(), LHS, RHS, N0.getOperand(2), 2654 N0.getOperand(3), NotCC); 2655 } 2656 } 2657 } 2658 2659 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y))) 2660 if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND && 2661 N0.getNode()->hasOneUse() && 2662 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){ 2663 SDValue V = N0.getOperand(0); 2664 V = DAG.getNode(ISD::XOR, N0.getDebugLoc(), V.getValueType(), V, 2665 DAG.getConstant(1, V.getValueType())); 2666 AddToWorkList(V.getNode()); 2667 return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT, V); 2668 } 2669 2670 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc 2671 if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 && 2672 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) { 2673 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1); 2674 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) { 2675 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND; 2676 LHS = DAG.getNode(ISD::XOR, LHS.getDebugLoc(), VT, LHS, N1); // LHS = ~LHS 2677 RHS = DAG.getNode(ISD::XOR, RHS.getDebugLoc(), VT, RHS, N1); // RHS = ~RHS 2678 AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode()); 2679 return DAG.getNode(NewOpcode, N->getDebugLoc(), VT, LHS, RHS); 2680 } 2681 } 2682 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants 2683 if (N1C && N1C->isAllOnesValue() && 2684 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) { 2685 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1); 2686 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) { 2687 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND; 2688 LHS = DAG.getNode(ISD::XOR, LHS.getDebugLoc(), VT, LHS, N1); // LHS = ~LHS 2689 RHS = DAG.getNode(ISD::XOR, RHS.getDebugLoc(), VT, RHS, N1); // RHS = ~RHS 2690 AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode()); 2691 return DAG.getNode(NewOpcode, N->getDebugLoc(), VT, LHS, RHS); 2692 } 2693 } 2694 // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2)) 2695 if (N1C && N0.getOpcode() == ISD::XOR) { 2696 ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0)); 2697 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 2698 if (N00C) 2699 return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT, N0.getOperand(1), 2700 DAG.getConstant(N1C->getAPIntValue() ^ 2701 N00C->getAPIntValue(), VT)); 2702 if (N01C) 2703 return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT, N0.getOperand(0), 2704 DAG.getConstant(N1C->getAPIntValue() ^ 2705 N01C->getAPIntValue(), VT)); 2706 } 2707 // fold (xor x, x) -> 0 2708 if (N0 == N1) { 2709 if (!VT.isVector()) { 2710 return DAG.getConstant(0, VT); 2711 } else if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT)){ 2712 // Produce a vector of zeros. 2713 SDValue El = DAG.getConstant(0, VT.getVectorElementType()); 2714 std::vector<SDValue> Ops(VT.getVectorNumElements(), El); 2715 return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(), VT, 2716 &Ops[0], Ops.size()); 2717 } 2718 } 2719 2720 // Simplify: xor (op x...), (op y...) -> (op (xor x, y)) 2721 if (N0.getOpcode() == N1.getOpcode()) { 2722 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N); 2723 if (Tmp.getNode()) return Tmp; 2724 } 2725 2726 // Simplify the expression using non-local knowledge. 2727 if (!VT.isVector() && 2728 SimplifyDemandedBits(SDValue(N, 0))) 2729 return SDValue(N, 0); 2730 2731 return SDValue(); 2732 } 2733 2734 /// visitShiftByConstant - Handle transforms common to the three shifts, when 2735 /// the shift amount is a constant. 2736 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, unsigned Amt) { 2737 SDNode *LHS = N->getOperand(0).getNode(); 2738 if (!LHS->hasOneUse()) return SDValue(); 2739 2740 // We want to pull some binops through shifts, so that we have (and (shift)) 2741 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of 2742 // thing happens with address calculations, so it's important to canonicalize 2743 // it. 2744 bool HighBitSet = false; // Can we transform this if the high bit is set? 2745 2746 switch (LHS->getOpcode()) { 2747 default: return SDValue(); 2748 case ISD::OR: 2749 case ISD::XOR: 2750 HighBitSet = false; // We can only transform sra if the high bit is clear. 2751 break; 2752 case ISD::AND: 2753 HighBitSet = true; // We can only transform sra if the high bit is set. 2754 break; 2755 case ISD::ADD: 2756 if (N->getOpcode() != ISD::SHL) 2757 return SDValue(); // only shl(add) not sr[al](add). 2758 HighBitSet = false; // We can only transform sra if the high bit is clear. 2759 break; 2760 } 2761 2762 // We require the RHS of the binop to be a constant as well. 2763 ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1)); 2764 if (!BinOpCst) return SDValue(); 2765 2766 // FIXME: disable this unless the input to the binop is a shift by a constant. 2767 // If it is not a shift, it pessimizes some common cases like: 2768 // 2769 // void foo(int *X, int i) { X[i & 1235] = 1; } 2770 // int bar(int *X, int i) { return X[i & 255]; } 2771 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode(); 2772 if ((BinOpLHSVal->getOpcode() != ISD::SHL && 2773 BinOpLHSVal->getOpcode() != ISD::SRA && 2774 BinOpLHSVal->getOpcode() != ISD::SRL) || 2775 !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1))) 2776 return SDValue(); 2777 2778 EVT VT = N->getValueType(0); 2779 2780 // If this is a signed shift right, and the high bit is modified by the 2781 // logical operation, do not perform the transformation. The highBitSet 2782 // boolean indicates the value of the high bit of the constant which would 2783 // cause it to be modified for this operation. 2784 if (N->getOpcode() == ISD::SRA) { 2785 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative(); 2786 if (BinOpRHSSignSet != HighBitSet) 2787 return SDValue(); 2788 } 2789 2790 // Fold the constants, shifting the binop RHS by the shift amount. 2791 SDValue NewRHS = DAG.getNode(N->getOpcode(), LHS->getOperand(1).getDebugLoc(), 2792 N->getValueType(0), 2793 LHS->getOperand(1), N->getOperand(1)); 2794 2795 // Create the new shift. 2796 SDValue NewShift = DAG.getNode(N->getOpcode(), LHS->getOperand(0).getDebugLoc(), 2797 VT, LHS->getOperand(0), N->getOperand(1)); 2798 2799 // Create the new binop. 2800 return DAG.getNode(LHS->getOpcode(), N->getDebugLoc(), VT, NewShift, NewRHS); 2801 } 2802 2803 SDValue DAGCombiner::visitSHL(SDNode *N) { 2804 SDValue N0 = N->getOperand(0); 2805 SDValue N1 = N->getOperand(1); 2806 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 2807 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 2808 EVT VT = N0.getValueType(); 2809 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits(); 2810 2811 // fold (shl c1, c2) -> c1<<c2 2812 if (N0C && N1C) 2813 return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C); 2814 // fold (shl 0, x) -> 0 2815 if (N0C && N0C->isNullValue()) 2816 return N0; 2817 // fold (shl x, c >= size(x)) -> undef 2818 if (N1C && N1C->getZExtValue() >= OpSizeInBits) 2819 return DAG.getUNDEF(VT); 2820 // fold (shl x, 0) -> x 2821 if (N1C && N1C->isNullValue()) 2822 return N0; 2823 // if (shl x, c) is known to be zero, return 0 2824 if (DAG.MaskedValueIsZero(SDValue(N, 0), 2825 APInt::getAllOnesValue(OpSizeInBits))) 2826 return DAG.getConstant(0, VT); 2827 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))). 2828 if (N1.getOpcode() == ISD::TRUNCATE && 2829 N1.getOperand(0).getOpcode() == ISD::AND && 2830 N1.hasOneUse() && N1.getOperand(0).hasOneUse()) { 2831 SDValue N101 = N1.getOperand(0).getOperand(1); 2832 if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) { 2833 EVT TruncVT = N1.getValueType(); 2834 SDValue N100 = N1.getOperand(0).getOperand(0); 2835 APInt TruncC = N101C->getAPIntValue(); 2836 TruncC.trunc(TruncVT.getSizeInBits()); 2837 return DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, N0, 2838 DAG.getNode(ISD::AND, N->getDebugLoc(), TruncVT, 2839 DAG.getNode(ISD::TRUNCATE, 2840 N->getDebugLoc(), 2841 TruncVT, N100), 2842 DAG.getConstant(TruncC, TruncVT))); 2843 } 2844 } 2845 2846 if (N1C && SimplifyDemandedBits(SDValue(N, 0))) 2847 return SDValue(N, 0); 2848 2849 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2)) 2850 if (N1C && N0.getOpcode() == ISD::SHL && 2851 N0.getOperand(1).getOpcode() == ISD::Constant) { 2852 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue(); 2853 uint64_t c2 = N1C->getZExtValue(); 2854 if (c1 + c2 > OpSizeInBits) 2855 return DAG.getConstant(0, VT); 2856 return DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, N0.getOperand(0), 2857 DAG.getConstant(c1 + c2, N1.getValueType())); 2858 } 2859 // fold (shl (srl x, c1), c2) -> (shl (and x, (shl -1, c1)), (sub c2, c1)) or 2860 // (srl (and x, (shl -1, c1)), (sub c1, c2)) 2861 if (N1C && N0.getOpcode() == ISD::SRL && 2862 N0.getOperand(1).getOpcode() == ISD::Constant) { 2863 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue(); 2864 if (c1 < VT.getSizeInBits()) { 2865 uint64_t c2 = N1C->getZExtValue(); 2866 SDValue HiBitsMask = 2867 DAG.getConstant(APInt::getHighBitsSet(VT.getSizeInBits(), 2868 VT.getSizeInBits() - c1), 2869 VT); 2870 SDValue Mask = DAG.getNode(ISD::AND, N0.getDebugLoc(), VT, 2871 N0.getOperand(0), 2872 HiBitsMask); 2873 if (c2 > c1) 2874 return DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, Mask, 2875 DAG.getConstant(c2-c1, N1.getValueType())); 2876 else 2877 return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, Mask, 2878 DAG.getConstant(c1-c2, N1.getValueType())); 2879 } 2880 } 2881 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1)) 2882 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) { 2883 SDValue HiBitsMask = 2884 DAG.getConstant(APInt::getHighBitsSet(VT.getSizeInBits(), 2885 VT.getSizeInBits() - 2886 N1C->getZExtValue()), 2887 VT); 2888 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0.getOperand(0), 2889 HiBitsMask); 2890 } 2891 2892 if (N1C) { 2893 SDValue NewSHL = visitShiftByConstant(N, N1C->getZExtValue()); 2894 if (NewSHL.getNode()) 2895 return NewSHL; 2896 } 2897 2898 return SDValue(); 2899 } 2900 2901 SDValue DAGCombiner::visitSRA(SDNode *N) { 2902 SDValue N0 = N->getOperand(0); 2903 SDValue N1 = N->getOperand(1); 2904 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 2905 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 2906 EVT VT = N0.getValueType(); 2907 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits(); 2908 2909 // fold (sra c1, c2) -> (sra c1, c2) 2910 if (N0C && N1C) 2911 return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C); 2912 // fold (sra 0, x) -> 0 2913 if (N0C && N0C->isNullValue()) 2914 return N0; 2915 // fold (sra -1, x) -> -1 2916 if (N0C && N0C->isAllOnesValue()) 2917 return N0; 2918 // fold (sra x, (setge c, size(x))) -> undef 2919 if (N1C && N1C->getZExtValue() >= OpSizeInBits) 2920 return DAG.getUNDEF(VT); 2921 // fold (sra x, 0) -> x 2922 if (N1C && N1C->isNullValue()) 2923 return N0; 2924 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports 2925 // sext_inreg. 2926 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) { 2927 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue(); 2928 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits); 2929 if (VT.isVector()) 2930 ExtVT = EVT::getVectorVT(*DAG.getContext(), 2931 ExtVT, VT.getVectorNumElements()); 2932 if ((!LegalOperations || 2933 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT))) 2934 return DAG.getNode(ISD::SIGN_EXTEND_INREG, N->getDebugLoc(), VT, 2935 N0.getOperand(0), DAG.getValueType(ExtVT)); 2936 } 2937 2938 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2)) 2939 if (N1C && N0.getOpcode() == ISD::SRA) { 2940 if (ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 2941 unsigned Sum = N1C->getZExtValue() + C1->getZExtValue(); 2942 if (Sum >= OpSizeInBits) Sum = OpSizeInBits-1; 2943 return DAG.getNode(ISD::SRA, N->getDebugLoc(), VT, N0.getOperand(0), 2944 DAG.getConstant(Sum, N1C->getValueType(0))); 2945 } 2946 } 2947 2948 // fold (sra (shl X, m), (sub result_size, n)) 2949 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for 2950 // result_size - n != m. 2951 // If truncate is free for the target sext(shl) is likely to result in better 2952 // code. 2953 if (N0.getOpcode() == ISD::SHL) { 2954 // Get the two constanst of the shifts, CN0 = m, CN = n. 2955 const ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 2956 if (N01C && N1C) { 2957 // Determine what the truncate's result bitsize and type would be. 2958 EVT TruncVT = 2959 EVT::getIntegerVT(*DAG.getContext(), OpSizeInBits - N1C->getZExtValue()); 2960 // Determine the residual right-shift amount. 2961 signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue(); 2962 2963 // If the shift is not a no-op (in which case this should be just a sign 2964 // extend already), the truncated to type is legal, sign_extend is legal 2965 // on that type, and the truncate to that type is both legal and free, 2966 // perform the transform. 2967 if ((ShiftAmt > 0) && 2968 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) && 2969 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) && 2970 TLI.isTruncateFree(VT, TruncVT)) { 2971 2972 SDValue Amt = DAG.getConstant(ShiftAmt, getShiftAmountTy()); 2973 SDValue Shift = DAG.getNode(ISD::SRL, N0.getDebugLoc(), VT, 2974 N0.getOperand(0), Amt); 2975 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(), TruncVT, 2976 Shift); 2977 return DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), 2978 N->getValueType(0), Trunc); 2979 } 2980 } 2981 } 2982 2983 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))). 2984 if (N1.getOpcode() == ISD::TRUNCATE && 2985 N1.getOperand(0).getOpcode() == ISD::AND && 2986 N1.hasOneUse() && N1.getOperand(0).hasOneUse()) { 2987 SDValue N101 = N1.getOperand(0).getOperand(1); 2988 if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) { 2989 EVT TruncVT = N1.getValueType(); 2990 SDValue N100 = N1.getOperand(0).getOperand(0); 2991 APInt TruncC = N101C->getAPIntValue(); 2992 TruncC.trunc(TruncVT.getScalarType().getSizeInBits()); 2993 return DAG.getNode(ISD::SRA, N->getDebugLoc(), VT, N0, 2994 DAG.getNode(ISD::AND, N->getDebugLoc(), 2995 TruncVT, 2996 DAG.getNode(ISD::TRUNCATE, 2997 N->getDebugLoc(), 2998 TruncVT, N100), 2999 DAG.getConstant(TruncC, TruncVT))); 3000 } 3001 } 3002 3003 // Simplify, based on bits shifted out of the LHS. 3004 if (N1C && SimplifyDemandedBits(SDValue(N, 0))) 3005 return SDValue(N, 0); 3006 3007 3008 // If the sign bit is known to be zero, switch this to a SRL. 3009 if (DAG.SignBitIsZero(N0)) 3010 return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0, N1); 3011 3012 if (N1C) { 3013 SDValue NewSRA = visitShiftByConstant(N, N1C->getZExtValue()); 3014 if (NewSRA.getNode()) 3015 return NewSRA; 3016 } 3017 3018 return SDValue(); 3019 } 3020 3021 SDValue DAGCombiner::visitSRL(SDNode *N) { 3022 SDValue N0 = N->getOperand(0); 3023 SDValue N1 = N->getOperand(1); 3024 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 3025 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 3026 EVT VT = N0.getValueType(); 3027 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits(); 3028 3029 // fold (srl c1, c2) -> c1 >>u c2 3030 if (N0C && N1C) 3031 return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C); 3032 // fold (srl 0, x) -> 0 3033 if (N0C && N0C->isNullValue()) 3034 return N0; 3035 // fold (srl x, c >= size(x)) -> undef 3036 if (N1C && N1C->getZExtValue() >= OpSizeInBits) 3037 return DAG.getUNDEF(VT); 3038 // fold (srl x, 0) -> x 3039 if (N1C && N1C->isNullValue()) 3040 return N0; 3041 // if (srl x, c) is known to be zero, return 0 3042 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0), 3043 APInt::getAllOnesValue(OpSizeInBits))) 3044 return DAG.getConstant(0, VT); 3045 3046 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2)) 3047 if (N1C && N0.getOpcode() == ISD::SRL && 3048 N0.getOperand(1).getOpcode() == ISD::Constant) { 3049 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue(); 3050 uint64_t c2 = N1C->getZExtValue(); 3051 if (c1 + c2 > OpSizeInBits) 3052 return DAG.getConstant(0, VT); 3053 return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0.getOperand(0), 3054 DAG.getConstant(c1 + c2, N1.getValueType())); 3055 } 3056 3057 // fold (srl (shl x, c), c) -> (and x, cst2) 3058 if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1 && 3059 N0.getValueSizeInBits() <= 64) { 3060 uint64_t ShAmt = N1C->getZExtValue()+64-N0.getValueSizeInBits(); 3061 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0.getOperand(0), 3062 DAG.getConstant(~0ULL >> ShAmt, VT)); 3063 } 3064 3065 3066 // fold (srl (anyextend x), c) -> (anyextend (srl x, c)) 3067 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) { 3068 // Shifting in all undef bits? 3069 EVT SmallVT = N0.getOperand(0).getValueType(); 3070 if (N1C->getZExtValue() >= SmallVT.getSizeInBits()) 3071 return DAG.getUNDEF(VT); 3072 3073 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) { 3074 SDValue SmallShift = DAG.getNode(ISD::SRL, N0.getDebugLoc(), SmallVT, 3075 N0.getOperand(0), N1); 3076 AddToWorkList(SmallShift.getNode()); 3077 return DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, SmallShift); 3078 } 3079 } 3080 3081 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign 3082 // bit, which is unmodified by sra. 3083 if (N1C && N1C->getZExtValue() + 1 == VT.getSizeInBits()) { 3084 if (N0.getOpcode() == ISD::SRA) 3085 return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0.getOperand(0), N1); 3086 } 3087 3088 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit). 3089 if (N1C && N0.getOpcode() == ISD::CTLZ && 3090 N1C->getAPIntValue() == Log2_32(VT.getSizeInBits())) { 3091 APInt KnownZero, KnownOne; 3092 APInt Mask = APInt::getAllOnesValue(VT.getScalarType().getSizeInBits()); 3093 DAG.ComputeMaskedBits(N0.getOperand(0), Mask, KnownZero, KnownOne); 3094 3095 // If any of the input bits are KnownOne, then the input couldn't be all 3096 // zeros, thus the result of the srl will always be zero. 3097 if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT); 3098 3099 // If all of the bits input the to ctlz node are known to be zero, then 3100 // the result of the ctlz is "32" and the result of the shift is one. 3101 APInt UnknownBits = ~KnownZero & Mask; 3102 if (UnknownBits == 0) return DAG.getConstant(1, VT); 3103 3104 // Otherwise, check to see if there is exactly one bit input to the ctlz. 3105 if ((UnknownBits & (UnknownBits - 1)) == 0) { 3106 // Okay, we know that only that the single bit specified by UnknownBits 3107 // could be set on input to the CTLZ node. If this bit is set, the SRL 3108 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair 3109 // to an SRL/XOR pair, which is likely to simplify more. 3110 unsigned ShAmt = UnknownBits.countTrailingZeros(); 3111 SDValue Op = N0.getOperand(0); 3112 3113 if (ShAmt) { 3114 Op = DAG.getNode(ISD::SRL, N0.getDebugLoc(), VT, Op, 3115 DAG.getConstant(ShAmt, getShiftAmountTy())); 3116 AddToWorkList(Op.getNode()); 3117 } 3118 3119 return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT, 3120 Op, DAG.getConstant(1, VT)); 3121 } 3122 } 3123 3124 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))). 3125 if (N1.getOpcode() == ISD::TRUNCATE && 3126 N1.getOperand(0).getOpcode() == ISD::AND && 3127 N1.hasOneUse() && N1.getOperand(0).hasOneUse()) { 3128 SDValue N101 = N1.getOperand(0).getOperand(1); 3129 if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) { 3130 EVT TruncVT = N1.getValueType(); 3131 SDValue N100 = N1.getOperand(0).getOperand(0); 3132 APInt TruncC = N101C->getAPIntValue(); 3133 TruncC.trunc(TruncVT.getSizeInBits()); 3134 return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0, 3135 DAG.getNode(ISD::AND, N->getDebugLoc(), 3136 TruncVT, 3137 DAG.getNode(ISD::TRUNCATE, 3138 N->getDebugLoc(), 3139 TruncVT, N100), 3140 DAG.getConstant(TruncC, TruncVT))); 3141 } 3142 } 3143 3144 // fold operands of srl based on knowledge that the low bits are not 3145 // demanded. 3146 if (N1C && SimplifyDemandedBits(SDValue(N, 0))) 3147 return SDValue(N, 0); 3148 3149 if (N1C) { 3150 SDValue NewSRL = visitShiftByConstant(N, N1C->getZExtValue()); 3151 if (NewSRL.getNode()) 3152 return NewSRL; 3153 } 3154 3155 // Here is a common situation. We want to optimize: 3156 // 3157 // %a = ... 3158 // %b = and i32 %a, 2 3159 // %c = srl i32 %b, 1 3160 // brcond i32 %c ... 3161 // 3162 // into 3163 // 3164 // %a = ... 3165 // %b = and %a, 2 3166 // %c = setcc eq %b, 0 3167 // brcond %c ... 3168 // 3169 // However when after the source operand of SRL is optimized into AND, the SRL 3170 // itself may not be optimized further. Look for it and add the BRCOND into 3171 // the worklist. 3172 if (N->hasOneUse()) { 3173 SDNode *Use = *N->use_begin(); 3174 if (Use->getOpcode() == ISD::BRCOND) 3175 AddToWorkList(Use); 3176 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) { 3177 // Also look pass the truncate. 3178 Use = *Use->use_begin(); 3179 if (Use->getOpcode() == ISD::BRCOND) 3180 AddToWorkList(Use); 3181 } 3182 } 3183 3184 return SDValue(); 3185 } 3186 3187 SDValue DAGCombiner::visitCTLZ(SDNode *N) { 3188 SDValue N0 = N->getOperand(0); 3189 EVT VT = N->getValueType(0); 3190 3191 // fold (ctlz c1) -> c2 3192 if (isa<ConstantSDNode>(N0)) 3193 return DAG.getNode(ISD::CTLZ, N->getDebugLoc(), VT, N0); 3194 return SDValue(); 3195 } 3196 3197 SDValue DAGCombiner::visitCTTZ(SDNode *N) { 3198 SDValue N0 = N->getOperand(0); 3199 EVT VT = N->getValueType(0); 3200 3201 // fold (cttz c1) -> c2 3202 if (isa<ConstantSDNode>(N0)) 3203 return DAG.getNode(ISD::CTTZ, N->getDebugLoc(), VT, N0); 3204 return SDValue(); 3205 } 3206 3207 SDValue DAGCombiner::visitCTPOP(SDNode *N) { 3208 SDValue N0 = N->getOperand(0); 3209 EVT VT = N->getValueType(0); 3210 3211 // fold (ctpop c1) -> c2 3212 if (isa<ConstantSDNode>(N0)) 3213 return DAG.getNode(ISD::CTPOP, N->getDebugLoc(), VT, N0); 3214 return SDValue(); 3215 } 3216 3217 SDValue DAGCombiner::visitSELECT(SDNode *N) { 3218 SDValue N0 = N->getOperand(0); 3219 SDValue N1 = N->getOperand(1); 3220 SDValue N2 = N->getOperand(2); 3221 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 3222 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 3223 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2); 3224 EVT VT = N->getValueType(0); 3225 EVT VT0 = N0.getValueType(); 3226 3227 // fold (select C, X, X) -> X 3228 if (N1 == N2) 3229 return N1; 3230 // fold (select true, X, Y) -> X 3231 if (N0C && !N0C->isNullValue()) 3232 return N1; 3233 // fold (select false, X, Y) -> Y 3234 if (N0C && N0C->isNullValue()) 3235 return N2; 3236 // fold (select C, 1, X) -> (or C, X) 3237 if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1) 3238 return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, N0, N2); 3239 // fold (select C, 0, 1) -> (xor C, 1) 3240 if (VT.isInteger() && 3241 (VT0 == MVT::i1 || 3242 (VT0.isInteger() && 3243 TLI.getBooleanContents() == TargetLowering::ZeroOrOneBooleanContent)) && 3244 N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) { 3245 SDValue XORNode; 3246 if (VT == VT0) 3247 return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT0, 3248 N0, DAG.getConstant(1, VT0)); 3249 XORNode = DAG.getNode(ISD::XOR, N0.getDebugLoc(), VT0, 3250 N0, DAG.getConstant(1, VT0)); 3251 AddToWorkList(XORNode.getNode()); 3252 if (VT.bitsGT(VT0)) 3253 return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT, XORNode); 3254 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, XORNode); 3255 } 3256 // fold (select C, 0, X) -> (and (not C), X) 3257 if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) { 3258 SDValue NOTNode = DAG.getNOT(N0.getDebugLoc(), N0, VT); 3259 AddToWorkList(NOTNode.getNode()); 3260 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, NOTNode, N2); 3261 } 3262 // fold (select C, X, 1) -> (or (not C), X) 3263 if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) { 3264 SDValue NOTNode = DAG.getNOT(N0.getDebugLoc(), N0, VT); 3265 AddToWorkList(NOTNode.getNode()); 3266 return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, NOTNode, N1); 3267 } 3268 // fold (select C, X, 0) -> (and C, X) 3269 if (VT == MVT::i1 && N2C && N2C->isNullValue()) 3270 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0, N1); 3271 // fold (select X, X, Y) -> (or X, Y) 3272 // fold (select X, 1, Y) -> (or X, Y) 3273 if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1))) 3274 return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, N0, N2); 3275 // fold (select X, Y, X) -> (and X, Y) 3276 // fold (select X, Y, 0) -> (and X, Y) 3277 if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0))) 3278 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0, N1); 3279 3280 // If we can fold this based on the true/false value, do so. 3281 if (SimplifySelectOps(N, N1, N2)) 3282 return SDValue(N, 0); // Don't revisit N. 3283 3284 // fold selects based on a setcc into other things, such as min/max/abs 3285 if (N0.getOpcode() == ISD::SETCC) { 3286 // FIXME: 3287 // Check against MVT::Other for SELECT_CC, which is a workaround for targets 3288 // having to say they don't support SELECT_CC on every type the DAG knows 3289 // about, since there is no way to mark an opcode illegal at all value types 3290 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other) && 3291 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) 3292 return DAG.getNode(ISD::SELECT_CC, N->getDebugLoc(), VT, 3293 N0.getOperand(0), N0.getOperand(1), 3294 N1, N2, N0.getOperand(2)); 3295 return SimplifySelect(N->getDebugLoc(), N0, N1, N2); 3296 } 3297 3298 return SDValue(); 3299 } 3300 3301 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) { 3302 SDValue N0 = N->getOperand(0); 3303 SDValue N1 = N->getOperand(1); 3304 SDValue N2 = N->getOperand(2); 3305 SDValue N3 = N->getOperand(3); 3306 SDValue N4 = N->getOperand(4); 3307 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get(); 3308 3309 // fold select_cc lhs, rhs, x, x, cc -> x 3310 if (N2 == N3) 3311 return N2; 3312 3313 // Determine if the condition we're dealing with is constant 3314 SDValue SCC = SimplifySetCC(TLI.getSetCCResultType(N0.getValueType()), 3315 N0, N1, CC, N->getDebugLoc(), false); 3316 if (SCC.getNode()) AddToWorkList(SCC.getNode()); 3317 3318 if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode())) { 3319 if (!SCCC->isNullValue()) 3320 return N2; // cond always true -> true val 3321 else 3322 return N3; // cond always false -> false val 3323 } 3324 3325 // Fold to a simpler select_cc 3326 if (SCC.getNode() && SCC.getOpcode() == ISD::SETCC) 3327 return DAG.getNode(ISD::SELECT_CC, N->getDebugLoc(), N2.getValueType(), 3328 SCC.getOperand(0), SCC.getOperand(1), N2, N3, 3329 SCC.getOperand(2)); 3330 3331 // If we can fold this based on the true/false value, do so. 3332 if (SimplifySelectOps(N, N2, N3)) 3333 return SDValue(N, 0); // Don't revisit N. 3334 3335 // fold select_cc into other things, such as min/max/abs 3336 return SimplifySelectCC(N->getDebugLoc(), N0, N1, N2, N3, CC); 3337 } 3338 3339 SDValue DAGCombiner::visitSETCC(SDNode *N) { 3340 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1), 3341 cast<CondCodeSDNode>(N->getOperand(2))->get(), 3342 N->getDebugLoc()); 3343 } 3344 3345 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this: 3346 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))" 3347 // transformation. Returns true if extension are possible and the above 3348 // mentioned transformation is profitable. 3349 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0, 3350 unsigned ExtOpc, 3351 SmallVector<SDNode*, 4> &ExtendNodes, 3352 const TargetLowering &TLI) { 3353 bool HasCopyToRegUses = false; 3354 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType()); 3355 for (SDNode::use_iterator UI = N0.getNode()->use_begin(), 3356 UE = N0.getNode()->use_end(); 3357 UI != UE; ++UI) { 3358 SDNode *User = *UI; 3359 if (User == N) 3360 continue; 3361 if (UI.getUse().getResNo() != N0.getResNo()) 3362 continue; 3363 // FIXME: Only extend SETCC N, N and SETCC N, c for now. 3364 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) { 3365 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get(); 3366 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC)) 3367 // Sign bits will be lost after a zext. 3368 return false; 3369 bool Add = false; 3370 for (unsigned i = 0; i != 2; ++i) { 3371 SDValue UseOp = User->getOperand(i); 3372 if (UseOp == N0) 3373 continue; 3374 if (!isa<ConstantSDNode>(UseOp)) 3375 return false; 3376 Add = true; 3377 } 3378 if (Add) 3379 ExtendNodes.push_back(User); 3380 continue; 3381 } 3382 // If truncates aren't free and there are users we can't 3383 // extend, it isn't worthwhile. 3384 if (!isTruncFree) 3385 return false; 3386 // Remember if this value is live-out. 3387 if (User->getOpcode() == ISD::CopyToReg) 3388 HasCopyToRegUses = true; 3389 } 3390 3391 if (HasCopyToRegUses) { 3392 bool BothLiveOut = false; 3393 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end(); 3394 UI != UE; ++UI) { 3395 SDUse &Use = UI.getUse(); 3396 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) { 3397 BothLiveOut = true; 3398 break; 3399 } 3400 } 3401 if (BothLiveOut) 3402 // Both unextended and extended values are live out. There had better be 3403 // good a reason for the transformation. 3404 return ExtendNodes.size(); 3405 } 3406 return true; 3407 } 3408 3409 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) { 3410 SDValue N0 = N->getOperand(0); 3411 EVT VT = N->getValueType(0); 3412 3413 // fold (sext c1) -> c1 3414 if (isa<ConstantSDNode>(N0)) 3415 return DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), VT, N0); 3416 3417 // fold (sext (sext x)) -> (sext x) 3418 // fold (sext (aext x)) -> (sext x) 3419 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) 3420 return DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), VT, 3421 N0.getOperand(0)); 3422 3423 if (N0.getOpcode() == ISD::TRUNCATE) { 3424 // fold (sext (truncate (load x))) -> (sext (smaller load x)) 3425 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n))) 3426 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode()); 3427 if (NarrowLoad.getNode()) { 3428 if (NarrowLoad.getNode() != N0.getNode()) 3429 CombineTo(N0.getNode(), NarrowLoad); 3430 return SDValue(N, 0); // Return N so it doesn't get rechecked! 3431 } 3432 3433 // See if the value being truncated is already sign extended. If so, just 3434 // eliminate the trunc/sext pair. 3435 SDValue Op = N0.getOperand(0); 3436 unsigned OpBits = Op.getValueType().getScalarType().getSizeInBits(); 3437 unsigned MidBits = N0.getValueType().getScalarType().getSizeInBits(); 3438 unsigned DestBits = VT.getScalarType().getSizeInBits(); 3439 unsigned NumSignBits = DAG.ComputeNumSignBits(Op); 3440 3441 if (OpBits == DestBits) { 3442 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign 3443 // bits, it is already ready. 3444 if (NumSignBits > DestBits-MidBits) 3445 return Op; 3446 } else if (OpBits < DestBits) { 3447 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign 3448 // bits, just sext from i32. 3449 if (NumSignBits > OpBits-MidBits) 3450 return DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), VT, Op); 3451 } else { 3452 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign 3453 // bits, just truncate to i32. 3454 if (NumSignBits > OpBits-MidBits) 3455 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, Op); 3456 } 3457 3458 // fold (sext (truncate x)) -> (sextinreg x). 3459 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, 3460 N0.getValueType())) { 3461 if (OpBits < DestBits) 3462 Op = DAG.getNode(ISD::ANY_EXTEND, N0.getDebugLoc(), VT, Op); 3463 else if (OpBits > DestBits) 3464 Op = DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(), VT, Op); 3465 return DAG.getNode(ISD::SIGN_EXTEND_INREG, N->getDebugLoc(), VT, Op, 3466 DAG.getValueType(N0.getValueType())); 3467 } 3468 } 3469 3470 // fold (sext (load x)) -> (sext (truncate (sextload x))) 3471 if (ISD::isNON_EXTLoad(N0.getNode()) && 3472 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) || 3473 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()))) { 3474 bool DoXform = true; 3475 SmallVector<SDNode*, 4> SetCCs; 3476 if (!N0.hasOneUse()) 3477 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI); 3478 if (DoXform) { 3479 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 3480 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, N->getDebugLoc(), VT, 3481 LN0->getChain(), 3482 LN0->getBasePtr(), LN0->getSrcValue(), 3483 LN0->getSrcValueOffset(), 3484 N0.getValueType(), 3485 LN0->isVolatile(), LN0->isNonTemporal(), 3486 LN0->getAlignment()); 3487 CombineTo(N, ExtLoad); 3488 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(), 3489 N0.getValueType(), ExtLoad); 3490 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1)); 3491 3492 // Extend SetCC uses if necessary. 3493 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) { 3494 SDNode *SetCC = SetCCs[i]; 3495 SmallVector<SDValue, 4> Ops; 3496 3497 for (unsigned j = 0; j != 2; ++j) { 3498 SDValue SOp = SetCC->getOperand(j); 3499 if (SOp == Trunc) 3500 Ops.push_back(ExtLoad); 3501 else 3502 Ops.push_back(DAG.getNode(ISD::SIGN_EXTEND, 3503 N->getDebugLoc(), VT, SOp)); 3504 } 3505 3506 Ops.push_back(SetCC->getOperand(2)); 3507 CombineTo(SetCC, DAG.getNode(ISD::SETCC, N->getDebugLoc(), 3508 SetCC->getValueType(0), 3509 &Ops[0], Ops.size())); 3510 } 3511 3512 return SDValue(N, 0); // Return N so it doesn't get rechecked! 3513 } 3514 } 3515 3516 // fold (sext (sextload x)) -> (sext (truncate (sextload x))) 3517 // fold (sext ( extload x)) -> (sext (truncate (sextload x))) 3518 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) && 3519 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) { 3520 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 3521 EVT MemVT = LN0->getMemoryVT(); 3522 if ((!LegalOperations && !LN0->isVolatile()) || 3523 TLI.isLoadExtLegal(ISD::SEXTLOAD, MemVT)) { 3524 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, N->getDebugLoc(), VT, 3525 LN0->getChain(), 3526 LN0->getBasePtr(), LN0->getSrcValue(), 3527 LN0->getSrcValueOffset(), MemVT, 3528 LN0->isVolatile(), LN0->isNonTemporal(), 3529 LN0->getAlignment()); 3530 CombineTo(N, ExtLoad); 3531 CombineTo(N0.getNode(), 3532 DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(), 3533 N0.getValueType(), ExtLoad), 3534 ExtLoad.getValue(1)); 3535 return SDValue(N, 0); // Return N so it doesn't get rechecked! 3536 } 3537 } 3538 3539 if (N0.getOpcode() == ISD::SETCC) { 3540 // sext(setcc) -> sext_in_reg(vsetcc) for vectors. 3541 // Only do this before legalize for now. 3542 if (VT.isVector() && !LegalOperations) { 3543 EVT N0VT = N0.getOperand(0).getValueType(); 3544 // We know that the # elements of the results is the same as the 3545 // # elements of the compare (and the # elements of the compare result 3546 // for that matter). Check to see that they are the same size. If so, 3547 // we know that the element size of the sext'd result matches the 3548 // element size of the compare operands. 3549 if (VT.getSizeInBits() == N0VT.getSizeInBits()) 3550 return DAG.getVSetCC(N->getDebugLoc(), VT, N0.getOperand(0), 3551 N0.getOperand(1), 3552 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 3553 // If the desired elements are smaller or larger than the source 3554 // elements we can use a matching integer vector type and then 3555 // truncate/sign extend 3556 else { 3557 EVT MatchingElementType = 3558 EVT::getIntegerVT(*DAG.getContext(), 3559 N0VT.getScalarType().getSizeInBits()); 3560 EVT MatchingVectorType = 3561 EVT::getVectorVT(*DAG.getContext(), MatchingElementType, 3562 N0VT.getVectorNumElements()); 3563 SDValue VsetCC = 3564 DAG.getVSetCC(N->getDebugLoc(), MatchingVectorType, N0.getOperand(0), 3565 N0.getOperand(1), 3566 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 3567 return DAG.getSExtOrTrunc(VsetCC, N->getDebugLoc(), VT); 3568 } 3569 } 3570 3571 // sext(setcc x, y, cc) -> (select_cc x, y, -1, 0, cc) 3572 unsigned ElementWidth = VT.getScalarType().getSizeInBits(); 3573 SDValue NegOne = 3574 DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT); 3575 SDValue SCC = 3576 SimplifySelectCC(N->getDebugLoc(), N0.getOperand(0), N0.getOperand(1), 3577 NegOne, DAG.getConstant(0, VT), 3578 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true); 3579 if (SCC.getNode()) return SCC; 3580 if (!LegalOperations || 3581 TLI.isOperationLegal(ISD::SETCC, TLI.getSetCCResultType(VT))) 3582 return DAG.getNode(ISD::SELECT, N->getDebugLoc(), VT, 3583 DAG.getSetCC(N->getDebugLoc(), 3584 TLI.getSetCCResultType(VT), 3585 N0.getOperand(0), N0.getOperand(1), 3586 cast<CondCodeSDNode>(N0.getOperand(2))->get()), 3587 NegOne, DAG.getConstant(0, VT)); 3588 } 3589 3590 3591 3592 // fold (sext x) -> (zext x) if the sign bit is known zero. 3593 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) && 3594 DAG.SignBitIsZero(N0)) 3595 return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT, N0); 3596 3597 return SDValue(); 3598 } 3599 3600 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) { 3601 SDValue N0 = N->getOperand(0); 3602 EVT VT = N->getValueType(0); 3603 3604 // fold (zext c1) -> c1 3605 if (isa<ConstantSDNode>(N0)) 3606 return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT, N0); 3607 // fold (zext (zext x)) -> (zext x) 3608 // fold (zext (aext x)) -> (zext x) 3609 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) 3610 return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT, 3611 N0.getOperand(0)); 3612 3613 // fold (zext (truncate (load x))) -> (zext (smaller load x)) 3614 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n))) 3615 if (N0.getOpcode() == ISD::TRUNCATE) { 3616 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode()); 3617 if (NarrowLoad.getNode()) { 3618 if (NarrowLoad.getNode() != N0.getNode()) 3619 CombineTo(N0.getNode(), NarrowLoad); 3620 return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT, NarrowLoad); 3621 } 3622 } 3623 3624 // fold (zext (truncate x)) -> (and x, mask) 3625 if (N0.getOpcode() == ISD::TRUNCATE && 3626 (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT)) && 3627 (!TLI.isTruncateFree(N0.getOperand(0).getValueType(), 3628 N0.getValueType()) || 3629 !TLI.isZExtFree(N0.getValueType(), VT))) { 3630 SDValue Op = N0.getOperand(0); 3631 if (Op.getValueType().bitsLT(VT)) { 3632 Op = DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, Op); 3633 } else if (Op.getValueType().bitsGT(VT)) { 3634 Op = DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, Op); 3635 } 3636 return DAG.getZeroExtendInReg(Op, N->getDebugLoc(), 3637 N0.getValueType().getScalarType()); 3638 } 3639 3640 // Fold (zext (and (trunc x), cst)) -> (and x, cst), 3641 // if either of the casts is not free. 3642 if (N0.getOpcode() == ISD::AND && 3643 N0.getOperand(0).getOpcode() == ISD::TRUNCATE && 3644 N0.getOperand(1).getOpcode() == ISD::Constant && 3645 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(), 3646 N0.getValueType()) || 3647 !TLI.isZExtFree(N0.getValueType(), VT))) { 3648 SDValue X = N0.getOperand(0).getOperand(0); 3649 if (X.getValueType().bitsLT(VT)) { 3650 X = DAG.getNode(ISD::ANY_EXTEND, X.getDebugLoc(), VT, X); 3651 } else if (X.getValueType().bitsGT(VT)) { 3652 X = DAG.getNode(ISD::TRUNCATE, X.getDebugLoc(), VT, X); 3653 } 3654 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 3655 Mask.zext(VT.getSizeInBits()); 3656 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, 3657 X, DAG.getConstant(Mask, VT)); 3658 } 3659 3660 // fold (zext (load x)) -> (zext (truncate (zextload x))) 3661 if (ISD::isNON_EXTLoad(N0.getNode()) && 3662 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) || 3663 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()))) { 3664 bool DoXform = true; 3665 SmallVector<SDNode*, 4> SetCCs; 3666 if (!N0.hasOneUse()) 3667 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI); 3668 if (DoXform) { 3669 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 3670 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, N->getDebugLoc(), VT, 3671 LN0->getChain(), 3672 LN0->getBasePtr(), LN0->getSrcValue(), 3673 LN0->getSrcValueOffset(), 3674 N0.getValueType(), 3675 LN0->isVolatile(), LN0->isNonTemporal(), 3676 LN0->getAlignment()); 3677 CombineTo(N, ExtLoad); 3678 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(), 3679 N0.getValueType(), ExtLoad); 3680 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1)); 3681 3682 // Extend SetCC uses if necessary. 3683 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) { 3684 SDNode *SetCC = SetCCs[i]; 3685 SmallVector<SDValue, 4> Ops; 3686 3687 for (unsigned j = 0; j != 2; ++j) { 3688 SDValue SOp = SetCC->getOperand(j); 3689 if (SOp == Trunc) 3690 Ops.push_back(ExtLoad); 3691 else 3692 Ops.push_back(DAG.getNode(ISD::ZERO_EXTEND, 3693 N->getDebugLoc(), VT, SOp)); 3694 } 3695 3696 Ops.push_back(SetCC->getOperand(2)); 3697 CombineTo(SetCC, DAG.getNode(ISD::SETCC, N->getDebugLoc(), 3698 SetCC->getValueType(0), 3699 &Ops[0], Ops.size())); 3700 } 3701 3702 return SDValue(N, 0); // Return N so it doesn't get rechecked! 3703 } 3704 } 3705 3706 // fold (zext (zextload x)) -> (zext (truncate (zextload x))) 3707 // fold (zext ( extload x)) -> (zext (truncate (zextload x))) 3708 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) && 3709 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) { 3710 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 3711 EVT MemVT = LN0->getMemoryVT(); 3712 if ((!LegalOperations && !LN0->isVolatile()) || 3713 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT)) { 3714 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, N->getDebugLoc(), VT, 3715 LN0->getChain(), 3716 LN0->getBasePtr(), LN0->getSrcValue(), 3717 LN0->getSrcValueOffset(), MemVT, 3718 LN0->isVolatile(), LN0->isNonTemporal(), 3719 LN0->getAlignment()); 3720 CombineTo(N, ExtLoad); 3721 CombineTo(N0.getNode(), 3722 DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(), N0.getValueType(), 3723 ExtLoad), 3724 ExtLoad.getValue(1)); 3725 return SDValue(N, 0); // Return N so it doesn't get rechecked! 3726 } 3727 } 3728 3729 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc 3730 if (N0.getOpcode() == ISD::SETCC) { 3731 SDValue SCC = 3732 SimplifySelectCC(N->getDebugLoc(), N0.getOperand(0), N0.getOperand(1), 3733 DAG.getConstant(1, VT), DAG.getConstant(0, VT), 3734 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true); 3735 if (SCC.getNode()) return SCC; 3736 } 3737 3738 // (zext (shl (zext x), cst)) -> (shl (zext x), cst) 3739 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) && 3740 isa<ConstantSDNode>(N0.getOperand(1)) && 3741 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND && 3742 N0.hasOneUse()) { 3743 if (N0.getOpcode() == ISD::SHL) { 3744 // If the original shl may be shifting out bits, do not perform this 3745 // transformation. 3746 unsigned ShAmt = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue(); 3747 unsigned KnownZeroBits = N0.getOperand(0).getValueType().getSizeInBits() - 3748 N0.getOperand(0).getOperand(0).getValueType().getSizeInBits(); 3749 if (ShAmt > KnownZeroBits) 3750 return SDValue(); 3751 } 3752 DebugLoc dl = N->getDebugLoc(); 3753 return DAG.getNode(N0.getOpcode(), dl, VT, 3754 DAG.getNode(ISD::ZERO_EXTEND, dl, VT, N0.getOperand(0)), 3755 DAG.getNode(ISD::ZERO_EXTEND, dl, 3756 N0.getOperand(1).getValueType(), 3757 N0.getOperand(1))); 3758 } 3759 3760 return SDValue(); 3761 } 3762 3763 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) { 3764 SDValue N0 = N->getOperand(0); 3765 EVT VT = N->getValueType(0); 3766 3767 // fold (aext c1) -> c1 3768 if (isa<ConstantSDNode>(N0)) 3769 return DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, N0); 3770 // fold (aext (aext x)) -> (aext x) 3771 // fold (aext (zext x)) -> (zext x) 3772 // fold (aext (sext x)) -> (sext x) 3773 if (N0.getOpcode() == ISD::ANY_EXTEND || 3774 N0.getOpcode() == ISD::ZERO_EXTEND || 3775 N0.getOpcode() == ISD::SIGN_EXTEND) 3776 return DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT, N0.getOperand(0)); 3777 3778 // fold (aext (truncate (load x))) -> (aext (smaller load x)) 3779 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n))) 3780 if (N0.getOpcode() == ISD::TRUNCATE) { 3781 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode()); 3782 if (NarrowLoad.getNode()) { 3783 if (NarrowLoad.getNode() != N0.getNode()) 3784 CombineTo(N0.getNode(), NarrowLoad); 3785 return DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, NarrowLoad); 3786 } 3787 } 3788 3789 // fold (aext (truncate x)) 3790 if (N0.getOpcode() == ISD::TRUNCATE) { 3791 SDValue TruncOp = N0.getOperand(0); 3792 if (TruncOp.getValueType() == VT) 3793 return TruncOp; // x iff x size == zext size. 3794 if (TruncOp.getValueType().bitsGT(VT)) 3795 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, TruncOp); 3796 return DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, TruncOp); 3797 } 3798 3799 // Fold (aext (and (trunc x), cst)) -> (and x, cst) 3800 // if the trunc is not free. 3801 if (N0.getOpcode() == ISD::AND && 3802 N0.getOperand(0).getOpcode() == ISD::TRUNCATE && 3803 N0.getOperand(1).getOpcode() == ISD::Constant && 3804 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(), 3805 N0.getValueType())) { 3806 SDValue X = N0.getOperand(0).getOperand(0); 3807 if (X.getValueType().bitsLT(VT)) { 3808 X = DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, X); 3809 } else if (X.getValueType().bitsGT(VT)) { 3810 X = DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, X); 3811 } 3812 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 3813 Mask.zext(VT.getSizeInBits()); 3814 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, 3815 X, DAG.getConstant(Mask, VT)); 3816 } 3817 3818 // fold (aext (load x)) -> (aext (truncate (extload x))) 3819 if (ISD::isNON_EXTLoad(N0.getNode()) && 3820 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) || 3821 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) { 3822 bool DoXform = true; 3823 SmallVector<SDNode*, 4> SetCCs; 3824 if (!N0.hasOneUse()) 3825 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI); 3826 if (DoXform) { 3827 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 3828 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, N->getDebugLoc(), VT, 3829 LN0->getChain(), 3830 LN0->getBasePtr(), LN0->getSrcValue(), 3831 LN0->getSrcValueOffset(), 3832 N0.getValueType(), 3833 LN0->isVolatile(), LN0->isNonTemporal(), 3834 LN0->getAlignment()); 3835 CombineTo(N, ExtLoad); 3836 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(), 3837 N0.getValueType(), ExtLoad); 3838 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1)); 3839 3840 // Extend SetCC uses if necessary. 3841 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) { 3842 SDNode *SetCC = SetCCs[i]; 3843 SmallVector<SDValue, 4> Ops; 3844 3845 for (unsigned j = 0; j != 2; ++j) { 3846 SDValue SOp = SetCC->getOperand(j); 3847 if (SOp == Trunc) 3848 Ops.push_back(ExtLoad); 3849 else 3850 Ops.push_back(DAG.getNode(ISD::ANY_EXTEND, 3851 N->getDebugLoc(), VT, SOp)); 3852 } 3853 3854 Ops.push_back(SetCC->getOperand(2)); 3855 CombineTo(SetCC, DAG.getNode(ISD::SETCC, N->getDebugLoc(), 3856 SetCC->getValueType(0), 3857 &Ops[0], Ops.size())); 3858 } 3859 3860 return SDValue(N, 0); // Return N so it doesn't get rechecked! 3861 } 3862 } 3863 3864 // fold (aext (zextload x)) -> (aext (truncate (zextload x))) 3865 // fold (aext (sextload x)) -> (aext (truncate (sextload x))) 3866 // fold (aext ( extload x)) -> (aext (truncate (extload x))) 3867 if (N0.getOpcode() == ISD::LOAD && 3868 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 3869 N0.hasOneUse()) { 3870 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 3871 EVT MemVT = LN0->getMemoryVT(); 3872 SDValue ExtLoad = DAG.getExtLoad(LN0->getExtensionType(), N->getDebugLoc(), 3873 VT, LN0->getChain(), LN0->getBasePtr(), 3874 LN0->getSrcValue(), 3875 LN0->getSrcValueOffset(), MemVT, 3876 LN0->isVolatile(), LN0->isNonTemporal(), 3877 LN0->getAlignment()); 3878 CombineTo(N, ExtLoad); 3879 CombineTo(N0.getNode(), 3880 DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(), 3881 N0.getValueType(), ExtLoad), 3882 ExtLoad.getValue(1)); 3883 return SDValue(N, 0); // Return N so it doesn't get rechecked! 3884 } 3885 3886 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc 3887 if (N0.getOpcode() == ISD::SETCC) { 3888 SDValue SCC = 3889 SimplifySelectCC(N->getDebugLoc(), N0.getOperand(0), N0.getOperand(1), 3890 DAG.getConstant(1, VT), DAG.getConstant(0, VT), 3891 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true); 3892 if (SCC.getNode()) 3893 return SCC; 3894 } 3895 3896 return SDValue(); 3897 } 3898 3899 /// GetDemandedBits - See if the specified operand can be simplified with the 3900 /// knowledge that only the bits specified by Mask are used. If so, return the 3901 /// simpler operand, otherwise return a null SDValue. 3902 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) { 3903 switch (V.getOpcode()) { 3904 default: break; 3905 case ISD::OR: 3906 case ISD::XOR: 3907 // If the LHS or RHS don't contribute bits to the or, drop them. 3908 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask)) 3909 return V.getOperand(1); 3910 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask)) 3911 return V.getOperand(0); 3912 break; 3913 case ISD::SRL: 3914 // Only look at single-use SRLs. 3915 if (!V.getNode()->hasOneUse()) 3916 break; 3917 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) { 3918 // See if we can recursively simplify the LHS. 3919 unsigned Amt = RHSC->getZExtValue(); 3920 3921 // Watch out for shift count overflow though. 3922 if (Amt >= Mask.getBitWidth()) break; 3923 APInt NewMask = Mask << Amt; 3924 SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask); 3925 if (SimplifyLHS.getNode()) 3926 return DAG.getNode(ISD::SRL, V.getDebugLoc(), V.getValueType(), 3927 SimplifyLHS, V.getOperand(1)); 3928 } 3929 } 3930 return SDValue(); 3931 } 3932 3933 /// ReduceLoadWidth - If the result of a wider load is shifted to right of N 3934 /// bits and then truncated to a narrower type and where N is a multiple 3935 /// of number of bits of the narrower type, transform it to a narrower load 3936 /// from address + N / num of bits of new type. If the result is to be 3937 /// extended, also fold the extension to form a extending load. 3938 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) { 3939 unsigned Opc = N->getOpcode(); 3940 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD; 3941 SDValue N0 = N->getOperand(0); 3942 EVT VT = N->getValueType(0); 3943 EVT ExtVT = VT; 3944 3945 // This transformation isn't valid for vector loads. 3946 if (VT.isVector()) 3947 return SDValue(); 3948 3949 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then 3950 // extended to VT. 3951 if (Opc == ISD::SIGN_EXTEND_INREG) { 3952 ExtType = ISD::SEXTLOAD; 3953 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT(); 3954 if (LegalOperations && !TLI.isLoadExtLegal(ISD::SEXTLOAD, ExtVT)) 3955 return SDValue(); 3956 } 3957 3958 unsigned EVTBits = ExtVT.getSizeInBits(); 3959 unsigned ShAmt = 0; 3960 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse() && ExtVT.isRound()) { 3961 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 3962 ShAmt = N01->getZExtValue(); 3963 // Is the shift amount a multiple of size of VT? 3964 if ((ShAmt & (EVTBits-1)) == 0) { 3965 N0 = N0.getOperand(0); 3966 // Is the load width a multiple of size of VT? 3967 if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0) 3968 return SDValue(); 3969 } 3970 } 3971 } 3972 3973 // Do not generate loads of non-round integer types since these can 3974 // be expensive (and would be wrong if the type is not byte sized). 3975 if (isa<LoadSDNode>(N0) && N0.hasOneUse() && ExtVT.isRound() && 3976 cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits() >= EVTBits && 3977 // Do not change the width of a volatile load. 3978 !cast<LoadSDNode>(N0)->isVolatile()) { 3979 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 3980 EVT PtrType = N0.getOperand(1).getValueType(); 3981 3982 // For big endian targets, we need to adjust the offset to the pointer to 3983 // load the correct bytes. 3984 if (TLI.isBigEndian()) { 3985 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits(); 3986 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits(); 3987 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt; 3988 } 3989 3990 uint64_t PtrOff = ShAmt / 8; 3991 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff); 3992 SDValue NewPtr = DAG.getNode(ISD::ADD, LN0->getDebugLoc(), 3993 PtrType, LN0->getBasePtr(), 3994 DAG.getConstant(PtrOff, PtrType)); 3995 AddToWorkList(NewPtr.getNode()); 3996 3997 SDValue Load = (ExtType == ISD::NON_EXTLOAD) 3998 ? DAG.getLoad(VT, N0.getDebugLoc(), LN0->getChain(), NewPtr, 3999 LN0->getSrcValue(), LN0->getSrcValueOffset() + PtrOff, 4000 LN0->isVolatile(), LN0->isNonTemporal(), NewAlign) 4001 : DAG.getExtLoad(ExtType, N0.getDebugLoc(), VT, LN0->getChain(), NewPtr, 4002 LN0->getSrcValue(), LN0->getSrcValueOffset() + PtrOff, 4003 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(), 4004 NewAlign); 4005 4006 // Replace the old load's chain with the new load's chain. 4007 WorkListRemover DeadNodes(*this); 4008 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1), 4009 &DeadNodes); 4010 4011 // Return the new loaded value. 4012 return Load; 4013 } 4014 4015 return SDValue(); 4016 } 4017 4018 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) { 4019 SDValue N0 = N->getOperand(0); 4020 SDValue N1 = N->getOperand(1); 4021 EVT VT = N->getValueType(0); 4022 EVT EVT = cast<VTSDNode>(N1)->getVT(); 4023 unsigned VTBits = VT.getScalarType().getSizeInBits(); 4024 unsigned EVTBits = EVT.getScalarType().getSizeInBits(); 4025 4026 // fold (sext_in_reg c1) -> c1 4027 if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF) 4028 return DAG.getNode(ISD::SIGN_EXTEND_INREG, N->getDebugLoc(), VT, N0, N1); 4029 4030 // If the input is already sign extended, just drop the extension. 4031 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1) 4032 return N0; 4033 4034 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2 4035 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG && 4036 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT())) { 4037 return DAG.getNode(ISD::SIGN_EXTEND_INREG, N->getDebugLoc(), VT, 4038 N0.getOperand(0), N1); 4039 } 4040 4041 // fold (sext_in_reg (sext x)) -> (sext x) 4042 // fold (sext_in_reg (aext x)) -> (sext x) 4043 // if x is small enough. 4044 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) { 4045 SDValue N00 = N0.getOperand(0); 4046 if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits && 4047 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT))) 4048 return DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), VT, N00, N1); 4049 } 4050 4051 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero. 4052 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits))) 4053 return DAG.getZeroExtendInReg(N0, N->getDebugLoc(), EVT); 4054 4055 // fold operands of sext_in_reg based on knowledge that the top bits are not 4056 // demanded. 4057 if (SimplifyDemandedBits(SDValue(N, 0))) 4058 return SDValue(N, 0); 4059 4060 // fold (sext_in_reg (load x)) -> (smaller sextload x) 4061 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits)) 4062 SDValue NarrowLoad = ReduceLoadWidth(N); 4063 if (NarrowLoad.getNode()) 4064 return NarrowLoad; 4065 4066 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24) 4067 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible. 4068 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above. 4069 if (N0.getOpcode() == ISD::SRL) { 4070 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1))) 4071 if (ShAmt->getZExtValue()+EVTBits <= VTBits) { 4072 // We can turn this into an SRA iff the input to the SRL is already sign 4073 // extended enough. 4074 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0)); 4075 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits) 4076 return DAG.getNode(ISD::SRA, N->getDebugLoc(), VT, 4077 N0.getOperand(0), N0.getOperand(1)); 4078 } 4079 } 4080 4081 // fold (sext_inreg (extload x)) -> (sextload x) 4082 if (ISD::isEXTLoad(N0.getNode()) && 4083 ISD::isUNINDEXEDLoad(N0.getNode()) && 4084 EVT == cast<LoadSDNode>(N0)->getMemoryVT() && 4085 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) || 4086 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) { 4087 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 4088 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, N->getDebugLoc(), VT, 4089 LN0->getChain(), 4090 LN0->getBasePtr(), LN0->getSrcValue(), 4091 LN0->getSrcValueOffset(), EVT, 4092 LN0->isVolatile(), LN0->isNonTemporal(), 4093 LN0->getAlignment()); 4094 CombineTo(N, ExtLoad); 4095 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 4096 return SDValue(N, 0); // Return N so it doesn't get rechecked! 4097 } 4098 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use 4099 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 4100 N0.hasOneUse() && 4101 EVT == cast<LoadSDNode>(N0)->getMemoryVT() && 4102 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) || 4103 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) { 4104 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 4105 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, N->getDebugLoc(), VT, 4106 LN0->getChain(), 4107 LN0->getBasePtr(), LN0->getSrcValue(), 4108 LN0->getSrcValueOffset(), EVT, 4109 LN0->isVolatile(), LN0->isNonTemporal(), 4110 LN0->getAlignment()); 4111 CombineTo(N, ExtLoad); 4112 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 4113 return SDValue(N, 0); // Return N so it doesn't get rechecked! 4114 } 4115 return SDValue(); 4116 } 4117 4118 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) { 4119 SDValue N0 = N->getOperand(0); 4120 EVT VT = N->getValueType(0); 4121 4122 // noop truncate 4123 if (N0.getValueType() == N->getValueType(0)) 4124 return N0; 4125 // fold (truncate c1) -> c1 4126 if (isa<ConstantSDNode>(N0)) 4127 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, N0); 4128 // fold (truncate (truncate x)) -> (truncate x) 4129 if (N0.getOpcode() == ISD::TRUNCATE) 4130 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, N0.getOperand(0)); 4131 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x 4132 if (N0.getOpcode() == ISD::ZERO_EXTEND || 4133 N0.getOpcode() == ISD::SIGN_EXTEND || 4134 N0.getOpcode() == ISD::ANY_EXTEND) { 4135 if (N0.getOperand(0).getValueType().bitsLT(VT)) 4136 // if the source is smaller than the dest, we still need an extend 4137 return DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT, 4138 N0.getOperand(0)); 4139 else if (N0.getOperand(0).getValueType().bitsGT(VT)) 4140 // if the source is larger than the dest, than we just need the truncate 4141 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, N0.getOperand(0)); 4142 else 4143 // if the source and dest are the same type, we can drop both the extend 4144 // and the truncate. 4145 return N0.getOperand(0); 4146 } 4147 4148 // See if we can simplify the input to this truncate through knowledge that 4149 // only the low bits are being used. For example "trunc (or (shl x, 8), y)" 4150 // -> trunc y 4151 SDValue Shorter = 4152 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(), 4153 VT.getSizeInBits())); 4154 if (Shorter.getNode()) 4155 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, Shorter); 4156 4157 // fold (truncate (load x)) -> (smaller load x) 4158 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits)) 4159 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) 4160 return ReduceLoadWidth(N); 4161 return SDValue(); 4162 } 4163 4164 static SDNode *getBuildPairElt(SDNode *N, unsigned i) { 4165 SDValue Elt = N->getOperand(i); 4166 if (Elt.getOpcode() != ISD::MERGE_VALUES) 4167 return Elt.getNode(); 4168 return Elt.getOperand(Elt.getResNo()).getNode(); 4169 } 4170 4171 /// CombineConsecutiveLoads - build_pair (load, load) -> load 4172 /// if load locations are consecutive. 4173 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) { 4174 assert(N->getOpcode() == ISD::BUILD_PAIR); 4175 4176 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0)); 4177 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1)); 4178 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse()) 4179 return SDValue(); 4180 EVT LD1VT = LD1->getValueType(0); 4181 4182 if (ISD::isNON_EXTLoad(LD2) && 4183 LD2->hasOneUse() && 4184 // If both are volatile this would reduce the number of volatile loads. 4185 // If one is volatile it might be ok, but play conservative and bail out. 4186 !LD1->isVolatile() && 4187 !LD2->isVolatile() && 4188 DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) { 4189 unsigned Align = LD1->getAlignment(); 4190 unsigned NewAlign = TLI.getTargetData()-> 4191 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext())); 4192 4193 if (NewAlign <= Align && 4194 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT))) 4195 return DAG.getLoad(VT, N->getDebugLoc(), LD1->getChain(), 4196 LD1->getBasePtr(), LD1->getSrcValue(), 4197 LD1->getSrcValueOffset(), false, false, Align); 4198 } 4199 4200 return SDValue(); 4201 } 4202 4203 SDValue DAGCombiner::visitBIT_CONVERT(SDNode *N) { 4204 SDValue N0 = N->getOperand(0); 4205 EVT VT = N->getValueType(0); 4206 4207 // If the input is a BUILD_VECTOR with all constant elements, fold this now. 4208 // Only do this before legalize, since afterward the target may be depending 4209 // on the bitconvert. 4210 // First check to see if this is all constant. 4211 if (!LegalTypes && 4212 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() && 4213 VT.isVector()) { 4214 bool isSimple = true; 4215 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) 4216 if (N0.getOperand(i).getOpcode() != ISD::UNDEF && 4217 N0.getOperand(i).getOpcode() != ISD::Constant && 4218 N0.getOperand(i).getOpcode() != ISD::ConstantFP) { 4219 isSimple = false; 4220 break; 4221 } 4222 4223 EVT DestEltVT = N->getValueType(0).getVectorElementType(); 4224 assert(!DestEltVT.isVector() && 4225 "Element type of vector ValueType must not be vector!"); 4226 if (isSimple) 4227 return ConstantFoldBIT_CONVERTofBUILD_VECTOR(N0.getNode(), DestEltVT); 4228 } 4229 4230 // If the input is a constant, let getNode fold it. 4231 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) { 4232 SDValue Res = DAG.getNode(ISD::BIT_CONVERT, N->getDebugLoc(), VT, N0); 4233 if (Res.getNode() != N) { 4234 if (!LegalOperations || 4235 TLI.isOperationLegal(Res.getNode()->getOpcode(), VT)) 4236 return Res; 4237 4238 // Folding it resulted in an illegal node, and it's too late to 4239 // do that. Clean up the old node and forego the transformation. 4240 // Ideally this won't happen very often, because instcombine 4241 // and the earlier dagcombine runs (where illegal nodes are 4242 // permitted) should have folded most of them already. 4243 DAG.DeleteNode(Res.getNode()); 4244 } 4245 } 4246 4247 // (conv (conv x, t1), t2) -> (conv x, t2) 4248 if (N0.getOpcode() == ISD::BIT_CONVERT) 4249 return DAG.getNode(ISD::BIT_CONVERT, N->getDebugLoc(), VT, 4250 N0.getOperand(0)); 4251 4252 // fold (conv (load x)) -> (load (conv*)x) 4253 // If the resultant load doesn't need a higher alignment than the original! 4254 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() && 4255 // Do not change the width of a volatile load. 4256 !cast<LoadSDNode>(N0)->isVolatile() && 4257 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT))) { 4258 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 4259 unsigned Align = TLI.getTargetData()-> 4260 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext())); 4261 unsigned OrigAlign = LN0->getAlignment(); 4262 4263 if (Align <= OrigAlign) { 4264 SDValue Load = DAG.getLoad(VT, N->getDebugLoc(), LN0->getChain(), 4265 LN0->getBasePtr(), 4266 LN0->getSrcValue(), LN0->getSrcValueOffset(), 4267 LN0->isVolatile(), LN0->isNonTemporal(), 4268 OrigAlign); 4269 AddToWorkList(N); 4270 CombineTo(N0.getNode(), 4271 DAG.getNode(ISD::BIT_CONVERT, N0.getDebugLoc(), 4272 N0.getValueType(), Load), 4273 Load.getValue(1)); 4274 return Load; 4275 } 4276 } 4277 4278 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit) 4279 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit)) 4280 // This often reduces constant pool loads. 4281 if ((N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FABS) && 4282 N0.getNode()->hasOneUse() && VT.isInteger() && !VT.isVector()) { 4283 SDValue NewConv = DAG.getNode(ISD::BIT_CONVERT, N0.getDebugLoc(), VT, 4284 N0.getOperand(0)); 4285 AddToWorkList(NewConv.getNode()); 4286 4287 APInt SignBit = APInt::getSignBit(VT.getSizeInBits()); 4288 if (N0.getOpcode() == ISD::FNEG) 4289 return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT, 4290 NewConv, DAG.getConstant(SignBit, VT)); 4291 assert(N0.getOpcode() == ISD::FABS); 4292 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, 4293 NewConv, DAG.getConstant(~SignBit, VT)); 4294 } 4295 4296 // fold (bitconvert (fcopysign cst, x)) -> 4297 // (or (and (bitconvert x), sign), (and cst, (not sign))) 4298 // Note that we don't handle (copysign x, cst) because this can always be 4299 // folded to an fneg or fabs. 4300 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() && 4301 isa<ConstantFPSDNode>(N0.getOperand(0)) && 4302 VT.isInteger() && !VT.isVector()) { 4303 unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits(); 4304 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth); 4305 if (isTypeLegal(IntXVT)) { 4306 SDValue X = DAG.getNode(ISD::BIT_CONVERT, N0.getDebugLoc(), 4307 IntXVT, N0.getOperand(1)); 4308 AddToWorkList(X.getNode()); 4309 4310 // If X has a different width than the result/lhs, sext it or truncate it. 4311 unsigned VTWidth = VT.getSizeInBits(); 4312 if (OrigXWidth < VTWidth) { 4313 X = DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), VT, X); 4314 AddToWorkList(X.getNode()); 4315 } else if (OrigXWidth > VTWidth) { 4316 // To get the sign bit in the right place, we have to shift it right 4317 // before truncating. 4318 X = DAG.getNode(ISD::SRL, X.getDebugLoc(), 4319 X.getValueType(), X, 4320 DAG.getConstant(OrigXWidth-VTWidth, X.getValueType())); 4321 AddToWorkList(X.getNode()); 4322 X = DAG.getNode(ISD::TRUNCATE, X.getDebugLoc(), VT, X); 4323 AddToWorkList(X.getNode()); 4324 } 4325 4326 APInt SignBit = APInt::getSignBit(VT.getSizeInBits()); 4327 X = DAG.getNode(ISD::AND, X.getDebugLoc(), VT, 4328 X, DAG.getConstant(SignBit, VT)); 4329 AddToWorkList(X.getNode()); 4330 4331 SDValue Cst = DAG.getNode(ISD::BIT_CONVERT, N0.getDebugLoc(), 4332 VT, N0.getOperand(0)); 4333 Cst = DAG.getNode(ISD::AND, Cst.getDebugLoc(), VT, 4334 Cst, DAG.getConstant(~SignBit, VT)); 4335 AddToWorkList(Cst.getNode()); 4336 4337 return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, X, Cst); 4338 } 4339 } 4340 4341 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive. 4342 if (N0.getOpcode() == ISD::BUILD_PAIR) { 4343 SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT); 4344 if (CombineLD.getNode()) 4345 return CombineLD; 4346 } 4347 4348 return SDValue(); 4349 } 4350 4351 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) { 4352 EVT VT = N->getValueType(0); 4353 return CombineConsecutiveLoads(N, VT); 4354 } 4355 4356 /// ConstantFoldBIT_CONVERTofBUILD_VECTOR - We know that BV is a build_vector 4357 /// node with Constant, ConstantFP or Undef operands. DstEltVT indicates the 4358 /// destination element value type. 4359 SDValue DAGCombiner:: 4360 ConstantFoldBIT_CONVERTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) { 4361 EVT SrcEltVT = BV->getValueType(0).getVectorElementType(); 4362 4363 // If this is already the right type, we're done. 4364 if (SrcEltVT == DstEltVT) return SDValue(BV, 0); 4365 4366 unsigned SrcBitSize = SrcEltVT.getSizeInBits(); 4367 unsigned DstBitSize = DstEltVT.getSizeInBits(); 4368 4369 // If this is a conversion of N elements of one type to N elements of another 4370 // type, convert each element. This handles FP<->INT cases. 4371 if (SrcBitSize == DstBitSize) { 4372 SmallVector<SDValue, 8> Ops; 4373 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) { 4374 SDValue Op = BV->getOperand(i); 4375 // If the vector element type is not legal, the BUILD_VECTOR operands 4376 // are promoted and implicitly truncated. Make that explicit here. 4377 if (Op.getValueType() != SrcEltVT) 4378 Op = DAG.getNode(ISD::TRUNCATE, BV->getDebugLoc(), SrcEltVT, Op); 4379 Ops.push_back(DAG.getNode(ISD::BIT_CONVERT, BV->getDebugLoc(), 4380 DstEltVT, Op)); 4381 AddToWorkList(Ops.back().getNode()); 4382 } 4383 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, 4384 BV->getValueType(0).getVectorNumElements()); 4385 return DAG.getNode(ISD::BUILD_VECTOR, BV->getDebugLoc(), VT, 4386 &Ops[0], Ops.size()); 4387 } 4388 4389 // Otherwise, we're growing or shrinking the elements. To avoid having to 4390 // handle annoying details of growing/shrinking FP values, we convert them to 4391 // int first. 4392 if (SrcEltVT.isFloatingPoint()) { 4393 // Convert the input float vector to a int vector where the elements are the 4394 // same sizes. 4395 assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!"); 4396 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits()); 4397 BV = ConstantFoldBIT_CONVERTofBUILD_VECTOR(BV, IntVT).getNode(); 4398 SrcEltVT = IntVT; 4399 } 4400 4401 // Now we know the input is an integer vector. If the output is a FP type, 4402 // convert to integer first, then to FP of the right size. 4403 if (DstEltVT.isFloatingPoint()) { 4404 assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!"); 4405 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits()); 4406 SDNode *Tmp = ConstantFoldBIT_CONVERTofBUILD_VECTOR(BV, TmpVT).getNode(); 4407 4408 // Next, convert to FP elements of the same size. 4409 return ConstantFoldBIT_CONVERTofBUILD_VECTOR(Tmp, DstEltVT); 4410 } 4411 4412 // Okay, we know the src/dst types are both integers of differing types. 4413 // Handling growing first. 4414 assert(SrcEltVT.isInteger() && DstEltVT.isInteger()); 4415 if (SrcBitSize < DstBitSize) { 4416 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize; 4417 4418 SmallVector<SDValue, 8> Ops; 4419 for (unsigned i = 0, e = BV->getNumOperands(); i != e; 4420 i += NumInputsPerOutput) { 4421 bool isLE = TLI.isLittleEndian(); 4422 APInt NewBits = APInt(DstBitSize, 0); 4423 bool EltIsUndef = true; 4424 for (unsigned j = 0; j != NumInputsPerOutput; ++j) { 4425 // Shift the previously computed bits over. 4426 NewBits <<= SrcBitSize; 4427 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j)); 4428 if (Op.getOpcode() == ISD::UNDEF) continue; 4429 EltIsUndef = false; 4430 4431 NewBits |= APInt(cast<ConstantSDNode>(Op)->getAPIntValue()). 4432 zextOrTrunc(SrcBitSize).zext(DstBitSize); 4433 } 4434 4435 if (EltIsUndef) 4436 Ops.push_back(DAG.getUNDEF(DstEltVT)); 4437 else 4438 Ops.push_back(DAG.getConstant(NewBits, DstEltVT)); 4439 } 4440 4441 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size()); 4442 return DAG.getNode(ISD::BUILD_VECTOR, BV->getDebugLoc(), VT, 4443 &Ops[0], Ops.size()); 4444 } 4445 4446 // Finally, this must be the case where we are shrinking elements: each input 4447 // turns into multiple outputs. 4448 bool isS2V = ISD::isScalarToVector(BV); 4449 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize; 4450 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, 4451 NumOutputsPerInput*BV->getNumOperands()); 4452 SmallVector<SDValue, 8> Ops; 4453 4454 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) { 4455 if (BV->getOperand(i).getOpcode() == ISD::UNDEF) { 4456 for (unsigned j = 0; j != NumOutputsPerInput; ++j) 4457 Ops.push_back(DAG.getUNDEF(DstEltVT)); 4458 continue; 4459 } 4460 4461 APInt OpVal = APInt(cast<ConstantSDNode>(BV->getOperand(i))-> 4462 getAPIntValue()).zextOrTrunc(SrcBitSize); 4463 4464 for (unsigned j = 0; j != NumOutputsPerInput; ++j) { 4465 APInt ThisVal = APInt(OpVal).trunc(DstBitSize); 4466 Ops.push_back(DAG.getConstant(ThisVal, DstEltVT)); 4467 if (isS2V && i == 0 && j == 0 && APInt(ThisVal).zext(SrcBitSize) == OpVal) 4468 // Simply turn this into a SCALAR_TO_VECTOR of the new type. 4469 return DAG.getNode(ISD::SCALAR_TO_VECTOR, BV->getDebugLoc(), VT, 4470 Ops[0]); 4471 OpVal = OpVal.lshr(DstBitSize); 4472 } 4473 4474 // For big endian targets, swap the order of the pieces of each element. 4475 if (TLI.isBigEndian()) 4476 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end()); 4477 } 4478 4479 return DAG.getNode(ISD::BUILD_VECTOR, BV->getDebugLoc(), VT, 4480 &Ops[0], Ops.size()); 4481 } 4482 4483 SDValue DAGCombiner::visitFADD(SDNode *N) { 4484 SDValue N0 = N->getOperand(0); 4485 SDValue N1 = N->getOperand(1); 4486 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 4487 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 4488 EVT VT = N->getValueType(0); 4489 4490 // fold vector ops 4491 if (VT.isVector()) { 4492 SDValue FoldedVOp = SimplifyVBinOp(N); 4493 if (FoldedVOp.getNode()) return FoldedVOp; 4494 } 4495 4496 // fold (fadd c1, c2) -> (fadd c1, c2) 4497 if (N0CFP && N1CFP && VT != MVT::ppcf128) 4498 return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N0, N1); 4499 // canonicalize constant to RHS 4500 if (N0CFP && !N1CFP) 4501 return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N1, N0); 4502 // fold (fadd A, 0) -> A 4503 if (UnsafeFPMath && N1CFP && N1CFP->getValueAPF().isZero()) 4504 return N0; 4505 // fold (fadd A, (fneg B)) -> (fsub A, B) 4506 if (isNegatibleForFree(N1, LegalOperations) == 2) 4507 return DAG.getNode(ISD::FSUB, N->getDebugLoc(), VT, N0, 4508 GetNegatedExpression(N1, DAG, LegalOperations)); 4509 // fold (fadd (fneg A), B) -> (fsub B, A) 4510 if (isNegatibleForFree(N0, LegalOperations) == 2) 4511 return DAG.getNode(ISD::FSUB, N->getDebugLoc(), VT, N1, 4512 GetNegatedExpression(N0, DAG, LegalOperations)); 4513 4514 // If allowed, fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2)) 4515 if (UnsafeFPMath && N1CFP && N0.getOpcode() == ISD::FADD && 4516 N0.getNode()->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1))) 4517 return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N0.getOperand(0), 4518 DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, 4519 N0.getOperand(1), N1)); 4520 4521 return SDValue(); 4522 } 4523 4524 SDValue DAGCombiner::visitFSUB(SDNode *N) { 4525 SDValue N0 = N->getOperand(0); 4526 SDValue N1 = N->getOperand(1); 4527 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 4528 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 4529 EVT VT = N->getValueType(0); 4530 4531 // fold vector ops 4532 if (VT.isVector()) { 4533 SDValue FoldedVOp = SimplifyVBinOp(N); 4534 if (FoldedVOp.getNode()) return FoldedVOp; 4535 } 4536 4537 // fold (fsub c1, c2) -> c1-c2 4538 if (N0CFP && N1CFP && VT != MVT::ppcf128) 4539 return DAG.getNode(ISD::FSUB, N->getDebugLoc(), VT, N0, N1); 4540 // fold (fsub A, 0) -> A 4541 if (UnsafeFPMath && N1CFP && N1CFP->getValueAPF().isZero()) 4542 return N0; 4543 // fold (fsub 0, B) -> -B 4544 if (UnsafeFPMath && N0CFP && N0CFP->getValueAPF().isZero()) { 4545 if (isNegatibleForFree(N1, LegalOperations)) 4546 return GetNegatedExpression(N1, DAG, LegalOperations); 4547 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT)) 4548 return DAG.getNode(ISD::FNEG, N->getDebugLoc(), VT, N1); 4549 } 4550 // fold (fsub A, (fneg B)) -> (fadd A, B) 4551 if (isNegatibleForFree(N1, LegalOperations)) 4552 return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N0, 4553 GetNegatedExpression(N1, DAG, LegalOperations)); 4554 4555 return SDValue(); 4556 } 4557 4558 SDValue DAGCombiner::visitFMUL(SDNode *N) { 4559 SDValue N0 = N->getOperand(0); 4560 SDValue N1 = N->getOperand(1); 4561 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 4562 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 4563 EVT VT = N->getValueType(0); 4564 4565 // fold vector ops 4566 if (VT.isVector()) { 4567 SDValue FoldedVOp = SimplifyVBinOp(N); 4568 if (FoldedVOp.getNode()) return FoldedVOp; 4569 } 4570 4571 // fold (fmul c1, c2) -> c1*c2 4572 if (N0CFP && N1CFP && VT != MVT::ppcf128) 4573 return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT, N0, N1); 4574 // canonicalize constant to RHS 4575 if (N0CFP && !N1CFP) 4576 return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT, N1, N0); 4577 // fold (fmul A, 0) -> 0 4578 if (UnsafeFPMath && N1CFP && N1CFP->getValueAPF().isZero()) 4579 return N1; 4580 // fold (fmul A, 0) -> 0, vector edition. 4581 if (UnsafeFPMath && ISD::isBuildVectorAllZeros(N1.getNode())) 4582 return N1; 4583 // fold (fmul X, 2.0) -> (fadd X, X) 4584 if (N1CFP && N1CFP->isExactlyValue(+2.0)) 4585 return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N0, N0); 4586 // fold (fmul X, -1.0) -> (fneg X) 4587 if (N1CFP && N1CFP->isExactlyValue(-1.0)) 4588 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT)) 4589 return DAG.getNode(ISD::FNEG, N->getDebugLoc(), VT, N0); 4590 4591 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y) 4592 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations)) { 4593 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations)) { 4594 // Both can be negated for free, check to see if at least one is cheaper 4595 // negated. 4596 if (LHSNeg == 2 || RHSNeg == 2) 4597 return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT, 4598 GetNegatedExpression(N0, DAG, LegalOperations), 4599 GetNegatedExpression(N1, DAG, LegalOperations)); 4600 } 4601 } 4602 4603 // If allowed, fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2)) 4604 if (UnsafeFPMath && N1CFP && N0.getOpcode() == ISD::FMUL && 4605 N0.getNode()->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1))) 4606 return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT, N0.getOperand(0), 4607 DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT, 4608 N0.getOperand(1), N1)); 4609 4610 return SDValue(); 4611 } 4612 4613 SDValue DAGCombiner::visitFDIV(SDNode *N) { 4614 SDValue N0 = N->getOperand(0); 4615 SDValue N1 = N->getOperand(1); 4616 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 4617 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 4618 EVT VT = N->getValueType(0); 4619 4620 // fold vector ops 4621 if (VT.isVector()) { 4622 SDValue FoldedVOp = SimplifyVBinOp(N); 4623 if (FoldedVOp.getNode()) return FoldedVOp; 4624 } 4625 4626 // fold (fdiv c1, c2) -> c1/c2 4627 if (N0CFP && N1CFP && VT != MVT::ppcf128) 4628 return DAG.getNode(ISD::FDIV, N->getDebugLoc(), VT, N0, N1); 4629 4630 4631 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y) 4632 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations)) { 4633 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations)) { 4634 // Both can be negated for free, check to see if at least one is cheaper 4635 // negated. 4636 if (LHSNeg == 2 || RHSNeg == 2) 4637 return DAG.getNode(ISD::FDIV, N->getDebugLoc(), VT, 4638 GetNegatedExpression(N0, DAG, LegalOperations), 4639 GetNegatedExpression(N1, DAG, LegalOperations)); 4640 } 4641 } 4642 4643 return SDValue(); 4644 } 4645 4646 SDValue DAGCombiner::visitFREM(SDNode *N) { 4647 SDValue N0 = N->getOperand(0); 4648 SDValue N1 = N->getOperand(1); 4649 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 4650 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 4651 EVT VT = N->getValueType(0); 4652 4653 // fold (frem c1, c2) -> fmod(c1,c2) 4654 if (N0CFP && N1CFP && VT != MVT::ppcf128) 4655 return DAG.getNode(ISD::FREM, N->getDebugLoc(), VT, N0, N1); 4656 4657 return SDValue(); 4658 } 4659 4660 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) { 4661 SDValue N0 = N->getOperand(0); 4662 SDValue N1 = N->getOperand(1); 4663 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 4664 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 4665 EVT VT = N->getValueType(0); 4666 4667 if (N0CFP && N1CFP && VT != MVT::ppcf128) // Constant fold 4668 return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT, N0, N1); 4669 4670 if (N1CFP) { 4671 const APFloat& V = N1CFP->getValueAPF(); 4672 // copysign(x, c1) -> fabs(x) iff ispos(c1) 4673 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1) 4674 if (!V.isNegative()) { 4675 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT)) 4676 return DAG.getNode(ISD::FABS, N->getDebugLoc(), VT, N0); 4677 } else { 4678 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT)) 4679 return DAG.getNode(ISD::FNEG, N->getDebugLoc(), VT, 4680 DAG.getNode(ISD::FABS, N0.getDebugLoc(), VT, N0)); 4681 } 4682 } 4683 4684 // copysign(fabs(x), y) -> copysign(x, y) 4685 // copysign(fneg(x), y) -> copysign(x, y) 4686 // copysign(copysign(x,z), y) -> copysign(x, y) 4687 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG || 4688 N0.getOpcode() == ISD::FCOPYSIGN) 4689 return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT, 4690 N0.getOperand(0), N1); 4691 4692 // copysign(x, abs(y)) -> abs(x) 4693 if (N1.getOpcode() == ISD::FABS) 4694 return DAG.getNode(ISD::FABS, N->getDebugLoc(), VT, N0); 4695 4696 // copysign(x, copysign(y,z)) -> copysign(x, z) 4697 if (N1.getOpcode() == ISD::FCOPYSIGN) 4698 return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT, 4699 N0, N1.getOperand(1)); 4700 4701 // copysign(x, fp_extend(y)) -> copysign(x, y) 4702 // copysign(x, fp_round(y)) -> copysign(x, y) 4703 if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND) 4704 return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT, 4705 N0, N1.getOperand(0)); 4706 4707 return SDValue(); 4708 } 4709 4710 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) { 4711 SDValue N0 = N->getOperand(0); 4712 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 4713 EVT VT = N->getValueType(0); 4714 EVT OpVT = N0.getValueType(); 4715 4716 // fold (sint_to_fp c1) -> c1fp 4717 if (N0C && OpVT != MVT::ppcf128) 4718 return DAG.getNode(ISD::SINT_TO_FP, N->getDebugLoc(), VT, N0); 4719 4720 // If the input is a legal type, and SINT_TO_FP is not legal on this target, 4721 // but UINT_TO_FP is legal on this target, try to convert. 4722 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) && 4723 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) { 4724 // If the sign bit is known to be zero, we can change this to UINT_TO_FP. 4725 if (DAG.SignBitIsZero(N0)) 4726 return DAG.getNode(ISD::UINT_TO_FP, N->getDebugLoc(), VT, N0); 4727 } 4728 4729 return SDValue(); 4730 } 4731 4732 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) { 4733 SDValue N0 = N->getOperand(0); 4734 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 4735 EVT VT = N->getValueType(0); 4736 EVT OpVT = N0.getValueType(); 4737 4738 // fold (uint_to_fp c1) -> c1fp 4739 if (N0C && OpVT != MVT::ppcf128) 4740 return DAG.getNode(ISD::UINT_TO_FP, N->getDebugLoc(), VT, N0); 4741 4742 // If the input is a legal type, and UINT_TO_FP is not legal on this target, 4743 // but SINT_TO_FP is legal on this target, try to convert. 4744 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) && 4745 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) { 4746 // If the sign bit is known to be zero, we can change this to SINT_TO_FP. 4747 if (DAG.SignBitIsZero(N0)) 4748 return DAG.getNode(ISD::SINT_TO_FP, N->getDebugLoc(), VT, N0); 4749 } 4750 4751 return SDValue(); 4752 } 4753 4754 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) { 4755 SDValue N0 = N->getOperand(0); 4756 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 4757 EVT VT = N->getValueType(0); 4758 4759 // fold (fp_to_sint c1fp) -> c1 4760 if (N0CFP) 4761 return DAG.getNode(ISD::FP_TO_SINT, N->getDebugLoc(), VT, N0); 4762 4763 return SDValue(); 4764 } 4765 4766 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) { 4767 SDValue N0 = N->getOperand(0); 4768 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 4769 EVT VT = N->getValueType(0); 4770 4771 // fold (fp_to_uint c1fp) -> c1 4772 if (N0CFP && VT != MVT::ppcf128) 4773 return DAG.getNode(ISD::FP_TO_UINT, N->getDebugLoc(), VT, N0); 4774 4775 return SDValue(); 4776 } 4777 4778 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) { 4779 SDValue N0 = N->getOperand(0); 4780 SDValue N1 = N->getOperand(1); 4781 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 4782 EVT VT = N->getValueType(0); 4783 4784 // fold (fp_round c1fp) -> c1fp 4785 if (N0CFP && N0.getValueType() != MVT::ppcf128) 4786 return DAG.getNode(ISD::FP_ROUND, N->getDebugLoc(), VT, N0, N1); 4787 4788 // fold (fp_round (fp_extend x)) -> x 4789 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType()) 4790 return N0.getOperand(0); 4791 4792 // fold (fp_round (fp_round x)) -> (fp_round x) 4793 if (N0.getOpcode() == ISD::FP_ROUND) { 4794 // This is a value preserving truncation if both round's are. 4795 bool IsTrunc = N->getConstantOperandVal(1) == 1 && 4796 N0.getNode()->getConstantOperandVal(1) == 1; 4797 return DAG.getNode(ISD::FP_ROUND, N->getDebugLoc(), VT, N0.getOperand(0), 4798 DAG.getIntPtrConstant(IsTrunc)); 4799 } 4800 4801 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y) 4802 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) { 4803 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, N0.getDebugLoc(), VT, 4804 N0.getOperand(0), N1); 4805 AddToWorkList(Tmp.getNode()); 4806 return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT, 4807 Tmp, N0.getOperand(1)); 4808 } 4809 4810 return SDValue(); 4811 } 4812 4813 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) { 4814 SDValue N0 = N->getOperand(0); 4815 EVT VT = N->getValueType(0); 4816 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT(); 4817 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 4818 4819 // fold (fp_round_inreg c1fp) -> c1fp 4820 if (N0CFP && isTypeLegal(EVT)) { 4821 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT); 4822 return DAG.getNode(ISD::FP_EXTEND, N->getDebugLoc(), VT, Round); 4823 } 4824 4825 return SDValue(); 4826 } 4827 4828 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) { 4829 SDValue N0 = N->getOperand(0); 4830 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 4831 EVT VT = N->getValueType(0); 4832 4833 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded. 4834 if (N->hasOneUse() && 4835 N->use_begin()->getOpcode() == ISD::FP_ROUND) 4836 return SDValue(); 4837 4838 // fold (fp_extend c1fp) -> c1fp 4839 if (N0CFP && VT != MVT::ppcf128) 4840 return DAG.getNode(ISD::FP_EXTEND, N->getDebugLoc(), VT, N0); 4841 4842 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the 4843 // value of X. 4844 if (N0.getOpcode() == ISD::FP_ROUND 4845 && N0.getNode()->getConstantOperandVal(1) == 1) { 4846 SDValue In = N0.getOperand(0); 4847 if (In.getValueType() == VT) return In; 4848 if (VT.bitsLT(In.getValueType())) 4849 return DAG.getNode(ISD::FP_ROUND, N->getDebugLoc(), VT, 4850 In, N0.getOperand(1)); 4851 return DAG.getNode(ISD::FP_EXTEND, N->getDebugLoc(), VT, In); 4852 } 4853 4854 // fold (fpext (load x)) -> (fpext (fptrunc (extload x))) 4855 if (ISD::isNON_EXTLoad(N0.getNode()) && N0.hasOneUse() && 4856 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) || 4857 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) { 4858 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 4859 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, N->getDebugLoc(), VT, 4860 LN0->getChain(), 4861 LN0->getBasePtr(), LN0->getSrcValue(), 4862 LN0->getSrcValueOffset(), 4863 N0.getValueType(), 4864 LN0->isVolatile(), LN0->isNonTemporal(), 4865 LN0->getAlignment()); 4866 CombineTo(N, ExtLoad); 4867 CombineTo(N0.getNode(), 4868 DAG.getNode(ISD::FP_ROUND, N0.getDebugLoc(), 4869 N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)), 4870 ExtLoad.getValue(1)); 4871 return SDValue(N, 0); // Return N so it doesn't get rechecked! 4872 } 4873 4874 return SDValue(); 4875 } 4876 4877 SDValue DAGCombiner::visitFNEG(SDNode *N) { 4878 SDValue N0 = N->getOperand(0); 4879 EVT VT = N->getValueType(0); 4880 4881 if (isNegatibleForFree(N0, LegalOperations)) 4882 return GetNegatedExpression(N0, DAG, LegalOperations); 4883 4884 // Transform fneg(bitconvert(x)) -> bitconvert(x^sign) to avoid loading 4885 // constant pool values. 4886 if (N0.getOpcode() == ISD::BIT_CONVERT && 4887 !VT.isVector() && 4888 N0.getNode()->hasOneUse() && 4889 N0.getOperand(0).getValueType().isInteger()) { 4890 SDValue Int = N0.getOperand(0); 4891 EVT IntVT = Int.getValueType(); 4892 if (IntVT.isInteger() && !IntVT.isVector()) { 4893 Int = DAG.getNode(ISD::XOR, N0.getDebugLoc(), IntVT, Int, 4894 DAG.getConstant(APInt::getSignBit(IntVT.getSizeInBits()), IntVT)); 4895 AddToWorkList(Int.getNode()); 4896 return DAG.getNode(ISD::BIT_CONVERT, N->getDebugLoc(), 4897 VT, Int); 4898 } 4899 } 4900 4901 return SDValue(); 4902 } 4903 4904 SDValue DAGCombiner::visitFABS(SDNode *N) { 4905 SDValue N0 = N->getOperand(0); 4906 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 4907 EVT VT = N->getValueType(0); 4908 4909 // fold (fabs c1) -> fabs(c1) 4910 if (N0CFP && VT != MVT::ppcf128) 4911 return DAG.getNode(ISD::FABS, N->getDebugLoc(), VT, N0); 4912 // fold (fabs (fabs x)) -> (fabs x) 4913 if (N0.getOpcode() == ISD::FABS) 4914 return N->getOperand(0); 4915 // fold (fabs (fneg x)) -> (fabs x) 4916 // fold (fabs (fcopysign x, y)) -> (fabs x) 4917 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN) 4918 return DAG.getNode(ISD::FABS, N->getDebugLoc(), VT, N0.getOperand(0)); 4919 4920 // Transform fabs(bitconvert(x)) -> bitconvert(x&~sign) to avoid loading 4921 // constant pool values. 4922 if (N0.getOpcode() == ISD::BIT_CONVERT && N0.getNode()->hasOneUse() && 4923 N0.getOperand(0).getValueType().isInteger() && 4924 !N0.getOperand(0).getValueType().isVector()) { 4925 SDValue Int = N0.getOperand(0); 4926 EVT IntVT = Int.getValueType(); 4927 if (IntVT.isInteger() && !IntVT.isVector()) { 4928 Int = DAG.getNode(ISD::AND, N0.getDebugLoc(), IntVT, Int, 4929 DAG.getConstant(~APInt::getSignBit(IntVT.getSizeInBits()), IntVT)); 4930 AddToWorkList(Int.getNode()); 4931 return DAG.getNode(ISD::BIT_CONVERT, N->getDebugLoc(), 4932 N->getValueType(0), Int); 4933 } 4934 } 4935 4936 return SDValue(); 4937 } 4938 4939 SDValue DAGCombiner::visitBRCOND(SDNode *N) { 4940 SDValue Chain = N->getOperand(0); 4941 SDValue N1 = N->getOperand(1); 4942 SDValue N2 = N->getOperand(2); 4943 4944 // If N is a constant we could fold this into a fallthrough or unconditional 4945 // branch. However that doesn't happen very often in normal code, because 4946 // Instcombine/SimplifyCFG should have handled the available opportunities. 4947 // If we did this folding here, it would be necessary to update the 4948 // MachineBasicBlock CFG, which is awkward. 4949 4950 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal 4951 // on the target. 4952 if (N1.getOpcode() == ISD::SETCC && 4953 TLI.isOperationLegalOrCustom(ISD::BR_CC, MVT::Other)) { 4954 return DAG.getNode(ISD::BR_CC, N->getDebugLoc(), MVT::Other, 4955 Chain, N1.getOperand(2), 4956 N1.getOperand(0), N1.getOperand(1), N2); 4957 } 4958 4959 SDNode *Trunc = 0; 4960 if (N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) { 4961 // Look past truncate. 4962 Trunc = N1.getNode(); 4963 N1 = N1.getOperand(0); 4964 } 4965 4966 if (N1.hasOneUse() && N1.getOpcode() == ISD::SRL) { 4967 // Match this pattern so that we can generate simpler code: 4968 // 4969 // %a = ... 4970 // %b = and i32 %a, 2 4971 // %c = srl i32 %b, 1 4972 // brcond i32 %c ... 4973 // 4974 // into 4975 // 4976 // %a = ... 4977 // %b = and i32 %a, 2 4978 // %c = setcc eq %b, 0 4979 // brcond %c ... 4980 // 4981 // This applies only when the AND constant value has one bit set and the 4982 // SRL constant is equal to the log2 of the AND constant. The back-end is 4983 // smart enough to convert the result into a TEST/JMP sequence. 4984 SDValue Op0 = N1.getOperand(0); 4985 SDValue Op1 = N1.getOperand(1); 4986 4987 if (Op0.getOpcode() == ISD::AND && 4988 Op1.getOpcode() == ISD::Constant) { 4989 SDValue AndOp1 = Op0.getOperand(1); 4990 4991 if (AndOp1.getOpcode() == ISD::Constant) { 4992 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue(); 4993 4994 if (AndConst.isPowerOf2() && 4995 cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) { 4996 SDValue SetCC = 4997 DAG.getSetCC(N->getDebugLoc(), 4998 TLI.getSetCCResultType(Op0.getValueType()), 4999 Op0, DAG.getConstant(0, Op0.getValueType()), 5000 ISD::SETNE); 5001 5002 SDValue NewBRCond = DAG.getNode(ISD::BRCOND, N->getDebugLoc(), 5003 MVT::Other, Chain, SetCC, N2); 5004 // Don't add the new BRCond into the worklist or else SimplifySelectCC 5005 // will convert it back to (X & C1) >> C2. 5006 CombineTo(N, NewBRCond, false); 5007 // Truncate is dead. 5008 if (Trunc) { 5009 removeFromWorkList(Trunc); 5010 DAG.DeleteNode(Trunc); 5011 } 5012 // Replace the uses of SRL with SETCC 5013 WorkListRemover DeadNodes(*this); 5014 DAG.ReplaceAllUsesOfValueWith(N1, SetCC, &DeadNodes); 5015 removeFromWorkList(N1.getNode()); 5016 DAG.DeleteNode(N1.getNode()); 5017 return SDValue(N, 0); // Return N so it doesn't get rechecked! 5018 } 5019 } 5020 } 5021 } 5022 5023 // Transform br(xor(x, y)) -> br(x != y) 5024 // Transform br(xor(xor(x,y), 1)) -> br (x == y) 5025 if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) { 5026 SDNode *TheXor = N1.getNode(); 5027 SDValue Op0 = TheXor->getOperand(0); 5028 SDValue Op1 = TheXor->getOperand(1); 5029 if (Op0.getOpcode() == Op1.getOpcode()) { 5030 // Avoid missing important xor optimizations. 5031 SDValue Tmp = visitXOR(TheXor); 5032 if (Tmp.getNode() && Tmp.getNode() != TheXor) { 5033 DEBUG(dbgs() << "\nReplacing.8 "; 5034 TheXor->dump(&DAG); 5035 dbgs() << "\nWith: "; 5036 Tmp.getNode()->dump(&DAG); 5037 dbgs() << '\n'); 5038 WorkListRemover DeadNodes(*this); 5039 DAG.ReplaceAllUsesOfValueWith(N1, Tmp, &DeadNodes); 5040 removeFromWorkList(TheXor); 5041 DAG.DeleteNode(TheXor); 5042 return DAG.getNode(ISD::BRCOND, N->getDebugLoc(), 5043 MVT::Other, Chain, Tmp, N2); 5044 } 5045 } 5046 5047 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) { 5048 bool Equal = false; 5049 if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0)) 5050 if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() && 5051 Op0.getOpcode() == ISD::XOR) { 5052 TheXor = Op0.getNode(); 5053 Equal = true; 5054 } 5055 5056 SDValue NodeToReplace = Trunc ? SDValue(Trunc, 0) : N1; 5057 5058 EVT SetCCVT = NodeToReplace.getValueType(); 5059 if (LegalTypes) 5060 SetCCVT = TLI.getSetCCResultType(SetCCVT); 5061 SDValue SetCC = DAG.getSetCC(TheXor->getDebugLoc(), 5062 SetCCVT, 5063 Op0, Op1, 5064 Equal ? ISD::SETEQ : ISD::SETNE); 5065 // Replace the uses of XOR with SETCC 5066 WorkListRemover DeadNodes(*this); 5067 DAG.ReplaceAllUsesOfValueWith(NodeToReplace, SetCC, &DeadNodes); 5068 removeFromWorkList(NodeToReplace.getNode()); 5069 DAG.DeleteNode(NodeToReplace.getNode()); 5070 return DAG.getNode(ISD::BRCOND, N->getDebugLoc(), 5071 MVT::Other, Chain, SetCC, N2); 5072 } 5073 } 5074 5075 return SDValue(); 5076 } 5077 5078 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB. 5079 // 5080 SDValue DAGCombiner::visitBR_CC(SDNode *N) { 5081 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1)); 5082 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3); 5083 5084 // If N is a constant we could fold this into a fallthrough or unconditional 5085 // branch. However that doesn't happen very often in normal code, because 5086 // Instcombine/SimplifyCFG should have handled the available opportunities. 5087 // If we did this folding here, it would be necessary to update the 5088 // MachineBasicBlock CFG, which is awkward. 5089 5090 // Use SimplifySetCC to simplify SETCC's. 5091 SDValue Simp = SimplifySetCC(TLI.getSetCCResultType(CondLHS.getValueType()), 5092 CondLHS, CondRHS, CC->get(), N->getDebugLoc(), 5093 false); 5094 if (Simp.getNode()) AddToWorkList(Simp.getNode()); 5095 5096 // fold to a simpler setcc 5097 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC) 5098 return DAG.getNode(ISD::BR_CC, N->getDebugLoc(), MVT::Other, 5099 N->getOperand(0), Simp.getOperand(2), 5100 Simp.getOperand(0), Simp.getOperand(1), 5101 N->getOperand(4)); 5102 5103 return SDValue(); 5104 } 5105 5106 /// CombineToPreIndexedLoadStore - Try turning a load / store into a 5107 /// pre-indexed load / store when the base pointer is an add or subtract 5108 /// and it has other uses besides the load / store. After the 5109 /// transformation, the new indexed load / store has effectively folded 5110 /// the add / subtract in and all of its other uses are redirected to the 5111 /// new load / store. 5112 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) { 5113 if (!LegalOperations) 5114 return false; 5115 5116 bool isLoad = true; 5117 SDValue Ptr; 5118 EVT VT; 5119 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 5120 if (LD->isIndexed()) 5121 return false; 5122 VT = LD->getMemoryVT(); 5123 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) && 5124 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT)) 5125 return false; 5126 Ptr = LD->getBasePtr(); 5127 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 5128 if (ST->isIndexed()) 5129 return false; 5130 VT = ST->getMemoryVT(); 5131 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) && 5132 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT)) 5133 return false; 5134 Ptr = ST->getBasePtr(); 5135 isLoad = false; 5136 } else { 5137 return false; 5138 } 5139 5140 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail 5141 // out. There is no reason to make this a preinc/predec. 5142 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) || 5143 Ptr.getNode()->hasOneUse()) 5144 return false; 5145 5146 // Ask the target to do addressing mode selection. 5147 SDValue BasePtr; 5148 SDValue Offset; 5149 ISD::MemIndexedMode AM = ISD::UNINDEXED; 5150 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG)) 5151 return false; 5152 // Don't create a indexed load / store with zero offset. 5153 if (isa<ConstantSDNode>(Offset) && 5154 cast<ConstantSDNode>(Offset)->isNullValue()) 5155 return false; 5156 5157 // Try turning it into a pre-indexed load / store except when: 5158 // 1) The new base ptr is a frame index. 5159 // 2) If N is a store and the new base ptr is either the same as or is a 5160 // predecessor of the value being stored. 5161 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded 5162 // that would create a cycle. 5163 // 4) All uses are load / store ops that use it as old base ptr. 5164 5165 // Check #1. Preinc'ing a frame index would require copying the stack pointer 5166 // (plus the implicit offset) to a register to preinc anyway. 5167 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr)) 5168 return false; 5169 5170 // Check #2. 5171 if (!isLoad) { 5172 SDValue Val = cast<StoreSDNode>(N)->getValue(); 5173 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode())) 5174 return false; 5175 } 5176 5177 // Now check for #3 and #4. 5178 bool RealUse = false; 5179 for (SDNode::use_iterator I = Ptr.getNode()->use_begin(), 5180 E = Ptr.getNode()->use_end(); I != E; ++I) { 5181 SDNode *Use = *I; 5182 if (Use == N) 5183 continue; 5184 if (Use->isPredecessorOf(N)) 5185 return false; 5186 5187 if (!((Use->getOpcode() == ISD::LOAD && 5188 cast<LoadSDNode>(Use)->getBasePtr() == Ptr) || 5189 (Use->getOpcode() == ISD::STORE && 5190 cast<StoreSDNode>(Use)->getBasePtr() == Ptr))) 5191 RealUse = true; 5192 } 5193 5194 if (!RealUse) 5195 return false; 5196 5197 SDValue Result; 5198 if (isLoad) 5199 Result = DAG.getIndexedLoad(SDValue(N,0), N->getDebugLoc(), 5200 BasePtr, Offset, AM); 5201 else 5202 Result = DAG.getIndexedStore(SDValue(N,0), N->getDebugLoc(), 5203 BasePtr, Offset, AM); 5204 ++PreIndexedNodes; 5205 ++NodesCombined; 5206 DEBUG(dbgs() << "\nReplacing.4 "; 5207 N->dump(&DAG); 5208 dbgs() << "\nWith: "; 5209 Result.getNode()->dump(&DAG); 5210 dbgs() << '\n'); 5211 WorkListRemover DeadNodes(*this); 5212 if (isLoad) { 5213 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0), 5214 &DeadNodes); 5215 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2), 5216 &DeadNodes); 5217 } else { 5218 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1), 5219 &DeadNodes); 5220 } 5221 5222 // Finally, since the node is now dead, remove it from the graph. 5223 DAG.DeleteNode(N); 5224 5225 // Replace the uses of Ptr with uses of the updated base value. 5226 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0), 5227 &DeadNodes); 5228 removeFromWorkList(Ptr.getNode()); 5229 DAG.DeleteNode(Ptr.getNode()); 5230 5231 return true; 5232 } 5233 5234 /// CombineToPostIndexedLoadStore - Try to combine a load / store with a 5235 /// add / sub of the base pointer node into a post-indexed load / store. 5236 /// The transformation folded the add / subtract into the new indexed 5237 /// load / store effectively and all of its uses are redirected to the 5238 /// new load / store. 5239 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) { 5240 if (!LegalOperations) 5241 return false; 5242 5243 bool isLoad = true; 5244 SDValue Ptr; 5245 EVT VT; 5246 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 5247 if (LD->isIndexed()) 5248 return false; 5249 VT = LD->getMemoryVT(); 5250 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) && 5251 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT)) 5252 return false; 5253 Ptr = LD->getBasePtr(); 5254 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 5255 if (ST->isIndexed()) 5256 return false; 5257 VT = ST->getMemoryVT(); 5258 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) && 5259 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT)) 5260 return false; 5261 Ptr = ST->getBasePtr(); 5262 isLoad = false; 5263 } else { 5264 return false; 5265 } 5266 5267 if (Ptr.getNode()->hasOneUse()) 5268 return false; 5269 5270 for (SDNode::use_iterator I = Ptr.getNode()->use_begin(), 5271 E = Ptr.getNode()->use_end(); I != E; ++I) { 5272 SDNode *Op = *I; 5273 if (Op == N || 5274 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB)) 5275 continue; 5276 5277 SDValue BasePtr; 5278 SDValue Offset; 5279 ISD::MemIndexedMode AM = ISD::UNINDEXED; 5280 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) { 5281 if (Ptr == Offset && Op->getOpcode() == ISD::ADD) 5282 std::swap(BasePtr, Offset); 5283 if (Ptr != BasePtr) 5284 continue; 5285 // Don't create a indexed load / store with zero offset. 5286 if (isa<ConstantSDNode>(Offset) && 5287 cast<ConstantSDNode>(Offset)->isNullValue()) 5288 continue; 5289 5290 // Try turning it into a post-indexed load / store except when 5291 // 1) All uses are load / store ops that use it as base ptr. 5292 // 2) Op must be independent of N, i.e. Op is neither a predecessor 5293 // nor a successor of N. Otherwise, if Op is folded that would 5294 // create a cycle. 5295 5296 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr)) 5297 continue; 5298 5299 // Check for #1. 5300 bool TryNext = false; 5301 for (SDNode::use_iterator II = BasePtr.getNode()->use_begin(), 5302 EE = BasePtr.getNode()->use_end(); II != EE; ++II) { 5303 SDNode *Use = *II; 5304 if (Use == Ptr.getNode()) 5305 continue; 5306 5307 // If all the uses are load / store addresses, then don't do the 5308 // transformation. 5309 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){ 5310 bool RealUse = false; 5311 for (SDNode::use_iterator III = Use->use_begin(), 5312 EEE = Use->use_end(); III != EEE; ++III) { 5313 SDNode *UseUse = *III; 5314 if (!((UseUse->getOpcode() == ISD::LOAD && 5315 cast<LoadSDNode>(UseUse)->getBasePtr().getNode() == Use) || 5316 (UseUse->getOpcode() == ISD::STORE && 5317 cast<StoreSDNode>(UseUse)->getBasePtr().getNode() == Use))) 5318 RealUse = true; 5319 } 5320 5321 if (!RealUse) { 5322 TryNext = true; 5323 break; 5324 } 5325 } 5326 } 5327 5328 if (TryNext) 5329 continue; 5330 5331 // Check for #2 5332 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) { 5333 SDValue Result = isLoad 5334 ? DAG.getIndexedLoad(SDValue(N,0), N->getDebugLoc(), 5335 BasePtr, Offset, AM) 5336 : DAG.getIndexedStore(SDValue(N,0), N->getDebugLoc(), 5337 BasePtr, Offset, AM); 5338 ++PostIndexedNodes; 5339 ++NodesCombined; 5340 DEBUG(dbgs() << "\nReplacing.5 "; 5341 N->dump(&DAG); 5342 dbgs() << "\nWith: "; 5343 Result.getNode()->dump(&DAG); 5344 dbgs() << '\n'); 5345 WorkListRemover DeadNodes(*this); 5346 if (isLoad) { 5347 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0), 5348 &DeadNodes); 5349 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2), 5350 &DeadNodes); 5351 } else { 5352 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1), 5353 &DeadNodes); 5354 } 5355 5356 // Finally, since the node is now dead, remove it from the graph. 5357 DAG.DeleteNode(N); 5358 5359 // Replace the uses of Use with uses of the updated base value. 5360 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0), 5361 Result.getValue(isLoad ? 1 : 0), 5362 &DeadNodes); 5363 removeFromWorkList(Op); 5364 DAG.DeleteNode(Op); 5365 return true; 5366 } 5367 } 5368 } 5369 5370 return false; 5371 } 5372 5373 SDValue DAGCombiner::visitLOAD(SDNode *N) { 5374 LoadSDNode *LD = cast<LoadSDNode>(N); 5375 SDValue Chain = LD->getChain(); 5376 SDValue Ptr = LD->getBasePtr(); 5377 5378 // If load is not volatile and there are no uses of the loaded value (and 5379 // the updated indexed value in case of indexed loads), change uses of the 5380 // chain value into uses of the chain input (i.e. delete the dead load). 5381 if (!LD->isVolatile()) { 5382 if (N->getValueType(1) == MVT::Other) { 5383 // Unindexed loads. 5384 if (N->hasNUsesOfValue(0, 0)) { 5385 // It's not safe to use the two value CombineTo variant here. e.g. 5386 // v1, chain2 = load chain1, loc 5387 // v2, chain3 = load chain2, loc 5388 // v3 = add v2, c 5389 // Now we replace use of chain2 with chain1. This makes the second load 5390 // isomorphic to the one we are deleting, and thus makes this load live. 5391 DEBUG(dbgs() << "\nReplacing.6 "; 5392 N->dump(&DAG); 5393 dbgs() << "\nWith chain: "; 5394 Chain.getNode()->dump(&DAG); 5395 dbgs() << "\n"); 5396 WorkListRemover DeadNodes(*this); 5397 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain, &DeadNodes); 5398 5399 if (N->use_empty()) { 5400 removeFromWorkList(N); 5401 DAG.DeleteNode(N); 5402 } 5403 5404 return SDValue(N, 0); // Return N so it doesn't get rechecked! 5405 } 5406 } else { 5407 // Indexed loads. 5408 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?"); 5409 if (N->hasNUsesOfValue(0, 0) && N->hasNUsesOfValue(0, 1)) { 5410 SDValue Undef = DAG.getUNDEF(N->getValueType(0)); 5411 DEBUG(dbgs() << "\nReplacing.7 "; 5412 N->dump(&DAG); 5413 dbgs() << "\nWith: "; 5414 Undef.getNode()->dump(&DAG); 5415 dbgs() << " and 2 other values\n"); 5416 WorkListRemover DeadNodes(*this); 5417 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef, &DeadNodes); 5418 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), 5419 DAG.getUNDEF(N->getValueType(1)), 5420 &DeadNodes); 5421 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain, &DeadNodes); 5422 removeFromWorkList(N); 5423 DAG.DeleteNode(N); 5424 return SDValue(N, 0); // Return N so it doesn't get rechecked! 5425 } 5426 } 5427 } 5428 5429 // If this load is directly stored, replace the load value with the stored 5430 // value. 5431 // TODO: Handle store large -> read small portion. 5432 // TODO: Handle TRUNCSTORE/LOADEXT 5433 if (LD->getExtensionType() == ISD::NON_EXTLOAD && 5434 !LD->isVolatile()) { 5435 if (ISD::isNON_TRUNCStore(Chain.getNode())) { 5436 StoreSDNode *PrevST = cast<StoreSDNode>(Chain); 5437 if (PrevST->getBasePtr() == Ptr && 5438 PrevST->getValue().getValueType() == N->getValueType(0)) 5439 return CombineTo(N, Chain.getOperand(1), Chain); 5440 } 5441 } 5442 5443 // Try to infer better alignment information than the load already has. 5444 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) { 5445 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) { 5446 if (Align > LD->getAlignment()) 5447 return DAG.getExtLoad(LD->getExtensionType(), N->getDebugLoc(), 5448 LD->getValueType(0), 5449 Chain, Ptr, LD->getSrcValue(), 5450 LD->getSrcValueOffset(), LD->getMemoryVT(), 5451 LD->isVolatile(), LD->isNonTemporal(), Align); 5452 } 5453 } 5454 5455 if (CombinerAA) { 5456 // Walk up chain skipping non-aliasing memory nodes. 5457 SDValue BetterChain = FindBetterChain(N, Chain); 5458 5459 // If there is a better chain. 5460 if (Chain != BetterChain) { 5461 SDValue ReplLoad; 5462 5463 // Replace the chain to void dependency. 5464 if (LD->getExtensionType() == ISD::NON_EXTLOAD) { 5465 ReplLoad = DAG.getLoad(N->getValueType(0), LD->getDebugLoc(), 5466 BetterChain, Ptr, 5467 LD->getSrcValue(), LD->getSrcValueOffset(), 5468 LD->isVolatile(), LD->isNonTemporal(), 5469 LD->getAlignment()); 5470 } else { 5471 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), LD->getDebugLoc(), 5472 LD->getValueType(0), 5473 BetterChain, Ptr, LD->getSrcValue(), 5474 LD->getSrcValueOffset(), 5475 LD->getMemoryVT(), 5476 LD->isVolatile(), 5477 LD->isNonTemporal(), 5478 LD->getAlignment()); 5479 } 5480 5481 // Create token factor to keep old chain connected. 5482 SDValue Token = DAG.getNode(ISD::TokenFactor, N->getDebugLoc(), 5483 MVT::Other, Chain, ReplLoad.getValue(1)); 5484 5485 // Make sure the new and old chains are cleaned up. 5486 AddToWorkList(Token.getNode()); 5487 5488 // Replace uses with load result and token factor. Don't add users 5489 // to work list. 5490 return CombineTo(N, ReplLoad.getValue(0), Token, false); 5491 } 5492 } 5493 5494 // Try transforming N to an indexed load. 5495 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N)) 5496 return SDValue(N, 0); 5497 5498 return SDValue(); 5499 } 5500 5501 /// CheckForMaskedLoad - Check to see if V is (and load (ptr), imm), where the 5502 /// load is having specific bytes cleared out. If so, return the byte size 5503 /// being masked out and the shift amount. 5504 static std::pair<unsigned, unsigned> 5505 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) { 5506 std::pair<unsigned, unsigned> Result(0, 0); 5507 5508 // Check for the structure we're looking for. 5509 if (V->getOpcode() != ISD::AND || 5510 !isa<ConstantSDNode>(V->getOperand(1)) || 5511 !ISD::isNormalLoad(V->getOperand(0).getNode())) 5512 return Result; 5513 5514 // Check the chain and pointer. 5515 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0)); 5516 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer. 5517 5518 // The store should be chained directly to the load or be an operand of a 5519 // tokenfactor. 5520 if (LD == Chain.getNode()) 5521 ; // ok. 5522 else if (Chain->getOpcode() != ISD::TokenFactor) 5523 return Result; // Fail. 5524 else { 5525 bool isOk = false; 5526 for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i) 5527 if (Chain->getOperand(i).getNode() == LD) { 5528 isOk = true; 5529 break; 5530 } 5531 if (!isOk) return Result; 5532 } 5533 5534 // This only handles simple types. 5535 if (V.getValueType() != MVT::i16 && 5536 V.getValueType() != MVT::i32 && 5537 V.getValueType() != MVT::i64) 5538 return Result; 5539 5540 // Check the constant mask. Invert it so that the bits being masked out are 5541 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits 5542 // follow the sign bit for uniformity. 5543 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue(); 5544 unsigned NotMaskLZ = CountLeadingZeros_64(NotMask); 5545 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte. 5546 unsigned NotMaskTZ = CountTrailingZeros_64(NotMask); 5547 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte. 5548 if (NotMaskLZ == 64) return Result; // All zero mask. 5549 5550 // See if we have a continuous run of bits. If so, we have 0*1+0* 5551 if (CountTrailingOnes_64(NotMask >> NotMaskTZ)+NotMaskTZ+NotMaskLZ != 64) 5552 return Result; 5553 5554 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64. 5555 if (V.getValueType() != MVT::i64 && NotMaskLZ) 5556 NotMaskLZ -= 64-V.getValueSizeInBits(); 5557 5558 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8; 5559 switch (MaskedBytes) { 5560 case 1: 5561 case 2: 5562 case 4: break; 5563 default: return Result; // All one mask, or 5-byte mask. 5564 } 5565 5566 // Verify that the first bit starts at a multiple of mask so that the access 5567 // is aligned the same as the access width. 5568 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result; 5569 5570 Result.first = MaskedBytes; 5571 Result.second = NotMaskTZ/8; 5572 return Result; 5573 } 5574 5575 5576 /// ShrinkLoadReplaceStoreWithStore - Check to see if IVal is something that 5577 /// provides a value as specified by MaskInfo. If so, replace the specified 5578 /// store with a narrower store of truncated IVal. 5579 static SDNode * 5580 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo, 5581 SDValue IVal, StoreSDNode *St, 5582 DAGCombiner *DC) { 5583 unsigned NumBytes = MaskInfo.first; 5584 unsigned ByteShift = MaskInfo.second; 5585 SelectionDAG &DAG = DC->getDAG(); 5586 5587 // Check to see if IVal is all zeros in the part being masked in by the 'or' 5588 // that uses this. If not, this is not a replacement. 5589 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(), 5590 ByteShift*8, (ByteShift+NumBytes)*8); 5591 if (!DAG.MaskedValueIsZero(IVal, Mask)) return 0; 5592 5593 // Check that it is legal on the target to do this. It is legal if the new 5594 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type 5595 // legalization. 5596 MVT VT = MVT::getIntegerVT(NumBytes*8); 5597 if (!DC->isTypeLegal(VT)) 5598 return 0; 5599 5600 // Okay, we can do this! Replace the 'St' store with a store of IVal that is 5601 // shifted by ByteShift and truncated down to NumBytes. 5602 if (ByteShift) 5603 IVal = DAG.getNode(ISD::SRL, IVal->getDebugLoc(), IVal.getValueType(), IVal, 5604 DAG.getConstant(ByteShift*8, DC->getShiftAmountTy())); 5605 5606 // Figure out the offset for the store and the alignment of the access. 5607 unsigned StOffset; 5608 unsigned NewAlign = St->getAlignment(); 5609 5610 if (DAG.getTargetLoweringInfo().isLittleEndian()) 5611 StOffset = ByteShift; 5612 else 5613 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes; 5614 5615 SDValue Ptr = St->getBasePtr(); 5616 if (StOffset) { 5617 Ptr = DAG.getNode(ISD::ADD, IVal->getDebugLoc(), Ptr.getValueType(), 5618 Ptr, DAG.getConstant(StOffset, Ptr.getValueType())); 5619 NewAlign = MinAlign(NewAlign, StOffset); 5620 } 5621 5622 // Truncate down to the new size. 5623 IVal = DAG.getNode(ISD::TRUNCATE, IVal->getDebugLoc(), VT, IVal); 5624 5625 ++OpsNarrowed; 5626 return DAG.getStore(St->getChain(), St->getDebugLoc(), IVal, Ptr, 5627 St->getSrcValue(), St->getSrcValueOffset()+StOffset, 5628 false, false, NewAlign).getNode(); 5629 } 5630 5631 5632 /// ReduceLoadOpStoreWidth - Look for sequence of load / op / store where op is 5633 /// one of 'or', 'xor', and 'and' of immediates. If 'op' is only touching some 5634 /// of the loaded bits, try narrowing the load and store if it would end up 5635 /// being a win for performance or code size. 5636 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) { 5637 StoreSDNode *ST = cast<StoreSDNode>(N); 5638 if (ST->isVolatile()) 5639 return SDValue(); 5640 5641 SDValue Chain = ST->getChain(); 5642 SDValue Value = ST->getValue(); 5643 SDValue Ptr = ST->getBasePtr(); 5644 EVT VT = Value.getValueType(); 5645 5646 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse()) 5647 return SDValue(); 5648 5649 unsigned Opc = Value.getOpcode(); 5650 5651 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst 5652 // is a byte mask indicating a consecutive number of bytes, check to see if 5653 // Y is known to provide just those bytes. If so, we try to replace the 5654 // load + replace + store sequence with a single (narrower) store, which makes 5655 // the load dead. 5656 if (Opc == ISD::OR) { 5657 std::pair<unsigned, unsigned> MaskedLoad; 5658 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain); 5659 if (MaskedLoad.first) 5660 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad, 5661 Value.getOperand(1), ST,this)) 5662 return SDValue(NewST, 0); 5663 5664 // Or is commutative, so try swapping X and Y. 5665 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain); 5666 if (MaskedLoad.first) 5667 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad, 5668 Value.getOperand(0), ST,this)) 5669 return SDValue(NewST, 0); 5670 } 5671 5672 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) || 5673 Value.getOperand(1).getOpcode() != ISD::Constant) 5674 return SDValue(); 5675 5676 SDValue N0 = Value.getOperand(0); 5677 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse()) { 5678 LoadSDNode *LD = cast<LoadSDNode>(N0); 5679 if (LD->getBasePtr() != Ptr) 5680 return SDValue(); 5681 5682 // Find the type to narrow it the load / op / store to. 5683 SDValue N1 = Value.getOperand(1); 5684 unsigned BitWidth = N1.getValueSizeInBits(); 5685 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue(); 5686 if (Opc == ISD::AND) 5687 Imm ^= APInt::getAllOnesValue(BitWidth); 5688 if (Imm == 0 || Imm.isAllOnesValue()) 5689 return SDValue(); 5690 unsigned ShAmt = Imm.countTrailingZeros(); 5691 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1; 5692 unsigned NewBW = NextPowerOf2(MSB - ShAmt); 5693 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW); 5694 while (NewBW < BitWidth && 5695 !(TLI.isOperationLegalOrCustom(Opc, NewVT) && 5696 TLI.isNarrowingProfitable(VT, NewVT))) { 5697 NewBW = NextPowerOf2(NewBW); 5698 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW); 5699 } 5700 if (NewBW >= BitWidth) 5701 return SDValue(); 5702 5703 // If the lsb changed does not start at the type bitwidth boundary, 5704 // start at the previous one. 5705 if (ShAmt % NewBW) 5706 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW; 5707 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt, ShAmt + NewBW); 5708 if ((Imm & Mask) == Imm) { 5709 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW); 5710 if (Opc == ISD::AND) 5711 NewImm ^= APInt::getAllOnesValue(NewBW); 5712 uint64_t PtrOff = ShAmt / 8; 5713 // For big endian targets, we need to adjust the offset to the pointer to 5714 // load the correct bytes. 5715 if (TLI.isBigEndian()) 5716 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff; 5717 5718 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff); 5719 const Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext()); 5720 if (NewAlign < TLI.getTargetData()->getABITypeAlignment(NewVTTy)) 5721 return SDValue(); 5722 5723 SDValue NewPtr = DAG.getNode(ISD::ADD, LD->getDebugLoc(), 5724 Ptr.getValueType(), Ptr, 5725 DAG.getConstant(PtrOff, Ptr.getValueType())); 5726 SDValue NewLD = DAG.getLoad(NewVT, N0.getDebugLoc(), 5727 LD->getChain(), NewPtr, 5728 LD->getSrcValue(), LD->getSrcValueOffset(), 5729 LD->isVolatile(), LD->isNonTemporal(), 5730 NewAlign); 5731 SDValue NewVal = DAG.getNode(Opc, Value.getDebugLoc(), NewVT, NewLD, 5732 DAG.getConstant(NewImm, NewVT)); 5733 SDValue NewST = DAG.getStore(Chain, N->getDebugLoc(), 5734 NewVal, NewPtr, 5735 ST->getSrcValue(), ST->getSrcValueOffset(), 5736 false, false, NewAlign); 5737 5738 AddToWorkList(NewPtr.getNode()); 5739 AddToWorkList(NewLD.getNode()); 5740 AddToWorkList(NewVal.getNode()); 5741 WorkListRemover DeadNodes(*this); 5742 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1), 5743 &DeadNodes); 5744 ++OpsNarrowed; 5745 return NewST; 5746 } 5747 } 5748 5749 return SDValue(); 5750 } 5751 5752 SDValue DAGCombiner::visitSTORE(SDNode *N) { 5753 StoreSDNode *ST = cast<StoreSDNode>(N); 5754 SDValue Chain = ST->getChain(); 5755 SDValue Value = ST->getValue(); 5756 SDValue Ptr = ST->getBasePtr(); 5757 5758 // If this is a store of a bit convert, store the input value if the 5759 // resultant store does not need a higher alignment than the original. 5760 if (Value.getOpcode() == ISD::BIT_CONVERT && !ST->isTruncatingStore() && 5761 ST->isUnindexed()) { 5762 unsigned OrigAlign = ST->getAlignment(); 5763 EVT SVT = Value.getOperand(0).getValueType(); 5764 unsigned Align = TLI.getTargetData()-> 5765 getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext())); 5766 if (Align <= OrigAlign && 5767 ((!LegalOperations && !ST->isVolatile()) || 5768 TLI.isOperationLegalOrCustom(ISD::STORE, SVT))) 5769 return DAG.getStore(Chain, N->getDebugLoc(), Value.getOperand(0), 5770 Ptr, ST->getSrcValue(), 5771 ST->getSrcValueOffset(), ST->isVolatile(), 5772 ST->isNonTemporal(), OrigAlign); 5773 } 5774 5775 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr' 5776 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) { 5777 // NOTE: If the original store is volatile, this transform must not increase 5778 // the number of stores. For example, on x86-32 an f64 can be stored in one 5779 // processor operation but an i64 (which is not legal) requires two. So the 5780 // transform should not be done in this case. 5781 if (Value.getOpcode() != ISD::TargetConstantFP) { 5782 SDValue Tmp; 5783 switch (CFP->getValueType(0).getSimpleVT().SimpleTy) { 5784 default: llvm_unreachable("Unknown FP type"); 5785 case MVT::f80: // We don't do this for these yet. 5786 case MVT::f128: 5787 case MVT::ppcf128: 5788 break; 5789 case MVT::f32: 5790 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) || 5791 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) { 5792 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF(). 5793 bitcastToAPInt().getZExtValue(), MVT::i32); 5794 return DAG.getStore(Chain, N->getDebugLoc(), Tmp, 5795 Ptr, ST->getSrcValue(), 5796 ST->getSrcValueOffset(), ST->isVolatile(), 5797 ST->isNonTemporal(), ST->getAlignment()); 5798 } 5799 break; 5800 case MVT::f64: 5801 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations && 5802 !ST->isVolatile()) || 5803 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) { 5804 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt(). 5805 getZExtValue(), MVT::i64); 5806 return DAG.getStore(Chain, N->getDebugLoc(), Tmp, 5807 Ptr, ST->getSrcValue(), 5808 ST->getSrcValueOffset(), ST->isVolatile(), 5809 ST->isNonTemporal(), ST->getAlignment()); 5810 } else if (!ST->isVolatile() && 5811 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) { 5812 // Many FP stores are not made apparent until after legalize, e.g. for 5813 // argument passing. Since this is so common, custom legalize the 5814 // 64-bit integer store into two 32-bit stores. 5815 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue(); 5816 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32); 5817 SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32); 5818 if (TLI.isBigEndian()) std::swap(Lo, Hi); 5819 5820 int SVOffset = ST->getSrcValueOffset(); 5821 unsigned Alignment = ST->getAlignment(); 5822 bool isVolatile = ST->isVolatile(); 5823 bool isNonTemporal = ST->isNonTemporal(); 5824 5825 SDValue St0 = DAG.getStore(Chain, ST->getDebugLoc(), Lo, 5826 Ptr, ST->getSrcValue(), 5827 ST->getSrcValueOffset(), 5828 isVolatile, isNonTemporal, 5829 ST->getAlignment()); 5830 Ptr = DAG.getNode(ISD::ADD, N->getDebugLoc(), Ptr.getValueType(), Ptr, 5831 DAG.getConstant(4, Ptr.getValueType())); 5832 SVOffset += 4; 5833 Alignment = MinAlign(Alignment, 4U); 5834 SDValue St1 = DAG.getStore(Chain, ST->getDebugLoc(), Hi, 5835 Ptr, ST->getSrcValue(), 5836 SVOffset, isVolatile, isNonTemporal, 5837 Alignment); 5838 return DAG.getNode(ISD::TokenFactor, N->getDebugLoc(), MVT::Other, 5839 St0, St1); 5840 } 5841 5842 break; 5843 } 5844 } 5845 } 5846 5847 // Try to infer better alignment information than the store already has. 5848 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) { 5849 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) { 5850 if (Align > ST->getAlignment()) 5851 return DAG.getTruncStore(Chain, N->getDebugLoc(), Value, 5852 Ptr, ST->getSrcValue(), 5853 ST->getSrcValueOffset(), ST->getMemoryVT(), 5854 ST->isVolatile(), ST->isNonTemporal(), Align); 5855 } 5856 } 5857 5858 if (CombinerAA) { 5859 // Walk up chain skipping non-aliasing memory nodes. 5860 SDValue BetterChain = FindBetterChain(N, Chain); 5861 5862 // If there is a better chain. 5863 if (Chain != BetterChain) { 5864 SDValue ReplStore; 5865 5866 // Replace the chain to avoid dependency. 5867 if (ST->isTruncatingStore()) { 5868 ReplStore = DAG.getTruncStore(BetterChain, N->getDebugLoc(), Value, Ptr, 5869 ST->getSrcValue(),ST->getSrcValueOffset(), 5870 ST->getMemoryVT(), ST->isVolatile(), 5871 ST->isNonTemporal(), ST->getAlignment()); 5872 } else { 5873 ReplStore = DAG.getStore(BetterChain, N->getDebugLoc(), Value, Ptr, 5874 ST->getSrcValue(), ST->getSrcValueOffset(), 5875 ST->isVolatile(), ST->isNonTemporal(), 5876 ST->getAlignment()); 5877 } 5878 5879 // Create token to keep both nodes around. 5880 SDValue Token = DAG.getNode(ISD::TokenFactor, N->getDebugLoc(), 5881 MVT::Other, Chain, ReplStore); 5882 5883 // Make sure the new and old chains are cleaned up. 5884 AddToWorkList(Token.getNode()); 5885 5886 // Don't add users to work list. 5887 return CombineTo(N, Token, false); 5888 } 5889 } 5890 5891 // Try transforming N to an indexed store. 5892 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N)) 5893 return SDValue(N, 0); 5894 5895 // FIXME: is there such a thing as a truncating indexed store? 5896 if (ST->isTruncatingStore() && ST->isUnindexed() && 5897 Value.getValueType().isInteger()) { 5898 // See if we can simplify the input to this truncstore with knowledge that 5899 // only the low bits are being used. For example: 5900 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8" 5901 SDValue Shorter = 5902 GetDemandedBits(Value, 5903 APInt::getLowBitsSet(Value.getValueSizeInBits(), 5904 ST->getMemoryVT().getSizeInBits())); 5905 AddToWorkList(Value.getNode()); 5906 if (Shorter.getNode()) 5907 return DAG.getTruncStore(Chain, N->getDebugLoc(), Shorter, 5908 Ptr, ST->getSrcValue(), 5909 ST->getSrcValueOffset(), ST->getMemoryVT(), 5910 ST->isVolatile(), ST->isNonTemporal(), 5911 ST->getAlignment()); 5912 5913 // Otherwise, see if we can simplify the operation with 5914 // SimplifyDemandedBits, which only works if the value has a single use. 5915 if (SimplifyDemandedBits(Value, 5916 APInt::getLowBitsSet( 5917 Value.getValueType().getScalarType().getSizeInBits(), 5918 ST->getMemoryVT().getScalarType().getSizeInBits()))) 5919 return SDValue(N, 0); 5920 } 5921 5922 // If this is a load followed by a store to the same location, then the store 5923 // is dead/noop. 5924 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) { 5925 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() && 5926 ST->isUnindexed() && !ST->isVolatile() && 5927 // There can't be any side effects between the load and store, such as 5928 // a call or store. 5929 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) { 5930 // The store is dead, remove it. 5931 return Chain; 5932 } 5933 } 5934 5935 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a 5936 // truncating store. We can do this even if this is already a truncstore. 5937 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE) 5938 && Value.getNode()->hasOneUse() && ST->isUnindexed() && 5939 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(), 5940 ST->getMemoryVT())) { 5941 return DAG.getTruncStore(Chain, N->getDebugLoc(), Value.getOperand(0), 5942 Ptr, ST->getSrcValue(), 5943 ST->getSrcValueOffset(), ST->getMemoryVT(), 5944 ST->isVolatile(), ST->isNonTemporal(), 5945 ST->getAlignment()); 5946 } 5947 5948 return ReduceLoadOpStoreWidth(N); 5949 } 5950 5951 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) { 5952 SDValue InVec = N->getOperand(0); 5953 SDValue InVal = N->getOperand(1); 5954 SDValue EltNo = N->getOperand(2); 5955 5956 // If the invec is a BUILD_VECTOR and if EltNo is a constant, build a new 5957 // vector with the inserted element. 5958 if (InVec.getOpcode() == ISD::BUILD_VECTOR && isa<ConstantSDNode>(EltNo)) { 5959 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue(); 5960 SmallVector<SDValue, 8> Ops(InVec.getNode()->op_begin(), 5961 InVec.getNode()->op_end()); 5962 if (Elt < Ops.size()) 5963 Ops[Elt] = InVal; 5964 return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(), 5965 InVec.getValueType(), &Ops[0], Ops.size()); 5966 } 5967 // If the invec is an UNDEF and if EltNo is a constant, create a new 5968 // BUILD_VECTOR with undef elements and the inserted element. 5969 if (!LegalOperations && InVec.getOpcode() == ISD::UNDEF && 5970 isa<ConstantSDNode>(EltNo)) { 5971 EVT VT = InVec.getValueType(); 5972 EVT EltVT = VT.getVectorElementType(); 5973 unsigned NElts = VT.getVectorNumElements(); 5974 SmallVector<SDValue, 8> Ops(NElts, DAG.getUNDEF(EltVT)); 5975 5976 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue(); 5977 if (Elt < Ops.size()) 5978 Ops[Elt] = InVal; 5979 return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(), 5980 InVec.getValueType(), &Ops[0], Ops.size()); 5981 } 5982 return SDValue(); 5983 } 5984 5985 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) { 5986 // (vextract (scalar_to_vector val, 0) -> val 5987 SDValue InVec = N->getOperand(0); 5988 5989 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) { 5990 // Check if the result type doesn't match the inserted element type. A 5991 // SCALAR_TO_VECTOR may truncate the inserted element and the 5992 // EXTRACT_VECTOR_ELT may widen the extracted vector. 5993 EVT EltVT = InVec.getValueType().getVectorElementType(); 5994 SDValue InOp = InVec.getOperand(0); 5995 EVT NVT = N->getValueType(0); 5996 if (InOp.getValueType() != NVT) { 5997 assert(InOp.getValueType().isInteger() && NVT.isInteger()); 5998 return DAG.getSExtOrTrunc(InOp, InVec.getDebugLoc(), NVT); 5999 } 6000 return InOp; 6001 } 6002 6003 // Perform only after legalization to ensure build_vector / vector_shuffle 6004 // optimizations have already been done. 6005 if (!LegalOperations) return SDValue(); 6006 6007 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size) 6008 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size) 6009 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr) 6010 SDValue EltNo = N->getOperand(1); 6011 6012 if (isa<ConstantSDNode>(EltNo)) { 6013 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue(); 6014 bool NewLoad = false; 6015 bool BCNumEltsChanged = false; 6016 EVT VT = InVec.getValueType(); 6017 EVT ExtVT = VT.getVectorElementType(); 6018 EVT LVT = ExtVT; 6019 6020 if (InVec.getOpcode() == ISD::BIT_CONVERT) { 6021 EVT BCVT = InVec.getOperand(0).getValueType(); 6022 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType())) 6023 return SDValue(); 6024 if (VT.getVectorNumElements() != BCVT.getVectorNumElements()) 6025 BCNumEltsChanged = true; 6026 InVec = InVec.getOperand(0); 6027 ExtVT = BCVT.getVectorElementType(); 6028 NewLoad = true; 6029 } 6030 6031 LoadSDNode *LN0 = NULL; 6032 const ShuffleVectorSDNode *SVN = NULL; 6033 if (ISD::isNormalLoad(InVec.getNode())) { 6034 LN0 = cast<LoadSDNode>(InVec); 6035 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR && 6036 InVec.getOperand(0).getValueType() == ExtVT && 6037 ISD::isNormalLoad(InVec.getOperand(0).getNode())) { 6038 LN0 = cast<LoadSDNode>(InVec.getOperand(0)); 6039 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) { 6040 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1) 6041 // => 6042 // (load $addr+1*size) 6043 6044 // If the bit convert changed the number of elements, it is unsafe 6045 // to examine the mask. 6046 if (BCNumEltsChanged) 6047 return SDValue(); 6048 6049 // Select the input vector, guarding against out of range extract vector. 6050 unsigned NumElems = VT.getVectorNumElements(); 6051 int Idx = (Elt > NumElems) ? -1 : SVN->getMaskElt(Elt); 6052 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1); 6053 6054 if (InVec.getOpcode() == ISD::BIT_CONVERT) 6055 InVec = InVec.getOperand(0); 6056 if (ISD::isNormalLoad(InVec.getNode())) { 6057 LN0 = cast<LoadSDNode>(InVec); 6058 Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems; 6059 } 6060 } 6061 6062 if (!LN0 || !LN0->hasOneUse() || LN0->isVolatile()) 6063 return SDValue(); 6064 6065 unsigned Align = LN0->getAlignment(); 6066 if (NewLoad) { 6067 // Check the resultant load doesn't need a higher alignment than the 6068 // original load. 6069 unsigned NewAlign = 6070 TLI.getTargetData()->getABITypeAlignment(LVT.getTypeForEVT(*DAG.getContext())); 6071 6072 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, LVT)) 6073 return SDValue(); 6074 6075 Align = NewAlign; 6076 } 6077 6078 SDValue NewPtr = LN0->getBasePtr(); 6079 if (Elt) { 6080 unsigned PtrOff = LVT.getSizeInBits() * Elt / 8; 6081 EVT PtrType = NewPtr.getValueType(); 6082 if (TLI.isBigEndian()) 6083 PtrOff = VT.getSizeInBits() / 8 - PtrOff; 6084 NewPtr = DAG.getNode(ISD::ADD, N->getDebugLoc(), PtrType, NewPtr, 6085 DAG.getConstant(PtrOff, PtrType)); 6086 } 6087 6088 return DAG.getLoad(LVT, N->getDebugLoc(), LN0->getChain(), NewPtr, 6089 LN0->getSrcValue(), LN0->getSrcValueOffset(), 6090 LN0->isVolatile(), LN0->isNonTemporal(), Align); 6091 } 6092 6093 return SDValue(); 6094 } 6095 6096 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) { 6097 unsigned NumInScalars = N->getNumOperands(); 6098 EVT VT = N->getValueType(0); 6099 6100 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT 6101 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from 6102 // at most two distinct vectors, turn this into a shuffle node. 6103 SDValue VecIn1, VecIn2; 6104 for (unsigned i = 0; i != NumInScalars; ++i) { 6105 // Ignore undef inputs. 6106 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue; 6107 6108 // If this input is something other than a EXTRACT_VECTOR_ELT with a 6109 // constant index, bail out. 6110 if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT || 6111 !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) { 6112 VecIn1 = VecIn2 = SDValue(0, 0); 6113 break; 6114 } 6115 6116 // If the input vector type disagrees with the result of the build_vector, 6117 // we can't make a shuffle. 6118 SDValue ExtractedFromVec = N->getOperand(i).getOperand(0); 6119 if (ExtractedFromVec.getValueType() != VT) { 6120 VecIn1 = VecIn2 = SDValue(0, 0); 6121 break; 6122 } 6123 6124 // Otherwise, remember this. We allow up to two distinct input vectors. 6125 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2) 6126 continue; 6127 6128 if (VecIn1.getNode() == 0) { 6129 VecIn1 = ExtractedFromVec; 6130 } else if (VecIn2.getNode() == 0) { 6131 VecIn2 = ExtractedFromVec; 6132 } else { 6133 // Too many inputs. 6134 VecIn1 = VecIn2 = SDValue(0, 0); 6135 break; 6136 } 6137 } 6138 6139 // If everything is good, we can make a shuffle operation. 6140 if (VecIn1.getNode()) { 6141 SmallVector<int, 8> Mask; 6142 for (unsigned i = 0; i != NumInScalars; ++i) { 6143 if (N->getOperand(i).getOpcode() == ISD::UNDEF) { 6144 Mask.push_back(-1); 6145 continue; 6146 } 6147 6148 // If extracting from the first vector, just use the index directly. 6149 SDValue Extract = N->getOperand(i); 6150 SDValue ExtVal = Extract.getOperand(1); 6151 if (Extract.getOperand(0) == VecIn1) { 6152 unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue(); 6153 if (ExtIndex > VT.getVectorNumElements()) 6154 return SDValue(); 6155 6156 Mask.push_back(ExtIndex); 6157 continue; 6158 } 6159 6160 // Otherwise, use InIdx + VecSize 6161 unsigned Idx = cast<ConstantSDNode>(ExtVal)->getZExtValue(); 6162 Mask.push_back(Idx+NumInScalars); 6163 } 6164 6165 // Add count and size info. 6166 if (!isTypeLegal(VT)) 6167 return SDValue(); 6168 6169 // Return the new VECTOR_SHUFFLE node. 6170 SDValue Ops[2]; 6171 Ops[0] = VecIn1; 6172 Ops[1] = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT); 6173 return DAG.getVectorShuffle(VT, N->getDebugLoc(), Ops[0], Ops[1], &Mask[0]); 6174 } 6175 6176 return SDValue(); 6177 } 6178 6179 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) { 6180 // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of 6181 // EXTRACT_SUBVECTOR operations. If so, and if the EXTRACT_SUBVECTOR vector 6182 // inputs come from at most two distinct vectors, turn this into a shuffle 6183 // node. 6184 6185 // If we only have one input vector, we don't need to do any concatenation. 6186 if (N->getNumOperands() == 1) 6187 return N->getOperand(0); 6188 6189 return SDValue(); 6190 } 6191 6192 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) { 6193 return SDValue(); 6194 6195 EVT VT = N->getValueType(0); 6196 unsigned NumElts = VT.getVectorNumElements(); 6197 6198 SDValue N0 = N->getOperand(0); 6199 6200 assert(N0.getValueType().getVectorNumElements() == NumElts && 6201 "Vector shuffle must be normalized in DAG"); 6202 6203 // FIXME: implement canonicalizations from DAG.getVectorShuffle() 6204 6205 // If it is a splat, check if the argument vector is a build_vector with 6206 // all scalar elements the same. 6207 if (cast<ShuffleVectorSDNode>(N)->isSplat()) { 6208 SDNode *V = N0.getNode(); 6209 6210 6211 // If this is a bit convert that changes the element type of the vector but 6212 // not the number of vector elements, look through it. Be careful not to 6213 // look though conversions that change things like v4f32 to v2f64. 6214 if (V->getOpcode() == ISD::BIT_CONVERT) { 6215 SDValue ConvInput = V->getOperand(0); 6216 if (ConvInput.getValueType().isVector() && 6217 ConvInput.getValueType().getVectorNumElements() == NumElts) 6218 V = ConvInput.getNode(); 6219 } 6220 6221 if (V->getOpcode() == ISD::BUILD_VECTOR) { 6222 unsigned NumElems = V->getNumOperands(); 6223 unsigned BaseIdx = cast<ShuffleVectorSDNode>(N)->getSplatIndex(); 6224 if (NumElems > BaseIdx) { 6225 SDValue Base; 6226 bool AllSame = true; 6227 for (unsigned i = 0; i != NumElems; ++i) { 6228 if (V->getOperand(i).getOpcode() != ISD::UNDEF) { 6229 Base = V->getOperand(i); 6230 break; 6231 } 6232 } 6233 // Splat of <u, u, u, u>, return <u, u, u, u> 6234 if (!Base.getNode()) 6235 return N0; 6236 for (unsigned i = 0; i != NumElems; ++i) { 6237 if (V->getOperand(i) != Base) { 6238 AllSame = false; 6239 break; 6240 } 6241 } 6242 // Splat of <x, x, x, x>, return <x, x, x, x> 6243 if (AllSame) 6244 return N0; 6245 } 6246 } 6247 } 6248 return SDValue(); 6249 } 6250 6251 /// XformToShuffleWithZero - Returns a vector_shuffle if it able to transform 6252 /// an AND to a vector_shuffle with the destination vector and a zero vector. 6253 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==> 6254 /// vector_shuffle V, Zero, <0, 4, 2, 4> 6255 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) { 6256 EVT VT = N->getValueType(0); 6257 DebugLoc dl = N->getDebugLoc(); 6258 SDValue LHS = N->getOperand(0); 6259 SDValue RHS = N->getOperand(1); 6260 if (N->getOpcode() == ISD::AND) { 6261 if (RHS.getOpcode() == ISD::BIT_CONVERT) 6262 RHS = RHS.getOperand(0); 6263 if (RHS.getOpcode() == ISD::BUILD_VECTOR) { 6264 SmallVector<int, 8> Indices; 6265 unsigned NumElts = RHS.getNumOperands(); 6266 for (unsigned i = 0; i != NumElts; ++i) { 6267 SDValue Elt = RHS.getOperand(i); 6268 if (!isa<ConstantSDNode>(Elt)) 6269 return SDValue(); 6270 else if (cast<ConstantSDNode>(Elt)->isAllOnesValue()) 6271 Indices.push_back(i); 6272 else if (cast<ConstantSDNode>(Elt)->isNullValue()) 6273 Indices.push_back(NumElts); 6274 else 6275 return SDValue(); 6276 } 6277 6278 // Let's see if the target supports this vector_shuffle. 6279 EVT RVT = RHS.getValueType(); 6280 if (!TLI.isVectorClearMaskLegal(Indices, RVT)) 6281 return SDValue(); 6282 6283 // Return the new VECTOR_SHUFFLE node. 6284 EVT EltVT = RVT.getVectorElementType(); 6285 SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(), 6286 DAG.getConstant(0, EltVT)); 6287 SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(), 6288 RVT, &ZeroOps[0], ZeroOps.size()); 6289 LHS = DAG.getNode(ISD::BIT_CONVERT, dl, RVT, LHS); 6290 SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]); 6291 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Shuf); 6292 } 6293 } 6294 6295 return SDValue(); 6296 } 6297 6298 /// SimplifyVBinOp - Visit a binary vector operation, like ADD. 6299 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) { 6300 // After legalize, the target may be depending on adds and other 6301 // binary ops to provide legal ways to construct constants or other 6302 // things. Simplifying them may result in a loss of legality. 6303 if (LegalOperations) return SDValue(); 6304 6305 EVT VT = N->getValueType(0); 6306 assert(VT.isVector() && "SimplifyVBinOp only works on vectors!"); 6307 6308 EVT EltType = VT.getVectorElementType(); 6309 SDValue LHS = N->getOperand(0); 6310 SDValue RHS = N->getOperand(1); 6311 SDValue Shuffle = XformToShuffleWithZero(N); 6312 if (Shuffle.getNode()) return Shuffle; 6313 6314 // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold 6315 // this operation. 6316 if (LHS.getOpcode() == ISD::BUILD_VECTOR && 6317 RHS.getOpcode() == ISD::BUILD_VECTOR) { 6318 SmallVector<SDValue, 8> Ops; 6319 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) { 6320 SDValue LHSOp = LHS.getOperand(i); 6321 SDValue RHSOp = RHS.getOperand(i); 6322 // If these two elements can't be folded, bail out. 6323 if ((LHSOp.getOpcode() != ISD::UNDEF && 6324 LHSOp.getOpcode() != ISD::Constant && 6325 LHSOp.getOpcode() != ISD::ConstantFP) || 6326 (RHSOp.getOpcode() != ISD::UNDEF && 6327 RHSOp.getOpcode() != ISD::Constant && 6328 RHSOp.getOpcode() != ISD::ConstantFP)) 6329 break; 6330 6331 // Can't fold divide by zero. 6332 if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV || 6333 N->getOpcode() == ISD::FDIV) { 6334 if ((RHSOp.getOpcode() == ISD::Constant && 6335 cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) || 6336 (RHSOp.getOpcode() == ISD::ConstantFP && 6337 cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero())) 6338 break; 6339 } 6340 6341 Ops.push_back(DAG.getNode(N->getOpcode(), LHS.getDebugLoc(), 6342 EltType, LHSOp, RHSOp)); 6343 AddToWorkList(Ops.back().getNode()); 6344 assert((Ops.back().getOpcode() == ISD::UNDEF || 6345 Ops.back().getOpcode() == ISD::Constant || 6346 Ops.back().getOpcode() == ISD::ConstantFP) && 6347 "Scalar binop didn't fold!"); 6348 } 6349 6350 if (Ops.size() == LHS.getNumOperands()) { 6351 EVT VT = LHS.getValueType(); 6352 return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(), VT, 6353 &Ops[0], Ops.size()); 6354 } 6355 } 6356 6357 return SDValue(); 6358 } 6359 6360 SDValue DAGCombiner::SimplifySelect(DebugLoc DL, SDValue N0, 6361 SDValue N1, SDValue N2){ 6362 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!"); 6363 6364 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2, 6365 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 6366 6367 // If we got a simplified select_cc node back from SimplifySelectCC, then 6368 // break it down into a new SETCC node, and a new SELECT node, and then return 6369 // the SELECT node, since we were called with a SELECT node. 6370 if (SCC.getNode()) { 6371 // Check to see if we got a select_cc back (to turn into setcc/select). 6372 // Otherwise, just return whatever node we got back, like fabs. 6373 if (SCC.getOpcode() == ISD::SELECT_CC) { 6374 SDValue SETCC = DAG.getNode(ISD::SETCC, N0.getDebugLoc(), 6375 N0.getValueType(), 6376 SCC.getOperand(0), SCC.getOperand(1), 6377 SCC.getOperand(4)); 6378 AddToWorkList(SETCC.getNode()); 6379 return DAG.getNode(ISD::SELECT, SCC.getDebugLoc(), SCC.getValueType(), 6380 SCC.getOperand(2), SCC.getOperand(3), SETCC); 6381 } 6382 6383 return SCC; 6384 } 6385 return SDValue(); 6386 } 6387 6388 /// SimplifySelectOps - Given a SELECT or a SELECT_CC node, where LHS and RHS 6389 /// are the two values being selected between, see if we can simplify the 6390 /// select. Callers of this should assume that TheSelect is deleted if this 6391 /// returns true. As such, they should return the appropriate thing (e.g. the 6392 /// node) back to the top-level of the DAG combiner loop to avoid it being 6393 /// looked at. 6394 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS, 6395 SDValue RHS) { 6396 6397 // If this is a select from two identical things, try to pull the operation 6398 // through the select. 6399 if (LHS.getOpcode() == RHS.getOpcode() && LHS.hasOneUse() && RHS.hasOneUse()){ 6400 // If this is a load and the token chain is identical, replace the select 6401 // of two loads with a load through a select of the address to load from. 6402 // This triggers in things like "select bool X, 10.0, 123.0" after the FP 6403 // constants have been dropped into the constant pool. 6404 if (LHS.getOpcode() == ISD::LOAD && 6405 // Do not let this transformation reduce the number of volatile loads. 6406 !cast<LoadSDNode>(LHS)->isVolatile() && 6407 !cast<LoadSDNode>(RHS)->isVolatile() && 6408 // Token chains must be identical. 6409 LHS.getOperand(0) == RHS.getOperand(0)) { 6410 LoadSDNode *LLD = cast<LoadSDNode>(LHS); 6411 LoadSDNode *RLD = cast<LoadSDNode>(RHS); 6412 6413 // If this is an EXTLOAD, the VT's must match. 6414 if (LLD->getMemoryVT() == RLD->getMemoryVT()) { 6415 // FIXME: this discards src value information. This is 6416 // over-conservative. It would be beneficial to be able to remember 6417 // both potential memory locations. Since we are discarding 6418 // src value info, don't do the transformation if the memory 6419 // locations are not in the default address space. 6420 unsigned LLDAddrSpace = 0, RLDAddrSpace = 0; 6421 if (const Value *LLDVal = LLD->getMemOperand()->getValue()) { 6422 if (const PointerType *PT = dyn_cast<PointerType>(LLDVal->getType())) 6423 LLDAddrSpace = PT->getAddressSpace(); 6424 } 6425 if (const Value *RLDVal = RLD->getMemOperand()->getValue()) { 6426 if (const PointerType *PT = dyn_cast<PointerType>(RLDVal->getType())) 6427 RLDAddrSpace = PT->getAddressSpace(); 6428 } 6429 SDValue Addr; 6430 if (LLDAddrSpace == 0 && RLDAddrSpace == 0) { 6431 if (TheSelect->getOpcode() == ISD::SELECT) { 6432 // Check that the condition doesn't reach either load. If so, folding 6433 // this will induce a cycle into the DAG. 6434 if ((!LLD->hasAnyUseOfValue(1) || 6435 !LLD->isPredecessorOf(TheSelect->getOperand(0).getNode())) && 6436 (!RLD->hasAnyUseOfValue(1) || 6437 !RLD->isPredecessorOf(TheSelect->getOperand(0).getNode()))) { 6438 Addr = DAG.getNode(ISD::SELECT, TheSelect->getDebugLoc(), 6439 LLD->getBasePtr().getValueType(), 6440 TheSelect->getOperand(0), LLD->getBasePtr(), 6441 RLD->getBasePtr()); 6442 } 6443 } else { 6444 // Check that the condition doesn't reach either load. If so, folding 6445 // this will induce a cycle into the DAG. 6446 if ((!LLD->hasAnyUseOfValue(1) || 6447 (!LLD->isPredecessorOf(TheSelect->getOperand(0).getNode()) && 6448 !LLD->isPredecessorOf(TheSelect->getOperand(1).getNode()))) && 6449 (!RLD->hasAnyUseOfValue(1) || 6450 (!RLD->isPredecessorOf(TheSelect->getOperand(0).getNode()) && 6451 !RLD->isPredecessorOf(TheSelect->getOperand(1).getNode())))) { 6452 Addr = DAG.getNode(ISD::SELECT_CC, TheSelect->getDebugLoc(), 6453 LLD->getBasePtr().getValueType(), 6454 TheSelect->getOperand(0), 6455 TheSelect->getOperand(1), 6456 LLD->getBasePtr(), RLD->getBasePtr(), 6457 TheSelect->getOperand(4)); 6458 } 6459 } 6460 } 6461 6462 if (Addr.getNode()) { 6463 SDValue Load; 6464 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) { 6465 Load = DAG.getLoad(TheSelect->getValueType(0), 6466 TheSelect->getDebugLoc(), 6467 LLD->getChain(), 6468 Addr, 0, 0, 6469 LLD->isVolatile(), 6470 LLD->isNonTemporal(), 6471 LLD->getAlignment()); 6472 } else { 6473 Load = DAG.getExtLoad(LLD->getExtensionType(), 6474 TheSelect->getDebugLoc(), 6475 TheSelect->getValueType(0), 6476 LLD->getChain(), Addr, 0, 0, 6477 LLD->getMemoryVT(), 6478 LLD->isVolatile(), 6479 LLD->isNonTemporal(), 6480 LLD->getAlignment()); 6481 } 6482 6483 // Users of the select now use the result of the load. 6484 CombineTo(TheSelect, Load); 6485 6486 // Users of the old loads now use the new load's chain. We know the 6487 // old-load value is dead now. 6488 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1)); 6489 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1)); 6490 return true; 6491 } 6492 } 6493 } 6494 } 6495 6496 return false; 6497 } 6498 6499 /// SimplifySelectCC - Simplify an expression of the form (N0 cond N1) ? N2 : N3 6500 /// where 'cond' is the comparison specified by CC. 6501 SDValue DAGCombiner::SimplifySelectCC(DebugLoc DL, SDValue N0, SDValue N1, 6502 SDValue N2, SDValue N3, 6503 ISD::CondCode CC, bool NotExtCompare) { 6504 // (x ? y : y) -> y. 6505 if (N2 == N3) return N2; 6506 6507 EVT VT = N2.getValueType(); 6508 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode()); 6509 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode()); 6510 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode()); 6511 6512 // Determine if the condition we're dealing with is constant 6513 SDValue SCC = SimplifySetCC(TLI.getSetCCResultType(N0.getValueType()), 6514 N0, N1, CC, DL, false); 6515 if (SCC.getNode()) AddToWorkList(SCC.getNode()); 6516 ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode()); 6517 6518 // fold select_cc true, x, y -> x 6519 if (SCCC && !SCCC->isNullValue()) 6520 return N2; 6521 // fold select_cc false, x, y -> y 6522 if (SCCC && SCCC->isNullValue()) 6523 return N3; 6524 6525 // Check to see if we can simplify the select into an fabs node 6526 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) { 6527 // Allow either -0.0 or 0.0 6528 if (CFP->getValueAPF().isZero()) { 6529 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs 6530 if ((CC == ISD::SETGE || CC == ISD::SETGT) && 6531 N0 == N2 && N3.getOpcode() == ISD::FNEG && 6532 N2 == N3.getOperand(0)) 6533 return DAG.getNode(ISD::FABS, DL, VT, N0); 6534 6535 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs 6536 if ((CC == ISD::SETLT || CC == ISD::SETLE) && 6537 N0 == N3 && N2.getOpcode() == ISD::FNEG && 6538 N2.getOperand(0) == N3) 6539 return DAG.getNode(ISD::FABS, DL, VT, N3); 6540 } 6541 } 6542 6543 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)" 6544 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0 6545 // in it. This is a win when the constant is not otherwise available because 6546 // it replaces two constant pool loads with one. We only do this if the FP 6547 // type is known to be legal, because if it isn't, then we are before legalize 6548 // types an we want the other legalization to happen first (e.g. to avoid 6549 // messing with soft float) and if the ConstantFP is not legal, because if 6550 // it is legal, we may not need to store the FP constant in a constant pool. 6551 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2)) 6552 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) { 6553 if (TLI.isTypeLegal(N2.getValueType()) && 6554 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) != 6555 TargetLowering::Legal) && 6556 // If both constants have multiple uses, then we won't need to do an 6557 // extra load, they are likely around in registers for other users. 6558 (TV->hasOneUse() || FV->hasOneUse())) { 6559 Constant *Elts[] = { 6560 const_cast<ConstantFP*>(FV->getConstantFPValue()), 6561 const_cast<ConstantFP*>(TV->getConstantFPValue()) 6562 }; 6563 const Type *FPTy = Elts[0]->getType(); 6564 const TargetData &TD = *TLI.getTargetData(); 6565 6566 // Create a ConstantArray of the two constants. 6567 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts, 2); 6568 SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(), 6569 TD.getPrefTypeAlignment(FPTy)); 6570 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment(); 6571 6572 // Get the offsets to the 0 and 1 element of the array so that we can 6573 // select between them. 6574 SDValue Zero = DAG.getIntPtrConstant(0); 6575 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType()); 6576 SDValue One = DAG.getIntPtrConstant(EltSize); 6577 6578 SDValue Cond = DAG.getSetCC(DL, 6579 TLI.getSetCCResultType(N0.getValueType()), 6580 N0, N1, CC); 6581 SDValue CstOffset = DAG.getNode(ISD::SELECT, DL, Zero.getValueType(), 6582 Cond, One, Zero); 6583 CPIdx = DAG.getNode(ISD::ADD, DL, TLI.getPointerTy(), CPIdx, 6584 CstOffset); 6585 return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx, 6586 PseudoSourceValue::getConstantPool(), 0, false, 6587 false, Alignment); 6588 6589 } 6590 } 6591 6592 // Check to see if we can perform the "gzip trick", transforming 6593 // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A) 6594 if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT && 6595 N0.getValueType().isInteger() && 6596 N2.getValueType().isInteger() && 6597 (N1C->isNullValue() || // (a < 0) ? b : 0 6598 (N1C->getAPIntValue() == 1 && N0 == N2))) { // (a < 1) ? a : 0 6599 EVT XType = N0.getValueType(); 6600 EVT AType = N2.getValueType(); 6601 if (XType.bitsGE(AType)) { 6602 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a 6603 // single-bit constant. 6604 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) { 6605 unsigned ShCtV = N2C->getAPIntValue().logBase2(); 6606 ShCtV = XType.getSizeInBits()-ShCtV-1; 6607 SDValue ShCt = DAG.getConstant(ShCtV, getShiftAmountTy()); 6608 SDValue Shift = DAG.getNode(ISD::SRL, N0.getDebugLoc(), 6609 XType, N0, ShCt); 6610 AddToWorkList(Shift.getNode()); 6611 6612 if (XType.bitsGT(AType)) { 6613 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift); 6614 AddToWorkList(Shift.getNode()); 6615 } 6616 6617 return DAG.getNode(ISD::AND, DL, AType, Shift, N2); 6618 } 6619 6620 SDValue Shift = DAG.getNode(ISD::SRA, N0.getDebugLoc(), 6621 XType, N0, 6622 DAG.getConstant(XType.getSizeInBits()-1, 6623 getShiftAmountTy())); 6624 AddToWorkList(Shift.getNode()); 6625 6626 if (XType.bitsGT(AType)) { 6627 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift); 6628 AddToWorkList(Shift.getNode()); 6629 } 6630 6631 return DAG.getNode(ISD::AND, DL, AType, Shift, N2); 6632 } 6633 } 6634 6635 // fold select C, 16, 0 -> shl C, 4 6636 if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() && 6637 TLI.getBooleanContents() == TargetLowering::ZeroOrOneBooleanContent) { 6638 6639 // If the caller doesn't want us to simplify this into a zext of a compare, 6640 // don't do it. 6641 if (NotExtCompare && N2C->getAPIntValue() == 1) 6642 return SDValue(); 6643 6644 // Get a SetCC of the condition 6645 // FIXME: Should probably make sure that setcc is legal if we ever have a 6646 // target where it isn't. 6647 SDValue Temp, SCC; 6648 // cast from setcc result type to select result type 6649 if (LegalTypes) { 6650 SCC = DAG.getSetCC(DL, TLI.getSetCCResultType(N0.getValueType()), 6651 N0, N1, CC); 6652 if (N2.getValueType().bitsLT(SCC.getValueType())) 6653 Temp = DAG.getZeroExtendInReg(SCC, N2.getDebugLoc(), N2.getValueType()); 6654 else 6655 Temp = DAG.getNode(ISD::ZERO_EXTEND, N2.getDebugLoc(), 6656 N2.getValueType(), SCC); 6657 } else { 6658 SCC = DAG.getSetCC(N0.getDebugLoc(), MVT::i1, N0, N1, CC); 6659 Temp = DAG.getNode(ISD::ZERO_EXTEND, N2.getDebugLoc(), 6660 N2.getValueType(), SCC); 6661 } 6662 6663 AddToWorkList(SCC.getNode()); 6664 AddToWorkList(Temp.getNode()); 6665 6666 if (N2C->getAPIntValue() == 1) 6667 return Temp; 6668 6669 // shl setcc result by log2 n2c 6670 return DAG.getNode(ISD::SHL, DL, N2.getValueType(), Temp, 6671 DAG.getConstant(N2C->getAPIntValue().logBase2(), 6672 getShiftAmountTy())); 6673 } 6674 6675 // Check to see if this is the equivalent of setcc 6676 // FIXME: Turn all of these into setcc if setcc if setcc is legal 6677 // otherwise, go ahead with the folds. 6678 if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) { 6679 EVT XType = N0.getValueType(); 6680 if (!LegalOperations || 6681 TLI.isOperationLegal(ISD::SETCC, TLI.getSetCCResultType(XType))) { 6682 SDValue Res = DAG.getSetCC(DL, TLI.getSetCCResultType(XType), N0, N1, CC); 6683 if (Res.getValueType() != VT) 6684 Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res); 6685 return Res; 6686 } 6687 6688 // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X)))) 6689 if (N1C && N1C->isNullValue() && CC == ISD::SETEQ && 6690 (!LegalOperations || 6691 TLI.isOperationLegal(ISD::CTLZ, XType))) { 6692 SDValue Ctlz = DAG.getNode(ISD::CTLZ, N0.getDebugLoc(), XType, N0); 6693 return DAG.getNode(ISD::SRL, DL, XType, Ctlz, 6694 DAG.getConstant(Log2_32(XType.getSizeInBits()), 6695 getShiftAmountTy())); 6696 } 6697 // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1)) 6698 if (N1C && N1C->isNullValue() && CC == ISD::SETGT) { 6699 SDValue NegN0 = DAG.getNode(ISD::SUB, N0.getDebugLoc(), 6700 XType, DAG.getConstant(0, XType), N0); 6701 SDValue NotN0 = DAG.getNOT(N0.getDebugLoc(), N0, XType); 6702 return DAG.getNode(ISD::SRL, DL, XType, 6703 DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0), 6704 DAG.getConstant(XType.getSizeInBits()-1, 6705 getShiftAmountTy())); 6706 } 6707 // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1)) 6708 if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) { 6709 SDValue Sign = DAG.getNode(ISD::SRL, N0.getDebugLoc(), XType, N0, 6710 DAG.getConstant(XType.getSizeInBits()-1, 6711 getShiftAmountTy())); 6712 return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType)); 6713 } 6714 } 6715 6716 // Check to see if this is an integer abs. select_cc setl[te] X, 0, -X, X -> 6717 // Y = sra (X, size(X)-1); xor (add (X, Y), Y) 6718 if (N1C && N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE) && 6719 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1) && 6720 N2.getOperand(0) == N1 && N0.getValueType().isInteger()) { 6721 EVT XType = N0.getValueType(); 6722 SDValue Shift = DAG.getNode(ISD::SRA, N0.getDebugLoc(), XType, N0, 6723 DAG.getConstant(XType.getSizeInBits()-1, 6724 getShiftAmountTy())); 6725 SDValue Add = DAG.getNode(ISD::ADD, N0.getDebugLoc(), XType, 6726 N0, Shift); 6727 AddToWorkList(Shift.getNode()); 6728 AddToWorkList(Add.getNode()); 6729 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift); 6730 } 6731 // Check to see if this is an integer abs. select_cc setgt X, -1, X, -X -> 6732 // Y = sra (X, size(X)-1); xor (add (X, Y), Y) 6733 if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT && 6734 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1)) { 6735 if (ConstantSDNode *SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0))) { 6736 EVT XType = N0.getValueType(); 6737 if (SubC->isNullValue() && XType.isInteger()) { 6738 SDValue Shift = DAG.getNode(ISD::SRA, N0.getDebugLoc(), XType, 6739 N0, 6740 DAG.getConstant(XType.getSizeInBits()-1, 6741 getShiftAmountTy())); 6742 SDValue Add = DAG.getNode(ISD::ADD, N0.getDebugLoc(), 6743 XType, N0, Shift); 6744 AddToWorkList(Shift.getNode()); 6745 AddToWorkList(Add.getNode()); 6746 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift); 6747 } 6748 } 6749 } 6750 6751 return SDValue(); 6752 } 6753 6754 /// SimplifySetCC - This is a stub for TargetLowering::SimplifySetCC. 6755 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0, 6756 SDValue N1, ISD::CondCode Cond, 6757 DebugLoc DL, bool foldBooleans) { 6758 TargetLowering::DAGCombinerInfo 6759 DagCombineInfo(DAG, !LegalTypes, !LegalOperations, false, this); 6760 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL); 6761 } 6762 6763 /// BuildSDIVSequence - Given an ISD::SDIV node expressing a divide by constant, 6764 /// return a DAG expression to select that will generate the same value by 6765 /// multiplying by a magic number. See: 6766 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html> 6767 SDValue DAGCombiner::BuildSDIV(SDNode *N) { 6768 std::vector<SDNode*> Built; 6769 SDValue S = TLI.BuildSDIV(N, DAG, &Built); 6770 6771 for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end(); 6772 ii != ee; ++ii) 6773 AddToWorkList(*ii); 6774 return S; 6775 } 6776 6777 /// BuildUDIVSequence - Given an ISD::UDIV node expressing a divide by constant, 6778 /// return a DAG expression to select that will generate the same value by 6779 /// multiplying by a magic number. See: 6780 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html> 6781 SDValue DAGCombiner::BuildUDIV(SDNode *N) { 6782 std::vector<SDNode*> Built; 6783 SDValue S = TLI.BuildUDIV(N, DAG, &Built); 6784 6785 for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end(); 6786 ii != ee; ++ii) 6787 AddToWorkList(*ii); 6788 return S; 6789 } 6790 6791 /// FindBaseOffset - Return true if base is a frame index, which is known not 6792 // to alias with anything but itself. Provides base object and offset as results. 6793 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset, 6794 const GlobalValue *&GV, void *&CV) { 6795 // Assume it is a primitive operation. 6796 Base = Ptr; Offset = 0; GV = 0; CV = 0; 6797 6798 // If it's an adding a simple constant then integrate the offset. 6799 if (Base.getOpcode() == ISD::ADD) { 6800 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) { 6801 Base = Base.getOperand(0); 6802 Offset += C->getZExtValue(); 6803 } 6804 } 6805 6806 // Return the underlying GlobalValue, and update the Offset. Return false 6807 // for GlobalAddressSDNode since the same GlobalAddress may be represented 6808 // by multiple nodes with different offsets. 6809 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) { 6810 GV = G->getGlobal(); 6811 Offset += G->getOffset(); 6812 return false; 6813 } 6814 6815 // Return the underlying Constant value, and update the Offset. Return false 6816 // for ConstantSDNodes since the same constant pool entry may be represented 6817 // by multiple nodes with different offsets. 6818 if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) { 6819 CV = C->isMachineConstantPoolEntry() ? (void *)C->getMachineCPVal() 6820 : (void *)C->getConstVal(); 6821 Offset += C->getOffset(); 6822 return false; 6823 } 6824 // If it's any of the following then it can't alias with anything but itself. 6825 return isa<FrameIndexSDNode>(Base); 6826 } 6827 6828 /// isAlias - Return true if there is any possibility that the two addresses 6829 /// overlap. 6830 bool DAGCombiner::isAlias(SDValue Ptr1, int64_t Size1, 6831 const Value *SrcValue1, int SrcValueOffset1, 6832 unsigned SrcValueAlign1, 6833 SDValue Ptr2, int64_t Size2, 6834 const Value *SrcValue2, int SrcValueOffset2, 6835 unsigned SrcValueAlign2) const { 6836 // If they are the same then they must be aliases. 6837 if (Ptr1 == Ptr2) return true; 6838 6839 // Gather base node and offset information. 6840 SDValue Base1, Base2; 6841 int64_t Offset1, Offset2; 6842 const GlobalValue *GV1, *GV2; 6843 void *CV1, *CV2; 6844 bool isFrameIndex1 = FindBaseOffset(Ptr1, Base1, Offset1, GV1, CV1); 6845 bool isFrameIndex2 = FindBaseOffset(Ptr2, Base2, Offset2, GV2, CV2); 6846 6847 // If they have a same base address then check to see if they overlap. 6848 if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2))) 6849 return !((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1); 6850 6851 // If we know what the bases are, and they aren't identical, then we know they 6852 // cannot alias. 6853 if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2)) 6854 return false; 6855 6856 // If we know required SrcValue1 and SrcValue2 have relatively large alignment 6857 // compared to the size and offset of the access, we may be able to prove they 6858 // do not alias. This check is conservative for now to catch cases created by 6859 // splitting vector types. 6860 if ((SrcValueAlign1 == SrcValueAlign2) && 6861 (SrcValueOffset1 != SrcValueOffset2) && 6862 (Size1 == Size2) && (SrcValueAlign1 > Size1)) { 6863 int64_t OffAlign1 = SrcValueOffset1 % SrcValueAlign1; 6864 int64_t OffAlign2 = SrcValueOffset2 % SrcValueAlign1; 6865 6866 // There is no overlap between these relatively aligned accesses of similar 6867 // size, return no alias. 6868 if ((OffAlign1 + Size1) <= OffAlign2 || (OffAlign2 + Size2) <= OffAlign1) 6869 return false; 6870 } 6871 6872 if (CombinerGlobalAA) { 6873 // Use alias analysis information. 6874 int64_t MinOffset = std::min(SrcValueOffset1, SrcValueOffset2); 6875 int64_t Overlap1 = Size1 + SrcValueOffset1 - MinOffset; 6876 int64_t Overlap2 = Size2 + SrcValueOffset2 - MinOffset; 6877 AliasAnalysis::AliasResult AAResult = 6878 AA.alias(SrcValue1, Overlap1, SrcValue2, Overlap2); 6879 if (AAResult == AliasAnalysis::NoAlias) 6880 return false; 6881 } 6882 6883 // Otherwise we have to assume they alias. 6884 return true; 6885 } 6886 6887 /// FindAliasInfo - Extracts the relevant alias information from the memory 6888 /// node. Returns true if the operand was a load. 6889 bool DAGCombiner::FindAliasInfo(SDNode *N, 6890 SDValue &Ptr, int64_t &Size, 6891 const Value *&SrcValue, 6892 int &SrcValueOffset, 6893 unsigned &SrcValueAlign) const { 6894 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 6895 Ptr = LD->getBasePtr(); 6896 Size = LD->getMemoryVT().getSizeInBits() >> 3; 6897 SrcValue = LD->getSrcValue(); 6898 SrcValueOffset = LD->getSrcValueOffset(); 6899 SrcValueAlign = LD->getOriginalAlignment(); 6900 return true; 6901 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 6902 Ptr = ST->getBasePtr(); 6903 Size = ST->getMemoryVT().getSizeInBits() >> 3; 6904 SrcValue = ST->getSrcValue(); 6905 SrcValueOffset = ST->getSrcValueOffset(); 6906 SrcValueAlign = ST->getOriginalAlignment(); 6907 } else { 6908 llvm_unreachable("FindAliasInfo expected a memory operand"); 6909 } 6910 6911 return false; 6912 } 6913 6914 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes, 6915 /// looking for aliasing nodes and adding them to the Aliases vector. 6916 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain, 6917 SmallVector<SDValue, 8> &Aliases) { 6918 SmallVector<SDValue, 8> Chains; // List of chains to visit. 6919 SmallPtrSet<SDNode *, 16> Visited; // Visited node set. 6920 6921 // Get alias information for node. 6922 SDValue Ptr; 6923 int64_t Size; 6924 const Value *SrcValue; 6925 int SrcValueOffset; 6926 unsigned SrcValueAlign; 6927 bool IsLoad = FindAliasInfo(N, Ptr, Size, SrcValue, SrcValueOffset, 6928 SrcValueAlign); 6929 6930 // Starting off. 6931 Chains.push_back(OriginalChain); 6932 unsigned Depth = 0; 6933 6934 // Look at each chain and determine if it is an alias. If so, add it to the 6935 // aliases list. If not, then continue up the chain looking for the next 6936 // candidate. 6937 while (!Chains.empty()) { 6938 SDValue Chain = Chains.back(); 6939 Chains.pop_back(); 6940 6941 // For TokenFactor nodes, look at each operand and only continue up the 6942 // chain until we find two aliases. If we've seen two aliases, assume we'll 6943 // find more and revert to original chain since the xform is unlikely to be 6944 // profitable. 6945 // 6946 // FIXME: The depth check could be made to return the last non-aliasing 6947 // chain we found before we hit a tokenfactor rather than the original 6948 // chain. 6949 if (Depth > 6 || Aliases.size() == 2) { 6950 Aliases.clear(); 6951 Aliases.push_back(OriginalChain); 6952 break; 6953 } 6954 6955 // Don't bother if we've been before. 6956 if (!Visited.insert(Chain.getNode())) 6957 continue; 6958 6959 switch (Chain.getOpcode()) { 6960 case ISD::EntryToken: 6961 // Entry token is ideal chain operand, but handled in FindBetterChain. 6962 break; 6963 6964 case ISD::LOAD: 6965 case ISD::STORE: { 6966 // Get alias information for Chain. 6967 SDValue OpPtr; 6968 int64_t OpSize; 6969 const Value *OpSrcValue; 6970 int OpSrcValueOffset; 6971 unsigned OpSrcValueAlign; 6972 bool IsOpLoad = FindAliasInfo(Chain.getNode(), OpPtr, OpSize, 6973 OpSrcValue, OpSrcValueOffset, 6974 OpSrcValueAlign); 6975 6976 // If chain is alias then stop here. 6977 if (!(IsLoad && IsOpLoad) && 6978 isAlias(Ptr, Size, SrcValue, SrcValueOffset, SrcValueAlign, 6979 OpPtr, OpSize, OpSrcValue, OpSrcValueOffset, 6980 OpSrcValueAlign)) { 6981 Aliases.push_back(Chain); 6982 } else { 6983 // Look further up the chain. 6984 Chains.push_back(Chain.getOperand(0)); 6985 ++Depth; 6986 } 6987 break; 6988 } 6989 6990 case ISD::TokenFactor: 6991 // We have to check each of the operands of the token factor for "small" 6992 // token factors, so we queue them up. Adding the operands to the queue 6993 // (stack) in reverse order maintains the original order and increases the 6994 // likelihood that getNode will find a matching token factor (CSE.) 6995 if (Chain.getNumOperands() > 16) { 6996 Aliases.push_back(Chain); 6997 break; 6998 } 6999 for (unsigned n = Chain.getNumOperands(); n;) 7000 Chains.push_back(Chain.getOperand(--n)); 7001 ++Depth; 7002 break; 7003 7004 default: 7005 // For all other instructions we will just have to take what we can get. 7006 Aliases.push_back(Chain); 7007 break; 7008 } 7009 } 7010 } 7011 7012 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes, looking 7013 /// for a better chain (aliasing node.) 7014 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) { 7015 SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor. 7016 7017 // Accumulate all the aliases to this node. 7018 GatherAllAliases(N, OldChain, Aliases); 7019 7020 if (Aliases.size() == 0) { 7021 // If no operands then chain to entry token. 7022 return DAG.getEntryNode(); 7023 } else if (Aliases.size() == 1) { 7024 // If a single operand then chain to it. We don't need to revisit it. 7025 return Aliases[0]; 7026 } 7027 7028 // Construct a custom tailored token factor. 7029 return DAG.getNode(ISD::TokenFactor, N->getDebugLoc(), MVT::Other, 7030 &Aliases[0], Aliases.size()); 7031 } 7032 7033 // SelectionDAG::Combine - This is the entry point for the file. 7034 // 7035 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA, 7036 CodeGenOpt::Level OptLevel) { 7037 /// run - This is the main entry point to this class. 7038 /// 7039 DAGCombiner(*this, AA, OptLevel).Run(Level); 7040 } 7041