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