DAGCombiner.cpp revision e5f163a3b98a531c3ff35da0e97e7364c0e04b95
1//===-- DAGCombiner.cpp - Implement a DAG node combiner -------------------===// 2// 3// The LLVM Compiler Infrastructure 4// 5// This file is distributed under the University of Illinois Open Source 6// License. See LICENSE.TXT for details. 7// 8//===----------------------------------------------------------------------===// 9// 10// This pass combines dag nodes to form fewer, simpler DAG nodes. It can be run 11// both before and after the DAG is legalized. 12// 13// This pass is not a substitute for the LLVM IR instcombine pass. This pass is 14// primarily intended to handle simplification opportunities that are implicit 15// in the LLVM IR and exposed by the various codegen lowering phases. 16// 17//===----------------------------------------------------------------------===// 18 19#define DEBUG_TYPE "dagcombine" 20#include "llvm/CodeGen/SelectionDAG.h" 21#include "llvm/DerivedTypes.h" 22#include "llvm/LLVMContext.h" 23#include "llvm/CodeGen/MachineFunction.h" 24#include "llvm/CodeGen/MachineFrameInfo.h" 25#include "llvm/Analysis/AliasAnalysis.h" 26#include "llvm/Target/TargetData.h" 27#include "llvm/Target/TargetLowering.h" 28#include "llvm/Target/TargetMachine.h" 29#include "llvm/Target/TargetOptions.h" 30#include "llvm/ADT/SmallPtrSet.h" 31#include "llvm/ADT/Statistic.h" 32#include "llvm/Support/CommandLine.h" 33#include "llvm/Support/Debug.h" 34#include "llvm/Support/ErrorHandling.h" 35#include "llvm/Support/MathExtras.h" 36#include "llvm/Support/raw_ostream.h" 37#include <algorithm> 38using namespace llvm; 39 40STATISTIC(NodesCombined , "Number of dag nodes combined"); 41STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created"); 42STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created"); 43STATISTIC(OpsNarrowed , "Number of load/op/store narrowed"); 44STATISTIC(LdStFP2Int , "Number of fp load/store pairs transformed to int"); 45 46namespace { 47 static cl::opt<bool> 48 CombinerAA("combiner-alias-analysis", cl::Hidden, 49 cl::desc("Turn on alias analysis during testing")); 50 51 static cl::opt<bool> 52 CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden, 53 cl::desc("Include global information in alias analysis")); 54 55//------------------------------ DAGCombiner ---------------------------------// 56 57 class DAGCombiner { 58 SelectionDAG &DAG; 59 const TargetLowering &TLI; 60 CombineLevel Level; 61 CodeGenOpt::Level OptLevel; 62 bool LegalOperations; 63 bool LegalTypes; 64 65 // Worklist of all of the nodes that need to be simplified. 66 // 67 // This has the semantics that when adding to the worklist, 68 // the item added must be next to be processed. It should 69 // also only appear once. The naive approach to this takes 70 // linear time. 71 // 72 // To reduce the insert/remove time to logarithmic, we use 73 // a set and a vector to maintain our worklist. 74 // 75 // The set contains the items on the worklist, but does not 76 // maintain the order they should be visited. 77 // 78 // The vector maintains the order nodes should be visited, but may 79 // contain duplicate or removed nodes. When choosing a node to 80 // visit, we pop off the order stack until we find an item that is 81 // also in the contents set. All operations are O(log N). 82 SmallPtrSet<SDNode*, 64> WorkListContents; 83 SmallVector<SDNode*, 64> WorkListOrder; 84 85 // AA - Used for DAG load/store alias analysis. 86 AliasAnalysis &AA; 87 88 /// AddUsersToWorkList - When an instruction is simplified, add all users of 89 /// the instruction to the work lists because they might get more simplified 90 /// now. 91 /// 92 void AddUsersToWorkList(SDNode *N) { 93 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end(); 94 UI != UE; ++UI) 95 AddToWorkList(*UI); 96 } 97 98 /// visit - call the node-specific routine that knows how to fold each 99 /// particular type of node. 100 SDValue visit(SDNode *N); 101 102 public: 103 /// AddToWorkList - Add to the work list making sure its instance is at the 104 /// back (next to be processed.) 105 void AddToWorkList(SDNode *N) { 106 WorkListContents.insert(N); 107 WorkListOrder.push_back(N); 108 } 109 110 /// removeFromWorkList - remove all instances of N from the worklist. 111 /// 112 void removeFromWorkList(SDNode *N) { 113 WorkListContents.erase(N); 114 } 115 116 SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo, 117 bool AddTo = true); 118 119 SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) { 120 return CombineTo(N, &Res, 1, AddTo); 121 } 122 123 SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1, 124 bool AddTo = true) { 125 SDValue To[] = { Res0, Res1 }; 126 return CombineTo(N, To, 2, AddTo); 127 } 128 129 void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO); 130 131 private: 132 133 /// SimplifyDemandedBits - Check the specified integer node value to see if 134 /// it can be simplified or if things it uses can be simplified by bit 135 /// propagation. If so, return true. 136 bool SimplifyDemandedBits(SDValue Op) { 137 unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits(); 138 APInt Demanded = APInt::getAllOnesValue(BitWidth); 139 return SimplifyDemandedBits(Op, Demanded); 140 } 141 142 bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded); 143 144 bool CombineToPreIndexedLoadStore(SDNode *N); 145 bool CombineToPostIndexedLoadStore(SDNode *N); 146 147 void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad); 148 SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace); 149 SDValue SExtPromoteOperand(SDValue Op, EVT PVT); 150 SDValue ZExtPromoteOperand(SDValue Op, EVT PVT); 151 SDValue PromoteIntBinOp(SDValue Op); 152 SDValue PromoteIntShiftOp(SDValue Op); 153 SDValue PromoteExtend(SDValue Op); 154 bool PromoteLoad(SDValue Op); 155 156 void ExtendSetCCUses(SmallVector<SDNode*, 4> SetCCs, 157 SDValue Trunc, SDValue ExtLoad, DebugLoc DL, 158 ISD::NodeType ExtType); 159 160 /// combine - call the node-specific routine that knows how to fold each 161 /// particular type of node. If that doesn't do anything, try the 162 /// target-specific DAG combines. 163 SDValue combine(SDNode *N); 164 165 // Visitation implementation - Implement dag node combining for different 166 // node types. The semantics are as follows: 167 // Return Value: 168 // SDValue.getNode() == 0 - No change was made 169 // SDValue.getNode() == N - N was replaced, is dead and has been handled. 170 // otherwise - N should be replaced by the returned Operand. 171 // 172 SDValue visitTokenFactor(SDNode *N); 173 SDValue visitMERGE_VALUES(SDNode *N); 174 SDValue visitADD(SDNode *N); 175 SDValue visitSUB(SDNode *N); 176 SDValue visitADDC(SDNode *N); 177 SDValue visitSUBC(SDNode *N); 178 SDValue visitADDE(SDNode *N); 179 SDValue visitSUBE(SDNode *N); 180 SDValue visitMUL(SDNode *N); 181 SDValue visitSDIV(SDNode *N); 182 SDValue visitUDIV(SDNode *N); 183 SDValue visitSREM(SDNode *N); 184 SDValue visitUREM(SDNode *N); 185 SDValue visitMULHU(SDNode *N); 186 SDValue visitMULHS(SDNode *N); 187 SDValue visitSMUL_LOHI(SDNode *N); 188 SDValue visitUMUL_LOHI(SDNode *N); 189 SDValue visitSMULO(SDNode *N); 190 SDValue visitUMULO(SDNode *N); 191 SDValue visitSDIVREM(SDNode *N); 192 SDValue visitUDIVREM(SDNode *N); 193 SDValue visitAND(SDNode *N); 194 SDValue visitOR(SDNode *N); 195 SDValue visitXOR(SDNode *N); 196 SDValue SimplifyVBinOp(SDNode *N); 197 SDValue SimplifyVUnaryOp(SDNode *N); 198 SDValue visitSHL(SDNode *N); 199 SDValue visitSRA(SDNode *N); 200 SDValue visitSRL(SDNode *N); 201 SDValue visitCTLZ(SDNode *N); 202 SDValue visitCTLZ_ZERO_UNDEF(SDNode *N); 203 SDValue visitCTTZ(SDNode *N); 204 SDValue visitCTTZ_ZERO_UNDEF(SDNode *N); 205 SDValue visitCTPOP(SDNode *N); 206 SDValue visitSELECT(SDNode *N); 207 SDValue visitSELECT_CC(SDNode *N); 208 SDValue visitSETCC(SDNode *N); 209 SDValue visitSIGN_EXTEND(SDNode *N); 210 SDValue visitZERO_EXTEND(SDNode *N); 211 SDValue visitANY_EXTEND(SDNode *N); 212 SDValue visitSIGN_EXTEND_INREG(SDNode *N); 213 SDValue visitTRUNCATE(SDNode *N); 214 SDValue visitBITCAST(SDNode *N); 215 SDValue visitBUILD_PAIR(SDNode *N); 216 SDValue visitFADD(SDNode *N); 217 SDValue visitFSUB(SDNode *N); 218 SDValue visitFMUL(SDNode *N); 219 SDValue visitFMA(SDNode *N); 220 SDValue visitFDIV(SDNode *N); 221 SDValue visitFREM(SDNode *N); 222 SDValue visitFCOPYSIGN(SDNode *N); 223 SDValue visitSINT_TO_FP(SDNode *N); 224 SDValue visitUINT_TO_FP(SDNode *N); 225 SDValue visitFP_TO_SINT(SDNode *N); 226 SDValue visitFP_TO_UINT(SDNode *N); 227 SDValue visitFP_ROUND(SDNode *N); 228 SDValue visitFP_ROUND_INREG(SDNode *N); 229 SDValue visitFP_EXTEND(SDNode *N); 230 SDValue visitFNEG(SDNode *N); 231 SDValue visitFABS(SDNode *N); 232 SDValue visitFCEIL(SDNode *N); 233 SDValue visitFTRUNC(SDNode *N); 234 SDValue visitFFLOOR(SDNode *N); 235 SDValue visitBRCOND(SDNode *N); 236 SDValue visitBR_CC(SDNode *N); 237 SDValue visitLOAD(SDNode *N); 238 SDValue visitSTORE(SDNode *N); 239 SDValue visitINSERT_VECTOR_ELT(SDNode *N); 240 SDValue visitEXTRACT_VECTOR_ELT(SDNode *N); 241 SDValue visitBUILD_VECTOR(SDNode *N); 242 SDValue visitCONCAT_VECTORS(SDNode *N); 243 SDValue visitEXTRACT_SUBVECTOR(SDNode *N); 244 SDValue visitVECTOR_SHUFFLE(SDNode *N); 245 SDValue visitMEMBARRIER(SDNode *N); 246 247 SDValue XformToShuffleWithZero(SDNode *N); 248 SDValue ReassociateOps(unsigned Opc, DebugLoc DL, SDValue LHS, SDValue RHS); 249 250 SDValue visitShiftByConstant(SDNode *N, unsigned Amt); 251 252 bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS); 253 SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N); 254 SDValue SimplifySelect(DebugLoc DL, SDValue N0, SDValue N1, SDValue N2); 255 SDValue SimplifySelectCC(DebugLoc DL, SDValue N0, SDValue N1, SDValue N2, 256 SDValue N3, ISD::CondCode CC, 257 bool NotExtCompare = false); 258 SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond, 259 DebugLoc DL, bool foldBooleans = true); 260 SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp, 261 unsigned HiOp); 262 SDValue CombineConsecutiveLoads(SDNode *N, EVT VT); 263 SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT); 264 SDValue BuildSDIV(SDNode *N); 265 SDValue BuildUDIV(SDNode *N); 266 SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1, 267 bool DemandHighBits = true); 268 SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1); 269 SDNode *MatchRotate(SDValue LHS, SDValue RHS, DebugLoc DL); 270 SDValue ReduceLoadWidth(SDNode *N); 271 SDValue ReduceLoadOpStoreWidth(SDNode *N); 272 SDValue TransformFPLoadStorePair(SDNode *N); 273 274 SDValue GetDemandedBits(SDValue V, const APInt &Mask); 275 276 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes, 277 /// looking for aliasing nodes and adding them to the Aliases vector. 278 void GatherAllAliases(SDNode *N, SDValue OriginalChain, 279 SmallVector<SDValue, 8> &Aliases); 280 281 /// isAlias - Return true if there is any possibility that the two addresses 282 /// overlap. 283 bool isAlias(SDValue Ptr1, int64_t Size1, 284 const Value *SrcValue1, int SrcValueOffset1, 285 unsigned SrcValueAlign1, 286 const MDNode *TBAAInfo1, 287 SDValue Ptr2, int64_t Size2, 288 const Value *SrcValue2, int SrcValueOffset2, 289 unsigned SrcValueAlign2, 290 const MDNode *TBAAInfo2) const; 291 292 /// FindAliasInfo - Extracts the relevant alias information from the memory 293 /// node. Returns true if the operand was a load. 294 bool FindAliasInfo(SDNode *N, 295 SDValue &Ptr, int64_t &Size, 296 const Value *&SrcValue, int &SrcValueOffset, 297 unsigned &SrcValueAlignment, 298 const MDNode *&TBAAInfo) const; 299 300 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes, 301 /// looking for a better chain (aliasing node.) 302 SDValue FindBetterChain(SDNode *N, SDValue Chain); 303 304 /// Merge consecutive store operations into a wide store. 305 /// \return True if some memory operations were changed. 306 bool MergeConsecutiveStores(StoreSDNode *N); 307 308 public: 309 DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL) 310 : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes), 311 OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {} 312 313 /// Run - runs the dag combiner on all nodes in the work list 314 void Run(CombineLevel AtLevel); 315 316 SelectionDAG &getDAG() const { return DAG; } 317 318 /// getShiftAmountTy - Returns a type large enough to hold any valid 319 /// shift amount - before type legalization these can be huge. 320 EVT getShiftAmountTy(EVT LHSTy) { 321 return LegalTypes ? TLI.getShiftAmountTy(LHSTy) : TLI.getPointerTy(); 322 } 323 324 /// isTypeLegal - This method returns true if we are running before type 325 /// legalization or if the specified VT is legal. 326 bool isTypeLegal(const EVT &VT) { 327 if (!LegalTypes) return true; 328 return TLI.isTypeLegal(VT); 329 } 330 }; 331} 332 333 334namespace { 335/// WorkListRemover - This class is a DAGUpdateListener that removes any deleted 336/// nodes from the worklist. 337class WorkListRemover : public SelectionDAG::DAGUpdateListener { 338 DAGCombiner &DC; 339public: 340 explicit WorkListRemover(DAGCombiner &dc) 341 : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {} 342 343 virtual void NodeDeleted(SDNode *N, SDNode *E) { 344 DC.removeFromWorkList(N); 345 } 346}; 347} 348 349//===----------------------------------------------------------------------===// 350// TargetLowering::DAGCombinerInfo implementation 351//===----------------------------------------------------------------------===// 352 353void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) { 354 ((DAGCombiner*)DC)->AddToWorkList(N); 355} 356 357void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) { 358 ((DAGCombiner*)DC)->removeFromWorkList(N); 359} 360 361SDValue TargetLowering::DAGCombinerInfo:: 362CombineTo(SDNode *N, const std::vector<SDValue> &To, bool AddTo) { 363 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo); 364} 365 366SDValue TargetLowering::DAGCombinerInfo:: 367CombineTo(SDNode *N, SDValue Res, bool AddTo) { 368 return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo); 369} 370 371 372SDValue TargetLowering::DAGCombinerInfo:: 373CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) { 374 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo); 375} 376 377void TargetLowering::DAGCombinerInfo:: 378CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) { 379 return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO); 380} 381 382//===----------------------------------------------------------------------===// 383// Helper Functions 384//===----------------------------------------------------------------------===// 385 386/// isNegatibleForFree - Return 1 if we can compute the negated form of the 387/// specified expression for the same cost as the expression itself, or 2 if we 388/// can compute the negated form more cheaply than the expression itself. 389static char isNegatibleForFree(SDValue Op, bool LegalOperations, 390 const TargetLowering &TLI, 391 const TargetOptions *Options, 392 unsigned Depth = 0) { 393 // No compile time optimizations on this type. 394 if (Op.getValueType() == MVT::ppcf128) 395 return 0; 396 397 // fneg is removable even if it has multiple uses. 398 if (Op.getOpcode() == ISD::FNEG) return 2; 399 400 // Don't allow anything with multiple uses. 401 if (!Op.hasOneUse()) return 0; 402 403 // Don't recurse exponentially. 404 if (Depth > 6) return 0; 405 406 switch (Op.getOpcode()) { 407 default: return false; 408 case ISD::ConstantFP: 409 // Don't invert constant FP values after legalize. The negated constant 410 // isn't necessarily legal. 411 return LegalOperations ? 0 : 1; 412 case ISD::FADD: 413 // FIXME: determine better conditions for this xform. 414 if (!Options->UnsafeFPMath) return 0; 415 416 // After operation legalization, it might not be legal to create new FSUBs. 417 if (LegalOperations && 418 !TLI.isOperationLegalOrCustom(ISD::FSUB, Op.getValueType())) 419 return 0; 420 421 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B) 422 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, 423 Options, Depth + 1)) 424 return V; 425 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A) 426 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options, 427 Depth + 1); 428 case ISD::FSUB: 429 // We can't turn -(A-B) into B-A when we honor signed zeros. 430 if (!Options->UnsafeFPMath) return 0; 431 432 // fold (fneg (fsub A, B)) -> (fsub B, A) 433 return 1; 434 435 case ISD::FMUL: 436 case ISD::FDIV: 437 if (Options->HonorSignDependentRoundingFPMath()) return 0; 438 439 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y)) 440 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, 441 Options, Depth + 1)) 442 return V; 443 444 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options, 445 Depth + 1); 446 447 case ISD::FP_EXTEND: 448 case ISD::FP_ROUND: 449 case ISD::FSIN: 450 return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options, 451 Depth + 1); 452 } 453} 454 455/// GetNegatedExpression - If isNegatibleForFree returns true, this function 456/// returns the newly negated expression. 457static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG, 458 bool LegalOperations, unsigned Depth = 0) { 459 // fneg is removable even if it has multiple uses. 460 if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0); 461 462 // Don't allow anything with multiple uses. 463 assert(Op.hasOneUse() && "Unknown reuse!"); 464 465 assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree"); 466 switch (Op.getOpcode()) { 467 default: llvm_unreachable("Unknown code"); 468 case ISD::ConstantFP: { 469 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF(); 470 V.changeSign(); 471 return DAG.getConstantFP(V, Op.getValueType()); 472 } 473 case ISD::FADD: 474 // FIXME: determine better conditions for this xform. 475 assert(DAG.getTarget().Options.UnsafeFPMath); 476 477 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B) 478 if (isNegatibleForFree(Op.getOperand(0), LegalOperations, 479 DAG.getTargetLoweringInfo(), 480 &DAG.getTarget().Options, Depth+1)) 481 return DAG.getNode(ISD::FSUB, Op.getDebugLoc(), Op.getValueType(), 482 GetNegatedExpression(Op.getOperand(0), DAG, 483 LegalOperations, Depth+1), 484 Op.getOperand(1)); 485 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A) 486 return DAG.getNode(ISD::FSUB, Op.getDebugLoc(), Op.getValueType(), 487 GetNegatedExpression(Op.getOperand(1), DAG, 488 LegalOperations, Depth+1), 489 Op.getOperand(0)); 490 case ISD::FSUB: 491 // We can't turn -(A-B) into B-A when we honor signed zeros. 492 assert(DAG.getTarget().Options.UnsafeFPMath); 493 494 // fold (fneg (fsub 0, B)) -> B 495 if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0))) 496 if (N0CFP->getValueAPF().isZero()) 497 return Op.getOperand(1); 498 499 // fold (fneg (fsub A, B)) -> (fsub B, A) 500 return DAG.getNode(ISD::FSUB, Op.getDebugLoc(), Op.getValueType(), 501 Op.getOperand(1), Op.getOperand(0)); 502 503 case ISD::FMUL: 504 case ISD::FDIV: 505 assert(!DAG.getTarget().Options.HonorSignDependentRoundingFPMath()); 506 507 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) 508 if (isNegatibleForFree(Op.getOperand(0), LegalOperations, 509 DAG.getTargetLoweringInfo(), 510 &DAG.getTarget().Options, Depth+1)) 511 return DAG.getNode(Op.getOpcode(), Op.getDebugLoc(), Op.getValueType(), 512 GetNegatedExpression(Op.getOperand(0), DAG, 513 LegalOperations, Depth+1), 514 Op.getOperand(1)); 515 516 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y)) 517 return DAG.getNode(Op.getOpcode(), Op.getDebugLoc(), Op.getValueType(), 518 Op.getOperand(0), 519 GetNegatedExpression(Op.getOperand(1), DAG, 520 LegalOperations, Depth+1)); 521 522 case ISD::FP_EXTEND: 523 case ISD::FSIN: 524 return DAG.getNode(Op.getOpcode(), Op.getDebugLoc(), Op.getValueType(), 525 GetNegatedExpression(Op.getOperand(0), DAG, 526 LegalOperations, Depth+1)); 527 case ISD::FP_ROUND: 528 return DAG.getNode(ISD::FP_ROUND, Op.getDebugLoc(), Op.getValueType(), 529 GetNegatedExpression(Op.getOperand(0), DAG, 530 LegalOperations, Depth+1), 531 Op.getOperand(1)); 532 } 533} 534 535 536// isSetCCEquivalent - Return true if this node is a setcc, or is a select_cc 537// that selects between the values 1 and 0, making it equivalent to a setcc. 538// Also, set the incoming LHS, RHS, and CC references to the appropriate 539// nodes based on the type of node we are checking. This simplifies life a 540// bit for the callers. 541static bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS, 542 SDValue &CC) { 543 if (N.getOpcode() == ISD::SETCC) { 544 LHS = N.getOperand(0); 545 RHS = N.getOperand(1); 546 CC = N.getOperand(2); 547 return true; 548 } 549 if (N.getOpcode() == ISD::SELECT_CC && 550 N.getOperand(2).getOpcode() == ISD::Constant && 551 N.getOperand(3).getOpcode() == ISD::Constant && 552 cast<ConstantSDNode>(N.getOperand(2))->getAPIntValue() == 1 && 553 cast<ConstantSDNode>(N.getOperand(3))->isNullValue()) { 554 LHS = N.getOperand(0); 555 RHS = N.getOperand(1); 556 CC = N.getOperand(4); 557 return true; 558 } 559 return false; 560} 561 562// isOneUseSetCC - Return true if this is a SetCC-equivalent operation with only 563// one use. If this is true, it allows the users to invert the operation for 564// free when it is profitable to do so. 565static bool isOneUseSetCC(SDValue N) { 566 SDValue N0, N1, N2; 567 if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse()) 568 return true; 569 return false; 570} 571 572SDValue DAGCombiner::ReassociateOps(unsigned Opc, DebugLoc DL, 573 SDValue N0, SDValue N1) { 574 EVT VT = N0.getValueType(); 575 if (N0.getOpcode() == Opc && isa<ConstantSDNode>(N0.getOperand(1))) { 576 if (isa<ConstantSDNode>(N1)) { 577 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2)) 578 SDValue OpNode = 579 DAG.FoldConstantArithmetic(Opc, VT, 580 cast<ConstantSDNode>(N0.getOperand(1)), 581 cast<ConstantSDNode>(N1)); 582 return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode); 583 } 584 if (N0.hasOneUse()) { 585 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one use 586 SDValue OpNode = DAG.getNode(Opc, N0.getDebugLoc(), VT, 587 N0.getOperand(0), N1); 588 AddToWorkList(OpNode.getNode()); 589 return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1)); 590 } 591 } 592 593 if (N1.getOpcode() == Opc && isa<ConstantSDNode>(N1.getOperand(1))) { 594 if (isa<ConstantSDNode>(N0)) { 595 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2)) 596 SDValue OpNode = 597 DAG.FoldConstantArithmetic(Opc, VT, 598 cast<ConstantSDNode>(N1.getOperand(1)), 599 cast<ConstantSDNode>(N0)); 600 return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode); 601 } 602 if (N1.hasOneUse()) { 603 // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one use 604 SDValue OpNode = DAG.getNode(Opc, N0.getDebugLoc(), VT, 605 N1.getOperand(0), N0); 606 AddToWorkList(OpNode.getNode()); 607 return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1)); 608 } 609 } 610 611 return SDValue(); 612} 613 614SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo, 615 bool AddTo) { 616 assert(N->getNumValues() == NumTo && "Broken CombineTo call!"); 617 ++NodesCombined; 618 DEBUG(dbgs() << "\nReplacing.1 "; 619 N->dump(&DAG); 620 dbgs() << "\nWith: "; 621 To[0].getNode()->dump(&DAG); 622 dbgs() << " and " << NumTo-1 << " other values\n"; 623 for (unsigned i = 0, e = NumTo; i != e; ++i) 624 assert((!To[i].getNode() || 625 N->getValueType(i) == To[i].getValueType()) && 626 "Cannot combine value to value of different type!")); 627 WorkListRemover DeadNodes(*this); 628 DAG.ReplaceAllUsesWith(N, To); 629 if (AddTo) { 630 // Push the new nodes and any users onto the worklist 631 for (unsigned i = 0, e = NumTo; i != e; ++i) { 632 if (To[i].getNode()) { 633 AddToWorkList(To[i].getNode()); 634 AddUsersToWorkList(To[i].getNode()); 635 } 636 } 637 } 638 639 // Finally, if the node is now dead, remove it from the graph. The node 640 // may not be dead if the replacement process recursively simplified to 641 // something else needing this node. 642 if (N->use_empty()) { 643 // Nodes can be reintroduced into the worklist. Make sure we do not 644 // process a node that has been replaced. 645 removeFromWorkList(N); 646 647 // Finally, since the node is now dead, remove it from the graph. 648 DAG.DeleteNode(N); 649 } 650 return SDValue(N, 0); 651} 652 653void DAGCombiner:: 654CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) { 655 // Replace all uses. If any nodes become isomorphic to other nodes and 656 // are deleted, make sure to remove them from our worklist. 657 WorkListRemover DeadNodes(*this); 658 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New); 659 660 // Push the new node and any (possibly new) users onto the worklist. 661 AddToWorkList(TLO.New.getNode()); 662 AddUsersToWorkList(TLO.New.getNode()); 663 664 // Finally, if the node is now dead, remove it from the graph. The node 665 // may not be dead if the replacement process recursively simplified to 666 // something else needing this node. 667 if (TLO.Old.getNode()->use_empty()) { 668 removeFromWorkList(TLO.Old.getNode()); 669 670 // If the operands of this node are only used by the node, they will now 671 // be dead. Make sure to visit them first to delete dead nodes early. 672 for (unsigned i = 0, e = TLO.Old.getNode()->getNumOperands(); i != e; ++i) 673 if (TLO.Old.getNode()->getOperand(i).getNode()->hasOneUse()) 674 AddToWorkList(TLO.Old.getNode()->getOperand(i).getNode()); 675 676 DAG.DeleteNode(TLO.Old.getNode()); 677 } 678} 679 680/// SimplifyDemandedBits - Check the specified integer node value to see if 681/// it can be simplified or if things it uses can be simplified by bit 682/// propagation. If so, return true. 683bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) { 684 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations); 685 APInt KnownZero, KnownOne; 686 if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO)) 687 return false; 688 689 // Revisit the node. 690 AddToWorkList(Op.getNode()); 691 692 // Replace the old value with the new one. 693 ++NodesCombined; 694 DEBUG(dbgs() << "\nReplacing.2 "; 695 TLO.Old.getNode()->dump(&DAG); 696 dbgs() << "\nWith: "; 697 TLO.New.getNode()->dump(&DAG); 698 dbgs() << '\n'); 699 700 CommitTargetLoweringOpt(TLO); 701 return true; 702} 703 704void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) { 705 DebugLoc dl = Load->getDebugLoc(); 706 EVT VT = Load->getValueType(0); 707 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0)); 708 709 DEBUG(dbgs() << "\nReplacing.9 "; 710 Load->dump(&DAG); 711 dbgs() << "\nWith: "; 712 Trunc.getNode()->dump(&DAG); 713 dbgs() << '\n'); 714 WorkListRemover DeadNodes(*this); 715 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc); 716 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1)); 717 removeFromWorkList(Load); 718 DAG.DeleteNode(Load); 719 AddToWorkList(Trunc.getNode()); 720} 721 722SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) { 723 Replace = false; 724 DebugLoc dl = Op.getDebugLoc(); 725 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) { 726 EVT MemVT = LD->getMemoryVT(); 727 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD) 728 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD 729 : ISD::EXTLOAD) 730 : LD->getExtensionType(); 731 Replace = true; 732 return DAG.getExtLoad(ExtType, dl, PVT, 733 LD->getChain(), LD->getBasePtr(), 734 LD->getPointerInfo(), 735 MemVT, LD->isVolatile(), 736 LD->isNonTemporal(), LD->getAlignment()); 737 } 738 739 unsigned Opc = Op.getOpcode(); 740 switch (Opc) { 741 default: break; 742 case ISD::AssertSext: 743 return DAG.getNode(ISD::AssertSext, dl, PVT, 744 SExtPromoteOperand(Op.getOperand(0), PVT), 745 Op.getOperand(1)); 746 case ISD::AssertZext: 747 return DAG.getNode(ISD::AssertZext, dl, PVT, 748 ZExtPromoteOperand(Op.getOperand(0), PVT), 749 Op.getOperand(1)); 750 case ISD::Constant: { 751 unsigned ExtOpc = 752 Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 753 return DAG.getNode(ExtOpc, dl, PVT, Op); 754 } 755 } 756 757 if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT)) 758 return SDValue(); 759 return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op); 760} 761 762SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) { 763 if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT)) 764 return SDValue(); 765 EVT OldVT = Op.getValueType(); 766 DebugLoc dl = Op.getDebugLoc(); 767 bool Replace = false; 768 SDValue NewOp = PromoteOperand(Op, PVT, Replace); 769 if (NewOp.getNode() == 0) 770 return SDValue(); 771 AddToWorkList(NewOp.getNode()); 772 773 if (Replace) 774 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode()); 775 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp, 776 DAG.getValueType(OldVT)); 777} 778 779SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) { 780 EVT OldVT = Op.getValueType(); 781 DebugLoc dl = Op.getDebugLoc(); 782 bool Replace = false; 783 SDValue NewOp = PromoteOperand(Op, PVT, Replace); 784 if (NewOp.getNode() == 0) 785 return SDValue(); 786 AddToWorkList(NewOp.getNode()); 787 788 if (Replace) 789 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode()); 790 return DAG.getZeroExtendInReg(NewOp, dl, OldVT); 791} 792 793/// PromoteIntBinOp - Promote the specified integer binary operation if the 794/// target indicates it is beneficial. e.g. On x86, it's usually better to 795/// promote i16 operations to i32 since i16 instructions are longer. 796SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) { 797 if (!LegalOperations) 798 return SDValue(); 799 800 EVT VT = Op.getValueType(); 801 if (VT.isVector() || !VT.isInteger()) 802 return SDValue(); 803 804 // If operation type is 'undesirable', e.g. i16 on x86, consider 805 // promoting it. 806 unsigned Opc = Op.getOpcode(); 807 if (TLI.isTypeDesirableForOp(Opc, VT)) 808 return SDValue(); 809 810 EVT PVT = VT; 811 // Consult target whether it is a good idea to promote this operation and 812 // what's the right type to promote it to. 813 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 814 assert(PVT != VT && "Don't know what type to promote to!"); 815 816 bool Replace0 = false; 817 SDValue N0 = Op.getOperand(0); 818 SDValue NN0 = PromoteOperand(N0, PVT, Replace0); 819 if (NN0.getNode() == 0) 820 return SDValue(); 821 822 bool Replace1 = false; 823 SDValue N1 = Op.getOperand(1); 824 SDValue NN1; 825 if (N0 == N1) 826 NN1 = NN0; 827 else { 828 NN1 = PromoteOperand(N1, PVT, Replace1); 829 if (NN1.getNode() == 0) 830 return SDValue(); 831 } 832 833 AddToWorkList(NN0.getNode()); 834 if (NN1.getNode()) 835 AddToWorkList(NN1.getNode()); 836 837 if (Replace0) 838 ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode()); 839 if (Replace1) 840 ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode()); 841 842 DEBUG(dbgs() << "\nPromoting "; 843 Op.getNode()->dump(&DAG)); 844 DebugLoc dl = Op.getDebugLoc(); 845 return DAG.getNode(ISD::TRUNCATE, dl, VT, 846 DAG.getNode(Opc, dl, PVT, NN0, NN1)); 847 } 848 return SDValue(); 849} 850 851/// PromoteIntShiftOp - Promote the specified integer shift operation if the 852/// target indicates it is beneficial. e.g. On x86, it's usually better to 853/// promote i16 operations to i32 since i16 instructions are longer. 854SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) { 855 if (!LegalOperations) 856 return SDValue(); 857 858 EVT VT = Op.getValueType(); 859 if (VT.isVector() || !VT.isInteger()) 860 return SDValue(); 861 862 // If operation type is 'undesirable', e.g. i16 on x86, consider 863 // promoting it. 864 unsigned Opc = Op.getOpcode(); 865 if (TLI.isTypeDesirableForOp(Opc, VT)) 866 return SDValue(); 867 868 EVT PVT = VT; 869 // Consult target whether it is a good idea to promote this operation and 870 // what's the right type to promote it to. 871 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 872 assert(PVT != VT && "Don't know what type to promote to!"); 873 874 bool Replace = false; 875 SDValue N0 = Op.getOperand(0); 876 if (Opc == ISD::SRA) 877 N0 = SExtPromoteOperand(Op.getOperand(0), PVT); 878 else if (Opc == ISD::SRL) 879 N0 = ZExtPromoteOperand(Op.getOperand(0), PVT); 880 else 881 N0 = PromoteOperand(N0, PVT, Replace); 882 if (N0.getNode() == 0) 883 return SDValue(); 884 885 AddToWorkList(N0.getNode()); 886 if (Replace) 887 ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode()); 888 889 DEBUG(dbgs() << "\nPromoting "; 890 Op.getNode()->dump(&DAG)); 891 DebugLoc dl = Op.getDebugLoc(); 892 return DAG.getNode(ISD::TRUNCATE, dl, VT, 893 DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1))); 894 } 895 return SDValue(); 896} 897 898SDValue DAGCombiner::PromoteExtend(SDValue Op) { 899 if (!LegalOperations) 900 return SDValue(); 901 902 EVT VT = Op.getValueType(); 903 if (VT.isVector() || !VT.isInteger()) 904 return SDValue(); 905 906 // If operation type is 'undesirable', e.g. i16 on x86, consider 907 // promoting it. 908 unsigned Opc = Op.getOpcode(); 909 if (TLI.isTypeDesirableForOp(Opc, VT)) 910 return SDValue(); 911 912 EVT PVT = VT; 913 // Consult target whether it is a good idea to promote this operation and 914 // what's the right type to promote it to. 915 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 916 assert(PVT != VT && "Don't know what type to promote to!"); 917 // fold (aext (aext x)) -> (aext x) 918 // fold (aext (zext x)) -> (zext x) 919 // fold (aext (sext x)) -> (sext x) 920 DEBUG(dbgs() << "\nPromoting "; 921 Op.getNode()->dump(&DAG)); 922 return DAG.getNode(Op.getOpcode(), Op.getDebugLoc(), VT, Op.getOperand(0)); 923 } 924 return SDValue(); 925} 926 927bool DAGCombiner::PromoteLoad(SDValue Op) { 928 if (!LegalOperations) 929 return false; 930 931 EVT VT = Op.getValueType(); 932 if (VT.isVector() || !VT.isInteger()) 933 return false; 934 935 // If operation type is 'undesirable', e.g. i16 on x86, consider 936 // promoting it. 937 unsigned Opc = Op.getOpcode(); 938 if (TLI.isTypeDesirableForOp(Opc, VT)) 939 return false; 940 941 EVT PVT = VT; 942 // Consult target whether it is a good idea to promote this operation and 943 // what's the right type to promote it to. 944 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 945 assert(PVT != VT && "Don't know what type to promote to!"); 946 947 DebugLoc dl = Op.getDebugLoc(); 948 SDNode *N = Op.getNode(); 949 LoadSDNode *LD = cast<LoadSDNode>(N); 950 EVT MemVT = LD->getMemoryVT(); 951 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD) 952 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD 953 : ISD::EXTLOAD) 954 : LD->getExtensionType(); 955 SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT, 956 LD->getChain(), LD->getBasePtr(), 957 LD->getPointerInfo(), 958 MemVT, LD->isVolatile(), 959 LD->isNonTemporal(), LD->getAlignment()); 960 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD); 961 962 DEBUG(dbgs() << "\nPromoting "; 963 N->dump(&DAG); 964 dbgs() << "\nTo: "; 965 Result.getNode()->dump(&DAG); 966 dbgs() << '\n'); 967 WorkListRemover DeadNodes(*this); 968 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result); 969 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1)); 970 removeFromWorkList(N); 971 DAG.DeleteNode(N); 972 AddToWorkList(Result.getNode()); 973 return true; 974 } 975 return false; 976} 977 978 979//===----------------------------------------------------------------------===// 980// Main DAG Combiner implementation 981//===----------------------------------------------------------------------===// 982 983void DAGCombiner::Run(CombineLevel AtLevel) { 984 // set the instance variables, so that the various visit routines may use it. 985 Level = AtLevel; 986 LegalOperations = Level >= AfterLegalizeVectorOps; 987 LegalTypes = Level >= AfterLegalizeTypes; 988 989 // Add all the dag nodes to the worklist. 990 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(), 991 E = DAG.allnodes_end(); I != E; ++I) 992 AddToWorkList(I); 993 994 // Create a dummy node (which is not added to allnodes), that adds a reference 995 // to the root node, preventing it from being deleted, and tracking any 996 // changes of the root. 997 HandleSDNode Dummy(DAG.getRoot()); 998 999 // The root of the dag may dangle to deleted nodes until the dag combiner is 1000 // done. Set it to null to avoid confusion. 1001 DAG.setRoot(SDValue()); 1002 1003 // while the worklist isn't empty, find a node and 1004 // try and combine it. 1005 while (!WorkListContents.empty()) { 1006 SDNode *N; 1007 // The WorkListOrder holds the SDNodes in order, but it may contain duplicates. 1008 // In order to avoid a linear scan, we use a set (O(log N)) to hold what the 1009 // worklist *should* contain, and check the node we want to visit is should 1010 // actually be visited. 1011 do { 1012 N = WorkListOrder.pop_back_val(); 1013 } while (!WorkListContents.erase(N)); 1014 1015 // If N has no uses, it is dead. Make sure to revisit all N's operands once 1016 // N is deleted from the DAG, since they too may now be dead or may have a 1017 // reduced number of uses, allowing other xforms. 1018 if (N->use_empty() && N != &Dummy) { 1019 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) 1020 AddToWorkList(N->getOperand(i).getNode()); 1021 1022 DAG.DeleteNode(N); 1023 continue; 1024 } 1025 1026 SDValue RV = combine(N); 1027 1028 if (RV.getNode() == 0) 1029 continue; 1030 1031 ++NodesCombined; 1032 1033 // If we get back the same node we passed in, rather than a new node or 1034 // zero, we know that the node must have defined multiple values and 1035 // CombineTo was used. Since CombineTo takes care of the worklist 1036 // mechanics for us, we have no work to do in this case. 1037 if (RV.getNode() == N) 1038 continue; 1039 1040 assert(N->getOpcode() != ISD::DELETED_NODE && 1041 RV.getNode()->getOpcode() != ISD::DELETED_NODE && 1042 "Node was deleted but visit returned new node!"); 1043 1044 DEBUG(dbgs() << "\nReplacing.3 "; 1045 N->dump(&DAG); 1046 dbgs() << "\nWith: "; 1047 RV.getNode()->dump(&DAG); 1048 dbgs() << '\n'); 1049 1050 // Transfer debug value. 1051 DAG.TransferDbgValues(SDValue(N, 0), RV); 1052 WorkListRemover DeadNodes(*this); 1053 if (N->getNumValues() == RV.getNode()->getNumValues()) 1054 DAG.ReplaceAllUsesWith(N, RV.getNode()); 1055 else { 1056 assert(N->getValueType(0) == RV.getValueType() && 1057 N->getNumValues() == 1 && "Type mismatch"); 1058 SDValue OpV = RV; 1059 DAG.ReplaceAllUsesWith(N, &OpV); 1060 } 1061 1062 // Push the new node and any users onto the worklist 1063 AddToWorkList(RV.getNode()); 1064 AddUsersToWorkList(RV.getNode()); 1065 1066 // Add any uses of the old node to the worklist in case this node is the 1067 // last one that uses them. They may become dead after this node is 1068 // deleted. 1069 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) 1070 AddToWorkList(N->getOperand(i).getNode()); 1071 1072 // Finally, if the node is now dead, remove it from the graph. The node 1073 // may not be dead if the replacement process recursively simplified to 1074 // something else needing this node. 1075 if (N->use_empty()) { 1076 // Nodes can be reintroduced into the worklist. Make sure we do not 1077 // process a node that has been replaced. 1078 removeFromWorkList(N); 1079 1080 // Finally, since the node is now dead, remove it from the graph. 1081 DAG.DeleteNode(N); 1082 } 1083 } 1084 1085 // If the root changed (e.g. it was a dead load, update the root). 1086 DAG.setRoot(Dummy.getValue()); 1087 DAG.RemoveDeadNodes(); 1088} 1089 1090SDValue DAGCombiner::visit(SDNode *N) { 1091 switch (N->getOpcode()) { 1092 default: break; 1093 case ISD::TokenFactor: return visitTokenFactor(N); 1094 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N); 1095 case ISD::ADD: return visitADD(N); 1096 case ISD::SUB: return visitSUB(N); 1097 case ISD::ADDC: return visitADDC(N); 1098 case ISD::SUBC: return visitSUBC(N); 1099 case ISD::ADDE: return visitADDE(N); 1100 case ISD::SUBE: return visitSUBE(N); 1101 case ISD::MUL: return visitMUL(N); 1102 case ISD::SDIV: return visitSDIV(N); 1103 case ISD::UDIV: return visitUDIV(N); 1104 case ISD::SREM: return visitSREM(N); 1105 case ISD::UREM: return visitUREM(N); 1106 case ISD::MULHU: return visitMULHU(N); 1107 case ISD::MULHS: return visitMULHS(N); 1108 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N); 1109 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N); 1110 case ISD::SMULO: return visitSMULO(N); 1111 case ISD::UMULO: return visitUMULO(N); 1112 case ISD::SDIVREM: return visitSDIVREM(N); 1113 case ISD::UDIVREM: return visitUDIVREM(N); 1114 case ISD::AND: return visitAND(N); 1115 case ISD::OR: return visitOR(N); 1116 case ISD::XOR: return visitXOR(N); 1117 case ISD::SHL: return visitSHL(N); 1118 case ISD::SRA: return visitSRA(N); 1119 case ISD::SRL: return visitSRL(N); 1120 case ISD::CTLZ: return visitCTLZ(N); 1121 case ISD::CTLZ_ZERO_UNDEF: return visitCTLZ_ZERO_UNDEF(N); 1122 case ISD::CTTZ: return visitCTTZ(N); 1123 case ISD::CTTZ_ZERO_UNDEF: return visitCTTZ_ZERO_UNDEF(N); 1124 case ISD::CTPOP: return visitCTPOP(N); 1125 case ISD::SELECT: return visitSELECT(N); 1126 case ISD::SELECT_CC: return visitSELECT_CC(N); 1127 case ISD::SETCC: return visitSETCC(N); 1128 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N); 1129 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N); 1130 case ISD::ANY_EXTEND: return visitANY_EXTEND(N); 1131 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N); 1132 case ISD::TRUNCATE: return visitTRUNCATE(N); 1133 case ISD::BITCAST: return visitBITCAST(N); 1134 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N); 1135 case ISD::FADD: return visitFADD(N); 1136 case ISD::FSUB: return visitFSUB(N); 1137 case ISD::FMUL: return visitFMUL(N); 1138 case ISD::FMA: return visitFMA(N); 1139 case ISD::FDIV: return visitFDIV(N); 1140 case ISD::FREM: return visitFREM(N); 1141 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N); 1142 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N); 1143 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N); 1144 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N); 1145 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N); 1146 case ISD::FP_ROUND: return visitFP_ROUND(N); 1147 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N); 1148 case ISD::FP_EXTEND: return visitFP_EXTEND(N); 1149 case ISD::FNEG: return visitFNEG(N); 1150 case ISD::FABS: return visitFABS(N); 1151 case ISD::FFLOOR: return visitFFLOOR(N); 1152 case ISD::FCEIL: return visitFCEIL(N); 1153 case ISD::FTRUNC: return visitFTRUNC(N); 1154 case ISD::BRCOND: return visitBRCOND(N); 1155 case ISD::BR_CC: return visitBR_CC(N); 1156 case ISD::LOAD: return visitLOAD(N); 1157 case ISD::STORE: return visitSTORE(N); 1158 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N); 1159 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N); 1160 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N); 1161 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N); 1162 case ISD::EXTRACT_SUBVECTOR: return visitEXTRACT_SUBVECTOR(N); 1163 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N); 1164 case ISD::MEMBARRIER: return visitMEMBARRIER(N); 1165 } 1166 return SDValue(); 1167} 1168 1169SDValue DAGCombiner::combine(SDNode *N) { 1170 SDValue RV = visit(N); 1171 1172 // If nothing happened, try a target-specific DAG combine. 1173 if (RV.getNode() == 0) { 1174 assert(N->getOpcode() != ISD::DELETED_NODE && 1175 "Node was deleted but visit returned NULL!"); 1176 1177 if (N->getOpcode() >= ISD::BUILTIN_OP_END || 1178 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) { 1179 1180 // Expose the DAG combiner to the target combiner impls. 1181 TargetLowering::DAGCombinerInfo 1182 DagCombineInfo(DAG, !LegalTypes, !LegalOperations, false, this); 1183 1184 RV = TLI.PerformDAGCombine(N, DagCombineInfo); 1185 } 1186 } 1187 1188 // If nothing happened still, try promoting the operation. 1189 if (RV.getNode() == 0) { 1190 switch (N->getOpcode()) { 1191 default: break; 1192 case ISD::ADD: 1193 case ISD::SUB: 1194 case ISD::MUL: 1195 case ISD::AND: 1196 case ISD::OR: 1197 case ISD::XOR: 1198 RV = PromoteIntBinOp(SDValue(N, 0)); 1199 break; 1200 case ISD::SHL: 1201 case ISD::SRA: 1202 case ISD::SRL: 1203 RV = PromoteIntShiftOp(SDValue(N, 0)); 1204 break; 1205 case ISD::SIGN_EXTEND: 1206 case ISD::ZERO_EXTEND: 1207 case ISD::ANY_EXTEND: 1208 RV = PromoteExtend(SDValue(N, 0)); 1209 break; 1210 case ISD::LOAD: 1211 if (PromoteLoad(SDValue(N, 0))) 1212 RV = SDValue(N, 0); 1213 break; 1214 } 1215 } 1216 1217 // If N is a commutative binary node, try commuting it to enable more 1218 // sdisel CSE. 1219 if (RV.getNode() == 0 && 1220 SelectionDAG::isCommutativeBinOp(N->getOpcode()) && 1221 N->getNumValues() == 1) { 1222 SDValue N0 = N->getOperand(0); 1223 SDValue N1 = N->getOperand(1); 1224 1225 // Constant operands are canonicalized to RHS. 1226 if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) { 1227 SDValue Ops[] = { N1, N0 }; 1228 SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), 1229 Ops, 2); 1230 if (CSENode) 1231 return SDValue(CSENode, 0); 1232 } 1233 } 1234 1235 return RV; 1236} 1237 1238/// getInputChainForNode - Given a node, return its input chain if it has one, 1239/// otherwise return a null sd operand. 1240static SDValue getInputChainForNode(SDNode *N) { 1241 if (unsigned NumOps = N->getNumOperands()) { 1242 if (N->getOperand(0).getValueType() == MVT::Other) 1243 return N->getOperand(0); 1244 else if (N->getOperand(NumOps-1).getValueType() == MVT::Other) 1245 return N->getOperand(NumOps-1); 1246 for (unsigned i = 1; i < NumOps-1; ++i) 1247 if (N->getOperand(i).getValueType() == MVT::Other) 1248 return N->getOperand(i); 1249 } 1250 return SDValue(); 1251} 1252 1253SDValue DAGCombiner::visitTokenFactor(SDNode *N) { 1254 // If N has two operands, where one has an input chain equal to the other, 1255 // the 'other' chain is redundant. 1256 if (N->getNumOperands() == 2) { 1257 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1)) 1258 return N->getOperand(0); 1259 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0)) 1260 return N->getOperand(1); 1261 } 1262 1263 SmallVector<SDNode *, 8> TFs; // List of token factors to visit. 1264 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor. 1265 SmallPtrSet<SDNode*, 16> SeenOps; 1266 bool Changed = false; // If we should replace this token factor. 1267 1268 // Start out with this token factor. 1269 TFs.push_back(N); 1270 1271 // Iterate through token factors. The TFs grows when new token factors are 1272 // encountered. 1273 for (unsigned i = 0; i < TFs.size(); ++i) { 1274 SDNode *TF = TFs[i]; 1275 1276 // Check each of the operands. 1277 for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) { 1278 SDValue Op = TF->getOperand(i); 1279 1280 switch (Op.getOpcode()) { 1281 case ISD::EntryToken: 1282 // Entry tokens don't need to be added to the list. They are 1283 // rededundant. 1284 Changed = true; 1285 break; 1286 1287 case ISD::TokenFactor: 1288 if (Op.hasOneUse() && 1289 std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) { 1290 // Queue up for processing. 1291 TFs.push_back(Op.getNode()); 1292 // Clean up in case the token factor is removed. 1293 AddToWorkList(Op.getNode()); 1294 Changed = true; 1295 break; 1296 } 1297 // Fall thru 1298 1299 default: 1300 // Only add if it isn't already in the list. 1301 if (SeenOps.insert(Op.getNode())) 1302 Ops.push_back(Op); 1303 else 1304 Changed = true; 1305 break; 1306 } 1307 } 1308 } 1309 1310 SDValue Result; 1311 1312 // If we've change things around then replace token factor. 1313 if (Changed) { 1314 if (Ops.empty()) { 1315 // The entry token is the only possible outcome. 1316 Result = DAG.getEntryNode(); 1317 } else { 1318 // New and improved token factor. 1319 Result = DAG.getNode(ISD::TokenFactor, N->getDebugLoc(), 1320 MVT::Other, &Ops[0], Ops.size()); 1321 } 1322 1323 // Don't add users to work list. 1324 return CombineTo(N, Result, false); 1325 } 1326 1327 return Result; 1328} 1329 1330/// MERGE_VALUES can always be eliminated. 1331SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) { 1332 WorkListRemover DeadNodes(*this); 1333 // Replacing results may cause a different MERGE_VALUES to suddenly 1334 // be CSE'd with N, and carry its uses with it. Iterate until no 1335 // uses remain, to ensure that the node can be safely deleted. 1336 // First add the users of this node to the work list so that they 1337 // can be tried again once they have new operands. 1338 AddUsersToWorkList(N); 1339 do { 1340 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) 1341 DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i)); 1342 } while (!N->use_empty()); 1343 removeFromWorkList(N); 1344 DAG.DeleteNode(N); 1345 return SDValue(N, 0); // Return N so it doesn't get rechecked! 1346} 1347 1348static 1349SDValue combineShlAddConstant(DebugLoc DL, SDValue N0, SDValue N1, 1350 SelectionDAG &DAG) { 1351 EVT VT = N0.getValueType(); 1352 SDValue N00 = N0.getOperand(0); 1353 SDValue N01 = N0.getOperand(1); 1354 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N01); 1355 1356 if (N01C && N00.getOpcode() == ISD::ADD && N00.getNode()->hasOneUse() && 1357 isa<ConstantSDNode>(N00.getOperand(1))) { 1358 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), ) 1359 N0 = DAG.getNode(ISD::ADD, N0.getDebugLoc(), VT, 1360 DAG.getNode(ISD::SHL, N00.getDebugLoc(), VT, 1361 N00.getOperand(0), N01), 1362 DAG.getNode(ISD::SHL, N01.getDebugLoc(), VT, 1363 N00.getOperand(1), N01)); 1364 return DAG.getNode(ISD::ADD, DL, VT, N0, N1); 1365 } 1366 1367 return SDValue(); 1368} 1369 1370SDValue DAGCombiner::visitADD(SDNode *N) { 1371 SDValue N0 = N->getOperand(0); 1372 SDValue N1 = N->getOperand(1); 1373 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 1374 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 1375 EVT VT = N0.getValueType(); 1376 1377 // fold vector ops 1378 if (VT.isVector()) { 1379 SDValue FoldedVOp = SimplifyVBinOp(N); 1380 if (FoldedVOp.getNode()) return FoldedVOp; 1381 } 1382 1383 // fold (add x, undef) -> undef 1384 if (N0.getOpcode() == ISD::UNDEF) 1385 return N0; 1386 if (N1.getOpcode() == ISD::UNDEF) 1387 return N1; 1388 // fold (add c1, c2) -> c1+c2 1389 if (N0C && N1C) 1390 return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C); 1391 // canonicalize constant to RHS 1392 if (N0C && !N1C) 1393 return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N1, N0); 1394 // fold (add x, 0) -> x 1395 if (N1C && N1C->isNullValue()) 1396 return N0; 1397 // fold (add Sym, c) -> Sym+c 1398 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0)) 1399 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C && 1400 GA->getOpcode() == ISD::GlobalAddress) 1401 return DAG.getGlobalAddress(GA->getGlobal(), N1C->getDebugLoc(), VT, 1402 GA->getOffset() + 1403 (uint64_t)N1C->getSExtValue()); 1404 // fold ((c1-A)+c2) -> (c1+c2)-A 1405 if (N1C && N0.getOpcode() == ISD::SUB) 1406 if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0))) 1407 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, 1408 DAG.getConstant(N1C->getAPIntValue()+ 1409 N0C->getAPIntValue(), VT), 1410 N0.getOperand(1)); 1411 // reassociate add 1412 SDValue RADD = ReassociateOps(ISD::ADD, N->getDebugLoc(), N0, N1); 1413 if (RADD.getNode() != 0) 1414 return RADD; 1415 // fold ((0-A) + B) -> B-A 1416 if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) && 1417 cast<ConstantSDNode>(N0.getOperand(0))->isNullValue()) 1418 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N1, N0.getOperand(1)); 1419 // fold (A + (0-B)) -> A-B 1420 if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) && 1421 cast<ConstantSDNode>(N1.getOperand(0))->isNullValue()) 1422 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N0, N1.getOperand(1)); 1423 // fold (A+(B-A)) -> B 1424 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1)) 1425 return N1.getOperand(0); 1426 // fold ((B-A)+A) -> B 1427 if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1)) 1428 return N0.getOperand(0); 1429 // fold (A+(B-(A+C))) to (B-C) 1430 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD && 1431 N0 == N1.getOperand(1).getOperand(0)) 1432 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N1.getOperand(0), 1433 N1.getOperand(1).getOperand(1)); 1434 // fold (A+(B-(C+A))) to (B-C) 1435 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD && 1436 N0 == N1.getOperand(1).getOperand(1)) 1437 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N1.getOperand(0), 1438 N1.getOperand(1).getOperand(0)); 1439 // fold (A+((B-A)+or-C)) to (B+or-C) 1440 if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) && 1441 N1.getOperand(0).getOpcode() == ISD::SUB && 1442 N0 == N1.getOperand(0).getOperand(1)) 1443 return DAG.getNode(N1.getOpcode(), N->getDebugLoc(), VT, 1444 N1.getOperand(0).getOperand(0), N1.getOperand(1)); 1445 1446 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant 1447 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) { 1448 SDValue N00 = N0.getOperand(0); 1449 SDValue N01 = N0.getOperand(1); 1450 SDValue N10 = N1.getOperand(0); 1451 SDValue N11 = N1.getOperand(1); 1452 1453 if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10)) 1454 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, 1455 DAG.getNode(ISD::ADD, N0.getDebugLoc(), VT, N00, N10), 1456 DAG.getNode(ISD::ADD, N1.getDebugLoc(), VT, N01, N11)); 1457 } 1458 1459 if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0))) 1460 return SDValue(N, 0); 1461 1462 // fold (a+b) -> (a|b) iff a and b share no bits. 1463 if (VT.isInteger() && !VT.isVector()) { 1464 APInt LHSZero, LHSOne; 1465 APInt RHSZero, RHSOne; 1466 DAG.ComputeMaskedBits(N0, LHSZero, LHSOne); 1467 1468 if (LHSZero.getBoolValue()) { 1469 DAG.ComputeMaskedBits(N1, RHSZero, RHSOne); 1470 1471 // If all possibly-set bits on the LHS are clear on the RHS, return an OR. 1472 // If all possibly-set bits on the RHS are clear on the LHS, return an OR. 1473 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero) 1474 return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, N0, N1); 1475 } 1476 } 1477 1478 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), ) 1479 if (N0.getOpcode() == ISD::SHL && N0.getNode()->hasOneUse()) { 1480 SDValue Result = combineShlAddConstant(N->getDebugLoc(), N0, N1, DAG); 1481 if (Result.getNode()) return Result; 1482 } 1483 if (N1.getOpcode() == ISD::SHL && N1.getNode()->hasOneUse()) { 1484 SDValue Result = combineShlAddConstant(N->getDebugLoc(), N1, N0, DAG); 1485 if (Result.getNode()) return Result; 1486 } 1487 1488 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n)) 1489 if (N1.getOpcode() == ISD::SHL && 1490 N1.getOperand(0).getOpcode() == ISD::SUB) 1491 if (ConstantSDNode *C = 1492 dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0))) 1493 if (C->getAPIntValue() == 0) 1494 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N0, 1495 DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, 1496 N1.getOperand(0).getOperand(1), 1497 N1.getOperand(1))); 1498 if (N0.getOpcode() == ISD::SHL && 1499 N0.getOperand(0).getOpcode() == ISD::SUB) 1500 if (ConstantSDNode *C = 1501 dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0))) 1502 if (C->getAPIntValue() == 0) 1503 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N1, 1504 DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, 1505 N0.getOperand(0).getOperand(1), 1506 N0.getOperand(1))); 1507 1508 if (N1.getOpcode() == ISD::AND) { 1509 SDValue AndOp0 = N1.getOperand(0); 1510 ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1)); 1511 unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0); 1512 unsigned DestBits = VT.getScalarType().getSizeInBits(); 1513 1514 // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x)) 1515 // and similar xforms where the inner op is either ~0 or 0. 1516 if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) { 1517 DebugLoc DL = N->getDebugLoc(); 1518 return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0); 1519 } 1520 } 1521 1522 // add (sext i1), X -> sub X, (zext i1) 1523 if (N0.getOpcode() == ISD::SIGN_EXTEND && 1524 N0.getOperand(0).getValueType() == MVT::i1 && 1525 !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) { 1526 DebugLoc DL = N->getDebugLoc(); 1527 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)); 1528 return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt); 1529 } 1530 1531 return SDValue(); 1532} 1533 1534SDValue DAGCombiner::visitADDC(SDNode *N) { 1535 SDValue N0 = N->getOperand(0); 1536 SDValue N1 = N->getOperand(1); 1537 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 1538 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 1539 EVT VT = N0.getValueType(); 1540 1541 // If the flag result is dead, turn this into an ADD. 1542 if (!N->hasAnyUseOfValue(1)) 1543 return CombineTo(N, DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0, N1), 1544 DAG.getNode(ISD::CARRY_FALSE, 1545 N->getDebugLoc(), MVT::Glue)); 1546 1547 // canonicalize constant to RHS. 1548 if (N0C && !N1C) 1549 return DAG.getNode(ISD::ADDC, N->getDebugLoc(), N->getVTList(), N1, N0); 1550 1551 // fold (addc x, 0) -> x + no carry out 1552 if (N1C && N1C->isNullValue()) 1553 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, 1554 N->getDebugLoc(), MVT::Glue)); 1555 1556 // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits. 1557 APInt LHSZero, LHSOne; 1558 APInt RHSZero, RHSOne; 1559 DAG.ComputeMaskedBits(N0, LHSZero, LHSOne); 1560 1561 if (LHSZero.getBoolValue()) { 1562 DAG.ComputeMaskedBits(N1, RHSZero, RHSOne); 1563 1564 // If all possibly-set bits on the LHS are clear on the RHS, return an OR. 1565 // If all possibly-set bits on the RHS are clear on the LHS, return an OR. 1566 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero) 1567 return CombineTo(N, DAG.getNode(ISD::OR, N->getDebugLoc(), VT, N0, N1), 1568 DAG.getNode(ISD::CARRY_FALSE, 1569 N->getDebugLoc(), MVT::Glue)); 1570 } 1571 1572 return SDValue(); 1573} 1574 1575SDValue DAGCombiner::visitADDE(SDNode *N) { 1576 SDValue N0 = N->getOperand(0); 1577 SDValue N1 = N->getOperand(1); 1578 SDValue CarryIn = N->getOperand(2); 1579 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 1580 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 1581 1582 // canonicalize constant to RHS 1583 if (N0C && !N1C) 1584 return DAG.getNode(ISD::ADDE, N->getDebugLoc(), N->getVTList(), 1585 N1, N0, CarryIn); 1586 1587 // fold (adde x, y, false) -> (addc x, y) 1588 if (CarryIn.getOpcode() == ISD::CARRY_FALSE) 1589 return DAG.getNode(ISD::ADDC, N->getDebugLoc(), N->getVTList(), N0, N1); 1590 1591 return SDValue(); 1592} 1593 1594// Since it may not be valid to emit a fold to zero for vector initializers 1595// check if we can before folding. 1596static SDValue tryFoldToZero(DebugLoc DL, const TargetLowering &TLI, EVT VT, 1597 SelectionDAG &DAG, bool LegalOperations) { 1598 if (!VT.isVector()) { 1599 return DAG.getConstant(0, VT); 1600 } 1601 if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT)) { 1602 // Produce a vector of zeros. 1603 SDValue El = DAG.getConstant(0, VT.getVectorElementType()); 1604 std::vector<SDValue> Ops(VT.getVectorNumElements(), El); 1605 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, 1606 &Ops[0], Ops.size()); 1607 } 1608 return SDValue(); 1609} 1610 1611SDValue DAGCombiner::visitSUB(SDNode *N) { 1612 SDValue N0 = N->getOperand(0); 1613 SDValue N1 = N->getOperand(1); 1614 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode()); 1615 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode()); 1616 ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? 0 : 1617 dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode()); 1618 EVT VT = N0.getValueType(); 1619 1620 // fold vector ops 1621 if (VT.isVector()) { 1622 SDValue FoldedVOp = SimplifyVBinOp(N); 1623 if (FoldedVOp.getNode()) return FoldedVOp; 1624 } 1625 1626 // fold (sub x, x) -> 0 1627 // FIXME: Refactor this and xor and other similar operations together. 1628 if (N0 == N1) 1629 return tryFoldToZero(N->getDebugLoc(), TLI, VT, DAG, LegalOperations); 1630 // fold (sub c1, c2) -> c1-c2 1631 if (N0C && N1C) 1632 return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C); 1633 // fold (sub x, c) -> (add x, -c) 1634 if (N1C) 1635 return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0, 1636 DAG.getConstant(-N1C->getAPIntValue(), VT)); 1637 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) 1638 if (N0C && N0C->isAllOnesValue()) 1639 return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT, N1, N0); 1640 // fold A-(A-B) -> B 1641 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0)) 1642 return N1.getOperand(1); 1643 // fold (A+B)-A -> B 1644 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1) 1645 return N0.getOperand(1); 1646 // fold (A+B)-B -> A 1647 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1) 1648 return N0.getOperand(0); 1649 // fold C2-(A+C1) -> (C2-C1)-A 1650 if (N1.getOpcode() == ISD::ADD && N0C && N1C1) { 1651 SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(), 1652 VT); 1653 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, NewC, 1654 N1.getOperand(0)); 1655 } 1656 // fold ((A+(B+or-C))-B) -> A+or-C 1657 if (N0.getOpcode() == ISD::ADD && 1658 (N0.getOperand(1).getOpcode() == ISD::SUB || 1659 N0.getOperand(1).getOpcode() == ISD::ADD) && 1660 N0.getOperand(1).getOperand(0) == N1) 1661 return DAG.getNode(N0.getOperand(1).getOpcode(), N->getDebugLoc(), VT, 1662 N0.getOperand(0), N0.getOperand(1).getOperand(1)); 1663 // fold ((A+(C+B))-B) -> A+C 1664 if (N0.getOpcode() == ISD::ADD && 1665 N0.getOperand(1).getOpcode() == ISD::ADD && 1666 N0.getOperand(1).getOperand(1) == N1) 1667 return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, 1668 N0.getOperand(0), N0.getOperand(1).getOperand(0)); 1669 // fold ((A-(B-C))-C) -> A-B 1670 if (N0.getOpcode() == ISD::SUB && 1671 N0.getOperand(1).getOpcode() == ISD::SUB && 1672 N0.getOperand(1).getOperand(1) == N1) 1673 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, 1674 N0.getOperand(0), N0.getOperand(1).getOperand(0)); 1675 1676 // If either operand of a sub is undef, the result is undef 1677 if (N0.getOpcode() == ISD::UNDEF) 1678 return N0; 1679 if (N1.getOpcode() == ISD::UNDEF) 1680 return N1; 1681 1682 // If the relocation model supports it, consider symbol offsets. 1683 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0)) 1684 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) { 1685 // fold (sub Sym, c) -> Sym-c 1686 if (N1C && GA->getOpcode() == ISD::GlobalAddress) 1687 return DAG.getGlobalAddress(GA->getGlobal(), N1C->getDebugLoc(), VT, 1688 GA->getOffset() - 1689 (uint64_t)N1C->getSExtValue()); 1690 // fold (sub Sym+c1, Sym+c2) -> c1-c2 1691 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1)) 1692 if (GA->getGlobal() == GB->getGlobal()) 1693 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(), 1694 VT); 1695 } 1696 1697 return SDValue(); 1698} 1699 1700SDValue DAGCombiner::visitSUBC(SDNode *N) { 1701 SDValue N0 = N->getOperand(0); 1702 SDValue N1 = N->getOperand(1); 1703 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 1704 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 1705 EVT VT = N0.getValueType(); 1706 1707 // If the flag result is dead, turn this into an SUB. 1708 if (!N->hasAnyUseOfValue(1)) 1709 return CombineTo(N, DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N0, N1), 1710 DAG.getNode(ISD::CARRY_FALSE, N->getDebugLoc(), 1711 MVT::Glue)); 1712 1713 // fold (subc x, x) -> 0 + no borrow 1714 if (N0 == N1) 1715 return CombineTo(N, DAG.getConstant(0, VT), 1716 DAG.getNode(ISD::CARRY_FALSE, N->getDebugLoc(), 1717 MVT::Glue)); 1718 1719 // fold (subc x, 0) -> x + no borrow 1720 if (N1C && N1C->isNullValue()) 1721 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, N->getDebugLoc(), 1722 MVT::Glue)); 1723 1724 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow 1725 if (N0C && N0C->isAllOnesValue()) 1726 return CombineTo(N, DAG.getNode(ISD::XOR, N->getDebugLoc(), VT, N1, N0), 1727 DAG.getNode(ISD::CARRY_FALSE, N->getDebugLoc(), 1728 MVT::Glue)); 1729 1730 return SDValue(); 1731} 1732 1733SDValue DAGCombiner::visitSUBE(SDNode *N) { 1734 SDValue N0 = N->getOperand(0); 1735 SDValue N1 = N->getOperand(1); 1736 SDValue CarryIn = N->getOperand(2); 1737 1738 // fold (sube x, y, false) -> (subc x, y) 1739 if (CarryIn.getOpcode() == ISD::CARRY_FALSE) 1740 return DAG.getNode(ISD::SUBC, N->getDebugLoc(), N->getVTList(), N0, N1); 1741 1742 return SDValue(); 1743} 1744 1745SDValue DAGCombiner::visitMUL(SDNode *N) { 1746 SDValue N0 = N->getOperand(0); 1747 SDValue N1 = N->getOperand(1); 1748 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 1749 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 1750 EVT VT = N0.getValueType(); 1751 1752 // fold vector ops 1753 if (VT.isVector()) { 1754 SDValue FoldedVOp = SimplifyVBinOp(N); 1755 if (FoldedVOp.getNode()) return FoldedVOp; 1756 } 1757 1758 // fold (mul x, undef) -> 0 1759 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF) 1760 return DAG.getConstant(0, VT); 1761 // fold (mul c1, c2) -> c1*c2 1762 if (N0C && N1C) 1763 return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0C, N1C); 1764 // canonicalize constant to RHS 1765 if (N0C && !N1C) 1766 return DAG.getNode(ISD::MUL, N->getDebugLoc(), VT, N1, N0); 1767 // fold (mul x, 0) -> 0 1768 if (N1C && N1C->isNullValue()) 1769 return N1; 1770 // fold (mul x, -1) -> 0-x 1771 if (N1C && N1C->isAllOnesValue()) 1772 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, 1773 DAG.getConstant(0, VT), N0); 1774 // fold (mul x, (1 << c)) -> x << c 1775 if (N1C && N1C->getAPIntValue().isPowerOf2()) 1776 return DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, N0, 1777 DAG.getConstant(N1C->getAPIntValue().logBase2(), 1778 getShiftAmountTy(N0.getValueType()))); 1779 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c 1780 if (N1C && (-N1C->getAPIntValue()).isPowerOf2()) { 1781 unsigned Log2Val = (-N1C->getAPIntValue()).logBase2(); 1782 // FIXME: If the input is something that is easily negated (e.g. a 1783 // single-use add), we should put the negate there. 1784 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, 1785 DAG.getConstant(0, VT), 1786 DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, N0, 1787 DAG.getConstant(Log2Val, 1788 getShiftAmountTy(N0.getValueType())))); 1789 } 1790 // (mul (shl X, c1), c2) -> (mul X, c2 << c1) 1791 if (N1C && N0.getOpcode() == ISD::SHL && 1792 isa<ConstantSDNode>(N0.getOperand(1))) { 1793 SDValue C3 = DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, 1794 N1, N0.getOperand(1)); 1795 AddToWorkList(C3.getNode()); 1796 return DAG.getNode(ISD::MUL, N->getDebugLoc(), VT, 1797 N0.getOperand(0), C3); 1798 } 1799 1800 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one 1801 // use. 1802 { 1803 SDValue Sh(0,0), Y(0,0); 1804 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)). 1805 if (N0.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N0.getOperand(1)) && 1806 N0.getNode()->hasOneUse()) { 1807 Sh = N0; Y = N1; 1808 } else if (N1.getOpcode() == ISD::SHL && 1809 isa<ConstantSDNode>(N1.getOperand(1)) && 1810 N1.getNode()->hasOneUse()) { 1811 Sh = N1; Y = N0; 1812 } 1813 1814 if (Sh.getNode()) { 1815 SDValue Mul = DAG.getNode(ISD::MUL, N->getDebugLoc(), VT, 1816 Sh.getOperand(0), Y); 1817 return DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, 1818 Mul, Sh.getOperand(1)); 1819 } 1820 } 1821 1822 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2) 1823 if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() && 1824 isa<ConstantSDNode>(N0.getOperand(1))) 1825 return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, 1826 DAG.getNode(ISD::MUL, N0.getDebugLoc(), VT, 1827 N0.getOperand(0), N1), 1828 DAG.getNode(ISD::MUL, N1.getDebugLoc(), VT, 1829 N0.getOperand(1), N1)); 1830 1831 // reassociate mul 1832 SDValue RMUL = ReassociateOps(ISD::MUL, N->getDebugLoc(), N0, N1); 1833 if (RMUL.getNode() != 0) 1834 return RMUL; 1835 1836 return SDValue(); 1837} 1838 1839SDValue DAGCombiner::visitSDIV(SDNode *N) { 1840 SDValue N0 = N->getOperand(0); 1841 SDValue N1 = N->getOperand(1); 1842 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode()); 1843 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode()); 1844 EVT VT = N->getValueType(0); 1845 1846 // fold vector ops 1847 if (VT.isVector()) { 1848 SDValue FoldedVOp = SimplifyVBinOp(N); 1849 if (FoldedVOp.getNode()) return FoldedVOp; 1850 } 1851 1852 // fold (sdiv c1, c2) -> c1/c2 1853 if (N0C && N1C && !N1C->isNullValue()) 1854 return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C); 1855 // fold (sdiv X, 1) -> X 1856 if (N1C && N1C->getAPIntValue() == 1LL) 1857 return N0; 1858 // fold (sdiv X, -1) -> 0-X 1859 if (N1C && N1C->isAllOnesValue()) 1860 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, 1861 DAG.getConstant(0, VT), N0); 1862 // If we know the sign bits of both operands are zero, strength reduce to a 1863 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2 1864 if (!VT.isVector()) { 1865 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0)) 1866 return DAG.getNode(ISD::UDIV, N->getDebugLoc(), N1.getValueType(), 1867 N0, N1); 1868 } 1869 // fold (sdiv X, pow2) -> simple ops after legalize 1870 if (N1C && !N1C->isNullValue() && 1871 (N1C->getAPIntValue().isPowerOf2() || 1872 (-N1C->getAPIntValue()).isPowerOf2())) { 1873 // If dividing by powers of two is cheap, then don't perform the following 1874 // fold. 1875 if (TLI.isPow2DivCheap()) 1876 return SDValue(); 1877 1878 unsigned lg2 = N1C->getAPIntValue().countTrailingZeros(); 1879 1880 // Splat the sign bit into the register 1881 SDValue SGN = DAG.getNode(ISD::SRA, N->getDebugLoc(), VT, N0, 1882 DAG.getConstant(VT.getSizeInBits()-1, 1883 getShiftAmountTy(N0.getValueType()))); 1884 AddToWorkList(SGN.getNode()); 1885 1886 // Add (N0 < 0) ? abs2 - 1 : 0; 1887 SDValue SRL = DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, SGN, 1888 DAG.getConstant(VT.getSizeInBits() - lg2, 1889 getShiftAmountTy(SGN.getValueType()))); 1890 SDValue ADD = DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0, SRL); 1891 AddToWorkList(SRL.getNode()); 1892 AddToWorkList(ADD.getNode()); // Divide by pow2 1893 SDValue SRA = DAG.getNode(ISD::SRA, N->getDebugLoc(), VT, ADD, 1894 DAG.getConstant(lg2, getShiftAmountTy(ADD.getValueType()))); 1895 1896 // If we're dividing by a positive value, we're done. Otherwise, we must 1897 // negate the result. 1898 if (N1C->getAPIntValue().isNonNegative()) 1899 return SRA; 1900 1901 AddToWorkList(SRA.getNode()); 1902 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, 1903 DAG.getConstant(0, VT), SRA); 1904 } 1905 1906 // if integer divide is expensive and we satisfy the requirements, emit an 1907 // alternate sequence. 1908 if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap()) { 1909 SDValue Op = BuildSDIV(N); 1910 if (Op.getNode()) return Op; 1911 } 1912 1913 // undef / X -> 0 1914 if (N0.getOpcode() == ISD::UNDEF) 1915 return DAG.getConstant(0, VT); 1916 // X / undef -> undef 1917 if (N1.getOpcode() == ISD::UNDEF) 1918 return N1; 1919 1920 return SDValue(); 1921} 1922 1923SDValue DAGCombiner::visitUDIV(SDNode *N) { 1924 SDValue N0 = N->getOperand(0); 1925 SDValue N1 = N->getOperand(1); 1926 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode()); 1927 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode()); 1928 EVT VT = N->getValueType(0); 1929 1930 // fold vector ops 1931 if (VT.isVector()) { 1932 SDValue FoldedVOp = SimplifyVBinOp(N); 1933 if (FoldedVOp.getNode()) return FoldedVOp; 1934 } 1935 1936 // fold (udiv c1, c2) -> c1/c2 1937 if (N0C && N1C && !N1C->isNullValue()) 1938 return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C); 1939 // fold (udiv x, (1 << c)) -> x >>u c 1940 if (N1C && N1C->getAPIntValue().isPowerOf2()) 1941 return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0, 1942 DAG.getConstant(N1C->getAPIntValue().logBase2(), 1943 getShiftAmountTy(N0.getValueType()))); 1944 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2 1945 if (N1.getOpcode() == ISD::SHL) { 1946 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) { 1947 if (SHC->getAPIntValue().isPowerOf2()) { 1948 EVT ADDVT = N1.getOperand(1).getValueType(); 1949 SDValue Add = DAG.getNode(ISD::ADD, N->getDebugLoc(), ADDVT, 1950 N1.getOperand(1), 1951 DAG.getConstant(SHC->getAPIntValue() 1952 .logBase2(), 1953 ADDVT)); 1954 AddToWorkList(Add.getNode()); 1955 return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0, Add); 1956 } 1957 } 1958 } 1959 // fold (udiv x, c) -> alternate 1960 if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap()) { 1961 SDValue Op = BuildUDIV(N); 1962 if (Op.getNode()) return Op; 1963 } 1964 1965 // undef / X -> 0 1966 if (N0.getOpcode() == ISD::UNDEF) 1967 return DAG.getConstant(0, VT); 1968 // X / undef -> undef 1969 if (N1.getOpcode() == ISD::UNDEF) 1970 return N1; 1971 1972 return SDValue(); 1973} 1974 1975SDValue DAGCombiner::visitSREM(SDNode *N) { 1976 SDValue N0 = N->getOperand(0); 1977 SDValue N1 = N->getOperand(1); 1978 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 1979 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 1980 EVT VT = N->getValueType(0); 1981 1982 // fold (srem c1, c2) -> c1%c2 1983 if (N0C && N1C && !N1C->isNullValue()) 1984 return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C); 1985 // If we know the sign bits of both operands are zero, strength reduce to a 1986 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15 1987 if (!VT.isVector()) { 1988 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0)) 1989 return DAG.getNode(ISD::UREM, N->getDebugLoc(), VT, N0, N1); 1990 } 1991 1992 // If X/C can be simplified by the division-by-constant logic, lower 1993 // X%C to the equivalent of X-X/C*C. 1994 if (N1C && !N1C->isNullValue()) { 1995 SDValue Div = DAG.getNode(ISD::SDIV, N->getDebugLoc(), VT, N0, N1); 1996 AddToWorkList(Div.getNode()); 1997 SDValue OptimizedDiv = combine(Div.getNode()); 1998 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) { 1999 SDValue Mul = DAG.getNode(ISD::MUL, N->getDebugLoc(), VT, 2000 OptimizedDiv, N1); 2001 SDValue Sub = DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N0, Mul); 2002 AddToWorkList(Mul.getNode()); 2003 return Sub; 2004 } 2005 } 2006 2007 // undef % X -> 0 2008 if (N0.getOpcode() == ISD::UNDEF) 2009 return DAG.getConstant(0, VT); 2010 // X % undef -> undef 2011 if (N1.getOpcode() == ISD::UNDEF) 2012 return N1; 2013 2014 return SDValue(); 2015} 2016 2017SDValue DAGCombiner::visitUREM(SDNode *N) { 2018 SDValue N0 = N->getOperand(0); 2019 SDValue N1 = N->getOperand(1); 2020 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 2021 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 2022 EVT VT = N->getValueType(0); 2023 2024 // fold (urem c1, c2) -> c1%c2 2025 if (N0C && N1C && !N1C->isNullValue()) 2026 return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C); 2027 // fold (urem x, pow2) -> (and x, pow2-1) 2028 if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2()) 2029 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0, 2030 DAG.getConstant(N1C->getAPIntValue()-1,VT)); 2031 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1)) 2032 if (N1.getOpcode() == ISD::SHL) { 2033 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) { 2034 if (SHC->getAPIntValue().isPowerOf2()) { 2035 SDValue Add = 2036 DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N1, 2037 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), 2038 VT)); 2039 AddToWorkList(Add.getNode()); 2040 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0, Add); 2041 } 2042 } 2043 } 2044 2045 // If X/C can be simplified by the division-by-constant logic, lower 2046 // X%C to the equivalent of X-X/C*C. 2047 if (N1C && !N1C->isNullValue()) { 2048 SDValue Div = DAG.getNode(ISD::UDIV, N->getDebugLoc(), VT, N0, N1); 2049 AddToWorkList(Div.getNode()); 2050 SDValue OptimizedDiv = combine(Div.getNode()); 2051 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) { 2052 SDValue Mul = DAG.getNode(ISD::MUL, N->getDebugLoc(), VT, 2053 OptimizedDiv, N1); 2054 SDValue Sub = DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N0, Mul); 2055 AddToWorkList(Mul.getNode()); 2056 return Sub; 2057 } 2058 } 2059 2060 // undef % X -> 0 2061 if (N0.getOpcode() == ISD::UNDEF) 2062 return DAG.getConstant(0, VT); 2063 // X % undef -> undef 2064 if (N1.getOpcode() == ISD::UNDEF) 2065 return N1; 2066 2067 return SDValue(); 2068} 2069 2070SDValue DAGCombiner::visitMULHS(SDNode *N) { 2071 SDValue N0 = N->getOperand(0); 2072 SDValue N1 = N->getOperand(1); 2073 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 2074 EVT VT = N->getValueType(0); 2075 DebugLoc DL = N->getDebugLoc(); 2076 2077 // fold (mulhs x, 0) -> 0 2078 if (N1C && N1C->isNullValue()) 2079 return N1; 2080 // fold (mulhs x, 1) -> (sra x, size(x)-1) 2081 if (N1C && N1C->getAPIntValue() == 1) 2082 return DAG.getNode(ISD::SRA, N->getDebugLoc(), N0.getValueType(), N0, 2083 DAG.getConstant(N0.getValueType().getSizeInBits() - 1, 2084 getShiftAmountTy(N0.getValueType()))); 2085 // fold (mulhs x, undef) -> 0 2086 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF) 2087 return DAG.getConstant(0, VT); 2088 2089 // If the type twice as wide is legal, transform the mulhs to a wider multiply 2090 // plus a shift. 2091 if (VT.isSimple() && !VT.isVector()) { 2092 MVT Simple = VT.getSimpleVT(); 2093 unsigned SimpleSize = Simple.getSizeInBits(); 2094 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 2095 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 2096 N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0); 2097 N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1); 2098 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1); 2099 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1, 2100 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType()))); 2101 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1); 2102 } 2103 } 2104 2105 return SDValue(); 2106} 2107 2108SDValue DAGCombiner::visitMULHU(SDNode *N) { 2109 SDValue N0 = N->getOperand(0); 2110 SDValue N1 = N->getOperand(1); 2111 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 2112 EVT VT = N->getValueType(0); 2113 DebugLoc DL = N->getDebugLoc(); 2114 2115 // fold (mulhu x, 0) -> 0 2116 if (N1C && N1C->isNullValue()) 2117 return N1; 2118 // fold (mulhu x, 1) -> 0 2119 if (N1C && N1C->getAPIntValue() == 1) 2120 return DAG.getConstant(0, N0.getValueType()); 2121 // fold (mulhu x, undef) -> 0 2122 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF) 2123 return DAG.getConstant(0, VT); 2124 2125 // If the type twice as wide is legal, transform the mulhu to a wider multiply 2126 // plus a shift. 2127 if (VT.isSimple() && !VT.isVector()) { 2128 MVT Simple = VT.getSimpleVT(); 2129 unsigned SimpleSize = Simple.getSizeInBits(); 2130 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 2131 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 2132 N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0); 2133 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1); 2134 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1); 2135 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1, 2136 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType()))); 2137 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1); 2138 } 2139 } 2140 2141 return SDValue(); 2142} 2143 2144/// SimplifyNodeWithTwoResults - Perform optimizations common to nodes that 2145/// compute two values. LoOp and HiOp give the opcodes for the two computations 2146/// that are being performed. Return true if a simplification was made. 2147/// 2148SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp, 2149 unsigned HiOp) { 2150 // If the high half is not needed, just compute the low half. 2151 bool HiExists = N->hasAnyUseOfValue(1); 2152 if (!HiExists && 2153 (!LegalOperations || 2154 TLI.isOperationLegal(LoOp, N->getValueType(0)))) { 2155 SDValue Res = DAG.getNode(LoOp, N->getDebugLoc(), N->getValueType(0), 2156 N->op_begin(), N->getNumOperands()); 2157 return CombineTo(N, Res, Res); 2158 } 2159 2160 // If the low half is not needed, just compute the high half. 2161 bool LoExists = N->hasAnyUseOfValue(0); 2162 if (!LoExists && 2163 (!LegalOperations || 2164 TLI.isOperationLegal(HiOp, N->getValueType(1)))) { 2165 SDValue Res = DAG.getNode(HiOp, N->getDebugLoc(), N->getValueType(1), 2166 N->op_begin(), N->getNumOperands()); 2167 return CombineTo(N, Res, Res); 2168 } 2169 2170 // If both halves are used, return as it is. 2171 if (LoExists && HiExists) 2172 return SDValue(); 2173 2174 // If the two computed results can be simplified separately, separate them. 2175 if (LoExists) { 2176 SDValue Lo = DAG.getNode(LoOp, N->getDebugLoc(), N->getValueType(0), 2177 N->op_begin(), N->getNumOperands()); 2178 AddToWorkList(Lo.getNode()); 2179 SDValue LoOpt = combine(Lo.getNode()); 2180 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() && 2181 (!LegalOperations || 2182 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType()))) 2183 return CombineTo(N, LoOpt, LoOpt); 2184 } 2185 2186 if (HiExists) { 2187 SDValue Hi = DAG.getNode(HiOp, N->getDebugLoc(), N->getValueType(1), 2188 N->op_begin(), N->getNumOperands()); 2189 AddToWorkList(Hi.getNode()); 2190 SDValue HiOpt = combine(Hi.getNode()); 2191 if (HiOpt.getNode() && HiOpt != Hi && 2192 (!LegalOperations || 2193 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType()))) 2194 return CombineTo(N, HiOpt, HiOpt); 2195 } 2196 2197 return SDValue(); 2198} 2199 2200SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) { 2201 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS); 2202 if (Res.getNode()) return Res; 2203 2204 EVT VT = N->getValueType(0); 2205 DebugLoc DL = N->getDebugLoc(); 2206 2207 // If the type twice as wide is legal, transform the mulhu to a wider multiply 2208 // plus a shift. 2209 if (VT.isSimple() && !VT.isVector()) { 2210 MVT Simple = VT.getSimpleVT(); 2211 unsigned SimpleSize = Simple.getSizeInBits(); 2212 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 2213 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 2214 SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0)); 2215 SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1)); 2216 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi); 2217 // Compute the high part as N1. 2218 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo, 2219 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType()))); 2220 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi); 2221 // Compute the low part as N0. 2222 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo); 2223 return CombineTo(N, Lo, Hi); 2224 } 2225 } 2226 2227 return SDValue(); 2228} 2229 2230SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) { 2231 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU); 2232 if (Res.getNode()) return Res; 2233 2234 EVT VT = N->getValueType(0); 2235 DebugLoc DL = N->getDebugLoc(); 2236 2237 // If the type twice as wide is legal, transform the mulhu to a wider multiply 2238 // plus a shift. 2239 if (VT.isSimple() && !VT.isVector()) { 2240 MVT Simple = VT.getSimpleVT(); 2241 unsigned SimpleSize = Simple.getSizeInBits(); 2242 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 2243 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 2244 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0)); 2245 SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1)); 2246 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi); 2247 // Compute the high part as N1. 2248 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo, 2249 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType()))); 2250 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi); 2251 // Compute the low part as N0. 2252 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo); 2253 return CombineTo(N, Lo, Hi); 2254 } 2255 } 2256 2257 return SDValue(); 2258} 2259 2260SDValue DAGCombiner::visitSMULO(SDNode *N) { 2261 // (smulo x, 2) -> (saddo x, x) 2262 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1))) 2263 if (C2->getAPIntValue() == 2) 2264 return DAG.getNode(ISD::SADDO, N->getDebugLoc(), N->getVTList(), 2265 N->getOperand(0), N->getOperand(0)); 2266 2267 return SDValue(); 2268} 2269 2270SDValue DAGCombiner::visitUMULO(SDNode *N) { 2271 // (umulo x, 2) -> (uaddo x, x) 2272 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1))) 2273 if (C2->getAPIntValue() == 2) 2274 return DAG.getNode(ISD::UADDO, N->getDebugLoc(), N->getVTList(), 2275 N->getOperand(0), N->getOperand(0)); 2276 2277 return SDValue(); 2278} 2279 2280SDValue DAGCombiner::visitSDIVREM(SDNode *N) { 2281 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM); 2282 if (Res.getNode()) return Res; 2283 2284 return SDValue(); 2285} 2286 2287SDValue DAGCombiner::visitUDIVREM(SDNode *N) { 2288 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM); 2289 if (Res.getNode()) return Res; 2290 2291 return SDValue(); 2292} 2293 2294/// SimplifyBinOpWithSameOpcodeHands - If this is a binary operator with 2295/// two operands of the same opcode, try to simplify it. 2296SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) { 2297 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1); 2298 EVT VT = N0.getValueType(); 2299 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!"); 2300 2301 // Bail early if none of these transforms apply. 2302 if (N0.getNode()->getNumOperands() == 0) return SDValue(); 2303 2304 // For each of OP in AND/OR/XOR: 2305 // fold (OP (zext x), (zext y)) -> (zext (OP x, y)) 2306 // fold (OP (sext x), (sext y)) -> (sext (OP x, y)) 2307 // fold (OP (aext x), (aext y)) -> (aext (OP x, y)) 2308 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free) 2309 // 2310 // do not sink logical op inside of a vector extend, since it may combine 2311 // into a vsetcc. 2312 EVT Op0VT = N0.getOperand(0).getValueType(); 2313 if ((N0.getOpcode() == ISD::ZERO_EXTEND || 2314 N0.getOpcode() == ISD::SIGN_EXTEND || 2315 // Avoid infinite looping with PromoteIntBinOp. 2316 (N0.getOpcode() == ISD::ANY_EXTEND && 2317 (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) || 2318 (N0.getOpcode() == ISD::TRUNCATE && 2319 (!TLI.isZExtFree(VT, Op0VT) || 2320 !TLI.isTruncateFree(Op0VT, VT)) && 2321 TLI.isTypeLegal(Op0VT))) && 2322 !VT.isVector() && 2323 Op0VT == N1.getOperand(0).getValueType() && 2324 (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) { 2325 SDValue ORNode = DAG.getNode(N->getOpcode(), N0.getDebugLoc(), 2326 N0.getOperand(0).getValueType(), 2327 N0.getOperand(0), N1.getOperand(0)); 2328 AddToWorkList(ORNode.getNode()); 2329 return DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT, ORNode); 2330 } 2331 2332 // For each of OP in SHL/SRL/SRA/AND... 2333 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z) 2334 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z) 2335 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z) 2336 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL || 2337 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) && 2338 N0.getOperand(1) == N1.getOperand(1)) { 2339 SDValue ORNode = DAG.getNode(N->getOpcode(), N0.getDebugLoc(), 2340 N0.getOperand(0).getValueType(), 2341 N0.getOperand(0), N1.getOperand(0)); 2342 AddToWorkList(ORNode.getNode()); 2343 return DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT, 2344 ORNode, N0.getOperand(1)); 2345 } 2346 2347 // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B)) 2348 // Only perform this optimization after type legalization and before 2349 // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by 2350 // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and 2351 // we don't want to undo this promotion. 2352 // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper 2353 // on scalars. 2354 if ((N0.getOpcode() == ISD::BITCAST || 2355 N0.getOpcode() == ISD::SCALAR_TO_VECTOR) && 2356 Level == AfterLegalizeTypes) { 2357 SDValue In0 = N0.getOperand(0); 2358 SDValue In1 = N1.getOperand(0); 2359 EVT In0Ty = In0.getValueType(); 2360 EVT In1Ty = In1.getValueType(); 2361 DebugLoc DL = N->getDebugLoc(); 2362 // If both incoming values are integers, and the original types are the 2363 // same. 2364 if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) { 2365 SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1); 2366 SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op); 2367 AddToWorkList(Op.getNode()); 2368 return BC; 2369 } 2370 } 2371 2372 // Xor/and/or are indifferent to the swizzle operation (shuffle of one value). 2373 // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B)) 2374 // If both shuffles use the same mask, and both shuffle within a single 2375 // vector, then it is worthwhile to move the swizzle after the operation. 2376 // The type-legalizer generates this pattern when loading illegal 2377 // vector types from memory. In many cases this allows additional shuffle 2378 // optimizations. 2379 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG && 2380 N0.getOperand(1).getOpcode() == ISD::UNDEF && 2381 N1.getOperand(1).getOpcode() == ISD::UNDEF) { 2382 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0); 2383 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1); 2384 2385 assert(N0.getOperand(0).getValueType() == N1.getOperand(1).getValueType() && 2386 "Inputs to shuffles are not the same type"); 2387 2388 unsigned NumElts = VT.getVectorNumElements(); 2389 2390 // Check that both shuffles use the same mask. The masks are known to be of 2391 // the same length because the result vector type is the same. 2392 bool SameMask = true; 2393 for (unsigned i = 0; i != NumElts; ++i) { 2394 int Idx0 = SVN0->getMaskElt(i); 2395 int Idx1 = SVN1->getMaskElt(i); 2396 if (Idx0 != Idx1) { 2397 SameMask = false; 2398 break; 2399 } 2400 } 2401 2402 if (SameMask) { 2403 SDValue Op = DAG.getNode(N->getOpcode(), N->getDebugLoc(), VT, 2404 N0.getOperand(0), N1.getOperand(0)); 2405 AddToWorkList(Op.getNode()); 2406 return DAG.getVectorShuffle(VT, N->getDebugLoc(), Op, 2407 DAG.getUNDEF(VT), &SVN0->getMask()[0]); 2408 } 2409 } 2410 2411 return SDValue(); 2412} 2413 2414SDValue DAGCombiner::visitAND(SDNode *N) { 2415 SDValue N0 = N->getOperand(0); 2416 SDValue N1 = N->getOperand(1); 2417 SDValue LL, LR, RL, RR, CC0, CC1; 2418 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 2419 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 2420 EVT VT = N1.getValueType(); 2421 unsigned BitWidth = VT.getScalarType().getSizeInBits(); 2422 2423 // fold vector ops 2424 if (VT.isVector()) { 2425 SDValue FoldedVOp = SimplifyVBinOp(N); 2426 if (FoldedVOp.getNode()) return FoldedVOp; 2427 } 2428 2429 // fold (and x, undef) -> 0 2430 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF) 2431 return DAG.getConstant(0, VT); 2432 // fold (and c1, c2) -> c1&c2 2433 if (N0C && N1C) 2434 return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C); 2435 // canonicalize constant to RHS 2436 if (N0C && !N1C) 2437 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N1, N0); 2438 // fold (and x, -1) -> x 2439 if (N1C && N1C->isAllOnesValue()) 2440 return N0; 2441 // if (and x, c) is known to be zero, return 0 2442 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0), 2443 APInt::getAllOnesValue(BitWidth))) 2444 return DAG.getConstant(0, VT); 2445 // reassociate and 2446 SDValue RAND = ReassociateOps(ISD::AND, N->getDebugLoc(), N0, N1); 2447 if (RAND.getNode() != 0) 2448 return RAND; 2449 // fold (and (or x, C), D) -> D if (C & D) == D 2450 if (N1C && N0.getOpcode() == ISD::OR) 2451 if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) 2452 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue()) 2453 return N1; 2454 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits. 2455 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) { 2456 SDValue N0Op0 = N0.getOperand(0); 2457 APInt Mask = ~N1C->getAPIntValue(); 2458 Mask = Mask.trunc(N0Op0.getValueSizeInBits()); 2459 if (DAG.MaskedValueIsZero(N0Op0, Mask)) { 2460 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), 2461 N0.getValueType(), N0Op0); 2462 2463 // Replace uses of the AND with uses of the Zero extend node. 2464 CombineTo(N, Zext); 2465 2466 // We actually want to replace all uses of the any_extend with the 2467 // zero_extend, to avoid duplicating things. This will later cause this 2468 // AND to be folded. 2469 CombineTo(N0.getNode(), Zext); 2470 return SDValue(N, 0); // Return N so it doesn't get rechecked! 2471 } 2472 } 2473 // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) -> 2474 // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must 2475 // already be zero by virtue of the width of the base type of the load. 2476 // 2477 // the 'X' node here can either be nothing or an extract_vector_elt to catch 2478 // more cases. 2479 if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT && 2480 N0.getOperand(0).getOpcode() == ISD::LOAD) || 2481 N0.getOpcode() == ISD::LOAD) { 2482 LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ? 2483 N0 : N0.getOperand(0) ); 2484 2485 // Get the constant (if applicable) the zero'th operand is being ANDed with. 2486 // This can be a pure constant or a vector splat, in which case we treat the 2487 // vector as a scalar and use the splat value. 2488 APInt Constant = APInt::getNullValue(1); 2489 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) { 2490 Constant = C->getAPIntValue(); 2491 } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) { 2492 APInt SplatValue, SplatUndef; 2493 unsigned SplatBitSize; 2494 bool HasAnyUndefs; 2495 bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef, 2496 SplatBitSize, HasAnyUndefs); 2497 if (IsSplat) { 2498 // Undef bits can contribute to a possible optimisation if set, so 2499 // set them. 2500 SplatValue |= SplatUndef; 2501 2502 // The splat value may be something like "0x00FFFFFF", which means 0 for 2503 // the first vector value and FF for the rest, repeating. We need a mask 2504 // that will apply equally to all members of the vector, so AND all the 2505 // lanes of the constant together. 2506 EVT VT = Vector->getValueType(0); 2507 unsigned BitWidth = VT.getVectorElementType().getSizeInBits(); 2508 2509 // If the splat value has been compressed to a bitlength lower 2510 // than the size of the vector lane, we need to re-expand it to 2511 // the lane size. 2512 if (BitWidth > SplatBitSize) 2513 for (SplatValue = SplatValue.zextOrTrunc(BitWidth); 2514 SplatBitSize < BitWidth; 2515 SplatBitSize = SplatBitSize * 2) 2516 SplatValue |= SplatValue.shl(SplatBitSize); 2517 2518 Constant = APInt::getAllOnesValue(BitWidth); 2519 for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i) 2520 Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth); 2521 } 2522 } 2523 2524 // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is 2525 // actually legal and isn't going to get expanded, else this is a false 2526 // optimisation. 2527 bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD, 2528 Load->getMemoryVT()); 2529 2530 // Resize the constant to the same size as the original memory access before 2531 // extension. If it is still the AllOnesValue then this AND is completely 2532 // unneeded. 2533 Constant = 2534 Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits()); 2535 2536 bool B; 2537 switch (Load->getExtensionType()) { 2538 default: B = false; break; 2539 case ISD::EXTLOAD: B = CanZextLoadProfitably; break; 2540 case ISD::ZEXTLOAD: 2541 case ISD::NON_EXTLOAD: B = true; break; 2542 } 2543 2544 if (B && Constant.isAllOnesValue()) { 2545 // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to 2546 // preserve semantics once we get rid of the AND. 2547 SDValue NewLoad(Load, 0); 2548 if (Load->getExtensionType() == ISD::EXTLOAD) { 2549 NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD, 2550 Load->getValueType(0), Load->getDebugLoc(), 2551 Load->getChain(), Load->getBasePtr(), 2552 Load->getOffset(), Load->getMemoryVT(), 2553 Load->getMemOperand()); 2554 // Replace uses of the EXTLOAD with the new ZEXTLOAD. 2555 if (Load->getNumValues() == 3) { 2556 // PRE/POST_INC loads have 3 values. 2557 SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1), 2558 NewLoad.getValue(2) }; 2559 CombineTo(Load, To, 3, true); 2560 } else { 2561 CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1)); 2562 } 2563 } 2564 2565 // Fold the AND away, taking care not to fold to the old load node if we 2566 // replaced it. 2567 CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0); 2568 2569 return SDValue(N, 0); // Return N so it doesn't get rechecked! 2570 } 2571 } 2572 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y)) 2573 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){ 2574 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get(); 2575 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get(); 2576 2577 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 && 2578 LL.getValueType().isInteger()) { 2579 // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0) 2580 if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) { 2581 SDValue ORNode = DAG.getNode(ISD::OR, N0.getDebugLoc(), 2582 LR.getValueType(), LL, RL); 2583 AddToWorkList(ORNode.getNode()); 2584 return DAG.getSetCC(N->getDebugLoc(), VT, ORNode, LR, Op1); 2585 } 2586 // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1) 2587 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) { 2588 SDValue ANDNode = DAG.getNode(ISD::AND, N0.getDebugLoc(), 2589 LR.getValueType(), LL, RL); 2590 AddToWorkList(ANDNode.getNode()); 2591 return DAG.getSetCC(N->getDebugLoc(), VT, ANDNode, LR, Op1); 2592 } 2593 // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1) 2594 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) { 2595 SDValue ORNode = DAG.getNode(ISD::OR, N0.getDebugLoc(), 2596 LR.getValueType(), LL, RL); 2597 AddToWorkList(ORNode.getNode()); 2598 return DAG.getSetCC(N->getDebugLoc(), VT, ORNode, LR, Op1); 2599 } 2600 } 2601 // canonicalize equivalent to ll == rl 2602 if (LL == RR && LR == RL) { 2603 Op1 = ISD::getSetCCSwappedOperands(Op1); 2604 std::swap(RL, RR); 2605 } 2606 if (LL == RL && LR == RR) { 2607 bool isInteger = LL.getValueType().isInteger(); 2608 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger); 2609 if (Result != ISD::SETCC_INVALID && 2610 (!LegalOperations || TLI.isCondCodeLegal(Result, LL.getValueType()))) 2611 return DAG.getSetCC(N->getDebugLoc(), N0.getValueType(), 2612 LL, LR, Result); 2613 } 2614 } 2615 2616 // Simplify: (and (op x...), (op y...)) -> (op (and x, y)) 2617 if (N0.getOpcode() == N1.getOpcode()) { 2618 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N); 2619 if (Tmp.getNode()) return Tmp; 2620 } 2621 2622 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1) 2623 // fold (and (sra)) -> (and (srl)) when possible. 2624 if (!VT.isVector() && 2625 SimplifyDemandedBits(SDValue(N, 0))) 2626 return SDValue(N, 0); 2627 2628 // fold (zext_inreg (extload x)) -> (zextload x) 2629 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) { 2630 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 2631 EVT MemVT = LN0->getMemoryVT(); 2632 // If we zero all the possible extended bits, then we can turn this into 2633 // a zextload if we are running before legalize or the operation is legal. 2634 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits(); 2635 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth, 2636 BitWidth - MemVT.getScalarType().getSizeInBits())) && 2637 ((!LegalOperations && !LN0->isVolatile()) || 2638 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) { 2639 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, N0.getDebugLoc(), VT, 2640 LN0->getChain(), LN0->getBasePtr(), 2641 LN0->getPointerInfo(), MemVT, 2642 LN0->isVolatile(), LN0->isNonTemporal(), 2643 LN0->getAlignment()); 2644 AddToWorkList(N); 2645 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 2646 return SDValue(N, 0); // Return N so it doesn't get rechecked! 2647 } 2648 } 2649 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use 2650 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 2651 N0.hasOneUse()) { 2652 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 2653 EVT MemVT = LN0->getMemoryVT(); 2654 // If we zero all the possible extended bits, then we can turn this into 2655 // a zextload if we are running before legalize or the operation is legal. 2656 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits(); 2657 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth, 2658 BitWidth - MemVT.getScalarType().getSizeInBits())) && 2659 ((!LegalOperations && !LN0->isVolatile()) || 2660 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) { 2661 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, N0.getDebugLoc(), VT, 2662 LN0->getChain(), 2663 LN0->getBasePtr(), LN0->getPointerInfo(), 2664 MemVT, 2665 LN0->isVolatile(), LN0->isNonTemporal(), 2666 LN0->getAlignment()); 2667 AddToWorkList(N); 2668 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 2669 return SDValue(N, 0); // Return N so it doesn't get rechecked! 2670 } 2671 } 2672 2673 // fold (and (load x), 255) -> (zextload x, i8) 2674 // fold (and (extload x, i16), 255) -> (zextload x, i8) 2675 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8) 2676 if (N1C && (N0.getOpcode() == ISD::LOAD || 2677 (N0.getOpcode() == ISD::ANY_EXTEND && 2678 N0.getOperand(0).getOpcode() == ISD::LOAD))) { 2679 bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND; 2680 LoadSDNode *LN0 = HasAnyExt 2681 ? cast<LoadSDNode>(N0.getOperand(0)) 2682 : cast<LoadSDNode>(N0); 2683 if (LN0->getExtensionType() != ISD::SEXTLOAD && 2684 LN0->isUnindexed() && N0.hasOneUse() && LN0->hasOneUse()) { 2685 uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits(); 2686 if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){ 2687 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits); 2688 EVT LoadedVT = LN0->getMemoryVT(); 2689 2690 if (ExtVT == LoadedVT && 2691 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) { 2692 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT; 2693 2694 SDValue NewLoad = 2695 DAG.getExtLoad(ISD::ZEXTLOAD, LN0->getDebugLoc(), LoadResultTy, 2696 LN0->getChain(), LN0->getBasePtr(), 2697 LN0->getPointerInfo(), 2698 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(), 2699 LN0->getAlignment()); 2700 AddToWorkList(N); 2701 CombineTo(LN0, NewLoad, NewLoad.getValue(1)); 2702 return SDValue(N, 0); // Return N so it doesn't get rechecked! 2703 } 2704 2705 // Do not change the width of a volatile load. 2706 // Do not generate loads of non-round integer types since these can 2707 // be expensive (and would be wrong if the type is not byte sized). 2708 if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() && 2709 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) { 2710 EVT PtrType = LN0->getOperand(1).getValueType(); 2711 2712 unsigned Alignment = LN0->getAlignment(); 2713 SDValue NewPtr = LN0->getBasePtr(); 2714 2715 // For big endian targets, we need to add an offset to the pointer 2716 // to load the correct bytes. For little endian systems, we merely 2717 // need to read fewer bytes from the same pointer. 2718 if (TLI.isBigEndian()) { 2719 unsigned LVTStoreBytes = LoadedVT.getStoreSize(); 2720 unsigned EVTStoreBytes = ExtVT.getStoreSize(); 2721 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes; 2722 NewPtr = DAG.getNode(ISD::ADD, LN0->getDebugLoc(), PtrType, 2723 NewPtr, DAG.getConstant(PtrOff, PtrType)); 2724 Alignment = MinAlign(Alignment, PtrOff); 2725 } 2726 2727 AddToWorkList(NewPtr.getNode()); 2728 2729 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT; 2730 SDValue Load = 2731 DAG.getExtLoad(ISD::ZEXTLOAD, LN0->getDebugLoc(), LoadResultTy, 2732 LN0->getChain(), NewPtr, 2733 LN0->getPointerInfo(), 2734 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(), 2735 Alignment); 2736 AddToWorkList(N); 2737 CombineTo(LN0, Load, Load.getValue(1)); 2738 return SDValue(N, 0); // Return N so it doesn't get rechecked! 2739 } 2740 } 2741 } 2742 } 2743 2744 if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL && 2745 VT.getSizeInBits() <= 64) { 2746 if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 2747 APInt ADDC = ADDI->getAPIntValue(); 2748 if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) { 2749 // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal 2750 // immediate for an add, but it is legal if its top c2 bits are set, 2751 // transform the ADD so the immediate doesn't need to be materialized 2752 // in a register. 2753 if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) { 2754 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(), 2755 SRLI->getZExtValue()); 2756 if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) { 2757 ADDC |= Mask; 2758 if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) { 2759 SDValue NewAdd = 2760 DAG.getNode(ISD::ADD, N0.getDebugLoc(), VT, 2761 N0.getOperand(0), DAG.getConstant(ADDC, VT)); 2762 CombineTo(N0.getNode(), NewAdd); 2763 return SDValue(N, 0); // Return N so it doesn't get rechecked! 2764 } 2765 } 2766 } 2767 } 2768 } 2769 } 2770 2771 2772 return SDValue(); 2773} 2774 2775/// MatchBSwapHWord - Match (a >> 8) | (a << 8) as (bswap a) >> 16 2776/// 2777SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1, 2778 bool DemandHighBits) { 2779 if (!LegalOperations) 2780 return SDValue(); 2781 2782 EVT VT = N->getValueType(0); 2783 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16) 2784 return SDValue(); 2785 if (!TLI.isOperationLegal(ISD::BSWAP, VT)) 2786 return SDValue(); 2787 2788 // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00) 2789 bool LookPassAnd0 = false; 2790 bool LookPassAnd1 = false; 2791 if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL) 2792 std::swap(N0, N1); 2793 if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL) 2794 std::swap(N0, N1); 2795 if (N0.getOpcode() == ISD::AND) { 2796 if (!N0.getNode()->hasOneUse()) 2797 return SDValue(); 2798 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 2799 if (!N01C || N01C->getZExtValue() != 0xFF00) 2800 return SDValue(); 2801 N0 = N0.getOperand(0); 2802 LookPassAnd0 = true; 2803 } 2804 2805 if (N1.getOpcode() == ISD::AND) { 2806 if (!N1.getNode()->hasOneUse()) 2807 return SDValue(); 2808 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 2809 if (!N11C || N11C->getZExtValue() != 0xFF) 2810 return SDValue(); 2811 N1 = N1.getOperand(0); 2812 LookPassAnd1 = true; 2813 } 2814 2815 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL) 2816 std::swap(N0, N1); 2817 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL) 2818 return SDValue(); 2819 if (!N0.getNode()->hasOneUse() || 2820 !N1.getNode()->hasOneUse()) 2821 return SDValue(); 2822 2823 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 2824 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 2825 if (!N01C || !N11C) 2826 return SDValue(); 2827 if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8) 2828 return SDValue(); 2829 2830 // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8) 2831 SDValue N00 = N0->getOperand(0); 2832 if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) { 2833 if (!N00.getNode()->hasOneUse()) 2834 return SDValue(); 2835 ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1)); 2836 if (!N001C || N001C->getZExtValue() != 0xFF) 2837 return SDValue(); 2838 N00 = N00.getOperand(0); 2839 LookPassAnd0 = true; 2840 } 2841 2842 SDValue N10 = N1->getOperand(0); 2843 if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) { 2844 if (!N10.getNode()->hasOneUse()) 2845 return SDValue(); 2846 ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1)); 2847 if (!N101C || N101C->getZExtValue() != 0xFF00) 2848 return SDValue(); 2849 N10 = N10.getOperand(0); 2850 LookPassAnd1 = true; 2851 } 2852 2853 if (N00 != N10) 2854 return SDValue(); 2855 2856 // Make sure everything beyond the low halfword is zero since the SRL 16 2857 // will clear the top bits. 2858 unsigned OpSizeInBits = VT.getSizeInBits(); 2859 if (DemandHighBits && OpSizeInBits > 16 && 2860 (!LookPassAnd0 || !LookPassAnd1) && 2861 !DAG.MaskedValueIsZero(N10, APInt::getHighBitsSet(OpSizeInBits, 16))) 2862 return SDValue(); 2863 2864 SDValue Res = DAG.getNode(ISD::BSWAP, N->getDebugLoc(), VT, N00); 2865 if (OpSizeInBits > 16) 2866 Res = DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, Res, 2867 DAG.getConstant(OpSizeInBits-16, getShiftAmountTy(VT))); 2868 return Res; 2869} 2870 2871/// isBSwapHWordElement - Return true if the specified node is an element 2872/// that makes up a 32-bit packed halfword byteswap. i.e. 2873/// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8) 2874static bool isBSwapHWordElement(SDValue N, SmallVector<SDNode*,4> &Parts) { 2875 if (!N.getNode()->hasOneUse()) 2876 return false; 2877 2878 unsigned Opc = N.getOpcode(); 2879 if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL) 2880 return false; 2881 2882 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1)); 2883 if (!N1C) 2884 return false; 2885 2886 unsigned Num; 2887 switch (N1C->getZExtValue()) { 2888 default: 2889 return false; 2890 case 0xFF: Num = 0; break; 2891 case 0xFF00: Num = 1; break; 2892 case 0xFF0000: Num = 2; break; 2893 case 0xFF000000: Num = 3; break; 2894 } 2895 2896 // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00). 2897 SDValue N0 = N.getOperand(0); 2898 if (Opc == ISD::AND) { 2899 if (Num == 0 || Num == 2) { 2900 // (x >> 8) & 0xff 2901 // (x >> 8) & 0xff0000 2902 if (N0.getOpcode() != ISD::SRL) 2903 return false; 2904 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 2905 if (!C || C->getZExtValue() != 8) 2906 return false; 2907 } else { 2908 // (x << 8) & 0xff00 2909 // (x << 8) & 0xff000000 2910 if (N0.getOpcode() != ISD::SHL) 2911 return false; 2912 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 2913 if (!C || C->getZExtValue() != 8) 2914 return false; 2915 } 2916 } else if (Opc == ISD::SHL) { 2917 // (x & 0xff) << 8 2918 // (x & 0xff0000) << 8 2919 if (Num != 0 && Num != 2) 2920 return false; 2921 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1)); 2922 if (!C || C->getZExtValue() != 8) 2923 return false; 2924 } else { // Opc == ISD::SRL 2925 // (x & 0xff00) >> 8 2926 // (x & 0xff000000) >> 8 2927 if (Num != 1 && Num != 3) 2928 return false; 2929 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1)); 2930 if (!C || C->getZExtValue() != 8) 2931 return false; 2932 } 2933 2934 if (Parts[Num]) 2935 return false; 2936 2937 Parts[Num] = N0.getOperand(0).getNode(); 2938 return true; 2939} 2940 2941/// MatchBSwapHWord - Match a 32-bit packed halfword bswap. That is 2942/// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8) 2943/// => (rotl (bswap x), 16) 2944SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) { 2945 if (!LegalOperations) 2946 return SDValue(); 2947 2948 EVT VT = N->getValueType(0); 2949 if (VT != MVT::i32) 2950 return SDValue(); 2951 if (!TLI.isOperationLegal(ISD::BSWAP, VT)) 2952 return SDValue(); 2953 2954 SmallVector<SDNode*,4> Parts(4, (SDNode*)0); 2955 // Look for either 2956 // (or (or (and), (and)), (or (and), (and))) 2957 // (or (or (or (and), (and)), (and)), (and)) 2958 if (N0.getOpcode() != ISD::OR) 2959 return SDValue(); 2960 SDValue N00 = N0.getOperand(0); 2961 SDValue N01 = N0.getOperand(1); 2962 2963 if (N1.getOpcode() == ISD::OR) { 2964 // (or (or (and), (and)), (or (and), (and))) 2965 SDValue N000 = N00.getOperand(0); 2966 if (!isBSwapHWordElement(N000, Parts)) 2967 return SDValue(); 2968 2969 SDValue N001 = N00.getOperand(1); 2970 if (!isBSwapHWordElement(N001, Parts)) 2971 return SDValue(); 2972 SDValue N010 = N01.getOperand(0); 2973 if (!isBSwapHWordElement(N010, Parts)) 2974 return SDValue(); 2975 SDValue N011 = N01.getOperand(1); 2976 if (!isBSwapHWordElement(N011, Parts)) 2977 return SDValue(); 2978 } else { 2979 // (or (or (or (and), (and)), (and)), (and)) 2980 if (!isBSwapHWordElement(N1, Parts)) 2981 return SDValue(); 2982 if (!isBSwapHWordElement(N01, Parts)) 2983 return SDValue(); 2984 if (N00.getOpcode() != ISD::OR) 2985 return SDValue(); 2986 SDValue N000 = N00.getOperand(0); 2987 if (!isBSwapHWordElement(N000, Parts)) 2988 return SDValue(); 2989 SDValue N001 = N00.getOperand(1); 2990 if (!isBSwapHWordElement(N001, Parts)) 2991 return SDValue(); 2992 } 2993 2994 // Make sure the parts are all coming from the same node. 2995 if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3]) 2996 return SDValue(); 2997 2998 SDValue BSwap = DAG.getNode(ISD::BSWAP, N->getDebugLoc(), VT, 2999 SDValue(Parts[0],0)); 3000 3001 // Result of the bswap should be rotated by 16. If it's not legal, than 3002 // do (x << 16) | (x >> 16). 3003 SDValue ShAmt = DAG.getConstant(16, getShiftAmountTy(VT)); 3004 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT)) 3005 return DAG.getNode(ISD::ROTL, N->getDebugLoc(), VT, BSwap, ShAmt); 3006 if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT)) 3007 return DAG.getNode(ISD::ROTR, N->getDebugLoc(), VT, BSwap, ShAmt); 3008 return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, 3009 DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, BSwap, ShAmt), 3010 DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, BSwap, ShAmt)); 3011} 3012 3013SDValue DAGCombiner::visitOR(SDNode *N) { 3014 SDValue N0 = N->getOperand(0); 3015 SDValue N1 = N->getOperand(1); 3016 SDValue LL, LR, RL, RR, CC0, CC1; 3017 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 3018 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 3019 EVT VT = N1.getValueType(); 3020 3021 // fold vector ops 3022 if (VT.isVector()) { 3023 SDValue FoldedVOp = SimplifyVBinOp(N); 3024 if (FoldedVOp.getNode()) return FoldedVOp; 3025 } 3026 3027 // fold (or x, undef) -> -1 3028 if (!LegalOperations && 3029 (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) { 3030 EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT; 3031 return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT); 3032 } 3033 // fold (or c1, c2) -> c1|c2 3034 if (N0C && N1C) 3035 return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C); 3036 // canonicalize constant to RHS 3037 if (N0C && !N1C) 3038 return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, N1, N0); 3039 // fold (or x, 0) -> x 3040 if (N1C && N1C->isNullValue()) 3041 return N0; 3042 // fold (or x, -1) -> -1 3043 if (N1C && N1C->isAllOnesValue()) 3044 return N1; 3045 // fold (or x, c) -> c iff (x & ~c) == 0 3046 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue())) 3047 return N1; 3048 3049 // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16) 3050 SDValue BSwap = MatchBSwapHWord(N, N0, N1); 3051 if (BSwap.getNode() != 0) 3052 return BSwap; 3053 BSwap = MatchBSwapHWordLow(N, N0, N1); 3054 if (BSwap.getNode() != 0) 3055 return BSwap; 3056 3057 // reassociate or 3058 SDValue ROR = ReassociateOps(ISD::OR, N->getDebugLoc(), N0, N1); 3059 if (ROR.getNode() != 0) 3060 return ROR; 3061 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2) 3062 // iff (c1 & c2) == 0. 3063 if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() && 3064 isa<ConstantSDNode>(N0.getOperand(1))) { 3065 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1)); 3066 if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) 3067 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, 3068 DAG.getNode(ISD::OR, N0.getDebugLoc(), VT, 3069 N0.getOperand(0), N1), 3070 DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1)); 3071 } 3072 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y)) 3073 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){ 3074 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get(); 3075 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get(); 3076 3077 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 && 3078 LL.getValueType().isInteger()) { 3079 // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0) 3080 // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0) 3081 if (cast<ConstantSDNode>(LR)->isNullValue() && 3082 (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) { 3083 SDValue ORNode = DAG.getNode(ISD::OR, LR.getDebugLoc(), 3084 LR.getValueType(), LL, RL); 3085 AddToWorkList(ORNode.getNode()); 3086 return DAG.getSetCC(N->getDebugLoc(), VT, ORNode, LR, Op1); 3087 } 3088 // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1) 3089 // fold (or (setgt X, -1), (setgt Y -1)) -> (setgt (and X, Y), -1) 3090 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && 3091 (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) { 3092 SDValue ANDNode = DAG.getNode(ISD::AND, LR.getDebugLoc(), 3093 LR.getValueType(), LL, RL); 3094 AddToWorkList(ANDNode.getNode()); 3095 return DAG.getSetCC(N->getDebugLoc(), VT, ANDNode, LR, Op1); 3096 } 3097 } 3098 // canonicalize equivalent to ll == rl 3099 if (LL == RR && LR == RL) { 3100 Op1 = ISD::getSetCCSwappedOperands(Op1); 3101 std::swap(RL, RR); 3102 } 3103 if (LL == RL && LR == RR) { 3104 bool isInteger = LL.getValueType().isInteger(); 3105 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger); 3106 if (Result != ISD::SETCC_INVALID && 3107 (!LegalOperations || TLI.isCondCodeLegal(Result, LL.getValueType()))) 3108 return DAG.getSetCC(N->getDebugLoc(), N0.getValueType(), 3109 LL, LR, Result); 3110 } 3111 } 3112 3113 // Simplify: (or (op x...), (op y...)) -> (op (or x, y)) 3114 if (N0.getOpcode() == N1.getOpcode()) { 3115 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N); 3116 if (Tmp.getNode()) return Tmp; 3117 } 3118 3119 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible. 3120 if (N0.getOpcode() == ISD::AND && 3121 N1.getOpcode() == ISD::AND && 3122 N0.getOperand(1).getOpcode() == ISD::Constant && 3123 N1.getOperand(1).getOpcode() == ISD::Constant && 3124 // Don't increase # computations. 3125 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) { 3126 // We can only do this xform if we know that bits from X that are set in C2 3127 // but not in C1 are already zero. Likewise for Y. 3128 const APInt &LHSMask = 3129 cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 3130 const APInt &RHSMask = 3131 cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue(); 3132 3133 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) && 3134 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) { 3135 SDValue X = DAG.getNode(ISD::OR, N0.getDebugLoc(), VT, 3136 N0.getOperand(0), N1.getOperand(0)); 3137 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, X, 3138 DAG.getConstant(LHSMask | RHSMask, VT)); 3139 } 3140 } 3141 3142 // See if this is some rotate idiom. 3143 if (SDNode *Rot = MatchRotate(N0, N1, N->getDebugLoc())) 3144 return SDValue(Rot, 0); 3145 3146 // Simplify the operands using demanded-bits information. 3147 if (!VT.isVector() && 3148 SimplifyDemandedBits(SDValue(N, 0))) 3149 return SDValue(N, 0); 3150 3151 return SDValue(); 3152} 3153 3154/// MatchRotateHalf - Match "(X shl/srl V1) & V2" where V2 may not be present. 3155static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) { 3156 if (Op.getOpcode() == ISD::AND) { 3157 if (isa<ConstantSDNode>(Op.getOperand(1))) { 3158 Mask = Op.getOperand(1); 3159 Op = Op.getOperand(0); 3160 } else { 3161 return false; 3162 } 3163 } 3164 3165 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) { 3166 Shift = Op; 3167 return true; 3168 } 3169 3170 return false; 3171} 3172 3173// MatchRotate - Handle an 'or' of two operands. If this is one of the many 3174// idioms for rotate, and if the target supports rotation instructions, generate 3175// a rot[lr]. 3176SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, DebugLoc DL) { 3177 // Must be a legal type. Expanded 'n promoted things won't work with rotates. 3178 EVT VT = LHS.getValueType(); 3179 if (!TLI.isTypeLegal(VT)) return 0; 3180 3181 // The target must have at least one rotate flavor. 3182 bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT); 3183 bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT); 3184 if (!HasROTL && !HasROTR) return 0; 3185 3186 // Match "(X shl/srl V1) & V2" where V2 may not be present. 3187 SDValue LHSShift; // The shift. 3188 SDValue LHSMask; // AND value if any. 3189 if (!MatchRotateHalf(LHS, LHSShift, LHSMask)) 3190 return 0; // Not part of a rotate. 3191 3192 SDValue RHSShift; // The shift. 3193 SDValue RHSMask; // AND value if any. 3194 if (!MatchRotateHalf(RHS, RHSShift, RHSMask)) 3195 return 0; // Not part of a rotate. 3196 3197 if (LHSShift.getOperand(0) != RHSShift.getOperand(0)) 3198 return 0; // Not shifting the same value. 3199 3200 if (LHSShift.getOpcode() == RHSShift.getOpcode()) 3201 return 0; // Shifts must disagree. 3202 3203 // Canonicalize shl to left side in a shl/srl pair. 3204 if (RHSShift.getOpcode() == ISD::SHL) { 3205 std::swap(LHS, RHS); 3206 std::swap(LHSShift, RHSShift); 3207 std::swap(LHSMask , RHSMask ); 3208 } 3209 3210 unsigned OpSizeInBits = VT.getSizeInBits(); 3211 SDValue LHSShiftArg = LHSShift.getOperand(0); 3212 SDValue LHSShiftAmt = LHSShift.getOperand(1); 3213 SDValue RHSShiftAmt = RHSShift.getOperand(1); 3214 3215 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1) 3216 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2) 3217 if (LHSShiftAmt.getOpcode() == ISD::Constant && 3218 RHSShiftAmt.getOpcode() == ISD::Constant) { 3219 uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue(); 3220 uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue(); 3221 if ((LShVal + RShVal) != OpSizeInBits) 3222 return 0; 3223 3224 SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT, 3225 LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt); 3226 3227 // If there is an AND of either shifted operand, apply it to the result. 3228 if (LHSMask.getNode() || RHSMask.getNode()) { 3229 APInt Mask = APInt::getAllOnesValue(OpSizeInBits); 3230 3231 if (LHSMask.getNode()) { 3232 APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal); 3233 Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits; 3234 } 3235 if (RHSMask.getNode()) { 3236 APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal); 3237 Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits; 3238 } 3239 3240 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT)); 3241 } 3242 3243 return Rot.getNode(); 3244 } 3245 3246 // If there is a mask here, and we have a variable shift, we can't be sure 3247 // that we're masking out the right stuff. 3248 if (LHSMask.getNode() || RHSMask.getNode()) 3249 return 0; 3250 3251 // fold (or (shl x, y), (srl x, (sub 32, y))) -> (rotl x, y) 3252 // fold (or (shl x, y), (srl x, (sub 32, y))) -> (rotr x, (sub 32, y)) 3253 if (RHSShiftAmt.getOpcode() == ISD::SUB && 3254 LHSShiftAmt == RHSShiftAmt.getOperand(1)) { 3255 if (ConstantSDNode *SUBC = 3256 dyn_cast<ConstantSDNode>(RHSShiftAmt.getOperand(0))) { 3257 if (SUBC->getAPIntValue() == OpSizeInBits) { 3258 return DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT, LHSShiftArg, 3259 HasROTL ? LHSShiftAmt : RHSShiftAmt).getNode(); 3260 } 3261 } 3262 } 3263 3264 // fold (or (shl x, (sub 32, y)), (srl x, r)) -> (rotr x, y) 3265 // fold (or (shl x, (sub 32, y)), (srl x, r)) -> (rotl x, (sub 32, y)) 3266 if (LHSShiftAmt.getOpcode() == ISD::SUB && 3267 RHSShiftAmt == LHSShiftAmt.getOperand(1)) { 3268 if (ConstantSDNode *SUBC = 3269 dyn_cast<ConstantSDNode>(LHSShiftAmt.getOperand(0))) { 3270 if (SUBC->getAPIntValue() == OpSizeInBits) { 3271 return DAG.getNode(HasROTR ? ISD::ROTR : ISD::ROTL, DL, VT, LHSShiftArg, 3272 HasROTR ? RHSShiftAmt : LHSShiftAmt).getNode(); 3273 } 3274 } 3275 } 3276 3277 // Look for sign/zext/any-extended or truncate cases: 3278 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND || 3279 LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND || 3280 LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND || 3281 LHSShiftAmt.getOpcode() == ISD::TRUNCATE) && 3282 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND || 3283 RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND || 3284 RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND || 3285 RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) { 3286 SDValue LExtOp0 = LHSShiftAmt.getOperand(0); 3287 SDValue RExtOp0 = RHSShiftAmt.getOperand(0); 3288 if (RExtOp0.getOpcode() == ISD::SUB && 3289 RExtOp0.getOperand(1) == LExtOp0) { 3290 // fold (or (shl x, (*ext y)), (srl x, (*ext (sub 32, y)))) -> 3291 // (rotl x, y) 3292 // fold (or (shl x, (*ext y)), (srl x, (*ext (sub 32, y)))) -> 3293 // (rotr x, (sub 32, y)) 3294 if (ConstantSDNode *SUBC = 3295 dyn_cast<ConstantSDNode>(RExtOp0.getOperand(0))) { 3296 if (SUBC->getAPIntValue() == OpSizeInBits) { 3297 return DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT, 3298 LHSShiftArg, 3299 HasROTL ? LHSShiftAmt : RHSShiftAmt).getNode(); 3300 } 3301 } 3302 } else if (LExtOp0.getOpcode() == ISD::SUB && 3303 RExtOp0 == LExtOp0.getOperand(1)) { 3304 // fold (or (shl x, (*ext (sub 32, y))), (srl x, (*ext y))) -> 3305 // (rotr x, y) 3306 // fold (or (shl x, (*ext (sub 32, y))), (srl x, (*ext y))) -> 3307 // (rotl x, (sub 32, y)) 3308 if (ConstantSDNode *SUBC = 3309 dyn_cast<ConstantSDNode>(LExtOp0.getOperand(0))) { 3310 if (SUBC->getAPIntValue() == OpSizeInBits) { 3311 return DAG.getNode(HasROTR ? ISD::ROTR : ISD::ROTL, DL, VT, 3312 LHSShiftArg, 3313 HasROTR ? RHSShiftAmt : LHSShiftAmt).getNode(); 3314 } 3315 } 3316 } 3317 } 3318 3319 return 0; 3320} 3321 3322SDValue DAGCombiner::visitXOR(SDNode *N) { 3323 SDValue N0 = N->getOperand(0); 3324 SDValue N1 = N->getOperand(1); 3325 SDValue LHS, RHS, CC; 3326 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 3327 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 3328 EVT VT = N0.getValueType(); 3329 3330 // fold vector ops 3331 if (VT.isVector()) { 3332 SDValue FoldedVOp = SimplifyVBinOp(N); 3333 if (FoldedVOp.getNode()) return FoldedVOp; 3334 } 3335 3336 // fold (xor undef, undef) -> 0. This is a common idiom (misuse). 3337 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF) 3338 return DAG.getConstant(0, VT); 3339 // fold (xor x, undef) -> undef 3340 if (N0.getOpcode() == ISD::UNDEF) 3341 return N0; 3342 if (N1.getOpcode() == ISD::UNDEF) 3343 return N1; 3344 // fold (xor c1, c2) -> c1^c2 3345 if (N0C && N1C) 3346 return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C); 3347 // canonicalize constant to RHS 3348 if (N0C && !N1C) 3349 return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT, N1, N0); 3350 // fold (xor x, 0) -> x 3351 if (N1C && N1C->isNullValue()) 3352 return N0; 3353 // reassociate xor 3354 SDValue RXOR = ReassociateOps(ISD::XOR, N->getDebugLoc(), N0, N1); 3355 if (RXOR.getNode() != 0) 3356 return RXOR; 3357 3358 // fold !(x cc y) -> (x !cc y) 3359 if (N1C && N1C->getAPIntValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) { 3360 bool isInt = LHS.getValueType().isInteger(); 3361 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(), 3362 isInt); 3363 3364 if (!LegalOperations || TLI.isCondCodeLegal(NotCC, LHS.getValueType())) { 3365 switch (N0.getOpcode()) { 3366 default: 3367 llvm_unreachable("Unhandled SetCC Equivalent!"); 3368 case ISD::SETCC: 3369 return DAG.getSetCC(N->getDebugLoc(), VT, LHS, RHS, NotCC); 3370 case ISD::SELECT_CC: 3371 return DAG.getSelectCC(N->getDebugLoc(), LHS, RHS, N0.getOperand(2), 3372 N0.getOperand(3), NotCC); 3373 } 3374 } 3375 } 3376 3377 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y))) 3378 if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND && 3379 N0.getNode()->hasOneUse() && 3380 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){ 3381 SDValue V = N0.getOperand(0); 3382 V = DAG.getNode(ISD::XOR, N0.getDebugLoc(), V.getValueType(), V, 3383 DAG.getConstant(1, V.getValueType())); 3384 AddToWorkList(V.getNode()); 3385 return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT, V); 3386 } 3387 3388 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc 3389 if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 && 3390 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) { 3391 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1); 3392 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) { 3393 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND; 3394 LHS = DAG.getNode(ISD::XOR, LHS.getDebugLoc(), VT, LHS, N1); // LHS = ~LHS 3395 RHS = DAG.getNode(ISD::XOR, RHS.getDebugLoc(), VT, RHS, N1); // RHS = ~RHS 3396 AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode()); 3397 return DAG.getNode(NewOpcode, N->getDebugLoc(), VT, LHS, RHS); 3398 } 3399 } 3400 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants 3401 if (N1C && N1C->isAllOnesValue() && 3402 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) { 3403 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1); 3404 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) { 3405 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND; 3406 LHS = DAG.getNode(ISD::XOR, LHS.getDebugLoc(), VT, LHS, N1); // LHS = ~LHS 3407 RHS = DAG.getNode(ISD::XOR, RHS.getDebugLoc(), VT, RHS, N1); // RHS = ~RHS 3408 AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode()); 3409 return DAG.getNode(NewOpcode, N->getDebugLoc(), VT, LHS, RHS); 3410 } 3411 } 3412 // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2)) 3413 if (N1C && N0.getOpcode() == ISD::XOR) { 3414 ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0)); 3415 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 3416 if (N00C) 3417 return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT, N0.getOperand(1), 3418 DAG.getConstant(N1C->getAPIntValue() ^ 3419 N00C->getAPIntValue(), VT)); 3420 if (N01C) 3421 return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT, N0.getOperand(0), 3422 DAG.getConstant(N1C->getAPIntValue() ^ 3423 N01C->getAPIntValue(), VT)); 3424 } 3425 // fold (xor x, x) -> 0 3426 if (N0 == N1) 3427 return tryFoldToZero(N->getDebugLoc(), TLI, VT, DAG, LegalOperations); 3428 3429 // Simplify: xor (op x...), (op y...) -> (op (xor x, y)) 3430 if (N0.getOpcode() == N1.getOpcode()) { 3431 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N); 3432 if (Tmp.getNode()) return Tmp; 3433 } 3434 3435 // Simplify the expression using non-local knowledge. 3436 if (!VT.isVector() && 3437 SimplifyDemandedBits(SDValue(N, 0))) 3438 return SDValue(N, 0); 3439 3440 return SDValue(); 3441} 3442 3443/// visitShiftByConstant - Handle transforms common to the three shifts, when 3444/// the shift amount is a constant. 3445SDValue DAGCombiner::visitShiftByConstant(SDNode *N, unsigned Amt) { 3446 SDNode *LHS = N->getOperand(0).getNode(); 3447 if (!LHS->hasOneUse()) return SDValue(); 3448 3449 // We want to pull some binops through shifts, so that we have (and (shift)) 3450 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of 3451 // thing happens with address calculations, so it's important to canonicalize 3452 // it. 3453 bool HighBitSet = false; // Can we transform this if the high bit is set? 3454 3455 switch (LHS->getOpcode()) { 3456 default: return SDValue(); 3457 case ISD::OR: 3458 case ISD::XOR: 3459 HighBitSet = false; // We can only transform sra if the high bit is clear. 3460 break; 3461 case ISD::AND: 3462 HighBitSet = true; // We can only transform sra if the high bit is set. 3463 break; 3464 case ISD::ADD: 3465 if (N->getOpcode() != ISD::SHL) 3466 return SDValue(); // only shl(add) not sr[al](add). 3467 HighBitSet = false; // We can only transform sra if the high bit is clear. 3468 break; 3469 } 3470 3471 // We require the RHS of the binop to be a constant as well. 3472 ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1)); 3473 if (!BinOpCst) return SDValue(); 3474 3475 // FIXME: disable this unless the input to the binop is a shift by a constant. 3476 // If it is not a shift, it pessimizes some common cases like: 3477 // 3478 // void foo(int *X, int i) { X[i & 1235] = 1; } 3479 // int bar(int *X, int i) { return X[i & 255]; } 3480 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode(); 3481 if ((BinOpLHSVal->getOpcode() != ISD::SHL && 3482 BinOpLHSVal->getOpcode() != ISD::SRA && 3483 BinOpLHSVal->getOpcode() != ISD::SRL) || 3484 !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1))) 3485 return SDValue(); 3486 3487 EVT VT = N->getValueType(0); 3488 3489 // If this is a signed shift right, and the high bit is modified by the 3490 // logical operation, do not perform the transformation. The highBitSet 3491 // boolean indicates the value of the high bit of the constant which would 3492 // cause it to be modified for this operation. 3493 if (N->getOpcode() == ISD::SRA) { 3494 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative(); 3495 if (BinOpRHSSignSet != HighBitSet) 3496 return SDValue(); 3497 } 3498 3499 // Fold the constants, shifting the binop RHS by the shift amount. 3500 SDValue NewRHS = DAG.getNode(N->getOpcode(), LHS->getOperand(1).getDebugLoc(), 3501 N->getValueType(0), 3502 LHS->getOperand(1), N->getOperand(1)); 3503 3504 // Create the new shift. 3505 SDValue NewShift = DAG.getNode(N->getOpcode(), 3506 LHS->getOperand(0).getDebugLoc(), 3507 VT, LHS->getOperand(0), N->getOperand(1)); 3508 3509 // Create the new binop. 3510 return DAG.getNode(LHS->getOpcode(), N->getDebugLoc(), VT, NewShift, NewRHS); 3511} 3512 3513SDValue DAGCombiner::visitSHL(SDNode *N) { 3514 SDValue N0 = N->getOperand(0); 3515 SDValue N1 = N->getOperand(1); 3516 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 3517 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 3518 EVT VT = N0.getValueType(); 3519 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits(); 3520 3521 // fold (shl c1, c2) -> c1<<c2 3522 if (N0C && N1C) 3523 return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C); 3524 // fold (shl 0, x) -> 0 3525 if (N0C && N0C->isNullValue()) 3526 return N0; 3527 // fold (shl x, c >= size(x)) -> undef 3528 if (N1C && N1C->getZExtValue() >= OpSizeInBits) 3529 return DAG.getUNDEF(VT); 3530 // fold (shl x, 0) -> x 3531 if (N1C && N1C->isNullValue()) 3532 return N0; 3533 // fold (shl undef, x) -> 0 3534 if (N0.getOpcode() == ISD::UNDEF) 3535 return DAG.getConstant(0, VT); 3536 // if (shl x, c) is known to be zero, return 0 3537 if (DAG.MaskedValueIsZero(SDValue(N, 0), 3538 APInt::getAllOnesValue(OpSizeInBits))) 3539 return DAG.getConstant(0, VT); 3540 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))). 3541 if (N1.getOpcode() == ISD::TRUNCATE && 3542 N1.getOperand(0).getOpcode() == ISD::AND && 3543 N1.hasOneUse() && N1.getOperand(0).hasOneUse()) { 3544 SDValue N101 = N1.getOperand(0).getOperand(1); 3545 if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) { 3546 EVT TruncVT = N1.getValueType(); 3547 SDValue N100 = N1.getOperand(0).getOperand(0); 3548 APInt TruncC = N101C->getAPIntValue(); 3549 TruncC = TruncC.trunc(TruncVT.getSizeInBits()); 3550 return DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, N0, 3551 DAG.getNode(ISD::AND, N->getDebugLoc(), TruncVT, 3552 DAG.getNode(ISD::TRUNCATE, 3553 N->getDebugLoc(), 3554 TruncVT, N100), 3555 DAG.getConstant(TruncC, TruncVT))); 3556 } 3557 } 3558 3559 if (N1C && SimplifyDemandedBits(SDValue(N, 0))) 3560 return SDValue(N, 0); 3561 3562 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2)) 3563 if (N1C && N0.getOpcode() == ISD::SHL && 3564 N0.getOperand(1).getOpcode() == ISD::Constant) { 3565 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue(); 3566 uint64_t c2 = N1C->getZExtValue(); 3567 if (c1 + c2 >= OpSizeInBits) 3568 return DAG.getConstant(0, VT); 3569 return DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, N0.getOperand(0), 3570 DAG.getConstant(c1 + c2, N1.getValueType())); 3571 } 3572 3573 // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2))) 3574 // For this to be valid, the second form must not preserve any of the bits 3575 // that are shifted out by the inner shift in the first form. This means 3576 // the outer shift size must be >= the number of bits added by the ext. 3577 // As a corollary, we don't care what kind of ext it is. 3578 if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND || 3579 N0.getOpcode() == ISD::ANY_EXTEND || 3580 N0.getOpcode() == ISD::SIGN_EXTEND) && 3581 N0.getOperand(0).getOpcode() == ISD::SHL && 3582 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) { 3583 uint64_t c1 = 3584 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue(); 3585 uint64_t c2 = N1C->getZExtValue(); 3586 EVT InnerShiftVT = N0.getOperand(0).getValueType(); 3587 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits(); 3588 if (c2 >= OpSizeInBits - InnerShiftSize) { 3589 if (c1 + c2 >= OpSizeInBits) 3590 return DAG.getConstant(0, VT); 3591 return DAG.getNode(ISD::SHL, N0->getDebugLoc(), VT, 3592 DAG.getNode(N0.getOpcode(), N0->getDebugLoc(), VT, 3593 N0.getOperand(0)->getOperand(0)), 3594 DAG.getConstant(c1 + c2, N1.getValueType())); 3595 } 3596 } 3597 3598 // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or 3599 // (and (srl x, (sub c1, c2), MASK) 3600 // Only fold this if the inner shift has no other uses -- if it does, folding 3601 // this will increase the total number of instructions. 3602 if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse() && 3603 N0.getOperand(1).getOpcode() == ISD::Constant) { 3604 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue(); 3605 if (c1 < VT.getSizeInBits()) { 3606 uint64_t c2 = N1C->getZExtValue(); 3607 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(), 3608 VT.getSizeInBits() - c1); 3609 SDValue Shift; 3610 if (c2 > c1) { 3611 Mask = Mask.shl(c2-c1); 3612 Shift = DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, N0.getOperand(0), 3613 DAG.getConstant(c2-c1, N1.getValueType())); 3614 } else { 3615 Mask = Mask.lshr(c1-c2); 3616 Shift = DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0.getOperand(0), 3617 DAG.getConstant(c1-c2, N1.getValueType())); 3618 } 3619 return DAG.getNode(ISD::AND, N0.getDebugLoc(), VT, Shift, 3620 DAG.getConstant(Mask, VT)); 3621 } 3622 } 3623 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1)) 3624 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) { 3625 SDValue HiBitsMask = 3626 DAG.getConstant(APInt::getHighBitsSet(VT.getSizeInBits(), 3627 VT.getSizeInBits() - 3628 N1C->getZExtValue()), 3629 VT); 3630 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0.getOperand(0), 3631 HiBitsMask); 3632 } 3633 3634 if (N1C) { 3635 SDValue NewSHL = visitShiftByConstant(N, N1C->getZExtValue()); 3636 if (NewSHL.getNode()) 3637 return NewSHL; 3638 } 3639 3640 return SDValue(); 3641} 3642 3643SDValue DAGCombiner::visitSRA(SDNode *N) { 3644 SDValue N0 = N->getOperand(0); 3645 SDValue N1 = N->getOperand(1); 3646 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 3647 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 3648 EVT VT = N0.getValueType(); 3649 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits(); 3650 3651 // fold (sra c1, c2) -> (sra c1, c2) 3652 if (N0C && N1C) 3653 return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C); 3654 // fold (sra 0, x) -> 0 3655 if (N0C && N0C->isNullValue()) 3656 return N0; 3657 // fold (sra -1, x) -> -1 3658 if (N0C && N0C->isAllOnesValue()) 3659 return N0; 3660 // fold (sra x, (setge c, size(x))) -> undef 3661 if (N1C && N1C->getZExtValue() >= OpSizeInBits) 3662 return DAG.getUNDEF(VT); 3663 // fold (sra x, 0) -> x 3664 if (N1C && N1C->isNullValue()) 3665 return N0; 3666 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports 3667 // sext_inreg. 3668 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) { 3669 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue(); 3670 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits); 3671 if (VT.isVector()) 3672 ExtVT = EVT::getVectorVT(*DAG.getContext(), 3673 ExtVT, VT.getVectorNumElements()); 3674 if ((!LegalOperations || 3675 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT))) 3676 return DAG.getNode(ISD::SIGN_EXTEND_INREG, N->getDebugLoc(), VT, 3677 N0.getOperand(0), DAG.getValueType(ExtVT)); 3678 } 3679 3680 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2)) 3681 if (N1C && N0.getOpcode() == ISD::SRA) { 3682 if (ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 3683 unsigned Sum = N1C->getZExtValue() + C1->getZExtValue(); 3684 if (Sum >= OpSizeInBits) Sum = OpSizeInBits-1; 3685 return DAG.getNode(ISD::SRA, N->getDebugLoc(), VT, N0.getOperand(0), 3686 DAG.getConstant(Sum, N1C->getValueType(0))); 3687 } 3688 } 3689 3690 // fold (sra (shl X, m), (sub result_size, n)) 3691 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for 3692 // result_size - n != m. 3693 // If truncate is free for the target sext(shl) is likely to result in better 3694 // code. 3695 if (N0.getOpcode() == ISD::SHL) { 3696 // Get the two constanst of the shifts, CN0 = m, CN = n. 3697 const ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 3698 if (N01C && N1C) { 3699 // Determine what the truncate's result bitsize and type would be. 3700 EVT TruncVT = 3701 EVT::getIntegerVT(*DAG.getContext(), 3702 OpSizeInBits - N1C->getZExtValue()); 3703 // Determine the residual right-shift amount. 3704 signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue(); 3705 3706 // If the shift is not a no-op (in which case this should be just a sign 3707 // extend already), the truncated to type is legal, sign_extend is legal 3708 // on that type, and the truncate to that type is both legal and free, 3709 // perform the transform. 3710 if ((ShiftAmt > 0) && 3711 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) && 3712 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) && 3713 TLI.isTruncateFree(VT, TruncVT)) { 3714 3715 SDValue Amt = DAG.getConstant(ShiftAmt, 3716 getShiftAmountTy(N0.getOperand(0).getValueType())); 3717 SDValue Shift = DAG.getNode(ISD::SRL, N0.getDebugLoc(), VT, 3718 N0.getOperand(0), Amt); 3719 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(), TruncVT, 3720 Shift); 3721 return DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), 3722 N->getValueType(0), Trunc); 3723 } 3724 } 3725 } 3726 3727 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))). 3728 if (N1.getOpcode() == ISD::TRUNCATE && 3729 N1.getOperand(0).getOpcode() == ISD::AND && 3730 N1.hasOneUse() && N1.getOperand(0).hasOneUse()) { 3731 SDValue N101 = N1.getOperand(0).getOperand(1); 3732 if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) { 3733 EVT TruncVT = N1.getValueType(); 3734 SDValue N100 = N1.getOperand(0).getOperand(0); 3735 APInt TruncC = N101C->getAPIntValue(); 3736 TruncC = TruncC.trunc(TruncVT.getScalarType().getSizeInBits()); 3737 return DAG.getNode(ISD::SRA, N->getDebugLoc(), VT, N0, 3738 DAG.getNode(ISD::AND, N->getDebugLoc(), 3739 TruncVT, 3740 DAG.getNode(ISD::TRUNCATE, 3741 N->getDebugLoc(), 3742 TruncVT, N100), 3743 DAG.getConstant(TruncC, TruncVT))); 3744 } 3745 } 3746 3747 // fold (sra (trunc (sr x, c1)), c2) -> (trunc (sra x, c1+c2)) 3748 // if c1 is equal to the number of bits the trunc removes 3749 if (N0.getOpcode() == ISD::TRUNCATE && 3750 (N0.getOperand(0).getOpcode() == ISD::SRL || 3751 N0.getOperand(0).getOpcode() == ISD::SRA) && 3752 N0.getOperand(0).hasOneUse() && 3753 N0.getOperand(0).getOperand(1).hasOneUse() && 3754 N1C && isa<ConstantSDNode>(N0.getOperand(0).getOperand(1))) { 3755 EVT LargeVT = N0.getOperand(0).getValueType(); 3756 ConstantSDNode *LargeShiftAmt = 3757 cast<ConstantSDNode>(N0.getOperand(0).getOperand(1)); 3758 3759 if (LargeVT.getScalarType().getSizeInBits() - OpSizeInBits == 3760 LargeShiftAmt->getZExtValue()) { 3761 SDValue Amt = 3762 DAG.getConstant(LargeShiftAmt->getZExtValue() + N1C->getZExtValue(), 3763 getShiftAmountTy(N0.getOperand(0).getOperand(0).getValueType())); 3764 SDValue SRA = DAG.getNode(ISD::SRA, N->getDebugLoc(), LargeVT, 3765 N0.getOperand(0).getOperand(0), Amt); 3766 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, SRA); 3767 } 3768 } 3769 3770 // Simplify, based on bits shifted out of the LHS. 3771 if (N1C && SimplifyDemandedBits(SDValue(N, 0))) 3772 return SDValue(N, 0); 3773 3774 3775 // If the sign bit is known to be zero, switch this to a SRL. 3776 if (DAG.SignBitIsZero(N0)) 3777 return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0, N1); 3778 3779 if (N1C) { 3780 SDValue NewSRA = visitShiftByConstant(N, N1C->getZExtValue()); 3781 if (NewSRA.getNode()) 3782 return NewSRA; 3783 } 3784 3785 return SDValue(); 3786} 3787 3788SDValue DAGCombiner::visitSRL(SDNode *N) { 3789 SDValue N0 = N->getOperand(0); 3790 SDValue N1 = N->getOperand(1); 3791 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 3792 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 3793 EVT VT = N0.getValueType(); 3794 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits(); 3795 3796 // fold (srl c1, c2) -> c1 >>u c2 3797 if (N0C && N1C) 3798 return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C); 3799 // fold (srl 0, x) -> 0 3800 if (N0C && N0C->isNullValue()) 3801 return N0; 3802 // fold (srl x, c >= size(x)) -> undef 3803 if (N1C && N1C->getZExtValue() >= OpSizeInBits) 3804 return DAG.getUNDEF(VT); 3805 // fold (srl x, 0) -> x 3806 if (N1C && N1C->isNullValue()) 3807 return N0; 3808 // if (srl x, c) is known to be zero, return 0 3809 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0), 3810 APInt::getAllOnesValue(OpSizeInBits))) 3811 return DAG.getConstant(0, VT); 3812 3813 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2)) 3814 if (N1C && N0.getOpcode() == ISD::SRL && 3815 N0.getOperand(1).getOpcode() == ISD::Constant) { 3816 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue(); 3817 uint64_t c2 = N1C->getZExtValue(); 3818 if (c1 + c2 >= OpSizeInBits) 3819 return DAG.getConstant(0, VT); 3820 return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0.getOperand(0), 3821 DAG.getConstant(c1 + c2, N1.getValueType())); 3822 } 3823 3824 // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2))) 3825 if (N1C && N0.getOpcode() == ISD::TRUNCATE && 3826 N0.getOperand(0).getOpcode() == ISD::SRL && 3827 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) { 3828 uint64_t c1 = 3829 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue(); 3830 uint64_t c2 = N1C->getZExtValue(); 3831 EVT InnerShiftVT = N0.getOperand(0).getValueType(); 3832 EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType(); 3833 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits(); 3834 // This is only valid if the OpSizeInBits + c1 = size of inner shift. 3835 if (c1 + OpSizeInBits == InnerShiftSize) { 3836 if (c1 + c2 >= InnerShiftSize) 3837 return DAG.getConstant(0, VT); 3838 return DAG.getNode(ISD::TRUNCATE, N0->getDebugLoc(), VT, 3839 DAG.getNode(ISD::SRL, N0->getDebugLoc(), InnerShiftVT, 3840 N0.getOperand(0)->getOperand(0), 3841 DAG.getConstant(c1 + c2, ShiftCountVT))); 3842 } 3843 } 3844 3845 // fold (srl (shl x, c), c) -> (and x, cst2) 3846 if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1 && 3847 N0.getValueSizeInBits() <= 64) { 3848 uint64_t ShAmt = N1C->getZExtValue()+64-N0.getValueSizeInBits(); 3849 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0.getOperand(0), 3850 DAG.getConstant(~0ULL >> ShAmt, VT)); 3851 } 3852 3853 3854 // fold (srl (anyextend x), c) -> (anyextend (srl x, c)) 3855 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) { 3856 // Shifting in all undef bits? 3857 EVT SmallVT = N0.getOperand(0).getValueType(); 3858 if (N1C->getZExtValue() >= SmallVT.getSizeInBits()) 3859 return DAG.getUNDEF(VT); 3860 3861 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) { 3862 uint64_t ShiftAmt = N1C->getZExtValue(); 3863 SDValue SmallShift = DAG.getNode(ISD::SRL, N0.getDebugLoc(), SmallVT, 3864 N0.getOperand(0), 3865 DAG.getConstant(ShiftAmt, getShiftAmountTy(SmallVT))); 3866 AddToWorkList(SmallShift.getNode()); 3867 return DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, SmallShift); 3868 } 3869 } 3870 3871 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign 3872 // bit, which is unmodified by sra. 3873 if (N1C && N1C->getZExtValue() + 1 == VT.getSizeInBits()) { 3874 if (N0.getOpcode() == ISD::SRA) 3875 return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0.getOperand(0), N1); 3876 } 3877 3878 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit). 3879 if (N1C && N0.getOpcode() == ISD::CTLZ && 3880 N1C->getAPIntValue() == Log2_32(VT.getSizeInBits())) { 3881 APInt KnownZero, KnownOne; 3882 DAG.ComputeMaskedBits(N0.getOperand(0), KnownZero, KnownOne); 3883 3884 // If any of the input bits are KnownOne, then the input couldn't be all 3885 // zeros, thus the result of the srl will always be zero. 3886 if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT); 3887 3888 // If all of the bits input the to ctlz node are known to be zero, then 3889 // the result of the ctlz is "32" and the result of the shift is one. 3890 APInt UnknownBits = ~KnownZero; 3891 if (UnknownBits == 0) return DAG.getConstant(1, VT); 3892 3893 // Otherwise, check to see if there is exactly one bit input to the ctlz. 3894 if ((UnknownBits & (UnknownBits - 1)) == 0) { 3895 // Okay, we know that only that the single bit specified by UnknownBits 3896 // could be set on input to the CTLZ node. If this bit is set, the SRL 3897 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair 3898 // to an SRL/XOR pair, which is likely to simplify more. 3899 unsigned ShAmt = UnknownBits.countTrailingZeros(); 3900 SDValue Op = N0.getOperand(0); 3901 3902 if (ShAmt) { 3903 Op = DAG.getNode(ISD::SRL, N0.getDebugLoc(), VT, Op, 3904 DAG.getConstant(ShAmt, getShiftAmountTy(Op.getValueType()))); 3905 AddToWorkList(Op.getNode()); 3906 } 3907 3908 return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT, 3909 Op, DAG.getConstant(1, VT)); 3910 } 3911 } 3912 3913 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))). 3914 if (N1.getOpcode() == ISD::TRUNCATE && 3915 N1.getOperand(0).getOpcode() == ISD::AND && 3916 N1.hasOneUse() && N1.getOperand(0).hasOneUse()) { 3917 SDValue N101 = N1.getOperand(0).getOperand(1); 3918 if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) { 3919 EVT TruncVT = N1.getValueType(); 3920 SDValue N100 = N1.getOperand(0).getOperand(0); 3921 APInt TruncC = N101C->getAPIntValue(); 3922 TruncC = TruncC.trunc(TruncVT.getSizeInBits()); 3923 return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0, 3924 DAG.getNode(ISD::AND, N->getDebugLoc(), 3925 TruncVT, 3926 DAG.getNode(ISD::TRUNCATE, 3927 N->getDebugLoc(), 3928 TruncVT, N100), 3929 DAG.getConstant(TruncC, TruncVT))); 3930 } 3931 } 3932 3933 // fold operands of srl based on knowledge that the low bits are not 3934 // demanded. 3935 if (N1C && SimplifyDemandedBits(SDValue(N, 0))) 3936 return SDValue(N, 0); 3937 3938 if (N1C) { 3939 SDValue NewSRL = visitShiftByConstant(N, N1C->getZExtValue()); 3940 if (NewSRL.getNode()) 3941 return NewSRL; 3942 } 3943 3944 // Attempt to convert a srl of a load into a narrower zero-extending load. 3945 SDValue NarrowLoad = ReduceLoadWidth(N); 3946 if (NarrowLoad.getNode()) 3947 return NarrowLoad; 3948 3949 // Here is a common situation. We want to optimize: 3950 // 3951 // %a = ... 3952 // %b = and i32 %a, 2 3953 // %c = srl i32 %b, 1 3954 // brcond i32 %c ... 3955 // 3956 // into 3957 // 3958 // %a = ... 3959 // %b = and %a, 2 3960 // %c = setcc eq %b, 0 3961 // brcond %c ... 3962 // 3963 // However when after the source operand of SRL is optimized into AND, the SRL 3964 // itself may not be optimized further. Look for it and add the BRCOND into 3965 // the worklist. 3966 if (N->hasOneUse()) { 3967 SDNode *Use = *N->use_begin(); 3968 if (Use->getOpcode() == ISD::BRCOND) 3969 AddToWorkList(Use); 3970 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) { 3971 // Also look pass the truncate. 3972 Use = *Use->use_begin(); 3973 if (Use->getOpcode() == ISD::BRCOND) 3974 AddToWorkList(Use); 3975 } 3976 } 3977 3978 return SDValue(); 3979} 3980 3981SDValue DAGCombiner::visitCTLZ(SDNode *N) { 3982 SDValue N0 = N->getOperand(0); 3983 EVT VT = N->getValueType(0); 3984 3985 // fold (ctlz c1) -> c2 3986 if (isa<ConstantSDNode>(N0)) 3987 return DAG.getNode(ISD::CTLZ, N->getDebugLoc(), VT, N0); 3988 return SDValue(); 3989} 3990 3991SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) { 3992 SDValue N0 = N->getOperand(0); 3993 EVT VT = N->getValueType(0); 3994 3995 // fold (ctlz_zero_undef c1) -> c2 3996 if (isa<ConstantSDNode>(N0)) 3997 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, N->getDebugLoc(), VT, N0); 3998 return SDValue(); 3999} 4000 4001SDValue DAGCombiner::visitCTTZ(SDNode *N) { 4002 SDValue N0 = N->getOperand(0); 4003 EVT VT = N->getValueType(0); 4004 4005 // fold (cttz c1) -> c2 4006 if (isa<ConstantSDNode>(N0)) 4007 return DAG.getNode(ISD::CTTZ, N->getDebugLoc(), VT, N0); 4008 return SDValue(); 4009} 4010 4011SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) { 4012 SDValue N0 = N->getOperand(0); 4013 EVT VT = N->getValueType(0); 4014 4015 // fold (cttz_zero_undef c1) -> c2 4016 if (isa<ConstantSDNode>(N0)) 4017 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, N->getDebugLoc(), VT, N0); 4018 return SDValue(); 4019} 4020 4021SDValue DAGCombiner::visitCTPOP(SDNode *N) { 4022 SDValue N0 = N->getOperand(0); 4023 EVT VT = N->getValueType(0); 4024 4025 // fold (ctpop c1) -> c2 4026 if (isa<ConstantSDNode>(N0)) 4027 return DAG.getNode(ISD::CTPOP, N->getDebugLoc(), VT, N0); 4028 return SDValue(); 4029} 4030 4031SDValue DAGCombiner::visitSELECT(SDNode *N) { 4032 SDValue N0 = N->getOperand(0); 4033 SDValue N1 = N->getOperand(1); 4034 SDValue N2 = N->getOperand(2); 4035 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 4036 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 4037 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2); 4038 EVT VT = N->getValueType(0); 4039 EVT VT0 = N0.getValueType(); 4040 4041 // fold (select C, X, X) -> X 4042 if (N1 == N2) 4043 return N1; 4044 // fold (select true, X, Y) -> X 4045 if (N0C && !N0C->isNullValue()) 4046 return N1; 4047 // fold (select false, X, Y) -> Y 4048 if (N0C && N0C->isNullValue()) 4049 return N2; 4050 // fold (select C, 1, X) -> (or C, X) 4051 if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1) 4052 return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, N0, N2); 4053 // fold (select C, 0, 1) -> (xor C, 1) 4054 if (VT.isInteger() && 4055 (VT0 == MVT::i1 || 4056 (VT0.isInteger() && 4057 TLI.getBooleanContents(false) == 4058 TargetLowering::ZeroOrOneBooleanContent)) && 4059 N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) { 4060 SDValue XORNode; 4061 if (VT == VT0) 4062 return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT0, 4063 N0, DAG.getConstant(1, VT0)); 4064 XORNode = DAG.getNode(ISD::XOR, N0.getDebugLoc(), VT0, 4065 N0, DAG.getConstant(1, VT0)); 4066 AddToWorkList(XORNode.getNode()); 4067 if (VT.bitsGT(VT0)) 4068 return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT, XORNode); 4069 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, XORNode); 4070 } 4071 // fold (select C, 0, X) -> (and (not C), X) 4072 if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) { 4073 SDValue NOTNode = DAG.getNOT(N0.getDebugLoc(), N0, VT); 4074 AddToWorkList(NOTNode.getNode()); 4075 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, NOTNode, N2); 4076 } 4077 // fold (select C, X, 1) -> (or (not C), X) 4078 if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) { 4079 SDValue NOTNode = DAG.getNOT(N0.getDebugLoc(), N0, VT); 4080 AddToWorkList(NOTNode.getNode()); 4081 return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, NOTNode, N1); 4082 } 4083 // fold (select C, X, 0) -> (and C, X) 4084 if (VT == MVT::i1 && N2C && N2C->isNullValue()) 4085 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0, N1); 4086 // fold (select X, X, Y) -> (or X, Y) 4087 // fold (select X, 1, Y) -> (or X, Y) 4088 if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1))) 4089 return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, N0, N2); 4090 // fold (select X, Y, X) -> (and X, Y) 4091 // fold (select X, Y, 0) -> (and X, Y) 4092 if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0))) 4093 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0, N1); 4094 4095 // If we can fold this based on the true/false value, do so. 4096 if (SimplifySelectOps(N, N1, N2)) 4097 return SDValue(N, 0); // Don't revisit N. 4098 4099 // fold selects based on a setcc into other things, such as min/max/abs 4100 if (N0.getOpcode() == ISD::SETCC) { 4101 // FIXME: 4102 // Check against MVT::Other for SELECT_CC, which is a workaround for targets 4103 // having to say they don't support SELECT_CC on every type the DAG knows 4104 // about, since there is no way to mark an opcode illegal at all value types 4105 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other) && 4106 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) 4107 return DAG.getNode(ISD::SELECT_CC, N->getDebugLoc(), VT, 4108 N0.getOperand(0), N0.getOperand(1), 4109 N1, N2, N0.getOperand(2)); 4110 return SimplifySelect(N->getDebugLoc(), N0, N1, N2); 4111 } 4112 4113 return SDValue(); 4114} 4115 4116SDValue DAGCombiner::visitSELECT_CC(SDNode *N) { 4117 SDValue N0 = N->getOperand(0); 4118 SDValue N1 = N->getOperand(1); 4119 SDValue N2 = N->getOperand(2); 4120 SDValue N3 = N->getOperand(3); 4121 SDValue N4 = N->getOperand(4); 4122 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get(); 4123 4124 // fold select_cc lhs, rhs, x, x, cc -> x 4125 if (N2 == N3) 4126 return N2; 4127 4128 // Determine if the condition we're dealing with is constant 4129 SDValue SCC = SimplifySetCC(TLI.getSetCCResultType(N0.getValueType()), 4130 N0, N1, CC, N->getDebugLoc(), false); 4131 if (SCC.getNode()) AddToWorkList(SCC.getNode()); 4132 4133 if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode())) { 4134 if (!SCCC->isNullValue()) 4135 return N2; // cond always true -> true val 4136 else 4137 return N3; // cond always false -> false val 4138 } 4139 4140 // Fold to a simpler select_cc 4141 if (SCC.getNode() && SCC.getOpcode() == ISD::SETCC) 4142 return DAG.getNode(ISD::SELECT_CC, N->getDebugLoc(), N2.getValueType(), 4143 SCC.getOperand(0), SCC.getOperand(1), N2, N3, 4144 SCC.getOperand(2)); 4145 4146 // If we can fold this based on the true/false value, do so. 4147 if (SimplifySelectOps(N, N2, N3)) 4148 return SDValue(N, 0); // Don't revisit N. 4149 4150 // fold select_cc into other things, such as min/max/abs 4151 return SimplifySelectCC(N->getDebugLoc(), N0, N1, N2, N3, CC); 4152} 4153 4154SDValue DAGCombiner::visitSETCC(SDNode *N) { 4155 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1), 4156 cast<CondCodeSDNode>(N->getOperand(2))->get(), 4157 N->getDebugLoc()); 4158} 4159 4160// ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this: 4161// "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))" 4162// transformation. Returns true if extension are possible and the above 4163// mentioned transformation is profitable. 4164static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0, 4165 unsigned ExtOpc, 4166 SmallVector<SDNode*, 4> &ExtendNodes, 4167 const TargetLowering &TLI) { 4168 bool HasCopyToRegUses = false; 4169 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType()); 4170 for (SDNode::use_iterator UI = N0.getNode()->use_begin(), 4171 UE = N0.getNode()->use_end(); 4172 UI != UE; ++UI) { 4173 SDNode *User = *UI; 4174 if (User == N) 4175 continue; 4176 if (UI.getUse().getResNo() != N0.getResNo()) 4177 continue; 4178 // FIXME: Only extend SETCC N, N and SETCC N, c for now. 4179 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) { 4180 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get(); 4181 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC)) 4182 // Sign bits will be lost after a zext. 4183 return false; 4184 bool Add = false; 4185 for (unsigned i = 0; i != 2; ++i) { 4186 SDValue UseOp = User->getOperand(i); 4187 if (UseOp == N0) 4188 continue; 4189 if (!isa<ConstantSDNode>(UseOp)) 4190 return false; 4191 Add = true; 4192 } 4193 if (Add) 4194 ExtendNodes.push_back(User); 4195 continue; 4196 } 4197 // If truncates aren't free and there are users we can't 4198 // extend, it isn't worthwhile. 4199 if (!isTruncFree) 4200 return false; 4201 // Remember if this value is live-out. 4202 if (User->getOpcode() == ISD::CopyToReg) 4203 HasCopyToRegUses = true; 4204 } 4205 4206 if (HasCopyToRegUses) { 4207 bool BothLiveOut = false; 4208 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end(); 4209 UI != UE; ++UI) { 4210 SDUse &Use = UI.getUse(); 4211 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) { 4212 BothLiveOut = true; 4213 break; 4214 } 4215 } 4216 if (BothLiveOut) 4217 // Both unextended and extended values are live out. There had better be 4218 // a good reason for the transformation. 4219 return ExtendNodes.size(); 4220 } 4221 return true; 4222} 4223 4224void DAGCombiner::ExtendSetCCUses(SmallVector<SDNode*, 4> SetCCs, 4225 SDValue Trunc, SDValue ExtLoad, DebugLoc DL, 4226 ISD::NodeType ExtType) { 4227 // Extend SetCC uses if necessary. 4228 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) { 4229 SDNode *SetCC = SetCCs[i]; 4230 SmallVector<SDValue, 4> Ops; 4231 4232 for (unsigned j = 0; j != 2; ++j) { 4233 SDValue SOp = SetCC->getOperand(j); 4234 if (SOp == Trunc) 4235 Ops.push_back(ExtLoad); 4236 else 4237 Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp)); 4238 } 4239 4240 Ops.push_back(SetCC->getOperand(2)); 4241 CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), 4242 &Ops[0], Ops.size())); 4243 } 4244} 4245 4246SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) { 4247 SDValue N0 = N->getOperand(0); 4248 EVT VT = N->getValueType(0); 4249 4250 // fold (sext c1) -> c1 4251 if (isa<ConstantSDNode>(N0)) 4252 return DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), VT, N0); 4253 4254 // fold (sext (sext x)) -> (sext x) 4255 // fold (sext (aext x)) -> (sext x) 4256 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) 4257 return DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), VT, 4258 N0.getOperand(0)); 4259 4260 if (N0.getOpcode() == ISD::TRUNCATE) { 4261 // fold (sext (truncate (load x))) -> (sext (smaller load x)) 4262 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n))) 4263 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode()); 4264 if (NarrowLoad.getNode()) { 4265 SDNode* oye = N0.getNode()->getOperand(0).getNode(); 4266 if (NarrowLoad.getNode() != N0.getNode()) { 4267 CombineTo(N0.getNode(), NarrowLoad); 4268 // CombineTo deleted the truncate, if needed, but not what's under it. 4269 AddToWorkList(oye); 4270 } 4271 return SDValue(N, 0); // Return N so it doesn't get rechecked! 4272 } 4273 4274 // See if the value being truncated is already sign extended. If so, just 4275 // eliminate the trunc/sext pair. 4276 SDValue Op = N0.getOperand(0); 4277 unsigned OpBits = Op.getValueType().getScalarType().getSizeInBits(); 4278 unsigned MidBits = N0.getValueType().getScalarType().getSizeInBits(); 4279 unsigned DestBits = VT.getScalarType().getSizeInBits(); 4280 unsigned NumSignBits = DAG.ComputeNumSignBits(Op); 4281 4282 if (OpBits == DestBits) { 4283 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign 4284 // bits, it is already ready. 4285 if (NumSignBits > DestBits-MidBits) 4286 return Op; 4287 } else if (OpBits < DestBits) { 4288 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign 4289 // bits, just sext from i32. 4290 if (NumSignBits > OpBits-MidBits) 4291 return DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), VT, Op); 4292 } else { 4293 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign 4294 // bits, just truncate to i32. 4295 if (NumSignBits > OpBits-MidBits) 4296 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, Op); 4297 } 4298 4299 // fold (sext (truncate x)) -> (sextinreg x). 4300 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, 4301 N0.getValueType())) { 4302 if (OpBits < DestBits) 4303 Op = DAG.getNode(ISD::ANY_EXTEND, N0.getDebugLoc(), VT, Op); 4304 else if (OpBits > DestBits) 4305 Op = DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(), VT, Op); 4306 return DAG.getNode(ISD::SIGN_EXTEND_INREG, N->getDebugLoc(), VT, Op, 4307 DAG.getValueType(N0.getValueType())); 4308 } 4309 } 4310 4311 // fold (sext (load x)) -> (sext (truncate (sextload x))) 4312 // None of the supported targets knows how to perform load and sign extend 4313 // on vectors in one instruction. We only perform this transformation on 4314 // scalars. 4315 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() && 4316 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) || 4317 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()))) { 4318 bool DoXform = true; 4319 SmallVector<SDNode*, 4> SetCCs; 4320 if (!N0.hasOneUse()) 4321 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI); 4322 if (DoXform) { 4323 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 4324 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, N->getDebugLoc(), VT, 4325 LN0->getChain(), 4326 LN0->getBasePtr(), LN0->getPointerInfo(), 4327 N0.getValueType(), 4328 LN0->isVolatile(), LN0->isNonTemporal(), 4329 LN0->getAlignment()); 4330 CombineTo(N, ExtLoad); 4331 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(), 4332 N0.getValueType(), ExtLoad); 4333 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1)); 4334 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, N->getDebugLoc(), 4335 ISD::SIGN_EXTEND); 4336 return SDValue(N, 0); // Return N so it doesn't get rechecked! 4337 } 4338 } 4339 4340 // fold (sext (sextload x)) -> (sext (truncate (sextload x))) 4341 // fold (sext ( extload x)) -> (sext (truncate (sextload x))) 4342 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) && 4343 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) { 4344 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 4345 EVT MemVT = LN0->getMemoryVT(); 4346 if ((!LegalOperations && !LN0->isVolatile()) || 4347 TLI.isLoadExtLegal(ISD::SEXTLOAD, MemVT)) { 4348 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, N->getDebugLoc(), VT, 4349 LN0->getChain(), 4350 LN0->getBasePtr(), LN0->getPointerInfo(), 4351 MemVT, 4352 LN0->isVolatile(), LN0->isNonTemporal(), 4353 LN0->getAlignment()); 4354 CombineTo(N, ExtLoad); 4355 CombineTo(N0.getNode(), 4356 DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(), 4357 N0.getValueType(), ExtLoad), 4358 ExtLoad.getValue(1)); 4359 return SDValue(N, 0); // Return N so it doesn't get rechecked! 4360 } 4361 } 4362 4363 // fold (sext (and/or/xor (load x), cst)) -> 4364 // (and/or/xor (sextload x), (sext cst)) 4365 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR || 4366 N0.getOpcode() == ISD::XOR) && 4367 isa<LoadSDNode>(N0.getOperand(0)) && 4368 N0.getOperand(1).getOpcode() == ISD::Constant && 4369 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()) && 4370 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) { 4371 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0)); 4372 if (LN0->getExtensionType() != ISD::ZEXTLOAD) { 4373 bool DoXform = true; 4374 SmallVector<SDNode*, 4> SetCCs; 4375 if (!N0.hasOneUse()) 4376 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND, 4377 SetCCs, TLI); 4378 if (DoXform) { 4379 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, LN0->getDebugLoc(), VT, 4380 LN0->getChain(), LN0->getBasePtr(), 4381 LN0->getPointerInfo(), 4382 LN0->getMemoryVT(), 4383 LN0->isVolatile(), 4384 LN0->isNonTemporal(), 4385 LN0->getAlignment()); 4386 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 4387 Mask = Mask.sext(VT.getSizeInBits()); 4388 SDValue And = DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT, 4389 ExtLoad, DAG.getConstant(Mask, VT)); 4390 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, 4391 N0.getOperand(0).getDebugLoc(), 4392 N0.getOperand(0).getValueType(), ExtLoad); 4393 CombineTo(N, And); 4394 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1)); 4395 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, N->getDebugLoc(), 4396 ISD::SIGN_EXTEND); 4397 return SDValue(N, 0); // Return N so it doesn't get rechecked! 4398 } 4399 } 4400 } 4401 4402 if (N0.getOpcode() == ISD::SETCC) { 4403 // sext(setcc) -> sext_in_reg(vsetcc) for vectors. 4404 // Only do this before legalize for now. 4405 if (VT.isVector() && !LegalOperations) { 4406 EVT N0VT = N0.getOperand(0).getValueType(); 4407 // On some architectures (such as SSE/NEON/etc) the SETCC result type is 4408 // of the same size as the compared operands. Only optimize sext(setcc()) 4409 // if this is the case. 4410 EVT SVT = TLI.getSetCCResultType(N0VT); 4411 4412 // We know that the # elements of the results is the same as the 4413 // # elements of the compare (and the # elements of the compare result 4414 // for that matter). Check to see that they are the same size. If so, 4415 // we know that the element size of the sext'd result matches the 4416 // element size of the compare operands. 4417 if (VT.getSizeInBits() == SVT.getSizeInBits()) 4418 return DAG.getSetCC(N->getDebugLoc(), VT, N0.getOperand(0), 4419 N0.getOperand(1), 4420 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 4421 // If the desired elements are smaller or larger than the source 4422 // elements we can use a matching integer vector type and then 4423 // truncate/sign extend 4424 EVT MatchingElementType = 4425 EVT::getIntegerVT(*DAG.getContext(), 4426 N0VT.getScalarType().getSizeInBits()); 4427 EVT MatchingVectorType = 4428 EVT::getVectorVT(*DAG.getContext(), MatchingElementType, 4429 N0VT.getVectorNumElements()); 4430 4431 if (SVT == MatchingVectorType) { 4432 SDValue VsetCC = DAG.getSetCC(N->getDebugLoc(), MatchingVectorType, 4433 N0.getOperand(0), N0.getOperand(1), 4434 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 4435 return DAG.getSExtOrTrunc(VsetCC, N->getDebugLoc(), VT); 4436 } 4437 } 4438 4439 // sext(setcc x, y, cc) -> (select_cc x, y, -1, 0, cc) 4440 unsigned ElementWidth = VT.getScalarType().getSizeInBits(); 4441 SDValue NegOne = 4442 DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT); 4443 SDValue SCC = 4444 SimplifySelectCC(N->getDebugLoc(), N0.getOperand(0), N0.getOperand(1), 4445 NegOne, DAG.getConstant(0, VT), 4446 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true); 4447 if (SCC.getNode()) return SCC; 4448 if (!LegalOperations || 4449 TLI.isOperationLegal(ISD::SETCC, TLI.getSetCCResultType(VT))) 4450 return DAG.getNode(ISD::SELECT, N->getDebugLoc(), VT, 4451 DAG.getSetCC(N->getDebugLoc(), 4452 TLI.getSetCCResultType(VT), 4453 N0.getOperand(0), N0.getOperand(1), 4454 cast<CondCodeSDNode>(N0.getOperand(2))->get()), 4455 NegOne, DAG.getConstant(0, VT)); 4456 } 4457 4458 // fold (sext x) -> (zext x) if the sign bit is known zero. 4459 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) && 4460 DAG.SignBitIsZero(N0)) 4461 return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT, N0); 4462 4463 return SDValue(); 4464} 4465 4466// isTruncateOf - If N is a truncate of some other value, return true, record 4467// the value being truncated in Op and which of Op's bits are zero in KnownZero. 4468// This function computes KnownZero to avoid a duplicated call to 4469// ComputeMaskedBits in the caller. 4470static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op, 4471 APInt &KnownZero) { 4472 APInt KnownOne; 4473 if (N->getOpcode() == ISD::TRUNCATE) { 4474 Op = N->getOperand(0); 4475 DAG.ComputeMaskedBits(Op, KnownZero, KnownOne); 4476 return true; 4477 } 4478 4479 if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 || 4480 cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE) 4481 return false; 4482 4483 SDValue Op0 = N->getOperand(0); 4484 SDValue Op1 = N->getOperand(1); 4485 assert(Op0.getValueType() == Op1.getValueType()); 4486 4487 ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0); 4488 ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1); 4489 if (COp0 && COp0->isNullValue()) 4490 Op = Op1; 4491 else if (COp1 && COp1->isNullValue()) 4492 Op = Op0; 4493 else 4494 return false; 4495 4496 DAG.ComputeMaskedBits(Op, KnownZero, KnownOne); 4497 4498 if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue()) 4499 return false; 4500 4501 return true; 4502} 4503 4504SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) { 4505 SDValue N0 = N->getOperand(0); 4506 EVT VT = N->getValueType(0); 4507 4508 // fold (zext c1) -> c1 4509 if (isa<ConstantSDNode>(N0)) 4510 return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT, N0); 4511 // fold (zext (zext x)) -> (zext x) 4512 // fold (zext (aext x)) -> (zext x) 4513 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) 4514 return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT, 4515 N0.getOperand(0)); 4516 4517 // fold (zext (truncate x)) -> (zext x) or 4518 // (zext (truncate x)) -> (truncate x) 4519 // This is valid when the truncated bits of x are already zero. 4520 // FIXME: We should extend this to work for vectors too. 4521 SDValue Op; 4522 APInt KnownZero; 4523 if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) { 4524 APInt TruncatedBits = 4525 (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ? 4526 APInt(Op.getValueSizeInBits(), 0) : 4527 APInt::getBitsSet(Op.getValueSizeInBits(), 4528 N0.getValueSizeInBits(), 4529 std::min(Op.getValueSizeInBits(), 4530 VT.getSizeInBits())); 4531 if (TruncatedBits == (KnownZero & TruncatedBits)) { 4532 if (VT.bitsGT(Op.getValueType())) 4533 return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT, Op); 4534 if (VT.bitsLT(Op.getValueType())) 4535 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, Op); 4536 4537 return Op; 4538 } 4539 } 4540 4541 // fold (zext (truncate (load x))) -> (zext (smaller load x)) 4542 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n))) 4543 if (N0.getOpcode() == ISD::TRUNCATE) { 4544 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode()); 4545 if (NarrowLoad.getNode()) { 4546 SDNode* oye = N0.getNode()->getOperand(0).getNode(); 4547 if (NarrowLoad.getNode() != N0.getNode()) { 4548 CombineTo(N0.getNode(), NarrowLoad); 4549 // CombineTo deleted the truncate, if needed, but not what's under it. 4550 AddToWorkList(oye); 4551 } 4552 return SDValue(N, 0); // Return N so it doesn't get rechecked! 4553 } 4554 } 4555 4556 // fold (zext (truncate x)) -> (and x, mask) 4557 if (N0.getOpcode() == ISD::TRUNCATE && 4558 (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) { 4559 4560 // fold (zext (truncate (load x))) -> (zext (smaller load x)) 4561 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n))) 4562 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode()); 4563 if (NarrowLoad.getNode()) { 4564 SDNode* oye = N0.getNode()->getOperand(0).getNode(); 4565 if (NarrowLoad.getNode() != N0.getNode()) { 4566 CombineTo(N0.getNode(), NarrowLoad); 4567 // CombineTo deleted the truncate, if needed, but not what's under it. 4568 AddToWorkList(oye); 4569 } 4570 return SDValue(N, 0); // Return N so it doesn't get rechecked! 4571 } 4572 4573 SDValue Op = N0.getOperand(0); 4574 if (Op.getValueType().bitsLT(VT)) { 4575 Op = DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, Op); 4576 AddToWorkList(Op.getNode()); 4577 } else if (Op.getValueType().bitsGT(VT)) { 4578 Op = DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, Op); 4579 AddToWorkList(Op.getNode()); 4580 } 4581 return DAG.getZeroExtendInReg(Op, N->getDebugLoc(), 4582 N0.getValueType().getScalarType()); 4583 } 4584 4585 // Fold (zext (and (trunc x), cst)) -> (and x, cst), 4586 // if either of the casts is not free. 4587 if (N0.getOpcode() == ISD::AND && 4588 N0.getOperand(0).getOpcode() == ISD::TRUNCATE && 4589 N0.getOperand(1).getOpcode() == ISD::Constant && 4590 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(), 4591 N0.getValueType()) || 4592 !TLI.isZExtFree(N0.getValueType(), VT))) { 4593 SDValue X = N0.getOperand(0).getOperand(0); 4594 if (X.getValueType().bitsLT(VT)) { 4595 X = DAG.getNode(ISD::ANY_EXTEND, X.getDebugLoc(), VT, X); 4596 } else if (X.getValueType().bitsGT(VT)) { 4597 X = DAG.getNode(ISD::TRUNCATE, X.getDebugLoc(), VT, X); 4598 } 4599 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 4600 Mask = Mask.zext(VT.getSizeInBits()); 4601 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, 4602 X, DAG.getConstant(Mask, VT)); 4603 } 4604 4605 // fold (zext (load x)) -> (zext (truncate (zextload x))) 4606 // None of the supported targets knows how to perform load and vector_zext 4607 // on vectors in one instruction. We only perform this transformation on 4608 // scalars. 4609 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() && 4610 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) || 4611 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()))) { 4612 bool DoXform = true; 4613 SmallVector<SDNode*, 4> SetCCs; 4614 if (!N0.hasOneUse()) 4615 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI); 4616 if (DoXform) { 4617 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 4618 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, N->getDebugLoc(), VT, 4619 LN0->getChain(), 4620 LN0->getBasePtr(), LN0->getPointerInfo(), 4621 N0.getValueType(), 4622 LN0->isVolatile(), LN0->isNonTemporal(), 4623 LN0->getAlignment()); 4624 CombineTo(N, ExtLoad); 4625 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(), 4626 N0.getValueType(), ExtLoad); 4627 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1)); 4628 4629 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, N->getDebugLoc(), 4630 ISD::ZERO_EXTEND); 4631 return SDValue(N, 0); // Return N so it doesn't get rechecked! 4632 } 4633 } 4634 4635 // fold (zext (and/or/xor (load x), cst)) -> 4636 // (and/or/xor (zextload x), (zext cst)) 4637 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR || 4638 N0.getOpcode() == ISD::XOR) && 4639 isa<LoadSDNode>(N0.getOperand(0)) && 4640 N0.getOperand(1).getOpcode() == ISD::Constant && 4641 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()) && 4642 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) { 4643 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0)); 4644 if (LN0->getExtensionType() != ISD::SEXTLOAD) { 4645 bool DoXform = true; 4646 SmallVector<SDNode*, 4> SetCCs; 4647 if (!N0.hasOneUse()) 4648 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND, 4649 SetCCs, TLI); 4650 if (DoXform) { 4651 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, LN0->getDebugLoc(), VT, 4652 LN0->getChain(), LN0->getBasePtr(), 4653 LN0->getPointerInfo(), 4654 LN0->getMemoryVT(), 4655 LN0->isVolatile(), 4656 LN0->isNonTemporal(), 4657 LN0->getAlignment()); 4658 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 4659 Mask = Mask.zext(VT.getSizeInBits()); 4660 SDValue And = DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT, 4661 ExtLoad, DAG.getConstant(Mask, VT)); 4662 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, 4663 N0.getOperand(0).getDebugLoc(), 4664 N0.getOperand(0).getValueType(), ExtLoad); 4665 CombineTo(N, And); 4666 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1)); 4667 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, N->getDebugLoc(), 4668 ISD::ZERO_EXTEND); 4669 return SDValue(N, 0); // Return N so it doesn't get rechecked! 4670 } 4671 } 4672 } 4673 4674 // fold (zext (zextload x)) -> (zext (truncate (zextload x))) 4675 // fold (zext ( extload x)) -> (zext (truncate (zextload x))) 4676 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) && 4677 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) { 4678 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 4679 EVT MemVT = LN0->getMemoryVT(); 4680 if ((!LegalOperations && !LN0->isVolatile()) || 4681 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT)) { 4682 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, N->getDebugLoc(), VT, 4683 LN0->getChain(), 4684 LN0->getBasePtr(), LN0->getPointerInfo(), 4685 MemVT, 4686 LN0->isVolatile(), LN0->isNonTemporal(), 4687 LN0->getAlignment()); 4688 CombineTo(N, ExtLoad); 4689 CombineTo(N0.getNode(), 4690 DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(), N0.getValueType(), 4691 ExtLoad), 4692 ExtLoad.getValue(1)); 4693 return SDValue(N, 0); // Return N so it doesn't get rechecked! 4694 } 4695 } 4696 4697 if (N0.getOpcode() == ISD::SETCC) { 4698 if (!LegalOperations && VT.isVector()) { 4699 // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors. 4700 // Only do this before legalize for now. 4701 EVT N0VT = N0.getOperand(0).getValueType(); 4702 EVT EltVT = VT.getVectorElementType(); 4703 SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(), 4704 DAG.getConstant(1, EltVT)); 4705 if (VT.getSizeInBits() == N0VT.getSizeInBits()) 4706 // We know that the # elements of the results is the same as the 4707 // # elements of the compare (and the # elements of the compare result 4708 // for that matter). Check to see that they are the same size. If so, 4709 // we know that the element size of the sext'd result matches the 4710 // element size of the compare operands. 4711 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, 4712 DAG.getSetCC(N->getDebugLoc(), VT, N0.getOperand(0), 4713 N0.getOperand(1), 4714 cast<CondCodeSDNode>(N0.getOperand(2))->get()), 4715 DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(), VT, 4716 &OneOps[0], OneOps.size())); 4717 4718 // If the desired elements are smaller or larger than the source 4719 // elements we can use a matching integer vector type and then 4720 // truncate/sign extend 4721 EVT MatchingElementType = 4722 EVT::getIntegerVT(*DAG.getContext(), 4723 N0VT.getScalarType().getSizeInBits()); 4724 EVT MatchingVectorType = 4725 EVT::getVectorVT(*DAG.getContext(), MatchingElementType, 4726 N0VT.getVectorNumElements()); 4727 SDValue VsetCC = 4728 DAG.getSetCC(N->getDebugLoc(), MatchingVectorType, N0.getOperand(0), 4729 N0.getOperand(1), 4730 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 4731 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, 4732 DAG.getSExtOrTrunc(VsetCC, N->getDebugLoc(), VT), 4733 DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(), VT, 4734 &OneOps[0], OneOps.size())); 4735 } 4736 4737 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc 4738 SDValue SCC = 4739 SimplifySelectCC(N->getDebugLoc(), N0.getOperand(0), N0.getOperand(1), 4740 DAG.getConstant(1, VT), DAG.getConstant(0, VT), 4741 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true); 4742 if (SCC.getNode()) return SCC; 4743 } 4744 4745 // (zext (shl (zext x), cst)) -> (shl (zext x), cst) 4746 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) && 4747 isa<ConstantSDNode>(N0.getOperand(1)) && 4748 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND && 4749 N0.hasOneUse()) { 4750 SDValue ShAmt = N0.getOperand(1); 4751 unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue(); 4752 if (N0.getOpcode() == ISD::SHL) { 4753 SDValue InnerZExt = N0.getOperand(0); 4754 // If the original shl may be shifting out bits, do not perform this 4755 // transformation. 4756 unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() - 4757 InnerZExt.getOperand(0).getValueType().getSizeInBits(); 4758 if (ShAmtVal > KnownZeroBits) 4759 return SDValue(); 4760 } 4761 4762 DebugLoc DL = N->getDebugLoc(); 4763 4764 // Ensure that the shift amount is wide enough for the shifted value. 4765 if (VT.getSizeInBits() >= 256) 4766 ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt); 4767 4768 return DAG.getNode(N0.getOpcode(), DL, VT, 4769 DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)), 4770 ShAmt); 4771 } 4772 4773 return SDValue(); 4774} 4775 4776SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) { 4777 SDValue N0 = N->getOperand(0); 4778 EVT VT = N->getValueType(0); 4779 4780 // fold (aext c1) -> c1 4781 if (isa<ConstantSDNode>(N0)) 4782 return DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, N0); 4783 // fold (aext (aext x)) -> (aext x) 4784 // fold (aext (zext x)) -> (zext x) 4785 // fold (aext (sext x)) -> (sext x) 4786 if (N0.getOpcode() == ISD::ANY_EXTEND || 4787 N0.getOpcode() == ISD::ZERO_EXTEND || 4788 N0.getOpcode() == ISD::SIGN_EXTEND) 4789 return DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT, N0.getOperand(0)); 4790 4791 // fold (aext (truncate (load x))) -> (aext (smaller load x)) 4792 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n))) 4793 if (N0.getOpcode() == ISD::TRUNCATE) { 4794 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode()); 4795 if (NarrowLoad.getNode()) { 4796 SDNode* oye = N0.getNode()->getOperand(0).getNode(); 4797 if (NarrowLoad.getNode() != N0.getNode()) { 4798 CombineTo(N0.getNode(), NarrowLoad); 4799 // CombineTo deleted the truncate, if needed, but not what's under it. 4800 AddToWorkList(oye); 4801 } 4802 return SDValue(N, 0); // Return N so it doesn't get rechecked! 4803 } 4804 } 4805 4806 // fold (aext (truncate x)) 4807 if (N0.getOpcode() == ISD::TRUNCATE) { 4808 SDValue TruncOp = N0.getOperand(0); 4809 if (TruncOp.getValueType() == VT) 4810 return TruncOp; // x iff x size == zext size. 4811 if (TruncOp.getValueType().bitsGT(VT)) 4812 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, TruncOp); 4813 return DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, TruncOp); 4814 } 4815 4816 // Fold (aext (and (trunc x), cst)) -> (and x, cst) 4817 // if the trunc is not free. 4818 if (N0.getOpcode() == ISD::AND && 4819 N0.getOperand(0).getOpcode() == ISD::TRUNCATE && 4820 N0.getOperand(1).getOpcode() == ISD::Constant && 4821 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(), 4822 N0.getValueType())) { 4823 SDValue X = N0.getOperand(0).getOperand(0); 4824 if (X.getValueType().bitsLT(VT)) { 4825 X = DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, X); 4826 } else if (X.getValueType().bitsGT(VT)) { 4827 X = DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, X); 4828 } 4829 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 4830 Mask = Mask.zext(VT.getSizeInBits()); 4831 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, 4832 X, DAG.getConstant(Mask, VT)); 4833 } 4834 4835 // fold (aext (load x)) -> (aext (truncate (extload x))) 4836 // None of the supported targets knows how to perform load and any_ext 4837 // on vectors in one instruction. We only perform this transformation on 4838 // scalars. 4839 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() && 4840 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) || 4841 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) { 4842 bool DoXform = true; 4843 SmallVector<SDNode*, 4> SetCCs; 4844 if (!N0.hasOneUse()) 4845 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI); 4846 if (DoXform) { 4847 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 4848 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, N->getDebugLoc(), VT, 4849 LN0->getChain(), 4850 LN0->getBasePtr(), LN0->getPointerInfo(), 4851 N0.getValueType(), 4852 LN0->isVolatile(), LN0->isNonTemporal(), 4853 LN0->getAlignment()); 4854 CombineTo(N, ExtLoad); 4855 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(), 4856 N0.getValueType(), ExtLoad); 4857 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1)); 4858 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, N->getDebugLoc(), 4859 ISD::ANY_EXTEND); 4860 return SDValue(N, 0); // Return N so it doesn't get rechecked! 4861 } 4862 } 4863 4864 // fold (aext (zextload x)) -> (aext (truncate (zextload x))) 4865 // fold (aext (sextload x)) -> (aext (truncate (sextload x))) 4866 // fold (aext ( extload x)) -> (aext (truncate (extload x))) 4867 if (N0.getOpcode() == ISD::LOAD && 4868 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 4869 N0.hasOneUse()) { 4870 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 4871 EVT MemVT = LN0->getMemoryVT(); 4872 SDValue ExtLoad = DAG.getExtLoad(LN0->getExtensionType(), N->getDebugLoc(), 4873 VT, LN0->getChain(), LN0->getBasePtr(), 4874 LN0->getPointerInfo(), MemVT, 4875 LN0->isVolatile(), LN0->isNonTemporal(), 4876 LN0->getAlignment()); 4877 CombineTo(N, ExtLoad); 4878 CombineTo(N0.getNode(), 4879 DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(), 4880 N0.getValueType(), ExtLoad), 4881 ExtLoad.getValue(1)); 4882 return SDValue(N, 0); // Return N so it doesn't get rechecked! 4883 } 4884 4885 if (N0.getOpcode() == ISD::SETCC) { 4886 // aext(setcc) -> sext_in_reg(vsetcc) for vectors. 4887 // Only do this before legalize for now. 4888 if (VT.isVector() && !LegalOperations) { 4889 EVT N0VT = N0.getOperand(0).getValueType(); 4890 // We know that the # elements of the results is the same as the 4891 // # elements of the compare (and the # elements of the compare result 4892 // for that matter). Check to see that they are the same size. If so, 4893 // we know that the element size of the sext'd result matches the 4894 // element size of the compare operands. 4895 if (VT.getSizeInBits() == N0VT.getSizeInBits()) 4896 return DAG.getSetCC(N->getDebugLoc(), VT, N0.getOperand(0), 4897 N0.getOperand(1), 4898 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 4899 // If the desired elements are smaller or larger than the source 4900 // elements we can use a matching integer vector type and then 4901 // truncate/sign extend 4902 else { 4903 EVT MatchingElementType = 4904 EVT::getIntegerVT(*DAG.getContext(), 4905 N0VT.getScalarType().getSizeInBits()); 4906 EVT MatchingVectorType = 4907 EVT::getVectorVT(*DAG.getContext(), MatchingElementType, 4908 N0VT.getVectorNumElements()); 4909 SDValue VsetCC = 4910 DAG.getSetCC(N->getDebugLoc(), MatchingVectorType, N0.getOperand(0), 4911 N0.getOperand(1), 4912 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 4913 return DAG.getSExtOrTrunc(VsetCC, N->getDebugLoc(), VT); 4914 } 4915 } 4916 4917 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc 4918 SDValue SCC = 4919 SimplifySelectCC(N->getDebugLoc(), N0.getOperand(0), N0.getOperand(1), 4920 DAG.getConstant(1, VT), DAG.getConstant(0, VT), 4921 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true); 4922 if (SCC.getNode()) 4923 return SCC; 4924 } 4925 4926 return SDValue(); 4927} 4928 4929/// GetDemandedBits - See if the specified operand can be simplified with the 4930/// knowledge that only the bits specified by Mask are used. If so, return the 4931/// simpler operand, otherwise return a null SDValue. 4932SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) { 4933 switch (V.getOpcode()) { 4934 default: break; 4935 case ISD::Constant: { 4936 const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode()); 4937 assert(CV != 0 && "Const value should be ConstSDNode."); 4938 const APInt &CVal = CV->getAPIntValue(); 4939 APInt NewVal = CVal & Mask; 4940 if (NewVal != CVal) { 4941 return DAG.getConstant(NewVal, V.getValueType()); 4942 } 4943 break; 4944 } 4945 case ISD::OR: 4946 case ISD::XOR: 4947 // If the LHS or RHS don't contribute bits to the or, drop them. 4948 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask)) 4949 return V.getOperand(1); 4950 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask)) 4951 return V.getOperand(0); 4952 break; 4953 case ISD::SRL: 4954 // Only look at single-use SRLs. 4955 if (!V.getNode()->hasOneUse()) 4956 break; 4957 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) { 4958 // See if we can recursively simplify the LHS. 4959 unsigned Amt = RHSC->getZExtValue(); 4960 4961 // Watch out for shift count overflow though. 4962 if (Amt >= Mask.getBitWidth()) break; 4963 APInt NewMask = Mask << Amt; 4964 SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask); 4965 if (SimplifyLHS.getNode()) 4966 return DAG.getNode(ISD::SRL, V.getDebugLoc(), V.getValueType(), 4967 SimplifyLHS, V.getOperand(1)); 4968 } 4969 } 4970 return SDValue(); 4971} 4972 4973/// ReduceLoadWidth - If the result of a wider load is shifted to right of N 4974/// bits and then truncated to a narrower type and where N is a multiple 4975/// of number of bits of the narrower type, transform it to a narrower load 4976/// from address + N / num of bits of new type. If the result is to be 4977/// extended, also fold the extension to form a extending load. 4978SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) { 4979 unsigned Opc = N->getOpcode(); 4980 4981 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD; 4982 SDValue N0 = N->getOperand(0); 4983 EVT VT = N->getValueType(0); 4984 EVT ExtVT = VT; 4985 4986 // This transformation isn't valid for vector loads. 4987 if (VT.isVector()) 4988 return SDValue(); 4989 4990 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then 4991 // extended to VT. 4992 if (Opc == ISD::SIGN_EXTEND_INREG) { 4993 ExtType = ISD::SEXTLOAD; 4994 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT(); 4995 } else if (Opc == ISD::SRL) { 4996 // Another special-case: SRL is basically zero-extending a narrower value. 4997 ExtType = ISD::ZEXTLOAD; 4998 N0 = SDValue(N, 0); 4999 ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 5000 if (!N01) return SDValue(); 5001 ExtVT = EVT::getIntegerVT(*DAG.getContext(), 5002 VT.getSizeInBits() - N01->getZExtValue()); 5003 } 5004 if (LegalOperations && !TLI.isLoadExtLegal(ExtType, ExtVT)) 5005 return SDValue(); 5006 5007 unsigned EVTBits = ExtVT.getSizeInBits(); 5008 5009 // Do not generate loads of non-round integer types since these can 5010 // be expensive (and would be wrong if the type is not byte sized). 5011 if (!ExtVT.isRound()) 5012 return SDValue(); 5013 5014 unsigned ShAmt = 0; 5015 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) { 5016 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 5017 ShAmt = N01->getZExtValue(); 5018 // Is the shift amount a multiple of size of VT? 5019 if ((ShAmt & (EVTBits-1)) == 0) { 5020 N0 = N0.getOperand(0); 5021 // Is the load width a multiple of size of VT? 5022 if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0) 5023 return SDValue(); 5024 } 5025 5026 // At this point, we must have a load or else we can't do the transform. 5027 if (!isa<LoadSDNode>(N0)) return SDValue(); 5028 5029 // If the shift amount is larger than the input type then we're not 5030 // accessing any of the loaded bytes. If the load was a zextload/extload 5031 // then the result of the shift+trunc is zero/undef (handled elsewhere). 5032 // If the load was a sextload then the result is a splat of the sign bit 5033 // of the extended byte. This is not worth optimizing for. 5034 if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits()) 5035 return SDValue(); 5036 } 5037 } 5038 5039 // If the load is shifted left (and the result isn't shifted back right), 5040 // we can fold the truncate through the shift. 5041 unsigned ShLeftAmt = 0; 5042 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() && 5043 ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) { 5044 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 5045 ShLeftAmt = N01->getZExtValue(); 5046 N0 = N0.getOperand(0); 5047 } 5048 } 5049 5050 // If we haven't found a load, we can't narrow it. Don't transform one with 5051 // multiple uses, this would require adding a new load. 5052 if (!isa<LoadSDNode>(N0) || !N0.hasOneUse() || 5053 // Don't change the width of a volatile load. 5054 cast<LoadSDNode>(N0)->isVolatile()) 5055 return SDValue(); 5056 5057 // Verify that we are actually reducing a load width here. 5058 if (cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits() < EVTBits) 5059 return SDValue(); 5060 5061 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 5062 EVT PtrType = N0.getOperand(1).getValueType(); 5063 5064 if (PtrType == MVT::Untyped || PtrType.isExtended()) 5065 // It's not possible to generate a constant of extended or untyped type. 5066 return SDValue(); 5067 5068 // For big endian targets, we need to adjust the offset to the pointer to 5069 // load the correct bytes. 5070 if (TLI.isBigEndian()) { 5071 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits(); 5072 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits(); 5073 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt; 5074 } 5075 5076 uint64_t PtrOff = ShAmt / 8; 5077 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff); 5078 SDValue NewPtr = DAG.getNode(ISD::ADD, LN0->getDebugLoc(), 5079 PtrType, LN0->getBasePtr(), 5080 DAG.getConstant(PtrOff, PtrType)); 5081 AddToWorkList(NewPtr.getNode()); 5082 5083 SDValue Load; 5084 if (ExtType == ISD::NON_EXTLOAD) 5085 Load = DAG.getLoad(VT, N0.getDebugLoc(), LN0->getChain(), NewPtr, 5086 LN0->getPointerInfo().getWithOffset(PtrOff), 5087 LN0->isVolatile(), LN0->isNonTemporal(), 5088 LN0->isInvariant(), NewAlign); 5089 else 5090 Load = DAG.getExtLoad(ExtType, N0.getDebugLoc(), VT, LN0->getChain(),NewPtr, 5091 LN0->getPointerInfo().getWithOffset(PtrOff), 5092 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(), 5093 NewAlign); 5094 5095 // Replace the old load's chain with the new load's chain. 5096 WorkListRemover DeadNodes(*this); 5097 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1)); 5098 5099 // Shift the result left, if we've swallowed a left shift. 5100 SDValue Result = Load; 5101 if (ShLeftAmt != 0) { 5102 EVT ShImmTy = getShiftAmountTy(Result.getValueType()); 5103 if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt)) 5104 ShImmTy = VT; 5105 Result = DAG.getNode(ISD::SHL, N0.getDebugLoc(), VT, 5106 Result, DAG.getConstant(ShLeftAmt, ShImmTy)); 5107 } 5108 5109 // Return the new loaded value. 5110 return Result; 5111} 5112 5113SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) { 5114 SDValue N0 = N->getOperand(0); 5115 SDValue N1 = N->getOperand(1); 5116 EVT VT = N->getValueType(0); 5117 EVT EVT = cast<VTSDNode>(N1)->getVT(); 5118 unsigned VTBits = VT.getScalarType().getSizeInBits(); 5119 unsigned EVTBits = EVT.getScalarType().getSizeInBits(); 5120 5121 // fold (sext_in_reg c1) -> c1 5122 if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF) 5123 return DAG.getNode(ISD::SIGN_EXTEND_INREG, N->getDebugLoc(), VT, N0, N1); 5124 5125 // If the input is already sign extended, just drop the extension. 5126 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1) 5127 return N0; 5128 5129 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2 5130 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG && 5131 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT())) { 5132 return DAG.getNode(ISD::SIGN_EXTEND_INREG, N->getDebugLoc(), VT, 5133 N0.getOperand(0), N1); 5134 } 5135 5136 // fold (sext_in_reg (sext x)) -> (sext x) 5137 // fold (sext_in_reg (aext x)) -> (sext x) 5138 // if x is small enough. 5139 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) { 5140 SDValue N00 = N0.getOperand(0); 5141 if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits && 5142 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT))) 5143 return DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), VT, N00, N1); 5144 } 5145 5146 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero. 5147 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits))) 5148 return DAG.getZeroExtendInReg(N0, N->getDebugLoc(), EVT); 5149 5150 // fold operands of sext_in_reg based on knowledge that the top bits are not 5151 // demanded. 5152 if (SimplifyDemandedBits(SDValue(N, 0))) 5153 return SDValue(N, 0); 5154 5155 // fold (sext_in_reg (load x)) -> (smaller sextload x) 5156 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits)) 5157 SDValue NarrowLoad = ReduceLoadWidth(N); 5158 if (NarrowLoad.getNode()) 5159 return NarrowLoad; 5160 5161 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24) 5162 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible. 5163 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above. 5164 if (N0.getOpcode() == ISD::SRL) { 5165 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1))) 5166 if (ShAmt->getZExtValue()+EVTBits <= VTBits) { 5167 // We can turn this into an SRA iff the input to the SRL is already sign 5168 // extended enough. 5169 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0)); 5170 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits) 5171 return DAG.getNode(ISD::SRA, N->getDebugLoc(), VT, 5172 N0.getOperand(0), N0.getOperand(1)); 5173 } 5174 } 5175 5176 // fold (sext_inreg (extload x)) -> (sextload x) 5177 if (ISD::isEXTLoad(N0.getNode()) && 5178 ISD::isUNINDEXEDLoad(N0.getNode()) && 5179 EVT == cast<LoadSDNode>(N0)->getMemoryVT() && 5180 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) || 5181 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) { 5182 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 5183 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, N->getDebugLoc(), VT, 5184 LN0->getChain(), 5185 LN0->getBasePtr(), LN0->getPointerInfo(), 5186 EVT, 5187 LN0->isVolatile(), LN0->isNonTemporal(), 5188 LN0->getAlignment()); 5189 CombineTo(N, ExtLoad); 5190 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 5191 return SDValue(N, 0); // Return N so it doesn't get rechecked! 5192 } 5193 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use 5194 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 5195 N0.hasOneUse() && 5196 EVT == cast<LoadSDNode>(N0)->getMemoryVT() && 5197 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) || 5198 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) { 5199 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 5200 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, N->getDebugLoc(), VT, 5201 LN0->getChain(), 5202 LN0->getBasePtr(), LN0->getPointerInfo(), 5203 EVT, 5204 LN0->isVolatile(), LN0->isNonTemporal(), 5205 LN0->getAlignment()); 5206 CombineTo(N, ExtLoad); 5207 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 5208 return SDValue(N, 0); // Return N so it doesn't get rechecked! 5209 } 5210 5211 // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16)) 5212 if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) { 5213 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0), 5214 N0.getOperand(1), false); 5215 if (BSwap.getNode() != 0) 5216 return DAG.getNode(ISD::SIGN_EXTEND_INREG, N->getDebugLoc(), VT, 5217 BSwap, N1); 5218 } 5219 5220 return SDValue(); 5221} 5222 5223SDValue DAGCombiner::visitTRUNCATE(SDNode *N) { 5224 SDValue N0 = N->getOperand(0); 5225 EVT VT = N->getValueType(0); 5226 bool isLE = TLI.isLittleEndian(); 5227 5228 // noop truncate 5229 if (N0.getValueType() == N->getValueType(0)) 5230 return N0; 5231 // fold (truncate c1) -> c1 5232 if (isa<ConstantSDNode>(N0)) 5233 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, N0); 5234 // fold (truncate (truncate x)) -> (truncate x) 5235 if (N0.getOpcode() == ISD::TRUNCATE) 5236 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, N0.getOperand(0)); 5237 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x 5238 if (N0.getOpcode() == ISD::ZERO_EXTEND || 5239 N0.getOpcode() == ISD::SIGN_EXTEND || 5240 N0.getOpcode() == ISD::ANY_EXTEND) { 5241 if (N0.getOperand(0).getValueType().bitsLT(VT)) 5242 // if the source is smaller than the dest, we still need an extend 5243 return DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT, 5244 N0.getOperand(0)); 5245 if (N0.getOperand(0).getValueType().bitsGT(VT)) 5246 // if the source is larger than the dest, than we just need the truncate 5247 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, N0.getOperand(0)); 5248 // if the source and dest are the same type, we can drop both the extend 5249 // and the truncate. 5250 return N0.getOperand(0); 5251 } 5252 5253 // Fold extract-and-trunc into a narrow extract. For example: 5254 // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1) 5255 // i32 y = TRUNCATE(i64 x) 5256 // -- becomes -- 5257 // v16i8 b = BITCAST (v2i64 val) 5258 // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8) 5259 // 5260 // Note: We only run this optimization after type legalization (which often 5261 // creates this pattern) and before operation legalization after which 5262 // we need to be more careful about the vector instructions that we generate. 5263 if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT && 5264 LegalTypes && !LegalOperations && N0->hasOneUse()) { 5265 5266 EVT VecTy = N0.getOperand(0).getValueType(); 5267 EVT ExTy = N0.getValueType(); 5268 EVT TrTy = N->getValueType(0); 5269 5270 unsigned NumElem = VecTy.getVectorNumElements(); 5271 unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits(); 5272 5273 EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem); 5274 assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size"); 5275 5276 SDValue EltNo = N0->getOperand(1); 5277 if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) { 5278 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue(); 5279 EVT IndexTy = N0->getOperand(1).getValueType(); 5280 int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1)); 5281 5282 SDValue V = DAG.getNode(ISD::BITCAST, N->getDebugLoc(), 5283 NVT, N0.getOperand(0)); 5284 5285 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, 5286 N->getDebugLoc(), TrTy, V, 5287 DAG.getConstant(Index, IndexTy)); 5288 } 5289 } 5290 5291 // See if we can simplify the input to this truncate through knowledge that 5292 // only the low bits are being used. 5293 // For example "trunc (or (shl x, 8), y)" // -> trunc y 5294 // Currently we only perform this optimization on scalars because vectors 5295 // may have different active low bits. 5296 if (!VT.isVector()) { 5297 SDValue Shorter = 5298 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(), 5299 VT.getSizeInBits())); 5300 if (Shorter.getNode()) 5301 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, Shorter); 5302 } 5303 // fold (truncate (load x)) -> (smaller load x) 5304 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits)) 5305 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) { 5306 SDValue Reduced = ReduceLoadWidth(N); 5307 if (Reduced.getNode()) 5308 return Reduced; 5309 } 5310 5311 // Simplify the operands using demanded-bits information. 5312 if (!VT.isVector() && 5313 SimplifyDemandedBits(SDValue(N, 0))) 5314 return SDValue(N, 0); 5315 5316 return SDValue(); 5317} 5318 5319static SDNode *getBuildPairElt(SDNode *N, unsigned i) { 5320 SDValue Elt = N->getOperand(i); 5321 if (Elt.getOpcode() != ISD::MERGE_VALUES) 5322 return Elt.getNode(); 5323 return Elt.getOperand(Elt.getResNo()).getNode(); 5324} 5325 5326/// CombineConsecutiveLoads - build_pair (load, load) -> load 5327/// if load locations are consecutive. 5328SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) { 5329 assert(N->getOpcode() == ISD::BUILD_PAIR); 5330 5331 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0)); 5332 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1)); 5333 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() || 5334 LD1->getPointerInfo().getAddrSpace() != 5335 LD2->getPointerInfo().getAddrSpace()) 5336 return SDValue(); 5337 EVT LD1VT = LD1->getValueType(0); 5338 5339 if (ISD::isNON_EXTLoad(LD2) && 5340 LD2->hasOneUse() && 5341 // If both are volatile this would reduce the number of volatile loads. 5342 // If one is volatile it might be ok, but play conservative and bail out. 5343 !LD1->isVolatile() && 5344 !LD2->isVolatile() && 5345 DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) { 5346 unsigned Align = LD1->getAlignment(); 5347 unsigned NewAlign = TLI.getTargetData()-> 5348 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext())); 5349 5350 if (NewAlign <= Align && 5351 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT))) 5352 return DAG.getLoad(VT, N->getDebugLoc(), LD1->getChain(), 5353 LD1->getBasePtr(), LD1->getPointerInfo(), 5354 false, false, false, Align); 5355 } 5356 5357 return SDValue(); 5358} 5359 5360SDValue DAGCombiner::visitBITCAST(SDNode *N) { 5361 SDValue N0 = N->getOperand(0); 5362 EVT VT = N->getValueType(0); 5363 5364 // If the input is a BUILD_VECTOR with all constant elements, fold this now. 5365 // Only do this before legalize, since afterward the target may be depending 5366 // on the bitconvert. 5367 // First check to see if this is all constant. 5368 if (!LegalTypes && 5369 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() && 5370 VT.isVector()) { 5371 bool isSimple = true; 5372 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) 5373 if (N0.getOperand(i).getOpcode() != ISD::UNDEF && 5374 N0.getOperand(i).getOpcode() != ISD::Constant && 5375 N0.getOperand(i).getOpcode() != ISD::ConstantFP) { 5376 isSimple = false; 5377 break; 5378 } 5379 5380 EVT DestEltVT = N->getValueType(0).getVectorElementType(); 5381 assert(!DestEltVT.isVector() && 5382 "Element type of vector ValueType must not be vector!"); 5383 if (isSimple) 5384 return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT); 5385 } 5386 5387 // If the input is a constant, let getNode fold it. 5388 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) { 5389 SDValue Res = DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, N0); 5390 if (Res.getNode() != N) { 5391 if (!LegalOperations || 5392 TLI.isOperationLegal(Res.getNode()->getOpcode(), VT)) 5393 return Res; 5394 5395 // Folding it resulted in an illegal node, and it's too late to 5396 // do that. Clean up the old node and forego the transformation. 5397 // Ideally this won't happen very often, because instcombine 5398 // and the earlier dagcombine runs (where illegal nodes are 5399 // permitted) should have folded most of them already. 5400 DAG.DeleteNode(Res.getNode()); 5401 } 5402 } 5403 5404 // (conv (conv x, t1), t2) -> (conv x, t2) 5405 if (N0.getOpcode() == ISD::BITCAST) 5406 return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, 5407 N0.getOperand(0)); 5408 5409 // fold (conv (load x)) -> (load (conv*)x) 5410 // If the resultant load doesn't need a higher alignment than the original! 5411 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() && 5412 // Do not change the width of a volatile load. 5413 !cast<LoadSDNode>(N0)->isVolatile() && 5414 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT))) { 5415 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 5416 unsigned Align = TLI.getTargetData()-> 5417 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext())); 5418 unsigned OrigAlign = LN0->getAlignment(); 5419 5420 if (Align <= OrigAlign) { 5421 SDValue Load = DAG.getLoad(VT, N->getDebugLoc(), LN0->getChain(), 5422 LN0->getBasePtr(), LN0->getPointerInfo(), 5423 LN0->isVolatile(), LN0->isNonTemporal(), 5424 LN0->isInvariant(), OrigAlign); 5425 AddToWorkList(N); 5426 CombineTo(N0.getNode(), 5427 DAG.getNode(ISD::BITCAST, N0.getDebugLoc(), 5428 N0.getValueType(), Load), 5429 Load.getValue(1)); 5430 return Load; 5431 } 5432 } 5433 5434 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit) 5435 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit)) 5436 // This often reduces constant pool loads. 5437 if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(VT)) || 5438 (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(VT))) && 5439 N0.getNode()->hasOneUse() && VT.isInteger() && 5440 !VT.isVector() && !N0.getValueType().isVector()) { 5441 SDValue NewConv = DAG.getNode(ISD::BITCAST, N0.getDebugLoc(), VT, 5442 N0.getOperand(0)); 5443 AddToWorkList(NewConv.getNode()); 5444 5445 APInt SignBit = APInt::getSignBit(VT.getSizeInBits()); 5446 if (N0.getOpcode() == ISD::FNEG) 5447 return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT, 5448 NewConv, DAG.getConstant(SignBit, VT)); 5449 assert(N0.getOpcode() == ISD::FABS); 5450 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, 5451 NewConv, DAG.getConstant(~SignBit, VT)); 5452 } 5453 5454 // fold (bitconvert (fcopysign cst, x)) -> 5455 // (or (and (bitconvert x), sign), (and cst, (not sign))) 5456 // Note that we don't handle (copysign x, cst) because this can always be 5457 // folded to an fneg or fabs. 5458 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() && 5459 isa<ConstantFPSDNode>(N0.getOperand(0)) && 5460 VT.isInteger() && !VT.isVector()) { 5461 unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits(); 5462 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth); 5463 if (isTypeLegal(IntXVT)) { 5464 SDValue X = DAG.getNode(ISD::BITCAST, N0.getDebugLoc(), 5465 IntXVT, N0.getOperand(1)); 5466 AddToWorkList(X.getNode()); 5467 5468 // If X has a different width than the result/lhs, sext it or truncate it. 5469 unsigned VTWidth = VT.getSizeInBits(); 5470 if (OrigXWidth < VTWidth) { 5471 X = DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), VT, X); 5472 AddToWorkList(X.getNode()); 5473 } else if (OrigXWidth > VTWidth) { 5474 // To get the sign bit in the right place, we have to shift it right 5475 // before truncating. 5476 X = DAG.getNode(ISD::SRL, X.getDebugLoc(), 5477 X.getValueType(), X, 5478 DAG.getConstant(OrigXWidth-VTWidth, X.getValueType())); 5479 AddToWorkList(X.getNode()); 5480 X = DAG.getNode(ISD::TRUNCATE, X.getDebugLoc(), VT, X); 5481 AddToWorkList(X.getNode()); 5482 } 5483 5484 APInt SignBit = APInt::getSignBit(VT.getSizeInBits()); 5485 X = DAG.getNode(ISD::AND, X.getDebugLoc(), VT, 5486 X, DAG.getConstant(SignBit, VT)); 5487 AddToWorkList(X.getNode()); 5488 5489 SDValue Cst = DAG.getNode(ISD::BITCAST, N0.getDebugLoc(), 5490 VT, N0.getOperand(0)); 5491 Cst = DAG.getNode(ISD::AND, Cst.getDebugLoc(), VT, 5492 Cst, DAG.getConstant(~SignBit, VT)); 5493 AddToWorkList(Cst.getNode()); 5494 5495 return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, X, Cst); 5496 } 5497 } 5498 5499 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive. 5500 if (N0.getOpcode() == ISD::BUILD_PAIR) { 5501 SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT); 5502 if (CombineLD.getNode()) 5503 return CombineLD; 5504 } 5505 5506 return SDValue(); 5507} 5508 5509SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) { 5510 EVT VT = N->getValueType(0); 5511 return CombineConsecutiveLoads(N, VT); 5512} 5513 5514/// ConstantFoldBITCASTofBUILD_VECTOR - We know that BV is a build_vector 5515/// node with Constant, ConstantFP or Undef operands. DstEltVT indicates the 5516/// destination element value type. 5517SDValue DAGCombiner:: 5518ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) { 5519 EVT SrcEltVT = BV->getValueType(0).getVectorElementType(); 5520 5521 // If this is already the right type, we're done. 5522 if (SrcEltVT == DstEltVT) return SDValue(BV, 0); 5523 5524 unsigned SrcBitSize = SrcEltVT.getSizeInBits(); 5525 unsigned DstBitSize = DstEltVT.getSizeInBits(); 5526 5527 // If this is a conversion of N elements of one type to N elements of another 5528 // type, convert each element. This handles FP<->INT cases. 5529 if (SrcBitSize == DstBitSize) { 5530 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, 5531 BV->getValueType(0).getVectorNumElements()); 5532 5533 // Due to the FP element handling below calling this routine recursively, 5534 // we can end up with a scalar-to-vector node here. 5535 if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR) 5536 return DAG.getNode(ISD::SCALAR_TO_VECTOR, BV->getDebugLoc(), VT, 5537 DAG.getNode(ISD::BITCAST, BV->getDebugLoc(), 5538 DstEltVT, BV->getOperand(0))); 5539 5540 SmallVector<SDValue, 8> Ops; 5541 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) { 5542 SDValue Op = BV->getOperand(i); 5543 // If the vector element type is not legal, the BUILD_VECTOR operands 5544 // are promoted and implicitly truncated. Make that explicit here. 5545 if (Op.getValueType() != SrcEltVT) 5546 Op = DAG.getNode(ISD::TRUNCATE, BV->getDebugLoc(), SrcEltVT, Op); 5547 Ops.push_back(DAG.getNode(ISD::BITCAST, BV->getDebugLoc(), 5548 DstEltVT, Op)); 5549 AddToWorkList(Ops.back().getNode()); 5550 } 5551 return DAG.getNode(ISD::BUILD_VECTOR, BV->getDebugLoc(), VT, 5552 &Ops[0], Ops.size()); 5553 } 5554 5555 // Otherwise, we're growing or shrinking the elements. To avoid having to 5556 // handle annoying details of growing/shrinking FP values, we convert them to 5557 // int first. 5558 if (SrcEltVT.isFloatingPoint()) { 5559 // Convert the input float vector to a int vector where the elements are the 5560 // same sizes. 5561 assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!"); 5562 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits()); 5563 BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode(); 5564 SrcEltVT = IntVT; 5565 } 5566 5567 // Now we know the input is an integer vector. If the output is a FP type, 5568 // convert to integer first, then to FP of the right size. 5569 if (DstEltVT.isFloatingPoint()) { 5570 assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!"); 5571 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits()); 5572 SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode(); 5573 5574 // Next, convert to FP elements of the same size. 5575 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT); 5576 } 5577 5578 // Okay, we know the src/dst types are both integers of differing types. 5579 // Handling growing first. 5580 assert(SrcEltVT.isInteger() && DstEltVT.isInteger()); 5581 if (SrcBitSize < DstBitSize) { 5582 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize; 5583 5584 SmallVector<SDValue, 8> Ops; 5585 for (unsigned i = 0, e = BV->getNumOperands(); i != e; 5586 i += NumInputsPerOutput) { 5587 bool isLE = TLI.isLittleEndian(); 5588 APInt NewBits = APInt(DstBitSize, 0); 5589 bool EltIsUndef = true; 5590 for (unsigned j = 0; j != NumInputsPerOutput; ++j) { 5591 // Shift the previously computed bits over. 5592 NewBits <<= SrcBitSize; 5593 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j)); 5594 if (Op.getOpcode() == ISD::UNDEF) continue; 5595 EltIsUndef = false; 5596 5597 NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue(). 5598 zextOrTrunc(SrcBitSize).zext(DstBitSize); 5599 } 5600 5601 if (EltIsUndef) 5602 Ops.push_back(DAG.getUNDEF(DstEltVT)); 5603 else 5604 Ops.push_back(DAG.getConstant(NewBits, DstEltVT)); 5605 } 5606 5607 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size()); 5608 return DAG.getNode(ISD::BUILD_VECTOR, BV->getDebugLoc(), VT, 5609 &Ops[0], Ops.size()); 5610 } 5611 5612 // Finally, this must be the case where we are shrinking elements: each input 5613 // turns into multiple outputs. 5614 bool isS2V = ISD::isScalarToVector(BV); 5615 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize; 5616 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, 5617 NumOutputsPerInput*BV->getNumOperands()); 5618 SmallVector<SDValue, 8> Ops; 5619 5620 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) { 5621 if (BV->getOperand(i).getOpcode() == ISD::UNDEF) { 5622 for (unsigned j = 0; j != NumOutputsPerInput; ++j) 5623 Ops.push_back(DAG.getUNDEF(DstEltVT)); 5624 continue; 5625 } 5626 5627 APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))-> 5628 getAPIntValue().zextOrTrunc(SrcBitSize); 5629 5630 for (unsigned j = 0; j != NumOutputsPerInput; ++j) { 5631 APInt ThisVal = OpVal.trunc(DstBitSize); 5632 Ops.push_back(DAG.getConstant(ThisVal, DstEltVT)); 5633 if (isS2V && i == 0 && j == 0 && ThisVal.zext(SrcBitSize) == OpVal) 5634 // Simply turn this into a SCALAR_TO_VECTOR of the new type. 5635 return DAG.getNode(ISD::SCALAR_TO_VECTOR, BV->getDebugLoc(), VT, 5636 Ops[0]); 5637 OpVal = OpVal.lshr(DstBitSize); 5638 } 5639 5640 // For big endian targets, swap the order of the pieces of each element. 5641 if (TLI.isBigEndian()) 5642 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end()); 5643 } 5644 5645 return DAG.getNode(ISD::BUILD_VECTOR, BV->getDebugLoc(), VT, 5646 &Ops[0], Ops.size()); 5647} 5648 5649SDValue DAGCombiner::visitFADD(SDNode *N) { 5650 SDValue N0 = N->getOperand(0); 5651 SDValue N1 = N->getOperand(1); 5652 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 5653 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 5654 EVT VT = N->getValueType(0); 5655 5656 // fold vector ops 5657 if (VT.isVector()) { 5658 SDValue FoldedVOp = SimplifyVBinOp(N); 5659 if (FoldedVOp.getNode()) return FoldedVOp; 5660 } 5661 5662 // fold (fadd c1, c2) -> c1 + c2 5663 if (N0CFP && N1CFP && VT != MVT::ppcf128) 5664 return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N0, N1); 5665 // canonicalize constant to RHS 5666 if (N0CFP && !N1CFP) 5667 return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N1, N0); 5668 // fold (fadd A, 0) -> A 5669 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP && 5670 N1CFP->getValueAPF().isZero()) 5671 return N0; 5672 // fold (fadd A, (fneg B)) -> (fsub A, B) 5673 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) && 5674 isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options) == 2) 5675 return DAG.getNode(ISD::FSUB, N->getDebugLoc(), VT, N0, 5676 GetNegatedExpression(N1, DAG, LegalOperations)); 5677 // fold (fadd (fneg A), B) -> (fsub B, A) 5678 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) && 5679 isNegatibleForFree(N0, LegalOperations, TLI, &DAG.getTarget().Options) == 2) 5680 return DAG.getNode(ISD::FSUB, N->getDebugLoc(), VT, N1, 5681 GetNegatedExpression(N0, DAG, LegalOperations)); 5682 5683 // If allowed, fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2)) 5684 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP && 5685 N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() && 5686 isa<ConstantFPSDNode>(N0.getOperand(1))) 5687 return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N0.getOperand(0), 5688 DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, 5689 N0.getOperand(1), N1)); 5690 5691 // In unsafe math mode, we can fold chains of FADD's of the same value 5692 // into multiplications. This transform is not safe in general because 5693 // we are reducing the number of rounding steps. 5694 if (DAG.getTarget().Options.UnsafeFPMath && 5695 TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && 5696 !N0CFP && !N1CFP) { 5697 if (N0.getOpcode() == ISD::FMUL) { 5698 ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0)); 5699 ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1)); 5700 5701 // (fadd (fmul c, x), x) -> (fmul c+1, x) 5702 if (CFP00 && !CFP01 && N0.getOperand(1) == N1) { 5703 SDValue NewCFP = DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, 5704 SDValue(CFP00, 0), 5705 DAG.getConstantFP(1.0, VT)); 5706 return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT, 5707 N1, NewCFP); 5708 } 5709 5710 // (fadd (fmul x, c), x) -> (fmul c+1, x) 5711 if (CFP01 && !CFP00 && N0.getOperand(0) == N1) { 5712 SDValue NewCFP = DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, 5713 SDValue(CFP01, 0), 5714 DAG.getConstantFP(1.0, VT)); 5715 return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT, 5716 N1, NewCFP); 5717 } 5718 5719 // (fadd (fadd x, x), x) -> (fmul 3.0, x) 5720 if (!CFP00 && !CFP01 && N0.getOperand(0) == N0.getOperand(1) && 5721 N0.getOperand(0) == N1) { 5722 return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT, 5723 N1, DAG.getConstantFP(3.0, VT)); 5724 } 5725 5726 // (fadd (fmul c, x), (fadd x, x)) -> (fmul c+2, x) 5727 if (CFP00 && !CFP01 && N1.getOpcode() == ISD::FADD && 5728 N1.getOperand(0) == N1.getOperand(1) && 5729 N0.getOperand(1) == N1.getOperand(0)) { 5730 SDValue NewCFP = DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, 5731 SDValue(CFP00, 0), 5732 DAG.getConstantFP(2.0, VT)); 5733 return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT, 5734 N0.getOperand(1), NewCFP); 5735 } 5736 5737 // (fadd (fmul x, c), (fadd x, x)) -> (fmul c+2, x) 5738 if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD && 5739 N1.getOperand(0) == N1.getOperand(1) && 5740 N0.getOperand(0) == N1.getOperand(0)) { 5741 SDValue NewCFP = DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, 5742 SDValue(CFP01, 0), 5743 DAG.getConstantFP(2.0, VT)); 5744 return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT, 5745 N0.getOperand(0), NewCFP); 5746 } 5747 } 5748 5749 if (N1.getOpcode() == ISD::FMUL) { 5750 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0)); 5751 ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1)); 5752 5753 // (fadd x, (fmul c, x)) -> (fmul c+1, x) 5754 if (CFP10 && !CFP11 && N1.getOperand(1) == N0) { 5755 SDValue NewCFP = DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, 5756 SDValue(CFP10, 0), 5757 DAG.getConstantFP(1.0, VT)); 5758 return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT, 5759 N0, NewCFP); 5760 } 5761 5762 // (fadd x, (fmul x, c)) -> (fmul c+1, x) 5763 if (CFP11 && !CFP10 && N1.getOperand(0) == N0) { 5764 SDValue NewCFP = DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, 5765 SDValue(CFP11, 0), 5766 DAG.getConstantFP(1.0, VT)); 5767 return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT, 5768 N0, NewCFP); 5769 } 5770 5771 // (fadd x, (fadd x, x)) -> (fmul 3.0, x) 5772 if (!CFP10 && !CFP11 && N1.getOperand(0) == N1.getOperand(1) && 5773 N1.getOperand(0) == N0) { 5774 return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT, 5775 N0, DAG.getConstantFP(3.0, VT)); 5776 } 5777 5778 // (fadd (fadd x, x), (fmul c, x)) -> (fmul c+2, x) 5779 if (CFP10 && !CFP11 && N1.getOpcode() == ISD::FADD && 5780 N1.getOperand(0) == N1.getOperand(1) && 5781 N0.getOperand(1) == N1.getOperand(0)) { 5782 SDValue NewCFP = DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, 5783 SDValue(CFP10, 0), 5784 DAG.getConstantFP(2.0, VT)); 5785 return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT, 5786 N0.getOperand(1), NewCFP); 5787 } 5788 5789 // (fadd (fadd x, x), (fmul x, c)) -> (fmul c+2, x) 5790 if (CFP11 && !CFP10 && N1.getOpcode() == ISD::FADD && 5791 N1.getOperand(0) == N1.getOperand(1) && 5792 N0.getOperand(0) == N1.getOperand(0)) { 5793 SDValue NewCFP = DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, 5794 SDValue(CFP11, 0), 5795 DAG.getConstantFP(2.0, VT)); 5796 return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT, 5797 N0.getOperand(0), NewCFP); 5798 } 5799 } 5800 5801 // (fadd (fadd x, x), (fadd x, x)) -> (fmul 4.0, x) 5802 if (N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD && 5803 N0.getOperand(0) == N0.getOperand(1) && 5804 N1.getOperand(0) == N1.getOperand(1) && 5805 N0.getOperand(0) == N1.getOperand(0)) { 5806 return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT, 5807 N0.getOperand(0), 5808 DAG.getConstantFP(4.0, VT)); 5809 } 5810 } 5811 5812 // FADD -> FMA combines: 5813 if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast || 5814 DAG.getTarget().Options.UnsafeFPMath) && 5815 DAG.getTarget().getTargetLowering()->isFMAFasterThanMulAndAdd(VT) && 5816 TLI.isOperationLegalOrCustom(ISD::FMA, VT)) { 5817 5818 // fold (fadd (fmul x, y), z) -> (fma x, y, z) 5819 if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse()) { 5820 return DAG.getNode(ISD::FMA, N->getDebugLoc(), VT, 5821 N0.getOperand(0), N0.getOperand(1), N1); 5822 } 5823 5824 // fold (fadd x, (fmul y, z)) -> (fma y, z, x) 5825 // Note: Commutes FADD operands. 5826 if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse()) { 5827 return DAG.getNode(ISD::FMA, N->getDebugLoc(), VT, 5828 N1.getOperand(0), N1.getOperand(1), N0); 5829 } 5830 } 5831 5832 return SDValue(); 5833} 5834 5835SDValue DAGCombiner::visitFSUB(SDNode *N) { 5836 SDValue N0 = N->getOperand(0); 5837 SDValue N1 = N->getOperand(1); 5838 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 5839 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 5840 EVT VT = N->getValueType(0); 5841 DebugLoc dl = N->getDebugLoc(); 5842 5843 // fold vector ops 5844 if (VT.isVector()) { 5845 SDValue FoldedVOp = SimplifyVBinOp(N); 5846 if (FoldedVOp.getNode()) return FoldedVOp; 5847 } 5848 5849 // fold (fsub c1, c2) -> c1-c2 5850 if (N0CFP && N1CFP && VT != MVT::ppcf128) 5851 return DAG.getNode(ISD::FSUB, N->getDebugLoc(), VT, N0, N1); 5852 // fold (fsub A, 0) -> A 5853 if (DAG.getTarget().Options.UnsafeFPMath && 5854 N1CFP && N1CFP->getValueAPF().isZero()) 5855 return N0; 5856 // fold (fsub 0, B) -> -B 5857 if (DAG.getTarget().Options.UnsafeFPMath && 5858 N0CFP && N0CFP->getValueAPF().isZero()) { 5859 if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options)) 5860 return GetNegatedExpression(N1, DAG, LegalOperations); 5861 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT)) 5862 return DAG.getNode(ISD::FNEG, dl, VT, N1); 5863 } 5864 // fold (fsub A, (fneg B)) -> (fadd A, B) 5865 if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options)) 5866 return DAG.getNode(ISD::FADD, dl, VT, N0, 5867 GetNegatedExpression(N1, DAG, LegalOperations)); 5868 5869 // If 'unsafe math' is enabled, fold 5870 // (fsub x, x) -> 0.0 & 5871 // (fsub x, (fadd x, y)) -> (fneg y) & 5872 // (fsub x, (fadd y, x)) -> (fneg y) 5873 if (DAG.getTarget().Options.UnsafeFPMath) { 5874 if (N0 == N1) 5875 return DAG.getConstantFP(0.0f, VT); 5876 5877 if (N1.getOpcode() == ISD::FADD) { 5878 SDValue N10 = N1->getOperand(0); 5879 SDValue N11 = N1->getOperand(1); 5880 5881 if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, 5882 &DAG.getTarget().Options)) 5883 return GetNegatedExpression(N11, DAG, LegalOperations); 5884 else if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, 5885 &DAG.getTarget().Options)) 5886 return GetNegatedExpression(N10, DAG, LegalOperations); 5887 } 5888 } 5889 5890 // FSUB -> FMA combines: 5891 if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast || 5892 DAG.getTarget().Options.UnsafeFPMath) && 5893 DAG.getTarget().getTargetLowering()->isFMAFasterThanMulAndAdd(VT) && 5894 TLI.isOperationLegalOrCustom(ISD::FMA, VT)) { 5895 5896 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z)) 5897 if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse()) { 5898 return DAG.getNode(ISD::FMA, dl, VT, 5899 N0.getOperand(0), N0.getOperand(1), 5900 DAG.getNode(ISD::FNEG, dl, VT, N1)); 5901 } 5902 5903 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x) 5904 // Note: Commutes FSUB operands. 5905 if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse()) { 5906 return DAG.getNode(ISD::FMA, dl, VT, 5907 DAG.getNode(ISD::FNEG, dl, VT, 5908 N1.getOperand(0)), 5909 N1.getOperand(1), N0); 5910 } 5911 5912 // fold (fsub (-(fmul, x, y)), z) -> (fma (fneg x), y, (fneg z)) 5913 if (N0.getOpcode() == ISD::FNEG && 5914 N0.getOperand(0).getOpcode() == ISD::FMUL && 5915 N0->hasOneUse() && N0.getOperand(0).hasOneUse()) { 5916 SDValue N00 = N0.getOperand(0).getOperand(0); 5917 SDValue N01 = N0.getOperand(0).getOperand(1); 5918 return DAG.getNode(ISD::FMA, dl, VT, 5919 DAG.getNode(ISD::FNEG, dl, VT, N00), N01, 5920 DAG.getNode(ISD::FNEG, dl, VT, N1)); 5921 } 5922 } 5923 5924 return SDValue(); 5925} 5926 5927SDValue DAGCombiner::visitFMUL(SDNode *N) { 5928 SDValue N0 = N->getOperand(0); 5929 SDValue N1 = N->getOperand(1); 5930 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 5931 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 5932 EVT VT = N->getValueType(0); 5933 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5934 5935 // fold vector ops 5936 if (VT.isVector()) { 5937 SDValue FoldedVOp = SimplifyVBinOp(N); 5938 if (FoldedVOp.getNode()) return FoldedVOp; 5939 } 5940 5941 // fold (fmul c1, c2) -> c1*c2 5942 if (N0CFP && N1CFP && VT != MVT::ppcf128) 5943 return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT, N0, N1); 5944 // canonicalize constant to RHS 5945 if (N0CFP && !N1CFP) 5946 return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT, N1, N0); 5947 // fold (fmul A, 0) -> 0 5948 if (DAG.getTarget().Options.UnsafeFPMath && 5949 N1CFP && N1CFP->getValueAPF().isZero()) 5950 return N1; 5951 // fold (fmul A, 0) -> 0, vector edition. 5952 if (DAG.getTarget().Options.UnsafeFPMath && 5953 ISD::isBuildVectorAllZeros(N1.getNode())) 5954 return N1; 5955 // fold (fmul A, 1.0) -> A 5956 if (N1CFP && N1CFP->isExactlyValue(1.0)) 5957 return N0; 5958 // fold (fmul X, 2.0) -> (fadd X, X) 5959 if (N1CFP && N1CFP->isExactlyValue(+2.0)) 5960 return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N0, N0); 5961 // fold (fmul X, -1.0) -> (fneg X) 5962 if (N1CFP && N1CFP->isExactlyValue(-1.0)) 5963 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT)) 5964 return DAG.getNode(ISD::FNEG, N->getDebugLoc(), VT, N0); 5965 5966 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y) 5967 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, 5968 &DAG.getTarget().Options)) { 5969 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, 5970 &DAG.getTarget().Options)) { 5971 // Both can be negated for free, check to see if at least one is cheaper 5972 // negated. 5973 if (LHSNeg == 2 || RHSNeg == 2) 5974 return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT, 5975 GetNegatedExpression(N0, DAG, LegalOperations), 5976 GetNegatedExpression(N1, DAG, LegalOperations)); 5977 } 5978 } 5979 5980 // If allowed, fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2)) 5981 if (DAG.getTarget().Options.UnsafeFPMath && 5982 N1CFP && N0.getOpcode() == ISD::FMUL && 5983 N0.getNode()->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1))) 5984 return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT, N0.getOperand(0), 5985 DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT, 5986 N0.getOperand(1), N1)); 5987 5988 return SDValue(); 5989} 5990 5991SDValue DAGCombiner::visitFMA(SDNode *N) { 5992 SDValue N0 = N->getOperand(0); 5993 SDValue N1 = N->getOperand(1); 5994 SDValue N2 = N->getOperand(2); 5995 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 5996 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 5997 EVT VT = N->getValueType(0); 5998 DebugLoc dl = N->getDebugLoc(); 5999 6000 if (N0CFP && N0CFP->isExactlyValue(1.0)) 6001 return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N1, N2); 6002 if (N1CFP && N1CFP->isExactlyValue(1.0)) 6003 return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N0, N2); 6004 6005 // Canonicalize (fma c, x, y) -> (fma x, c, y) 6006 if (N0CFP && !N1CFP) 6007 return DAG.getNode(ISD::FMA, N->getDebugLoc(), VT, N1, N0, N2); 6008 6009 // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2) 6010 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP && 6011 N2.getOpcode() == ISD::FMUL && 6012 N0 == N2.getOperand(0) && 6013 N2.getOperand(1).getOpcode() == ISD::ConstantFP) { 6014 return DAG.getNode(ISD::FMUL, dl, VT, N0, 6015 DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1))); 6016 } 6017 6018 6019 // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y) 6020 if (DAG.getTarget().Options.UnsafeFPMath && 6021 N0.getOpcode() == ISD::FMUL && N1CFP && 6022 N0.getOperand(1).getOpcode() == ISD::ConstantFP) { 6023 return DAG.getNode(ISD::FMA, dl, VT, 6024 N0.getOperand(0), 6025 DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)), 6026 N2); 6027 } 6028 6029 // (fma x, 1, y) -> (fadd x, y) 6030 // (fma x, -1, y) -> (fadd (fneg x), y) 6031 if (N1CFP) { 6032 if (N1CFP->isExactlyValue(1.0)) 6033 return DAG.getNode(ISD::FADD, dl, VT, N0, N2); 6034 6035 if (N1CFP->isExactlyValue(-1.0) && 6036 (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) { 6037 SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0); 6038 AddToWorkList(RHSNeg.getNode()); 6039 return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg); 6040 } 6041 } 6042 6043 // (fma x, c, x) -> (fmul x, (c+1)) 6044 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP && N0 == N2) { 6045 return DAG.getNode(ISD::FMUL, dl, VT, 6046 N0, 6047 DAG.getNode(ISD::FADD, dl, VT, 6048 N1, DAG.getConstantFP(1.0, VT))); 6049 } 6050 6051 // (fma x, c, (fneg x)) -> (fmul x, (c-1)) 6052 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP && 6053 N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0) { 6054 return DAG.getNode(ISD::FMUL, dl, VT, 6055 N0, 6056 DAG.getNode(ISD::FADD, dl, VT, 6057 N1, DAG.getConstantFP(-1.0, VT))); 6058 } 6059 6060 6061 return SDValue(); 6062} 6063 6064SDValue DAGCombiner::visitFDIV(SDNode *N) { 6065 SDValue N0 = N->getOperand(0); 6066 SDValue N1 = N->getOperand(1); 6067 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 6068 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 6069 EVT VT = N->getValueType(0); 6070 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6071 6072 // fold vector ops 6073 if (VT.isVector()) { 6074 SDValue FoldedVOp = SimplifyVBinOp(N); 6075 if (FoldedVOp.getNode()) return FoldedVOp; 6076 } 6077 6078 // fold (fdiv c1, c2) -> c1/c2 6079 if (N0CFP && N1CFP && VT != MVT::ppcf128) 6080 return DAG.getNode(ISD::FDIV, N->getDebugLoc(), VT, N0, N1); 6081 6082 // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable. 6083 if (N1CFP && VT != MVT::ppcf128 && DAG.getTarget().Options.UnsafeFPMath) { 6084 // Compute the reciprocal 1.0 / c2. 6085 APFloat N1APF = N1CFP->getValueAPF(); 6086 APFloat Recip(N1APF.getSemantics(), 1); // 1.0 6087 APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven); 6088 // Only do the transform if the reciprocal is a legal fp immediate that 6089 // isn't too nasty (eg NaN, denormal, ...). 6090 if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty 6091 (!LegalOperations || 6092 // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM 6093 // backend)... we should handle this gracefully after Legalize. 6094 // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) || 6095 TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) || 6096 TLI.isFPImmLegal(Recip, VT))) 6097 return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT, N0, 6098 DAG.getConstantFP(Recip, VT)); 6099 } 6100 6101 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y) 6102 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, 6103 &DAG.getTarget().Options)) { 6104 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, 6105 &DAG.getTarget().Options)) { 6106 // Both can be negated for free, check to see if at least one is cheaper 6107 // negated. 6108 if (LHSNeg == 2 || RHSNeg == 2) 6109 return DAG.getNode(ISD::FDIV, N->getDebugLoc(), VT, 6110 GetNegatedExpression(N0, DAG, LegalOperations), 6111 GetNegatedExpression(N1, DAG, LegalOperations)); 6112 } 6113 } 6114 6115 return SDValue(); 6116} 6117 6118SDValue DAGCombiner::visitFREM(SDNode *N) { 6119 SDValue N0 = N->getOperand(0); 6120 SDValue N1 = N->getOperand(1); 6121 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 6122 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 6123 EVT VT = N->getValueType(0); 6124 6125 // fold (frem c1, c2) -> fmod(c1,c2) 6126 if (N0CFP && N1CFP && VT != MVT::ppcf128) 6127 return DAG.getNode(ISD::FREM, N->getDebugLoc(), VT, N0, N1); 6128 6129 return SDValue(); 6130} 6131 6132SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) { 6133 SDValue N0 = N->getOperand(0); 6134 SDValue N1 = N->getOperand(1); 6135 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 6136 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 6137 EVT VT = N->getValueType(0); 6138 6139 if (N0CFP && N1CFP && VT != MVT::ppcf128) // Constant fold 6140 return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT, N0, N1); 6141 6142 if (N1CFP) { 6143 const APFloat& V = N1CFP->getValueAPF(); 6144 // copysign(x, c1) -> fabs(x) iff ispos(c1) 6145 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1) 6146 if (!V.isNegative()) { 6147 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT)) 6148 return DAG.getNode(ISD::FABS, N->getDebugLoc(), VT, N0); 6149 } else { 6150 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT)) 6151 return DAG.getNode(ISD::FNEG, N->getDebugLoc(), VT, 6152 DAG.getNode(ISD::FABS, N0.getDebugLoc(), VT, N0)); 6153 } 6154 } 6155 6156 // copysign(fabs(x), y) -> copysign(x, y) 6157 // copysign(fneg(x), y) -> copysign(x, y) 6158 // copysign(copysign(x,z), y) -> copysign(x, y) 6159 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG || 6160 N0.getOpcode() == ISD::FCOPYSIGN) 6161 return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT, 6162 N0.getOperand(0), N1); 6163 6164 // copysign(x, abs(y)) -> abs(x) 6165 if (N1.getOpcode() == ISD::FABS) 6166 return DAG.getNode(ISD::FABS, N->getDebugLoc(), VT, N0); 6167 6168 // copysign(x, copysign(y,z)) -> copysign(x, z) 6169 if (N1.getOpcode() == ISD::FCOPYSIGN) 6170 return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT, 6171 N0, N1.getOperand(1)); 6172 6173 // copysign(x, fp_extend(y)) -> copysign(x, y) 6174 // copysign(x, fp_round(y)) -> copysign(x, y) 6175 if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND) 6176 return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT, 6177 N0, N1.getOperand(0)); 6178 6179 return SDValue(); 6180} 6181 6182SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) { 6183 SDValue N0 = N->getOperand(0); 6184 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 6185 EVT VT = N->getValueType(0); 6186 EVT OpVT = N0.getValueType(); 6187 6188 // fold (sint_to_fp c1) -> c1fp 6189 if (N0C && OpVT != MVT::ppcf128 && 6190 // ...but only if the target supports immediate floating-point values 6191 (!LegalOperations || 6192 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) 6193 return DAG.getNode(ISD::SINT_TO_FP, N->getDebugLoc(), VT, N0); 6194 6195 // If the input is a legal type, and SINT_TO_FP is not legal on this target, 6196 // but UINT_TO_FP is legal on this target, try to convert. 6197 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) && 6198 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) { 6199 // If the sign bit is known to be zero, we can change this to UINT_TO_FP. 6200 if (DAG.SignBitIsZero(N0)) 6201 return DAG.getNode(ISD::UINT_TO_FP, N->getDebugLoc(), VT, N0); 6202 } 6203 6204 // The next optimizations are desireable only if SELECT_CC can be lowered. 6205 // Check against MVT::Other for SELECT_CC, which is a workaround for targets 6206 // having to say they don't support SELECT_CC on every type the DAG knows 6207 // about, since there is no way to mark an opcode illegal at all value types 6208 // (See also visitSELECT) 6209 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other)) { 6210 // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc) 6211 if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 && 6212 !VT.isVector() && 6213 (!LegalOperations || 6214 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) { 6215 SDValue Ops[] = 6216 { N0.getOperand(0), N0.getOperand(1), 6217 DAG.getConstantFP(-1.0, VT) , DAG.getConstantFP(0.0, VT), 6218 N0.getOperand(2) }; 6219 return DAG.getNode(ISD::SELECT_CC, N->getDebugLoc(), VT, Ops, 5); 6220 } 6221 6222 // fold (sint_to_fp (zext (setcc x, y, cc))) -> 6223 // (select_cc x, y, 1.0, 0.0,, cc) 6224 if (N0.getOpcode() == ISD::ZERO_EXTEND && 6225 N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() && 6226 (!LegalOperations || 6227 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) { 6228 SDValue Ops[] = 6229 { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1), 6230 DAG.getConstantFP(1.0, VT) , DAG.getConstantFP(0.0, VT), 6231 N0.getOperand(0).getOperand(2) }; 6232 return DAG.getNode(ISD::SELECT_CC, N->getDebugLoc(), VT, Ops, 5); 6233 } 6234 } 6235 6236 return SDValue(); 6237} 6238 6239SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) { 6240 SDValue N0 = N->getOperand(0); 6241 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 6242 EVT VT = N->getValueType(0); 6243 EVT OpVT = N0.getValueType(); 6244 6245 // fold (uint_to_fp c1) -> c1fp 6246 if (N0C && OpVT != MVT::ppcf128 && 6247 // ...but only if the target supports immediate floating-point values 6248 (!LegalOperations || 6249 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) 6250 return DAG.getNode(ISD::UINT_TO_FP, N->getDebugLoc(), VT, N0); 6251 6252 // If the input is a legal type, and UINT_TO_FP is not legal on this target, 6253 // but SINT_TO_FP is legal on this target, try to convert. 6254 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) && 6255 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) { 6256 // If the sign bit is known to be zero, we can change this to SINT_TO_FP. 6257 if (DAG.SignBitIsZero(N0)) 6258 return DAG.getNode(ISD::SINT_TO_FP, N->getDebugLoc(), VT, N0); 6259 } 6260 6261 // The next optimizations are desireable only if SELECT_CC can be lowered. 6262 // Check against MVT::Other for SELECT_CC, which is a workaround for targets 6263 // having to say they don't support SELECT_CC on every type the DAG knows 6264 // about, since there is no way to mark an opcode illegal at all value types 6265 // (See also visitSELECT) 6266 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other)) { 6267 // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc) 6268 6269 if (N0.getOpcode() == ISD::SETCC && !VT.isVector() && 6270 (!LegalOperations || 6271 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) { 6272 SDValue Ops[] = 6273 { N0.getOperand(0), N0.getOperand(1), 6274 DAG.getConstantFP(1.0, VT), DAG.getConstantFP(0.0, VT), 6275 N0.getOperand(2) }; 6276 return DAG.getNode(ISD::SELECT_CC, N->getDebugLoc(), VT, Ops, 5); 6277 } 6278 } 6279 6280 return SDValue(); 6281} 6282 6283SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) { 6284 SDValue N0 = N->getOperand(0); 6285 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 6286 EVT VT = N->getValueType(0); 6287 6288 // fold (fp_to_sint c1fp) -> c1 6289 if (N0CFP) 6290 return DAG.getNode(ISD::FP_TO_SINT, N->getDebugLoc(), VT, N0); 6291 6292 return SDValue(); 6293} 6294 6295SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) { 6296 SDValue N0 = N->getOperand(0); 6297 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 6298 EVT VT = N->getValueType(0); 6299 6300 // fold (fp_to_uint c1fp) -> c1 6301 if (N0CFP && VT != MVT::ppcf128) 6302 return DAG.getNode(ISD::FP_TO_UINT, N->getDebugLoc(), VT, N0); 6303 6304 return SDValue(); 6305} 6306 6307SDValue DAGCombiner::visitFP_ROUND(SDNode *N) { 6308 SDValue N0 = N->getOperand(0); 6309 SDValue N1 = N->getOperand(1); 6310 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 6311 EVT VT = N->getValueType(0); 6312 6313 // fold (fp_round c1fp) -> c1fp 6314 if (N0CFP && N0.getValueType() != MVT::ppcf128) 6315 return DAG.getNode(ISD::FP_ROUND, N->getDebugLoc(), VT, N0, N1); 6316 6317 // fold (fp_round (fp_extend x)) -> x 6318 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType()) 6319 return N0.getOperand(0); 6320 6321 // fold (fp_round (fp_round x)) -> (fp_round x) 6322 if (N0.getOpcode() == ISD::FP_ROUND) { 6323 // This is a value preserving truncation if both round's are. 6324 bool IsTrunc = N->getConstantOperandVal(1) == 1 && 6325 N0.getNode()->getConstantOperandVal(1) == 1; 6326 return DAG.getNode(ISD::FP_ROUND, N->getDebugLoc(), VT, N0.getOperand(0), 6327 DAG.getIntPtrConstant(IsTrunc)); 6328 } 6329 6330 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y) 6331 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) { 6332 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, N0.getDebugLoc(), VT, 6333 N0.getOperand(0), N1); 6334 AddToWorkList(Tmp.getNode()); 6335 return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT, 6336 Tmp, N0.getOperand(1)); 6337 } 6338 6339 return SDValue(); 6340} 6341 6342SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) { 6343 SDValue N0 = N->getOperand(0); 6344 EVT VT = N->getValueType(0); 6345 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT(); 6346 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 6347 6348 // fold (fp_round_inreg c1fp) -> c1fp 6349 if (N0CFP && isTypeLegal(EVT)) { 6350 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT); 6351 return DAG.getNode(ISD::FP_EXTEND, N->getDebugLoc(), VT, Round); 6352 } 6353 6354 return SDValue(); 6355} 6356 6357SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) { 6358 SDValue N0 = N->getOperand(0); 6359 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 6360 EVT VT = N->getValueType(0); 6361 6362 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded. 6363 if (N->hasOneUse() && 6364 N->use_begin()->getOpcode() == ISD::FP_ROUND) 6365 return SDValue(); 6366 6367 // fold (fp_extend c1fp) -> c1fp 6368 if (N0CFP && VT != MVT::ppcf128) 6369 return DAG.getNode(ISD::FP_EXTEND, N->getDebugLoc(), VT, N0); 6370 6371 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the 6372 // value of X. 6373 if (N0.getOpcode() == ISD::FP_ROUND 6374 && N0.getNode()->getConstantOperandVal(1) == 1) { 6375 SDValue In = N0.getOperand(0); 6376 if (In.getValueType() == VT) return In; 6377 if (VT.bitsLT(In.getValueType())) 6378 return DAG.getNode(ISD::FP_ROUND, N->getDebugLoc(), VT, 6379 In, N0.getOperand(1)); 6380 return DAG.getNode(ISD::FP_EXTEND, N->getDebugLoc(), VT, In); 6381 } 6382 6383 // fold (fpext (load x)) -> (fpext (fptrunc (extload x))) 6384 if (ISD::isNON_EXTLoad(N0.getNode()) && N0.hasOneUse() && 6385 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) || 6386 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) { 6387 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6388 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, N->getDebugLoc(), VT, 6389 LN0->getChain(), 6390 LN0->getBasePtr(), LN0->getPointerInfo(), 6391 N0.getValueType(), 6392 LN0->isVolatile(), LN0->isNonTemporal(), 6393 LN0->getAlignment()); 6394 CombineTo(N, ExtLoad); 6395 CombineTo(N0.getNode(), 6396 DAG.getNode(ISD::FP_ROUND, N0.getDebugLoc(), 6397 N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)), 6398 ExtLoad.getValue(1)); 6399 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6400 } 6401 6402 return SDValue(); 6403} 6404 6405SDValue DAGCombiner::visitFNEG(SDNode *N) { 6406 SDValue N0 = N->getOperand(0); 6407 EVT VT = N->getValueType(0); 6408 6409 if (VT.isVector()) { 6410 SDValue FoldedVOp = SimplifyVUnaryOp(N); 6411 if (FoldedVOp.getNode()) return FoldedVOp; 6412 } 6413 6414 if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(), 6415 &DAG.getTarget().Options)) 6416 return GetNegatedExpression(N0, DAG, LegalOperations); 6417 6418 // Transform fneg(bitconvert(x)) -> bitconvert(x^sign) to avoid loading 6419 // constant pool values. 6420 if (!TLI.isFNegFree(VT) && N0.getOpcode() == ISD::BITCAST && 6421 !VT.isVector() && 6422 N0.getNode()->hasOneUse() && 6423 N0.getOperand(0).getValueType().isInteger()) { 6424 SDValue Int = N0.getOperand(0); 6425 EVT IntVT = Int.getValueType(); 6426 if (IntVT.isInteger() && !IntVT.isVector()) { 6427 Int = DAG.getNode(ISD::XOR, N0.getDebugLoc(), IntVT, Int, 6428 DAG.getConstant(APInt::getSignBit(IntVT.getSizeInBits()), IntVT)); 6429 AddToWorkList(Int.getNode()); 6430 return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), 6431 VT, Int); 6432 } 6433 } 6434 6435 // (fneg (fmul c, x)) -> (fmul -c, x) 6436 if (N0.getOpcode() == ISD::FMUL) { 6437 ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1)); 6438 if (CFP1) { 6439 return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT, 6440 N0.getOperand(0), 6441 DAG.getNode(ISD::FNEG, N->getDebugLoc(), VT, 6442 N0.getOperand(1))); 6443 } 6444 } 6445 6446 return SDValue(); 6447} 6448 6449SDValue DAGCombiner::visitFCEIL(SDNode *N) { 6450 SDValue N0 = N->getOperand(0); 6451 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 6452 EVT VT = N->getValueType(0); 6453 6454 // fold (fceil c1) -> fceil(c1) 6455 if (N0CFP && VT != MVT::ppcf128) 6456 return DAG.getNode(ISD::FCEIL, N->getDebugLoc(), VT, N0); 6457 6458 return SDValue(); 6459} 6460 6461SDValue DAGCombiner::visitFTRUNC(SDNode *N) { 6462 SDValue N0 = N->getOperand(0); 6463 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 6464 EVT VT = N->getValueType(0); 6465 6466 // fold (ftrunc c1) -> ftrunc(c1) 6467 if (N0CFP && VT != MVT::ppcf128) 6468 return DAG.getNode(ISD::FTRUNC, N->getDebugLoc(), VT, N0); 6469 6470 return SDValue(); 6471} 6472 6473SDValue DAGCombiner::visitFFLOOR(SDNode *N) { 6474 SDValue N0 = N->getOperand(0); 6475 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 6476 EVT VT = N->getValueType(0); 6477 6478 // fold (ffloor c1) -> ffloor(c1) 6479 if (N0CFP && VT != MVT::ppcf128) 6480 return DAG.getNode(ISD::FFLOOR, N->getDebugLoc(), VT, N0); 6481 6482 return SDValue(); 6483} 6484 6485SDValue DAGCombiner::visitFABS(SDNode *N) { 6486 SDValue N0 = N->getOperand(0); 6487 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 6488 EVT VT = N->getValueType(0); 6489 6490 if (VT.isVector()) { 6491 SDValue FoldedVOp = SimplifyVUnaryOp(N); 6492 if (FoldedVOp.getNode()) return FoldedVOp; 6493 } 6494 6495 // fold (fabs c1) -> fabs(c1) 6496 if (N0CFP && VT != MVT::ppcf128) 6497 return DAG.getNode(ISD::FABS, N->getDebugLoc(), VT, N0); 6498 // fold (fabs (fabs x)) -> (fabs x) 6499 if (N0.getOpcode() == ISD::FABS) 6500 return N->getOperand(0); 6501 // fold (fabs (fneg x)) -> (fabs x) 6502 // fold (fabs (fcopysign x, y)) -> (fabs x) 6503 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN) 6504 return DAG.getNode(ISD::FABS, N->getDebugLoc(), VT, N0.getOperand(0)); 6505 6506 // Transform fabs(bitconvert(x)) -> bitconvert(x&~sign) to avoid loading 6507 // constant pool values. 6508 if (!TLI.isFAbsFree(VT) && 6509 N0.getOpcode() == ISD::BITCAST && N0.getNode()->hasOneUse() && 6510 N0.getOperand(0).getValueType().isInteger() && 6511 !N0.getOperand(0).getValueType().isVector()) { 6512 SDValue Int = N0.getOperand(0); 6513 EVT IntVT = Int.getValueType(); 6514 if (IntVT.isInteger() && !IntVT.isVector()) { 6515 Int = DAG.getNode(ISD::AND, N0.getDebugLoc(), IntVT, Int, 6516 DAG.getConstant(~APInt::getSignBit(IntVT.getSizeInBits()), IntVT)); 6517 AddToWorkList(Int.getNode()); 6518 return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), 6519 N->getValueType(0), Int); 6520 } 6521 } 6522 6523 return SDValue(); 6524} 6525 6526SDValue DAGCombiner::visitBRCOND(SDNode *N) { 6527 SDValue Chain = N->getOperand(0); 6528 SDValue N1 = N->getOperand(1); 6529 SDValue N2 = N->getOperand(2); 6530 6531 // If N is a constant we could fold this into a fallthrough or unconditional 6532 // branch. However that doesn't happen very often in normal code, because 6533 // Instcombine/SimplifyCFG should have handled the available opportunities. 6534 // If we did this folding here, it would be necessary to update the 6535 // MachineBasicBlock CFG, which is awkward. 6536 6537 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal 6538 // on the target. 6539 if (N1.getOpcode() == ISD::SETCC && 6540 TLI.isOperationLegalOrCustom(ISD::BR_CC, MVT::Other)) { 6541 return DAG.getNode(ISD::BR_CC, N->getDebugLoc(), MVT::Other, 6542 Chain, N1.getOperand(2), 6543 N1.getOperand(0), N1.getOperand(1), N2); 6544 } 6545 6546 if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) || 6547 ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) && 6548 (N1.getOperand(0).hasOneUse() && 6549 N1.getOperand(0).getOpcode() == ISD::SRL))) { 6550 SDNode *Trunc = 0; 6551 if (N1.getOpcode() == ISD::TRUNCATE) { 6552 // Look pass the truncate. 6553 Trunc = N1.getNode(); 6554 N1 = N1.getOperand(0); 6555 } 6556 6557 // Match this pattern so that we can generate simpler code: 6558 // 6559 // %a = ... 6560 // %b = and i32 %a, 2 6561 // %c = srl i32 %b, 1 6562 // brcond i32 %c ... 6563 // 6564 // into 6565 // 6566 // %a = ... 6567 // %b = and i32 %a, 2 6568 // %c = setcc eq %b, 0 6569 // brcond %c ... 6570 // 6571 // This applies only when the AND constant value has one bit set and the 6572 // SRL constant is equal to the log2 of the AND constant. The back-end is 6573 // smart enough to convert the result into a TEST/JMP sequence. 6574 SDValue Op0 = N1.getOperand(0); 6575 SDValue Op1 = N1.getOperand(1); 6576 6577 if (Op0.getOpcode() == ISD::AND && 6578 Op1.getOpcode() == ISD::Constant) { 6579 SDValue AndOp1 = Op0.getOperand(1); 6580 6581 if (AndOp1.getOpcode() == ISD::Constant) { 6582 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue(); 6583 6584 if (AndConst.isPowerOf2() && 6585 cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) { 6586 SDValue SetCC = 6587 DAG.getSetCC(N->getDebugLoc(), 6588 TLI.getSetCCResultType(Op0.getValueType()), 6589 Op0, DAG.getConstant(0, Op0.getValueType()), 6590 ISD::SETNE); 6591 6592 SDValue NewBRCond = DAG.getNode(ISD::BRCOND, N->getDebugLoc(), 6593 MVT::Other, Chain, SetCC, N2); 6594 // Don't add the new BRCond into the worklist or else SimplifySelectCC 6595 // will convert it back to (X & C1) >> C2. 6596 CombineTo(N, NewBRCond, false); 6597 // Truncate is dead. 6598 if (Trunc) { 6599 removeFromWorkList(Trunc); 6600 DAG.DeleteNode(Trunc); 6601 } 6602 // Replace the uses of SRL with SETCC 6603 WorkListRemover DeadNodes(*this); 6604 DAG.ReplaceAllUsesOfValueWith(N1, SetCC); 6605 removeFromWorkList(N1.getNode()); 6606 DAG.DeleteNode(N1.getNode()); 6607 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6608 } 6609 } 6610 } 6611 6612 if (Trunc) 6613 // Restore N1 if the above transformation doesn't match. 6614 N1 = N->getOperand(1); 6615 } 6616 6617 // Transform br(xor(x, y)) -> br(x != y) 6618 // Transform br(xor(xor(x,y), 1)) -> br (x == y) 6619 if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) { 6620 SDNode *TheXor = N1.getNode(); 6621 SDValue Op0 = TheXor->getOperand(0); 6622 SDValue Op1 = TheXor->getOperand(1); 6623 if (Op0.getOpcode() == Op1.getOpcode()) { 6624 // Avoid missing important xor optimizations. 6625 SDValue Tmp = visitXOR(TheXor); 6626 if (Tmp.getNode() && Tmp.getNode() != TheXor) { 6627 DEBUG(dbgs() << "\nReplacing.8 "; 6628 TheXor->dump(&DAG); 6629 dbgs() << "\nWith: "; 6630 Tmp.getNode()->dump(&DAG); 6631 dbgs() << '\n'); 6632 WorkListRemover DeadNodes(*this); 6633 DAG.ReplaceAllUsesOfValueWith(N1, Tmp); 6634 removeFromWorkList(TheXor); 6635 DAG.DeleteNode(TheXor); 6636 return DAG.getNode(ISD::BRCOND, N->getDebugLoc(), 6637 MVT::Other, Chain, Tmp, N2); 6638 } 6639 } 6640 6641 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) { 6642 bool Equal = false; 6643 if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0)) 6644 if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() && 6645 Op0.getOpcode() == ISD::XOR) { 6646 TheXor = Op0.getNode(); 6647 Equal = true; 6648 } 6649 6650 EVT SetCCVT = N1.getValueType(); 6651 if (LegalTypes) 6652 SetCCVT = TLI.getSetCCResultType(SetCCVT); 6653 SDValue SetCC = DAG.getSetCC(TheXor->getDebugLoc(), 6654 SetCCVT, 6655 Op0, Op1, 6656 Equal ? ISD::SETEQ : ISD::SETNE); 6657 // Replace the uses of XOR with SETCC 6658 WorkListRemover DeadNodes(*this); 6659 DAG.ReplaceAllUsesOfValueWith(N1, SetCC); 6660 removeFromWorkList(N1.getNode()); 6661 DAG.DeleteNode(N1.getNode()); 6662 return DAG.getNode(ISD::BRCOND, N->getDebugLoc(), 6663 MVT::Other, Chain, SetCC, N2); 6664 } 6665 } 6666 6667 return SDValue(); 6668} 6669 6670// Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB. 6671// 6672SDValue DAGCombiner::visitBR_CC(SDNode *N) { 6673 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1)); 6674 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3); 6675 6676 // If N is a constant we could fold this into a fallthrough or unconditional 6677 // branch. However that doesn't happen very often in normal code, because 6678 // Instcombine/SimplifyCFG should have handled the available opportunities. 6679 // If we did this folding here, it would be necessary to update the 6680 // MachineBasicBlock CFG, which is awkward. 6681 6682 // Use SimplifySetCC to simplify SETCC's. 6683 SDValue Simp = SimplifySetCC(TLI.getSetCCResultType(CondLHS.getValueType()), 6684 CondLHS, CondRHS, CC->get(), N->getDebugLoc(), 6685 false); 6686 if (Simp.getNode()) AddToWorkList(Simp.getNode()); 6687 6688 // fold to a simpler setcc 6689 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC) 6690 return DAG.getNode(ISD::BR_CC, N->getDebugLoc(), MVT::Other, 6691 N->getOperand(0), Simp.getOperand(2), 6692 Simp.getOperand(0), Simp.getOperand(1), 6693 N->getOperand(4)); 6694 6695 return SDValue(); 6696} 6697 6698/// canFoldInAddressingMode - Return true if 'Use' is a load or a store that 6699/// uses N as its base pointer and that N may be folded in the load / store 6700/// addressing mode. 6701static bool canFoldInAddressingMode(SDNode *N, SDNode *Use, 6702 SelectionDAG &DAG, 6703 const TargetLowering &TLI) { 6704 EVT VT; 6705 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) { 6706 if (LD->isIndexed() || LD->getBasePtr().getNode() != N) 6707 return false; 6708 VT = Use->getValueType(0); 6709 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) { 6710 if (ST->isIndexed() || ST->getBasePtr().getNode() != N) 6711 return false; 6712 VT = ST->getValue().getValueType(); 6713 } else 6714 return false; 6715 6716 TargetLowering::AddrMode AM; 6717 if (N->getOpcode() == ISD::ADD) { 6718 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1)); 6719 if (Offset) 6720 // [reg +/- imm] 6721 AM.BaseOffs = Offset->getSExtValue(); 6722 else 6723 // [reg +/- reg] 6724 AM.Scale = 1; 6725 } else if (N->getOpcode() == ISD::SUB) { 6726 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1)); 6727 if (Offset) 6728 // [reg +/- imm] 6729 AM.BaseOffs = -Offset->getSExtValue(); 6730 else 6731 // [reg +/- reg] 6732 AM.Scale = 1; 6733 } else 6734 return false; 6735 6736 return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext())); 6737} 6738 6739/// CombineToPreIndexedLoadStore - Try turning a load / store into a 6740/// pre-indexed load / store when the base pointer is an add or subtract 6741/// and it has other uses besides the load / store. After the 6742/// transformation, the new indexed load / store has effectively folded 6743/// the add / subtract in and all of its other uses are redirected to the 6744/// new load / store. 6745bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) { 6746 if (Level < AfterLegalizeDAG) 6747 return false; 6748 6749 bool isLoad = true; 6750 SDValue Ptr; 6751 EVT VT; 6752 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 6753 if (LD->isIndexed()) 6754 return false; 6755 VT = LD->getMemoryVT(); 6756 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) && 6757 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT)) 6758 return false; 6759 Ptr = LD->getBasePtr(); 6760 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 6761 if (ST->isIndexed()) 6762 return false; 6763 VT = ST->getMemoryVT(); 6764 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) && 6765 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT)) 6766 return false; 6767 Ptr = ST->getBasePtr(); 6768 isLoad = false; 6769 } else { 6770 return false; 6771 } 6772 6773 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail 6774 // out. There is no reason to make this a preinc/predec. 6775 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) || 6776 Ptr.getNode()->hasOneUse()) 6777 return false; 6778 6779 // Ask the target to do addressing mode selection. 6780 SDValue BasePtr; 6781 SDValue Offset; 6782 ISD::MemIndexedMode AM = ISD::UNINDEXED; 6783 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG)) 6784 return false; 6785 // Don't create a indexed load / store with zero offset. 6786 if (isa<ConstantSDNode>(Offset) && 6787 cast<ConstantSDNode>(Offset)->isNullValue()) 6788 return false; 6789 6790 // Try turning it into a pre-indexed load / store except when: 6791 // 1) The new base ptr is a frame index. 6792 // 2) If N is a store and the new base ptr is either the same as or is a 6793 // predecessor of the value being stored. 6794 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded 6795 // that would create a cycle. 6796 // 4) All uses are load / store ops that use it as old base ptr. 6797 6798 // Check #1. Preinc'ing a frame index would require copying the stack pointer 6799 // (plus the implicit offset) to a register to preinc anyway. 6800 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr)) 6801 return false; 6802 6803 // Check #2. 6804 if (!isLoad) { 6805 SDValue Val = cast<StoreSDNode>(N)->getValue(); 6806 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode())) 6807 return false; 6808 } 6809 6810 // Now check for #3 and #4. 6811 bool RealUse = false; 6812 6813 // Caches for hasPredecessorHelper 6814 SmallPtrSet<const SDNode *, 32> Visited; 6815 SmallVector<const SDNode *, 16> Worklist; 6816 6817 for (SDNode::use_iterator I = Ptr.getNode()->use_begin(), 6818 E = Ptr.getNode()->use_end(); I != E; ++I) { 6819 SDNode *Use = *I; 6820 if (Use == N) 6821 continue; 6822 if (N->hasPredecessorHelper(Use, Visited, Worklist)) 6823 return false; 6824 6825 // If Ptr may be folded in addressing mode of other use, then it's 6826 // not profitable to do this transformation. 6827 if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI)) 6828 RealUse = true; 6829 } 6830 6831 if (!RealUse) 6832 return false; 6833 6834 SDValue Result; 6835 if (isLoad) 6836 Result = DAG.getIndexedLoad(SDValue(N,0), N->getDebugLoc(), 6837 BasePtr, Offset, AM); 6838 else 6839 Result = DAG.getIndexedStore(SDValue(N,0), N->getDebugLoc(), 6840 BasePtr, Offset, AM); 6841 ++PreIndexedNodes; 6842 ++NodesCombined; 6843 DEBUG(dbgs() << "\nReplacing.4 "; 6844 N->dump(&DAG); 6845 dbgs() << "\nWith: "; 6846 Result.getNode()->dump(&DAG); 6847 dbgs() << '\n'); 6848 WorkListRemover DeadNodes(*this); 6849 if (isLoad) { 6850 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0)); 6851 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2)); 6852 } else { 6853 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1)); 6854 } 6855 6856 // Finally, since the node is now dead, remove it from the graph. 6857 DAG.DeleteNode(N); 6858 6859 // Replace the uses of Ptr with uses of the updated base value. 6860 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0)); 6861 removeFromWorkList(Ptr.getNode()); 6862 DAG.DeleteNode(Ptr.getNode()); 6863 6864 return true; 6865} 6866 6867/// CombineToPostIndexedLoadStore - Try to combine a load / store with a 6868/// add / sub of the base pointer node into a post-indexed load / store. 6869/// The transformation folded the add / subtract into the new indexed 6870/// load / store effectively and all of its uses are redirected to the 6871/// new load / store. 6872bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) { 6873 if (Level < AfterLegalizeDAG) 6874 return false; 6875 6876 bool isLoad = true; 6877 SDValue Ptr; 6878 EVT VT; 6879 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 6880 if (LD->isIndexed()) 6881 return false; 6882 VT = LD->getMemoryVT(); 6883 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) && 6884 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT)) 6885 return false; 6886 Ptr = LD->getBasePtr(); 6887 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 6888 if (ST->isIndexed()) 6889 return false; 6890 VT = ST->getMemoryVT(); 6891 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) && 6892 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT)) 6893 return false; 6894 Ptr = ST->getBasePtr(); 6895 isLoad = false; 6896 } else { 6897 return false; 6898 } 6899 6900 if (Ptr.getNode()->hasOneUse()) 6901 return false; 6902 6903 for (SDNode::use_iterator I = Ptr.getNode()->use_begin(), 6904 E = Ptr.getNode()->use_end(); I != E; ++I) { 6905 SDNode *Op = *I; 6906 if (Op == N || 6907 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB)) 6908 continue; 6909 6910 SDValue BasePtr; 6911 SDValue Offset; 6912 ISD::MemIndexedMode AM = ISD::UNINDEXED; 6913 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) { 6914 // Don't create a indexed load / store with zero offset. 6915 if (isa<ConstantSDNode>(Offset) && 6916 cast<ConstantSDNode>(Offset)->isNullValue()) 6917 continue; 6918 6919 // Try turning it into a post-indexed load / store except when 6920 // 1) All uses are load / store ops that use it as base ptr (and 6921 // it may be folded as addressing mmode). 6922 // 2) Op must be independent of N, i.e. Op is neither a predecessor 6923 // nor a successor of N. Otherwise, if Op is folded that would 6924 // create a cycle. 6925 6926 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr)) 6927 continue; 6928 6929 // Check for #1. 6930 bool TryNext = false; 6931 for (SDNode::use_iterator II = BasePtr.getNode()->use_begin(), 6932 EE = BasePtr.getNode()->use_end(); II != EE; ++II) { 6933 SDNode *Use = *II; 6934 if (Use == Ptr.getNode()) 6935 continue; 6936 6937 // If all the uses are load / store addresses, then don't do the 6938 // transformation. 6939 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){ 6940 bool RealUse = false; 6941 for (SDNode::use_iterator III = Use->use_begin(), 6942 EEE = Use->use_end(); III != EEE; ++III) { 6943 SDNode *UseUse = *III; 6944 if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI)) 6945 RealUse = true; 6946 } 6947 6948 if (!RealUse) { 6949 TryNext = true; 6950 break; 6951 } 6952 } 6953 } 6954 6955 if (TryNext) 6956 continue; 6957 6958 // Check for #2 6959 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) { 6960 SDValue Result = isLoad 6961 ? DAG.getIndexedLoad(SDValue(N,0), N->getDebugLoc(), 6962 BasePtr, Offset, AM) 6963 : DAG.getIndexedStore(SDValue(N,0), N->getDebugLoc(), 6964 BasePtr, Offset, AM); 6965 ++PostIndexedNodes; 6966 ++NodesCombined; 6967 DEBUG(dbgs() << "\nReplacing.5 "; 6968 N->dump(&DAG); 6969 dbgs() << "\nWith: "; 6970 Result.getNode()->dump(&DAG); 6971 dbgs() << '\n'); 6972 WorkListRemover DeadNodes(*this); 6973 if (isLoad) { 6974 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0)); 6975 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2)); 6976 } else { 6977 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1)); 6978 } 6979 6980 // Finally, since the node is now dead, remove it from the graph. 6981 DAG.DeleteNode(N); 6982 6983 // Replace the uses of Use with uses of the updated base value. 6984 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0), 6985 Result.getValue(isLoad ? 1 : 0)); 6986 removeFromWorkList(Op); 6987 DAG.DeleteNode(Op); 6988 return true; 6989 } 6990 } 6991 } 6992 6993 return false; 6994} 6995 6996SDValue DAGCombiner::visitLOAD(SDNode *N) { 6997 LoadSDNode *LD = cast<LoadSDNode>(N); 6998 SDValue Chain = LD->getChain(); 6999 SDValue Ptr = LD->getBasePtr(); 7000 7001 // If load is not volatile and there are no uses of the loaded value (and 7002 // the updated indexed value in case of indexed loads), change uses of the 7003 // chain value into uses of the chain input (i.e. delete the dead load). 7004 if (!LD->isVolatile()) { 7005 if (N->getValueType(1) == MVT::Other) { 7006 // Unindexed loads. 7007 if (!N->hasAnyUseOfValue(0)) { 7008 // It's not safe to use the two value CombineTo variant here. e.g. 7009 // v1, chain2 = load chain1, loc 7010 // v2, chain3 = load chain2, loc 7011 // v3 = add v2, c 7012 // Now we replace use of chain2 with chain1. This makes the second load 7013 // isomorphic to the one we are deleting, and thus makes this load live. 7014 DEBUG(dbgs() << "\nReplacing.6 "; 7015 N->dump(&DAG); 7016 dbgs() << "\nWith chain: "; 7017 Chain.getNode()->dump(&DAG); 7018 dbgs() << "\n"); 7019 WorkListRemover DeadNodes(*this); 7020 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain); 7021 7022 if (N->use_empty()) { 7023 removeFromWorkList(N); 7024 DAG.DeleteNode(N); 7025 } 7026 7027 return SDValue(N, 0); // Return N so it doesn't get rechecked! 7028 } 7029 } else { 7030 // Indexed loads. 7031 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?"); 7032 if (!N->hasAnyUseOfValue(0) && !N->hasAnyUseOfValue(1)) { 7033 SDValue Undef = DAG.getUNDEF(N->getValueType(0)); 7034 DEBUG(dbgs() << "\nReplacing.7 "; 7035 N->dump(&DAG); 7036 dbgs() << "\nWith: "; 7037 Undef.getNode()->dump(&DAG); 7038 dbgs() << " and 2 other values\n"); 7039 WorkListRemover DeadNodes(*this); 7040 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef); 7041 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), 7042 DAG.getUNDEF(N->getValueType(1))); 7043 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain); 7044 removeFromWorkList(N); 7045 DAG.DeleteNode(N); 7046 return SDValue(N, 0); // Return N so it doesn't get rechecked! 7047 } 7048 } 7049 } 7050 7051 // If this load is directly stored, replace the load value with the stored 7052 // value. 7053 // TODO: Handle store large -> read small portion. 7054 // TODO: Handle TRUNCSTORE/LOADEXT 7055 if (ISD::isNormalLoad(N) && !LD->isVolatile()) { 7056 if (ISD::isNON_TRUNCStore(Chain.getNode())) { 7057 StoreSDNode *PrevST = cast<StoreSDNode>(Chain); 7058 if (PrevST->getBasePtr() == Ptr && 7059 PrevST->getValue().getValueType() == N->getValueType(0)) 7060 return CombineTo(N, Chain.getOperand(1), Chain); 7061 } 7062 } 7063 7064 // Try to infer better alignment information than the load already has. 7065 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) { 7066 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) { 7067 if (Align > LD->getAlignment()) 7068 return DAG.getExtLoad(LD->getExtensionType(), N->getDebugLoc(), 7069 LD->getValueType(0), 7070 Chain, Ptr, LD->getPointerInfo(), 7071 LD->getMemoryVT(), 7072 LD->isVolatile(), LD->isNonTemporal(), Align); 7073 } 7074 } 7075 7076 if (CombinerAA) { 7077 // Walk up chain skipping non-aliasing memory nodes. 7078 SDValue BetterChain = FindBetterChain(N, Chain); 7079 7080 // If there is a better chain. 7081 if (Chain != BetterChain) { 7082 SDValue ReplLoad; 7083 7084 // Replace the chain to void dependency. 7085 if (LD->getExtensionType() == ISD::NON_EXTLOAD) { 7086 ReplLoad = DAG.getLoad(N->getValueType(0), LD->getDebugLoc(), 7087 BetterChain, Ptr, LD->getPointerInfo(), 7088 LD->isVolatile(), LD->isNonTemporal(), 7089 LD->isInvariant(), LD->getAlignment()); 7090 } else { 7091 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), LD->getDebugLoc(), 7092 LD->getValueType(0), 7093 BetterChain, Ptr, LD->getPointerInfo(), 7094 LD->getMemoryVT(), 7095 LD->isVolatile(), 7096 LD->isNonTemporal(), 7097 LD->getAlignment()); 7098 } 7099 7100 // Create token factor to keep old chain connected. 7101 SDValue Token = DAG.getNode(ISD::TokenFactor, N->getDebugLoc(), 7102 MVT::Other, Chain, ReplLoad.getValue(1)); 7103 7104 // Make sure the new and old chains are cleaned up. 7105 AddToWorkList(Token.getNode()); 7106 7107 // Replace uses with load result and token factor. Don't add users 7108 // to work list. 7109 return CombineTo(N, ReplLoad.getValue(0), Token, false); 7110 } 7111 } 7112 7113 // Try transforming N to an indexed load. 7114 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N)) 7115 return SDValue(N, 0); 7116 7117 return SDValue(); 7118} 7119 7120/// CheckForMaskedLoad - Check to see if V is (and load (ptr), imm), where the 7121/// load is having specific bytes cleared out. If so, return the byte size 7122/// being masked out and the shift amount. 7123static std::pair<unsigned, unsigned> 7124CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) { 7125 std::pair<unsigned, unsigned> Result(0, 0); 7126 7127 // Check for the structure we're looking for. 7128 if (V->getOpcode() != ISD::AND || 7129 !isa<ConstantSDNode>(V->getOperand(1)) || 7130 !ISD::isNormalLoad(V->getOperand(0).getNode())) 7131 return Result; 7132 7133 // Check the chain and pointer. 7134 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0)); 7135 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer. 7136 7137 // The store should be chained directly to the load or be an operand of a 7138 // tokenfactor. 7139 if (LD == Chain.getNode()) 7140 ; // ok. 7141 else if (Chain->getOpcode() != ISD::TokenFactor) 7142 return Result; // Fail. 7143 else { 7144 bool isOk = false; 7145 for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i) 7146 if (Chain->getOperand(i).getNode() == LD) { 7147 isOk = true; 7148 break; 7149 } 7150 if (!isOk) return Result; 7151 } 7152 7153 // This only handles simple types. 7154 if (V.getValueType() != MVT::i16 && 7155 V.getValueType() != MVT::i32 && 7156 V.getValueType() != MVT::i64) 7157 return Result; 7158 7159 // Check the constant mask. Invert it so that the bits being masked out are 7160 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits 7161 // follow the sign bit for uniformity. 7162 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue(); 7163 unsigned NotMaskLZ = CountLeadingZeros_64(NotMask); 7164 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte. 7165 unsigned NotMaskTZ = CountTrailingZeros_64(NotMask); 7166 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte. 7167 if (NotMaskLZ == 64) return Result; // All zero mask. 7168 7169 // See if we have a continuous run of bits. If so, we have 0*1+0* 7170 if (CountTrailingOnes_64(NotMask >> NotMaskTZ)+NotMaskTZ+NotMaskLZ != 64) 7171 return Result; 7172 7173 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64. 7174 if (V.getValueType() != MVT::i64 && NotMaskLZ) 7175 NotMaskLZ -= 64-V.getValueSizeInBits(); 7176 7177 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8; 7178 switch (MaskedBytes) { 7179 case 1: 7180 case 2: 7181 case 4: break; 7182 default: return Result; // All one mask, or 5-byte mask. 7183 } 7184 7185 // Verify that the first bit starts at a multiple of mask so that the access 7186 // is aligned the same as the access width. 7187 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result; 7188 7189 Result.first = MaskedBytes; 7190 Result.second = NotMaskTZ/8; 7191 return Result; 7192} 7193 7194 7195/// ShrinkLoadReplaceStoreWithStore - Check to see if IVal is something that 7196/// provides a value as specified by MaskInfo. If so, replace the specified 7197/// store with a narrower store of truncated IVal. 7198static SDNode * 7199ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo, 7200 SDValue IVal, StoreSDNode *St, 7201 DAGCombiner *DC) { 7202 unsigned NumBytes = MaskInfo.first; 7203 unsigned ByteShift = MaskInfo.second; 7204 SelectionDAG &DAG = DC->getDAG(); 7205 7206 // Check to see if IVal is all zeros in the part being masked in by the 'or' 7207 // that uses this. If not, this is not a replacement. 7208 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(), 7209 ByteShift*8, (ByteShift+NumBytes)*8); 7210 if (!DAG.MaskedValueIsZero(IVal, Mask)) return 0; 7211 7212 // Check that it is legal on the target to do this. It is legal if the new 7213 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type 7214 // legalization. 7215 MVT VT = MVT::getIntegerVT(NumBytes*8); 7216 if (!DC->isTypeLegal(VT)) 7217 return 0; 7218 7219 // Okay, we can do this! Replace the 'St' store with a store of IVal that is 7220 // shifted by ByteShift and truncated down to NumBytes. 7221 if (ByteShift) 7222 IVal = DAG.getNode(ISD::SRL, IVal->getDebugLoc(), IVal.getValueType(), IVal, 7223 DAG.getConstant(ByteShift*8, 7224 DC->getShiftAmountTy(IVal.getValueType()))); 7225 7226 // Figure out the offset for the store and the alignment of the access. 7227 unsigned StOffset; 7228 unsigned NewAlign = St->getAlignment(); 7229 7230 if (DAG.getTargetLoweringInfo().isLittleEndian()) 7231 StOffset = ByteShift; 7232 else 7233 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes; 7234 7235 SDValue Ptr = St->getBasePtr(); 7236 if (StOffset) { 7237 Ptr = DAG.getNode(ISD::ADD, IVal->getDebugLoc(), Ptr.getValueType(), 7238 Ptr, DAG.getConstant(StOffset, Ptr.getValueType())); 7239 NewAlign = MinAlign(NewAlign, StOffset); 7240 } 7241 7242 // Truncate down to the new size. 7243 IVal = DAG.getNode(ISD::TRUNCATE, IVal->getDebugLoc(), VT, IVal); 7244 7245 ++OpsNarrowed; 7246 return DAG.getStore(St->getChain(), St->getDebugLoc(), IVal, Ptr, 7247 St->getPointerInfo().getWithOffset(StOffset), 7248 false, false, NewAlign).getNode(); 7249} 7250 7251 7252/// ReduceLoadOpStoreWidth - Look for sequence of load / op / store where op is 7253/// one of 'or', 'xor', and 'and' of immediates. If 'op' is only touching some 7254/// of the loaded bits, try narrowing the load and store if it would end up 7255/// being a win for performance or code size. 7256SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) { 7257 StoreSDNode *ST = cast<StoreSDNode>(N); 7258 if (ST->isVolatile()) 7259 return SDValue(); 7260 7261 SDValue Chain = ST->getChain(); 7262 SDValue Value = ST->getValue(); 7263 SDValue Ptr = ST->getBasePtr(); 7264 EVT VT = Value.getValueType(); 7265 7266 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse()) 7267 return SDValue(); 7268 7269 unsigned Opc = Value.getOpcode(); 7270 7271 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst 7272 // is a byte mask indicating a consecutive number of bytes, check to see if 7273 // Y is known to provide just those bytes. If so, we try to replace the 7274 // load + replace + store sequence with a single (narrower) store, which makes 7275 // the load dead. 7276 if (Opc == ISD::OR) { 7277 std::pair<unsigned, unsigned> MaskedLoad; 7278 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain); 7279 if (MaskedLoad.first) 7280 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad, 7281 Value.getOperand(1), ST,this)) 7282 return SDValue(NewST, 0); 7283 7284 // Or is commutative, so try swapping X and Y. 7285 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain); 7286 if (MaskedLoad.first) 7287 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad, 7288 Value.getOperand(0), ST,this)) 7289 return SDValue(NewST, 0); 7290 } 7291 7292 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) || 7293 Value.getOperand(1).getOpcode() != ISD::Constant) 7294 return SDValue(); 7295 7296 SDValue N0 = Value.getOperand(0); 7297 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() && 7298 Chain == SDValue(N0.getNode(), 1)) { 7299 LoadSDNode *LD = cast<LoadSDNode>(N0); 7300 if (LD->getBasePtr() != Ptr || 7301 LD->getPointerInfo().getAddrSpace() != 7302 ST->getPointerInfo().getAddrSpace()) 7303 return SDValue(); 7304 7305 // Find the type to narrow it the load / op / store to. 7306 SDValue N1 = Value.getOperand(1); 7307 unsigned BitWidth = N1.getValueSizeInBits(); 7308 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue(); 7309 if (Opc == ISD::AND) 7310 Imm ^= APInt::getAllOnesValue(BitWidth); 7311 if (Imm == 0 || Imm.isAllOnesValue()) 7312 return SDValue(); 7313 unsigned ShAmt = Imm.countTrailingZeros(); 7314 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1; 7315 unsigned NewBW = NextPowerOf2(MSB - ShAmt); 7316 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW); 7317 while (NewBW < BitWidth && 7318 !(TLI.isOperationLegalOrCustom(Opc, NewVT) && 7319 TLI.isNarrowingProfitable(VT, NewVT))) { 7320 NewBW = NextPowerOf2(NewBW); 7321 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW); 7322 } 7323 if (NewBW >= BitWidth) 7324 return SDValue(); 7325 7326 // If the lsb changed does not start at the type bitwidth boundary, 7327 // start at the previous one. 7328 if (ShAmt % NewBW) 7329 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW; 7330 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt, ShAmt + NewBW); 7331 if ((Imm & Mask) == Imm) { 7332 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW); 7333 if (Opc == ISD::AND) 7334 NewImm ^= APInt::getAllOnesValue(NewBW); 7335 uint64_t PtrOff = ShAmt / 8; 7336 // For big endian targets, we need to adjust the offset to the pointer to 7337 // load the correct bytes. 7338 if (TLI.isBigEndian()) 7339 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff; 7340 7341 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff); 7342 Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext()); 7343 if (NewAlign < TLI.getTargetData()->getABITypeAlignment(NewVTTy)) 7344 return SDValue(); 7345 7346 SDValue NewPtr = DAG.getNode(ISD::ADD, LD->getDebugLoc(), 7347 Ptr.getValueType(), Ptr, 7348 DAG.getConstant(PtrOff, Ptr.getValueType())); 7349 SDValue NewLD = DAG.getLoad(NewVT, N0.getDebugLoc(), 7350 LD->getChain(), NewPtr, 7351 LD->getPointerInfo().getWithOffset(PtrOff), 7352 LD->isVolatile(), LD->isNonTemporal(), 7353 LD->isInvariant(), NewAlign); 7354 SDValue NewVal = DAG.getNode(Opc, Value.getDebugLoc(), NewVT, NewLD, 7355 DAG.getConstant(NewImm, NewVT)); 7356 SDValue NewST = DAG.getStore(Chain, N->getDebugLoc(), 7357 NewVal, NewPtr, 7358 ST->getPointerInfo().getWithOffset(PtrOff), 7359 false, false, NewAlign); 7360 7361 AddToWorkList(NewPtr.getNode()); 7362 AddToWorkList(NewLD.getNode()); 7363 AddToWorkList(NewVal.getNode()); 7364 WorkListRemover DeadNodes(*this); 7365 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1)); 7366 ++OpsNarrowed; 7367 return NewST; 7368 } 7369 } 7370 7371 return SDValue(); 7372} 7373 7374/// TransformFPLoadStorePair - For a given floating point load / store pair, 7375/// if the load value isn't used by any other operations, then consider 7376/// transforming the pair to integer load / store operations if the target 7377/// deems the transformation profitable. 7378SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) { 7379 StoreSDNode *ST = cast<StoreSDNode>(N); 7380 SDValue Chain = ST->getChain(); 7381 SDValue Value = ST->getValue(); 7382 if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) && 7383 Value.hasOneUse() && 7384 Chain == SDValue(Value.getNode(), 1)) { 7385 LoadSDNode *LD = cast<LoadSDNode>(Value); 7386 EVT VT = LD->getMemoryVT(); 7387 if (!VT.isFloatingPoint() || 7388 VT != ST->getMemoryVT() || 7389 LD->isNonTemporal() || 7390 ST->isNonTemporal() || 7391 LD->getPointerInfo().getAddrSpace() != 0 || 7392 ST->getPointerInfo().getAddrSpace() != 0) 7393 return SDValue(); 7394 7395 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits()); 7396 if (!TLI.isOperationLegal(ISD::LOAD, IntVT) || 7397 !TLI.isOperationLegal(ISD::STORE, IntVT) || 7398 !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) || 7399 !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT)) 7400 return SDValue(); 7401 7402 unsigned LDAlign = LD->getAlignment(); 7403 unsigned STAlign = ST->getAlignment(); 7404 Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext()); 7405 unsigned ABIAlign = TLI.getTargetData()->getABITypeAlignment(IntVTTy); 7406 if (LDAlign < ABIAlign || STAlign < ABIAlign) 7407 return SDValue(); 7408 7409 SDValue NewLD = DAG.getLoad(IntVT, Value.getDebugLoc(), 7410 LD->getChain(), LD->getBasePtr(), 7411 LD->getPointerInfo(), 7412 false, false, false, LDAlign); 7413 7414 SDValue NewST = DAG.getStore(NewLD.getValue(1), N->getDebugLoc(), 7415 NewLD, ST->getBasePtr(), 7416 ST->getPointerInfo(), 7417 false, false, STAlign); 7418 7419 AddToWorkList(NewLD.getNode()); 7420 AddToWorkList(NewST.getNode()); 7421 WorkListRemover DeadNodes(*this); 7422 DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1)); 7423 ++LdStFP2Int; 7424 return NewST; 7425 } 7426 7427 return SDValue(); 7428} 7429 7430/// Returns the base pointer and an integer offset from that object. 7431static std::pair<SDValue, int64_t> GetPointerBaseAndOffset(SDValue Ptr) { 7432 if (Ptr->getOpcode() == ISD::ADD && isa<ConstantSDNode>(Ptr->getOperand(1))) { 7433 int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue(); 7434 SDValue Base = Ptr->getOperand(0); 7435 return std::make_pair(Base, Offset); 7436 } 7437 7438 return std::make_pair(Ptr, 0); 7439} 7440 7441struct ConsecutiveMemoryChainSorter { 7442 typedef std::pair<LSBaseSDNode*, int64_t> MemLink; 7443 bool operator()(MemLink LHS, MemLink RHS) { 7444 return LHS.second < RHS.second; 7445 } 7446}; 7447 7448bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) { 7449 EVT MemVT = St->getMemoryVT(); 7450 int64_t ElementSizeBytes = MemVT.getSizeInBits()/8; 7451 7452 // Don't handle vectors. 7453 if (MemVT.isVector() || !MemVT.isSimple()) 7454 return false; 7455 7456 // Perform an early exit check. Do not bother looking at stored values that 7457 // are not constants or loads. 7458 SDValue StoredVal = St->getValue(); 7459 if (!isa<ConstantSDNode>(StoredVal) && !isa<ConstantFPSDNode>(StoredVal) && 7460 !isa<LoadSDNode>(StoredVal)) 7461 return false; 7462 7463 // Is this a load-to-store or a const-store. 7464 bool IsLoadSrc = isa<LoadSDNode>(StoredVal); 7465 7466 // Only look at ends of store chains. 7467 SDValue Chain = SDValue(St, 1); 7468 if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE) 7469 return false; 7470 7471 // This holds the base pointer and the offset in bytes from the base pointer. 7472 std::pair<SDValue, int64_t> BasePtr = 7473 GetPointerBaseAndOffset(St->getBasePtr()); 7474 7475 // We must have a base and an offset. 7476 if (!BasePtr.first.getNode()) 7477 return false; 7478 7479 // Do not handle stores to undef base pointers. 7480 if (BasePtr.first.getOpcode() == ISD::UNDEF) 7481 return false; 7482 7483 SmallVector<std::pair<StoreSDNode*, int64_t>, 8> StoreNodes; 7484 // Walk up the chain and look for nodes with offsets from the same 7485 // base pointer. Stop when reaching an instruction with a different kind 7486 // or instruction which has a different base pointer. 7487 StoreSDNode *Index = St; 7488 while (Index) { 7489 // If the chain has more than one use, then we can't reorder the mem ops. 7490 if (Index != St && !SDValue(Index, 1)->hasOneUse()) 7491 break; 7492 7493 // Find the base pointer and offset for this memory node. 7494 std::pair<SDValue, int64_t> Ptr = 7495 GetPointerBaseAndOffset(Index->getBasePtr()); 7496 7497 // Check that the base pointer is the same as the original one. 7498 if (Ptr.first.getNode() != BasePtr.first.getNode()) 7499 break; 7500 7501 // Check that the alignment is the same. 7502 if (Index->getAlignment() != St->getAlignment()) 7503 break; 7504 7505 // The memory operands must not be volatile. 7506 if (Index->isVolatile() || Index->isIndexed()) 7507 break; 7508 7509 // No truncation. 7510 if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index)) 7511 if (St->isTruncatingStore()) 7512 break; 7513 7514 // The stored memory type must be the same. 7515 if (Index->getMemoryVT() != MemVT) 7516 break; 7517 7518 // We found a potential memory operand to merge. 7519 StoreNodes.push_back(std::make_pair(Index,Ptr.second)); 7520 7521 // Move up the chain to the next memory operation. 7522 Index = dyn_cast<StoreSDNode>(Index->getChain().getNode()); 7523 } 7524 7525 // Check if there is anything to merge. 7526 if (StoreNodes.size() < 2) 7527 return false; 7528 7529 // Remember which node is the earliest node in the chain. 7530 LSBaseSDNode *EarliestOp = StoreNodes.back().first; 7531 7532 // Sort the memory operands according to their distance from the base pointer. 7533 std::sort(StoreNodes.begin(), StoreNodes.end(), 7534 ConsecutiveMemoryChainSorter()); 7535 7536 LSBaseSDNode *FirstInChain = StoreNodes[0].first; 7537 7538 // Scan the memory operations on the chain and find the first non-consecutive 7539 // store memory address. 7540 unsigned LastConsecutiveStore = 0; 7541 int64_t StartAddress = StoreNodes[0].second; 7542 for (unsigned i=1; i<StoreNodes.size(); ++i) { 7543 int64_t CurrAddress = StoreNodes[i].second; 7544 if (CurrAddress - StartAddress != (ElementSizeBytes * i)) 7545 break; 7546 LastConsecutiveStore = i; 7547 } 7548 7549 // Store the constants into memory as one consecutive store. 7550 if (!IsLoadSrc) { 7551 unsigned LastConst = 0; 7552 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) { 7553 SDValue StoredVal = StoreNodes[i].first->getValue(); 7554 bool IsConst = (isa<ConstantSDNode>(StoredVal) || isa<ConstantFPSDNode>(StoredVal)); 7555 if (!IsConst) 7556 break; 7557 LastConst = i; 7558 } 7559 unsigned NumElem = std::min(LastConsecutiveStore + 1, LastConst + 1); 7560 if (NumElem < 2) 7561 return false; 7562 7563 EVT JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem); 7564 DebugLoc DL = StoreNodes[0].first->getDebugLoc(); 7565 SmallVector<SDValue, 8> Ops; 7566 7567 for (unsigned i = 0; i < NumElem ; ++i) { 7568 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].first); 7569 Ops.push_back(St->getValue()); 7570 } 7571 7572 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, 7573 JointMemOpVT, &Ops[0], Ops.size()); 7574 7575 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), DL, BV, 7576 FirstInChain->getBasePtr(), 7577 FirstInChain->getPointerInfo(), false, false, 7578 FirstInChain->getAlignment()); 7579 7580 for (unsigned i = 0; i < NumElem ; ++i) { 7581 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].first); 7582 CombineTo(St, NewStore); 7583 } 7584 return true; 7585 } 7586 7587 // Look for load nodes wich are used by the stored values. 7588 SmallVector<std::pair<LoadSDNode*, int64_t>, 8> LoadNodes; 7589 7590 // Find acceptible loads. Loads need to have the same chain (token factor), 7591 // must not be zext, volatile, indexed, and they must be consecutive. 7592 SDValue LdBasePtr; 7593 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) { 7594 LoadSDNode *Ld = dyn_cast<LoadSDNode>(StoreNodes[i].first->getValue()); 7595 if (!Ld) break; 7596 7597 // Loads must only have one use. 7598 if (!Ld->hasNUsesOfValue(1, 0)) 7599 break; 7600 7601 // Check that the alignment is the same as the stores. 7602 if (Ld->getAlignment() != St->getAlignment()) 7603 break; 7604 7605 // The memory operands must not be volatile. 7606 if (Ld->isVolatile() || Ld->isIndexed()) 7607 break; 7608 7609 if (Ld->getExtensionType() != ISD::NON_EXTLOAD) 7610 break; 7611 7612 // The stored memory type must be the same. 7613 if (Ld->getMemoryVT() != MemVT) 7614 break; 7615 7616 std::pair<SDValue, int64_t> LdPtr = 7617 GetPointerBaseAndOffset(Ld->getBasePtr()); 7618 7619 // If this is not the first ptr that we check. 7620 if (LdBasePtr.getNode()) { 7621 // The base ptr must be the same, 7622 if (LdPtr.first != LdBasePtr) 7623 break; 7624 } else { 7625 LdBasePtr = LdPtr.first; 7626 } 7627 7628 // We found a potential memory operand to merge. 7629 LoadNodes.push_back(std::make_pair(Ld, LdPtr.second)); 7630 } 7631 7632 if (LoadNodes.size() < 2) 7633 return false; 7634 7635 // Scan the memory operations on the chain and find the first non-consecutive 7636 // load memory address. 7637 unsigned LastConsecutiveLoad = 0; 7638 StartAddress = LoadNodes[0].second; 7639 for (unsigned i=1; i<LoadNodes.size(); ++i) { 7640 int64_t CurrAddress = LoadNodes[i].second; 7641 if (CurrAddress - StartAddress != (ElementSizeBytes * i)) 7642 break; 7643 LastConsecutiveLoad = i; 7644 } 7645 7646 unsigned NumElem = 7647 std::min(LastConsecutiveStore + 1, LastConsecutiveLoad + 1); 7648 7649 EVT JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem); 7650 DebugLoc LoadDL = LoadNodes[0].first->getDebugLoc(); 7651 DebugLoc StoreDL = StoreNodes[0].first->getDebugLoc(); 7652 7653 LoadSDNode *FirstLoad = LoadNodes[0].first; 7654 SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL, 7655 FirstLoad->getChain(), 7656 FirstLoad->getBasePtr(), 7657 FirstLoad->getPointerInfo(), 7658 false, false, false, 7659 FirstLoad->getAlignment()); 7660 7661 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), StoreDL, NewLoad, 7662 FirstInChain->getBasePtr(), 7663 FirstInChain->getPointerInfo(), false, false, 7664 FirstInChain->getAlignment()); 7665 7666 for (unsigned i = 0; i < NumElem ; ++i) { 7667 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].first); 7668 CombineTo(St, NewStore); 7669 } 7670 7671 return true; 7672} 7673 7674SDValue DAGCombiner::visitSTORE(SDNode *N) { 7675 StoreSDNode *ST = cast<StoreSDNode>(N); 7676 SDValue Chain = ST->getChain(); 7677 SDValue Value = ST->getValue(); 7678 SDValue Ptr = ST->getBasePtr(); 7679 7680 // If this is a store of a bit convert, store the input value if the 7681 // resultant store does not need a higher alignment than the original. 7682 if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() && 7683 ST->isUnindexed()) { 7684 unsigned OrigAlign = ST->getAlignment(); 7685 EVT SVT = Value.getOperand(0).getValueType(); 7686 unsigned Align = TLI.getTargetData()-> 7687 getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext())); 7688 if (Align <= OrigAlign && 7689 ((!LegalOperations && !ST->isVolatile()) || 7690 TLI.isOperationLegalOrCustom(ISD::STORE, SVT))) 7691 return DAG.getStore(Chain, N->getDebugLoc(), Value.getOperand(0), 7692 Ptr, ST->getPointerInfo(), ST->isVolatile(), 7693 ST->isNonTemporal(), OrigAlign); 7694 } 7695 7696 // Turn 'store undef, Ptr' -> nothing. 7697 if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed()) 7698 return Chain; 7699 7700 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr' 7701 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) { 7702 // NOTE: If the original store is volatile, this transform must not increase 7703 // the number of stores. For example, on x86-32 an f64 can be stored in one 7704 // processor operation but an i64 (which is not legal) requires two. So the 7705 // transform should not be done in this case. 7706 if (Value.getOpcode() != ISD::TargetConstantFP) { 7707 SDValue Tmp; 7708 switch (CFP->getValueType(0).getSimpleVT().SimpleTy) { 7709 default: llvm_unreachable("Unknown FP type"); 7710 case MVT::f16: // We don't do this for these yet. 7711 case MVT::f80: 7712 case MVT::f128: 7713 case MVT::ppcf128: 7714 break; 7715 case MVT::f32: 7716 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) || 7717 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) { 7718 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF(). 7719 bitcastToAPInt().getZExtValue(), MVT::i32); 7720 return DAG.getStore(Chain, N->getDebugLoc(), Tmp, 7721 Ptr, ST->getPointerInfo(), ST->isVolatile(), 7722 ST->isNonTemporal(), ST->getAlignment()); 7723 } 7724 break; 7725 case MVT::f64: 7726 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations && 7727 !ST->isVolatile()) || 7728 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) { 7729 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt(). 7730 getZExtValue(), MVT::i64); 7731 return DAG.getStore(Chain, N->getDebugLoc(), Tmp, 7732 Ptr, ST->getPointerInfo(), ST->isVolatile(), 7733 ST->isNonTemporal(), ST->getAlignment()); 7734 } 7735 7736 if (!ST->isVolatile() && 7737 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) { 7738 // Many FP stores are not made apparent until after legalize, e.g. for 7739 // argument passing. Since this is so common, custom legalize the 7740 // 64-bit integer store into two 32-bit stores. 7741 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue(); 7742 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32); 7743 SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32); 7744 if (TLI.isBigEndian()) std::swap(Lo, Hi); 7745 7746 unsigned Alignment = ST->getAlignment(); 7747 bool isVolatile = ST->isVolatile(); 7748 bool isNonTemporal = ST->isNonTemporal(); 7749 7750 SDValue St0 = DAG.getStore(Chain, ST->getDebugLoc(), Lo, 7751 Ptr, ST->getPointerInfo(), 7752 isVolatile, isNonTemporal, 7753 ST->getAlignment()); 7754 Ptr = DAG.getNode(ISD::ADD, N->getDebugLoc(), Ptr.getValueType(), Ptr, 7755 DAG.getConstant(4, Ptr.getValueType())); 7756 Alignment = MinAlign(Alignment, 4U); 7757 SDValue St1 = DAG.getStore(Chain, ST->getDebugLoc(), Hi, 7758 Ptr, ST->getPointerInfo().getWithOffset(4), 7759 isVolatile, isNonTemporal, 7760 Alignment); 7761 return DAG.getNode(ISD::TokenFactor, N->getDebugLoc(), MVT::Other, 7762 St0, St1); 7763 } 7764 7765 break; 7766 } 7767 } 7768 } 7769 7770 // Try to infer better alignment information than the store already has. 7771 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) { 7772 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) { 7773 if (Align > ST->getAlignment()) 7774 return DAG.getTruncStore(Chain, N->getDebugLoc(), Value, 7775 Ptr, ST->getPointerInfo(), ST->getMemoryVT(), 7776 ST->isVolatile(), ST->isNonTemporal(), Align); 7777 } 7778 } 7779 7780 // Try transforming a pair floating point load / store ops to integer 7781 // load / store ops. 7782 SDValue NewST = TransformFPLoadStorePair(N); 7783 if (NewST.getNode()) 7784 return NewST; 7785 7786 if (CombinerAA) { 7787 // Walk up chain skipping non-aliasing memory nodes. 7788 SDValue BetterChain = FindBetterChain(N, Chain); 7789 7790 // If there is a better chain. 7791 if (Chain != BetterChain) { 7792 SDValue ReplStore; 7793 7794 // Replace the chain to avoid dependency. 7795 if (ST->isTruncatingStore()) { 7796 ReplStore = DAG.getTruncStore(BetterChain, N->getDebugLoc(), Value, Ptr, 7797 ST->getPointerInfo(), 7798 ST->getMemoryVT(), ST->isVolatile(), 7799 ST->isNonTemporal(), ST->getAlignment()); 7800 } else { 7801 ReplStore = DAG.getStore(BetterChain, N->getDebugLoc(), Value, Ptr, 7802 ST->getPointerInfo(), 7803 ST->isVolatile(), ST->isNonTemporal(), 7804 ST->getAlignment()); 7805 } 7806 7807 // Create token to keep both nodes around. 7808 SDValue Token = DAG.getNode(ISD::TokenFactor, N->getDebugLoc(), 7809 MVT::Other, Chain, ReplStore); 7810 7811 // Make sure the new and old chains are cleaned up. 7812 AddToWorkList(Token.getNode()); 7813 7814 // Don't add users to work list. 7815 return CombineTo(N, Token, false); 7816 } 7817 } 7818 7819 // Try transforming N to an indexed store. 7820 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N)) 7821 return SDValue(N, 0); 7822 7823 // FIXME: is there such a thing as a truncating indexed store? 7824 if (ST->isTruncatingStore() && ST->isUnindexed() && 7825 Value.getValueType().isInteger()) { 7826 // See if we can simplify the input to this truncstore with knowledge that 7827 // only the low bits are being used. For example: 7828 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8" 7829 SDValue Shorter = 7830 GetDemandedBits(Value, 7831 APInt::getLowBitsSet( 7832 Value.getValueType().getScalarType().getSizeInBits(), 7833 ST->getMemoryVT().getScalarType().getSizeInBits())); 7834 AddToWorkList(Value.getNode()); 7835 if (Shorter.getNode()) 7836 return DAG.getTruncStore(Chain, N->getDebugLoc(), Shorter, 7837 Ptr, ST->getPointerInfo(), ST->getMemoryVT(), 7838 ST->isVolatile(), ST->isNonTemporal(), 7839 ST->getAlignment()); 7840 7841 // Otherwise, see if we can simplify the operation with 7842 // SimplifyDemandedBits, which only works if the value has a single use. 7843 if (SimplifyDemandedBits(Value, 7844 APInt::getLowBitsSet( 7845 Value.getValueType().getScalarType().getSizeInBits(), 7846 ST->getMemoryVT().getScalarType().getSizeInBits()))) 7847 return SDValue(N, 0); 7848 } 7849 7850 // If this is a load followed by a store to the same location, then the store 7851 // is dead/noop. 7852 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) { 7853 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() && 7854 ST->isUnindexed() && !ST->isVolatile() && 7855 // There can't be any side effects between the load and store, such as 7856 // a call or store. 7857 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) { 7858 // The store is dead, remove it. 7859 return Chain; 7860 } 7861 } 7862 7863 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a 7864 // truncating store. We can do this even if this is already a truncstore. 7865 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE) 7866 && Value.getNode()->hasOneUse() && ST->isUnindexed() && 7867 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(), 7868 ST->getMemoryVT())) { 7869 return DAG.getTruncStore(Chain, N->getDebugLoc(), Value.getOperand(0), 7870 Ptr, ST->getPointerInfo(), ST->getMemoryVT(), 7871 ST->isVolatile(), ST->isNonTemporal(), 7872 ST->getAlignment()); 7873 } 7874 7875 7876 // Only perform this optimization before the types are legal, because we 7877 // don't want to generate illegal types in this optimization. 7878 if (!LegalTypes && MergeConsecutiveStores(ST)) 7879 return SDValue(N, 0); 7880 7881 return ReduceLoadOpStoreWidth(N); 7882} 7883 7884SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) { 7885 SDValue InVec = N->getOperand(0); 7886 SDValue InVal = N->getOperand(1); 7887 SDValue EltNo = N->getOperand(2); 7888 DebugLoc dl = N->getDebugLoc(); 7889 7890 // If the inserted element is an UNDEF, just use the input vector. 7891 if (InVal.getOpcode() == ISD::UNDEF) 7892 return InVec; 7893 7894 EVT VT = InVec.getValueType(); 7895 7896 // If we can't generate a legal BUILD_VECTOR, exit 7897 if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT)) 7898 return SDValue(); 7899 7900 // Check that we know which element is being inserted 7901 if (!isa<ConstantSDNode>(EltNo)) 7902 return SDValue(); 7903 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue(); 7904 7905 // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially 7906 // be converted to a BUILD_VECTOR). Fill in the Ops vector with the 7907 // vector elements. 7908 SmallVector<SDValue, 8> Ops; 7909 if (InVec.getOpcode() == ISD::BUILD_VECTOR) { 7910 Ops.append(InVec.getNode()->op_begin(), 7911 InVec.getNode()->op_end()); 7912 } else if (InVec.getOpcode() == ISD::UNDEF) { 7913 unsigned NElts = VT.getVectorNumElements(); 7914 Ops.append(NElts, DAG.getUNDEF(InVal.getValueType())); 7915 } else { 7916 return SDValue(); 7917 } 7918 7919 // Insert the element 7920 if (Elt < Ops.size()) { 7921 // All the operands of BUILD_VECTOR must have the same type; 7922 // we enforce that here. 7923 EVT OpVT = Ops[0].getValueType(); 7924 if (InVal.getValueType() != OpVT) 7925 InVal = OpVT.bitsGT(InVal.getValueType()) ? 7926 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) : 7927 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal); 7928 Ops[Elt] = InVal; 7929 } 7930 7931 // Return the new vector 7932 return DAG.getNode(ISD::BUILD_VECTOR, dl, 7933 VT, &Ops[0], Ops.size()); 7934} 7935 7936SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) { 7937 // (vextract (scalar_to_vector val, 0) -> val 7938 SDValue InVec = N->getOperand(0); 7939 EVT VT = InVec.getValueType(); 7940 EVT NVT = N->getValueType(0); 7941 7942 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) { 7943 // Check if the result type doesn't match the inserted element type. A 7944 // SCALAR_TO_VECTOR may truncate the inserted element and the 7945 // EXTRACT_VECTOR_ELT may widen the extracted vector. 7946 SDValue InOp = InVec.getOperand(0); 7947 if (InOp.getValueType() != NVT) { 7948 assert(InOp.getValueType().isInteger() && NVT.isInteger()); 7949 return DAG.getSExtOrTrunc(InOp, InVec.getDebugLoc(), NVT); 7950 } 7951 return InOp; 7952 } 7953 7954 SDValue EltNo = N->getOperand(1); 7955 bool ConstEltNo = isa<ConstantSDNode>(EltNo); 7956 7957 // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT. 7958 // We only perform this optimization before the op legalization phase because 7959 // we may introduce new vector instructions which are not backed by TD 7960 // patterns. For example on AVX, extracting elements from a wide vector 7961 // without using extract_subvector. 7962 if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE 7963 && ConstEltNo && !LegalOperations) { 7964 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue(); 7965 int NumElem = VT.getVectorNumElements(); 7966 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec); 7967 // Find the new index to extract from. 7968 int OrigElt = SVOp->getMaskElt(Elt); 7969 7970 // Extracting an undef index is undef. 7971 if (OrigElt == -1) 7972 return DAG.getUNDEF(NVT); 7973 7974 // Select the right vector half to extract from. 7975 if (OrigElt < NumElem) { 7976 InVec = InVec->getOperand(0); 7977 } else { 7978 InVec = InVec->getOperand(1); 7979 OrigElt -= NumElem; 7980 } 7981 7982 EVT IndexTy = N->getOperand(1).getValueType(); 7983 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, N->getDebugLoc(), NVT, 7984 InVec, DAG.getConstant(OrigElt, IndexTy)); 7985 } 7986 7987 // Perform only after legalization to ensure build_vector / vector_shuffle 7988 // optimizations have already been done. 7989 if (!LegalOperations) return SDValue(); 7990 7991 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size) 7992 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size) 7993 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr) 7994 7995 if (ConstEltNo) { 7996 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue(); 7997 bool NewLoad = false; 7998 bool BCNumEltsChanged = false; 7999 EVT ExtVT = VT.getVectorElementType(); 8000 EVT LVT = ExtVT; 8001 8002 // If the result of load has to be truncated, then it's not necessarily 8003 // profitable. 8004 if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT)) 8005 return SDValue(); 8006 8007 if (InVec.getOpcode() == ISD::BITCAST) { 8008 // Don't duplicate a load with other uses. 8009 if (!InVec.hasOneUse()) 8010 return SDValue(); 8011 8012 EVT BCVT = InVec.getOperand(0).getValueType(); 8013 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType())) 8014 return SDValue(); 8015 if (VT.getVectorNumElements() != BCVT.getVectorNumElements()) 8016 BCNumEltsChanged = true; 8017 InVec = InVec.getOperand(0); 8018 ExtVT = BCVT.getVectorElementType(); 8019 NewLoad = true; 8020 } 8021 8022 LoadSDNode *LN0 = NULL; 8023 const ShuffleVectorSDNode *SVN = NULL; 8024 if (ISD::isNormalLoad(InVec.getNode())) { 8025 LN0 = cast<LoadSDNode>(InVec); 8026 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR && 8027 InVec.getOperand(0).getValueType() == ExtVT && 8028 ISD::isNormalLoad(InVec.getOperand(0).getNode())) { 8029 // Don't duplicate a load with other uses. 8030 if (!InVec.hasOneUse()) 8031 return SDValue(); 8032 8033 LN0 = cast<LoadSDNode>(InVec.getOperand(0)); 8034 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) { 8035 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1) 8036 // => 8037 // (load $addr+1*size) 8038 8039 // Don't duplicate a load with other uses. 8040 if (!InVec.hasOneUse()) 8041 return SDValue(); 8042 8043 // If the bit convert changed the number of elements, it is unsafe 8044 // to examine the mask. 8045 if (BCNumEltsChanged) 8046 return SDValue(); 8047 8048 // Select the input vector, guarding against out of range extract vector. 8049 unsigned NumElems = VT.getVectorNumElements(); 8050 int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt); 8051 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1); 8052 8053 if (InVec.getOpcode() == ISD::BITCAST) { 8054 // Don't duplicate a load with other uses. 8055 if (!InVec.hasOneUse()) 8056 return SDValue(); 8057 8058 InVec = InVec.getOperand(0); 8059 } 8060 if (ISD::isNormalLoad(InVec.getNode())) { 8061 LN0 = cast<LoadSDNode>(InVec); 8062 Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems; 8063 } 8064 } 8065 8066 // Make sure we found a non-volatile load and the extractelement is 8067 // the only use. 8068 if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile()) 8069 return SDValue(); 8070 8071 // If Idx was -1 above, Elt is going to be -1, so just return undef. 8072 if (Elt == -1) 8073 return DAG.getUNDEF(LVT); 8074 8075 unsigned Align = LN0->getAlignment(); 8076 if (NewLoad) { 8077 // Check the resultant load doesn't need a higher alignment than the 8078 // original load. 8079 unsigned NewAlign = 8080 TLI.getTargetData() 8081 ->getABITypeAlignment(LVT.getTypeForEVT(*DAG.getContext())); 8082 8083 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, LVT)) 8084 return SDValue(); 8085 8086 Align = NewAlign; 8087 } 8088 8089 SDValue NewPtr = LN0->getBasePtr(); 8090 unsigned PtrOff = 0; 8091 8092 if (Elt) { 8093 PtrOff = LVT.getSizeInBits() * Elt / 8; 8094 EVT PtrType = NewPtr.getValueType(); 8095 if (TLI.isBigEndian()) 8096 PtrOff = VT.getSizeInBits() / 8 - PtrOff; 8097 NewPtr = DAG.getNode(ISD::ADD, N->getDebugLoc(), PtrType, NewPtr, 8098 DAG.getConstant(PtrOff, PtrType)); 8099 } 8100 8101 // The replacement we need to do here is a little tricky: we need to 8102 // replace an extractelement of a load with a load. 8103 // Use ReplaceAllUsesOfValuesWith to do the replacement. 8104 // Note that this replacement assumes that the extractvalue is the only 8105 // use of the load; that's okay because we don't want to perform this 8106 // transformation in other cases anyway. 8107 SDValue Load; 8108 SDValue Chain; 8109 if (NVT.bitsGT(LVT)) { 8110 // If the result type of vextract is wider than the load, then issue an 8111 // extending load instead. 8112 ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, LVT) 8113 ? ISD::ZEXTLOAD : ISD::EXTLOAD; 8114 Load = DAG.getExtLoad(ExtType, N->getDebugLoc(), NVT, LN0->getChain(), 8115 NewPtr, LN0->getPointerInfo().getWithOffset(PtrOff), 8116 LVT, LN0->isVolatile(), LN0->isNonTemporal(),Align); 8117 Chain = Load.getValue(1); 8118 } else { 8119 Load = DAG.getLoad(LVT, N->getDebugLoc(), LN0->getChain(), NewPtr, 8120 LN0->getPointerInfo().getWithOffset(PtrOff), 8121 LN0->isVolatile(), LN0->isNonTemporal(), 8122 LN0->isInvariant(), Align); 8123 Chain = Load.getValue(1); 8124 if (NVT.bitsLT(LVT)) 8125 Load = DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), NVT, Load); 8126 else 8127 Load = DAG.getNode(ISD::BITCAST, N->getDebugLoc(), NVT, Load); 8128 } 8129 WorkListRemover DeadNodes(*this); 8130 SDValue From[] = { SDValue(N, 0), SDValue(LN0,1) }; 8131 SDValue To[] = { Load, Chain }; 8132 DAG.ReplaceAllUsesOfValuesWith(From, To, 2); 8133 // Since we're explcitly calling ReplaceAllUses, add the new node to the 8134 // worklist explicitly as well. 8135 AddToWorkList(Load.getNode()); 8136 AddUsersToWorkList(Load.getNode()); // Add users too 8137 // Make sure to revisit this node to clean it up; it will usually be dead. 8138 AddToWorkList(N); 8139 return SDValue(N, 0); 8140 } 8141 8142 return SDValue(); 8143} 8144 8145SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) { 8146 unsigned NumInScalars = N->getNumOperands(); 8147 DebugLoc dl = N->getDebugLoc(); 8148 EVT VT = N->getValueType(0); 8149 8150 // A vector built entirely of undefs is undef. 8151 if (ISD::allOperandsUndef(N)) 8152 return DAG.getUNDEF(VT); 8153 8154 // Check to see if this is a BUILD_VECTOR of a bunch of values 8155 // which come from any_extend or zero_extend nodes. If so, we can create 8156 // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR 8157 // optimizations. We do not handle sign-extend because we can't fill the sign 8158 // using shuffles. 8159 EVT SourceType = MVT::Other; 8160 bool AllAnyExt = true; 8161 8162 for (unsigned i = 0; i != NumInScalars; ++i) { 8163 SDValue In = N->getOperand(i); 8164 // Ignore undef inputs. 8165 if (In.getOpcode() == ISD::UNDEF) continue; 8166 8167 bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND; 8168 bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND; 8169 8170 // Abort if the element is not an extension. 8171 if (!ZeroExt && !AnyExt) { 8172 SourceType = MVT::Other; 8173 break; 8174 } 8175 8176 // The input is a ZeroExt or AnyExt. Check the original type. 8177 EVT InTy = In.getOperand(0).getValueType(); 8178 8179 // Check that all of the widened source types are the same. 8180 if (SourceType == MVT::Other) 8181 // First time. 8182 SourceType = InTy; 8183 else if (InTy != SourceType) { 8184 // Multiple income types. Abort. 8185 SourceType = MVT::Other; 8186 break; 8187 } 8188 8189 // Check if all of the extends are ANY_EXTENDs. 8190 AllAnyExt &= AnyExt; 8191 } 8192 8193 // In order to have valid types, all of the inputs must be extended from the 8194 // same source type and all of the inputs must be any or zero extend. 8195 // Scalar sizes must be a power of two. 8196 EVT OutScalarTy = N->getValueType(0).getScalarType(); 8197 bool ValidTypes = SourceType != MVT::Other && 8198 isPowerOf2_32(OutScalarTy.getSizeInBits()) && 8199 isPowerOf2_32(SourceType.getSizeInBits()); 8200 8201 // We perform this optimization post type-legalization because 8202 // the type-legalizer often scalarizes integer-promoted vectors. 8203 // Performing this optimization before may create bit-casts which 8204 // will be type-legalized to complex code sequences. 8205 // We perform this optimization only before the operation legalizer because we 8206 // may introduce illegal operations. 8207 // Create a new simpler BUILD_VECTOR sequence which other optimizations can 8208 // turn into a single shuffle instruction. 8209 if ((Level == AfterLegalizeVectorOps || Level == AfterLegalizeTypes) && 8210 ValidTypes) { 8211 bool isLE = TLI.isLittleEndian(); 8212 unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits(); 8213 assert(ElemRatio > 1 && "Invalid element size ratio"); 8214 SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType): 8215 DAG.getConstant(0, SourceType); 8216 8217 unsigned NewBVElems = ElemRatio * N->getValueType(0).getVectorNumElements(); 8218 SmallVector<SDValue, 8> Ops(NewBVElems, Filler); 8219 8220 // Populate the new build_vector 8221 for (unsigned i=0; i < N->getNumOperands(); ++i) { 8222 SDValue Cast = N->getOperand(i); 8223 assert((Cast.getOpcode() == ISD::ANY_EXTEND || 8224 Cast.getOpcode() == ISD::ZERO_EXTEND || 8225 Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode"); 8226 SDValue In; 8227 if (Cast.getOpcode() == ISD::UNDEF) 8228 In = DAG.getUNDEF(SourceType); 8229 else 8230 In = Cast->getOperand(0); 8231 unsigned Index = isLE ? (i * ElemRatio) : 8232 (i * ElemRatio + (ElemRatio - 1)); 8233 8234 assert(Index < Ops.size() && "Invalid index"); 8235 Ops[Index] = In; 8236 } 8237 8238 // The type of the new BUILD_VECTOR node. 8239 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems); 8240 assert(VecVT.getSizeInBits() == N->getValueType(0).getSizeInBits() && 8241 "Invalid vector size"); 8242 // Check if the new vector type is legal. 8243 if (!isTypeLegal(VecVT)) return SDValue(); 8244 8245 // Make the new BUILD_VECTOR. 8246 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(), 8247 VecVT, &Ops[0], Ops.size()); 8248 8249 // The new BUILD_VECTOR node has the potential to be further optimized. 8250 AddToWorkList(BV.getNode()); 8251 // Bitcast to the desired type. 8252 return DAG.getNode(ISD::BITCAST, dl, N->getValueType(0), BV); 8253 } 8254 8255 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT 8256 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from 8257 // at most two distinct vectors, turn this into a shuffle node. 8258 8259 // May only combine to shuffle after legalize if shuffle is legal. 8260 if (LegalOperations && 8261 !TLI.isOperationLegalOrCustom(ISD::VECTOR_SHUFFLE, VT)) 8262 return SDValue(); 8263 8264 SDValue VecIn1, VecIn2; 8265 for (unsigned i = 0; i != NumInScalars; ++i) { 8266 // Ignore undef inputs. 8267 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue; 8268 8269 // If this input is something other than a EXTRACT_VECTOR_ELT with a 8270 // constant index, bail out. 8271 if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT || 8272 !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) { 8273 VecIn1 = VecIn2 = SDValue(0, 0); 8274 break; 8275 } 8276 8277 // We allow up to two distinct input vectors. 8278 SDValue ExtractedFromVec = N->getOperand(i).getOperand(0); 8279 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2) 8280 continue; 8281 8282 if (VecIn1.getNode() == 0) { 8283 VecIn1 = ExtractedFromVec; 8284 } else if (VecIn2.getNode() == 0) { 8285 VecIn2 = ExtractedFromVec; 8286 } else { 8287 // Too many inputs. 8288 VecIn1 = VecIn2 = SDValue(0, 0); 8289 break; 8290 } 8291 } 8292 8293 // If everything is good, we can make a shuffle operation. 8294 if (VecIn1.getNode()) { 8295 SmallVector<int, 8> Mask; 8296 for (unsigned i = 0; i != NumInScalars; ++i) { 8297 if (N->getOperand(i).getOpcode() == ISD::UNDEF) { 8298 Mask.push_back(-1); 8299 continue; 8300 } 8301 8302 // If extracting from the first vector, just use the index directly. 8303 SDValue Extract = N->getOperand(i); 8304 SDValue ExtVal = Extract.getOperand(1); 8305 if (Extract.getOperand(0) == VecIn1) { 8306 unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue(); 8307 if (ExtIndex > VT.getVectorNumElements()) 8308 return SDValue(); 8309 8310 Mask.push_back(ExtIndex); 8311 continue; 8312 } 8313 8314 // Otherwise, use InIdx + VecSize 8315 unsigned Idx = cast<ConstantSDNode>(ExtVal)->getZExtValue(); 8316 Mask.push_back(Idx+NumInScalars); 8317 } 8318 8319 // We can't generate a shuffle node with mismatched input and output types. 8320 // Attempt to transform a single input vector to the correct type. 8321 if ((VT != VecIn1.getValueType())) { 8322 // We don't support shuffeling between TWO values of different types. 8323 if (VecIn2.getNode() != 0) 8324 return SDValue(); 8325 8326 // We only support widening of vectors which are half the size of the 8327 // output registers. For example XMM->YMM widening on X86 with AVX. 8328 if (VecIn1.getValueType().getSizeInBits()*2 != VT.getSizeInBits()) 8329 return SDValue(); 8330 8331 // If the input vector type has a different base type to the output 8332 // vector type, bail out. 8333 if (VecIn1.getValueType().getVectorElementType() != 8334 VT.getVectorElementType()) 8335 return SDValue(); 8336 8337 // Widen the input vector by adding undef values. 8338 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, N->getDebugLoc(), VT, 8339 VecIn1, DAG.getUNDEF(VecIn1.getValueType())); 8340 } 8341 8342 // If VecIn2 is unused then change it to undef. 8343 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT); 8344 8345 // Check that we were able to transform all incoming values to the same 8346 // type. 8347 if (VecIn2.getValueType() != VecIn1.getValueType() || 8348 VecIn1.getValueType() != VT) 8349 return SDValue(); 8350 8351 // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes. 8352 if (!isTypeLegal(VT)) 8353 return SDValue(); 8354 8355 // Return the new VECTOR_SHUFFLE node. 8356 SDValue Ops[2]; 8357 Ops[0] = VecIn1; 8358 Ops[1] = VecIn2; 8359 return DAG.getVectorShuffle(VT, N->getDebugLoc(), Ops[0], Ops[1], &Mask[0]); 8360 } 8361 8362 return SDValue(); 8363} 8364 8365SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) { 8366 // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of 8367 // EXTRACT_SUBVECTOR operations. If so, and if the EXTRACT_SUBVECTOR vector 8368 // inputs come from at most two distinct vectors, turn this into a shuffle 8369 // node. 8370 8371 // If we only have one input vector, we don't need to do any concatenation. 8372 if (N->getNumOperands() == 1) 8373 return N->getOperand(0); 8374 8375 // Check if all of the operands are undefs. 8376 if (ISD::allOperandsUndef(N)) 8377 return DAG.getUNDEF(N->getValueType(0)); 8378 8379 return SDValue(); 8380} 8381 8382SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) { 8383 EVT NVT = N->getValueType(0); 8384 SDValue V = N->getOperand(0); 8385 8386 if (V->getOpcode() == ISD::INSERT_SUBVECTOR) { 8387 // Handle only simple case where vector being inserted and vector 8388 // being extracted are of same type, and are half size of larger vectors. 8389 EVT BigVT = V->getOperand(0).getValueType(); 8390 EVT SmallVT = V->getOperand(1).getValueType(); 8391 if (NVT != SmallVT || NVT.getSizeInBits()*2 != BigVT.getSizeInBits()) 8392 return SDValue(); 8393 8394 // Only handle cases where both indexes are constants with the same type. 8395 ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(N->getOperand(1)); 8396 ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(V->getOperand(2)); 8397 8398 if (InsIdx && ExtIdx && 8399 InsIdx->getValueType(0).getSizeInBits() <= 64 && 8400 ExtIdx->getValueType(0).getSizeInBits() <= 64) { 8401 // Combine: 8402 // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx) 8403 // Into: 8404 // indices are equal => V1 8405 // otherwise => (extract_subvec V1, ExtIdx) 8406 if (InsIdx->getZExtValue() == ExtIdx->getZExtValue()) 8407 return V->getOperand(1); 8408 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, N->getDebugLoc(), NVT, 8409 V->getOperand(0), N->getOperand(1)); 8410 } 8411 } 8412 8413 return SDValue(); 8414} 8415 8416SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) { 8417 EVT VT = N->getValueType(0); 8418 unsigned NumElts = VT.getVectorNumElements(); 8419 8420 SDValue N0 = N->getOperand(0); 8421 SDValue N1 = N->getOperand(1); 8422 8423 assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG"); 8424 8425 // Canonicalize shuffle undef, undef -> undef 8426 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF) 8427 return DAG.getUNDEF(VT); 8428 8429 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N); 8430 8431 // Canonicalize shuffle v, v -> v, undef 8432 if (N0 == N1) { 8433 SmallVector<int, 8> NewMask; 8434 for (unsigned i = 0; i != NumElts; ++i) { 8435 int Idx = SVN->getMaskElt(i); 8436 if (Idx >= (int)NumElts) Idx -= NumElts; 8437 NewMask.push_back(Idx); 8438 } 8439 return DAG.getVectorShuffle(VT, N->getDebugLoc(), N0, DAG.getUNDEF(VT), 8440 &NewMask[0]); 8441 } 8442 8443 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask. 8444 if (N0.getOpcode() == ISD::UNDEF) { 8445 SmallVector<int, 8> NewMask; 8446 for (unsigned i = 0; i != NumElts; ++i) { 8447 int Idx = SVN->getMaskElt(i); 8448 if (Idx >= 0) { 8449 if (Idx < (int)NumElts) 8450 Idx += NumElts; 8451 else 8452 Idx -= NumElts; 8453 } 8454 NewMask.push_back(Idx); 8455 } 8456 return DAG.getVectorShuffle(VT, N->getDebugLoc(), N1, DAG.getUNDEF(VT), 8457 &NewMask[0]); 8458 } 8459 8460 // Remove references to rhs if it is undef 8461 if (N1.getOpcode() == ISD::UNDEF) { 8462 bool Changed = false; 8463 SmallVector<int, 8> NewMask; 8464 for (unsigned i = 0; i != NumElts; ++i) { 8465 int Idx = SVN->getMaskElt(i); 8466 if (Idx >= (int)NumElts) { 8467 Idx = -1; 8468 Changed = true; 8469 } 8470 NewMask.push_back(Idx); 8471 } 8472 if (Changed) 8473 return DAG.getVectorShuffle(VT, N->getDebugLoc(), N0, N1, &NewMask[0]); 8474 } 8475 8476 // If it is a splat, check if the argument vector is another splat or a 8477 // build_vector with all scalar elements the same. 8478 if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) { 8479 SDNode *V = N0.getNode(); 8480 8481 // If this is a bit convert that changes the element type of the vector but 8482 // not the number of vector elements, look through it. Be careful not to 8483 // look though conversions that change things like v4f32 to v2f64. 8484 if (V->getOpcode() == ISD::BITCAST) { 8485 SDValue ConvInput = V->getOperand(0); 8486 if (ConvInput.getValueType().isVector() && 8487 ConvInput.getValueType().getVectorNumElements() == NumElts) 8488 V = ConvInput.getNode(); 8489 } 8490 8491 if (V->getOpcode() == ISD::BUILD_VECTOR) { 8492 assert(V->getNumOperands() == NumElts && 8493 "BUILD_VECTOR has wrong number of operands"); 8494 SDValue Base; 8495 bool AllSame = true; 8496 for (unsigned i = 0; i != NumElts; ++i) { 8497 if (V->getOperand(i).getOpcode() != ISD::UNDEF) { 8498 Base = V->getOperand(i); 8499 break; 8500 } 8501 } 8502 // Splat of <u, u, u, u>, return <u, u, u, u> 8503 if (!Base.getNode()) 8504 return N0; 8505 for (unsigned i = 0; i != NumElts; ++i) { 8506 if (V->getOperand(i) != Base) { 8507 AllSame = false; 8508 break; 8509 } 8510 } 8511 // Splat of <x, x, x, x>, return <x, x, x, x> 8512 if (AllSame) 8513 return N0; 8514 } 8515 } 8516 8517 // If this shuffle node is simply a swizzle of another shuffle node, 8518 // and it reverses the swizzle of the previous shuffle then we can 8519 // optimize shuffle(shuffle(x, undef), undef) -> x. 8520 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG && 8521 N1.getOpcode() == ISD::UNDEF) { 8522 8523 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0); 8524 8525 // Shuffle nodes can only reverse shuffles with a single non-undef value. 8526 if (N0.getOperand(1).getOpcode() != ISD::UNDEF) 8527 return SDValue(); 8528 8529 // The incoming shuffle must be of the same type as the result of the 8530 // current shuffle. 8531 assert(OtherSV->getOperand(0).getValueType() == VT && 8532 "Shuffle types don't match"); 8533 8534 for (unsigned i = 0; i != NumElts; ++i) { 8535 int Idx = SVN->getMaskElt(i); 8536 assert(Idx < (int)NumElts && "Index references undef operand"); 8537 // Next, this index comes from the first value, which is the incoming 8538 // shuffle. Adopt the incoming index. 8539 if (Idx >= 0) 8540 Idx = OtherSV->getMaskElt(Idx); 8541 8542 // The combined shuffle must map each index to itself. 8543 if (Idx >= 0 && (unsigned)Idx != i) 8544 return SDValue(); 8545 } 8546 8547 return OtherSV->getOperand(0); 8548 } 8549 8550 return SDValue(); 8551} 8552 8553SDValue DAGCombiner::visitMEMBARRIER(SDNode* N) { 8554 if (!TLI.getShouldFoldAtomicFences()) 8555 return SDValue(); 8556 8557 SDValue atomic = N->getOperand(0); 8558 switch (atomic.getOpcode()) { 8559 case ISD::ATOMIC_CMP_SWAP: 8560 case ISD::ATOMIC_SWAP: 8561 case ISD::ATOMIC_LOAD_ADD: 8562 case ISD::ATOMIC_LOAD_SUB: 8563 case ISD::ATOMIC_LOAD_AND: 8564 case ISD::ATOMIC_LOAD_OR: 8565 case ISD::ATOMIC_LOAD_XOR: 8566 case ISD::ATOMIC_LOAD_NAND: 8567 case ISD::ATOMIC_LOAD_MIN: 8568 case ISD::ATOMIC_LOAD_MAX: 8569 case ISD::ATOMIC_LOAD_UMIN: 8570 case ISD::ATOMIC_LOAD_UMAX: 8571 break; 8572 default: 8573 return SDValue(); 8574 } 8575 8576 SDValue fence = atomic.getOperand(0); 8577 if (fence.getOpcode() != ISD::MEMBARRIER) 8578 return SDValue(); 8579 8580 switch (atomic.getOpcode()) { 8581 case ISD::ATOMIC_CMP_SWAP: 8582 return SDValue(DAG.UpdateNodeOperands(atomic.getNode(), 8583 fence.getOperand(0), 8584 atomic.getOperand(1), atomic.getOperand(2), 8585 atomic.getOperand(3)), atomic.getResNo()); 8586 case ISD::ATOMIC_SWAP: 8587 case ISD::ATOMIC_LOAD_ADD: 8588 case ISD::ATOMIC_LOAD_SUB: 8589 case ISD::ATOMIC_LOAD_AND: 8590 case ISD::ATOMIC_LOAD_OR: 8591 case ISD::ATOMIC_LOAD_XOR: 8592 case ISD::ATOMIC_LOAD_NAND: 8593 case ISD::ATOMIC_LOAD_MIN: 8594 case ISD::ATOMIC_LOAD_MAX: 8595 case ISD::ATOMIC_LOAD_UMIN: 8596 case ISD::ATOMIC_LOAD_UMAX: 8597 return SDValue(DAG.UpdateNodeOperands(atomic.getNode(), 8598 fence.getOperand(0), 8599 atomic.getOperand(1), atomic.getOperand(2)), 8600 atomic.getResNo()); 8601 default: 8602 return SDValue(); 8603 } 8604} 8605 8606/// XformToShuffleWithZero - Returns a vector_shuffle if it able to transform 8607/// an AND to a vector_shuffle with the destination vector and a zero vector. 8608/// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==> 8609/// vector_shuffle V, Zero, <0, 4, 2, 4> 8610SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) { 8611 EVT VT = N->getValueType(0); 8612 DebugLoc dl = N->getDebugLoc(); 8613 SDValue LHS = N->getOperand(0); 8614 SDValue RHS = N->getOperand(1); 8615 if (N->getOpcode() == ISD::AND) { 8616 if (RHS.getOpcode() == ISD::BITCAST) 8617 RHS = RHS.getOperand(0); 8618 if (RHS.getOpcode() == ISD::BUILD_VECTOR) { 8619 SmallVector<int, 8> Indices; 8620 unsigned NumElts = RHS.getNumOperands(); 8621 for (unsigned i = 0; i != NumElts; ++i) { 8622 SDValue Elt = RHS.getOperand(i); 8623 if (!isa<ConstantSDNode>(Elt)) 8624 return SDValue(); 8625 8626 if (cast<ConstantSDNode>(Elt)->isAllOnesValue()) 8627 Indices.push_back(i); 8628 else if (cast<ConstantSDNode>(Elt)->isNullValue()) 8629 Indices.push_back(NumElts); 8630 else 8631 return SDValue(); 8632 } 8633 8634 // Let's see if the target supports this vector_shuffle. 8635 EVT RVT = RHS.getValueType(); 8636 if (!TLI.isVectorClearMaskLegal(Indices, RVT)) 8637 return SDValue(); 8638 8639 // Return the new VECTOR_SHUFFLE node. 8640 EVT EltVT = RVT.getVectorElementType(); 8641 SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(), 8642 DAG.getConstant(0, EltVT)); 8643 SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(), 8644 RVT, &ZeroOps[0], ZeroOps.size()); 8645 LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS); 8646 SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]); 8647 return DAG.getNode(ISD::BITCAST, dl, VT, Shuf); 8648 } 8649 } 8650 8651 return SDValue(); 8652} 8653 8654/// SimplifyVBinOp - Visit a binary vector operation, like ADD. 8655SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) { 8656 // After legalize, the target may be depending on adds and other 8657 // binary ops to provide legal ways to construct constants or other 8658 // things. Simplifying them may result in a loss of legality. 8659 if (LegalOperations) return SDValue(); 8660 8661 assert(N->getValueType(0).isVector() && 8662 "SimplifyVBinOp only works on vectors!"); 8663 8664 SDValue LHS = N->getOperand(0); 8665 SDValue RHS = N->getOperand(1); 8666 SDValue Shuffle = XformToShuffleWithZero(N); 8667 if (Shuffle.getNode()) return Shuffle; 8668 8669 // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold 8670 // this operation. 8671 if (LHS.getOpcode() == ISD::BUILD_VECTOR && 8672 RHS.getOpcode() == ISD::BUILD_VECTOR) { 8673 SmallVector<SDValue, 8> Ops; 8674 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) { 8675 SDValue LHSOp = LHS.getOperand(i); 8676 SDValue RHSOp = RHS.getOperand(i); 8677 // If these two elements can't be folded, bail out. 8678 if ((LHSOp.getOpcode() != ISD::UNDEF && 8679 LHSOp.getOpcode() != ISD::Constant && 8680 LHSOp.getOpcode() != ISD::ConstantFP) || 8681 (RHSOp.getOpcode() != ISD::UNDEF && 8682 RHSOp.getOpcode() != ISD::Constant && 8683 RHSOp.getOpcode() != ISD::ConstantFP)) 8684 break; 8685 8686 // Can't fold divide by zero. 8687 if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV || 8688 N->getOpcode() == ISD::FDIV) { 8689 if ((RHSOp.getOpcode() == ISD::Constant && 8690 cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) || 8691 (RHSOp.getOpcode() == ISD::ConstantFP && 8692 cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero())) 8693 break; 8694 } 8695 8696 EVT VT = LHSOp.getValueType(); 8697 EVT RVT = RHSOp.getValueType(); 8698 if (RVT != VT) { 8699 // Integer BUILD_VECTOR operands may have types larger than the element 8700 // size (e.g., when the element type is not legal). Prior to type 8701 // legalization, the types may not match between the two BUILD_VECTORS. 8702 // Truncate one of the operands to make them match. 8703 if (RVT.getSizeInBits() > VT.getSizeInBits()) { 8704 RHSOp = DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, RHSOp); 8705 } else { 8706 LHSOp = DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), RVT, LHSOp); 8707 VT = RVT; 8708 } 8709 } 8710 SDValue FoldOp = DAG.getNode(N->getOpcode(), LHS.getDebugLoc(), VT, 8711 LHSOp, RHSOp); 8712 if (FoldOp.getOpcode() != ISD::UNDEF && 8713 FoldOp.getOpcode() != ISD::Constant && 8714 FoldOp.getOpcode() != ISD::ConstantFP) 8715 break; 8716 Ops.push_back(FoldOp); 8717 AddToWorkList(FoldOp.getNode()); 8718 } 8719 8720 if (Ops.size() == LHS.getNumOperands()) 8721 return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(), 8722 LHS.getValueType(), &Ops[0], Ops.size()); 8723 } 8724 8725 return SDValue(); 8726} 8727 8728/// SimplifyVUnaryOp - Visit a binary vector operation, like FABS/FNEG. 8729SDValue DAGCombiner::SimplifyVUnaryOp(SDNode *N) { 8730 // After legalize, the target may be depending on adds and other 8731 // binary ops to provide legal ways to construct constants or other 8732 // things. Simplifying them may result in a loss of legality. 8733 if (LegalOperations) return SDValue(); 8734 8735 assert(N->getValueType(0).isVector() && 8736 "SimplifyVUnaryOp only works on vectors!"); 8737 8738 SDValue N0 = N->getOperand(0); 8739 8740 if (N0.getOpcode() != ISD::BUILD_VECTOR) 8741 return SDValue(); 8742 8743 // Operand is a BUILD_VECTOR node, see if we can constant fold it. 8744 SmallVector<SDValue, 8> Ops; 8745 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) { 8746 SDValue Op = N0.getOperand(i); 8747 if (Op.getOpcode() != ISD::UNDEF && 8748 Op.getOpcode() != ISD::ConstantFP) 8749 break; 8750 EVT EltVT = Op.getValueType(); 8751 SDValue FoldOp = DAG.getNode(N->getOpcode(), N0.getDebugLoc(), EltVT, Op); 8752 if (FoldOp.getOpcode() != ISD::UNDEF && 8753 FoldOp.getOpcode() != ISD::ConstantFP) 8754 break; 8755 Ops.push_back(FoldOp); 8756 AddToWorkList(FoldOp.getNode()); 8757 } 8758 8759 if (Ops.size() != N0.getNumOperands()) 8760 return SDValue(); 8761 8762 return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(), 8763 N0.getValueType(), &Ops[0], Ops.size()); 8764} 8765 8766SDValue DAGCombiner::SimplifySelect(DebugLoc DL, SDValue N0, 8767 SDValue N1, SDValue N2){ 8768 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!"); 8769 8770 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2, 8771 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 8772 8773 // If we got a simplified select_cc node back from SimplifySelectCC, then 8774 // break it down into a new SETCC node, and a new SELECT node, and then return 8775 // the SELECT node, since we were called with a SELECT node. 8776 if (SCC.getNode()) { 8777 // Check to see if we got a select_cc back (to turn into setcc/select). 8778 // Otherwise, just return whatever node we got back, like fabs. 8779 if (SCC.getOpcode() == ISD::SELECT_CC) { 8780 SDValue SETCC = DAG.getNode(ISD::SETCC, N0.getDebugLoc(), 8781 N0.getValueType(), 8782 SCC.getOperand(0), SCC.getOperand(1), 8783 SCC.getOperand(4)); 8784 AddToWorkList(SETCC.getNode()); 8785 return DAG.getNode(ISD::SELECT, SCC.getDebugLoc(), SCC.getValueType(), 8786 SCC.getOperand(2), SCC.getOperand(3), SETCC); 8787 } 8788 8789 return SCC; 8790 } 8791 return SDValue(); 8792} 8793 8794/// SimplifySelectOps - Given a SELECT or a SELECT_CC node, where LHS and RHS 8795/// are the two values being selected between, see if we can simplify the 8796/// select. Callers of this should assume that TheSelect is deleted if this 8797/// returns true. As such, they should return the appropriate thing (e.g. the 8798/// node) back to the top-level of the DAG combiner loop to avoid it being 8799/// looked at. 8800bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS, 8801 SDValue RHS) { 8802 8803 // Cannot simplify select with vector condition 8804 if (TheSelect->getOperand(0).getValueType().isVector()) return false; 8805 8806 // If this is a select from two identical things, try to pull the operation 8807 // through the select. 8808 if (LHS.getOpcode() != RHS.getOpcode() || 8809 !LHS.hasOneUse() || !RHS.hasOneUse()) 8810 return false; 8811 8812 // If this is a load and the token chain is identical, replace the select 8813 // of two loads with a load through a select of the address to load from. 8814 // This triggers in things like "select bool X, 10.0, 123.0" after the FP 8815 // constants have been dropped into the constant pool. 8816 if (LHS.getOpcode() == ISD::LOAD) { 8817 LoadSDNode *LLD = cast<LoadSDNode>(LHS); 8818 LoadSDNode *RLD = cast<LoadSDNode>(RHS); 8819 8820 // Token chains must be identical. 8821 if (LHS.getOperand(0) != RHS.getOperand(0) || 8822 // Do not let this transformation reduce the number of volatile loads. 8823 LLD->isVolatile() || RLD->isVolatile() || 8824 // If this is an EXTLOAD, the VT's must match. 8825 LLD->getMemoryVT() != RLD->getMemoryVT() || 8826 // If this is an EXTLOAD, the kind of extension must match. 8827 (LLD->getExtensionType() != RLD->getExtensionType() && 8828 // The only exception is if one of the extensions is anyext. 8829 LLD->getExtensionType() != ISD::EXTLOAD && 8830 RLD->getExtensionType() != ISD::EXTLOAD) || 8831 // FIXME: this discards src value information. This is 8832 // over-conservative. It would be beneficial to be able to remember 8833 // both potential memory locations. Since we are discarding 8834 // src value info, don't do the transformation if the memory 8835 // locations are not in the default address space. 8836 LLD->getPointerInfo().getAddrSpace() != 0 || 8837 RLD->getPointerInfo().getAddrSpace() != 0) 8838 return false; 8839 8840 // Check that the select condition doesn't reach either load. If so, 8841 // folding this will induce a cycle into the DAG. If not, this is safe to 8842 // xform, so create a select of the addresses. 8843 SDValue Addr; 8844 if (TheSelect->getOpcode() == ISD::SELECT) { 8845 SDNode *CondNode = TheSelect->getOperand(0).getNode(); 8846 if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) || 8847 (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode))) 8848 return false; 8849 Addr = DAG.getNode(ISD::SELECT, TheSelect->getDebugLoc(), 8850 LLD->getBasePtr().getValueType(), 8851 TheSelect->getOperand(0), LLD->getBasePtr(), 8852 RLD->getBasePtr()); 8853 } else { // Otherwise SELECT_CC 8854 SDNode *CondLHS = TheSelect->getOperand(0).getNode(); 8855 SDNode *CondRHS = TheSelect->getOperand(1).getNode(); 8856 8857 if ((LLD->hasAnyUseOfValue(1) && 8858 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) || 8859 (RLD->hasAnyUseOfValue(1) && 8860 (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS)))) 8861 return false; 8862 8863 Addr = DAG.getNode(ISD::SELECT_CC, TheSelect->getDebugLoc(), 8864 LLD->getBasePtr().getValueType(), 8865 TheSelect->getOperand(0), 8866 TheSelect->getOperand(1), 8867 LLD->getBasePtr(), RLD->getBasePtr(), 8868 TheSelect->getOperand(4)); 8869 } 8870 8871 SDValue Load; 8872 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) { 8873 Load = DAG.getLoad(TheSelect->getValueType(0), 8874 TheSelect->getDebugLoc(), 8875 // FIXME: Discards pointer info. 8876 LLD->getChain(), Addr, MachinePointerInfo(), 8877 LLD->isVolatile(), LLD->isNonTemporal(), 8878 LLD->isInvariant(), LLD->getAlignment()); 8879 } else { 8880 Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ? 8881 RLD->getExtensionType() : LLD->getExtensionType(), 8882 TheSelect->getDebugLoc(), 8883 TheSelect->getValueType(0), 8884 // FIXME: Discards pointer info. 8885 LLD->getChain(), Addr, MachinePointerInfo(), 8886 LLD->getMemoryVT(), LLD->isVolatile(), 8887 LLD->isNonTemporal(), LLD->getAlignment()); 8888 } 8889 8890 // Users of the select now use the result of the load. 8891 CombineTo(TheSelect, Load); 8892 8893 // Users of the old loads now use the new load's chain. We know the 8894 // old-load value is dead now. 8895 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1)); 8896 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1)); 8897 return true; 8898 } 8899 8900 return false; 8901} 8902 8903/// SimplifySelectCC - Simplify an expression of the form (N0 cond N1) ? N2 : N3 8904/// where 'cond' is the comparison specified by CC. 8905SDValue DAGCombiner::SimplifySelectCC(DebugLoc DL, SDValue N0, SDValue N1, 8906 SDValue N2, SDValue N3, 8907 ISD::CondCode CC, bool NotExtCompare) { 8908 // (x ? y : y) -> y. 8909 if (N2 == N3) return N2; 8910 8911 EVT VT = N2.getValueType(); 8912 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode()); 8913 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode()); 8914 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode()); 8915 8916 // Determine if the condition we're dealing with is constant 8917 SDValue SCC = SimplifySetCC(TLI.getSetCCResultType(N0.getValueType()), 8918 N0, N1, CC, DL, false); 8919 if (SCC.getNode()) AddToWorkList(SCC.getNode()); 8920 ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode()); 8921 8922 // fold select_cc true, x, y -> x 8923 if (SCCC && !SCCC->isNullValue()) 8924 return N2; 8925 // fold select_cc false, x, y -> y 8926 if (SCCC && SCCC->isNullValue()) 8927 return N3; 8928 8929 // Check to see if we can simplify the select into an fabs node 8930 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) { 8931 // Allow either -0.0 or 0.0 8932 if (CFP->getValueAPF().isZero()) { 8933 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs 8934 if ((CC == ISD::SETGE || CC == ISD::SETGT) && 8935 N0 == N2 && N3.getOpcode() == ISD::FNEG && 8936 N2 == N3.getOperand(0)) 8937 return DAG.getNode(ISD::FABS, DL, VT, N0); 8938 8939 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs 8940 if ((CC == ISD::SETLT || CC == ISD::SETLE) && 8941 N0 == N3 && N2.getOpcode() == ISD::FNEG && 8942 N2.getOperand(0) == N3) 8943 return DAG.getNode(ISD::FABS, DL, VT, N3); 8944 } 8945 } 8946 8947 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)" 8948 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0 8949 // in it. This is a win when the constant is not otherwise available because 8950 // it replaces two constant pool loads with one. We only do this if the FP 8951 // type is known to be legal, because if it isn't, then we are before legalize 8952 // types an we want the other legalization to happen first (e.g. to avoid 8953 // messing with soft float) and if the ConstantFP is not legal, because if 8954 // it is legal, we may not need to store the FP constant in a constant pool. 8955 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2)) 8956 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) { 8957 if (TLI.isTypeLegal(N2.getValueType()) && 8958 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) != 8959 TargetLowering::Legal) && 8960 // If both constants have multiple uses, then we won't need to do an 8961 // extra load, they are likely around in registers for other users. 8962 (TV->hasOneUse() || FV->hasOneUse())) { 8963 Constant *Elts[] = { 8964 const_cast<ConstantFP*>(FV->getConstantFPValue()), 8965 const_cast<ConstantFP*>(TV->getConstantFPValue()) 8966 }; 8967 Type *FPTy = Elts[0]->getType(); 8968 const TargetData &TD = *TLI.getTargetData(); 8969 8970 // Create a ConstantArray of the two constants. 8971 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts); 8972 SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(), 8973 TD.getPrefTypeAlignment(FPTy)); 8974 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment(); 8975 8976 // Get the offsets to the 0 and 1 element of the array so that we can 8977 // select between them. 8978 SDValue Zero = DAG.getIntPtrConstant(0); 8979 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType()); 8980 SDValue One = DAG.getIntPtrConstant(EltSize); 8981 8982 SDValue Cond = DAG.getSetCC(DL, 8983 TLI.getSetCCResultType(N0.getValueType()), 8984 N0, N1, CC); 8985 AddToWorkList(Cond.getNode()); 8986 SDValue CstOffset = DAG.getNode(ISD::SELECT, DL, Zero.getValueType(), 8987 Cond, One, Zero); 8988 AddToWorkList(CstOffset.getNode()); 8989 CPIdx = DAG.getNode(ISD::ADD, DL, TLI.getPointerTy(), CPIdx, 8990 CstOffset); 8991 AddToWorkList(CPIdx.getNode()); 8992 return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx, 8993 MachinePointerInfo::getConstantPool(), false, 8994 false, false, Alignment); 8995 8996 } 8997 } 8998 8999 // Check to see if we can perform the "gzip trick", transforming 9000 // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A) 9001 if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT && 9002 (N1C->isNullValue() || // (a < 0) ? b : 0 9003 (N1C->getAPIntValue() == 1 && N0 == N2))) { // (a < 1) ? a : 0 9004 EVT XType = N0.getValueType(); 9005 EVT AType = N2.getValueType(); 9006 if (XType.bitsGE(AType)) { 9007 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a 9008 // single-bit constant. 9009 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) { 9010 unsigned ShCtV = N2C->getAPIntValue().logBase2(); 9011 ShCtV = XType.getSizeInBits()-ShCtV-1; 9012 SDValue ShCt = DAG.getConstant(ShCtV, 9013 getShiftAmountTy(N0.getValueType())); 9014 SDValue Shift = DAG.getNode(ISD::SRL, N0.getDebugLoc(), 9015 XType, N0, ShCt); 9016 AddToWorkList(Shift.getNode()); 9017 9018 if (XType.bitsGT(AType)) { 9019 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift); 9020 AddToWorkList(Shift.getNode()); 9021 } 9022 9023 return DAG.getNode(ISD::AND, DL, AType, Shift, N2); 9024 } 9025 9026 SDValue Shift = DAG.getNode(ISD::SRA, N0.getDebugLoc(), 9027 XType, N0, 9028 DAG.getConstant(XType.getSizeInBits()-1, 9029 getShiftAmountTy(N0.getValueType()))); 9030 AddToWorkList(Shift.getNode()); 9031 9032 if (XType.bitsGT(AType)) { 9033 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift); 9034 AddToWorkList(Shift.getNode()); 9035 } 9036 9037 return DAG.getNode(ISD::AND, DL, AType, Shift, N2); 9038 } 9039 } 9040 9041 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A) 9042 // where y is has a single bit set. 9043 // A plaintext description would be, we can turn the SELECT_CC into an AND 9044 // when the condition can be materialized as an all-ones register. Any 9045 // single bit-test can be materialized as an all-ones register with 9046 // shift-left and shift-right-arith. 9047 if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND && 9048 N0->getValueType(0) == VT && 9049 N1C && N1C->isNullValue() && 9050 N2C && N2C->isNullValue()) { 9051 SDValue AndLHS = N0->getOperand(0); 9052 ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 9053 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) { 9054 // Shift the tested bit over the sign bit. 9055 APInt AndMask = ConstAndRHS->getAPIntValue(); 9056 SDValue ShlAmt = 9057 DAG.getConstant(AndMask.countLeadingZeros(), 9058 getShiftAmountTy(AndLHS.getValueType())); 9059 SDValue Shl = DAG.getNode(ISD::SHL, N0.getDebugLoc(), VT, AndLHS, ShlAmt); 9060 9061 // Now arithmetic right shift it all the way over, so the result is either 9062 // all-ones, or zero. 9063 SDValue ShrAmt = 9064 DAG.getConstant(AndMask.getBitWidth()-1, 9065 getShiftAmountTy(Shl.getValueType())); 9066 SDValue Shr = DAG.getNode(ISD::SRA, N0.getDebugLoc(), VT, Shl, ShrAmt); 9067 9068 return DAG.getNode(ISD::AND, DL, VT, Shr, N3); 9069 } 9070 } 9071 9072 // fold select C, 16, 0 -> shl C, 4 9073 if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() && 9074 TLI.getBooleanContents(N0.getValueType().isVector()) == 9075 TargetLowering::ZeroOrOneBooleanContent) { 9076 9077 // If the caller doesn't want us to simplify this into a zext of a compare, 9078 // don't do it. 9079 if (NotExtCompare && N2C->getAPIntValue() == 1) 9080 return SDValue(); 9081 9082 // Get a SetCC of the condition 9083 // FIXME: Should probably make sure that setcc is legal if we ever have a 9084 // target where it isn't. 9085 SDValue Temp, SCC; 9086 // cast from setcc result type to select result type 9087 if (LegalTypes) { 9088 SCC = DAG.getSetCC(DL, TLI.getSetCCResultType(N0.getValueType()), 9089 N0, N1, CC); 9090 if (N2.getValueType().bitsLT(SCC.getValueType())) 9091 Temp = DAG.getZeroExtendInReg(SCC, N2.getDebugLoc(), N2.getValueType()); 9092 else 9093 Temp = DAG.getNode(ISD::ZERO_EXTEND, N2.getDebugLoc(), 9094 N2.getValueType(), SCC); 9095 } else { 9096 SCC = DAG.getSetCC(N0.getDebugLoc(), MVT::i1, N0, N1, CC); 9097 Temp = DAG.getNode(ISD::ZERO_EXTEND, N2.getDebugLoc(), 9098 N2.getValueType(), SCC); 9099 } 9100 9101 AddToWorkList(SCC.getNode()); 9102 AddToWorkList(Temp.getNode()); 9103 9104 if (N2C->getAPIntValue() == 1) 9105 return Temp; 9106 9107 // shl setcc result by log2 n2c 9108 return DAG.getNode(ISD::SHL, DL, N2.getValueType(), Temp, 9109 DAG.getConstant(N2C->getAPIntValue().logBase2(), 9110 getShiftAmountTy(Temp.getValueType()))); 9111 } 9112 9113 // Check to see if this is the equivalent of setcc 9114 // FIXME: Turn all of these into setcc if setcc if setcc is legal 9115 // otherwise, go ahead with the folds. 9116 if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) { 9117 EVT XType = N0.getValueType(); 9118 if (!LegalOperations || 9119 TLI.isOperationLegal(ISD::SETCC, TLI.getSetCCResultType(XType))) { 9120 SDValue Res = DAG.getSetCC(DL, TLI.getSetCCResultType(XType), N0, N1, CC); 9121 if (Res.getValueType() != VT) 9122 Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res); 9123 return Res; 9124 } 9125 9126 // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X)))) 9127 if (N1C && N1C->isNullValue() && CC == ISD::SETEQ && 9128 (!LegalOperations || 9129 TLI.isOperationLegal(ISD::CTLZ, XType))) { 9130 SDValue Ctlz = DAG.getNode(ISD::CTLZ, N0.getDebugLoc(), XType, N0); 9131 return DAG.getNode(ISD::SRL, DL, XType, Ctlz, 9132 DAG.getConstant(Log2_32(XType.getSizeInBits()), 9133 getShiftAmountTy(Ctlz.getValueType()))); 9134 } 9135 // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1)) 9136 if (N1C && N1C->isNullValue() && CC == ISD::SETGT) { 9137 SDValue NegN0 = DAG.getNode(ISD::SUB, N0.getDebugLoc(), 9138 XType, DAG.getConstant(0, XType), N0); 9139 SDValue NotN0 = DAG.getNOT(N0.getDebugLoc(), N0, XType); 9140 return DAG.getNode(ISD::SRL, DL, XType, 9141 DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0), 9142 DAG.getConstant(XType.getSizeInBits()-1, 9143 getShiftAmountTy(XType))); 9144 } 9145 // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1)) 9146 if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) { 9147 SDValue Sign = DAG.getNode(ISD::SRL, N0.getDebugLoc(), XType, N0, 9148 DAG.getConstant(XType.getSizeInBits()-1, 9149 getShiftAmountTy(N0.getValueType()))); 9150 return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType)); 9151 } 9152 } 9153 9154 // Check to see if this is an integer abs. 9155 // select_cc setg[te] X, 0, X, -X -> 9156 // select_cc setgt X, -1, X, -X -> 9157 // select_cc setl[te] X, 0, -X, X -> 9158 // select_cc setlt X, 1, -X, X -> 9159 // Y = sra (X, size(X)-1); xor (add (X, Y), Y) 9160 if (N1C) { 9161 ConstantSDNode *SubC = NULL; 9162 if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) || 9163 (N1C->isAllOnesValue() && CC == ISD::SETGT)) && 9164 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1)) 9165 SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0)); 9166 else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) || 9167 (N1C->isOne() && CC == ISD::SETLT)) && 9168 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1)) 9169 SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0)); 9170 9171 EVT XType = N0.getValueType(); 9172 if (SubC && SubC->isNullValue() && XType.isInteger()) { 9173 SDValue Shift = DAG.getNode(ISD::SRA, N0.getDebugLoc(), XType, 9174 N0, 9175 DAG.getConstant(XType.getSizeInBits()-1, 9176 getShiftAmountTy(N0.getValueType()))); 9177 SDValue Add = DAG.getNode(ISD::ADD, N0.getDebugLoc(), 9178 XType, N0, Shift); 9179 AddToWorkList(Shift.getNode()); 9180 AddToWorkList(Add.getNode()); 9181 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift); 9182 } 9183 } 9184 9185 return SDValue(); 9186} 9187 9188/// SimplifySetCC - This is a stub for TargetLowering::SimplifySetCC. 9189SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0, 9190 SDValue N1, ISD::CondCode Cond, 9191 DebugLoc DL, bool foldBooleans) { 9192 TargetLowering::DAGCombinerInfo 9193 DagCombineInfo(DAG, !LegalTypes, !LegalOperations, false, this); 9194 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL); 9195} 9196 9197/// BuildSDIVSequence - Given an ISD::SDIV node expressing a divide by constant, 9198/// return a DAG expression to select that will generate the same value by 9199/// multiplying by a magic number. See: 9200/// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html> 9201SDValue DAGCombiner::BuildSDIV(SDNode *N) { 9202 std::vector<SDNode*> Built; 9203 SDValue S = TLI.BuildSDIV(N, DAG, LegalOperations, &Built); 9204 9205 for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end(); 9206 ii != ee; ++ii) 9207 AddToWorkList(*ii); 9208 return S; 9209} 9210 9211/// BuildUDIVSequence - Given an ISD::UDIV node expressing a divide by constant, 9212/// return a DAG expression to select that will generate the same value by 9213/// multiplying by a magic number. See: 9214/// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html> 9215SDValue DAGCombiner::BuildUDIV(SDNode *N) { 9216 std::vector<SDNode*> Built; 9217 SDValue S = TLI.BuildUDIV(N, DAG, LegalOperations, &Built); 9218 9219 for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end(); 9220 ii != ee; ++ii) 9221 AddToWorkList(*ii); 9222 return S; 9223} 9224 9225/// FindBaseOffset - Return true if base is a frame index, which is known not 9226// to alias with anything but itself. Provides base object and offset as 9227// results. 9228static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset, 9229 const GlobalValue *&GV, const void *&CV) { 9230 // Assume it is a primitive operation. 9231 Base = Ptr; Offset = 0; GV = 0; CV = 0; 9232 9233 // If it's an adding a simple constant then integrate the offset. 9234 if (Base.getOpcode() == ISD::ADD) { 9235 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) { 9236 Base = Base.getOperand(0); 9237 Offset += C->getZExtValue(); 9238 } 9239 } 9240 9241 // Return the underlying GlobalValue, and update the Offset. Return false 9242 // for GlobalAddressSDNode since the same GlobalAddress may be represented 9243 // by multiple nodes with different offsets. 9244 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) { 9245 GV = G->getGlobal(); 9246 Offset += G->getOffset(); 9247 return false; 9248 } 9249 9250 // Return the underlying Constant value, and update the Offset. Return false 9251 // for ConstantSDNodes since the same constant pool entry may be represented 9252 // by multiple nodes with different offsets. 9253 if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) { 9254 CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal() 9255 : (const void *)C->getConstVal(); 9256 Offset += C->getOffset(); 9257 return false; 9258 } 9259 // If it's any of the following then it can't alias with anything but itself. 9260 return isa<FrameIndexSDNode>(Base); 9261} 9262 9263/// isAlias - Return true if there is any possibility that the two addresses 9264/// overlap. 9265bool DAGCombiner::isAlias(SDValue Ptr1, int64_t Size1, 9266 const Value *SrcValue1, int SrcValueOffset1, 9267 unsigned SrcValueAlign1, 9268 const MDNode *TBAAInfo1, 9269 SDValue Ptr2, int64_t Size2, 9270 const Value *SrcValue2, int SrcValueOffset2, 9271 unsigned SrcValueAlign2, 9272 const MDNode *TBAAInfo2) const { 9273 // If they are the same then they must be aliases. 9274 if (Ptr1 == Ptr2) return true; 9275 9276 // Gather base node and offset information. 9277 SDValue Base1, Base2; 9278 int64_t Offset1, Offset2; 9279 const GlobalValue *GV1, *GV2; 9280 const void *CV1, *CV2; 9281 bool isFrameIndex1 = FindBaseOffset(Ptr1, Base1, Offset1, GV1, CV1); 9282 bool isFrameIndex2 = FindBaseOffset(Ptr2, Base2, Offset2, GV2, CV2); 9283 9284 // If they have a same base address then check to see if they overlap. 9285 if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2))) 9286 return !((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1); 9287 9288 // It is possible for different frame indices to alias each other, mostly 9289 // when tail call optimization reuses return address slots for arguments. 9290 // To catch this case, look up the actual index of frame indices to compute 9291 // the real alias relationship. 9292 if (isFrameIndex1 && isFrameIndex2) { 9293 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo(); 9294 Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex()); 9295 Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex()); 9296 return !((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1); 9297 } 9298 9299 // Otherwise, if we know what the bases are, and they aren't identical, then 9300 // we know they cannot alias. 9301 if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2)) 9302 return false; 9303 9304 // If we know required SrcValue1 and SrcValue2 have relatively large alignment 9305 // compared to the size and offset of the access, we may be able to prove they 9306 // do not alias. This check is conservative for now to catch cases created by 9307 // splitting vector types. 9308 if ((SrcValueAlign1 == SrcValueAlign2) && 9309 (SrcValueOffset1 != SrcValueOffset2) && 9310 (Size1 == Size2) && (SrcValueAlign1 > Size1)) { 9311 int64_t OffAlign1 = SrcValueOffset1 % SrcValueAlign1; 9312 int64_t OffAlign2 = SrcValueOffset2 % SrcValueAlign1; 9313 9314 // There is no overlap between these relatively aligned accesses of similar 9315 // size, return no alias. 9316 if ((OffAlign1 + Size1) <= OffAlign2 || (OffAlign2 + Size2) <= OffAlign1) 9317 return false; 9318 } 9319 9320 if (CombinerGlobalAA) { 9321 // Use alias analysis information. 9322 int64_t MinOffset = std::min(SrcValueOffset1, SrcValueOffset2); 9323 int64_t Overlap1 = Size1 + SrcValueOffset1 - MinOffset; 9324 int64_t Overlap2 = Size2 + SrcValueOffset2 - MinOffset; 9325 AliasAnalysis::AliasResult AAResult = 9326 AA.alias(AliasAnalysis::Location(SrcValue1, Overlap1, TBAAInfo1), 9327 AliasAnalysis::Location(SrcValue2, Overlap2, TBAAInfo2)); 9328 if (AAResult == AliasAnalysis::NoAlias) 9329 return false; 9330 } 9331 9332 // Otherwise we have to assume they alias. 9333 return true; 9334} 9335 9336/// FindAliasInfo - Extracts the relevant alias information from the memory 9337/// node. Returns true if the operand was a load. 9338bool DAGCombiner::FindAliasInfo(SDNode *N, 9339 SDValue &Ptr, int64_t &Size, 9340 const Value *&SrcValue, 9341 int &SrcValueOffset, 9342 unsigned &SrcValueAlign, 9343 const MDNode *&TBAAInfo) const { 9344 LSBaseSDNode *LS = cast<LSBaseSDNode>(N); 9345 9346 Ptr = LS->getBasePtr(); 9347 Size = LS->getMemoryVT().getSizeInBits() >> 3; 9348 SrcValue = LS->getSrcValue(); 9349 SrcValueOffset = LS->getSrcValueOffset(); 9350 SrcValueAlign = LS->getOriginalAlignment(); 9351 TBAAInfo = LS->getTBAAInfo(); 9352 return isa<LoadSDNode>(LS); 9353} 9354 9355/// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes, 9356/// looking for aliasing nodes and adding them to the Aliases vector. 9357void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain, 9358 SmallVector<SDValue, 8> &Aliases) { 9359 SmallVector<SDValue, 8> Chains; // List of chains to visit. 9360 SmallPtrSet<SDNode *, 16> Visited; // Visited node set. 9361 9362 // Get alias information for node. 9363 SDValue Ptr; 9364 int64_t Size; 9365 const Value *SrcValue; 9366 int SrcValueOffset; 9367 unsigned SrcValueAlign; 9368 const MDNode *SrcTBAAInfo; 9369 bool IsLoad = FindAliasInfo(N, Ptr, Size, SrcValue, SrcValueOffset, 9370 SrcValueAlign, SrcTBAAInfo); 9371 9372 // Starting off. 9373 Chains.push_back(OriginalChain); 9374 unsigned Depth = 0; 9375 9376 // Look at each chain and determine if it is an alias. If so, add it to the 9377 // aliases list. If not, then continue up the chain looking for the next 9378 // candidate. 9379 while (!Chains.empty()) { 9380 SDValue Chain = Chains.back(); 9381 Chains.pop_back(); 9382 9383 // For TokenFactor nodes, look at each operand and only continue up the 9384 // chain until we find two aliases. If we've seen two aliases, assume we'll 9385 // find more and revert to original chain since the xform is unlikely to be 9386 // profitable. 9387 // 9388 // FIXME: The depth check could be made to return the last non-aliasing 9389 // chain we found before we hit a tokenfactor rather than the original 9390 // chain. 9391 if (Depth > 6 || Aliases.size() == 2) { 9392 Aliases.clear(); 9393 Aliases.push_back(OriginalChain); 9394 break; 9395 } 9396 9397 // Don't bother if we've been before. 9398 if (!Visited.insert(Chain.getNode())) 9399 continue; 9400 9401 switch (Chain.getOpcode()) { 9402 case ISD::EntryToken: 9403 // Entry token is ideal chain operand, but handled in FindBetterChain. 9404 break; 9405 9406 case ISD::LOAD: 9407 case ISD::STORE: { 9408 // Get alias information for Chain. 9409 SDValue OpPtr; 9410 int64_t OpSize; 9411 const Value *OpSrcValue; 9412 int OpSrcValueOffset; 9413 unsigned OpSrcValueAlign; 9414 const MDNode *OpSrcTBAAInfo; 9415 bool IsOpLoad = FindAliasInfo(Chain.getNode(), OpPtr, OpSize, 9416 OpSrcValue, OpSrcValueOffset, 9417 OpSrcValueAlign, 9418 OpSrcTBAAInfo); 9419 9420 // If chain is alias then stop here. 9421 if (!(IsLoad && IsOpLoad) && 9422 isAlias(Ptr, Size, SrcValue, SrcValueOffset, SrcValueAlign, 9423 SrcTBAAInfo, 9424 OpPtr, OpSize, OpSrcValue, OpSrcValueOffset, 9425 OpSrcValueAlign, OpSrcTBAAInfo)) { 9426 Aliases.push_back(Chain); 9427 } else { 9428 // Look further up the chain. 9429 Chains.push_back(Chain.getOperand(0)); 9430 ++Depth; 9431 } 9432 break; 9433 } 9434 9435 case ISD::TokenFactor: 9436 // We have to check each of the operands of the token factor for "small" 9437 // token factors, so we queue them up. Adding the operands to the queue 9438 // (stack) in reverse order maintains the original order and increases the 9439 // likelihood that getNode will find a matching token factor (CSE.) 9440 if (Chain.getNumOperands() > 16) { 9441 Aliases.push_back(Chain); 9442 break; 9443 } 9444 for (unsigned n = Chain.getNumOperands(); n;) 9445 Chains.push_back(Chain.getOperand(--n)); 9446 ++Depth; 9447 break; 9448 9449 default: 9450 // For all other instructions we will just have to take what we can get. 9451 Aliases.push_back(Chain); 9452 break; 9453 } 9454 } 9455} 9456 9457/// FindBetterChain - Walk up chain skipping non-aliasing memory nodes, looking 9458/// for a better chain (aliasing node.) 9459SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) { 9460 SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor. 9461 9462 // Accumulate all the aliases to this node. 9463 GatherAllAliases(N, OldChain, Aliases); 9464 9465 // If no operands then chain to entry token. 9466 if (Aliases.size() == 0) 9467 return DAG.getEntryNode(); 9468 9469 // If a single operand then chain to it. We don't need to revisit it. 9470 if (Aliases.size() == 1) 9471 return Aliases[0]; 9472 9473 // Construct a custom tailored token factor. 9474 return DAG.getNode(ISD::TokenFactor, N->getDebugLoc(), MVT::Other, 9475 &Aliases[0], Aliases.size()); 9476} 9477 9478// SelectionDAG::Combine - This is the entry point for the file. 9479// 9480void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA, 9481 CodeGenOpt::Level OptLevel) { 9482 /// run - This is the main entry point to this class. 9483 /// 9484 DAGCombiner(*this, AA, OptLevel).Run(Level); 9485} 9486