DAGCombiner.cpp revision e1679735d6df98bd71808f3c34a32599de0f40a1
1//===-- DAGCombiner.cpp - Implement a DAG node combiner -------------------===// 2// 3// The LLVM Compiler Infrastructure 4// 5// This file is distributed under the University of Illinois Open Source 6// License. See LICENSE.TXT for details. 7// 8//===----------------------------------------------------------------------===// 9// 10// This pass combines dag nodes to form fewer, simpler DAG nodes. It can be run 11// both before and after the DAG is legalized. 12// 13// This pass is not a substitute for the LLVM IR instcombine pass. This pass is 14// primarily intended to handle simplification opportunities that are implicit 15// in the LLVM IR and exposed by the various codegen lowering phases. 16// 17//===----------------------------------------------------------------------===// 18 19#define DEBUG_TYPE "dagcombine" 20#include "llvm/CodeGen/SelectionDAG.h" 21#include "llvm/ADT/SmallPtrSet.h" 22#include "llvm/ADT/Statistic.h" 23#include "llvm/Analysis/AliasAnalysis.h" 24#include "llvm/CodeGen/MachineFrameInfo.h" 25#include "llvm/CodeGen/MachineFunction.h" 26#include "llvm/IR/DataLayout.h" 27#include "llvm/IR/DerivedTypes.h" 28#include "llvm/IR/Function.h" 29#include "llvm/IR/LLVMContext.h" 30#include "llvm/Support/CommandLine.h" 31#include "llvm/Support/Debug.h" 32#include "llvm/Support/ErrorHandling.h" 33#include "llvm/Support/MathExtras.h" 34#include "llvm/Support/raw_ostream.h" 35#include "llvm/Target/TargetLowering.h" 36#include "llvm/Target/TargetMachine.h" 37#include "llvm/Target/TargetOptions.h" 38#include "llvm/Target/TargetRegisterInfo.h" 39#include "llvm/Target/TargetSubtargetInfo.h" 40#include <algorithm> 41using namespace llvm; 42 43STATISTIC(NodesCombined , "Number of dag nodes combined"); 44STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created"); 45STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created"); 46STATISTIC(OpsNarrowed , "Number of load/op/store narrowed"); 47STATISTIC(LdStFP2Int , "Number of fp load/store pairs transformed to int"); 48STATISTIC(SlicedLoads, "Number of load sliced"); 49 50namespace { 51 static cl::opt<bool> 52 CombinerAA("combiner-alias-analysis", cl::Hidden, 53 cl::desc("Turn on alias analysis during testing")); 54 55 static cl::opt<bool> 56 CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden, 57 cl::desc("Include global information in alias analysis")); 58 59 /// Hidden option to stress test load slicing, i.e., when this option 60 /// is enabled, load slicing bypasses most of its profitability guards. 61 static cl::opt<bool> 62 StressLoadSlicing("combiner-stress-load-slicing", cl::Hidden, 63 cl::desc("Bypass the profitability model of load " 64 "slicing"), 65 cl::init(false)); 66 67//------------------------------ DAGCombiner ---------------------------------// 68 69 class DAGCombiner { 70 SelectionDAG &DAG; 71 const TargetLowering &TLI; 72 CombineLevel Level; 73 CodeGenOpt::Level OptLevel; 74 bool LegalOperations; 75 bool LegalTypes; 76 bool ForCodeSize; 77 78 // Worklist of all of the nodes that need to be simplified. 79 // 80 // This has the semantics that when adding to the worklist, 81 // the item added must be next to be processed. It should 82 // also only appear once. The naive approach to this takes 83 // linear time. 84 // 85 // To reduce the insert/remove time to logarithmic, we use 86 // a set and a vector to maintain our worklist. 87 // 88 // The set contains the items on the worklist, but does not 89 // maintain the order they should be visited. 90 // 91 // The vector maintains the order nodes should be visited, but may 92 // contain duplicate or removed nodes. When choosing a node to 93 // visit, we pop off the order stack until we find an item that is 94 // also in the contents set. All operations are O(log N). 95 SmallPtrSet<SDNode*, 64> WorkListContents; 96 SmallVector<SDNode*, 64> WorkListOrder; 97 98 // AA - Used for DAG load/store alias analysis. 99 AliasAnalysis &AA; 100 101 /// AddUsersToWorkList - When an instruction is simplified, add all users of 102 /// the instruction to the work lists because they might get more simplified 103 /// now. 104 /// 105 void AddUsersToWorkList(SDNode *N) { 106 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end(); 107 UI != UE; ++UI) 108 AddToWorkList(*UI); 109 } 110 111 /// visit - call the node-specific routine that knows how to fold each 112 /// particular type of node. 113 SDValue visit(SDNode *N); 114 115 public: 116 /// AddToWorkList - Add to the work list making sure its instance is at the 117 /// back (next to be processed.) 118 void AddToWorkList(SDNode *N) { 119 WorkListContents.insert(N); 120 WorkListOrder.push_back(N); 121 } 122 123 /// removeFromWorkList - remove all instances of N from the worklist. 124 /// 125 void removeFromWorkList(SDNode *N) { 126 WorkListContents.erase(N); 127 } 128 129 SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo, 130 bool AddTo = true); 131 132 SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) { 133 return CombineTo(N, &Res, 1, AddTo); 134 } 135 136 SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1, 137 bool AddTo = true) { 138 SDValue To[] = { Res0, Res1 }; 139 return CombineTo(N, To, 2, AddTo); 140 } 141 142 void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO); 143 144 private: 145 146 /// SimplifyDemandedBits - Check the specified integer node value to see if 147 /// it can be simplified or if things it uses can be simplified by bit 148 /// propagation. If so, return true. 149 bool SimplifyDemandedBits(SDValue Op) { 150 unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits(); 151 APInt Demanded = APInt::getAllOnesValue(BitWidth); 152 return SimplifyDemandedBits(Op, Demanded); 153 } 154 155 bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded); 156 157 bool CombineToPreIndexedLoadStore(SDNode *N); 158 bool CombineToPostIndexedLoadStore(SDNode *N); 159 bool SliceUpLoad(SDNode *N); 160 161 void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad); 162 SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace); 163 SDValue SExtPromoteOperand(SDValue Op, EVT PVT); 164 SDValue ZExtPromoteOperand(SDValue Op, EVT PVT); 165 SDValue PromoteIntBinOp(SDValue Op); 166 SDValue PromoteIntShiftOp(SDValue Op); 167 SDValue PromoteExtend(SDValue Op); 168 bool PromoteLoad(SDValue Op); 169 170 void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs, 171 SDValue Trunc, SDValue ExtLoad, SDLoc DL, 172 ISD::NodeType ExtType); 173 174 /// combine - call the node-specific routine that knows how to fold each 175 /// particular type of node. If that doesn't do anything, try the 176 /// target-specific DAG combines. 177 SDValue combine(SDNode *N); 178 179 // Visitation implementation - Implement dag node combining for different 180 // node types. The semantics are as follows: 181 // Return Value: 182 // SDValue.getNode() == 0 - No change was made 183 // SDValue.getNode() == N - N was replaced, is dead and has been handled. 184 // otherwise - N should be replaced by the returned Operand. 185 // 186 SDValue visitTokenFactor(SDNode *N); 187 SDValue visitMERGE_VALUES(SDNode *N); 188 SDValue visitADD(SDNode *N); 189 SDValue visitSUB(SDNode *N); 190 SDValue visitADDC(SDNode *N); 191 SDValue visitSUBC(SDNode *N); 192 SDValue visitADDE(SDNode *N); 193 SDValue visitSUBE(SDNode *N); 194 SDValue visitMUL(SDNode *N); 195 SDValue visitSDIV(SDNode *N); 196 SDValue visitUDIV(SDNode *N); 197 SDValue visitSREM(SDNode *N); 198 SDValue visitUREM(SDNode *N); 199 SDValue visitMULHU(SDNode *N); 200 SDValue visitMULHS(SDNode *N); 201 SDValue visitSMUL_LOHI(SDNode *N); 202 SDValue visitUMUL_LOHI(SDNode *N); 203 SDValue visitSMULO(SDNode *N); 204 SDValue visitUMULO(SDNode *N); 205 SDValue visitSDIVREM(SDNode *N); 206 SDValue visitUDIVREM(SDNode *N); 207 SDValue visitAND(SDNode *N); 208 SDValue visitOR(SDNode *N); 209 SDValue visitXOR(SDNode *N); 210 SDValue SimplifyVBinOp(SDNode *N); 211 SDValue SimplifyVUnaryOp(SDNode *N); 212 SDValue visitSHL(SDNode *N); 213 SDValue visitSRA(SDNode *N); 214 SDValue visitSRL(SDNode *N); 215 SDValue visitCTLZ(SDNode *N); 216 SDValue visitCTLZ_ZERO_UNDEF(SDNode *N); 217 SDValue visitCTTZ(SDNode *N); 218 SDValue visitCTTZ_ZERO_UNDEF(SDNode *N); 219 SDValue visitCTPOP(SDNode *N); 220 SDValue visitSELECT(SDNode *N); 221 SDValue visitVSELECT(SDNode *N); 222 SDValue visitSELECT_CC(SDNode *N); 223 SDValue visitSETCC(SDNode *N); 224 SDValue visitSIGN_EXTEND(SDNode *N); 225 SDValue visitZERO_EXTEND(SDNode *N); 226 SDValue visitANY_EXTEND(SDNode *N); 227 SDValue visitSIGN_EXTEND_INREG(SDNode *N); 228 SDValue visitTRUNCATE(SDNode *N); 229 SDValue visitBITCAST(SDNode *N); 230 SDValue visitBUILD_PAIR(SDNode *N); 231 SDValue visitFADD(SDNode *N); 232 SDValue visitFSUB(SDNode *N); 233 SDValue visitFMUL(SDNode *N); 234 SDValue visitFMA(SDNode *N); 235 SDValue visitFDIV(SDNode *N); 236 SDValue visitFREM(SDNode *N); 237 SDValue visitFCOPYSIGN(SDNode *N); 238 SDValue visitSINT_TO_FP(SDNode *N); 239 SDValue visitUINT_TO_FP(SDNode *N); 240 SDValue visitFP_TO_SINT(SDNode *N); 241 SDValue visitFP_TO_UINT(SDNode *N); 242 SDValue visitFP_ROUND(SDNode *N); 243 SDValue visitFP_ROUND_INREG(SDNode *N); 244 SDValue visitFP_EXTEND(SDNode *N); 245 SDValue visitFNEG(SDNode *N); 246 SDValue visitFABS(SDNode *N); 247 SDValue visitFCEIL(SDNode *N); 248 SDValue visitFTRUNC(SDNode *N); 249 SDValue visitFFLOOR(SDNode *N); 250 SDValue visitBRCOND(SDNode *N); 251 SDValue visitBR_CC(SDNode *N); 252 SDValue visitLOAD(SDNode *N); 253 SDValue visitSTORE(SDNode *N); 254 SDValue visitINSERT_VECTOR_ELT(SDNode *N); 255 SDValue visitEXTRACT_VECTOR_ELT(SDNode *N); 256 SDValue visitBUILD_VECTOR(SDNode *N); 257 SDValue visitCONCAT_VECTORS(SDNode *N); 258 SDValue visitEXTRACT_SUBVECTOR(SDNode *N); 259 SDValue visitVECTOR_SHUFFLE(SDNode *N); 260 261 SDValue XformToShuffleWithZero(SDNode *N); 262 SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS); 263 264 SDValue visitShiftByConstant(SDNode *N, unsigned Amt); 265 266 bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS); 267 SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N); 268 SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2); 269 SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2, 270 SDValue N3, ISD::CondCode CC, 271 bool NotExtCompare = false); 272 SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond, 273 SDLoc DL, bool foldBooleans = true); 274 SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp, 275 unsigned HiOp); 276 SDValue CombineConsecutiveLoads(SDNode *N, EVT VT); 277 SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT); 278 SDValue BuildSDIV(SDNode *N); 279 SDValue BuildUDIV(SDNode *N); 280 SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1, 281 bool DemandHighBits = true); 282 SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1); 283 SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL); 284 SDValue ReduceLoadWidth(SDNode *N); 285 SDValue ReduceLoadOpStoreWidth(SDNode *N); 286 SDValue TransformFPLoadStorePair(SDNode *N); 287 SDValue reduceBuildVecExtToExtBuildVec(SDNode *N); 288 SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N); 289 290 SDValue GetDemandedBits(SDValue V, const APInt &Mask); 291 292 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes, 293 /// looking for aliasing nodes and adding them to the Aliases vector. 294 void GatherAllAliases(SDNode *N, SDValue OriginalChain, 295 SmallVectorImpl<SDValue> &Aliases); 296 297 /// isAlias - Return true if there is any possibility that the two addresses 298 /// overlap. 299 bool isAlias(SDValue Ptr1, int64_t Size1, bool IsVolatile1, 300 const Value *SrcValue1, int SrcValueOffset1, 301 unsigned SrcValueAlign1, 302 const MDNode *TBAAInfo1, 303 SDValue Ptr2, int64_t Size2, bool IsVolatile2, 304 const Value *SrcValue2, int SrcValueOffset2, 305 unsigned SrcValueAlign2, 306 const MDNode *TBAAInfo2) const; 307 308 /// isAlias - Return true if there is any possibility that the two addresses 309 /// overlap. 310 bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1); 311 312 /// FindAliasInfo - Extracts the relevant alias information from the memory 313 /// node. Returns true if the operand was a load. 314 bool FindAliasInfo(SDNode *N, 315 SDValue &Ptr, int64_t &Size, bool &IsVolatile, 316 const Value *&SrcValue, int &SrcValueOffset, 317 unsigned &SrcValueAlignment, 318 const MDNode *&TBAAInfo) const; 319 320 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes, 321 /// looking for a better chain (aliasing node.) 322 SDValue FindBetterChain(SDNode *N, SDValue Chain); 323 324 /// Merge consecutive store operations into a wide store. 325 /// This optimization uses wide integers or vectors when possible. 326 /// \return True if some memory operations were changed. 327 bool MergeConsecutiveStores(StoreSDNode *N); 328 329 public: 330 DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL) 331 : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes), 332 OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) { 333 AttributeSet FnAttrs = 334 DAG.getMachineFunction().getFunction()->getAttributes(); 335 ForCodeSize = 336 FnAttrs.hasAttribute(AttributeSet::FunctionIndex, 337 Attribute::OptimizeForSize) || 338 FnAttrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::MinSize); 339 } 340 341 /// Run - runs the dag combiner on all nodes in the work list 342 void Run(CombineLevel AtLevel); 343 344 SelectionDAG &getDAG() const { return DAG; } 345 346 /// getShiftAmountTy - Returns a type large enough to hold any valid 347 /// shift amount - before type legalization these can be huge. 348 EVT getShiftAmountTy(EVT LHSTy) { 349 assert(LHSTy.isInteger() && "Shift amount is not an integer type!"); 350 if (LHSTy.isVector()) 351 return LHSTy; 352 return LegalTypes ? TLI.getScalarShiftAmountTy(LHSTy) 353 : TLI.getPointerTy(); 354 } 355 356 /// isTypeLegal - This method returns true if we are running before type 357 /// legalization or if the specified VT is legal. 358 bool isTypeLegal(const EVT &VT) { 359 if (!LegalTypes) return true; 360 return TLI.isTypeLegal(VT); 361 } 362 363 /// getSetCCResultType - Convenience wrapper around 364 /// TargetLowering::getSetCCResultType 365 EVT getSetCCResultType(EVT VT) const { 366 return TLI.getSetCCResultType(*DAG.getContext(), VT); 367 } 368 }; 369} 370 371 372namespace { 373/// WorkListRemover - This class is a DAGUpdateListener that removes any deleted 374/// nodes from the worklist. 375class WorkListRemover : public SelectionDAG::DAGUpdateListener { 376 DAGCombiner &DC; 377public: 378 explicit WorkListRemover(DAGCombiner &dc) 379 : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {} 380 381 virtual void NodeDeleted(SDNode *N, SDNode *E) { 382 DC.removeFromWorkList(N); 383 } 384}; 385} 386 387//===----------------------------------------------------------------------===// 388// TargetLowering::DAGCombinerInfo implementation 389//===----------------------------------------------------------------------===// 390 391void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) { 392 ((DAGCombiner*)DC)->AddToWorkList(N); 393} 394 395void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) { 396 ((DAGCombiner*)DC)->removeFromWorkList(N); 397} 398 399SDValue TargetLowering::DAGCombinerInfo:: 400CombineTo(SDNode *N, const std::vector<SDValue> &To, bool AddTo) { 401 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo); 402} 403 404SDValue TargetLowering::DAGCombinerInfo:: 405CombineTo(SDNode *N, SDValue Res, bool AddTo) { 406 return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo); 407} 408 409 410SDValue TargetLowering::DAGCombinerInfo:: 411CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) { 412 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo); 413} 414 415void TargetLowering::DAGCombinerInfo:: 416CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) { 417 return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO); 418} 419 420//===----------------------------------------------------------------------===// 421// Helper Functions 422//===----------------------------------------------------------------------===// 423 424/// isNegatibleForFree - Return 1 if we can compute the negated form of the 425/// specified expression for the same cost as the expression itself, or 2 if we 426/// can compute the negated form more cheaply than the expression itself. 427static char isNegatibleForFree(SDValue Op, bool LegalOperations, 428 const TargetLowering &TLI, 429 const TargetOptions *Options, 430 unsigned Depth = 0) { 431 // fneg is removable even if it has multiple uses. 432 if (Op.getOpcode() == ISD::FNEG) return 2; 433 434 // Don't allow anything with multiple uses. 435 if (!Op.hasOneUse()) return 0; 436 437 // Don't recurse exponentially. 438 if (Depth > 6) return 0; 439 440 switch (Op.getOpcode()) { 441 default: return false; 442 case ISD::ConstantFP: 443 // Don't invert constant FP values after legalize. The negated constant 444 // isn't necessarily legal. 445 return LegalOperations ? 0 : 1; 446 case ISD::FADD: 447 // FIXME: determine better conditions for this xform. 448 if (!Options->UnsafeFPMath) return 0; 449 450 // After operation legalization, it might not be legal to create new FSUBs. 451 if (LegalOperations && 452 !TLI.isOperationLegalOrCustom(ISD::FSUB, Op.getValueType())) 453 return 0; 454 455 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B) 456 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, 457 Options, Depth + 1)) 458 return V; 459 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A) 460 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options, 461 Depth + 1); 462 case ISD::FSUB: 463 // We can't turn -(A-B) into B-A when we honor signed zeros. 464 if (!Options->UnsafeFPMath) return 0; 465 466 // fold (fneg (fsub A, B)) -> (fsub B, A) 467 return 1; 468 469 case ISD::FMUL: 470 case ISD::FDIV: 471 if (Options->HonorSignDependentRoundingFPMath()) return 0; 472 473 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y)) 474 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, 475 Options, Depth + 1)) 476 return V; 477 478 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options, 479 Depth + 1); 480 481 case ISD::FP_EXTEND: 482 case ISD::FP_ROUND: 483 case ISD::FSIN: 484 return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options, 485 Depth + 1); 486 } 487} 488 489/// GetNegatedExpression - If isNegatibleForFree returns true, this function 490/// returns the newly negated expression. 491static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG, 492 bool LegalOperations, unsigned Depth = 0) { 493 // fneg is removable even if it has multiple uses. 494 if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0); 495 496 // Don't allow anything with multiple uses. 497 assert(Op.hasOneUse() && "Unknown reuse!"); 498 499 assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree"); 500 switch (Op.getOpcode()) { 501 default: llvm_unreachable("Unknown code"); 502 case ISD::ConstantFP: { 503 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF(); 504 V.changeSign(); 505 return DAG.getConstantFP(V, Op.getValueType()); 506 } 507 case ISD::FADD: 508 // FIXME: determine better conditions for this xform. 509 assert(DAG.getTarget().Options.UnsafeFPMath); 510 511 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B) 512 if (isNegatibleForFree(Op.getOperand(0), LegalOperations, 513 DAG.getTargetLoweringInfo(), 514 &DAG.getTarget().Options, Depth+1)) 515 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(), 516 GetNegatedExpression(Op.getOperand(0), DAG, 517 LegalOperations, Depth+1), 518 Op.getOperand(1)); 519 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A) 520 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(), 521 GetNegatedExpression(Op.getOperand(1), DAG, 522 LegalOperations, Depth+1), 523 Op.getOperand(0)); 524 case ISD::FSUB: 525 // We can't turn -(A-B) into B-A when we honor signed zeros. 526 assert(DAG.getTarget().Options.UnsafeFPMath); 527 528 // fold (fneg (fsub 0, B)) -> B 529 if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0))) 530 if (N0CFP->getValueAPF().isZero()) 531 return Op.getOperand(1); 532 533 // fold (fneg (fsub A, B)) -> (fsub B, A) 534 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(), 535 Op.getOperand(1), Op.getOperand(0)); 536 537 case ISD::FMUL: 538 case ISD::FDIV: 539 assert(!DAG.getTarget().Options.HonorSignDependentRoundingFPMath()); 540 541 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) 542 if (isNegatibleForFree(Op.getOperand(0), LegalOperations, 543 DAG.getTargetLoweringInfo(), 544 &DAG.getTarget().Options, Depth+1)) 545 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(), 546 GetNegatedExpression(Op.getOperand(0), DAG, 547 LegalOperations, Depth+1), 548 Op.getOperand(1)); 549 550 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y)) 551 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(), 552 Op.getOperand(0), 553 GetNegatedExpression(Op.getOperand(1), DAG, 554 LegalOperations, Depth+1)); 555 556 case ISD::FP_EXTEND: 557 case ISD::FSIN: 558 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(), 559 GetNegatedExpression(Op.getOperand(0), DAG, 560 LegalOperations, Depth+1)); 561 case ISD::FP_ROUND: 562 return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(), 563 GetNegatedExpression(Op.getOperand(0), DAG, 564 LegalOperations, Depth+1), 565 Op.getOperand(1)); 566 } 567} 568 569 570// isSetCCEquivalent - Return true if this node is a setcc, or is a select_cc 571// that selects between the values 1 and 0, making it equivalent to a setcc. 572// Also, set the incoming LHS, RHS, and CC references to the appropriate 573// nodes based on the type of node we are checking. This simplifies life a 574// bit for the callers. 575static bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS, 576 SDValue &CC) { 577 if (N.getOpcode() == ISD::SETCC) { 578 LHS = N.getOperand(0); 579 RHS = N.getOperand(1); 580 CC = N.getOperand(2); 581 return true; 582 } 583 if (N.getOpcode() == ISD::SELECT_CC && 584 N.getOperand(2).getOpcode() == ISD::Constant && 585 N.getOperand(3).getOpcode() == ISD::Constant && 586 cast<ConstantSDNode>(N.getOperand(2))->getAPIntValue() == 1 && 587 cast<ConstantSDNode>(N.getOperand(3))->isNullValue()) { 588 LHS = N.getOperand(0); 589 RHS = N.getOperand(1); 590 CC = N.getOperand(4); 591 return true; 592 } 593 return false; 594} 595 596// isOneUseSetCC - Return true if this is a SetCC-equivalent operation with only 597// one use. If this is true, it allows the users to invert the operation for 598// free when it is profitable to do so. 599static bool isOneUseSetCC(SDValue N) { 600 SDValue N0, N1, N2; 601 if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse()) 602 return true; 603 return false; 604} 605 606SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL, 607 SDValue N0, SDValue N1) { 608 EVT VT = N0.getValueType(); 609 if (N0.getOpcode() == Opc && isa<ConstantSDNode>(N0.getOperand(1))) { 610 if (isa<ConstantSDNode>(N1)) { 611 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2)) 612 SDValue OpNode = 613 DAG.FoldConstantArithmetic(Opc, VT, 614 cast<ConstantSDNode>(N0.getOperand(1)), 615 cast<ConstantSDNode>(N1)); 616 return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode); 617 } 618 if (N0.hasOneUse()) { 619 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one use 620 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, 621 N0.getOperand(0), N1); 622 AddToWorkList(OpNode.getNode()); 623 return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1)); 624 } 625 } 626 627 if (N1.getOpcode() == Opc && isa<ConstantSDNode>(N1.getOperand(1))) { 628 if (isa<ConstantSDNode>(N0)) { 629 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2)) 630 SDValue OpNode = 631 DAG.FoldConstantArithmetic(Opc, VT, 632 cast<ConstantSDNode>(N1.getOperand(1)), 633 cast<ConstantSDNode>(N0)); 634 return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode); 635 } 636 if (N1.hasOneUse()) { 637 // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one use 638 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, 639 N1.getOperand(0), N0); 640 AddToWorkList(OpNode.getNode()); 641 return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1)); 642 } 643 } 644 645 return SDValue(); 646} 647 648SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo, 649 bool AddTo) { 650 assert(N->getNumValues() == NumTo && "Broken CombineTo call!"); 651 ++NodesCombined; 652 DEBUG(dbgs() << "\nReplacing.1 "; 653 N->dump(&DAG); 654 dbgs() << "\nWith: "; 655 To[0].getNode()->dump(&DAG); 656 dbgs() << " and " << NumTo-1 << " other values\n"; 657 for (unsigned i = 0, e = NumTo; i != e; ++i) 658 assert((!To[i].getNode() || 659 N->getValueType(i) == To[i].getValueType()) && 660 "Cannot combine value to value of different type!")); 661 WorkListRemover DeadNodes(*this); 662 DAG.ReplaceAllUsesWith(N, To); 663 if (AddTo) { 664 // Push the new nodes and any users onto the worklist 665 for (unsigned i = 0, e = NumTo; i != e; ++i) { 666 if (To[i].getNode()) { 667 AddToWorkList(To[i].getNode()); 668 AddUsersToWorkList(To[i].getNode()); 669 } 670 } 671 } 672 673 // Finally, if the node is now dead, remove it from the graph. The node 674 // may not be dead if the replacement process recursively simplified to 675 // something else needing this node. 676 if (N->use_empty()) { 677 // Nodes can be reintroduced into the worklist. Make sure we do not 678 // process a node that has been replaced. 679 removeFromWorkList(N); 680 681 // Finally, since the node is now dead, remove it from the graph. 682 DAG.DeleteNode(N); 683 } 684 return SDValue(N, 0); 685} 686 687void DAGCombiner:: 688CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) { 689 // Replace all uses. If any nodes become isomorphic to other nodes and 690 // are deleted, make sure to remove them from our worklist. 691 WorkListRemover DeadNodes(*this); 692 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New); 693 694 // Push the new node and any (possibly new) users onto the worklist. 695 AddToWorkList(TLO.New.getNode()); 696 AddUsersToWorkList(TLO.New.getNode()); 697 698 // Finally, if the node is now dead, remove it from the graph. The node 699 // may not be dead if the replacement process recursively simplified to 700 // something else needing this node. 701 if (TLO.Old.getNode()->use_empty()) { 702 removeFromWorkList(TLO.Old.getNode()); 703 704 // If the operands of this node are only used by the node, they will now 705 // be dead. Make sure to visit them first to delete dead nodes early. 706 for (unsigned i = 0, e = TLO.Old.getNode()->getNumOperands(); i != e; ++i) 707 if (TLO.Old.getNode()->getOperand(i).getNode()->hasOneUse()) 708 AddToWorkList(TLO.Old.getNode()->getOperand(i).getNode()); 709 710 DAG.DeleteNode(TLO.Old.getNode()); 711 } 712} 713 714/// SimplifyDemandedBits - Check the specified integer node value to see if 715/// it can be simplified or if things it uses can be simplified by bit 716/// propagation. If so, return true. 717bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) { 718 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations); 719 APInt KnownZero, KnownOne; 720 if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO)) 721 return false; 722 723 // Revisit the node. 724 AddToWorkList(Op.getNode()); 725 726 // Replace the old value with the new one. 727 ++NodesCombined; 728 DEBUG(dbgs() << "\nReplacing.2 "; 729 TLO.Old.getNode()->dump(&DAG); 730 dbgs() << "\nWith: "; 731 TLO.New.getNode()->dump(&DAG); 732 dbgs() << '\n'); 733 734 CommitTargetLoweringOpt(TLO); 735 return true; 736} 737 738void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) { 739 SDLoc dl(Load); 740 EVT VT = Load->getValueType(0); 741 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0)); 742 743 DEBUG(dbgs() << "\nReplacing.9 "; 744 Load->dump(&DAG); 745 dbgs() << "\nWith: "; 746 Trunc.getNode()->dump(&DAG); 747 dbgs() << '\n'); 748 WorkListRemover DeadNodes(*this); 749 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc); 750 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1)); 751 removeFromWorkList(Load); 752 DAG.DeleteNode(Load); 753 AddToWorkList(Trunc.getNode()); 754} 755 756SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) { 757 Replace = false; 758 SDLoc dl(Op); 759 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) { 760 EVT MemVT = LD->getMemoryVT(); 761 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD) 762 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD 763 : ISD::EXTLOAD) 764 : LD->getExtensionType(); 765 Replace = true; 766 return DAG.getExtLoad(ExtType, dl, PVT, 767 LD->getChain(), LD->getBasePtr(), 768 MemVT, LD->getMemOperand()); 769 } 770 771 unsigned Opc = Op.getOpcode(); 772 switch (Opc) { 773 default: break; 774 case ISD::AssertSext: 775 return DAG.getNode(ISD::AssertSext, dl, PVT, 776 SExtPromoteOperand(Op.getOperand(0), PVT), 777 Op.getOperand(1)); 778 case ISD::AssertZext: 779 return DAG.getNode(ISD::AssertZext, dl, PVT, 780 ZExtPromoteOperand(Op.getOperand(0), PVT), 781 Op.getOperand(1)); 782 case ISD::Constant: { 783 unsigned ExtOpc = 784 Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 785 return DAG.getNode(ExtOpc, dl, PVT, Op); 786 } 787 } 788 789 if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT)) 790 return SDValue(); 791 return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op); 792} 793 794SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) { 795 if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT)) 796 return SDValue(); 797 EVT OldVT = Op.getValueType(); 798 SDLoc dl(Op); 799 bool Replace = false; 800 SDValue NewOp = PromoteOperand(Op, PVT, Replace); 801 if (NewOp.getNode() == 0) 802 return SDValue(); 803 AddToWorkList(NewOp.getNode()); 804 805 if (Replace) 806 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode()); 807 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp, 808 DAG.getValueType(OldVT)); 809} 810 811SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) { 812 EVT OldVT = Op.getValueType(); 813 SDLoc dl(Op); 814 bool Replace = false; 815 SDValue NewOp = PromoteOperand(Op, PVT, Replace); 816 if (NewOp.getNode() == 0) 817 return SDValue(); 818 AddToWorkList(NewOp.getNode()); 819 820 if (Replace) 821 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode()); 822 return DAG.getZeroExtendInReg(NewOp, dl, OldVT); 823} 824 825/// PromoteIntBinOp - Promote the specified integer binary operation if the 826/// target indicates it is beneficial. e.g. On x86, it's usually better to 827/// promote i16 operations to i32 since i16 instructions are longer. 828SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) { 829 if (!LegalOperations) 830 return SDValue(); 831 832 EVT VT = Op.getValueType(); 833 if (VT.isVector() || !VT.isInteger()) 834 return SDValue(); 835 836 // If operation type is 'undesirable', e.g. i16 on x86, consider 837 // promoting it. 838 unsigned Opc = Op.getOpcode(); 839 if (TLI.isTypeDesirableForOp(Opc, VT)) 840 return SDValue(); 841 842 EVT PVT = VT; 843 // Consult target whether it is a good idea to promote this operation and 844 // what's the right type to promote it to. 845 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 846 assert(PVT != VT && "Don't know what type to promote to!"); 847 848 bool Replace0 = false; 849 SDValue N0 = Op.getOperand(0); 850 SDValue NN0 = PromoteOperand(N0, PVT, Replace0); 851 if (NN0.getNode() == 0) 852 return SDValue(); 853 854 bool Replace1 = false; 855 SDValue N1 = Op.getOperand(1); 856 SDValue NN1; 857 if (N0 == N1) 858 NN1 = NN0; 859 else { 860 NN1 = PromoteOperand(N1, PVT, Replace1); 861 if (NN1.getNode() == 0) 862 return SDValue(); 863 } 864 865 AddToWorkList(NN0.getNode()); 866 if (NN1.getNode()) 867 AddToWorkList(NN1.getNode()); 868 869 if (Replace0) 870 ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode()); 871 if (Replace1) 872 ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode()); 873 874 DEBUG(dbgs() << "\nPromoting "; 875 Op.getNode()->dump(&DAG)); 876 SDLoc dl(Op); 877 return DAG.getNode(ISD::TRUNCATE, dl, VT, 878 DAG.getNode(Opc, dl, PVT, NN0, NN1)); 879 } 880 return SDValue(); 881} 882 883/// PromoteIntShiftOp - Promote the specified integer shift operation if the 884/// target indicates it is beneficial. e.g. On x86, it's usually better to 885/// promote i16 operations to i32 since i16 instructions are longer. 886SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) { 887 if (!LegalOperations) 888 return SDValue(); 889 890 EVT VT = Op.getValueType(); 891 if (VT.isVector() || !VT.isInteger()) 892 return SDValue(); 893 894 // If operation type is 'undesirable', e.g. i16 on x86, consider 895 // promoting it. 896 unsigned Opc = Op.getOpcode(); 897 if (TLI.isTypeDesirableForOp(Opc, VT)) 898 return SDValue(); 899 900 EVT PVT = VT; 901 // Consult target whether it is a good idea to promote this operation and 902 // what's the right type to promote it to. 903 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 904 assert(PVT != VT && "Don't know what type to promote to!"); 905 906 bool Replace = false; 907 SDValue N0 = Op.getOperand(0); 908 if (Opc == ISD::SRA) 909 N0 = SExtPromoteOperand(Op.getOperand(0), PVT); 910 else if (Opc == ISD::SRL) 911 N0 = ZExtPromoteOperand(Op.getOperand(0), PVT); 912 else 913 N0 = PromoteOperand(N0, PVT, Replace); 914 if (N0.getNode() == 0) 915 return SDValue(); 916 917 AddToWorkList(N0.getNode()); 918 if (Replace) 919 ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode()); 920 921 DEBUG(dbgs() << "\nPromoting "; 922 Op.getNode()->dump(&DAG)); 923 SDLoc dl(Op); 924 return DAG.getNode(ISD::TRUNCATE, dl, VT, 925 DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1))); 926 } 927 return SDValue(); 928} 929 930SDValue DAGCombiner::PromoteExtend(SDValue Op) { 931 if (!LegalOperations) 932 return SDValue(); 933 934 EVT VT = Op.getValueType(); 935 if (VT.isVector() || !VT.isInteger()) 936 return SDValue(); 937 938 // If operation type is 'undesirable', e.g. i16 on x86, consider 939 // promoting it. 940 unsigned Opc = Op.getOpcode(); 941 if (TLI.isTypeDesirableForOp(Opc, VT)) 942 return SDValue(); 943 944 EVT PVT = VT; 945 // Consult target whether it is a good idea to promote this operation and 946 // what's the right type to promote it to. 947 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 948 assert(PVT != VT && "Don't know what type to promote to!"); 949 // fold (aext (aext x)) -> (aext x) 950 // fold (aext (zext x)) -> (zext x) 951 // fold (aext (sext x)) -> (sext x) 952 DEBUG(dbgs() << "\nPromoting "; 953 Op.getNode()->dump(&DAG)); 954 return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0)); 955 } 956 return SDValue(); 957} 958 959bool DAGCombiner::PromoteLoad(SDValue Op) { 960 if (!LegalOperations) 961 return false; 962 963 EVT VT = Op.getValueType(); 964 if (VT.isVector() || !VT.isInteger()) 965 return false; 966 967 // If operation type is 'undesirable', e.g. i16 on x86, consider 968 // promoting it. 969 unsigned Opc = Op.getOpcode(); 970 if (TLI.isTypeDesirableForOp(Opc, VT)) 971 return false; 972 973 EVT PVT = VT; 974 // Consult target whether it is a good idea to promote this operation and 975 // what's the right type to promote it to. 976 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 977 assert(PVT != VT && "Don't know what type to promote to!"); 978 979 SDLoc dl(Op); 980 SDNode *N = Op.getNode(); 981 LoadSDNode *LD = cast<LoadSDNode>(N); 982 EVT MemVT = LD->getMemoryVT(); 983 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD) 984 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD 985 : ISD::EXTLOAD) 986 : LD->getExtensionType(); 987 SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT, 988 LD->getChain(), LD->getBasePtr(), 989 MemVT, LD->getMemOperand()); 990 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD); 991 992 DEBUG(dbgs() << "\nPromoting "; 993 N->dump(&DAG); 994 dbgs() << "\nTo: "; 995 Result.getNode()->dump(&DAG); 996 dbgs() << '\n'); 997 WorkListRemover DeadNodes(*this); 998 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result); 999 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1)); 1000 removeFromWorkList(N); 1001 DAG.DeleteNode(N); 1002 AddToWorkList(Result.getNode()); 1003 return true; 1004 } 1005 return false; 1006} 1007 1008 1009//===----------------------------------------------------------------------===// 1010// Main DAG Combiner implementation 1011//===----------------------------------------------------------------------===// 1012 1013void DAGCombiner::Run(CombineLevel AtLevel) { 1014 // set the instance variables, so that the various visit routines may use it. 1015 Level = AtLevel; 1016 LegalOperations = Level >= AfterLegalizeVectorOps; 1017 LegalTypes = Level >= AfterLegalizeTypes; 1018 1019 // Add all the dag nodes to the worklist. 1020 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(), 1021 E = DAG.allnodes_end(); I != E; ++I) 1022 AddToWorkList(I); 1023 1024 // Create a dummy node (which is not added to allnodes), that adds a reference 1025 // to the root node, preventing it from being deleted, and tracking any 1026 // changes of the root. 1027 HandleSDNode Dummy(DAG.getRoot()); 1028 1029 // The root of the dag may dangle to deleted nodes until the dag combiner is 1030 // done. Set it to null to avoid confusion. 1031 DAG.setRoot(SDValue()); 1032 1033 // while the worklist isn't empty, find a node and 1034 // try and combine it. 1035 while (!WorkListContents.empty()) { 1036 SDNode *N; 1037 // The WorkListOrder holds the SDNodes in order, but it may contain 1038 // duplicates. 1039 // In order to avoid a linear scan, we use a set (O(log N)) to hold what the 1040 // worklist *should* contain, and check the node we want to visit is should 1041 // actually be visited. 1042 do { 1043 N = WorkListOrder.pop_back_val(); 1044 } while (!WorkListContents.erase(N)); 1045 1046 // If N has no uses, it is dead. Make sure to revisit all N's operands once 1047 // N is deleted from the DAG, since they too may now be dead or may have a 1048 // reduced number of uses, allowing other xforms. 1049 if (N->use_empty() && N != &Dummy) { 1050 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) 1051 AddToWorkList(N->getOperand(i).getNode()); 1052 1053 DAG.DeleteNode(N); 1054 continue; 1055 } 1056 1057 SDValue RV = combine(N); 1058 1059 if (RV.getNode() == 0) 1060 continue; 1061 1062 ++NodesCombined; 1063 1064 // If we get back the same node we passed in, rather than a new node or 1065 // zero, we know that the node must have defined multiple values and 1066 // CombineTo was used. Since CombineTo takes care of the worklist 1067 // mechanics for us, we have no work to do in this case. 1068 if (RV.getNode() == N) 1069 continue; 1070 1071 assert(N->getOpcode() != ISD::DELETED_NODE && 1072 RV.getNode()->getOpcode() != ISD::DELETED_NODE && 1073 "Node was deleted but visit returned new node!"); 1074 1075 DEBUG(dbgs() << "\nReplacing.3 "; 1076 N->dump(&DAG); 1077 dbgs() << "\nWith: "; 1078 RV.getNode()->dump(&DAG); 1079 dbgs() << '\n'); 1080 1081 // Transfer debug value. 1082 DAG.TransferDbgValues(SDValue(N, 0), RV); 1083 WorkListRemover DeadNodes(*this); 1084 if (N->getNumValues() == RV.getNode()->getNumValues()) 1085 DAG.ReplaceAllUsesWith(N, RV.getNode()); 1086 else { 1087 assert(N->getValueType(0) == RV.getValueType() && 1088 N->getNumValues() == 1 && "Type mismatch"); 1089 SDValue OpV = RV; 1090 DAG.ReplaceAllUsesWith(N, &OpV); 1091 } 1092 1093 // Push the new node and any users onto the worklist 1094 AddToWorkList(RV.getNode()); 1095 AddUsersToWorkList(RV.getNode()); 1096 1097 // Add any uses of the old node to the worklist in case this node is the 1098 // last one that uses them. They may become dead after this node is 1099 // deleted. 1100 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) 1101 AddToWorkList(N->getOperand(i).getNode()); 1102 1103 // Finally, if the node is now dead, remove it from the graph. The node 1104 // may not be dead if the replacement process recursively simplified to 1105 // something else needing this node. 1106 if (N->use_empty()) { 1107 // Nodes can be reintroduced into the worklist. Make sure we do not 1108 // process a node that has been replaced. 1109 removeFromWorkList(N); 1110 1111 // Finally, since the node is now dead, remove it from the graph. 1112 DAG.DeleteNode(N); 1113 } 1114 } 1115 1116 // If the root changed (e.g. it was a dead load, update the root). 1117 DAG.setRoot(Dummy.getValue()); 1118 DAG.RemoveDeadNodes(); 1119} 1120 1121SDValue DAGCombiner::visit(SDNode *N) { 1122 switch (N->getOpcode()) { 1123 default: break; 1124 case ISD::TokenFactor: return visitTokenFactor(N); 1125 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N); 1126 case ISD::ADD: return visitADD(N); 1127 case ISD::SUB: return visitSUB(N); 1128 case ISD::ADDC: return visitADDC(N); 1129 case ISD::SUBC: return visitSUBC(N); 1130 case ISD::ADDE: return visitADDE(N); 1131 case ISD::SUBE: return visitSUBE(N); 1132 case ISD::MUL: return visitMUL(N); 1133 case ISD::SDIV: return visitSDIV(N); 1134 case ISD::UDIV: return visitUDIV(N); 1135 case ISD::SREM: return visitSREM(N); 1136 case ISD::UREM: return visitUREM(N); 1137 case ISD::MULHU: return visitMULHU(N); 1138 case ISD::MULHS: return visitMULHS(N); 1139 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N); 1140 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N); 1141 case ISD::SMULO: return visitSMULO(N); 1142 case ISD::UMULO: return visitUMULO(N); 1143 case ISD::SDIVREM: return visitSDIVREM(N); 1144 case ISD::UDIVREM: return visitUDIVREM(N); 1145 case ISD::AND: return visitAND(N); 1146 case ISD::OR: return visitOR(N); 1147 case ISD::XOR: return visitXOR(N); 1148 case ISD::SHL: return visitSHL(N); 1149 case ISD::SRA: return visitSRA(N); 1150 case ISD::SRL: return visitSRL(N); 1151 case ISD::CTLZ: return visitCTLZ(N); 1152 case ISD::CTLZ_ZERO_UNDEF: return visitCTLZ_ZERO_UNDEF(N); 1153 case ISD::CTTZ: return visitCTTZ(N); 1154 case ISD::CTTZ_ZERO_UNDEF: return visitCTTZ_ZERO_UNDEF(N); 1155 case ISD::CTPOP: return visitCTPOP(N); 1156 case ISD::SELECT: return visitSELECT(N); 1157 case ISD::VSELECT: return visitVSELECT(N); 1158 case ISD::SELECT_CC: return visitSELECT_CC(N); 1159 case ISD::SETCC: return visitSETCC(N); 1160 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N); 1161 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N); 1162 case ISD::ANY_EXTEND: return visitANY_EXTEND(N); 1163 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N); 1164 case ISD::TRUNCATE: return visitTRUNCATE(N); 1165 case ISD::BITCAST: return visitBITCAST(N); 1166 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N); 1167 case ISD::FADD: return visitFADD(N); 1168 case ISD::FSUB: return visitFSUB(N); 1169 case ISD::FMUL: return visitFMUL(N); 1170 case ISD::FMA: return visitFMA(N); 1171 case ISD::FDIV: return visitFDIV(N); 1172 case ISD::FREM: return visitFREM(N); 1173 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N); 1174 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N); 1175 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N); 1176 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N); 1177 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N); 1178 case ISD::FP_ROUND: return visitFP_ROUND(N); 1179 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N); 1180 case ISD::FP_EXTEND: return visitFP_EXTEND(N); 1181 case ISD::FNEG: return visitFNEG(N); 1182 case ISD::FABS: return visitFABS(N); 1183 case ISD::FFLOOR: return visitFFLOOR(N); 1184 case ISD::FCEIL: return visitFCEIL(N); 1185 case ISD::FTRUNC: return visitFTRUNC(N); 1186 case ISD::BRCOND: return visitBRCOND(N); 1187 case ISD::BR_CC: return visitBR_CC(N); 1188 case ISD::LOAD: return visitLOAD(N); 1189 case ISD::STORE: return visitSTORE(N); 1190 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N); 1191 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N); 1192 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N); 1193 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N); 1194 case ISD::EXTRACT_SUBVECTOR: return visitEXTRACT_SUBVECTOR(N); 1195 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N); 1196 } 1197 return SDValue(); 1198} 1199 1200SDValue DAGCombiner::combine(SDNode *N) { 1201 SDValue RV = visit(N); 1202 1203 // If nothing happened, try a target-specific DAG combine. 1204 if (RV.getNode() == 0) { 1205 assert(N->getOpcode() != ISD::DELETED_NODE && 1206 "Node was deleted but visit returned NULL!"); 1207 1208 if (N->getOpcode() >= ISD::BUILTIN_OP_END || 1209 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) { 1210 1211 // Expose the DAG combiner to the target combiner impls. 1212 TargetLowering::DAGCombinerInfo 1213 DagCombineInfo(DAG, Level, false, this); 1214 1215 RV = TLI.PerformDAGCombine(N, DagCombineInfo); 1216 } 1217 } 1218 1219 // If nothing happened still, try promoting the operation. 1220 if (RV.getNode() == 0) { 1221 switch (N->getOpcode()) { 1222 default: break; 1223 case ISD::ADD: 1224 case ISD::SUB: 1225 case ISD::MUL: 1226 case ISD::AND: 1227 case ISD::OR: 1228 case ISD::XOR: 1229 RV = PromoteIntBinOp(SDValue(N, 0)); 1230 break; 1231 case ISD::SHL: 1232 case ISD::SRA: 1233 case ISD::SRL: 1234 RV = PromoteIntShiftOp(SDValue(N, 0)); 1235 break; 1236 case ISD::SIGN_EXTEND: 1237 case ISD::ZERO_EXTEND: 1238 case ISD::ANY_EXTEND: 1239 RV = PromoteExtend(SDValue(N, 0)); 1240 break; 1241 case ISD::LOAD: 1242 if (PromoteLoad(SDValue(N, 0))) 1243 RV = SDValue(N, 0); 1244 break; 1245 } 1246 } 1247 1248 // If N is a commutative binary node, try commuting it to enable more 1249 // sdisel CSE. 1250 if (RV.getNode() == 0 && 1251 SelectionDAG::isCommutativeBinOp(N->getOpcode()) && 1252 N->getNumValues() == 1) { 1253 SDValue N0 = N->getOperand(0); 1254 SDValue N1 = N->getOperand(1); 1255 1256 // Constant operands are canonicalized to RHS. 1257 if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) { 1258 SDValue Ops[] = { N1, N0 }; 1259 SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), 1260 Ops, 2); 1261 if (CSENode) 1262 return SDValue(CSENode, 0); 1263 } 1264 } 1265 1266 return RV; 1267} 1268 1269/// getInputChainForNode - Given a node, return its input chain if it has one, 1270/// otherwise return a null sd operand. 1271static SDValue getInputChainForNode(SDNode *N) { 1272 if (unsigned NumOps = N->getNumOperands()) { 1273 if (N->getOperand(0).getValueType() == MVT::Other) 1274 return N->getOperand(0); 1275 if (N->getOperand(NumOps-1).getValueType() == MVT::Other) 1276 return N->getOperand(NumOps-1); 1277 for (unsigned i = 1; i < NumOps-1; ++i) 1278 if (N->getOperand(i).getValueType() == MVT::Other) 1279 return N->getOperand(i); 1280 } 1281 return SDValue(); 1282} 1283 1284SDValue DAGCombiner::visitTokenFactor(SDNode *N) { 1285 // If N has two operands, where one has an input chain equal to the other, 1286 // the 'other' chain is redundant. 1287 if (N->getNumOperands() == 2) { 1288 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1)) 1289 return N->getOperand(0); 1290 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0)) 1291 return N->getOperand(1); 1292 } 1293 1294 SmallVector<SDNode *, 8> TFs; // List of token factors to visit. 1295 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor. 1296 SmallPtrSet<SDNode*, 16> SeenOps; 1297 bool Changed = false; // If we should replace this token factor. 1298 1299 // Start out with this token factor. 1300 TFs.push_back(N); 1301 1302 // Iterate through token factors. The TFs grows when new token factors are 1303 // encountered. 1304 for (unsigned i = 0; i < TFs.size(); ++i) { 1305 SDNode *TF = TFs[i]; 1306 1307 // Check each of the operands. 1308 for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) { 1309 SDValue Op = TF->getOperand(i); 1310 1311 switch (Op.getOpcode()) { 1312 case ISD::EntryToken: 1313 // Entry tokens don't need to be added to the list. They are 1314 // rededundant. 1315 Changed = true; 1316 break; 1317 1318 case ISD::TokenFactor: 1319 if (Op.hasOneUse() && 1320 std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) { 1321 // Queue up for processing. 1322 TFs.push_back(Op.getNode()); 1323 // Clean up in case the token factor is removed. 1324 AddToWorkList(Op.getNode()); 1325 Changed = true; 1326 break; 1327 } 1328 // Fall thru 1329 1330 default: 1331 // Only add if it isn't already in the list. 1332 if (SeenOps.insert(Op.getNode())) 1333 Ops.push_back(Op); 1334 else 1335 Changed = true; 1336 break; 1337 } 1338 } 1339 } 1340 1341 SDValue Result; 1342 1343 // If we've change things around then replace token factor. 1344 if (Changed) { 1345 if (Ops.empty()) { 1346 // The entry token is the only possible outcome. 1347 Result = DAG.getEntryNode(); 1348 } else { 1349 // New and improved token factor. 1350 Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), 1351 MVT::Other, &Ops[0], Ops.size()); 1352 } 1353 1354 // Don't add users to work list. 1355 return CombineTo(N, Result, false); 1356 } 1357 1358 return Result; 1359} 1360 1361/// MERGE_VALUES can always be eliminated. 1362SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) { 1363 WorkListRemover DeadNodes(*this); 1364 // Replacing results may cause a different MERGE_VALUES to suddenly 1365 // be CSE'd with N, and carry its uses with it. Iterate until no 1366 // uses remain, to ensure that the node can be safely deleted. 1367 // First add the users of this node to the work list so that they 1368 // can be tried again once they have new operands. 1369 AddUsersToWorkList(N); 1370 do { 1371 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) 1372 DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i)); 1373 } while (!N->use_empty()); 1374 removeFromWorkList(N); 1375 DAG.DeleteNode(N); 1376 return SDValue(N, 0); // Return N so it doesn't get rechecked! 1377} 1378 1379static 1380SDValue combineShlAddConstant(SDLoc DL, SDValue N0, SDValue N1, 1381 SelectionDAG &DAG) { 1382 EVT VT = N0.getValueType(); 1383 SDValue N00 = N0.getOperand(0); 1384 SDValue N01 = N0.getOperand(1); 1385 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N01); 1386 1387 if (N01C && N00.getOpcode() == ISD::ADD && N00.getNode()->hasOneUse() && 1388 isa<ConstantSDNode>(N00.getOperand(1))) { 1389 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), ) 1390 N0 = DAG.getNode(ISD::ADD, SDLoc(N0), VT, 1391 DAG.getNode(ISD::SHL, SDLoc(N00), VT, 1392 N00.getOperand(0), N01), 1393 DAG.getNode(ISD::SHL, SDLoc(N01), VT, 1394 N00.getOperand(1), N01)); 1395 return DAG.getNode(ISD::ADD, DL, VT, N0, N1); 1396 } 1397 1398 return SDValue(); 1399} 1400 1401SDValue DAGCombiner::visitADD(SDNode *N) { 1402 SDValue N0 = N->getOperand(0); 1403 SDValue N1 = N->getOperand(1); 1404 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 1405 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 1406 EVT VT = N0.getValueType(); 1407 1408 // fold vector ops 1409 if (VT.isVector()) { 1410 SDValue FoldedVOp = SimplifyVBinOp(N); 1411 if (FoldedVOp.getNode()) return FoldedVOp; 1412 1413 // fold (add x, 0) -> x, vector edition 1414 if (ISD::isBuildVectorAllZeros(N1.getNode())) 1415 return N0; 1416 if (ISD::isBuildVectorAllZeros(N0.getNode())) 1417 return N1; 1418 } 1419 1420 // fold (add x, undef) -> undef 1421 if (N0.getOpcode() == ISD::UNDEF) 1422 return N0; 1423 if (N1.getOpcode() == ISD::UNDEF) 1424 return N1; 1425 // fold (add c1, c2) -> c1+c2 1426 if (N0C && N1C) 1427 return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C); 1428 // canonicalize constant to RHS 1429 if (N0C && !N1C) 1430 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0); 1431 // fold (add x, 0) -> x 1432 if (N1C && N1C->isNullValue()) 1433 return N0; 1434 // fold (add Sym, c) -> Sym+c 1435 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0)) 1436 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C && 1437 GA->getOpcode() == ISD::GlobalAddress) 1438 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT, 1439 GA->getOffset() + 1440 (uint64_t)N1C->getSExtValue()); 1441 // fold ((c1-A)+c2) -> (c1+c2)-A 1442 if (N1C && N0.getOpcode() == ISD::SUB) 1443 if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0))) 1444 return DAG.getNode(ISD::SUB, SDLoc(N), VT, 1445 DAG.getConstant(N1C->getAPIntValue()+ 1446 N0C->getAPIntValue(), VT), 1447 N0.getOperand(1)); 1448 // reassociate add 1449 SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1); 1450 if (RADD.getNode() != 0) 1451 return RADD; 1452 // fold ((0-A) + B) -> B-A 1453 if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) && 1454 cast<ConstantSDNode>(N0.getOperand(0))->isNullValue()) 1455 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1)); 1456 // fold (A + (0-B)) -> A-B 1457 if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) && 1458 cast<ConstantSDNode>(N1.getOperand(0))->isNullValue()) 1459 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1)); 1460 // fold (A+(B-A)) -> B 1461 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1)) 1462 return N1.getOperand(0); 1463 // fold ((B-A)+A) -> B 1464 if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1)) 1465 return N0.getOperand(0); 1466 // fold (A+(B-(A+C))) to (B-C) 1467 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD && 1468 N0 == N1.getOperand(1).getOperand(0)) 1469 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0), 1470 N1.getOperand(1).getOperand(1)); 1471 // fold (A+(B-(C+A))) to (B-C) 1472 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD && 1473 N0 == N1.getOperand(1).getOperand(1)) 1474 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0), 1475 N1.getOperand(1).getOperand(0)); 1476 // fold (A+((B-A)+or-C)) to (B+or-C) 1477 if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) && 1478 N1.getOperand(0).getOpcode() == ISD::SUB && 1479 N0 == N1.getOperand(0).getOperand(1)) 1480 return DAG.getNode(N1.getOpcode(), SDLoc(N), VT, 1481 N1.getOperand(0).getOperand(0), N1.getOperand(1)); 1482 1483 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant 1484 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) { 1485 SDValue N00 = N0.getOperand(0); 1486 SDValue N01 = N0.getOperand(1); 1487 SDValue N10 = N1.getOperand(0); 1488 SDValue N11 = N1.getOperand(1); 1489 1490 if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10)) 1491 return DAG.getNode(ISD::SUB, SDLoc(N), VT, 1492 DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10), 1493 DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11)); 1494 } 1495 1496 if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0))) 1497 return SDValue(N, 0); 1498 1499 // fold (a+b) -> (a|b) iff a and b share no bits. 1500 if (VT.isInteger() && !VT.isVector()) { 1501 APInt LHSZero, LHSOne; 1502 APInt RHSZero, RHSOne; 1503 DAG.ComputeMaskedBits(N0, LHSZero, LHSOne); 1504 1505 if (LHSZero.getBoolValue()) { 1506 DAG.ComputeMaskedBits(N1, RHSZero, RHSOne); 1507 1508 // If all possibly-set bits on the LHS are clear on the RHS, return an OR. 1509 // If all possibly-set bits on the RHS are clear on the LHS, return an OR. 1510 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero) 1511 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1); 1512 } 1513 } 1514 1515 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), ) 1516 if (N0.getOpcode() == ISD::SHL && N0.getNode()->hasOneUse()) { 1517 SDValue Result = combineShlAddConstant(SDLoc(N), N0, N1, DAG); 1518 if (Result.getNode()) return Result; 1519 } 1520 if (N1.getOpcode() == ISD::SHL && N1.getNode()->hasOneUse()) { 1521 SDValue Result = combineShlAddConstant(SDLoc(N), N1, N0, DAG); 1522 if (Result.getNode()) return Result; 1523 } 1524 1525 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n)) 1526 if (N1.getOpcode() == ISD::SHL && 1527 N1.getOperand(0).getOpcode() == ISD::SUB) 1528 if (ConstantSDNode *C = 1529 dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0))) 1530 if (C->getAPIntValue() == 0) 1531 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, 1532 DAG.getNode(ISD::SHL, SDLoc(N), VT, 1533 N1.getOperand(0).getOperand(1), 1534 N1.getOperand(1))); 1535 if (N0.getOpcode() == ISD::SHL && 1536 N0.getOperand(0).getOpcode() == ISD::SUB) 1537 if (ConstantSDNode *C = 1538 dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0))) 1539 if (C->getAPIntValue() == 0) 1540 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, 1541 DAG.getNode(ISD::SHL, SDLoc(N), VT, 1542 N0.getOperand(0).getOperand(1), 1543 N0.getOperand(1))); 1544 1545 if (N1.getOpcode() == ISD::AND) { 1546 SDValue AndOp0 = N1.getOperand(0); 1547 ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1)); 1548 unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0); 1549 unsigned DestBits = VT.getScalarType().getSizeInBits(); 1550 1551 // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x)) 1552 // and similar xforms where the inner op is either ~0 or 0. 1553 if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) { 1554 SDLoc DL(N); 1555 return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0); 1556 } 1557 } 1558 1559 // add (sext i1), X -> sub X, (zext i1) 1560 if (N0.getOpcode() == ISD::SIGN_EXTEND && 1561 N0.getOperand(0).getValueType() == MVT::i1 && 1562 !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) { 1563 SDLoc DL(N); 1564 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)); 1565 return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt); 1566 } 1567 1568 return SDValue(); 1569} 1570 1571SDValue DAGCombiner::visitADDC(SDNode *N) { 1572 SDValue N0 = N->getOperand(0); 1573 SDValue N1 = N->getOperand(1); 1574 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 1575 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 1576 EVT VT = N0.getValueType(); 1577 1578 // If the flag result is dead, turn this into an ADD. 1579 if (!N->hasAnyUseOfValue(1)) 1580 return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1), 1581 DAG.getNode(ISD::CARRY_FALSE, 1582 SDLoc(N), MVT::Glue)); 1583 1584 // canonicalize constant to RHS. 1585 if (N0C && !N1C) 1586 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0); 1587 1588 // fold (addc x, 0) -> x + no carry out 1589 if (N1C && N1C->isNullValue()) 1590 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, 1591 SDLoc(N), MVT::Glue)); 1592 1593 // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits. 1594 APInt LHSZero, LHSOne; 1595 APInt RHSZero, RHSOne; 1596 DAG.ComputeMaskedBits(N0, LHSZero, LHSOne); 1597 1598 if (LHSZero.getBoolValue()) { 1599 DAG.ComputeMaskedBits(N1, RHSZero, RHSOne); 1600 1601 // If all possibly-set bits on the LHS are clear on the RHS, return an OR. 1602 // If all possibly-set bits on the RHS are clear on the LHS, return an OR. 1603 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero) 1604 return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1), 1605 DAG.getNode(ISD::CARRY_FALSE, 1606 SDLoc(N), MVT::Glue)); 1607 } 1608 1609 return SDValue(); 1610} 1611 1612SDValue DAGCombiner::visitADDE(SDNode *N) { 1613 SDValue N0 = N->getOperand(0); 1614 SDValue N1 = N->getOperand(1); 1615 SDValue CarryIn = N->getOperand(2); 1616 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 1617 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 1618 1619 // canonicalize constant to RHS 1620 if (N0C && !N1C) 1621 return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(), 1622 N1, N0, CarryIn); 1623 1624 // fold (adde x, y, false) -> (addc x, y) 1625 if (CarryIn.getOpcode() == ISD::CARRY_FALSE) 1626 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1); 1627 1628 return SDValue(); 1629} 1630 1631// Since it may not be valid to emit a fold to zero for vector initializers 1632// check if we can before folding. 1633static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT, 1634 SelectionDAG &DAG, 1635 bool LegalOperations, bool LegalTypes) { 1636 if (!VT.isVector()) 1637 return DAG.getConstant(0, VT); 1638 if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT)) { 1639 // Produce a vector of zeros. 1640 EVT ElemTy = VT.getVectorElementType(); 1641 if (LegalTypes && TLI.getTypeAction(*DAG.getContext(), ElemTy) == 1642 TargetLowering::TypePromoteInteger) 1643 ElemTy = TLI.getTypeToTransformTo(*DAG.getContext(), ElemTy); 1644 assert((!LegalTypes || TLI.isTypeLegal(ElemTy)) && 1645 "Type for zero vector elements is not legal"); 1646 SDValue El = DAG.getConstant(0, ElemTy); 1647 std::vector<SDValue> Ops(VT.getVectorNumElements(), El); 1648 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, 1649 &Ops[0], Ops.size()); 1650 } 1651 return SDValue(); 1652} 1653 1654SDValue DAGCombiner::visitSUB(SDNode *N) { 1655 SDValue N0 = N->getOperand(0); 1656 SDValue N1 = N->getOperand(1); 1657 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode()); 1658 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode()); 1659 ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? 0 : 1660 dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode()); 1661 EVT VT = N0.getValueType(); 1662 1663 // fold vector ops 1664 if (VT.isVector()) { 1665 SDValue FoldedVOp = SimplifyVBinOp(N); 1666 if (FoldedVOp.getNode()) return FoldedVOp; 1667 1668 // fold (sub x, 0) -> x, vector edition 1669 if (ISD::isBuildVectorAllZeros(N1.getNode())) 1670 return N0; 1671 } 1672 1673 // fold (sub x, x) -> 0 1674 // FIXME: Refactor this and xor and other similar operations together. 1675 if (N0 == N1) 1676 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes); 1677 // fold (sub c1, c2) -> c1-c2 1678 if (N0C && N1C) 1679 return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C); 1680 // fold (sub x, c) -> (add x, -c) 1681 if (N1C) 1682 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, 1683 DAG.getConstant(-N1C->getAPIntValue(), VT)); 1684 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) 1685 if (N0C && N0C->isAllOnesValue()) 1686 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0); 1687 // fold A-(A-B) -> B 1688 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0)) 1689 return N1.getOperand(1); 1690 // fold (A+B)-A -> B 1691 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1) 1692 return N0.getOperand(1); 1693 // fold (A+B)-B -> A 1694 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1) 1695 return N0.getOperand(0); 1696 // fold C2-(A+C1) -> (C2-C1)-A 1697 if (N1.getOpcode() == ISD::ADD && N0C && N1C1) { 1698 SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(), 1699 VT); 1700 return DAG.getNode(ISD::SUB, SDLoc(N), VT, NewC, 1701 N1.getOperand(0)); 1702 } 1703 // fold ((A+(B+or-C))-B) -> A+or-C 1704 if (N0.getOpcode() == ISD::ADD && 1705 (N0.getOperand(1).getOpcode() == ISD::SUB || 1706 N0.getOperand(1).getOpcode() == ISD::ADD) && 1707 N0.getOperand(1).getOperand(0) == N1) 1708 return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT, 1709 N0.getOperand(0), N0.getOperand(1).getOperand(1)); 1710 // fold ((A+(C+B))-B) -> A+C 1711 if (N0.getOpcode() == ISD::ADD && 1712 N0.getOperand(1).getOpcode() == ISD::ADD && 1713 N0.getOperand(1).getOperand(1) == N1) 1714 return DAG.getNode(ISD::ADD, SDLoc(N), VT, 1715 N0.getOperand(0), N0.getOperand(1).getOperand(0)); 1716 // fold ((A-(B-C))-C) -> A-B 1717 if (N0.getOpcode() == ISD::SUB && 1718 N0.getOperand(1).getOpcode() == ISD::SUB && 1719 N0.getOperand(1).getOperand(1) == N1) 1720 return DAG.getNode(ISD::SUB, SDLoc(N), VT, 1721 N0.getOperand(0), N0.getOperand(1).getOperand(0)); 1722 1723 // If either operand of a sub is undef, the result is undef 1724 if (N0.getOpcode() == ISD::UNDEF) 1725 return N0; 1726 if (N1.getOpcode() == ISD::UNDEF) 1727 return N1; 1728 1729 // If the relocation model supports it, consider symbol offsets. 1730 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0)) 1731 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) { 1732 // fold (sub Sym, c) -> Sym-c 1733 if (N1C && GA->getOpcode() == ISD::GlobalAddress) 1734 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT, 1735 GA->getOffset() - 1736 (uint64_t)N1C->getSExtValue()); 1737 // fold (sub Sym+c1, Sym+c2) -> c1-c2 1738 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1)) 1739 if (GA->getGlobal() == GB->getGlobal()) 1740 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(), 1741 VT); 1742 } 1743 1744 return SDValue(); 1745} 1746 1747SDValue DAGCombiner::visitSUBC(SDNode *N) { 1748 SDValue N0 = N->getOperand(0); 1749 SDValue N1 = N->getOperand(1); 1750 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 1751 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 1752 EVT VT = N0.getValueType(); 1753 1754 // If the flag result is dead, turn this into an SUB. 1755 if (!N->hasAnyUseOfValue(1)) 1756 return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1), 1757 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N), 1758 MVT::Glue)); 1759 1760 // fold (subc x, x) -> 0 + no borrow 1761 if (N0 == N1) 1762 return CombineTo(N, DAG.getConstant(0, VT), 1763 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N), 1764 MVT::Glue)); 1765 1766 // fold (subc x, 0) -> x + no borrow 1767 if (N1C && N1C->isNullValue()) 1768 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N), 1769 MVT::Glue)); 1770 1771 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow 1772 if (N0C && N0C->isAllOnesValue()) 1773 return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0), 1774 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N), 1775 MVT::Glue)); 1776 1777 return SDValue(); 1778} 1779 1780SDValue DAGCombiner::visitSUBE(SDNode *N) { 1781 SDValue N0 = N->getOperand(0); 1782 SDValue N1 = N->getOperand(1); 1783 SDValue CarryIn = N->getOperand(2); 1784 1785 // fold (sube x, y, false) -> (subc x, y) 1786 if (CarryIn.getOpcode() == ISD::CARRY_FALSE) 1787 return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1); 1788 1789 return SDValue(); 1790} 1791 1792/// isConstantSplatVector - Returns true if N is a BUILD_VECTOR node whose 1793/// elements are all the same constant or undefined. 1794static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) { 1795 BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N); 1796 if (!C) 1797 return false; 1798 1799 APInt SplatUndef; 1800 unsigned SplatBitSize; 1801 bool HasAnyUndefs; 1802 EVT EltVT = N->getValueType(0).getVectorElementType(); 1803 return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize, 1804 HasAnyUndefs) && 1805 EltVT.getSizeInBits() >= SplatBitSize); 1806} 1807 1808SDValue DAGCombiner::visitMUL(SDNode *N) { 1809 SDValue N0 = N->getOperand(0); 1810 SDValue N1 = N->getOperand(1); 1811 EVT VT = N0.getValueType(); 1812 1813 // fold (mul x, undef) -> 0 1814 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF) 1815 return DAG.getConstant(0, VT); 1816 1817 bool N0IsConst = false; 1818 bool N1IsConst = false; 1819 APInt ConstValue0, ConstValue1; 1820 // fold vector ops 1821 if (VT.isVector()) { 1822 SDValue FoldedVOp = SimplifyVBinOp(N); 1823 if (FoldedVOp.getNode()) return FoldedVOp; 1824 1825 N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0); 1826 N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1); 1827 } else { 1828 N0IsConst = dyn_cast<ConstantSDNode>(N0) != 0; 1829 ConstValue0 = N0IsConst ? (dyn_cast<ConstantSDNode>(N0))->getAPIntValue() 1830 : APInt(); 1831 N1IsConst = dyn_cast<ConstantSDNode>(N1) != 0; 1832 ConstValue1 = N1IsConst ? (dyn_cast<ConstantSDNode>(N1))->getAPIntValue() 1833 : APInt(); 1834 } 1835 1836 // fold (mul c1, c2) -> c1*c2 1837 if (N0IsConst && N1IsConst) 1838 return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0.getNode(), N1.getNode()); 1839 1840 // canonicalize constant to RHS 1841 if (N0IsConst && !N1IsConst) 1842 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0); 1843 // fold (mul x, 0) -> 0 1844 if (N1IsConst && ConstValue1 == 0) 1845 return N1; 1846 // We require a splat of the entire scalar bit width for non-contiguous 1847 // bit patterns. 1848 bool IsFullSplat = 1849 ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits(); 1850 // fold (mul x, 1) -> x 1851 if (N1IsConst && ConstValue1 == 1 && IsFullSplat) 1852 return N0; 1853 // fold (mul x, -1) -> 0-x 1854 if (N1IsConst && ConstValue1.isAllOnesValue()) 1855 return DAG.getNode(ISD::SUB, SDLoc(N), VT, 1856 DAG.getConstant(0, VT), N0); 1857 // fold (mul x, (1 << c)) -> x << c 1858 if (N1IsConst && ConstValue1.isPowerOf2() && IsFullSplat) 1859 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, 1860 DAG.getConstant(ConstValue1.logBase2(), 1861 getShiftAmountTy(N0.getValueType()))); 1862 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c 1863 if (N1IsConst && (-ConstValue1).isPowerOf2() && IsFullSplat) { 1864 unsigned Log2Val = (-ConstValue1).logBase2(); 1865 // FIXME: If the input is something that is easily negated (e.g. a 1866 // single-use add), we should put the negate there. 1867 return DAG.getNode(ISD::SUB, SDLoc(N), VT, 1868 DAG.getConstant(0, VT), 1869 DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, 1870 DAG.getConstant(Log2Val, 1871 getShiftAmountTy(N0.getValueType())))); 1872 } 1873 1874 APInt Val; 1875 // (mul (shl X, c1), c2) -> (mul X, c2 << c1) 1876 if (N1IsConst && N0.getOpcode() == ISD::SHL && 1877 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) || 1878 isa<ConstantSDNode>(N0.getOperand(1)))) { 1879 SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT, 1880 N1, N0.getOperand(1)); 1881 AddToWorkList(C3.getNode()); 1882 return DAG.getNode(ISD::MUL, SDLoc(N), VT, 1883 N0.getOperand(0), C3); 1884 } 1885 1886 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one 1887 // use. 1888 { 1889 SDValue Sh(0,0), Y(0,0); 1890 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)). 1891 if (N0.getOpcode() == ISD::SHL && 1892 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) || 1893 isa<ConstantSDNode>(N0.getOperand(1))) && 1894 N0.getNode()->hasOneUse()) { 1895 Sh = N0; Y = N1; 1896 } else if (N1.getOpcode() == ISD::SHL && 1897 isa<ConstantSDNode>(N1.getOperand(1)) && 1898 N1.getNode()->hasOneUse()) { 1899 Sh = N1; Y = N0; 1900 } 1901 1902 if (Sh.getNode()) { 1903 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT, 1904 Sh.getOperand(0), Y); 1905 return DAG.getNode(ISD::SHL, SDLoc(N), VT, 1906 Mul, Sh.getOperand(1)); 1907 } 1908 } 1909 1910 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2) 1911 if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() && 1912 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) || 1913 isa<ConstantSDNode>(N0.getOperand(1)))) 1914 return DAG.getNode(ISD::ADD, SDLoc(N), VT, 1915 DAG.getNode(ISD::MUL, SDLoc(N0), VT, 1916 N0.getOperand(0), N1), 1917 DAG.getNode(ISD::MUL, SDLoc(N1), VT, 1918 N0.getOperand(1), N1)); 1919 1920 // reassociate mul 1921 SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1); 1922 if (RMUL.getNode() != 0) 1923 return RMUL; 1924 1925 return SDValue(); 1926} 1927 1928SDValue DAGCombiner::visitSDIV(SDNode *N) { 1929 SDValue N0 = N->getOperand(0); 1930 SDValue N1 = N->getOperand(1); 1931 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode()); 1932 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode()); 1933 EVT VT = N->getValueType(0); 1934 1935 // fold vector ops 1936 if (VT.isVector()) { 1937 SDValue FoldedVOp = SimplifyVBinOp(N); 1938 if (FoldedVOp.getNode()) return FoldedVOp; 1939 } 1940 1941 // fold (sdiv c1, c2) -> c1/c2 1942 if (N0C && N1C && !N1C->isNullValue()) 1943 return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C); 1944 // fold (sdiv X, 1) -> X 1945 if (N1C && N1C->getAPIntValue() == 1LL) 1946 return N0; 1947 // fold (sdiv X, -1) -> 0-X 1948 if (N1C && N1C->isAllOnesValue()) 1949 return DAG.getNode(ISD::SUB, SDLoc(N), VT, 1950 DAG.getConstant(0, VT), N0); 1951 // If we know the sign bits of both operands are zero, strength reduce to a 1952 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2 1953 if (!VT.isVector()) { 1954 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0)) 1955 return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(), 1956 N0, N1); 1957 } 1958 // fold (sdiv X, pow2) -> simple ops after legalize 1959 if (N1C && !N1C->isNullValue() && 1960 (N1C->getAPIntValue().isPowerOf2() || 1961 (-N1C->getAPIntValue()).isPowerOf2())) { 1962 // If dividing by powers of two is cheap, then don't perform the following 1963 // fold. 1964 if (TLI.isPow2DivCheap()) 1965 return SDValue(); 1966 1967 unsigned lg2 = N1C->getAPIntValue().countTrailingZeros(); 1968 1969 // Splat the sign bit into the register 1970 SDValue SGN = DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, 1971 DAG.getConstant(VT.getSizeInBits()-1, 1972 getShiftAmountTy(N0.getValueType()))); 1973 AddToWorkList(SGN.getNode()); 1974 1975 // Add (N0 < 0) ? abs2 - 1 : 0; 1976 SDValue SRL = DAG.getNode(ISD::SRL, SDLoc(N), VT, SGN, 1977 DAG.getConstant(VT.getSizeInBits() - lg2, 1978 getShiftAmountTy(SGN.getValueType()))); 1979 SDValue ADD = DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, SRL); 1980 AddToWorkList(SRL.getNode()); 1981 AddToWorkList(ADD.getNode()); // Divide by pow2 1982 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), VT, ADD, 1983 DAG.getConstant(lg2, getShiftAmountTy(ADD.getValueType()))); 1984 1985 // If we're dividing by a positive value, we're done. Otherwise, we must 1986 // negate the result. 1987 if (N1C->getAPIntValue().isNonNegative()) 1988 return SRA; 1989 1990 AddToWorkList(SRA.getNode()); 1991 return DAG.getNode(ISD::SUB, SDLoc(N), VT, 1992 DAG.getConstant(0, VT), SRA); 1993 } 1994 1995 // if integer divide is expensive and we satisfy the requirements, emit an 1996 // alternate sequence. 1997 if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap()) { 1998 SDValue Op = BuildSDIV(N); 1999 if (Op.getNode()) return Op; 2000 } 2001 2002 // undef / X -> 0 2003 if (N0.getOpcode() == ISD::UNDEF) 2004 return DAG.getConstant(0, VT); 2005 // X / undef -> undef 2006 if (N1.getOpcode() == ISD::UNDEF) 2007 return N1; 2008 2009 return SDValue(); 2010} 2011 2012SDValue DAGCombiner::visitUDIV(SDNode *N) { 2013 SDValue N0 = N->getOperand(0); 2014 SDValue N1 = N->getOperand(1); 2015 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode()); 2016 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode()); 2017 EVT VT = N->getValueType(0); 2018 2019 // fold vector ops 2020 if (VT.isVector()) { 2021 SDValue FoldedVOp = SimplifyVBinOp(N); 2022 if (FoldedVOp.getNode()) return FoldedVOp; 2023 } 2024 2025 // fold (udiv c1, c2) -> c1/c2 2026 if (N0C && N1C && !N1C->isNullValue()) 2027 return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C); 2028 // fold (udiv x, (1 << c)) -> x >>u c 2029 if (N1C && N1C->getAPIntValue().isPowerOf2()) 2030 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, 2031 DAG.getConstant(N1C->getAPIntValue().logBase2(), 2032 getShiftAmountTy(N0.getValueType()))); 2033 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2 2034 if (N1.getOpcode() == ISD::SHL) { 2035 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) { 2036 if (SHC->getAPIntValue().isPowerOf2()) { 2037 EVT ADDVT = N1.getOperand(1).getValueType(); 2038 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N), ADDVT, 2039 N1.getOperand(1), 2040 DAG.getConstant(SHC->getAPIntValue() 2041 .logBase2(), 2042 ADDVT)); 2043 AddToWorkList(Add.getNode()); 2044 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, Add); 2045 } 2046 } 2047 } 2048 // fold (udiv x, c) -> alternate 2049 if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap()) { 2050 SDValue Op = BuildUDIV(N); 2051 if (Op.getNode()) return Op; 2052 } 2053 2054 // undef / X -> 0 2055 if (N0.getOpcode() == ISD::UNDEF) 2056 return DAG.getConstant(0, VT); 2057 // X / undef -> undef 2058 if (N1.getOpcode() == ISD::UNDEF) 2059 return N1; 2060 2061 return SDValue(); 2062} 2063 2064SDValue DAGCombiner::visitSREM(SDNode *N) { 2065 SDValue N0 = N->getOperand(0); 2066 SDValue N1 = N->getOperand(1); 2067 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 2068 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 2069 EVT VT = N->getValueType(0); 2070 2071 // fold (srem c1, c2) -> c1%c2 2072 if (N0C && N1C && !N1C->isNullValue()) 2073 return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C); 2074 // If we know the sign bits of both operands are zero, strength reduce to a 2075 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15 2076 if (!VT.isVector()) { 2077 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0)) 2078 return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1); 2079 } 2080 2081 // If X/C can be simplified by the division-by-constant logic, lower 2082 // X%C to the equivalent of X-X/C*C. 2083 if (N1C && !N1C->isNullValue()) { 2084 SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1); 2085 AddToWorkList(Div.getNode()); 2086 SDValue OptimizedDiv = combine(Div.getNode()); 2087 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) { 2088 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT, 2089 OptimizedDiv, N1); 2090 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul); 2091 AddToWorkList(Mul.getNode()); 2092 return Sub; 2093 } 2094 } 2095 2096 // undef % X -> 0 2097 if (N0.getOpcode() == ISD::UNDEF) 2098 return DAG.getConstant(0, VT); 2099 // X % undef -> undef 2100 if (N1.getOpcode() == ISD::UNDEF) 2101 return N1; 2102 2103 return SDValue(); 2104} 2105 2106SDValue DAGCombiner::visitUREM(SDNode *N) { 2107 SDValue N0 = N->getOperand(0); 2108 SDValue N1 = N->getOperand(1); 2109 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 2110 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 2111 EVT VT = N->getValueType(0); 2112 2113 // fold (urem c1, c2) -> c1%c2 2114 if (N0C && N1C && !N1C->isNullValue()) 2115 return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C); 2116 // fold (urem x, pow2) -> (and x, pow2-1) 2117 if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2()) 2118 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, 2119 DAG.getConstant(N1C->getAPIntValue()-1,VT)); 2120 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1)) 2121 if (N1.getOpcode() == ISD::SHL) { 2122 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) { 2123 if (SHC->getAPIntValue().isPowerOf2()) { 2124 SDValue Add = 2125 DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, 2126 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), 2127 VT)); 2128 AddToWorkList(Add.getNode()); 2129 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, Add); 2130 } 2131 } 2132 } 2133 2134 // If X/C can be simplified by the division-by-constant logic, lower 2135 // X%C to the equivalent of X-X/C*C. 2136 if (N1C && !N1C->isNullValue()) { 2137 SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1); 2138 AddToWorkList(Div.getNode()); 2139 SDValue OptimizedDiv = combine(Div.getNode()); 2140 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) { 2141 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT, 2142 OptimizedDiv, N1); 2143 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul); 2144 AddToWorkList(Mul.getNode()); 2145 return Sub; 2146 } 2147 } 2148 2149 // undef % X -> 0 2150 if (N0.getOpcode() == ISD::UNDEF) 2151 return DAG.getConstant(0, VT); 2152 // X % undef -> undef 2153 if (N1.getOpcode() == ISD::UNDEF) 2154 return N1; 2155 2156 return SDValue(); 2157} 2158 2159SDValue DAGCombiner::visitMULHS(SDNode *N) { 2160 SDValue N0 = N->getOperand(0); 2161 SDValue N1 = N->getOperand(1); 2162 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 2163 EVT VT = N->getValueType(0); 2164 SDLoc DL(N); 2165 2166 // fold (mulhs x, 0) -> 0 2167 if (N1C && N1C->isNullValue()) 2168 return N1; 2169 // fold (mulhs x, 1) -> (sra x, size(x)-1) 2170 if (N1C && N1C->getAPIntValue() == 1) 2171 return DAG.getNode(ISD::SRA, SDLoc(N), N0.getValueType(), N0, 2172 DAG.getConstant(N0.getValueType().getSizeInBits() - 1, 2173 getShiftAmountTy(N0.getValueType()))); 2174 // fold (mulhs x, undef) -> 0 2175 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF) 2176 return DAG.getConstant(0, VT); 2177 2178 // If the type twice as wide is legal, transform the mulhs to a wider multiply 2179 // plus a shift. 2180 if (VT.isSimple() && !VT.isVector()) { 2181 MVT Simple = VT.getSimpleVT(); 2182 unsigned SimpleSize = Simple.getSizeInBits(); 2183 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 2184 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 2185 N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0); 2186 N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1); 2187 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1); 2188 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1, 2189 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType()))); 2190 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1); 2191 } 2192 } 2193 2194 return SDValue(); 2195} 2196 2197SDValue DAGCombiner::visitMULHU(SDNode *N) { 2198 SDValue N0 = N->getOperand(0); 2199 SDValue N1 = N->getOperand(1); 2200 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 2201 EVT VT = N->getValueType(0); 2202 SDLoc DL(N); 2203 2204 // fold (mulhu x, 0) -> 0 2205 if (N1C && N1C->isNullValue()) 2206 return N1; 2207 // fold (mulhu x, 1) -> 0 2208 if (N1C && N1C->getAPIntValue() == 1) 2209 return DAG.getConstant(0, N0.getValueType()); 2210 // fold (mulhu x, undef) -> 0 2211 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF) 2212 return DAG.getConstant(0, VT); 2213 2214 // If the type twice as wide is legal, transform the mulhu to a wider multiply 2215 // plus a shift. 2216 if (VT.isSimple() && !VT.isVector()) { 2217 MVT Simple = VT.getSimpleVT(); 2218 unsigned SimpleSize = Simple.getSizeInBits(); 2219 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 2220 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 2221 N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0); 2222 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1); 2223 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1); 2224 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1, 2225 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType()))); 2226 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1); 2227 } 2228 } 2229 2230 return SDValue(); 2231} 2232 2233/// SimplifyNodeWithTwoResults - Perform optimizations common to nodes that 2234/// compute two values. LoOp and HiOp give the opcodes for the two computations 2235/// that are being performed. Return true if a simplification was made. 2236/// 2237SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp, 2238 unsigned HiOp) { 2239 // If the high half is not needed, just compute the low half. 2240 bool HiExists = N->hasAnyUseOfValue(1); 2241 if (!HiExists && 2242 (!LegalOperations || 2243 TLI.isOperationLegal(LoOp, N->getValueType(0)))) { 2244 SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), 2245 N->op_begin(), N->getNumOperands()); 2246 return CombineTo(N, Res, Res); 2247 } 2248 2249 // If the low half is not needed, just compute the high half. 2250 bool LoExists = N->hasAnyUseOfValue(0); 2251 if (!LoExists && 2252 (!LegalOperations || 2253 TLI.isOperationLegal(HiOp, N->getValueType(1)))) { 2254 SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), 2255 N->op_begin(), N->getNumOperands()); 2256 return CombineTo(N, Res, Res); 2257 } 2258 2259 // If both halves are used, return as it is. 2260 if (LoExists && HiExists) 2261 return SDValue(); 2262 2263 // If the two computed results can be simplified separately, separate them. 2264 if (LoExists) { 2265 SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), 2266 N->op_begin(), N->getNumOperands()); 2267 AddToWorkList(Lo.getNode()); 2268 SDValue LoOpt = combine(Lo.getNode()); 2269 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() && 2270 (!LegalOperations || 2271 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType()))) 2272 return CombineTo(N, LoOpt, LoOpt); 2273 } 2274 2275 if (HiExists) { 2276 SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), 2277 N->op_begin(), N->getNumOperands()); 2278 AddToWorkList(Hi.getNode()); 2279 SDValue HiOpt = combine(Hi.getNode()); 2280 if (HiOpt.getNode() && HiOpt != Hi && 2281 (!LegalOperations || 2282 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType()))) 2283 return CombineTo(N, HiOpt, HiOpt); 2284 } 2285 2286 return SDValue(); 2287} 2288 2289SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) { 2290 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS); 2291 if (Res.getNode()) return Res; 2292 2293 EVT VT = N->getValueType(0); 2294 SDLoc DL(N); 2295 2296 // If the type twice as wide is legal, transform the mulhu to a wider multiply 2297 // plus a shift. 2298 if (VT.isSimple() && !VT.isVector()) { 2299 MVT Simple = VT.getSimpleVT(); 2300 unsigned SimpleSize = Simple.getSizeInBits(); 2301 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 2302 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 2303 SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0)); 2304 SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1)); 2305 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi); 2306 // Compute the high part as N1. 2307 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo, 2308 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType()))); 2309 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi); 2310 // Compute the low part as N0. 2311 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo); 2312 return CombineTo(N, Lo, Hi); 2313 } 2314 } 2315 2316 return SDValue(); 2317} 2318 2319SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) { 2320 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU); 2321 if (Res.getNode()) return Res; 2322 2323 EVT VT = N->getValueType(0); 2324 SDLoc DL(N); 2325 2326 // If the type twice as wide is legal, transform the mulhu to a wider multiply 2327 // plus a shift. 2328 if (VT.isSimple() && !VT.isVector()) { 2329 MVT Simple = VT.getSimpleVT(); 2330 unsigned SimpleSize = Simple.getSizeInBits(); 2331 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 2332 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 2333 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0)); 2334 SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1)); 2335 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi); 2336 // Compute the high part as N1. 2337 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo, 2338 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType()))); 2339 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi); 2340 // Compute the low part as N0. 2341 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo); 2342 return CombineTo(N, Lo, Hi); 2343 } 2344 } 2345 2346 return SDValue(); 2347} 2348 2349SDValue DAGCombiner::visitSMULO(SDNode *N) { 2350 // (smulo x, 2) -> (saddo x, x) 2351 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1))) 2352 if (C2->getAPIntValue() == 2) 2353 return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(), 2354 N->getOperand(0), N->getOperand(0)); 2355 2356 return SDValue(); 2357} 2358 2359SDValue DAGCombiner::visitUMULO(SDNode *N) { 2360 // (umulo x, 2) -> (uaddo x, x) 2361 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1))) 2362 if (C2->getAPIntValue() == 2) 2363 return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(), 2364 N->getOperand(0), N->getOperand(0)); 2365 2366 return SDValue(); 2367} 2368 2369SDValue DAGCombiner::visitSDIVREM(SDNode *N) { 2370 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM); 2371 if (Res.getNode()) return Res; 2372 2373 return SDValue(); 2374} 2375 2376SDValue DAGCombiner::visitUDIVREM(SDNode *N) { 2377 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM); 2378 if (Res.getNode()) return Res; 2379 2380 return SDValue(); 2381} 2382 2383/// SimplifyBinOpWithSameOpcodeHands - If this is a binary operator with 2384/// two operands of the same opcode, try to simplify it. 2385SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) { 2386 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1); 2387 EVT VT = N0.getValueType(); 2388 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!"); 2389 2390 // Bail early if none of these transforms apply. 2391 if (N0.getNode()->getNumOperands() == 0) return SDValue(); 2392 2393 // For each of OP in AND/OR/XOR: 2394 // fold (OP (zext x), (zext y)) -> (zext (OP x, y)) 2395 // fold (OP (sext x), (sext y)) -> (sext (OP x, y)) 2396 // fold (OP (aext x), (aext y)) -> (aext (OP x, y)) 2397 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free) 2398 // 2399 // do not sink logical op inside of a vector extend, since it may combine 2400 // into a vsetcc. 2401 EVT Op0VT = N0.getOperand(0).getValueType(); 2402 if ((N0.getOpcode() == ISD::ZERO_EXTEND || 2403 N0.getOpcode() == ISD::SIGN_EXTEND || 2404 // Avoid infinite looping with PromoteIntBinOp. 2405 (N0.getOpcode() == ISD::ANY_EXTEND && 2406 (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) || 2407 (N0.getOpcode() == ISD::TRUNCATE && 2408 (!TLI.isZExtFree(VT, Op0VT) || 2409 !TLI.isTruncateFree(Op0VT, VT)) && 2410 TLI.isTypeLegal(Op0VT))) && 2411 !VT.isVector() && 2412 Op0VT == N1.getOperand(0).getValueType() && 2413 (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) { 2414 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0), 2415 N0.getOperand(0).getValueType(), 2416 N0.getOperand(0), N1.getOperand(0)); 2417 AddToWorkList(ORNode.getNode()); 2418 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode); 2419 } 2420 2421 // For each of OP in SHL/SRL/SRA/AND... 2422 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z) 2423 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z) 2424 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z) 2425 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL || 2426 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) && 2427 N0.getOperand(1) == N1.getOperand(1)) { 2428 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0), 2429 N0.getOperand(0).getValueType(), 2430 N0.getOperand(0), N1.getOperand(0)); 2431 AddToWorkList(ORNode.getNode()); 2432 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, 2433 ORNode, N0.getOperand(1)); 2434 } 2435 2436 // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B)) 2437 // Only perform this optimization after type legalization and before 2438 // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by 2439 // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and 2440 // we don't want to undo this promotion. 2441 // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper 2442 // on scalars. 2443 if ((N0.getOpcode() == ISD::BITCAST || 2444 N0.getOpcode() == ISD::SCALAR_TO_VECTOR) && 2445 Level == AfterLegalizeTypes) { 2446 SDValue In0 = N0.getOperand(0); 2447 SDValue In1 = N1.getOperand(0); 2448 EVT In0Ty = In0.getValueType(); 2449 EVT In1Ty = In1.getValueType(); 2450 SDLoc DL(N); 2451 // If both incoming values are integers, and the original types are the 2452 // same. 2453 if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) { 2454 SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1); 2455 SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op); 2456 AddToWorkList(Op.getNode()); 2457 return BC; 2458 } 2459 } 2460 2461 // Xor/and/or are indifferent to the swizzle operation (shuffle of one value). 2462 // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B)) 2463 // If both shuffles use the same mask, and both shuffle within a single 2464 // vector, then it is worthwhile to move the swizzle after the operation. 2465 // The type-legalizer generates this pattern when loading illegal 2466 // vector types from memory. In many cases this allows additional shuffle 2467 // optimizations. 2468 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG && 2469 N0.getOperand(1).getOpcode() == ISD::UNDEF && 2470 N1.getOperand(1).getOpcode() == ISD::UNDEF) { 2471 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0); 2472 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1); 2473 2474 assert(N0.getOperand(0).getValueType() == N1.getOperand(1).getValueType() && 2475 "Inputs to shuffles are not the same type"); 2476 2477 unsigned NumElts = VT.getVectorNumElements(); 2478 2479 // Check that both shuffles use the same mask. The masks are known to be of 2480 // the same length because the result vector type is the same. 2481 bool SameMask = true; 2482 for (unsigned i = 0; i != NumElts; ++i) { 2483 int Idx0 = SVN0->getMaskElt(i); 2484 int Idx1 = SVN1->getMaskElt(i); 2485 if (Idx0 != Idx1) { 2486 SameMask = false; 2487 break; 2488 } 2489 } 2490 2491 if (SameMask) { 2492 SDValue Op = DAG.getNode(N->getOpcode(), SDLoc(N), VT, 2493 N0.getOperand(0), N1.getOperand(0)); 2494 AddToWorkList(Op.getNode()); 2495 return DAG.getVectorShuffle(VT, SDLoc(N), Op, 2496 DAG.getUNDEF(VT), &SVN0->getMask()[0]); 2497 } 2498 } 2499 2500 return SDValue(); 2501} 2502 2503SDValue DAGCombiner::visitAND(SDNode *N) { 2504 SDValue N0 = N->getOperand(0); 2505 SDValue N1 = N->getOperand(1); 2506 SDValue LL, LR, RL, RR, CC0, CC1; 2507 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 2508 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 2509 EVT VT = N1.getValueType(); 2510 unsigned BitWidth = VT.getScalarType().getSizeInBits(); 2511 2512 // fold vector ops 2513 if (VT.isVector()) { 2514 SDValue FoldedVOp = SimplifyVBinOp(N); 2515 if (FoldedVOp.getNode()) return FoldedVOp; 2516 2517 // fold (and x, 0) -> 0, vector edition 2518 if (ISD::isBuildVectorAllZeros(N0.getNode())) 2519 return N0; 2520 if (ISD::isBuildVectorAllZeros(N1.getNode())) 2521 return N1; 2522 2523 // fold (and x, -1) -> x, vector edition 2524 if (ISD::isBuildVectorAllOnes(N0.getNode())) 2525 return N1; 2526 if (ISD::isBuildVectorAllOnes(N1.getNode())) 2527 return N0; 2528 } 2529 2530 // fold (and x, undef) -> 0 2531 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF) 2532 return DAG.getConstant(0, VT); 2533 // fold (and c1, c2) -> c1&c2 2534 if (N0C && N1C) 2535 return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C); 2536 // canonicalize constant to RHS 2537 if (N0C && !N1C) 2538 return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0); 2539 // fold (and x, -1) -> x 2540 if (N1C && N1C->isAllOnesValue()) 2541 return N0; 2542 // if (and x, c) is known to be zero, return 0 2543 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0), 2544 APInt::getAllOnesValue(BitWidth))) 2545 return DAG.getConstant(0, VT); 2546 // reassociate and 2547 SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1); 2548 if (RAND.getNode() != 0) 2549 return RAND; 2550 // fold (and (or x, C), D) -> D if (C & D) == D 2551 if (N1C && N0.getOpcode() == ISD::OR) 2552 if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) 2553 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue()) 2554 return N1; 2555 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits. 2556 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) { 2557 SDValue N0Op0 = N0.getOperand(0); 2558 APInt Mask = ~N1C->getAPIntValue(); 2559 Mask = Mask.trunc(N0Op0.getValueSizeInBits()); 2560 if (DAG.MaskedValueIsZero(N0Op0, Mask)) { 2561 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), 2562 N0.getValueType(), N0Op0); 2563 2564 // Replace uses of the AND with uses of the Zero extend node. 2565 CombineTo(N, Zext); 2566 2567 // We actually want to replace all uses of the any_extend with the 2568 // zero_extend, to avoid duplicating things. This will later cause this 2569 // AND to be folded. 2570 CombineTo(N0.getNode(), Zext); 2571 return SDValue(N, 0); // Return N so it doesn't get rechecked! 2572 } 2573 } 2574 // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) -> 2575 // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must 2576 // already be zero by virtue of the width of the base type of the load. 2577 // 2578 // the 'X' node here can either be nothing or an extract_vector_elt to catch 2579 // more cases. 2580 if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT && 2581 N0.getOperand(0).getOpcode() == ISD::LOAD) || 2582 N0.getOpcode() == ISD::LOAD) { 2583 LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ? 2584 N0 : N0.getOperand(0) ); 2585 2586 // Get the constant (if applicable) the zero'th operand is being ANDed with. 2587 // This can be a pure constant or a vector splat, in which case we treat the 2588 // vector as a scalar and use the splat value. 2589 APInt Constant = APInt::getNullValue(1); 2590 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) { 2591 Constant = C->getAPIntValue(); 2592 } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) { 2593 APInt SplatValue, SplatUndef; 2594 unsigned SplatBitSize; 2595 bool HasAnyUndefs; 2596 bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef, 2597 SplatBitSize, HasAnyUndefs); 2598 if (IsSplat) { 2599 // Undef bits can contribute to a possible optimisation if set, so 2600 // set them. 2601 SplatValue |= SplatUndef; 2602 2603 // The splat value may be something like "0x00FFFFFF", which means 0 for 2604 // the first vector value and FF for the rest, repeating. We need a mask 2605 // that will apply equally to all members of the vector, so AND all the 2606 // lanes of the constant together. 2607 EVT VT = Vector->getValueType(0); 2608 unsigned BitWidth = VT.getVectorElementType().getSizeInBits(); 2609 2610 // If the splat value has been compressed to a bitlength lower 2611 // than the size of the vector lane, we need to re-expand it to 2612 // the lane size. 2613 if (BitWidth > SplatBitSize) 2614 for (SplatValue = SplatValue.zextOrTrunc(BitWidth); 2615 SplatBitSize < BitWidth; 2616 SplatBitSize = SplatBitSize * 2) 2617 SplatValue |= SplatValue.shl(SplatBitSize); 2618 2619 Constant = APInt::getAllOnesValue(BitWidth); 2620 for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i) 2621 Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth); 2622 } 2623 } 2624 2625 // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is 2626 // actually legal and isn't going to get expanded, else this is a false 2627 // optimisation. 2628 bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD, 2629 Load->getMemoryVT()); 2630 2631 // Resize the constant to the same size as the original memory access before 2632 // extension. If it is still the AllOnesValue then this AND is completely 2633 // unneeded. 2634 Constant = 2635 Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits()); 2636 2637 bool B; 2638 switch (Load->getExtensionType()) { 2639 default: B = false; break; 2640 case ISD::EXTLOAD: B = CanZextLoadProfitably; break; 2641 case ISD::ZEXTLOAD: 2642 case ISD::NON_EXTLOAD: B = true; break; 2643 } 2644 2645 if (B && Constant.isAllOnesValue()) { 2646 // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to 2647 // preserve semantics once we get rid of the AND. 2648 SDValue NewLoad(Load, 0); 2649 if (Load->getExtensionType() == ISD::EXTLOAD) { 2650 NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD, 2651 Load->getValueType(0), SDLoc(Load), 2652 Load->getChain(), Load->getBasePtr(), 2653 Load->getOffset(), Load->getMemoryVT(), 2654 Load->getMemOperand()); 2655 // Replace uses of the EXTLOAD with the new ZEXTLOAD. 2656 if (Load->getNumValues() == 3) { 2657 // PRE/POST_INC loads have 3 values. 2658 SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1), 2659 NewLoad.getValue(2) }; 2660 CombineTo(Load, To, 3, true); 2661 } else { 2662 CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1)); 2663 } 2664 } 2665 2666 // Fold the AND away, taking care not to fold to the old load node if we 2667 // replaced it. 2668 CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0); 2669 2670 return SDValue(N, 0); // Return N so it doesn't get rechecked! 2671 } 2672 } 2673 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y)) 2674 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){ 2675 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get(); 2676 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get(); 2677 2678 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 && 2679 LL.getValueType().isInteger()) { 2680 // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0) 2681 if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) { 2682 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0), 2683 LR.getValueType(), LL, RL); 2684 AddToWorkList(ORNode.getNode()); 2685 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1); 2686 } 2687 // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1) 2688 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) { 2689 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0), 2690 LR.getValueType(), LL, RL); 2691 AddToWorkList(ANDNode.getNode()); 2692 return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1); 2693 } 2694 // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1) 2695 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) { 2696 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0), 2697 LR.getValueType(), LL, RL); 2698 AddToWorkList(ORNode.getNode()); 2699 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1); 2700 } 2701 } 2702 // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2) 2703 if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) && 2704 Op0 == Op1 && LL.getValueType().isInteger() && 2705 Op0 == ISD::SETNE && ((cast<ConstantSDNode>(LR)->isNullValue() && 2706 cast<ConstantSDNode>(RR)->isAllOnesValue()) || 2707 (cast<ConstantSDNode>(LR)->isAllOnesValue() && 2708 cast<ConstantSDNode>(RR)->isNullValue()))) { 2709 SDValue ADDNode = DAG.getNode(ISD::ADD, SDLoc(N0), LL.getValueType(), 2710 LL, DAG.getConstant(1, LL.getValueType())); 2711 AddToWorkList(ADDNode.getNode()); 2712 return DAG.getSetCC(SDLoc(N), VT, ADDNode, 2713 DAG.getConstant(2, LL.getValueType()), ISD::SETUGE); 2714 } 2715 // canonicalize equivalent to ll == rl 2716 if (LL == RR && LR == RL) { 2717 Op1 = ISD::getSetCCSwappedOperands(Op1); 2718 std::swap(RL, RR); 2719 } 2720 if (LL == RL && LR == RR) { 2721 bool isInteger = LL.getValueType().isInteger(); 2722 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger); 2723 if (Result != ISD::SETCC_INVALID && 2724 (!LegalOperations || 2725 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) && 2726 TLI.isOperationLegal(ISD::SETCC, 2727 getSetCCResultType(N0.getSimpleValueType()))))) 2728 return DAG.getSetCC(SDLoc(N), N0.getValueType(), 2729 LL, LR, Result); 2730 } 2731 } 2732 2733 // Simplify: (and (op x...), (op y...)) -> (op (and x, y)) 2734 if (N0.getOpcode() == N1.getOpcode()) { 2735 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N); 2736 if (Tmp.getNode()) return Tmp; 2737 } 2738 2739 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1) 2740 // fold (and (sra)) -> (and (srl)) when possible. 2741 if (!VT.isVector() && 2742 SimplifyDemandedBits(SDValue(N, 0))) 2743 return SDValue(N, 0); 2744 2745 // fold (zext_inreg (extload x)) -> (zextload x) 2746 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) { 2747 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 2748 EVT MemVT = LN0->getMemoryVT(); 2749 // If we zero all the possible extended bits, then we can turn this into 2750 // a zextload if we are running before legalize or the operation is legal. 2751 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits(); 2752 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth, 2753 BitWidth - MemVT.getScalarType().getSizeInBits())) && 2754 ((!LegalOperations && !LN0->isVolatile()) || 2755 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) { 2756 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT, 2757 LN0->getChain(), LN0->getBasePtr(), 2758 MemVT, LN0->getMemOperand()); 2759 AddToWorkList(N); 2760 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 2761 return SDValue(N, 0); // Return N so it doesn't get rechecked! 2762 } 2763 } 2764 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use 2765 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 2766 N0.hasOneUse()) { 2767 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 2768 EVT MemVT = LN0->getMemoryVT(); 2769 // If we zero all the possible extended bits, then we can turn this into 2770 // a zextload if we are running before legalize or the operation is legal. 2771 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits(); 2772 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth, 2773 BitWidth - MemVT.getScalarType().getSizeInBits())) && 2774 ((!LegalOperations && !LN0->isVolatile()) || 2775 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) { 2776 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT, 2777 LN0->getChain(), LN0->getBasePtr(), 2778 MemVT, LN0->getMemOperand()); 2779 AddToWorkList(N); 2780 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 2781 return SDValue(N, 0); // Return N so it doesn't get rechecked! 2782 } 2783 } 2784 2785 // fold (and (load x), 255) -> (zextload x, i8) 2786 // fold (and (extload x, i16), 255) -> (zextload x, i8) 2787 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8) 2788 if (N1C && (N0.getOpcode() == ISD::LOAD || 2789 (N0.getOpcode() == ISD::ANY_EXTEND && 2790 N0.getOperand(0).getOpcode() == ISD::LOAD))) { 2791 bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND; 2792 LoadSDNode *LN0 = HasAnyExt 2793 ? cast<LoadSDNode>(N0.getOperand(0)) 2794 : cast<LoadSDNode>(N0); 2795 if (LN0->getExtensionType() != ISD::SEXTLOAD && 2796 LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) { 2797 uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits(); 2798 if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){ 2799 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits); 2800 EVT LoadedVT = LN0->getMemoryVT(); 2801 2802 if (ExtVT == LoadedVT && 2803 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) { 2804 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT; 2805 2806 SDValue NewLoad = 2807 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy, 2808 LN0->getChain(), LN0->getBasePtr(), ExtVT, 2809 LN0->getMemOperand()); 2810 AddToWorkList(N); 2811 CombineTo(LN0, NewLoad, NewLoad.getValue(1)); 2812 return SDValue(N, 0); // Return N so it doesn't get rechecked! 2813 } 2814 2815 // Do not change the width of a volatile load. 2816 // Do not generate loads of non-round integer types since these can 2817 // be expensive (and would be wrong if the type is not byte sized). 2818 if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() && 2819 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) { 2820 EVT PtrType = LN0->getOperand(1).getValueType(); 2821 2822 unsigned Alignment = LN0->getAlignment(); 2823 SDValue NewPtr = LN0->getBasePtr(); 2824 2825 // For big endian targets, we need to add an offset to the pointer 2826 // to load the correct bytes. For little endian systems, we merely 2827 // need to read fewer bytes from the same pointer. 2828 if (TLI.isBigEndian()) { 2829 unsigned LVTStoreBytes = LoadedVT.getStoreSize(); 2830 unsigned EVTStoreBytes = ExtVT.getStoreSize(); 2831 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes; 2832 NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0), PtrType, 2833 NewPtr, DAG.getConstant(PtrOff, PtrType)); 2834 Alignment = MinAlign(Alignment, PtrOff); 2835 } 2836 2837 AddToWorkList(NewPtr.getNode()); 2838 2839 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT; 2840 SDValue Load = 2841 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy, 2842 LN0->getChain(), NewPtr, 2843 LN0->getPointerInfo(), 2844 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(), 2845 Alignment, LN0->getTBAAInfo()); 2846 AddToWorkList(N); 2847 CombineTo(LN0, Load, Load.getValue(1)); 2848 return SDValue(N, 0); // Return N so it doesn't get rechecked! 2849 } 2850 } 2851 } 2852 } 2853 2854 if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL && 2855 VT.getSizeInBits() <= 64) { 2856 if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 2857 APInt ADDC = ADDI->getAPIntValue(); 2858 if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) { 2859 // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal 2860 // immediate for an add, but it is legal if its top c2 bits are set, 2861 // transform the ADD so the immediate doesn't need to be materialized 2862 // in a register. 2863 if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) { 2864 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(), 2865 SRLI->getZExtValue()); 2866 if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) { 2867 ADDC |= Mask; 2868 if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) { 2869 SDValue NewAdd = 2870 DAG.getNode(ISD::ADD, SDLoc(N0), VT, 2871 N0.getOperand(0), DAG.getConstant(ADDC, VT)); 2872 CombineTo(N0.getNode(), NewAdd); 2873 return SDValue(N, 0); // Return N so it doesn't get rechecked! 2874 } 2875 } 2876 } 2877 } 2878 } 2879 } 2880 2881 // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const) 2882 if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) { 2883 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0), 2884 N0.getOperand(1), false); 2885 if (BSwap.getNode()) 2886 return BSwap; 2887 } 2888 2889 return SDValue(); 2890} 2891 2892/// MatchBSwapHWord - Match (a >> 8) | (a << 8) as (bswap a) >> 16 2893/// 2894SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1, 2895 bool DemandHighBits) { 2896 if (!LegalOperations) 2897 return SDValue(); 2898 2899 EVT VT = N->getValueType(0); 2900 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16) 2901 return SDValue(); 2902 if (!TLI.isOperationLegal(ISD::BSWAP, VT)) 2903 return SDValue(); 2904 2905 // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00) 2906 bool LookPassAnd0 = false; 2907 bool LookPassAnd1 = false; 2908 if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL) 2909 std::swap(N0, N1); 2910 if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL) 2911 std::swap(N0, N1); 2912 if (N0.getOpcode() == ISD::AND) { 2913 if (!N0.getNode()->hasOneUse()) 2914 return SDValue(); 2915 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 2916 if (!N01C || N01C->getZExtValue() != 0xFF00) 2917 return SDValue(); 2918 N0 = N0.getOperand(0); 2919 LookPassAnd0 = true; 2920 } 2921 2922 if (N1.getOpcode() == ISD::AND) { 2923 if (!N1.getNode()->hasOneUse()) 2924 return SDValue(); 2925 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 2926 if (!N11C || N11C->getZExtValue() != 0xFF) 2927 return SDValue(); 2928 N1 = N1.getOperand(0); 2929 LookPassAnd1 = true; 2930 } 2931 2932 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL) 2933 std::swap(N0, N1); 2934 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL) 2935 return SDValue(); 2936 if (!N0.getNode()->hasOneUse() || 2937 !N1.getNode()->hasOneUse()) 2938 return SDValue(); 2939 2940 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 2941 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 2942 if (!N01C || !N11C) 2943 return SDValue(); 2944 if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8) 2945 return SDValue(); 2946 2947 // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8) 2948 SDValue N00 = N0->getOperand(0); 2949 if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) { 2950 if (!N00.getNode()->hasOneUse()) 2951 return SDValue(); 2952 ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1)); 2953 if (!N001C || N001C->getZExtValue() != 0xFF) 2954 return SDValue(); 2955 N00 = N00.getOperand(0); 2956 LookPassAnd0 = true; 2957 } 2958 2959 SDValue N10 = N1->getOperand(0); 2960 if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) { 2961 if (!N10.getNode()->hasOneUse()) 2962 return SDValue(); 2963 ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1)); 2964 if (!N101C || N101C->getZExtValue() != 0xFF00) 2965 return SDValue(); 2966 N10 = N10.getOperand(0); 2967 LookPassAnd1 = true; 2968 } 2969 2970 if (N00 != N10) 2971 return SDValue(); 2972 2973 // Make sure everything beyond the low halfword gets set to zero since the SRL 2974 // 16 will clear the top bits. 2975 unsigned OpSizeInBits = VT.getSizeInBits(); 2976 if (DemandHighBits && OpSizeInBits > 16) { 2977 // If the left-shift isn't masked out then the only way this is a bswap is 2978 // if all bits beyond the low 8 are 0. In that case the entire pattern 2979 // reduces to a left shift anyway: leave it for other parts of the combiner. 2980 if (!LookPassAnd0) 2981 return SDValue(); 2982 2983 // However, if the right shift isn't masked out then it might be because 2984 // it's not needed. See if we can spot that too. 2985 if (!LookPassAnd1 && 2986 !DAG.MaskedValueIsZero( 2987 N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16))) 2988 return SDValue(); 2989 } 2990 2991 SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00); 2992 if (OpSizeInBits > 16) 2993 Res = DAG.getNode(ISD::SRL, SDLoc(N), VT, Res, 2994 DAG.getConstant(OpSizeInBits-16, getShiftAmountTy(VT))); 2995 return Res; 2996} 2997 2998/// isBSwapHWordElement - Return true if the specified node is an element 2999/// that makes up a 32-bit packed halfword byteswap. i.e. 3000/// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8) 3001static bool isBSwapHWordElement(SDValue N, SmallVectorImpl<SDNode *> &Parts) { 3002 if (!N.getNode()->hasOneUse()) 3003 return false; 3004 3005 unsigned Opc = N.getOpcode(); 3006 if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL) 3007 return false; 3008 3009 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1)); 3010 if (!N1C) 3011 return false; 3012 3013 unsigned Num; 3014 switch (N1C->getZExtValue()) { 3015 default: 3016 return false; 3017 case 0xFF: Num = 0; break; 3018 case 0xFF00: Num = 1; break; 3019 case 0xFF0000: Num = 2; break; 3020 case 0xFF000000: Num = 3; break; 3021 } 3022 3023 // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00). 3024 SDValue N0 = N.getOperand(0); 3025 if (Opc == ISD::AND) { 3026 if (Num == 0 || Num == 2) { 3027 // (x >> 8) & 0xff 3028 // (x >> 8) & 0xff0000 3029 if (N0.getOpcode() != ISD::SRL) 3030 return false; 3031 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 3032 if (!C || C->getZExtValue() != 8) 3033 return false; 3034 } else { 3035 // (x << 8) & 0xff00 3036 // (x << 8) & 0xff000000 3037 if (N0.getOpcode() != ISD::SHL) 3038 return false; 3039 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 3040 if (!C || C->getZExtValue() != 8) 3041 return false; 3042 } 3043 } else if (Opc == ISD::SHL) { 3044 // (x & 0xff) << 8 3045 // (x & 0xff0000) << 8 3046 if (Num != 0 && Num != 2) 3047 return false; 3048 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1)); 3049 if (!C || C->getZExtValue() != 8) 3050 return false; 3051 } else { // Opc == ISD::SRL 3052 // (x & 0xff00) >> 8 3053 // (x & 0xff000000) >> 8 3054 if (Num != 1 && Num != 3) 3055 return false; 3056 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1)); 3057 if (!C || C->getZExtValue() != 8) 3058 return false; 3059 } 3060 3061 if (Parts[Num]) 3062 return false; 3063 3064 Parts[Num] = N0.getOperand(0).getNode(); 3065 return true; 3066} 3067 3068/// MatchBSwapHWord - Match a 32-bit packed halfword bswap. That is 3069/// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8) 3070/// => (rotl (bswap x), 16) 3071SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) { 3072 if (!LegalOperations) 3073 return SDValue(); 3074 3075 EVT VT = N->getValueType(0); 3076 if (VT != MVT::i32) 3077 return SDValue(); 3078 if (!TLI.isOperationLegal(ISD::BSWAP, VT)) 3079 return SDValue(); 3080 3081 SmallVector<SDNode*,4> Parts(4, (SDNode*)0); 3082 // Look for either 3083 // (or (or (and), (and)), (or (and), (and))) 3084 // (or (or (or (and), (and)), (and)), (and)) 3085 if (N0.getOpcode() != ISD::OR) 3086 return SDValue(); 3087 SDValue N00 = N0.getOperand(0); 3088 SDValue N01 = N0.getOperand(1); 3089 3090 if (N1.getOpcode() == ISD::OR && 3091 N00.getNumOperands() == 2 && N01.getNumOperands() == 2) { 3092 // (or (or (and), (and)), (or (and), (and))) 3093 SDValue N000 = N00.getOperand(0); 3094 if (!isBSwapHWordElement(N000, Parts)) 3095 return SDValue(); 3096 3097 SDValue N001 = N00.getOperand(1); 3098 if (!isBSwapHWordElement(N001, Parts)) 3099 return SDValue(); 3100 SDValue N010 = N01.getOperand(0); 3101 if (!isBSwapHWordElement(N010, Parts)) 3102 return SDValue(); 3103 SDValue N011 = N01.getOperand(1); 3104 if (!isBSwapHWordElement(N011, Parts)) 3105 return SDValue(); 3106 } else { 3107 // (or (or (or (and), (and)), (and)), (and)) 3108 if (!isBSwapHWordElement(N1, Parts)) 3109 return SDValue(); 3110 if (!isBSwapHWordElement(N01, Parts)) 3111 return SDValue(); 3112 if (N00.getOpcode() != ISD::OR) 3113 return SDValue(); 3114 SDValue N000 = N00.getOperand(0); 3115 if (!isBSwapHWordElement(N000, Parts)) 3116 return SDValue(); 3117 SDValue N001 = N00.getOperand(1); 3118 if (!isBSwapHWordElement(N001, Parts)) 3119 return SDValue(); 3120 } 3121 3122 // Make sure the parts are all coming from the same node. 3123 if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3]) 3124 return SDValue(); 3125 3126 SDValue BSwap = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, 3127 SDValue(Parts[0],0)); 3128 3129 // Result of the bswap should be rotated by 16. If it's not legal, then 3130 // do (x << 16) | (x >> 16). 3131 SDValue ShAmt = DAG.getConstant(16, getShiftAmountTy(VT)); 3132 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT)) 3133 return DAG.getNode(ISD::ROTL, SDLoc(N), VT, BSwap, ShAmt); 3134 if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT)) 3135 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, BSwap, ShAmt); 3136 return DAG.getNode(ISD::OR, SDLoc(N), VT, 3137 DAG.getNode(ISD::SHL, SDLoc(N), VT, BSwap, ShAmt), 3138 DAG.getNode(ISD::SRL, SDLoc(N), VT, BSwap, ShAmt)); 3139} 3140 3141SDValue DAGCombiner::visitOR(SDNode *N) { 3142 SDValue N0 = N->getOperand(0); 3143 SDValue N1 = N->getOperand(1); 3144 SDValue LL, LR, RL, RR, CC0, CC1; 3145 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 3146 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 3147 EVT VT = N1.getValueType(); 3148 3149 // fold vector ops 3150 if (VT.isVector()) { 3151 SDValue FoldedVOp = SimplifyVBinOp(N); 3152 if (FoldedVOp.getNode()) return FoldedVOp; 3153 3154 // fold (or x, 0) -> x, vector edition 3155 if (ISD::isBuildVectorAllZeros(N0.getNode())) 3156 return N1; 3157 if (ISD::isBuildVectorAllZeros(N1.getNode())) 3158 return N0; 3159 3160 // fold (or x, -1) -> -1, vector edition 3161 if (ISD::isBuildVectorAllOnes(N0.getNode())) 3162 return N0; 3163 if (ISD::isBuildVectorAllOnes(N1.getNode())) 3164 return N1; 3165 } 3166 3167 // fold (or x, undef) -> -1 3168 if (!LegalOperations && 3169 (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) { 3170 EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT; 3171 return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT); 3172 } 3173 // fold (or c1, c2) -> c1|c2 3174 if (N0C && N1C) 3175 return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C); 3176 // canonicalize constant to RHS 3177 if (N0C && !N1C) 3178 return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0); 3179 // fold (or x, 0) -> x 3180 if (N1C && N1C->isNullValue()) 3181 return N0; 3182 // fold (or x, -1) -> -1 3183 if (N1C && N1C->isAllOnesValue()) 3184 return N1; 3185 // fold (or x, c) -> c iff (x & ~c) == 0 3186 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue())) 3187 return N1; 3188 3189 // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16) 3190 SDValue BSwap = MatchBSwapHWord(N, N0, N1); 3191 if (BSwap.getNode() != 0) 3192 return BSwap; 3193 BSwap = MatchBSwapHWordLow(N, N0, N1); 3194 if (BSwap.getNode() != 0) 3195 return BSwap; 3196 3197 // reassociate or 3198 SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1); 3199 if (ROR.getNode() != 0) 3200 return ROR; 3201 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2) 3202 // iff (c1 & c2) == 0. 3203 if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() && 3204 isa<ConstantSDNode>(N0.getOperand(1))) { 3205 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1)); 3206 if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) 3207 return DAG.getNode(ISD::AND, SDLoc(N), VT, 3208 DAG.getNode(ISD::OR, SDLoc(N0), VT, 3209 N0.getOperand(0), N1), 3210 DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1)); 3211 } 3212 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y)) 3213 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){ 3214 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get(); 3215 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get(); 3216 3217 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 && 3218 LL.getValueType().isInteger()) { 3219 // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0) 3220 // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0) 3221 if (cast<ConstantSDNode>(LR)->isNullValue() && 3222 (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) { 3223 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR), 3224 LR.getValueType(), LL, RL); 3225 AddToWorkList(ORNode.getNode()); 3226 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1); 3227 } 3228 // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1) 3229 // fold (or (setgt X, -1), (setgt Y -1)) -> (setgt (and X, Y), -1) 3230 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && 3231 (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) { 3232 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR), 3233 LR.getValueType(), LL, RL); 3234 AddToWorkList(ANDNode.getNode()); 3235 return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1); 3236 } 3237 } 3238 // canonicalize equivalent to ll == rl 3239 if (LL == RR && LR == RL) { 3240 Op1 = ISD::getSetCCSwappedOperands(Op1); 3241 std::swap(RL, RR); 3242 } 3243 if (LL == RL && LR == RR) { 3244 bool isInteger = LL.getValueType().isInteger(); 3245 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger); 3246 if (Result != ISD::SETCC_INVALID && 3247 (!LegalOperations || 3248 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) && 3249 TLI.isOperationLegal(ISD::SETCC, 3250 getSetCCResultType(N0.getValueType()))))) 3251 return DAG.getSetCC(SDLoc(N), N0.getValueType(), 3252 LL, LR, Result); 3253 } 3254 } 3255 3256 // Simplify: (or (op x...), (op y...)) -> (op (or x, y)) 3257 if (N0.getOpcode() == N1.getOpcode()) { 3258 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N); 3259 if (Tmp.getNode()) return Tmp; 3260 } 3261 3262 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible. 3263 if (N0.getOpcode() == ISD::AND && 3264 N1.getOpcode() == ISD::AND && 3265 N0.getOperand(1).getOpcode() == ISD::Constant && 3266 N1.getOperand(1).getOpcode() == ISD::Constant && 3267 // Don't increase # computations. 3268 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) { 3269 // We can only do this xform if we know that bits from X that are set in C2 3270 // but not in C1 are already zero. Likewise for Y. 3271 const APInt &LHSMask = 3272 cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 3273 const APInt &RHSMask = 3274 cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue(); 3275 3276 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) && 3277 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) { 3278 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT, 3279 N0.getOperand(0), N1.getOperand(0)); 3280 return DAG.getNode(ISD::AND, SDLoc(N), VT, X, 3281 DAG.getConstant(LHSMask | RHSMask, VT)); 3282 } 3283 } 3284 3285 // See if this is some rotate idiom. 3286 if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N))) 3287 return SDValue(Rot, 0); 3288 3289 // Simplify the operands using demanded-bits information. 3290 if (!VT.isVector() && 3291 SimplifyDemandedBits(SDValue(N, 0))) 3292 return SDValue(N, 0); 3293 3294 return SDValue(); 3295} 3296 3297/// MatchRotateHalf - Match "(X shl/srl V1) & V2" where V2 may not be present. 3298static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) { 3299 if (Op.getOpcode() == ISD::AND) { 3300 if (isa<ConstantSDNode>(Op.getOperand(1))) { 3301 Mask = Op.getOperand(1); 3302 Op = Op.getOperand(0); 3303 } else { 3304 return false; 3305 } 3306 } 3307 3308 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) { 3309 Shift = Op; 3310 return true; 3311 } 3312 3313 return false; 3314} 3315 3316// MatchRotate - Handle an 'or' of two operands. If this is one of the many 3317// idioms for rotate, and if the target supports rotation instructions, generate 3318// a rot[lr]. 3319SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) { 3320 // Must be a legal type. Expanded 'n promoted things won't work with rotates. 3321 EVT VT = LHS.getValueType(); 3322 if (!TLI.isTypeLegal(VT)) return 0; 3323 3324 // The target must have at least one rotate flavor. 3325 bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT); 3326 bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT); 3327 if (!HasROTL && !HasROTR) return 0; 3328 3329 // Match "(X shl/srl V1) & V2" where V2 may not be present. 3330 SDValue LHSShift; // The shift. 3331 SDValue LHSMask; // AND value if any. 3332 if (!MatchRotateHalf(LHS, LHSShift, LHSMask)) 3333 return 0; // Not part of a rotate. 3334 3335 SDValue RHSShift; // The shift. 3336 SDValue RHSMask; // AND value if any. 3337 if (!MatchRotateHalf(RHS, RHSShift, RHSMask)) 3338 return 0; // Not part of a rotate. 3339 3340 if (LHSShift.getOperand(0) != RHSShift.getOperand(0)) 3341 return 0; // Not shifting the same value. 3342 3343 if (LHSShift.getOpcode() == RHSShift.getOpcode()) 3344 return 0; // Shifts must disagree. 3345 3346 // Canonicalize shl to left side in a shl/srl pair. 3347 if (RHSShift.getOpcode() == ISD::SHL) { 3348 std::swap(LHS, RHS); 3349 std::swap(LHSShift, RHSShift); 3350 std::swap(LHSMask , RHSMask ); 3351 } 3352 3353 unsigned OpSizeInBits = VT.getSizeInBits(); 3354 SDValue LHSShiftArg = LHSShift.getOperand(0); 3355 SDValue LHSShiftAmt = LHSShift.getOperand(1); 3356 SDValue RHSShiftArg = RHSShift.getOperand(0); 3357 SDValue RHSShiftAmt = RHSShift.getOperand(1); 3358 3359 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1) 3360 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2) 3361 if (LHSShiftAmt.getOpcode() == ISD::Constant && 3362 RHSShiftAmt.getOpcode() == ISD::Constant) { 3363 uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue(); 3364 uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue(); 3365 if ((LShVal + RShVal) != OpSizeInBits) 3366 return 0; 3367 3368 SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT, 3369 LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt); 3370 3371 // If there is an AND of either shifted operand, apply it to the result. 3372 if (LHSMask.getNode() || RHSMask.getNode()) { 3373 APInt Mask = APInt::getAllOnesValue(OpSizeInBits); 3374 3375 if (LHSMask.getNode()) { 3376 APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal); 3377 Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits; 3378 } 3379 if (RHSMask.getNode()) { 3380 APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal); 3381 Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits; 3382 } 3383 3384 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT)); 3385 } 3386 3387 return Rot.getNode(); 3388 } 3389 3390 // If there is a mask here, and we have a variable shift, we can't be sure 3391 // that we're masking out the right stuff. 3392 if (LHSMask.getNode() || RHSMask.getNode()) 3393 return 0; 3394 3395 // If the shift amount is sign/zext/any-extended just peel it off. 3396 SDValue LExtOp0 = LHSShiftAmt; 3397 SDValue RExtOp0 = RHSShiftAmt; 3398 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND || 3399 LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND || 3400 LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND || 3401 LHSShiftAmt.getOpcode() == ISD::TRUNCATE) && 3402 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND || 3403 RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND || 3404 RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND || 3405 RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) { 3406 LExtOp0 = LHSShiftAmt.getOperand(0); 3407 RExtOp0 = RHSShiftAmt.getOperand(0); 3408 } 3409 3410 if (RExtOp0.getOpcode() == ISD::SUB && RExtOp0.getOperand(1) == LExtOp0) { 3411 // fold (or (shl x, (*ext y)), (srl x, (*ext (sub 32, y)))) -> 3412 // (rotl x, y) 3413 // fold (or (shl x, (*ext y)), (srl x, (*ext (sub 32, y)))) -> 3414 // (rotr x, (sub 32, y)) 3415 if (ConstantSDNode *SUBC = 3416 dyn_cast<ConstantSDNode>(RExtOp0.getOperand(0))) { 3417 if (SUBC->getAPIntValue() == OpSizeInBits) { 3418 return DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT, LHSShiftArg, 3419 HasROTL ? LHSShiftAmt : RHSShiftAmt).getNode(); 3420 } else if (LHSShiftArg.getOpcode() == ISD::ZERO_EXTEND || 3421 LHSShiftArg.getOpcode() == ISD::ANY_EXTEND) { 3422 // fold (or (shl (*ext x), (*ext y)), 3423 // (srl (*ext x), (*ext (sub 32, y)))) -> 3424 // (*ext (rotl x, y)) 3425 // fold (or (shl (*ext x), (*ext y)), 3426 // (srl (*ext x), (*ext (sub 32, y)))) -> 3427 // (*ext (rotr x, (sub 32, y))) 3428 SDValue LArgExtOp0 = LHSShiftArg.getOperand(0); 3429 EVT LArgVT = LArgExtOp0.getValueType(); 3430 bool HasROTRWithLArg = TLI.isOperationLegalOrCustom(ISD::ROTR, LArgVT); 3431 bool HasROTLWithLArg = TLI.isOperationLegalOrCustom(ISD::ROTL, LArgVT); 3432 if (HasROTRWithLArg || HasROTLWithLArg) { 3433 if (LArgVT.getSizeInBits() == SUBC->getAPIntValue()) { 3434 SDValue V = 3435 DAG.getNode(HasROTLWithLArg ? ISD::ROTL : ISD::ROTR, DL, LArgVT, 3436 LArgExtOp0, HasROTL ? LHSShiftAmt : RHSShiftAmt); 3437 return DAG.getNode(LHSShiftArg.getOpcode(), DL, VT, V).getNode(); 3438 } 3439 } 3440 } 3441 } 3442 } else if (LExtOp0.getOpcode() == ISD::SUB && 3443 RExtOp0 == LExtOp0.getOperand(1)) { 3444 // fold (or (shl x, (*ext (sub 32, y))), (srl x, (*ext y))) -> 3445 // (rotr x, y) 3446 // fold (or (shl x, (*ext (sub 32, y))), (srl x, (*ext y))) -> 3447 // (rotl x, (sub 32, y)) 3448 if (ConstantSDNode *SUBC = 3449 dyn_cast<ConstantSDNode>(LExtOp0.getOperand(0))) { 3450 if (SUBC->getAPIntValue() == OpSizeInBits) { 3451 return DAG.getNode(HasROTR ? ISD::ROTR : ISD::ROTL, DL, VT, LHSShiftArg, 3452 HasROTR ? RHSShiftAmt : LHSShiftAmt).getNode(); 3453 } else if (RHSShiftArg.getOpcode() == ISD::ZERO_EXTEND || 3454 RHSShiftArg.getOpcode() == ISD::ANY_EXTEND) { 3455 // fold (or (shl (*ext x), (*ext (sub 32, y))), 3456 // (srl (*ext x), (*ext y))) -> 3457 // (*ext (rotl x, y)) 3458 // fold (or (shl (*ext x), (*ext (sub 32, y))), 3459 // (srl (*ext x), (*ext y))) -> 3460 // (*ext (rotr x, (sub 32, y))) 3461 SDValue RArgExtOp0 = RHSShiftArg.getOperand(0); 3462 EVT RArgVT = RArgExtOp0.getValueType(); 3463 bool HasROTRWithRArg = TLI.isOperationLegalOrCustom(ISD::ROTR, RArgVT); 3464 bool HasROTLWithRArg = TLI.isOperationLegalOrCustom(ISD::ROTL, RArgVT); 3465 if (HasROTRWithRArg || HasROTLWithRArg) { 3466 if (RArgVT.getSizeInBits() == SUBC->getAPIntValue()) { 3467 SDValue V = 3468 DAG.getNode(HasROTRWithRArg ? ISD::ROTR : ISD::ROTL, DL, RArgVT, 3469 RArgExtOp0, HasROTR ? RHSShiftAmt : LHSShiftAmt); 3470 return DAG.getNode(RHSShiftArg.getOpcode(), DL, VT, V).getNode(); 3471 } 3472 } 3473 } 3474 } 3475 } 3476 3477 return 0; 3478} 3479 3480SDValue DAGCombiner::visitXOR(SDNode *N) { 3481 SDValue N0 = N->getOperand(0); 3482 SDValue N1 = N->getOperand(1); 3483 SDValue LHS, RHS, CC; 3484 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 3485 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 3486 EVT VT = N0.getValueType(); 3487 3488 // fold vector ops 3489 if (VT.isVector()) { 3490 SDValue FoldedVOp = SimplifyVBinOp(N); 3491 if (FoldedVOp.getNode()) return FoldedVOp; 3492 3493 // fold (xor x, 0) -> x, vector edition 3494 if (ISD::isBuildVectorAllZeros(N0.getNode())) 3495 return N1; 3496 if (ISD::isBuildVectorAllZeros(N1.getNode())) 3497 return N0; 3498 } 3499 3500 // fold (xor undef, undef) -> 0. This is a common idiom (misuse). 3501 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF) 3502 return DAG.getConstant(0, VT); 3503 // fold (xor x, undef) -> undef 3504 if (N0.getOpcode() == ISD::UNDEF) 3505 return N0; 3506 if (N1.getOpcode() == ISD::UNDEF) 3507 return N1; 3508 // fold (xor c1, c2) -> c1^c2 3509 if (N0C && N1C) 3510 return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C); 3511 // canonicalize constant to RHS 3512 if (N0C && !N1C) 3513 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0); 3514 // fold (xor x, 0) -> x 3515 if (N1C && N1C->isNullValue()) 3516 return N0; 3517 // reassociate xor 3518 SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1); 3519 if (RXOR.getNode() != 0) 3520 return RXOR; 3521 3522 // fold !(x cc y) -> (x !cc y) 3523 if (N1C && N1C->getAPIntValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) { 3524 bool isInt = LHS.getValueType().isInteger(); 3525 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(), 3526 isInt); 3527 3528 if (!LegalOperations || 3529 TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) { 3530 switch (N0.getOpcode()) { 3531 default: 3532 llvm_unreachable("Unhandled SetCC Equivalent!"); 3533 case ISD::SETCC: 3534 return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC); 3535 case ISD::SELECT_CC: 3536 return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2), 3537 N0.getOperand(3), NotCC); 3538 } 3539 } 3540 } 3541 3542 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y))) 3543 if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND && 3544 N0.getNode()->hasOneUse() && 3545 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){ 3546 SDValue V = N0.getOperand(0); 3547 V = DAG.getNode(ISD::XOR, SDLoc(N0), V.getValueType(), V, 3548 DAG.getConstant(1, V.getValueType())); 3549 AddToWorkList(V.getNode()); 3550 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V); 3551 } 3552 3553 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc 3554 if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 && 3555 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) { 3556 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1); 3557 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) { 3558 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND; 3559 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS 3560 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS 3561 AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode()); 3562 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS); 3563 } 3564 } 3565 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants 3566 if (N1C && N1C->isAllOnesValue() && 3567 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) { 3568 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1); 3569 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) { 3570 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND; 3571 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS 3572 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS 3573 AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode()); 3574 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS); 3575 } 3576 } 3577 // fold (xor (and x, y), y) -> (and (not x), y) 3578 if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() && 3579 N0->getOperand(1) == N1) { 3580 SDValue X = N0->getOperand(0); 3581 SDValue NotX = DAG.getNOT(SDLoc(X), X, VT); 3582 AddToWorkList(NotX.getNode()); 3583 return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1); 3584 } 3585 // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2)) 3586 if (N1C && N0.getOpcode() == ISD::XOR) { 3587 ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0)); 3588 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 3589 if (N00C) 3590 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(1), 3591 DAG.getConstant(N1C->getAPIntValue() ^ 3592 N00C->getAPIntValue(), VT)); 3593 if (N01C) 3594 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(0), 3595 DAG.getConstant(N1C->getAPIntValue() ^ 3596 N01C->getAPIntValue(), VT)); 3597 } 3598 // fold (xor x, x) -> 0 3599 if (N0 == N1) 3600 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes); 3601 3602 // Simplify: xor (op x...), (op y...) -> (op (xor x, y)) 3603 if (N0.getOpcode() == N1.getOpcode()) { 3604 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N); 3605 if (Tmp.getNode()) return Tmp; 3606 } 3607 3608 // Simplify the expression using non-local knowledge. 3609 if (!VT.isVector() && 3610 SimplifyDemandedBits(SDValue(N, 0))) 3611 return SDValue(N, 0); 3612 3613 return SDValue(); 3614} 3615 3616/// visitShiftByConstant - Handle transforms common to the three shifts, when 3617/// the shift amount is a constant. 3618SDValue DAGCombiner::visitShiftByConstant(SDNode *N, unsigned Amt) { 3619 SDNode *LHS = N->getOperand(0).getNode(); 3620 if (!LHS->hasOneUse()) return SDValue(); 3621 3622 // We want to pull some binops through shifts, so that we have (and (shift)) 3623 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of 3624 // thing happens with address calculations, so it's important to canonicalize 3625 // it. 3626 bool HighBitSet = false; // Can we transform this if the high bit is set? 3627 3628 switch (LHS->getOpcode()) { 3629 default: return SDValue(); 3630 case ISD::OR: 3631 case ISD::XOR: 3632 HighBitSet = false; // We can only transform sra if the high bit is clear. 3633 break; 3634 case ISD::AND: 3635 HighBitSet = true; // We can only transform sra if the high bit is set. 3636 break; 3637 case ISD::ADD: 3638 if (N->getOpcode() != ISD::SHL) 3639 return SDValue(); // only shl(add) not sr[al](add). 3640 HighBitSet = false; // We can only transform sra if the high bit is clear. 3641 break; 3642 } 3643 3644 // We require the RHS of the binop to be a constant as well. 3645 ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1)); 3646 if (!BinOpCst) return SDValue(); 3647 3648 // FIXME: disable this unless the input to the binop is a shift by a constant. 3649 // If it is not a shift, it pessimizes some common cases like: 3650 // 3651 // void foo(int *X, int i) { X[i & 1235] = 1; } 3652 // int bar(int *X, int i) { return X[i & 255]; } 3653 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode(); 3654 if ((BinOpLHSVal->getOpcode() != ISD::SHL && 3655 BinOpLHSVal->getOpcode() != ISD::SRA && 3656 BinOpLHSVal->getOpcode() != ISD::SRL) || 3657 !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1))) 3658 return SDValue(); 3659 3660 EVT VT = N->getValueType(0); 3661 3662 // If this is a signed shift right, and the high bit is modified by the 3663 // logical operation, do not perform the transformation. The highBitSet 3664 // boolean indicates the value of the high bit of the constant which would 3665 // cause it to be modified for this operation. 3666 if (N->getOpcode() == ISD::SRA) { 3667 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative(); 3668 if (BinOpRHSSignSet != HighBitSet) 3669 return SDValue(); 3670 } 3671 3672 // Fold the constants, shifting the binop RHS by the shift amount. 3673 SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)), 3674 N->getValueType(0), 3675 LHS->getOperand(1), N->getOperand(1)); 3676 3677 // Create the new shift. 3678 SDValue NewShift = DAG.getNode(N->getOpcode(), 3679 SDLoc(LHS->getOperand(0)), 3680 VT, LHS->getOperand(0), N->getOperand(1)); 3681 3682 // Create the new binop. 3683 return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS); 3684} 3685 3686SDValue DAGCombiner::visitSHL(SDNode *N) { 3687 SDValue N0 = N->getOperand(0); 3688 SDValue N1 = N->getOperand(1); 3689 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 3690 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 3691 EVT VT = N0.getValueType(); 3692 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits(); 3693 3694 // fold vector ops 3695 if (VT.isVector()) { 3696 SDValue FoldedVOp = SimplifyVBinOp(N); 3697 if (FoldedVOp.getNode()) return FoldedVOp; 3698 } 3699 3700 // fold (shl c1, c2) -> c1<<c2 3701 if (N0C && N1C) 3702 return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C); 3703 // fold (shl 0, x) -> 0 3704 if (N0C && N0C->isNullValue()) 3705 return N0; 3706 // fold (shl x, c >= size(x)) -> undef 3707 if (N1C && N1C->getZExtValue() >= OpSizeInBits) 3708 return DAG.getUNDEF(VT); 3709 // fold (shl x, 0) -> x 3710 if (N1C && N1C->isNullValue()) 3711 return N0; 3712 // fold (shl undef, x) -> 0 3713 if (N0.getOpcode() == ISD::UNDEF) 3714 return DAG.getConstant(0, VT); 3715 // if (shl x, c) is known to be zero, return 0 3716 if (DAG.MaskedValueIsZero(SDValue(N, 0), 3717 APInt::getAllOnesValue(OpSizeInBits))) 3718 return DAG.getConstant(0, VT); 3719 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))). 3720 if (N1.getOpcode() == ISD::TRUNCATE && 3721 N1.getOperand(0).getOpcode() == ISD::AND && 3722 N1.hasOneUse() && N1.getOperand(0).hasOneUse()) { 3723 SDValue N101 = N1.getOperand(0).getOperand(1); 3724 if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) { 3725 EVT TruncVT = N1.getValueType(); 3726 SDValue N100 = N1.getOperand(0).getOperand(0); 3727 APInt TruncC = N101C->getAPIntValue(); 3728 TruncC = TruncC.trunc(TruncVT.getSizeInBits()); 3729 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, 3730 DAG.getNode(ISD::AND, SDLoc(N), TruncVT, 3731 DAG.getNode(ISD::TRUNCATE, 3732 SDLoc(N), 3733 TruncVT, N100), 3734 DAG.getConstant(TruncC, TruncVT))); 3735 } 3736 } 3737 3738 if (N1C && SimplifyDemandedBits(SDValue(N, 0))) 3739 return SDValue(N, 0); 3740 3741 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2)) 3742 if (N1C && N0.getOpcode() == ISD::SHL && 3743 N0.getOperand(1).getOpcode() == ISD::Constant) { 3744 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue(); 3745 uint64_t c2 = N1C->getZExtValue(); 3746 if (c1 + c2 >= OpSizeInBits) 3747 return DAG.getConstant(0, VT); 3748 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0), 3749 DAG.getConstant(c1 + c2, N1.getValueType())); 3750 } 3751 3752 // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2))) 3753 // For this to be valid, the second form must not preserve any of the bits 3754 // that are shifted out by the inner shift in the first form. This means 3755 // the outer shift size must be >= the number of bits added by the ext. 3756 // As a corollary, we don't care what kind of ext it is. 3757 if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND || 3758 N0.getOpcode() == ISD::ANY_EXTEND || 3759 N0.getOpcode() == ISD::SIGN_EXTEND) && 3760 N0.getOperand(0).getOpcode() == ISD::SHL && 3761 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) { 3762 uint64_t c1 = 3763 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue(); 3764 uint64_t c2 = N1C->getZExtValue(); 3765 EVT InnerShiftVT = N0.getOperand(0).getValueType(); 3766 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits(); 3767 if (c2 >= OpSizeInBits - InnerShiftSize) { 3768 if (c1 + c2 >= OpSizeInBits) 3769 return DAG.getConstant(0, VT); 3770 return DAG.getNode(ISD::SHL, SDLoc(N0), VT, 3771 DAG.getNode(N0.getOpcode(), SDLoc(N0), VT, 3772 N0.getOperand(0)->getOperand(0)), 3773 DAG.getConstant(c1 + c2, N1.getValueType())); 3774 } 3775 } 3776 3777 // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C)) 3778 // Only fold this if the inner zext has no other uses to avoid increasing 3779 // the total number of instructions. 3780 if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() && 3781 N0.getOperand(0).getOpcode() == ISD::SRL && 3782 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) { 3783 uint64_t c1 = 3784 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue(); 3785 if (c1 < VT.getSizeInBits()) { 3786 uint64_t c2 = N1C->getZExtValue(); 3787 if (c1 == c2) { 3788 SDValue NewOp0 = N0.getOperand(0); 3789 EVT CountVT = NewOp0.getOperand(1).getValueType(); 3790 SDValue NewSHL = DAG.getNode(ISD::SHL, SDLoc(N), NewOp0.getValueType(), 3791 NewOp0, DAG.getConstant(c2, CountVT)); 3792 AddToWorkList(NewSHL.getNode()); 3793 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL); 3794 } 3795 } 3796 } 3797 3798 // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or 3799 // (and (srl x, (sub c1, c2), MASK) 3800 // Only fold this if the inner shift has no other uses -- if it does, folding 3801 // this will increase the total number of instructions. 3802 if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse() && 3803 N0.getOperand(1).getOpcode() == ISD::Constant) { 3804 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue(); 3805 if (c1 < VT.getSizeInBits()) { 3806 uint64_t c2 = N1C->getZExtValue(); 3807 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(), 3808 VT.getSizeInBits() - c1); 3809 SDValue Shift; 3810 if (c2 > c1) { 3811 Mask = Mask.shl(c2-c1); 3812 Shift = DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0), 3813 DAG.getConstant(c2-c1, N1.getValueType())); 3814 } else { 3815 Mask = Mask.lshr(c1-c2); 3816 Shift = DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), 3817 DAG.getConstant(c1-c2, N1.getValueType())); 3818 } 3819 return DAG.getNode(ISD::AND, SDLoc(N0), VT, Shift, 3820 DAG.getConstant(Mask, VT)); 3821 } 3822 } 3823 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1)) 3824 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) { 3825 SDValue HiBitsMask = 3826 DAG.getConstant(APInt::getHighBitsSet(VT.getSizeInBits(), 3827 VT.getSizeInBits() - 3828 N1C->getZExtValue()), 3829 VT); 3830 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0), 3831 HiBitsMask); 3832 } 3833 3834 if (N1C) { 3835 SDValue NewSHL = visitShiftByConstant(N, N1C->getZExtValue()); 3836 if (NewSHL.getNode()) 3837 return NewSHL; 3838 } 3839 3840 return SDValue(); 3841} 3842 3843SDValue DAGCombiner::visitSRA(SDNode *N) { 3844 SDValue N0 = N->getOperand(0); 3845 SDValue N1 = N->getOperand(1); 3846 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 3847 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 3848 EVT VT = N0.getValueType(); 3849 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits(); 3850 3851 // fold vector ops 3852 if (VT.isVector()) { 3853 SDValue FoldedVOp = SimplifyVBinOp(N); 3854 if (FoldedVOp.getNode()) return FoldedVOp; 3855 } 3856 3857 // fold (sra c1, c2) -> (sra c1, c2) 3858 if (N0C && N1C) 3859 return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C); 3860 // fold (sra 0, x) -> 0 3861 if (N0C && N0C->isNullValue()) 3862 return N0; 3863 // fold (sra -1, x) -> -1 3864 if (N0C && N0C->isAllOnesValue()) 3865 return N0; 3866 // fold (sra x, (setge c, size(x))) -> undef 3867 if (N1C && N1C->getZExtValue() >= OpSizeInBits) 3868 return DAG.getUNDEF(VT); 3869 // fold (sra x, 0) -> x 3870 if (N1C && N1C->isNullValue()) 3871 return N0; 3872 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports 3873 // sext_inreg. 3874 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) { 3875 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue(); 3876 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits); 3877 if (VT.isVector()) 3878 ExtVT = EVT::getVectorVT(*DAG.getContext(), 3879 ExtVT, VT.getVectorNumElements()); 3880 if ((!LegalOperations || 3881 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT))) 3882 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, 3883 N0.getOperand(0), DAG.getValueType(ExtVT)); 3884 } 3885 3886 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2)) 3887 if (N1C && N0.getOpcode() == ISD::SRA) { 3888 if (ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 3889 unsigned Sum = N1C->getZExtValue() + C1->getZExtValue(); 3890 if (Sum >= OpSizeInBits) Sum = OpSizeInBits-1; 3891 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0.getOperand(0), 3892 DAG.getConstant(Sum, N1C->getValueType(0))); 3893 } 3894 } 3895 3896 // fold (sra (shl X, m), (sub result_size, n)) 3897 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for 3898 // result_size - n != m. 3899 // If truncate is free for the target sext(shl) is likely to result in better 3900 // code. 3901 if (N0.getOpcode() == ISD::SHL) { 3902 // Get the two constanst of the shifts, CN0 = m, CN = n. 3903 const ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 3904 if (N01C && N1C) { 3905 // Determine what the truncate's result bitsize and type would be. 3906 EVT TruncVT = 3907 EVT::getIntegerVT(*DAG.getContext(), 3908 OpSizeInBits - N1C->getZExtValue()); 3909 // Determine the residual right-shift amount. 3910 signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue(); 3911 3912 // If the shift is not a no-op (in which case this should be just a sign 3913 // extend already), the truncated to type is legal, sign_extend is legal 3914 // on that type, and the truncate to that type is both legal and free, 3915 // perform the transform. 3916 if ((ShiftAmt > 0) && 3917 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) && 3918 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) && 3919 TLI.isTruncateFree(VT, TruncVT)) { 3920 3921 SDValue Amt = DAG.getConstant(ShiftAmt, 3922 getShiftAmountTy(N0.getOperand(0).getValueType())); 3923 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), VT, 3924 N0.getOperand(0), Amt); 3925 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), TruncVT, 3926 Shift); 3927 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), 3928 N->getValueType(0), Trunc); 3929 } 3930 } 3931 } 3932 3933 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))). 3934 if (N1.getOpcode() == ISD::TRUNCATE && 3935 N1.getOperand(0).getOpcode() == ISD::AND && 3936 N1.hasOneUse() && N1.getOperand(0).hasOneUse()) { 3937 SDValue N101 = N1.getOperand(0).getOperand(1); 3938 if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) { 3939 EVT TruncVT = N1.getValueType(); 3940 SDValue N100 = N1.getOperand(0).getOperand(0); 3941 APInt TruncC = N101C->getAPIntValue(); 3942 TruncC = TruncC.trunc(TruncVT.getScalarType().getSizeInBits()); 3943 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, 3944 DAG.getNode(ISD::AND, SDLoc(N), 3945 TruncVT, 3946 DAG.getNode(ISD::TRUNCATE, 3947 SDLoc(N), 3948 TruncVT, N100), 3949 DAG.getConstant(TruncC, TruncVT))); 3950 } 3951 } 3952 3953 // fold (sra (trunc (sr x, c1)), c2) -> (trunc (sra x, c1+c2)) 3954 // if c1 is equal to the number of bits the trunc removes 3955 if (N0.getOpcode() == ISD::TRUNCATE && 3956 (N0.getOperand(0).getOpcode() == ISD::SRL || 3957 N0.getOperand(0).getOpcode() == ISD::SRA) && 3958 N0.getOperand(0).hasOneUse() && 3959 N0.getOperand(0).getOperand(1).hasOneUse() && 3960 N1C && isa<ConstantSDNode>(N0.getOperand(0).getOperand(1))) { 3961 EVT LargeVT = N0.getOperand(0).getValueType(); 3962 ConstantSDNode *LargeShiftAmt = 3963 cast<ConstantSDNode>(N0.getOperand(0).getOperand(1)); 3964 3965 if (LargeVT.getScalarType().getSizeInBits() - OpSizeInBits == 3966 LargeShiftAmt->getZExtValue()) { 3967 SDValue Amt = 3968 DAG.getConstant(LargeShiftAmt->getZExtValue() + N1C->getZExtValue(), 3969 getShiftAmountTy(N0.getOperand(0).getOperand(0).getValueType())); 3970 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), LargeVT, 3971 N0.getOperand(0).getOperand(0), Amt); 3972 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, SRA); 3973 } 3974 } 3975 3976 // Simplify, based on bits shifted out of the LHS. 3977 if (N1C && SimplifyDemandedBits(SDValue(N, 0))) 3978 return SDValue(N, 0); 3979 3980 3981 // If the sign bit is known to be zero, switch this to a SRL. 3982 if (DAG.SignBitIsZero(N0)) 3983 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1); 3984 3985 if (N1C) { 3986 SDValue NewSRA = visitShiftByConstant(N, N1C->getZExtValue()); 3987 if (NewSRA.getNode()) 3988 return NewSRA; 3989 } 3990 3991 return SDValue(); 3992} 3993 3994SDValue DAGCombiner::visitSRL(SDNode *N) { 3995 SDValue N0 = N->getOperand(0); 3996 SDValue N1 = N->getOperand(1); 3997 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 3998 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 3999 EVT VT = N0.getValueType(); 4000 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits(); 4001 4002 // fold vector ops 4003 if (VT.isVector()) { 4004 SDValue FoldedVOp = SimplifyVBinOp(N); 4005 if (FoldedVOp.getNode()) return FoldedVOp; 4006 } 4007 4008 // fold (srl c1, c2) -> c1 >>u c2 4009 if (N0C && N1C) 4010 return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C); 4011 // fold (srl 0, x) -> 0 4012 if (N0C && N0C->isNullValue()) 4013 return N0; 4014 // fold (srl x, c >= size(x)) -> undef 4015 if (N1C && N1C->getZExtValue() >= OpSizeInBits) 4016 return DAG.getUNDEF(VT); 4017 // fold (srl x, 0) -> x 4018 if (N1C && N1C->isNullValue()) 4019 return N0; 4020 // if (srl x, c) is known to be zero, return 0 4021 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0), 4022 APInt::getAllOnesValue(OpSizeInBits))) 4023 return DAG.getConstant(0, VT); 4024 4025 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2)) 4026 if (N1C && N0.getOpcode() == ISD::SRL && 4027 N0.getOperand(1).getOpcode() == ISD::Constant) { 4028 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue(); 4029 uint64_t c2 = N1C->getZExtValue(); 4030 if (c1 + c2 >= OpSizeInBits) 4031 return DAG.getConstant(0, VT); 4032 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), 4033 DAG.getConstant(c1 + c2, N1.getValueType())); 4034 } 4035 4036 // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2))) 4037 if (N1C && N0.getOpcode() == ISD::TRUNCATE && 4038 N0.getOperand(0).getOpcode() == ISD::SRL && 4039 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) { 4040 uint64_t c1 = 4041 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue(); 4042 uint64_t c2 = N1C->getZExtValue(); 4043 EVT InnerShiftVT = N0.getOperand(0).getValueType(); 4044 EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType(); 4045 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits(); 4046 // This is only valid if the OpSizeInBits + c1 = size of inner shift. 4047 if (c1 + OpSizeInBits == InnerShiftSize) { 4048 if (c1 + c2 >= InnerShiftSize) 4049 return DAG.getConstant(0, VT); 4050 return DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, 4051 DAG.getNode(ISD::SRL, SDLoc(N0), InnerShiftVT, 4052 N0.getOperand(0)->getOperand(0), 4053 DAG.getConstant(c1 + c2, ShiftCountVT))); 4054 } 4055 } 4056 4057 // fold (srl (shl x, c), c) -> (and x, cst2) 4058 if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1 && 4059 N0.getValueSizeInBits() <= 64) { 4060 uint64_t ShAmt = N1C->getZExtValue()+64-N0.getValueSizeInBits(); 4061 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0), 4062 DAG.getConstant(~0ULL >> ShAmt, VT)); 4063 } 4064 4065 // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask) 4066 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) { 4067 // Shifting in all undef bits? 4068 EVT SmallVT = N0.getOperand(0).getValueType(); 4069 if (N1C->getZExtValue() >= SmallVT.getSizeInBits()) 4070 return DAG.getUNDEF(VT); 4071 4072 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) { 4073 uint64_t ShiftAmt = N1C->getZExtValue(); 4074 SDValue SmallShift = DAG.getNode(ISD::SRL, SDLoc(N0), SmallVT, 4075 N0.getOperand(0), 4076 DAG.getConstant(ShiftAmt, getShiftAmountTy(SmallVT))); 4077 AddToWorkList(SmallShift.getNode()); 4078 APInt Mask = APInt::getAllOnesValue(VT.getSizeInBits()).lshr(ShiftAmt); 4079 return DAG.getNode(ISD::AND, SDLoc(N), VT, 4080 DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, SmallShift), 4081 DAG.getConstant(Mask, VT)); 4082 } 4083 } 4084 4085 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign 4086 // bit, which is unmodified by sra. 4087 if (N1C && N1C->getZExtValue() + 1 == VT.getSizeInBits()) { 4088 if (N0.getOpcode() == ISD::SRA) 4089 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1); 4090 } 4091 4092 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit). 4093 if (N1C && N0.getOpcode() == ISD::CTLZ && 4094 N1C->getAPIntValue() == Log2_32(VT.getSizeInBits())) { 4095 APInt KnownZero, KnownOne; 4096 DAG.ComputeMaskedBits(N0.getOperand(0), KnownZero, KnownOne); 4097 4098 // If any of the input bits are KnownOne, then the input couldn't be all 4099 // zeros, thus the result of the srl will always be zero. 4100 if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT); 4101 4102 // If all of the bits input the to ctlz node are known to be zero, then 4103 // the result of the ctlz is "32" and the result of the shift is one. 4104 APInt UnknownBits = ~KnownZero; 4105 if (UnknownBits == 0) return DAG.getConstant(1, VT); 4106 4107 // Otherwise, check to see if there is exactly one bit input to the ctlz. 4108 if ((UnknownBits & (UnknownBits - 1)) == 0) { 4109 // Okay, we know that only that the single bit specified by UnknownBits 4110 // could be set on input to the CTLZ node. If this bit is set, the SRL 4111 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair 4112 // to an SRL/XOR pair, which is likely to simplify more. 4113 unsigned ShAmt = UnknownBits.countTrailingZeros(); 4114 SDValue Op = N0.getOperand(0); 4115 4116 if (ShAmt) { 4117 Op = DAG.getNode(ISD::SRL, SDLoc(N0), VT, Op, 4118 DAG.getConstant(ShAmt, getShiftAmountTy(Op.getValueType()))); 4119 AddToWorkList(Op.getNode()); 4120 } 4121 4122 return DAG.getNode(ISD::XOR, SDLoc(N), VT, 4123 Op, DAG.getConstant(1, VT)); 4124 } 4125 } 4126 4127 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))). 4128 if (N1.getOpcode() == ISD::TRUNCATE && 4129 N1.getOperand(0).getOpcode() == ISD::AND && 4130 N1.hasOneUse() && N1.getOperand(0).hasOneUse()) { 4131 SDValue N101 = N1.getOperand(0).getOperand(1); 4132 if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) { 4133 EVT TruncVT = N1.getValueType(); 4134 SDValue N100 = N1.getOperand(0).getOperand(0); 4135 APInt TruncC = N101C->getAPIntValue(); 4136 TruncC = TruncC.trunc(TruncVT.getSizeInBits()); 4137 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, 4138 DAG.getNode(ISD::AND, SDLoc(N), 4139 TruncVT, 4140 DAG.getNode(ISD::TRUNCATE, 4141 SDLoc(N), 4142 TruncVT, N100), 4143 DAG.getConstant(TruncC, TruncVT))); 4144 } 4145 } 4146 4147 // fold operands of srl based on knowledge that the low bits are not 4148 // demanded. 4149 if (N1C && SimplifyDemandedBits(SDValue(N, 0))) 4150 return SDValue(N, 0); 4151 4152 if (N1C) { 4153 SDValue NewSRL = visitShiftByConstant(N, N1C->getZExtValue()); 4154 if (NewSRL.getNode()) 4155 return NewSRL; 4156 } 4157 4158 // Attempt to convert a srl of a load into a narrower zero-extending load. 4159 SDValue NarrowLoad = ReduceLoadWidth(N); 4160 if (NarrowLoad.getNode()) 4161 return NarrowLoad; 4162 4163 // Here is a common situation. We want to optimize: 4164 // 4165 // %a = ... 4166 // %b = and i32 %a, 2 4167 // %c = srl i32 %b, 1 4168 // brcond i32 %c ... 4169 // 4170 // into 4171 // 4172 // %a = ... 4173 // %b = and %a, 2 4174 // %c = setcc eq %b, 0 4175 // brcond %c ... 4176 // 4177 // However when after the source operand of SRL is optimized into AND, the SRL 4178 // itself may not be optimized further. Look for it and add the BRCOND into 4179 // the worklist. 4180 if (N->hasOneUse()) { 4181 SDNode *Use = *N->use_begin(); 4182 if (Use->getOpcode() == ISD::BRCOND) 4183 AddToWorkList(Use); 4184 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) { 4185 // Also look pass the truncate. 4186 Use = *Use->use_begin(); 4187 if (Use->getOpcode() == ISD::BRCOND) 4188 AddToWorkList(Use); 4189 } 4190 } 4191 4192 return SDValue(); 4193} 4194 4195SDValue DAGCombiner::visitCTLZ(SDNode *N) { 4196 SDValue N0 = N->getOperand(0); 4197 EVT VT = N->getValueType(0); 4198 4199 // fold (ctlz c1) -> c2 4200 if (isa<ConstantSDNode>(N0)) 4201 return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0); 4202 return SDValue(); 4203} 4204 4205SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) { 4206 SDValue N0 = N->getOperand(0); 4207 EVT VT = N->getValueType(0); 4208 4209 // fold (ctlz_zero_undef c1) -> c2 4210 if (isa<ConstantSDNode>(N0)) 4211 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0); 4212 return SDValue(); 4213} 4214 4215SDValue DAGCombiner::visitCTTZ(SDNode *N) { 4216 SDValue N0 = N->getOperand(0); 4217 EVT VT = N->getValueType(0); 4218 4219 // fold (cttz c1) -> c2 4220 if (isa<ConstantSDNode>(N0)) 4221 return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0); 4222 return SDValue(); 4223} 4224 4225SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) { 4226 SDValue N0 = N->getOperand(0); 4227 EVT VT = N->getValueType(0); 4228 4229 // fold (cttz_zero_undef c1) -> c2 4230 if (isa<ConstantSDNode>(N0)) 4231 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0); 4232 return SDValue(); 4233} 4234 4235SDValue DAGCombiner::visitCTPOP(SDNode *N) { 4236 SDValue N0 = N->getOperand(0); 4237 EVT VT = N->getValueType(0); 4238 4239 // fold (ctpop c1) -> c2 4240 if (isa<ConstantSDNode>(N0)) 4241 return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0); 4242 return SDValue(); 4243} 4244 4245SDValue DAGCombiner::visitSELECT(SDNode *N) { 4246 SDValue N0 = N->getOperand(0); 4247 SDValue N1 = N->getOperand(1); 4248 SDValue N2 = N->getOperand(2); 4249 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 4250 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 4251 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2); 4252 EVT VT = N->getValueType(0); 4253 EVT VT0 = N0.getValueType(); 4254 4255 // fold (select C, X, X) -> X 4256 if (N1 == N2) 4257 return N1; 4258 // fold (select true, X, Y) -> X 4259 if (N0C && !N0C->isNullValue()) 4260 return N1; 4261 // fold (select false, X, Y) -> Y 4262 if (N0C && N0C->isNullValue()) 4263 return N2; 4264 // fold (select C, 1, X) -> (or C, X) 4265 if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1) 4266 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2); 4267 // fold (select C, 0, 1) -> (xor C, 1) 4268 if (VT.isInteger() && 4269 (VT0 == MVT::i1 || 4270 (VT0.isInteger() && 4271 TLI.getBooleanContents(false) == 4272 TargetLowering::ZeroOrOneBooleanContent)) && 4273 N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) { 4274 SDValue XORNode; 4275 if (VT == VT0) 4276 return DAG.getNode(ISD::XOR, SDLoc(N), VT0, 4277 N0, DAG.getConstant(1, VT0)); 4278 XORNode = DAG.getNode(ISD::XOR, SDLoc(N0), VT0, 4279 N0, DAG.getConstant(1, VT0)); 4280 AddToWorkList(XORNode.getNode()); 4281 if (VT.bitsGT(VT0)) 4282 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode); 4283 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode); 4284 } 4285 // fold (select C, 0, X) -> (and (not C), X) 4286 if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) { 4287 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT); 4288 AddToWorkList(NOTNode.getNode()); 4289 return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2); 4290 } 4291 // fold (select C, X, 1) -> (or (not C), X) 4292 if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) { 4293 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT); 4294 AddToWorkList(NOTNode.getNode()); 4295 return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1); 4296 } 4297 // fold (select C, X, 0) -> (and C, X) 4298 if (VT == MVT::i1 && N2C && N2C->isNullValue()) 4299 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1); 4300 // fold (select X, X, Y) -> (or X, Y) 4301 // fold (select X, 1, Y) -> (or X, Y) 4302 if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1))) 4303 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2); 4304 // fold (select X, Y, X) -> (and X, Y) 4305 // fold (select X, Y, 0) -> (and X, Y) 4306 if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0))) 4307 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1); 4308 4309 // If we can fold this based on the true/false value, do so. 4310 if (SimplifySelectOps(N, N1, N2)) 4311 return SDValue(N, 0); // Don't revisit N. 4312 4313 // fold selects based on a setcc into other things, such as min/max/abs 4314 if (N0.getOpcode() == ISD::SETCC) { 4315 // FIXME: 4316 // Check against MVT::Other for SELECT_CC, which is a workaround for targets 4317 // having to say they don't support SELECT_CC on every type the DAG knows 4318 // about, since there is no way to mark an opcode illegal at all value types 4319 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other) && 4320 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) 4321 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, 4322 N0.getOperand(0), N0.getOperand(1), 4323 N1, N2, N0.getOperand(2)); 4324 return SimplifySelect(SDLoc(N), N0, N1, N2); 4325 } 4326 4327 return SDValue(); 4328} 4329 4330static 4331std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) { 4332 SDLoc DL(N); 4333 EVT LoVT, HiVT; 4334 llvm::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0)); 4335 4336 // Split the inputs. 4337 SDValue Lo, Hi, LL, LH, RL, RH; 4338 llvm::tie(LL, LH) = DAG.SplitVectorOperand(N, 0); 4339 llvm::tie(RL, RH) = DAG.SplitVectorOperand(N, 1); 4340 4341 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2)); 4342 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2)); 4343 4344 return std::make_pair(Lo, Hi); 4345} 4346 4347SDValue DAGCombiner::visitVSELECT(SDNode *N) { 4348 SDValue N0 = N->getOperand(0); 4349 SDValue N1 = N->getOperand(1); 4350 SDValue N2 = N->getOperand(2); 4351 SDLoc DL(N); 4352 4353 // Canonicalize integer abs. 4354 // vselect (setg[te] X, 0), X, -X -> 4355 // vselect (setgt X, -1), X, -X -> 4356 // vselect (setl[te] X, 0), -X, X -> 4357 // Y = sra (X, size(X)-1); xor (add (X, Y), Y) 4358 if (N0.getOpcode() == ISD::SETCC) { 4359 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1); 4360 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get(); 4361 bool isAbs = false; 4362 bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode()); 4363 4364 if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) || 4365 (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) && 4366 N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1)) 4367 isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode()); 4368 else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) && 4369 N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1)) 4370 isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode()); 4371 4372 if (isAbs) { 4373 EVT VT = LHS.getValueType(); 4374 SDValue Shift = DAG.getNode( 4375 ISD::SRA, DL, VT, LHS, 4376 DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, VT)); 4377 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift); 4378 AddToWorkList(Shift.getNode()); 4379 AddToWorkList(Add.getNode()); 4380 return DAG.getNode(ISD::XOR, DL, VT, Add, Shift); 4381 } 4382 } 4383 4384 // If the VSELECT result requires splitting and the mask is provided by a 4385 // SETCC, then split both nodes and its operands before legalization. This 4386 // prevents the type legalizer from unrolling SETCC into scalar comparisons 4387 // and enables future optimizations (e.g. min/max pattern matching on X86). 4388 if (N0.getOpcode() == ISD::SETCC) { 4389 EVT VT = N->getValueType(0); 4390 4391 // Check if any splitting is required. 4392 if (TLI.getTypeAction(*DAG.getContext(), VT) != 4393 TargetLowering::TypeSplitVector) 4394 return SDValue(); 4395 4396 SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH; 4397 llvm::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG); 4398 llvm::tie(LL, LH) = DAG.SplitVectorOperand(N, 1); 4399 llvm::tie(RL, RH) = DAG.SplitVectorOperand(N, 2); 4400 4401 Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL); 4402 Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH); 4403 4404 // Add the new VSELECT nodes to the work list in case they need to be split 4405 // again. 4406 AddToWorkList(Lo.getNode()); 4407 AddToWorkList(Hi.getNode()); 4408 4409 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi); 4410 } 4411 4412 return SDValue(); 4413} 4414 4415SDValue DAGCombiner::visitSELECT_CC(SDNode *N) { 4416 SDValue N0 = N->getOperand(0); 4417 SDValue N1 = N->getOperand(1); 4418 SDValue N2 = N->getOperand(2); 4419 SDValue N3 = N->getOperand(3); 4420 SDValue N4 = N->getOperand(4); 4421 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get(); 4422 4423 // fold select_cc lhs, rhs, x, x, cc -> x 4424 if (N2 == N3) 4425 return N2; 4426 4427 // Determine if the condition we're dealing with is constant 4428 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()), 4429 N0, N1, CC, SDLoc(N), false); 4430 if (SCC.getNode()) { 4431 AddToWorkList(SCC.getNode()); 4432 4433 if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) { 4434 if (!SCCC->isNullValue()) 4435 return N2; // cond always true -> true val 4436 else 4437 return N3; // cond always false -> false val 4438 } 4439 4440 // Fold to a simpler select_cc 4441 if (SCC.getOpcode() == ISD::SETCC) 4442 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(), 4443 SCC.getOperand(0), SCC.getOperand(1), N2, N3, 4444 SCC.getOperand(2)); 4445 } 4446 4447 // If we can fold this based on the true/false value, do so. 4448 if (SimplifySelectOps(N, N2, N3)) 4449 return SDValue(N, 0); // Don't revisit N. 4450 4451 // fold select_cc into other things, such as min/max/abs 4452 return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC); 4453} 4454 4455SDValue DAGCombiner::visitSETCC(SDNode *N) { 4456 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1), 4457 cast<CondCodeSDNode>(N->getOperand(2))->get(), 4458 SDLoc(N)); 4459} 4460 4461// ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this: 4462// "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))" 4463// transformation. Returns true if extension are possible and the above 4464// mentioned transformation is profitable. 4465static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0, 4466 unsigned ExtOpc, 4467 SmallVectorImpl<SDNode *> &ExtendNodes, 4468 const TargetLowering &TLI) { 4469 bool HasCopyToRegUses = false; 4470 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType()); 4471 for (SDNode::use_iterator UI = N0.getNode()->use_begin(), 4472 UE = N0.getNode()->use_end(); 4473 UI != UE; ++UI) { 4474 SDNode *User = *UI; 4475 if (User == N) 4476 continue; 4477 if (UI.getUse().getResNo() != N0.getResNo()) 4478 continue; 4479 // FIXME: Only extend SETCC N, N and SETCC N, c for now. 4480 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) { 4481 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get(); 4482 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC)) 4483 // Sign bits will be lost after a zext. 4484 return false; 4485 bool Add = false; 4486 for (unsigned i = 0; i != 2; ++i) { 4487 SDValue UseOp = User->getOperand(i); 4488 if (UseOp == N0) 4489 continue; 4490 if (!isa<ConstantSDNode>(UseOp)) 4491 return false; 4492 Add = true; 4493 } 4494 if (Add) 4495 ExtendNodes.push_back(User); 4496 continue; 4497 } 4498 // If truncates aren't free and there are users we can't 4499 // extend, it isn't worthwhile. 4500 if (!isTruncFree) 4501 return false; 4502 // Remember if this value is live-out. 4503 if (User->getOpcode() == ISD::CopyToReg) 4504 HasCopyToRegUses = true; 4505 } 4506 4507 if (HasCopyToRegUses) { 4508 bool BothLiveOut = false; 4509 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end(); 4510 UI != UE; ++UI) { 4511 SDUse &Use = UI.getUse(); 4512 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) { 4513 BothLiveOut = true; 4514 break; 4515 } 4516 } 4517 if (BothLiveOut) 4518 // Both unextended and extended values are live out. There had better be 4519 // a good reason for the transformation. 4520 return ExtendNodes.size(); 4521 } 4522 return true; 4523} 4524 4525void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs, 4526 SDValue Trunc, SDValue ExtLoad, SDLoc DL, 4527 ISD::NodeType ExtType) { 4528 // Extend SetCC uses if necessary. 4529 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) { 4530 SDNode *SetCC = SetCCs[i]; 4531 SmallVector<SDValue, 4> Ops; 4532 4533 for (unsigned j = 0; j != 2; ++j) { 4534 SDValue SOp = SetCC->getOperand(j); 4535 if (SOp == Trunc) 4536 Ops.push_back(ExtLoad); 4537 else 4538 Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp)); 4539 } 4540 4541 Ops.push_back(SetCC->getOperand(2)); 4542 CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), 4543 &Ops[0], Ops.size())); 4544 } 4545} 4546 4547SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) { 4548 SDValue N0 = N->getOperand(0); 4549 EVT VT = N->getValueType(0); 4550 4551 // fold (sext c1) -> c1 4552 if (isa<ConstantSDNode>(N0)) 4553 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N0); 4554 4555 // fold (sext (sext x)) -> (sext x) 4556 // fold (sext (aext x)) -> (sext x) 4557 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) 4558 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, 4559 N0.getOperand(0)); 4560 4561 if (N0.getOpcode() == ISD::TRUNCATE) { 4562 // fold (sext (truncate (load x))) -> (sext (smaller load x)) 4563 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n))) 4564 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode()); 4565 if (NarrowLoad.getNode()) { 4566 SDNode* oye = N0.getNode()->getOperand(0).getNode(); 4567 if (NarrowLoad.getNode() != N0.getNode()) { 4568 CombineTo(N0.getNode(), NarrowLoad); 4569 // CombineTo deleted the truncate, if needed, but not what's under it. 4570 AddToWorkList(oye); 4571 } 4572 return SDValue(N, 0); // Return N so it doesn't get rechecked! 4573 } 4574 4575 // See if the value being truncated is already sign extended. If so, just 4576 // eliminate the trunc/sext pair. 4577 SDValue Op = N0.getOperand(0); 4578 unsigned OpBits = Op.getValueType().getScalarType().getSizeInBits(); 4579 unsigned MidBits = N0.getValueType().getScalarType().getSizeInBits(); 4580 unsigned DestBits = VT.getScalarType().getSizeInBits(); 4581 unsigned NumSignBits = DAG.ComputeNumSignBits(Op); 4582 4583 if (OpBits == DestBits) { 4584 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign 4585 // bits, it is already ready. 4586 if (NumSignBits > DestBits-MidBits) 4587 return Op; 4588 } else if (OpBits < DestBits) { 4589 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign 4590 // bits, just sext from i32. 4591 if (NumSignBits > OpBits-MidBits) 4592 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op); 4593 } else { 4594 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign 4595 // bits, just truncate to i32. 4596 if (NumSignBits > OpBits-MidBits) 4597 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op); 4598 } 4599 4600 // fold (sext (truncate x)) -> (sextinreg x). 4601 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, 4602 N0.getValueType())) { 4603 if (OpBits < DestBits) 4604 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op); 4605 else if (OpBits > DestBits) 4606 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op); 4607 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op, 4608 DAG.getValueType(N0.getValueType())); 4609 } 4610 } 4611 4612 // fold (sext (load x)) -> (sext (truncate (sextload x))) 4613 // None of the supported targets knows how to perform load and sign extend 4614 // on vectors in one instruction. We only perform this transformation on 4615 // scalars. 4616 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() && 4617 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) || 4618 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()))) { 4619 bool DoXform = true; 4620 SmallVector<SDNode*, 4> SetCCs; 4621 if (!N0.hasOneUse()) 4622 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI); 4623 if (DoXform) { 4624 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 4625 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT, 4626 LN0->getChain(), 4627 LN0->getBasePtr(), N0.getValueType(), 4628 LN0->getMemOperand()); 4629 CombineTo(N, ExtLoad); 4630 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 4631 N0.getValueType(), ExtLoad); 4632 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1)); 4633 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N), 4634 ISD::SIGN_EXTEND); 4635 return SDValue(N, 0); // Return N so it doesn't get rechecked! 4636 } 4637 } 4638 4639 // fold (sext (sextload x)) -> (sext (truncate (sextload x))) 4640 // fold (sext ( extload x)) -> (sext (truncate (sextload x))) 4641 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) && 4642 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) { 4643 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 4644 EVT MemVT = LN0->getMemoryVT(); 4645 if ((!LegalOperations && !LN0->isVolatile()) || 4646 TLI.isLoadExtLegal(ISD::SEXTLOAD, MemVT)) { 4647 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT, 4648 LN0->getChain(), 4649 LN0->getBasePtr(), MemVT, 4650 LN0->getMemOperand()); 4651 CombineTo(N, ExtLoad); 4652 CombineTo(N0.getNode(), 4653 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 4654 N0.getValueType(), ExtLoad), 4655 ExtLoad.getValue(1)); 4656 return SDValue(N, 0); // Return N so it doesn't get rechecked! 4657 } 4658 } 4659 4660 // fold (sext (and/or/xor (load x), cst)) -> 4661 // (and/or/xor (sextload x), (sext cst)) 4662 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR || 4663 N0.getOpcode() == ISD::XOR) && 4664 isa<LoadSDNode>(N0.getOperand(0)) && 4665 N0.getOperand(1).getOpcode() == ISD::Constant && 4666 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()) && 4667 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) { 4668 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0)); 4669 if (LN0->getExtensionType() != ISD::ZEXTLOAD) { 4670 bool DoXform = true; 4671 SmallVector<SDNode*, 4> SetCCs; 4672 if (!N0.hasOneUse()) 4673 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND, 4674 SetCCs, TLI); 4675 if (DoXform) { 4676 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT, 4677 LN0->getChain(), LN0->getBasePtr(), 4678 LN0->getMemoryVT(), 4679 LN0->getMemOperand()); 4680 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 4681 Mask = Mask.sext(VT.getSizeInBits()); 4682 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT, 4683 ExtLoad, DAG.getConstant(Mask, VT)); 4684 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, 4685 SDLoc(N0.getOperand(0)), 4686 N0.getOperand(0).getValueType(), ExtLoad); 4687 CombineTo(N, And); 4688 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1)); 4689 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N), 4690 ISD::SIGN_EXTEND); 4691 return SDValue(N, 0); // Return N so it doesn't get rechecked! 4692 } 4693 } 4694 } 4695 4696 if (N0.getOpcode() == ISD::SETCC) { 4697 // sext(setcc) -> sext_in_reg(vsetcc) for vectors. 4698 // Only do this before legalize for now. 4699 if (VT.isVector() && !LegalOperations && 4700 TLI.getBooleanContents(true) == 4701 TargetLowering::ZeroOrNegativeOneBooleanContent) { 4702 EVT N0VT = N0.getOperand(0).getValueType(); 4703 // On some architectures (such as SSE/NEON/etc) the SETCC result type is 4704 // of the same size as the compared operands. Only optimize sext(setcc()) 4705 // if this is the case. 4706 EVT SVT = getSetCCResultType(N0VT); 4707 4708 // We know that the # elements of the results is the same as the 4709 // # elements of the compare (and the # elements of the compare result 4710 // for that matter). Check to see that they are the same size. If so, 4711 // we know that the element size of the sext'd result matches the 4712 // element size of the compare operands. 4713 if (VT.getSizeInBits() == SVT.getSizeInBits()) 4714 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0), 4715 N0.getOperand(1), 4716 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 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 MatchingVectorType = N0VT.changeVectorElementTypeToInteger(); 4722 if (SVT == MatchingVectorType) { 4723 SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType, 4724 N0.getOperand(0), N0.getOperand(1), 4725 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 4726 return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT); 4727 } 4728 } 4729 4730 // sext(setcc x, y, cc) -> (select_cc x, y, -1, 0, cc) 4731 unsigned ElementWidth = VT.getScalarType().getSizeInBits(); 4732 SDValue NegOne = 4733 DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT); 4734 SDValue SCC = 4735 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1), 4736 NegOne, DAG.getConstant(0, VT), 4737 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true); 4738 if (SCC.getNode()) return SCC; 4739 if (!VT.isVector() && 4740 (!LegalOperations || 4741 TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(VT)))) { 4742 return DAG.getSelect(SDLoc(N), VT, 4743 DAG.getSetCC(SDLoc(N), 4744 getSetCCResultType(VT), 4745 N0.getOperand(0), N0.getOperand(1), 4746 cast<CondCodeSDNode>(N0.getOperand(2))->get()), 4747 NegOne, DAG.getConstant(0, VT)); 4748 } 4749 } 4750 4751 // fold (sext x) -> (zext x) if the sign bit is known zero. 4752 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) && 4753 DAG.SignBitIsZero(N0)) 4754 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0); 4755 4756 return SDValue(); 4757} 4758 4759// isTruncateOf - If N is a truncate of some other value, return true, record 4760// the value being truncated in Op and which of Op's bits are zero in KnownZero. 4761// This function computes KnownZero to avoid a duplicated call to 4762// ComputeMaskedBits in the caller. 4763static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op, 4764 APInt &KnownZero) { 4765 APInt KnownOne; 4766 if (N->getOpcode() == ISD::TRUNCATE) { 4767 Op = N->getOperand(0); 4768 DAG.ComputeMaskedBits(Op, KnownZero, KnownOne); 4769 return true; 4770 } 4771 4772 if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 || 4773 cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE) 4774 return false; 4775 4776 SDValue Op0 = N->getOperand(0); 4777 SDValue Op1 = N->getOperand(1); 4778 assert(Op0.getValueType() == Op1.getValueType()); 4779 4780 ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0); 4781 ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1); 4782 if (COp0 && COp0->isNullValue()) 4783 Op = Op1; 4784 else if (COp1 && COp1->isNullValue()) 4785 Op = Op0; 4786 else 4787 return false; 4788 4789 DAG.ComputeMaskedBits(Op, KnownZero, KnownOne); 4790 4791 if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue()) 4792 return false; 4793 4794 return true; 4795} 4796 4797SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) { 4798 SDValue N0 = N->getOperand(0); 4799 EVT VT = N->getValueType(0); 4800 4801 // fold (zext c1) -> c1 4802 if (isa<ConstantSDNode>(N0)) 4803 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0); 4804 // fold (zext (zext x)) -> (zext x) 4805 // fold (zext (aext x)) -> (zext x) 4806 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) 4807 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, 4808 N0.getOperand(0)); 4809 4810 // fold (zext (truncate x)) -> (zext x) or 4811 // (zext (truncate x)) -> (truncate x) 4812 // This is valid when the truncated bits of x are already zero. 4813 // FIXME: We should extend this to work for vectors too. 4814 SDValue Op; 4815 APInt KnownZero; 4816 if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) { 4817 APInt TruncatedBits = 4818 (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ? 4819 APInt(Op.getValueSizeInBits(), 0) : 4820 APInt::getBitsSet(Op.getValueSizeInBits(), 4821 N0.getValueSizeInBits(), 4822 std::min(Op.getValueSizeInBits(), 4823 VT.getSizeInBits())); 4824 if (TruncatedBits == (KnownZero & TruncatedBits)) { 4825 if (VT.bitsGT(Op.getValueType())) 4826 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op); 4827 if (VT.bitsLT(Op.getValueType())) 4828 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op); 4829 4830 return Op; 4831 } 4832 } 4833 4834 // fold (zext (truncate (load x))) -> (zext (smaller load x)) 4835 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n))) 4836 if (N0.getOpcode() == ISD::TRUNCATE) { 4837 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode()); 4838 if (NarrowLoad.getNode()) { 4839 SDNode* oye = N0.getNode()->getOperand(0).getNode(); 4840 if (NarrowLoad.getNode() != N0.getNode()) { 4841 CombineTo(N0.getNode(), NarrowLoad); 4842 // CombineTo deleted the truncate, if needed, but not what's under it. 4843 AddToWorkList(oye); 4844 } 4845 return SDValue(N, 0); // Return N so it doesn't get rechecked! 4846 } 4847 } 4848 4849 // fold (zext (truncate x)) -> (and x, mask) 4850 if (N0.getOpcode() == ISD::TRUNCATE && 4851 (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) { 4852 4853 // fold (zext (truncate (load x))) -> (zext (smaller load x)) 4854 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n))) 4855 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode()); 4856 if (NarrowLoad.getNode()) { 4857 SDNode* oye = N0.getNode()->getOperand(0).getNode(); 4858 if (NarrowLoad.getNode() != N0.getNode()) { 4859 CombineTo(N0.getNode(), NarrowLoad); 4860 // CombineTo deleted the truncate, if needed, but not what's under it. 4861 AddToWorkList(oye); 4862 } 4863 return SDValue(N, 0); // Return N so it doesn't get rechecked! 4864 } 4865 4866 SDValue Op = N0.getOperand(0); 4867 if (Op.getValueType().bitsLT(VT)) { 4868 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op); 4869 AddToWorkList(Op.getNode()); 4870 } else if (Op.getValueType().bitsGT(VT)) { 4871 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op); 4872 AddToWorkList(Op.getNode()); 4873 } 4874 return DAG.getZeroExtendInReg(Op, SDLoc(N), 4875 N0.getValueType().getScalarType()); 4876 } 4877 4878 // Fold (zext (and (trunc x), cst)) -> (and x, cst), 4879 // if either of the casts is not free. 4880 if (N0.getOpcode() == ISD::AND && 4881 N0.getOperand(0).getOpcode() == ISD::TRUNCATE && 4882 N0.getOperand(1).getOpcode() == ISD::Constant && 4883 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(), 4884 N0.getValueType()) || 4885 !TLI.isZExtFree(N0.getValueType(), VT))) { 4886 SDValue X = N0.getOperand(0).getOperand(0); 4887 if (X.getValueType().bitsLT(VT)) { 4888 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X); 4889 } else if (X.getValueType().bitsGT(VT)) { 4890 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X); 4891 } 4892 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 4893 Mask = Mask.zext(VT.getSizeInBits()); 4894 return DAG.getNode(ISD::AND, SDLoc(N), VT, 4895 X, DAG.getConstant(Mask, VT)); 4896 } 4897 4898 // fold (zext (load x)) -> (zext (truncate (zextload x))) 4899 // None of the supported targets knows how to perform load and vector_zext 4900 // on vectors in one instruction. We only perform this transformation on 4901 // scalars. 4902 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() && 4903 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) || 4904 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()))) { 4905 bool DoXform = true; 4906 SmallVector<SDNode*, 4> SetCCs; 4907 if (!N0.hasOneUse()) 4908 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI); 4909 if (DoXform) { 4910 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 4911 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT, 4912 LN0->getChain(), 4913 LN0->getBasePtr(), N0.getValueType(), 4914 LN0->getMemOperand()); 4915 CombineTo(N, ExtLoad); 4916 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 4917 N0.getValueType(), ExtLoad); 4918 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1)); 4919 4920 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N), 4921 ISD::ZERO_EXTEND); 4922 return SDValue(N, 0); // Return N so it doesn't get rechecked! 4923 } 4924 } 4925 4926 // fold (zext (and/or/xor (load x), cst)) -> 4927 // (and/or/xor (zextload x), (zext cst)) 4928 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR || 4929 N0.getOpcode() == ISD::XOR) && 4930 isa<LoadSDNode>(N0.getOperand(0)) && 4931 N0.getOperand(1).getOpcode() == ISD::Constant && 4932 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()) && 4933 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) { 4934 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0)); 4935 if (LN0->getExtensionType() != ISD::SEXTLOAD) { 4936 bool DoXform = true; 4937 SmallVector<SDNode*, 4> SetCCs; 4938 if (!N0.hasOneUse()) 4939 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND, 4940 SetCCs, TLI); 4941 if (DoXform) { 4942 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT, 4943 LN0->getChain(), LN0->getBasePtr(), 4944 LN0->getMemoryVT(), 4945 LN0->getMemOperand()); 4946 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 4947 Mask = Mask.zext(VT.getSizeInBits()); 4948 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT, 4949 ExtLoad, DAG.getConstant(Mask, VT)); 4950 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, 4951 SDLoc(N0.getOperand(0)), 4952 N0.getOperand(0).getValueType(), ExtLoad); 4953 CombineTo(N, And); 4954 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1)); 4955 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N), 4956 ISD::ZERO_EXTEND); 4957 return SDValue(N, 0); // Return N so it doesn't get rechecked! 4958 } 4959 } 4960 } 4961 4962 // fold (zext (zextload x)) -> (zext (truncate (zextload x))) 4963 // fold (zext ( extload x)) -> (zext (truncate (zextload x))) 4964 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) && 4965 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) { 4966 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 4967 EVT MemVT = LN0->getMemoryVT(); 4968 if ((!LegalOperations && !LN0->isVolatile()) || 4969 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT)) { 4970 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT, 4971 LN0->getChain(), 4972 LN0->getBasePtr(), MemVT, 4973 LN0->getMemOperand()); 4974 CombineTo(N, ExtLoad); 4975 CombineTo(N0.getNode(), 4976 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), 4977 ExtLoad), 4978 ExtLoad.getValue(1)); 4979 return SDValue(N, 0); // Return N so it doesn't get rechecked! 4980 } 4981 } 4982 4983 if (N0.getOpcode() == ISD::SETCC) { 4984 if (!LegalOperations && VT.isVector()) { 4985 // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors. 4986 // Only do this before legalize for now. 4987 EVT N0VT = N0.getOperand(0).getValueType(); 4988 EVT EltVT = VT.getVectorElementType(); 4989 SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(), 4990 DAG.getConstant(1, EltVT)); 4991 if (VT.getSizeInBits() == N0VT.getSizeInBits()) 4992 // We know that the # elements of the results is the same as the 4993 // # elements of the compare (and the # elements of the compare result 4994 // for that matter). Check to see that they are the same size. If so, 4995 // we know that the element size of the sext'd result matches the 4996 // element size of the compare operands. 4997 return DAG.getNode(ISD::AND, SDLoc(N), VT, 4998 DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0), 4999 N0.getOperand(1), 5000 cast<CondCodeSDNode>(N0.getOperand(2))->get()), 5001 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, 5002 &OneOps[0], OneOps.size())); 5003 5004 // If the desired elements are smaller or larger than the source 5005 // elements we can use a matching integer vector type and then 5006 // truncate/sign extend 5007 EVT MatchingElementType = 5008 EVT::getIntegerVT(*DAG.getContext(), 5009 N0VT.getScalarType().getSizeInBits()); 5010 EVT MatchingVectorType = 5011 EVT::getVectorVT(*DAG.getContext(), MatchingElementType, 5012 N0VT.getVectorNumElements()); 5013 SDValue VsetCC = 5014 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0), 5015 N0.getOperand(1), 5016 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 5017 return DAG.getNode(ISD::AND, SDLoc(N), VT, 5018 DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT), 5019 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, 5020 &OneOps[0], OneOps.size())); 5021 } 5022 5023 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc 5024 SDValue SCC = 5025 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1), 5026 DAG.getConstant(1, VT), DAG.getConstant(0, VT), 5027 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true); 5028 if (SCC.getNode()) return SCC; 5029 } 5030 5031 // (zext (shl (zext x), cst)) -> (shl (zext x), cst) 5032 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) && 5033 isa<ConstantSDNode>(N0.getOperand(1)) && 5034 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND && 5035 N0.hasOneUse()) { 5036 SDValue ShAmt = N0.getOperand(1); 5037 unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue(); 5038 if (N0.getOpcode() == ISD::SHL) { 5039 SDValue InnerZExt = N0.getOperand(0); 5040 // If the original shl may be shifting out bits, do not perform this 5041 // transformation. 5042 unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() - 5043 InnerZExt.getOperand(0).getValueType().getSizeInBits(); 5044 if (ShAmtVal > KnownZeroBits) 5045 return SDValue(); 5046 } 5047 5048 SDLoc DL(N); 5049 5050 // Ensure that the shift amount is wide enough for the shifted value. 5051 if (VT.getSizeInBits() >= 256) 5052 ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt); 5053 5054 return DAG.getNode(N0.getOpcode(), DL, VT, 5055 DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)), 5056 ShAmt); 5057 } 5058 5059 return SDValue(); 5060} 5061 5062SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) { 5063 SDValue N0 = N->getOperand(0); 5064 EVT VT = N->getValueType(0); 5065 5066 // fold (aext c1) -> c1 5067 if (isa<ConstantSDNode>(N0)) 5068 return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, N0); 5069 // fold (aext (aext x)) -> (aext x) 5070 // fold (aext (zext x)) -> (zext x) 5071 // fold (aext (sext x)) -> (sext x) 5072 if (N0.getOpcode() == ISD::ANY_EXTEND || 5073 N0.getOpcode() == ISD::ZERO_EXTEND || 5074 N0.getOpcode() == ISD::SIGN_EXTEND) 5075 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0)); 5076 5077 // fold (aext (truncate (load x))) -> (aext (smaller load x)) 5078 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n))) 5079 if (N0.getOpcode() == ISD::TRUNCATE) { 5080 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode()); 5081 if (NarrowLoad.getNode()) { 5082 SDNode* oye = N0.getNode()->getOperand(0).getNode(); 5083 if (NarrowLoad.getNode() != N0.getNode()) { 5084 CombineTo(N0.getNode(), NarrowLoad); 5085 // CombineTo deleted the truncate, if needed, but not what's under it. 5086 AddToWorkList(oye); 5087 } 5088 return SDValue(N, 0); // Return N so it doesn't get rechecked! 5089 } 5090 } 5091 5092 // fold (aext (truncate x)) 5093 if (N0.getOpcode() == ISD::TRUNCATE) { 5094 SDValue TruncOp = N0.getOperand(0); 5095 if (TruncOp.getValueType() == VT) 5096 return TruncOp; // x iff x size == zext size. 5097 if (TruncOp.getValueType().bitsGT(VT)) 5098 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp); 5099 return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp); 5100 } 5101 5102 // Fold (aext (and (trunc x), cst)) -> (and x, cst) 5103 // if the trunc is not free. 5104 if (N0.getOpcode() == ISD::AND && 5105 N0.getOperand(0).getOpcode() == ISD::TRUNCATE && 5106 N0.getOperand(1).getOpcode() == ISD::Constant && 5107 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(), 5108 N0.getValueType())) { 5109 SDValue X = N0.getOperand(0).getOperand(0); 5110 if (X.getValueType().bitsLT(VT)) { 5111 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X); 5112 } else if (X.getValueType().bitsGT(VT)) { 5113 X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X); 5114 } 5115 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 5116 Mask = Mask.zext(VT.getSizeInBits()); 5117 return DAG.getNode(ISD::AND, SDLoc(N), VT, 5118 X, DAG.getConstant(Mask, VT)); 5119 } 5120 5121 // fold (aext (load x)) -> (aext (truncate (extload x))) 5122 // None of the supported targets knows how to perform load and any_ext 5123 // on vectors in one instruction. We only perform this transformation on 5124 // scalars. 5125 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() && 5126 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) || 5127 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) { 5128 bool DoXform = true; 5129 SmallVector<SDNode*, 4> SetCCs; 5130 if (!N0.hasOneUse()) 5131 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI); 5132 if (DoXform) { 5133 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 5134 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT, 5135 LN0->getChain(), 5136 LN0->getBasePtr(), N0.getValueType(), 5137 LN0->getMemOperand()); 5138 CombineTo(N, ExtLoad); 5139 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 5140 N0.getValueType(), ExtLoad); 5141 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1)); 5142 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N), 5143 ISD::ANY_EXTEND); 5144 return SDValue(N, 0); // Return N so it doesn't get rechecked! 5145 } 5146 } 5147 5148 // fold (aext (zextload x)) -> (aext (truncate (zextload x))) 5149 // fold (aext (sextload x)) -> (aext (truncate (sextload x))) 5150 // fold (aext ( extload x)) -> (aext (truncate (extload x))) 5151 if (N0.getOpcode() == ISD::LOAD && 5152 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 5153 N0.hasOneUse()) { 5154 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 5155 EVT MemVT = LN0->getMemoryVT(); 5156 SDValue ExtLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(N), 5157 VT, LN0->getChain(), LN0->getBasePtr(), 5158 MemVT, LN0->getMemOperand()); 5159 CombineTo(N, ExtLoad); 5160 CombineTo(N0.getNode(), 5161 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 5162 N0.getValueType(), ExtLoad), 5163 ExtLoad.getValue(1)); 5164 return SDValue(N, 0); // Return N so it doesn't get rechecked! 5165 } 5166 5167 if (N0.getOpcode() == ISD::SETCC) { 5168 // aext(setcc) -> sext_in_reg(vsetcc) for vectors. 5169 // Only do this before legalize for now. 5170 if (VT.isVector() && !LegalOperations) { 5171 EVT N0VT = N0.getOperand(0).getValueType(); 5172 // We know that the # elements of the results is the same as the 5173 // # elements of the compare (and the # elements of the compare result 5174 // for that matter). Check to see that they are the same size. If so, 5175 // we know that the element size of the sext'd result matches the 5176 // element size of the compare operands. 5177 if (VT.getSizeInBits() == N0VT.getSizeInBits()) 5178 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0), 5179 N0.getOperand(1), 5180 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 5181 // If the desired elements are smaller or larger than the source 5182 // elements we can use a matching integer vector type and then 5183 // truncate/sign extend 5184 else { 5185 EVT MatchingElementType = 5186 EVT::getIntegerVT(*DAG.getContext(), 5187 N0VT.getScalarType().getSizeInBits()); 5188 EVT MatchingVectorType = 5189 EVT::getVectorVT(*DAG.getContext(), MatchingElementType, 5190 N0VT.getVectorNumElements()); 5191 SDValue VsetCC = 5192 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0), 5193 N0.getOperand(1), 5194 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 5195 return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT); 5196 } 5197 } 5198 5199 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc 5200 SDValue SCC = 5201 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1), 5202 DAG.getConstant(1, VT), DAG.getConstant(0, VT), 5203 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true); 5204 if (SCC.getNode()) 5205 return SCC; 5206 } 5207 5208 return SDValue(); 5209} 5210 5211/// GetDemandedBits - See if the specified operand can be simplified with the 5212/// knowledge that only the bits specified by Mask are used. If so, return the 5213/// simpler operand, otherwise return a null SDValue. 5214SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) { 5215 switch (V.getOpcode()) { 5216 default: break; 5217 case ISD::Constant: { 5218 const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode()); 5219 assert(CV != 0 && "Const value should be ConstSDNode."); 5220 const APInt &CVal = CV->getAPIntValue(); 5221 APInt NewVal = CVal & Mask; 5222 if (NewVal != CVal) 5223 return DAG.getConstant(NewVal, V.getValueType()); 5224 break; 5225 } 5226 case ISD::OR: 5227 case ISD::XOR: 5228 // If the LHS or RHS don't contribute bits to the or, drop them. 5229 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask)) 5230 return V.getOperand(1); 5231 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask)) 5232 return V.getOperand(0); 5233 break; 5234 case ISD::SRL: 5235 // Only look at single-use SRLs. 5236 if (!V.getNode()->hasOneUse()) 5237 break; 5238 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) { 5239 // See if we can recursively simplify the LHS. 5240 unsigned Amt = RHSC->getZExtValue(); 5241 5242 // Watch out for shift count overflow though. 5243 if (Amt >= Mask.getBitWidth()) break; 5244 APInt NewMask = Mask << Amt; 5245 SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask); 5246 if (SimplifyLHS.getNode()) 5247 return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(), 5248 SimplifyLHS, V.getOperand(1)); 5249 } 5250 } 5251 return SDValue(); 5252} 5253 5254/// ReduceLoadWidth - If the result of a wider load is shifted to right of N 5255/// bits and then truncated to a narrower type and where N is a multiple 5256/// of number of bits of the narrower type, transform it to a narrower load 5257/// from address + N / num of bits of new type. If the result is to be 5258/// extended, also fold the extension to form a extending load. 5259SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) { 5260 unsigned Opc = N->getOpcode(); 5261 5262 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD; 5263 SDValue N0 = N->getOperand(0); 5264 EVT VT = N->getValueType(0); 5265 EVT ExtVT = VT; 5266 5267 // This transformation isn't valid for vector loads. 5268 if (VT.isVector()) 5269 return SDValue(); 5270 5271 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then 5272 // extended to VT. 5273 if (Opc == ISD::SIGN_EXTEND_INREG) { 5274 ExtType = ISD::SEXTLOAD; 5275 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT(); 5276 } else if (Opc == ISD::SRL) { 5277 // Another special-case: SRL is basically zero-extending a narrower value. 5278 ExtType = ISD::ZEXTLOAD; 5279 N0 = SDValue(N, 0); 5280 ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 5281 if (!N01) return SDValue(); 5282 ExtVT = EVT::getIntegerVT(*DAG.getContext(), 5283 VT.getSizeInBits() - N01->getZExtValue()); 5284 } 5285 if (LegalOperations && !TLI.isLoadExtLegal(ExtType, ExtVT)) 5286 return SDValue(); 5287 5288 unsigned EVTBits = ExtVT.getSizeInBits(); 5289 5290 // Do not generate loads of non-round integer types since these can 5291 // be expensive (and would be wrong if the type is not byte sized). 5292 if (!ExtVT.isRound()) 5293 return SDValue(); 5294 5295 unsigned ShAmt = 0; 5296 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) { 5297 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 5298 ShAmt = N01->getZExtValue(); 5299 // Is the shift amount a multiple of size of VT? 5300 if ((ShAmt & (EVTBits-1)) == 0) { 5301 N0 = N0.getOperand(0); 5302 // Is the load width a multiple of size of VT? 5303 if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0) 5304 return SDValue(); 5305 } 5306 5307 // At this point, we must have a load or else we can't do the transform. 5308 if (!isa<LoadSDNode>(N0)) return SDValue(); 5309 5310 // Because a SRL must be assumed to *need* to zero-extend the high bits 5311 // (as opposed to anyext the high bits), we can't combine the zextload 5312 // lowering of SRL and an sextload. 5313 if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD) 5314 return SDValue(); 5315 5316 // If the shift amount is larger than the input type then we're not 5317 // accessing any of the loaded bytes. If the load was a zextload/extload 5318 // then the result of the shift+trunc is zero/undef (handled elsewhere). 5319 if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits()) 5320 return SDValue(); 5321 } 5322 } 5323 5324 // If the load is shifted left (and the result isn't shifted back right), 5325 // we can fold the truncate through the shift. 5326 unsigned ShLeftAmt = 0; 5327 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() && 5328 ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) { 5329 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 5330 ShLeftAmt = N01->getZExtValue(); 5331 N0 = N0.getOperand(0); 5332 } 5333 } 5334 5335 // If we haven't found a load, we can't narrow it. Don't transform one with 5336 // multiple uses, this would require adding a new load. 5337 if (!isa<LoadSDNode>(N0) || !N0.hasOneUse()) 5338 return SDValue(); 5339 5340 // Don't change the width of a volatile load. 5341 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 5342 if (LN0->isVolatile()) 5343 return SDValue(); 5344 5345 // Verify that we are actually reducing a load width here. 5346 if (LN0->getMemoryVT().getSizeInBits() < EVTBits) 5347 return SDValue(); 5348 5349 // For the transform to be legal, the load must produce only two values 5350 // (the value loaded and the chain). Don't transform a pre-increment 5351 // load, for example, which produces an extra value. Otherwise the 5352 // transformation is not equivalent, and the downstream logic to replace 5353 // uses gets things wrong. 5354 if (LN0->getNumValues() > 2) 5355 return SDValue(); 5356 5357 // If the load that we're shrinking is an extload and we're not just 5358 // discarding the extension we can't simply shrink the load. Bail. 5359 // TODO: It would be possible to merge the extensions in some cases. 5360 if (LN0->getExtensionType() != ISD::NON_EXTLOAD && 5361 LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt) 5362 return SDValue(); 5363 5364 EVT PtrType = N0.getOperand(1).getValueType(); 5365 5366 if (PtrType == MVT::Untyped || PtrType.isExtended()) 5367 // It's not possible to generate a constant of extended or untyped type. 5368 return SDValue(); 5369 5370 // For big endian targets, we need to adjust the offset to the pointer to 5371 // load the correct bytes. 5372 if (TLI.isBigEndian()) { 5373 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits(); 5374 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits(); 5375 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt; 5376 } 5377 5378 uint64_t PtrOff = ShAmt / 8; 5379 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff); 5380 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0), 5381 PtrType, LN0->getBasePtr(), 5382 DAG.getConstant(PtrOff, PtrType)); 5383 AddToWorkList(NewPtr.getNode()); 5384 5385 SDValue Load; 5386 if (ExtType == ISD::NON_EXTLOAD) 5387 Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr, 5388 LN0->getPointerInfo().getWithOffset(PtrOff), 5389 LN0->isVolatile(), LN0->isNonTemporal(), 5390 LN0->isInvariant(), NewAlign, LN0->getTBAAInfo()); 5391 else 5392 Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr, 5393 LN0->getPointerInfo().getWithOffset(PtrOff), 5394 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(), 5395 NewAlign, LN0->getTBAAInfo()); 5396 5397 // Replace the old load's chain with the new load's chain. 5398 WorkListRemover DeadNodes(*this); 5399 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1)); 5400 5401 // Shift the result left, if we've swallowed a left shift. 5402 SDValue Result = Load; 5403 if (ShLeftAmt != 0) { 5404 EVT ShImmTy = getShiftAmountTy(Result.getValueType()); 5405 if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt)) 5406 ShImmTy = VT; 5407 // If the shift amount is as large as the result size (but, presumably, 5408 // no larger than the source) then the useful bits of the result are 5409 // zero; we can't simply return the shortened shift, because the result 5410 // of that operation is undefined. 5411 if (ShLeftAmt >= VT.getSizeInBits()) 5412 Result = DAG.getConstant(0, VT); 5413 else 5414 Result = DAG.getNode(ISD::SHL, SDLoc(N0), VT, 5415 Result, DAG.getConstant(ShLeftAmt, ShImmTy)); 5416 } 5417 5418 // Return the new loaded value. 5419 return Result; 5420} 5421 5422SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) { 5423 SDValue N0 = N->getOperand(0); 5424 SDValue N1 = N->getOperand(1); 5425 EVT VT = N->getValueType(0); 5426 EVT EVT = cast<VTSDNode>(N1)->getVT(); 5427 unsigned VTBits = VT.getScalarType().getSizeInBits(); 5428 unsigned EVTBits = EVT.getScalarType().getSizeInBits(); 5429 5430 // fold (sext_in_reg c1) -> c1 5431 if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF) 5432 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1); 5433 5434 // If the input is already sign extended, just drop the extension. 5435 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1) 5436 return N0; 5437 5438 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2 5439 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG && 5440 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT())) 5441 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, 5442 N0.getOperand(0), N1); 5443 5444 // fold (sext_in_reg (sext x)) -> (sext x) 5445 // fold (sext_in_reg (aext x)) -> (sext x) 5446 // if x is small enough. 5447 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) { 5448 SDValue N00 = N0.getOperand(0); 5449 if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits && 5450 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT))) 5451 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1); 5452 } 5453 5454 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero. 5455 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits))) 5456 return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT); 5457 5458 // fold operands of sext_in_reg based on knowledge that the top bits are not 5459 // demanded. 5460 if (SimplifyDemandedBits(SDValue(N, 0))) 5461 return SDValue(N, 0); 5462 5463 // fold (sext_in_reg (load x)) -> (smaller sextload x) 5464 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits)) 5465 SDValue NarrowLoad = ReduceLoadWidth(N); 5466 if (NarrowLoad.getNode()) 5467 return NarrowLoad; 5468 5469 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24) 5470 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible. 5471 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above. 5472 if (N0.getOpcode() == ISD::SRL) { 5473 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1))) 5474 if (ShAmt->getZExtValue()+EVTBits <= VTBits) { 5475 // We can turn this into an SRA iff the input to the SRL is already sign 5476 // extended enough. 5477 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0)); 5478 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits) 5479 return DAG.getNode(ISD::SRA, SDLoc(N), VT, 5480 N0.getOperand(0), N0.getOperand(1)); 5481 } 5482 } 5483 5484 // fold (sext_inreg (extload x)) -> (sextload x) 5485 if (ISD::isEXTLoad(N0.getNode()) && 5486 ISD::isUNINDEXEDLoad(N0.getNode()) && 5487 EVT == cast<LoadSDNode>(N0)->getMemoryVT() && 5488 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) || 5489 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) { 5490 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 5491 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT, 5492 LN0->getChain(), 5493 LN0->getBasePtr(), EVT, 5494 LN0->getMemOperand()); 5495 CombineTo(N, ExtLoad); 5496 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 5497 AddToWorkList(ExtLoad.getNode()); 5498 return SDValue(N, 0); // Return N so it doesn't get rechecked! 5499 } 5500 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use 5501 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 5502 N0.hasOneUse() && 5503 EVT == cast<LoadSDNode>(N0)->getMemoryVT() && 5504 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) || 5505 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) { 5506 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 5507 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT, 5508 LN0->getChain(), 5509 LN0->getBasePtr(), EVT, 5510 LN0->getMemOperand()); 5511 CombineTo(N, ExtLoad); 5512 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 5513 return SDValue(N, 0); // Return N so it doesn't get rechecked! 5514 } 5515 5516 // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16)) 5517 if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) { 5518 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0), 5519 N0.getOperand(1), false); 5520 if (BSwap.getNode() != 0) 5521 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, 5522 BSwap, N1); 5523 } 5524 5525 return SDValue(); 5526} 5527 5528SDValue DAGCombiner::visitTRUNCATE(SDNode *N) { 5529 SDValue N0 = N->getOperand(0); 5530 EVT VT = N->getValueType(0); 5531 bool isLE = TLI.isLittleEndian(); 5532 5533 // noop truncate 5534 if (N0.getValueType() == N->getValueType(0)) 5535 return N0; 5536 // fold (truncate c1) -> c1 5537 if (isa<ConstantSDNode>(N0)) 5538 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0); 5539 // fold (truncate (truncate x)) -> (truncate x) 5540 if (N0.getOpcode() == ISD::TRUNCATE) 5541 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0)); 5542 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x 5543 if (N0.getOpcode() == ISD::ZERO_EXTEND || 5544 N0.getOpcode() == ISD::SIGN_EXTEND || 5545 N0.getOpcode() == ISD::ANY_EXTEND) { 5546 if (N0.getOperand(0).getValueType().bitsLT(VT)) 5547 // if the source is smaller than the dest, we still need an extend 5548 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, 5549 N0.getOperand(0)); 5550 if (N0.getOperand(0).getValueType().bitsGT(VT)) 5551 // if the source is larger than the dest, than we just need the truncate 5552 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0)); 5553 // if the source and dest are the same type, we can drop both the extend 5554 // and the truncate. 5555 return N0.getOperand(0); 5556 } 5557 5558 // Fold extract-and-trunc into a narrow extract. For example: 5559 // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1) 5560 // i32 y = TRUNCATE(i64 x) 5561 // -- becomes -- 5562 // v16i8 b = BITCAST (v2i64 val) 5563 // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8) 5564 // 5565 // Note: We only run this optimization after type legalization (which often 5566 // creates this pattern) and before operation legalization after which 5567 // we need to be more careful about the vector instructions that we generate. 5568 if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT && 5569 LegalTypes && !LegalOperations && N0->hasOneUse()) { 5570 5571 EVT VecTy = N0.getOperand(0).getValueType(); 5572 EVT ExTy = N0.getValueType(); 5573 EVT TrTy = N->getValueType(0); 5574 5575 unsigned NumElem = VecTy.getVectorNumElements(); 5576 unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits(); 5577 5578 EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem); 5579 assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size"); 5580 5581 SDValue EltNo = N0->getOperand(1); 5582 if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) { 5583 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue(); 5584 EVT IndexTy = TLI.getVectorIdxTy(); 5585 int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1)); 5586 5587 SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N), 5588 NVT, N0.getOperand(0)); 5589 5590 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, 5591 SDLoc(N), TrTy, V, 5592 DAG.getConstant(Index, IndexTy)); 5593 } 5594 } 5595 5596 // Fold a series of buildvector, bitcast, and truncate if possible. 5597 // For example fold 5598 // (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to 5599 // (2xi32 (buildvector x, y)). 5600 if (Level == AfterLegalizeVectorOps && VT.isVector() && 5601 N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() && 5602 N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR && 5603 N0.getOperand(0).hasOneUse()) { 5604 5605 SDValue BuildVect = N0.getOperand(0); 5606 EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType(); 5607 EVT TruncVecEltTy = VT.getVectorElementType(); 5608 5609 // Check that the element types match. 5610 if (BuildVectEltTy == TruncVecEltTy) { 5611 // Now we only need to compute the offset of the truncated elements. 5612 unsigned BuildVecNumElts = BuildVect.getNumOperands(); 5613 unsigned TruncVecNumElts = VT.getVectorNumElements(); 5614 unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts; 5615 5616 assert((BuildVecNumElts % TruncVecNumElts) == 0 && 5617 "Invalid number of elements"); 5618 5619 SmallVector<SDValue, 8> Opnds; 5620 for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset) 5621 Opnds.push_back(BuildVect.getOperand(i)); 5622 5623 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, &Opnds[0], 5624 Opnds.size()); 5625 } 5626 } 5627 5628 // See if we can simplify the input to this truncate through knowledge that 5629 // only the low bits are being used. 5630 // For example "trunc (or (shl x, 8), y)" // -> trunc y 5631 // Currently we only perform this optimization on scalars because vectors 5632 // may have different active low bits. 5633 if (!VT.isVector()) { 5634 SDValue Shorter = 5635 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(), 5636 VT.getSizeInBits())); 5637 if (Shorter.getNode()) 5638 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter); 5639 } 5640 // fold (truncate (load x)) -> (smaller load x) 5641 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits)) 5642 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) { 5643 SDValue Reduced = ReduceLoadWidth(N); 5644 if (Reduced.getNode()) 5645 return Reduced; 5646 } 5647 // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)), 5648 // where ... are all 'undef'. 5649 if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) { 5650 SmallVector<EVT, 8> VTs; 5651 SDValue V; 5652 unsigned Idx = 0; 5653 unsigned NumDefs = 0; 5654 5655 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) { 5656 SDValue X = N0.getOperand(i); 5657 if (X.getOpcode() != ISD::UNDEF) { 5658 V = X; 5659 Idx = i; 5660 NumDefs++; 5661 } 5662 // Stop if more than one members are non-undef. 5663 if (NumDefs > 1) 5664 break; 5665 VTs.push_back(EVT::getVectorVT(*DAG.getContext(), 5666 VT.getVectorElementType(), 5667 X.getValueType().getVectorNumElements())); 5668 } 5669 5670 if (NumDefs == 0) 5671 return DAG.getUNDEF(VT); 5672 5673 if (NumDefs == 1) { 5674 assert(V.getNode() && "The single defined operand is empty!"); 5675 SmallVector<SDValue, 8> Opnds; 5676 for (unsigned i = 0, e = VTs.size(); i != e; ++i) { 5677 if (i != Idx) { 5678 Opnds.push_back(DAG.getUNDEF(VTs[i])); 5679 continue; 5680 } 5681 SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V); 5682 AddToWorkList(NV.getNode()); 5683 Opnds.push_back(NV); 5684 } 5685 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, 5686 &Opnds[0], Opnds.size()); 5687 } 5688 } 5689 5690 // Simplify the operands using demanded-bits information. 5691 if (!VT.isVector() && 5692 SimplifyDemandedBits(SDValue(N, 0))) 5693 return SDValue(N, 0); 5694 5695 return SDValue(); 5696} 5697 5698static SDNode *getBuildPairElt(SDNode *N, unsigned i) { 5699 SDValue Elt = N->getOperand(i); 5700 if (Elt.getOpcode() != ISD::MERGE_VALUES) 5701 return Elt.getNode(); 5702 return Elt.getOperand(Elt.getResNo()).getNode(); 5703} 5704 5705/// CombineConsecutiveLoads - build_pair (load, load) -> load 5706/// if load locations are consecutive. 5707SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) { 5708 assert(N->getOpcode() == ISD::BUILD_PAIR); 5709 5710 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0)); 5711 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1)); 5712 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() || 5713 LD1->getPointerInfo().getAddrSpace() != 5714 LD2->getPointerInfo().getAddrSpace()) 5715 return SDValue(); 5716 EVT LD1VT = LD1->getValueType(0); 5717 5718 if (ISD::isNON_EXTLoad(LD2) && 5719 LD2->hasOneUse() && 5720 // If both are volatile this would reduce the number of volatile loads. 5721 // If one is volatile it might be ok, but play conservative and bail out. 5722 !LD1->isVolatile() && 5723 !LD2->isVolatile() && 5724 DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) { 5725 unsigned Align = LD1->getAlignment(); 5726 unsigned NewAlign = TLI.getDataLayout()-> 5727 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext())); 5728 5729 if (NewAlign <= Align && 5730 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT))) 5731 return DAG.getLoad(VT, SDLoc(N), LD1->getChain(), 5732 LD1->getBasePtr(), LD1->getPointerInfo(), 5733 false, false, false, Align); 5734 } 5735 5736 return SDValue(); 5737} 5738 5739SDValue DAGCombiner::visitBITCAST(SDNode *N) { 5740 SDValue N0 = N->getOperand(0); 5741 EVT VT = N->getValueType(0); 5742 5743 // If the input is a BUILD_VECTOR with all constant elements, fold this now. 5744 // Only do this before legalize, since afterward the target may be depending 5745 // on the bitconvert. 5746 // First check to see if this is all constant. 5747 if (!LegalTypes && 5748 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() && 5749 VT.isVector()) { 5750 bool isSimple = true; 5751 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) 5752 if (N0.getOperand(i).getOpcode() != ISD::UNDEF && 5753 N0.getOperand(i).getOpcode() != ISD::Constant && 5754 N0.getOperand(i).getOpcode() != ISD::ConstantFP) { 5755 isSimple = false; 5756 break; 5757 } 5758 5759 EVT DestEltVT = N->getValueType(0).getVectorElementType(); 5760 assert(!DestEltVT.isVector() && 5761 "Element type of vector ValueType must not be vector!"); 5762 if (isSimple) 5763 return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT); 5764 } 5765 5766 // If the input is a constant, let getNode fold it. 5767 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) { 5768 SDValue Res = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0); 5769 if (Res.getNode() != N) { 5770 if (!LegalOperations || 5771 TLI.isOperationLegal(Res.getNode()->getOpcode(), VT)) 5772 return Res; 5773 5774 // Folding it resulted in an illegal node, and it's too late to 5775 // do that. Clean up the old node and forego the transformation. 5776 // Ideally this won't happen very often, because instcombine 5777 // and the earlier dagcombine runs (where illegal nodes are 5778 // permitted) should have folded most of them already. 5779 DAG.DeleteNode(Res.getNode()); 5780 } 5781 } 5782 5783 // (conv (conv x, t1), t2) -> (conv x, t2) 5784 if (N0.getOpcode() == ISD::BITCAST) 5785 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, 5786 N0.getOperand(0)); 5787 5788 // fold (conv (load x)) -> (load (conv*)x) 5789 // If the resultant load doesn't need a higher alignment than the original! 5790 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() && 5791 // Do not change the width of a volatile load. 5792 !cast<LoadSDNode>(N0)->isVolatile() && 5793 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) && 5794 TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) { 5795 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 5796 unsigned Align = TLI.getDataLayout()-> 5797 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext())); 5798 unsigned OrigAlign = LN0->getAlignment(); 5799 5800 if (Align <= OrigAlign) { 5801 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(), 5802 LN0->getBasePtr(), LN0->getPointerInfo(), 5803 LN0->isVolatile(), LN0->isNonTemporal(), 5804 LN0->isInvariant(), OrigAlign, 5805 LN0->getTBAAInfo()); 5806 AddToWorkList(N); 5807 CombineTo(N0.getNode(), 5808 DAG.getNode(ISD::BITCAST, SDLoc(N0), 5809 N0.getValueType(), Load), 5810 Load.getValue(1)); 5811 return Load; 5812 } 5813 } 5814 5815 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit) 5816 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit)) 5817 // This often reduces constant pool loads. 5818 if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) || 5819 (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) && 5820 N0.getNode()->hasOneUse() && VT.isInteger() && 5821 !VT.isVector() && !N0.getValueType().isVector()) { 5822 SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT, 5823 N0.getOperand(0)); 5824 AddToWorkList(NewConv.getNode()); 5825 5826 APInt SignBit = APInt::getSignBit(VT.getSizeInBits()); 5827 if (N0.getOpcode() == ISD::FNEG) 5828 return DAG.getNode(ISD::XOR, SDLoc(N), VT, 5829 NewConv, DAG.getConstant(SignBit, VT)); 5830 assert(N0.getOpcode() == ISD::FABS); 5831 return DAG.getNode(ISD::AND, SDLoc(N), VT, 5832 NewConv, DAG.getConstant(~SignBit, VT)); 5833 } 5834 5835 // fold (bitconvert (fcopysign cst, x)) -> 5836 // (or (and (bitconvert x), sign), (and cst, (not sign))) 5837 // Note that we don't handle (copysign x, cst) because this can always be 5838 // folded to an fneg or fabs. 5839 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() && 5840 isa<ConstantFPSDNode>(N0.getOperand(0)) && 5841 VT.isInteger() && !VT.isVector()) { 5842 unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits(); 5843 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth); 5844 if (isTypeLegal(IntXVT)) { 5845 SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0), 5846 IntXVT, N0.getOperand(1)); 5847 AddToWorkList(X.getNode()); 5848 5849 // If X has a different width than the result/lhs, sext it or truncate it. 5850 unsigned VTWidth = VT.getSizeInBits(); 5851 if (OrigXWidth < VTWidth) { 5852 X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X); 5853 AddToWorkList(X.getNode()); 5854 } else if (OrigXWidth > VTWidth) { 5855 // To get the sign bit in the right place, we have to shift it right 5856 // before truncating. 5857 X = DAG.getNode(ISD::SRL, SDLoc(X), 5858 X.getValueType(), X, 5859 DAG.getConstant(OrigXWidth-VTWidth, X.getValueType())); 5860 AddToWorkList(X.getNode()); 5861 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X); 5862 AddToWorkList(X.getNode()); 5863 } 5864 5865 APInt SignBit = APInt::getSignBit(VT.getSizeInBits()); 5866 X = DAG.getNode(ISD::AND, SDLoc(X), VT, 5867 X, DAG.getConstant(SignBit, VT)); 5868 AddToWorkList(X.getNode()); 5869 5870 SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0), 5871 VT, N0.getOperand(0)); 5872 Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT, 5873 Cst, DAG.getConstant(~SignBit, VT)); 5874 AddToWorkList(Cst.getNode()); 5875 5876 return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst); 5877 } 5878 } 5879 5880 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive. 5881 if (N0.getOpcode() == ISD::BUILD_PAIR) { 5882 SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT); 5883 if (CombineLD.getNode()) 5884 return CombineLD; 5885 } 5886 5887 return SDValue(); 5888} 5889 5890SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) { 5891 EVT VT = N->getValueType(0); 5892 return CombineConsecutiveLoads(N, VT); 5893} 5894 5895/// ConstantFoldBITCASTofBUILD_VECTOR - We know that BV is a build_vector 5896/// node with Constant, ConstantFP or Undef operands. DstEltVT indicates the 5897/// destination element value type. 5898SDValue DAGCombiner:: 5899ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) { 5900 EVT SrcEltVT = BV->getValueType(0).getVectorElementType(); 5901 5902 // If this is already the right type, we're done. 5903 if (SrcEltVT == DstEltVT) return SDValue(BV, 0); 5904 5905 unsigned SrcBitSize = SrcEltVT.getSizeInBits(); 5906 unsigned DstBitSize = DstEltVT.getSizeInBits(); 5907 5908 // If this is a conversion of N elements of one type to N elements of another 5909 // type, convert each element. This handles FP<->INT cases. 5910 if (SrcBitSize == DstBitSize) { 5911 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, 5912 BV->getValueType(0).getVectorNumElements()); 5913 5914 // Due to the FP element handling below calling this routine recursively, 5915 // we can end up with a scalar-to-vector node here. 5916 if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR) 5917 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT, 5918 DAG.getNode(ISD::BITCAST, SDLoc(BV), 5919 DstEltVT, BV->getOperand(0))); 5920 5921 SmallVector<SDValue, 8> Ops; 5922 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) { 5923 SDValue Op = BV->getOperand(i); 5924 // If the vector element type is not legal, the BUILD_VECTOR operands 5925 // are promoted and implicitly truncated. Make that explicit here. 5926 if (Op.getValueType() != SrcEltVT) 5927 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op); 5928 Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV), 5929 DstEltVT, Op)); 5930 AddToWorkList(Ops.back().getNode()); 5931 } 5932 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, 5933 &Ops[0], Ops.size()); 5934 } 5935 5936 // Otherwise, we're growing or shrinking the elements. To avoid having to 5937 // handle annoying details of growing/shrinking FP values, we convert them to 5938 // int first. 5939 if (SrcEltVT.isFloatingPoint()) { 5940 // Convert the input float vector to a int vector where the elements are the 5941 // same sizes. 5942 assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!"); 5943 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits()); 5944 BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode(); 5945 SrcEltVT = IntVT; 5946 } 5947 5948 // Now we know the input is an integer vector. If the output is a FP type, 5949 // convert to integer first, then to FP of the right size. 5950 if (DstEltVT.isFloatingPoint()) { 5951 assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!"); 5952 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits()); 5953 SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode(); 5954 5955 // Next, convert to FP elements of the same size. 5956 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT); 5957 } 5958 5959 // Okay, we know the src/dst types are both integers of differing types. 5960 // Handling growing first. 5961 assert(SrcEltVT.isInteger() && DstEltVT.isInteger()); 5962 if (SrcBitSize < DstBitSize) { 5963 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize; 5964 5965 SmallVector<SDValue, 8> Ops; 5966 for (unsigned i = 0, e = BV->getNumOperands(); i != e; 5967 i += NumInputsPerOutput) { 5968 bool isLE = TLI.isLittleEndian(); 5969 APInt NewBits = APInt(DstBitSize, 0); 5970 bool EltIsUndef = true; 5971 for (unsigned j = 0; j != NumInputsPerOutput; ++j) { 5972 // Shift the previously computed bits over. 5973 NewBits <<= SrcBitSize; 5974 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j)); 5975 if (Op.getOpcode() == ISD::UNDEF) continue; 5976 EltIsUndef = false; 5977 5978 NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue(). 5979 zextOrTrunc(SrcBitSize).zext(DstBitSize); 5980 } 5981 5982 if (EltIsUndef) 5983 Ops.push_back(DAG.getUNDEF(DstEltVT)); 5984 else 5985 Ops.push_back(DAG.getConstant(NewBits, DstEltVT)); 5986 } 5987 5988 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size()); 5989 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, 5990 &Ops[0], Ops.size()); 5991 } 5992 5993 // Finally, this must be the case where we are shrinking elements: each input 5994 // turns into multiple outputs. 5995 bool isS2V = ISD::isScalarToVector(BV); 5996 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize; 5997 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, 5998 NumOutputsPerInput*BV->getNumOperands()); 5999 SmallVector<SDValue, 8> Ops; 6000 6001 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) { 6002 if (BV->getOperand(i).getOpcode() == ISD::UNDEF) { 6003 for (unsigned j = 0; j != NumOutputsPerInput; ++j) 6004 Ops.push_back(DAG.getUNDEF(DstEltVT)); 6005 continue; 6006 } 6007 6008 APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))-> 6009 getAPIntValue().zextOrTrunc(SrcBitSize); 6010 6011 for (unsigned j = 0; j != NumOutputsPerInput; ++j) { 6012 APInt ThisVal = OpVal.trunc(DstBitSize); 6013 Ops.push_back(DAG.getConstant(ThisVal, DstEltVT)); 6014 if (isS2V && i == 0 && j == 0 && ThisVal.zext(SrcBitSize) == OpVal) 6015 // Simply turn this into a SCALAR_TO_VECTOR of the new type. 6016 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT, 6017 Ops[0]); 6018 OpVal = OpVal.lshr(DstBitSize); 6019 } 6020 6021 // For big endian targets, swap the order of the pieces of each element. 6022 if (TLI.isBigEndian()) 6023 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end()); 6024 } 6025 6026 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, 6027 &Ops[0], Ops.size()); 6028} 6029 6030SDValue DAGCombiner::visitFADD(SDNode *N) { 6031 SDValue N0 = N->getOperand(0); 6032 SDValue N1 = N->getOperand(1); 6033 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 6034 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 6035 EVT VT = N->getValueType(0); 6036 6037 // fold vector ops 6038 if (VT.isVector()) { 6039 SDValue FoldedVOp = SimplifyVBinOp(N); 6040 if (FoldedVOp.getNode()) return FoldedVOp; 6041 } 6042 6043 // fold (fadd c1, c2) -> c1 + c2 6044 if (N0CFP && N1CFP) 6045 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N1); 6046 // canonicalize constant to RHS 6047 if (N0CFP && !N1CFP) 6048 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N0); 6049 // fold (fadd A, 0) -> A 6050 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP && 6051 N1CFP->getValueAPF().isZero()) 6052 return N0; 6053 // fold (fadd A, (fneg B)) -> (fsub A, B) 6054 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) && 6055 isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options) == 2) 6056 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0, 6057 GetNegatedExpression(N1, DAG, LegalOperations)); 6058 // fold (fadd (fneg A), B) -> (fsub B, A) 6059 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) && 6060 isNegatibleForFree(N0, LegalOperations, TLI, &DAG.getTarget().Options) == 2) 6061 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N1, 6062 GetNegatedExpression(N0, DAG, LegalOperations)); 6063 6064 // If allowed, fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2)) 6065 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP && 6066 N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() && 6067 isa<ConstantFPSDNode>(N0.getOperand(1))) 6068 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0.getOperand(0), 6069 DAG.getNode(ISD::FADD, SDLoc(N), VT, 6070 N0.getOperand(1), N1)); 6071 6072 // No FP constant should be created after legalization as Instruction 6073 // Selection pass has hard time in dealing with FP constant. 6074 // 6075 // We don't need test this condition for transformation like following, as 6076 // the DAG being transformed implies it is legal to take FP constant as 6077 // operand. 6078 // 6079 // (fadd (fmul c, x), x) -> (fmul c+1, x) 6080 // 6081 bool AllowNewFpConst = (Level < AfterLegalizeDAG); 6082 6083 // If allow, fold (fadd (fneg x), x) -> 0.0 6084 if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath && 6085 N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1) 6086 return DAG.getConstantFP(0.0, VT); 6087 6088 // If allow, fold (fadd x, (fneg x)) -> 0.0 6089 if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath && 6090 N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0) 6091 return DAG.getConstantFP(0.0, VT); 6092 6093 // In unsafe math mode, we can fold chains of FADD's of the same value 6094 // into multiplications. This transform is not safe in general because 6095 // we are reducing the number of rounding steps. 6096 if (DAG.getTarget().Options.UnsafeFPMath && 6097 TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && 6098 !N0CFP && !N1CFP) { 6099 if (N0.getOpcode() == ISD::FMUL) { 6100 ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0)); 6101 ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1)); 6102 6103 // (fadd (fmul c, x), x) -> (fmul x, c+1) 6104 if (CFP00 && !CFP01 && N0.getOperand(1) == N1) { 6105 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT, 6106 SDValue(CFP00, 0), 6107 DAG.getConstantFP(1.0, VT)); 6108 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, 6109 N1, NewCFP); 6110 } 6111 6112 // (fadd (fmul x, c), x) -> (fmul x, c+1) 6113 if (CFP01 && !CFP00 && N0.getOperand(0) == N1) { 6114 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT, 6115 SDValue(CFP01, 0), 6116 DAG.getConstantFP(1.0, VT)); 6117 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, 6118 N1, NewCFP); 6119 } 6120 6121 // (fadd (fmul c, x), (fadd x, x)) -> (fmul x, c+2) 6122 if (CFP00 && !CFP01 && N1.getOpcode() == ISD::FADD && 6123 N1.getOperand(0) == N1.getOperand(1) && 6124 N0.getOperand(1) == N1.getOperand(0)) { 6125 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT, 6126 SDValue(CFP00, 0), 6127 DAG.getConstantFP(2.0, VT)); 6128 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, 6129 N0.getOperand(1), NewCFP); 6130 } 6131 6132 // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2) 6133 if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD && 6134 N1.getOperand(0) == N1.getOperand(1) && 6135 N0.getOperand(0) == N1.getOperand(0)) { 6136 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT, 6137 SDValue(CFP01, 0), 6138 DAG.getConstantFP(2.0, VT)); 6139 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, 6140 N0.getOperand(0), NewCFP); 6141 } 6142 } 6143 6144 if (N1.getOpcode() == ISD::FMUL) { 6145 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0)); 6146 ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1)); 6147 6148 // (fadd x, (fmul c, x)) -> (fmul x, c+1) 6149 if (CFP10 && !CFP11 && N1.getOperand(1) == N0) { 6150 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT, 6151 SDValue(CFP10, 0), 6152 DAG.getConstantFP(1.0, VT)); 6153 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, 6154 N0, NewCFP); 6155 } 6156 6157 // (fadd x, (fmul x, c)) -> (fmul x, c+1) 6158 if (CFP11 && !CFP10 && N1.getOperand(0) == N0) { 6159 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT, 6160 SDValue(CFP11, 0), 6161 DAG.getConstantFP(1.0, VT)); 6162 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, 6163 N0, NewCFP); 6164 } 6165 6166 6167 // (fadd (fadd x, x), (fmul c, x)) -> (fmul x, c+2) 6168 if (CFP10 && !CFP11 && N0.getOpcode() == ISD::FADD && 6169 N0.getOperand(0) == N0.getOperand(1) && 6170 N1.getOperand(1) == N0.getOperand(0)) { 6171 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT, 6172 SDValue(CFP10, 0), 6173 DAG.getConstantFP(2.0, VT)); 6174 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, 6175 N1.getOperand(1), NewCFP); 6176 } 6177 6178 // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2) 6179 if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD && 6180 N0.getOperand(0) == N0.getOperand(1) && 6181 N1.getOperand(0) == N0.getOperand(0)) { 6182 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT, 6183 SDValue(CFP11, 0), 6184 DAG.getConstantFP(2.0, VT)); 6185 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, 6186 N1.getOperand(0), NewCFP); 6187 } 6188 } 6189 6190 if (N0.getOpcode() == ISD::FADD && AllowNewFpConst) { 6191 ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0)); 6192 // (fadd (fadd x, x), x) -> (fmul x, 3.0) 6193 if (!CFP && N0.getOperand(0) == N0.getOperand(1) && 6194 (N0.getOperand(0) == N1)) 6195 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, 6196 N1, DAG.getConstantFP(3.0, VT)); 6197 } 6198 6199 if (N1.getOpcode() == ISD::FADD && AllowNewFpConst) { 6200 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0)); 6201 // (fadd x, (fadd x, x)) -> (fmul x, 3.0) 6202 if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) && 6203 N1.getOperand(0) == N0) 6204 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, 6205 N0, DAG.getConstantFP(3.0, VT)); 6206 } 6207 6208 // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0) 6209 if (AllowNewFpConst && 6210 N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD && 6211 N0.getOperand(0) == N0.getOperand(1) && 6212 N1.getOperand(0) == N1.getOperand(1) && 6213 N0.getOperand(0) == N1.getOperand(0)) 6214 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, 6215 N0.getOperand(0), 6216 DAG.getConstantFP(4.0, VT)); 6217 } 6218 6219 // FADD -> FMA combines: 6220 if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast || 6221 DAG.getTarget().Options.UnsafeFPMath) && 6222 DAG.getTarget().getTargetLowering()->isFMAFasterThanFMulAndFAdd(VT) && 6223 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) { 6224 6225 // fold (fadd (fmul x, y), z) -> (fma x, y, z) 6226 if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse()) 6227 return DAG.getNode(ISD::FMA, SDLoc(N), VT, 6228 N0.getOperand(0), N0.getOperand(1), N1); 6229 6230 // fold (fadd x, (fmul y, z)) -> (fma y, z, x) 6231 // Note: Commutes FADD operands. 6232 if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse()) 6233 return DAG.getNode(ISD::FMA, SDLoc(N), VT, 6234 N1.getOperand(0), N1.getOperand(1), N0); 6235 } 6236 6237 return SDValue(); 6238} 6239 6240SDValue DAGCombiner::visitFSUB(SDNode *N) { 6241 SDValue N0 = N->getOperand(0); 6242 SDValue N1 = N->getOperand(1); 6243 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 6244 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 6245 EVT VT = N->getValueType(0); 6246 SDLoc dl(N); 6247 6248 // fold vector ops 6249 if (VT.isVector()) { 6250 SDValue FoldedVOp = SimplifyVBinOp(N); 6251 if (FoldedVOp.getNode()) return FoldedVOp; 6252 } 6253 6254 // fold (fsub c1, c2) -> c1-c2 6255 if (N0CFP && N1CFP) 6256 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0, N1); 6257 // fold (fsub A, 0) -> A 6258 if (DAG.getTarget().Options.UnsafeFPMath && 6259 N1CFP && N1CFP->getValueAPF().isZero()) 6260 return N0; 6261 // fold (fsub 0, B) -> -B 6262 if (DAG.getTarget().Options.UnsafeFPMath && 6263 N0CFP && N0CFP->getValueAPF().isZero()) { 6264 if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options)) 6265 return GetNegatedExpression(N1, DAG, LegalOperations); 6266 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT)) 6267 return DAG.getNode(ISD::FNEG, dl, VT, N1); 6268 } 6269 // fold (fsub A, (fneg B)) -> (fadd A, B) 6270 if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options)) 6271 return DAG.getNode(ISD::FADD, dl, VT, N0, 6272 GetNegatedExpression(N1, DAG, LegalOperations)); 6273 6274 // If 'unsafe math' is enabled, fold 6275 // (fsub x, x) -> 0.0 & 6276 // (fsub x, (fadd x, y)) -> (fneg y) & 6277 // (fsub x, (fadd y, x)) -> (fneg y) 6278 if (DAG.getTarget().Options.UnsafeFPMath) { 6279 if (N0 == N1) 6280 return DAG.getConstantFP(0.0f, VT); 6281 6282 if (N1.getOpcode() == ISD::FADD) { 6283 SDValue N10 = N1->getOperand(0); 6284 SDValue N11 = N1->getOperand(1); 6285 6286 if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, 6287 &DAG.getTarget().Options)) 6288 return GetNegatedExpression(N11, DAG, LegalOperations); 6289 6290 if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, 6291 &DAG.getTarget().Options)) 6292 return GetNegatedExpression(N10, DAG, LegalOperations); 6293 } 6294 } 6295 6296 // FSUB -> FMA combines: 6297 if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast || 6298 DAG.getTarget().Options.UnsafeFPMath) && 6299 DAG.getTarget().getTargetLowering()->isFMAFasterThanFMulAndFAdd(VT) && 6300 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) { 6301 6302 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z)) 6303 if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse()) 6304 return DAG.getNode(ISD::FMA, dl, VT, 6305 N0.getOperand(0), N0.getOperand(1), 6306 DAG.getNode(ISD::FNEG, dl, VT, N1)); 6307 6308 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x) 6309 // Note: Commutes FSUB operands. 6310 if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse()) 6311 return DAG.getNode(ISD::FMA, dl, VT, 6312 DAG.getNode(ISD::FNEG, dl, VT, 6313 N1.getOperand(0)), 6314 N1.getOperand(1), N0); 6315 6316 // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z)) 6317 if (N0.getOpcode() == ISD::FNEG && 6318 N0.getOperand(0).getOpcode() == ISD::FMUL && 6319 N0->hasOneUse() && N0.getOperand(0).hasOneUse()) { 6320 SDValue N00 = N0.getOperand(0).getOperand(0); 6321 SDValue N01 = N0.getOperand(0).getOperand(1); 6322 return DAG.getNode(ISD::FMA, dl, VT, 6323 DAG.getNode(ISD::FNEG, dl, VT, N00), N01, 6324 DAG.getNode(ISD::FNEG, dl, VT, N1)); 6325 } 6326 } 6327 6328 return SDValue(); 6329} 6330 6331SDValue DAGCombiner::visitFMUL(SDNode *N) { 6332 SDValue N0 = N->getOperand(0); 6333 SDValue N1 = N->getOperand(1); 6334 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 6335 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 6336 EVT VT = N->getValueType(0); 6337 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6338 6339 // fold vector ops 6340 if (VT.isVector()) { 6341 SDValue FoldedVOp = SimplifyVBinOp(N); 6342 if (FoldedVOp.getNode()) return FoldedVOp; 6343 } 6344 6345 // fold (fmul c1, c2) -> c1*c2 6346 if (N0CFP && N1CFP) 6347 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, N1); 6348 // canonicalize constant to RHS 6349 if (N0CFP && !N1CFP) 6350 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, N0); 6351 // fold (fmul A, 0) -> 0 6352 if (DAG.getTarget().Options.UnsafeFPMath && 6353 N1CFP && N1CFP->getValueAPF().isZero()) 6354 return N1; 6355 // fold (fmul A, 0) -> 0, vector edition. 6356 if (DAG.getTarget().Options.UnsafeFPMath && 6357 ISD::isBuildVectorAllZeros(N1.getNode())) 6358 return N1; 6359 // fold (fmul A, 1.0) -> A 6360 if (N1CFP && N1CFP->isExactlyValue(1.0)) 6361 return N0; 6362 // fold (fmul X, 2.0) -> (fadd X, X) 6363 if (N1CFP && N1CFP->isExactlyValue(+2.0)) 6364 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N0); 6365 // fold (fmul X, -1.0) -> (fneg X) 6366 if (N1CFP && N1CFP->isExactlyValue(-1.0)) 6367 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT)) 6368 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0); 6369 6370 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y) 6371 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, 6372 &DAG.getTarget().Options)) { 6373 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, 6374 &DAG.getTarget().Options)) { 6375 // Both can be negated for free, check to see if at least one is cheaper 6376 // negated. 6377 if (LHSNeg == 2 || RHSNeg == 2) 6378 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, 6379 GetNegatedExpression(N0, DAG, LegalOperations), 6380 GetNegatedExpression(N1, DAG, LegalOperations)); 6381 } 6382 } 6383 6384 // If allowed, fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2)) 6385 if (DAG.getTarget().Options.UnsafeFPMath && 6386 N1CFP && N0.getOpcode() == ISD::FMUL && 6387 N0.getNode()->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1))) 6388 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0), 6389 DAG.getNode(ISD::FMUL, SDLoc(N), VT, 6390 N0.getOperand(1), N1)); 6391 6392 return SDValue(); 6393} 6394 6395SDValue DAGCombiner::visitFMA(SDNode *N) { 6396 SDValue N0 = N->getOperand(0); 6397 SDValue N1 = N->getOperand(1); 6398 SDValue N2 = N->getOperand(2); 6399 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 6400 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 6401 EVT VT = N->getValueType(0); 6402 SDLoc dl(N); 6403 6404 if (DAG.getTarget().Options.UnsafeFPMath) { 6405 if (N0CFP && N0CFP->isZero()) 6406 return N2; 6407 if (N1CFP && N1CFP->isZero()) 6408 return N2; 6409 } 6410 if (N0CFP && N0CFP->isExactlyValue(1.0)) 6411 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2); 6412 if (N1CFP && N1CFP->isExactlyValue(1.0)) 6413 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2); 6414 6415 // Canonicalize (fma c, x, y) -> (fma x, c, y) 6416 if (N0CFP && !N1CFP) 6417 return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2); 6418 6419 // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2) 6420 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP && 6421 N2.getOpcode() == ISD::FMUL && 6422 N0 == N2.getOperand(0) && 6423 N2.getOperand(1).getOpcode() == ISD::ConstantFP) { 6424 return DAG.getNode(ISD::FMUL, dl, VT, N0, 6425 DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1))); 6426 } 6427 6428 6429 // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y) 6430 if (DAG.getTarget().Options.UnsafeFPMath && 6431 N0.getOpcode() == ISD::FMUL && N1CFP && 6432 N0.getOperand(1).getOpcode() == ISD::ConstantFP) { 6433 return DAG.getNode(ISD::FMA, dl, VT, 6434 N0.getOperand(0), 6435 DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)), 6436 N2); 6437 } 6438 6439 // (fma x, 1, y) -> (fadd x, y) 6440 // (fma x, -1, y) -> (fadd (fneg x), y) 6441 if (N1CFP) { 6442 if (N1CFP->isExactlyValue(1.0)) 6443 return DAG.getNode(ISD::FADD, dl, VT, N0, N2); 6444 6445 if (N1CFP->isExactlyValue(-1.0) && 6446 (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) { 6447 SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0); 6448 AddToWorkList(RHSNeg.getNode()); 6449 return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg); 6450 } 6451 } 6452 6453 // (fma x, c, x) -> (fmul x, (c+1)) 6454 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP && N0 == N2) 6455 return DAG.getNode(ISD::FMUL, dl, VT, N0, 6456 DAG.getNode(ISD::FADD, dl, VT, 6457 N1, DAG.getConstantFP(1.0, VT))); 6458 6459 // (fma x, c, (fneg x)) -> (fmul x, (c-1)) 6460 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP && 6461 N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0) 6462 return DAG.getNode(ISD::FMUL, dl, VT, N0, 6463 DAG.getNode(ISD::FADD, dl, VT, 6464 N1, DAG.getConstantFP(-1.0, VT))); 6465 6466 6467 return SDValue(); 6468} 6469 6470SDValue DAGCombiner::visitFDIV(SDNode *N) { 6471 SDValue N0 = N->getOperand(0); 6472 SDValue N1 = N->getOperand(1); 6473 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 6474 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 6475 EVT VT = N->getValueType(0); 6476 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6477 6478 // fold vector ops 6479 if (VT.isVector()) { 6480 SDValue FoldedVOp = SimplifyVBinOp(N); 6481 if (FoldedVOp.getNode()) return FoldedVOp; 6482 } 6483 6484 // fold (fdiv c1, c2) -> c1/c2 6485 if (N0CFP && N1CFP) 6486 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1); 6487 6488 // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable. 6489 if (N1CFP && DAG.getTarget().Options.UnsafeFPMath) { 6490 // Compute the reciprocal 1.0 / c2. 6491 APFloat N1APF = N1CFP->getValueAPF(); 6492 APFloat Recip(N1APF.getSemantics(), 1); // 1.0 6493 APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven); 6494 // Only do the transform if the reciprocal is a legal fp immediate that 6495 // isn't too nasty (eg NaN, denormal, ...). 6496 if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty 6497 (!LegalOperations || 6498 // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM 6499 // backend)... we should handle this gracefully after Legalize. 6500 // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) || 6501 TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) || 6502 TLI.isFPImmLegal(Recip, VT))) 6503 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, 6504 DAG.getConstantFP(Recip, VT)); 6505 } 6506 6507 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y) 6508 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, 6509 &DAG.getTarget().Options)) { 6510 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, 6511 &DAG.getTarget().Options)) { 6512 // Both can be negated for free, check to see if at least one is cheaper 6513 // negated. 6514 if (LHSNeg == 2 || RHSNeg == 2) 6515 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, 6516 GetNegatedExpression(N0, DAG, LegalOperations), 6517 GetNegatedExpression(N1, DAG, LegalOperations)); 6518 } 6519 } 6520 6521 return SDValue(); 6522} 6523 6524SDValue DAGCombiner::visitFREM(SDNode *N) { 6525 SDValue N0 = N->getOperand(0); 6526 SDValue N1 = N->getOperand(1); 6527 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 6528 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 6529 EVT VT = N->getValueType(0); 6530 6531 // fold (frem c1, c2) -> fmod(c1,c2) 6532 if (N0CFP && N1CFP) 6533 return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1); 6534 6535 return SDValue(); 6536} 6537 6538SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) { 6539 SDValue N0 = N->getOperand(0); 6540 SDValue N1 = N->getOperand(1); 6541 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 6542 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 6543 EVT VT = N->getValueType(0); 6544 6545 if (N0CFP && N1CFP) // Constant fold 6546 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1); 6547 6548 if (N1CFP) { 6549 const APFloat& V = N1CFP->getValueAPF(); 6550 // copysign(x, c1) -> fabs(x) iff ispos(c1) 6551 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1) 6552 if (!V.isNegative()) { 6553 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT)) 6554 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0); 6555 } else { 6556 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT)) 6557 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, 6558 DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0)); 6559 } 6560 } 6561 6562 // copysign(fabs(x), y) -> copysign(x, y) 6563 // copysign(fneg(x), y) -> copysign(x, y) 6564 // copysign(copysign(x,z), y) -> copysign(x, y) 6565 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG || 6566 N0.getOpcode() == ISD::FCOPYSIGN) 6567 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, 6568 N0.getOperand(0), N1); 6569 6570 // copysign(x, abs(y)) -> abs(x) 6571 if (N1.getOpcode() == ISD::FABS) 6572 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0); 6573 6574 // copysign(x, copysign(y,z)) -> copysign(x, z) 6575 if (N1.getOpcode() == ISD::FCOPYSIGN) 6576 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, 6577 N0, N1.getOperand(1)); 6578 6579 // copysign(x, fp_extend(y)) -> copysign(x, y) 6580 // copysign(x, fp_round(y)) -> copysign(x, y) 6581 if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND) 6582 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, 6583 N0, N1.getOperand(0)); 6584 6585 return SDValue(); 6586} 6587 6588SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) { 6589 SDValue N0 = N->getOperand(0); 6590 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 6591 EVT VT = N->getValueType(0); 6592 EVT OpVT = N0.getValueType(); 6593 6594 // fold (sint_to_fp c1) -> c1fp 6595 if (N0C && 6596 // ...but only if the target supports immediate floating-point values 6597 (!LegalOperations || 6598 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) 6599 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0); 6600 6601 // If the input is a legal type, and SINT_TO_FP is not legal on this target, 6602 // but UINT_TO_FP is legal on this target, try to convert. 6603 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) && 6604 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) { 6605 // If the sign bit is known to be zero, we can change this to UINT_TO_FP. 6606 if (DAG.SignBitIsZero(N0)) 6607 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0); 6608 } 6609 6610 // The next optimizations are desireable only if SELECT_CC can be lowered. 6611 // Check against MVT::Other for SELECT_CC, which is a workaround for targets 6612 // having to say they don't support SELECT_CC on every type the DAG knows 6613 // about, since there is no way to mark an opcode illegal at all value types 6614 // (See also visitSELECT) 6615 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other)) { 6616 // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc) 6617 if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 && 6618 !VT.isVector() && 6619 (!LegalOperations || 6620 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) { 6621 SDValue Ops[] = 6622 { N0.getOperand(0), N0.getOperand(1), 6623 DAG.getConstantFP(-1.0, VT) , DAG.getConstantFP(0.0, VT), 6624 N0.getOperand(2) }; 6625 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops, 5); 6626 } 6627 6628 // fold (sint_to_fp (zext (setcc x, y, cc))) -> 6629 // (select_cc x, y, 1.0, 0.0,, cc) 6630 if (N0.getOpcode() == ISD::ZERO_EXTEND && 6631 N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() && 6632 (!LegalOperations || 6633 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) { 6634 SDValue Ops[] = 6635 { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1), 6636 DAG.getConstantFP(1.0, VT) , DAG.getConstantFP(0.0, VT), 6637 N0.getOperand(0).getOperand(2) }; 6638 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops, 5); 6639 } 6640 } 6641 6642 return SDValue(); 6643} 6644 6645SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) { 6646 SDValue N0 = N->getOperand(0); 6647 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 6648 EVT VT = N->getValueType(0); 6649 EVT OpVT = N0.getValueType(); 6650 6651 // fold (uint_to_fp c1) -> c1fp 6652 if (N0C && 6653 // ...but only if the target supports immediate floating-point values 6654 (!LegalOperations || 6655 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) 6656 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0); 6657 6658 // If the input is a legal type, and UINT_TO_FP is not legal on this target, 6659 // but SINT_TO_FP is legal on this target, try to convert. 6660 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) && 6661 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) { 6662 // If the sign bit is known to be zero, we can change this to SINT_TO_FP. 6663 if (DAG.SignBitIsZero(N0)) 6664 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0); 6665 } 6666 6667 // The next optimizations are desireable only if SELECT_CC can be lowered. 6668 // Check against MVT::Other for SELECT_CC, which is a workaround for targets 6669 // having to say they don't support SELECT_CC on every type the DAG knows 6670 // about, since there is no way to mark an opcode illegal at all value types 6671 // (See also visitSELECT) 6672 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other)) { 6673 // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc) 6674 6675 if (N0.getOpcode() == ISD::SETCC && !VT.isVector() && 6676 (!LegalOperations || 6677 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) { 6678 SDValue Ops[] = 6679 { N0.getOperand(0), N0.getOperand(1), 6680 DAG.getConstantFP(1.0, VT), DAG.getConstantFP(0.0, VT), 6681 N0.getOperand(2) }; 6682 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops, 5); 6683 } 6684 } 6685 6686 return SDValue(); 6687} 6688 6689SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) { 6690 SDValue N0 = N->getOperand(0); 6691 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 6692 EVT VT = N->getValueType(0); 6693 6694 // fold (fp_to_sint c1fp) -> c1 6695 if (N0CFP) 6696 return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0); 6697 6698 return SDValue(); 6699} 6700 6701SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) { 6702 SDValue N0 = N->getOperand(0); 6703 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 6704 EVT VT = N->getValueType(0); 6705 6706 // fold (fp_to_uint c1fp) -> c1 6707 if (N0CFP) 6708 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0); 6709 6710 return SDValue(); 6711} 6712 6713SDValue DAGCombiner::visitFP_ROUND(SDNode *N) { 6714 SDValue N0 = N->getOperand(0); 6715 SDValue N1 = N->getOperand(1); 6716 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 6717 EVT VT = N->getValueType(0); 6718 6719 // fold (fp_round c1fp) -> c1fp 6720 if (N0CFP) 6721 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1); 6722 6723 // fold (fp_round (fp_extend x)) -> x 6724 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType()) 6725 return N0.getOperand(0); 6726 6727 // fold (fp_round (fp_round x)) -> (fp_round x) 6728 if (N0.getOpcode() == ISD::FP_ROUND) { 6729 // This is a value preserving truncation if both round's are. 6730 bool IsTrunc = N->getConstantOperandVal(1) == 1 && 6731 N0.getNode()->getConstantOperandVal(1) == 1; 6732 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0.getOperand(0), 6733 DAG.getIntPtrConstant(IsTrunc)); 6734 } 6735 6736 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y) 6737 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) { 6738 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT, 6739 N0.getOperand(0), N1); 6740 AddToWorkList(Tmp.getNode()); 6741 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, 6742 Tmp, N0.getOperand(1)); 6743 } 6744 6745 return SDValue(); 6746} 6747 6748SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) { 6749 SDValue N0 = N->getOperand(0); 6750 EVT VT = N->getValueType(0); 6751 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT(); 6752 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 6753 6754 // fold (fp_round_inreg c1fp) -> c1fp 6755 if (N0CFP && isTypeLegal(EVT)) { 6756 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT); 6757 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, Round); 6758 } 6759 6760 return SDValue(); 6761} 6762 6763SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) { 6764 SDValue N0 = N->getOperand(0); 6765 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 6766 EVT VT = N->getValueType(0); 6767 6768 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded. 6769 if (N->hasOneUse() && 6770 N->use_begin()->getOpcode() == ISD::FP_ROUND) 6771 return SDValue(); 6772 6773 // fold (fp_extend c1fp) -> c1fp 6774 if (N0CFP) 6775 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0); 6776 6777 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the 6778 // value of X. 6779 if (N0.getOpcode() == ISD::FP_ROUND 6780 && N0.getNode()->getConstantOperandVal(1) == 1) { 6781 SDValue In = N0.getOperand(0); 6782 if (In.getValueType() == VT) return In; 6783 if (VT.bitsLT(In.getValueType())) 6784 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, 6785 In, N0.getOperand(1)); 6786 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In); 6787 } 6788 6789 // fold (fpext (load x)) -> (fpext (fptrunc (extload x))) 6790 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() && 6791 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) || 6792 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) { 6793 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6794 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT, 6795 LN0->getChain(), 6796 LN0->getBasePtr(), N0.getValueType(), 6797 LN0->getMemOperand()); 6798 CombineTo(N, ExtLoad); 6799 CombineTo(N0.getNode(), 6800 DAG.getNode(ISD::FP_ROUND, SDLoc(N0), 6801 N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)), 6802 ExtLoad.getValue(1)); 6803 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6804 } 6805 6806 return SDValue(); 6807} 6808 6809SDValue DAGCombiner::visitFNEG(SDNode *N) { 6810 SDValue N0 = N->getOperand(0); 6811 EVT VT = N->getValueType(0); 6812 6813 if (VT.isVector()) { 6814 SDValue FoldedVOp = SimplifyVUnaryOp(N); 6815 if (FoldedVOp.getNode()) return FoldedVOp; 6816 } 6817 6818 if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(), 6819 &DAG.getTarget().Options)) 6820 return GetNegatedExpression(N0, DAG, LegalOperations); 6821 6822 // Transform fneg(bitconvert(x)) -> bitconvert(x^sign) to avoid loading 6823 // constant pool values. 6824 if (!TLI.isFNegFree(VT) && N0.getOpcode() == ISD::BITCAST && 6825 !VT.isVector() && 6826 N0.getNode()->hasOneUse() && 6827 N0.getOperand(0).getValueType().isInteger()) { 6828 SDValue Int = N0.getOperand(0); 6829 EVT IntVT = Int.getValueType(); 6830 if (IntVT.isInteger() && !IntVT.isVector()) { 6831 Int = DAG.getNode(ISD::XOR, SDLoc(N0), IntVT, Int, 6832 DAG.getConstant(APInt::getSignBit(IntVT.getSizeInBits()), IntVT)); 6833 AddToWorkList(Int.getNode()); 6834 return DAG.getNode(ISD::BITCAST, SDLoc(N), 6835 VT, Int); 6836 } 6837 } 6838 6839 // (fneg (fmul c, x)) -> (fmul -c, x) 6840 if (N0.getOpcode() == ISD::FMUL) { 6841 ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1)); 6842 if (CFP1) 6843 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, 6844 N0.getOperand(0), 6845 DAG.getNode(ISD::FNEG, SDLoc(N), VT, 6846 N0.getOperand(1))); 6847 } 6848 6849 return SDValue(); 6850} 6851 6852SDValue DAGCombiner::visitFCEIL(SDNode *N) { 6853 SDValue N0 = N->getOperand(0); 6854 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 6855 EVT VT = N->getValueType(0); 6856 6857 // fold (fceil c1) -> fceil(c1) 6858 if (N0CFP) 6859 return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0); 6860 6861 return SDValue(); 6862} 6863 6864SDValue DAGCombiner::visitFTRUNC(SDNode *N) { 6865 SDValue N0 = N->getOperand(0); 6866 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 6867 EVT VT = N->getValueType(0); 6868 6869 // fold (ftrunc c1) -> ftrunc(c1) 6870 if (N0CFP) 6871 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0); 6872 6873 return SDValue(); 6874} 6875 6876SDValue DAGCombiner::visitFFLOOR(SDNode *N) { 6877 SDValue N0 = N->getOperand(0); 6878 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 6879 EVT VT = N->getValueType(0); 6880 6881 // fold (ffloor c1) -> ffloor(c1) 6882 if (N0CFP) 6883 return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0); 6884 6885 return SDValue(); 6886} 6887 6888SDValue DAGCombiner::visitFABS(SDNode *N) { 6889 SDValue N0 = N->getOperand(0); 6890 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 6891 EVT VT = N->getValueType(0); 6892 6893 if (VT.isVector()) { 6894 SDValue FoldedVOp = SimplifyVUnaryOp(N); 6895 if (FoldedVOp.getNode()) return FoldedVOp; 6896 } 6897 6898 // fold (fabs c1) -> fabs(c1) 6899 if (N0CFP) 6900 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0); 6901 // fold (fabs (fabs x)) -> (fabs x) 6902 if (N0.getOpcode() == ISD::FABS) 6903 return N->getOperand(0); 6904 // fold (fabs (fneg x)) -> (fabs x) 6905 // fold (fabs (fcopysign x, y)) -> (fabs x) 6906 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN) 6907 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0)); 6908 6909 // Transform fabs(bitconvert(x)) -> bitconvert(x&~sign) to avoid loading 6910 // constant pool values. 6911 if (!TLI.isFAbsFree(VT) && 6912 N0.getOpcode() == ISD::BITCAST && N0.getNode()->hasOneUse() && 6913 N0.getOperand(0).getValueType().isInteger() && 6914 !N0.getOperand(0).getValueType().isVector()) { 6915 SDValue Int = N0.getOperand(0); 6916 EVT IntVT = Int.getValueType(); 6917 if (IntVT.isInteger() && !IntVT.isVector()) { 6918 Int = DAG.getNode(ISD::AND, SDLoc(N0), IntVT, Int, 6919 DAG.getConstant(~APInt::getSignBit(IntVT.getSizeInBits()), IntVT)); 6920 AddToWorkList(Int.getNode()); 6921 return DAG.getNode(ISD::BITCAST, SDLoc(N), 6922 N->getValueType(0), Int); 6923 } 6924 } 6925 6926 return SDValue(); 6927} 6928 6929SDValue DAGCombiner::visitBRCOND(SDNode *N) { 6930 SDValue Chain = N->getOperand(0); 6931 SDValue N1 = N->getOperand(1); 6932 SDValue N2 = N->getOperand(2); 6933 6934 // If N is a constant we could fold this into a fallthrough or unconditional 6935 // branch. However that doesn't happen very often in normal code, because 6936 // Instcombine/SimplifyCFG should have handled the available opportunities. 6937 // If we did this folding here, it would be necessary to update the 6938 // MachineBasicBlock CFG, which is awkward. 6939 6940 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal 6941 // on the target. 6942 if (N1.getOpcode() == ISD::SETCC && 6943 TLI.isOperationLegalOrCustom(ISD::BR_CC, 6944 N1.getOperand(0).getValueType())) { 6945 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other, 6946 Chain, N1.getOperand(2), 6947 N1.getOperand(0), N1.getOperand(1), N2); 6948 } 6949 6950 if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) || 6951 ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) && 6952 (N1.getOperand(0).hasOneUse() && 6953 N1.getOperand(0).getOpcode() == ISD::SRL))) { 6954 SDNode *Trunc = 0; 6955 if (N1.getOpcode() == ISD::TRUNCATE) { 6956 // Look pass the truncate. 6957 Trunc = N1.getNode(); 6958 N1 = N1.getOperand(0); 6959 } 6960 6961 // Match this pattern so that we can generate simpler code: 6962 // 6963 // %a = ... 6964 // %b = and i32 %a, 2 6965 // %c = srl i32 %b, 1 6966 // brcond i32 %c ... 6967 // 6968 // into 6969 // 6970 // %a = ... 6971 // %b = and i32 %a, 2 6972 // %c = setcc eq %b, 0 6973 // brcond %c ... 6974 // 6975 // This applies only when the AND constant value has one bit set and the 6976 // SRL constant is equal to the log2 of the AND constant. The back-end is 6977 // smart enough to convert the result into a TEST/JMP sequence. 6978 SDValue Op0 = N1.getOperand(0); 6979 SDValue Op1 = N1.getOperand(1); 6980 6981 if (Op0.getOpcode() == ISD::AND && 6982 Op1.getOpcode() == ISD::Constant) { 6983 SDValue AndOp1 = Op0.getOperand(1); 6984 6985 if (AndOp1.getOpcode() == ISD::Constant) { 6986 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue(); 6987 6988 if (AndConst.isPowerOf2() && 6989 cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) { 6990 SDValue SetCC = 6991 DAG.getSetCC(SDLoc(N), 6992 getSetCCResultType(Op0.getValueType()), 6993 Op0, DAG.getConstant(0, Op0.getValueType()), 6994 ISD::SETNE); 6995 6996 SDValue NewBRCond = DAG.getNode(ISD::BRCOND, SDLoc(N), 6997 MVT::Other, Chain, SetCC, N2); 6998 // Don't add the new BRCond into the worklist or else SimplifySelectCC 6999 // will convert it back to (X & C1) >> C2. 7000 CombineTo(N, NewBRCond, false); 7001 // Truncate is dead. 7002 if (Trunc) { 7003 removeFromWorkList(Trunc); 7004 DAG.DeleteNode(Trunc); 7005 } 7006 // Replace the uses of SRL with SETCC 7007 WorkListRemover DeadNodes(*this); 7008 DAG.ReplaceAllUsesOfValueWith(N1, SetCC); 7009 removeFromWorkList(N1.getNode()); 7010 DAG.DeleteNode(N1.getNode()); 7011 return SDValue(N, 0); // Return N so it doesn't get rechecked! 7012 } 7013 } 7014 } 7015 7016 if (Trunc) 7017 // Restore N1 if the above transformation doesn't match. 7018 N1 = N->getOperand(1); 7019 } 7020 7021 // Transform br(xor(x, y)) -> br(x != y) 7022 // Transform br(xor(xor(x,y), 1)) -> br (x == y) 7023 if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) { 7024 SDNode *TheXor = N1.getNode(); 7025 SDValue Op0 = TheXor->getOperand(0); 7026 SDValue Op1 = TheXor->getOperand(1); 7027 if (Op0.getOpcode() == Op1.getOpcode()) { 7028 // Avoid missing important xor optimizations. 7029 SDValue Tmp = visitXOR(TheXor); 7030 if (Tmp.getNode()) { 7031 if (Tmp.getNode() != TheXor) { 7032 DEBUG(dbgs() << "\nReplacing.8 "; 7033 TheXor->dump(&DAG); 7034 dbgs() << "\nWith: "; 7035 Tmp.getNode()->dump(&DAG); 7036 dbgs() << '\n'); 7037 WorkListRemover DeadNodes(*this); 7038 DAG.ReplaceAllUsesOfValueWith(N1, Tmp); 7039 removeFromWorkList(TheXor); 7040 DAG.DeleteNode(TheXor); 7041 return DAG.getNode(ISD::BRCOND, SDLoc(N), 7042 MVT::Other, Chain, Tmp, N2); 7043 } 7044 7045 // visitXOR has changed XOR's operands or replaced the XOR completely, 7046 // bail out. 7047 return SDValue(N, 0); 7048 } 7049 } 7050 7051 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) { 7052 bool Equal = false; 7053 if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0)) 7054 if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() && 7055 Op0.getOpcode() == ISD::XOR) { 7056 TheXor = Op0.getNode(); 7057 Equal = true; 7058 } 7059 7060 EVT SetCCVT = N1.getValueType(); 7061 if (LegalTypes) 7062 SetCCVT = getSetCCResultType(SetCCVT); 7063 SDValue SetCC = DAG.getSetCC(SDLoc(TheXor), 7064 SetCCVT, 7065 Op0, Op1, 7066 Equal ? ISD::SETEQ : ISD::SETNE); 7067 // Replace the uses of XOR with SETCC 7068 WorkListRemover DeadNodes(*this); 7069 DAG.ReplaceAllUsesOfValueWith(N1, SetCC); 7070 removeFromWorkList(N1.getNode()); 7071 DAG.DeleteNode(N1.getNode()); 7072 return DAG.getNode(ISD::BRCOND, SDLoc(N), 7073 MVT::Other, Chain, SetCC, N2); 7074 } 7075 } 7076 7077 return SDValue(); 7078} 7079 7080// Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB. 7081// 7082SDValue DAGCombiner::visitBR_CC(SDNode *N) { 7083 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1)); 7084 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3); 7085 7086 // If N is a constant we could fold this into a fallthrough or unconditional 7087 // branch. However that doesn't happen very often in normal code, because 7088 // Instcombine/SimplifyCFG should have handled the available opportunities. 7089 // If we did this folding here, it would be necessary to update the 7090 // MachineBasicBlock CFG, which is awkward. 7091 7092 // Use SimplifySetCC to simplify SETCC's. 7093 SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()), 7094 CondLHS, CondRHS, CC->get(), SDLoc(N), 7095 false); 7096 if (Simp.getNode()) AddToWorkList(Simp.getNode()); 7097 7098 // fold to a simpler setcc 7099 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC) 7100 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other, 7101 N->getOperand(0), Simp.getOperand(2), 7102 Simp.getOperand(0), Simp.getOperand(1), 7103 N->getOperand(4)); 7104 7105 return SDValue(); 7106} 7107 7108/// canFoldInAddressingMode - Return true if 'Use' is a load or a store that 7109/// uses N as its base pointer and that N may be folded in the load / store 7110/// addressing mode. 7111static bool canFoldInAddressingMode(SDNode *N, SDNode *Use, 7112 SelectionDAG &DAG, 7113 const TargetLowering &TLI) { 7114 EVT VT; 7115 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) { 7116 if (LD->isIndexed() || LD->getBasePtr().getNode() != N) 7117 return false; 7118 VT = Use->getValueType(0); 7119 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) { 7120 if (ST->isIndexed() || ST->getBasePtr().getNode() != N) 7121 return false; 7122 VT = ST->getValue().getValueType(); 7123 } else 7124 return false; 7125 7126 TargetLowering::AddrMode AM; 7127 if (N->getOpcode() == ISD::ADD) { 7128 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1)); 7129 if (Offset) 7130 // [reg +/- imm] 7131 AM.BaseOffs = Offset->getSExtValue(); 7132 else 7133 // [reg +/- reg] 7134 AM.Scale = 1; 7135 } else if (N->getOpcode() == ISD::SUB) { 7136 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1)); 7137 if (Offset) 7138 // [reg +/- imm] 7139 AM.BaseOffs = -Offset->getSExtValue(); 7140 else 7141 // [reg +/- reg] 7142 AM.Scale = 1; 7143 } else 7144 return false; 7145 7146 return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext())); 7147} 7148 7149/// CombineToPreIndexedLoadStore - Try turning a load / store into a 7150/// pre-indexed load / store when the base pointer is an add or subtract 7151/// and it has other uses besides the load / store. After the 7152/// transformation, the new indexed load / store has effectively folded 7153/// the add / subtract in and all of its other uses are redirected to the 7154/// new load / store. 7155bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) { 7156 if (Level < AfterLegalizeDAG) 7157 return false; 7158 7159 bool isLoad = true; 7160 SDValue Ptr; 7161 EVT VT; 7162 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 7163 if (LD->isIndexed()) 7164 return false; 7165 VT = LD->getMemoryVT(); 7166 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) && 7167 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT)) 7168 return false; 7169 Ptr = LD->getBasePtr(); 7170 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 7171 if (ST->isIndexed()) 7172 return false; 7173 VT = ST->getMemoryVT(); 7174 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) && 7175 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT)) 7176 return false; 7177 Ptr = ST->getBasePtr(); 7178 isLoad = false; 7179 } else { 7180 return false; 7181 } 7182 7183 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail 7184 // out. There is no reason to make this a preinc/predec. 7185 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) || 7186 Ptr.getNode()->hasOneUse()) 7187 return false; 7188 7189 // Ask the target to do addressing mode selection. 7190 SDValue BasePtr; 7191 SDValue Offset; 7192 ISD::MemIndexedMode AM = ISD::UNINDEXED; 7193 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG)) 7194 return false; 7195 7196 // Backends without true r+i pre-indexed forms may need to pass a 7197 // constant base with a variable offset so that constant coercion 7198 // will work with the patterns in canonical form. 7199 bool Swapped = false; 7200 if (isa<ConstantSDNode>(BasePtr)) { 7201 std::swap(BasePtr, Offset); 7202 Swapped = true; 7203 } 7204 7205 // Don't create a indexed load / store with zero offset. 7206 if (isa<ConstantSDNode>(Offset) && 7207 cast<ConstantSDNode>(Offset)->isNullValue()) 7208 return false; 7209 7210 // Try turning it into a pre-indexed load / store except when: 7211 // 1) The new base ptr is a frame index. 7212 // 2) If N is a store and the new base ptr is either the same as or is a 7213 // predecessor of the value being stored. 7214 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded 7215 // that would create a cycle. 7216 // 4) All uses are load / store ops that use it as old base ptr. 7217 7218 // Check #1. Preinc'ing a frame index would require copying the stack pointer 7219 // (plus the implicit offset) to a register to preinc anyway. 7220 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr)) 7221 return false; 7222 7223 // Check #2. 7224 if (!isLoad) { 7225 SDValue Val = cast<StoreSDNode>(N)->getValue(); 7226 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode())) 7227 return false; 7228 } 7229 7230 // If the offset is a constant, there may be other adds of constants that 7231 // can be folded with this one. We should do this to avoid having to keep 7232 // a copy of the original base pointer. 7233 SmallVector<SDNode *, 16> OtherUses; 7234 if (isa<ConstantSDNode>(Offset)) 7235 for (SDNode::use_iterator I = BasePtr.getNode()->use_begin(), 7236 E = BasePtr.getNode()->use_end(); I != E; ++I) { 7237 SDNode *Use = *I; 7238 if (Use == Ptr.getNode()) 7239 continue; 7240 7241 if (Use->isPredecessorOf(N)) 7242 continue; 7243 7244 if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) { 7245 OtherUses.clear(); 7246 break; 7247 } 7248 7249 SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1); 7250 if (Op1.getNode() == BasePtr.getNode()) 7251 std::swap(Op0, Op1); 7252 assert(Op0.getNode() == BasePtr.getNode() && 7253 "Use of ADD/SUB but not an operand"); 7254 7255 if (!isa<ConstantSDNode>(Op1)) { 7256 OtherUses.clear(); 7257 break; 7258 } 7259 7260 // FIXME: In some cases, we can be smarter about this. 7261 if (Op1.getValueType() != Offset.getValueType()) { 7262 OtherUses.clear(); 7263 break; 7264 } 7265 7266 OtherUses.push_back(Use); 7267 } 7268 7269 if (Swapped) 7270 std::swap(BasePtr, Offset); 7271 7272 // Now check for #3 and #4. 7273 bool RealUse = false; 7274 7275 // Caches for hasPredecessorHelper 7276 SmallPtrSet<const SDNode *, 32> Visited; 7277 SmallVector<const SDNode *, 16> Worklist; 7278 7279 for (SDNode::use_iterator I = Ptr.getNode()->use_begin(), 7280 E = Ptr.getNode()->use_end(); I != E; ++I) { 7281 SDNode *Use = *I; 7282 if (Use == N) 7283 continue; 7284 if (N->hasPredecessorHelper(Use, Visited, Worklist)) 7285 return false; 7286 7287 // If Ptr may be folded in addressing mode of other use, then it's 7288 // not profitable to do this transformation. 7289 if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI)) 7290 RealUse = true; 7291 } 7292 7293 if (!RealUse) 7294 return false; 7295 7296 SDValue Result; 7297 if (isLoad) 7298 Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N), 7299 BasePtr, Offset, AM); 7300 else 7301 Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N), 7302 BasePtr, Offset, AM); 7303 ++PreIndexedNodes; 7304 ++NodesCombined; 7305 DEBUG(dbgs() << "\nReplacing.4 "; 7306 N->dump(&DAG); 7307 dbgs() << "\nWith: "; 7308 Result.getNode()->dump(&DAG); 7309 dbgs() << '\n'); 7310 WorkListRemover DeadNodes(*this); 7311 if (isLoad) { 7312 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0)); 7313 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2)); 7314 } else { 7315 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1)); 7316 } 7317 7318 // Finally, since the node is now dead, remove it from the graph. 7319 DAG.DeleteNode(N); 7320 7321 if (Swapped) 7322 std::swap(BasePtr, Offset); 7323 7324 // Replace other uses of BasePtr that can be updated to use Ptr 7325 for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) { 7326 unsigned OffsetIdx = 1; 7327 if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode()) 7328 OffsetIdx = 0; 7329 assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() == 7330 BasePtr.getNode() && "Expected BasePtr operand"); 7331 7332 // We need to replace ptr0 in the following expression: 7333 // x0 * offset0 + y0 * ptr0 = t0 7334 // knowing that 7335 // x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store) 7336 // 7337 // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the 7338 // indexed load/store and the expresion that needs to be re-written. 7339 // 7340 // Therefore, we have: 7341 // t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1 7342 7343 ConstantSDNode *CN = 7344 cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx)); 7345 int X0, X1, Y0, Y1; 7346 APInt Offset0 = CN->getAPIntValue(); 7347 APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue(); 7348 7349 X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1; 7350 Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1; 7351 X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1; 7352 Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1; 7353 7354 unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD; 7355 7356 APInt CNV = Offset0; 7357 if (X0 < 0) CNV = -CNV; 7358 if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1; 7359 else CNV = CNV - Offset1; 7360 7361 // We can now generate the new expression. 7362 SDValue NewOp1 = DAG.getConstant(CNV, CN->getValueType(0)); 7363 SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0); 7364 7365 SDValue NewUse = DAG.getNode(Opcode, 7366 SDLoc(OtherUses[i]), 7367 OtherUses[i]->getValueType(0), NewOp1, NewOp2); 7368 DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse); 7369 removeFromWorkList(OtherUses[i]); 7370 DAG.DeleteNode(OtherUses[i]); 7371 } 7372 7373 // Replace the uses of Ptr with uses of the updated base value. 7374 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0)); 7375 removeFromWorkList(Ptr.getNode()); 7376 DAG.DeleteNode(Ptr.getNode()); 7377 7378 return true; 7379} 7380 7381/// CombineToPostIndexedLoadStore - Try to combine a load / store with a 7382/// add / sub of the base pointer node into a post-indexed load / store. 7383/// The transformation folded the add / subtract into the new indexed 7384/// load / store effectively and all of its uses are redirected to the 7385/// new load / store. 7386bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) { 7387 if (Level < AfterLegalizeDAG) 7388 return false; 7389 7390 bool isLoad = true; 7391 SDValue Ptr; 7392 EVT VT; 7393 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 7394 if (LD->isIndexed()) 7395 return false; 7396 VT = LD->getMemoryVT(); 7397 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) && 7398 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT)) 7399 return false; 7400 Ptr = LD->getBasePtr(); 7401 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 7402 if (ST->isIndexed()) 7403 return false; 7404 VT = ST->getMemoryVT(); 7405 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) && 7406 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT)) 7407 return false; 7408 Ptr = ST->getBasePtr(); 7409 isLoad = false; 7410 } else { 7411 return false; 7412 } 7413 7414 if (Ptr.getNode()->hasOneUse()) 7415 return false; 7416 7417 for (SDNode::use_iterator I = Ptr.getNode()->use_begin(), 7418 E = Ptr.getNode()->use_end(); I != E; ++I) { 7419 SDNode *Op = *I; 7420 if (Op == N || 7421 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB)) 7422 continue; 7423 7424 SDValue BasePtr; 7425 SDValue Offset; 7426 ISD::MemIndexedMode AM = ISD::UNINDEXED; 7427 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) { 7428 // Don't create a indexed load / store with zero offset. 7429 if (isa<ConstantSDNode>(Offset) && 7430 cast<ConstantSDNode>(Offset)->isNullValue()) 7431 continue; 7432 7433 // Try turning it into a post-indexed load / store except when 7434 // 1) All uses are load / store ops that use it as base ptr (and 7435 // it may be folded as addressing mmode). 7436 // 2) Op must be independent of N, i.e. Op is neither a predecessor 7437 // nor a successor of N. Otherwise, if Op is folded that would 7438 // create a cycle. 7439 7440 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr)) 7441 continue; 7442 7443 // Check for #1. 7444 bool TryNext = false; 7445 for (SDNode::use_iterator II = BasePtr.getNode()->use_begin(), 7446 EE = BasePtr.getNode()->use_end(); II != EE; ++II) { 7447 SDNode *Use = *II; 7448 if (Use == Ptr.getNode()) 7449 continue; 7450 7451 // If all the uses are load / store addresses, then don't do the 7452 // transformation. 7453 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){ 7454 bool RealUse = false; 7455 for (SDNode::use_iterator III = Use->use_begin(), 7456 EEE = Use->use_end(); III != EEE; ++III) { 7457 SDNode *UseUse = *III; 7458 if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI)) 7459 RealUse = true; 7460 } 7461 7462 if (!RealUse) { 7463 TryNext = true; 7464 break; 7465 } 7466 } 7467 } 7468 7469 if (TryNext) 7470 continue; 7471 7472 // Check for #2 7473 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) { 7474 SDValue Result = isLoad 7475 ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N), 7476 BasePtr, Offset, AM) 7477 : DAG.getIndexedStore(SDValue(N,0), SDLoc(N), 7478 BasePtr, Offset, AM); 7479 ++PostIndexedNodes; 7480 ++NodesCombined; 7481 DEBUG(dbgs() << "\nReplacing.5 "; 7482 N->dump(&DAG); 7483 dbgs() << "\nWith: "; 7484 Result.getNode()->dump(&DAG); 7485 dbgs() << '\n'); 7486 WorkListRemover DeadNodes(*this); 7487 if (isLoad) { 7488 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0)); 7489 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2)); 7490 } else { 7491 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1)); 7492 } 7493 7494 // Finally, since the node is now dead, remove it from the graph. 7495 DAG.DeleteNode(N); 7496 7497 // Replace the uses of Use with uses of the updated base value. 7498 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0), 7499 Result.getValue(isLoad ? 1 : 0)); 7500 removeFromWorkList(Op); 7501 DAG.DeleteNode(Op); 7502 return true; 7503 } 7504 } 7505 } 7506 7507 return false; 7508} 7509 7510SDValue DAGCombiner::visitLOAD(SDNode *N) { 7511 LoadSDNode *LD = cast<LoadSDNode>(N); 7512 SDValue Chain = LD->getChain(); 7513 SDValue Ptr = LD->getBasePtr(); 7514 7515 // If load is not volatile and there are no uses of the loaded value (and 7516 // the updated indexed value in case of indexed loads), change uses of the 7517 // chain value into uses of the chain input (i.e. delete the dead load). 7518 if (!LD->isVolatile()) { 7519 if (N->getValueType(1) == MVT::Other) { 7520 // Unindexed loads. 7521 if (!N->hasAnyUseOfValue(0)) { 7522 // It's not safe to use the two value CombineTo variant here. e.g. 7523 // v1, chain2 = load chain1, loc 7524 // v2, chain3 = load chain2, loc 7525 // v3 = add v2, c 7526 // Now we replace use of chain2 with chain1. This makes the second load 7527 // isomorphic to the one we are deleting, and thus makes this load live. 7528 DEBUG(dbgs() << "\nReplacing.6 "; 7529 N->dump(&DAG); 7530 dbgs() << "\nWith chain: "; 7531 Chain.getNode()->dump(&DAG); 7532 dbgs() << "\n"); 7533 WorkListRemover DeadNodes(*this); 7534 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain); 7535 7536 if (N->use_empty()) { 7537 removeFromWorkList(N); 7538 DAG.DeleteNode(N); 7539 } 7540 7541 return SDValue(N, 0); // Return N so it doesn't get rechecked! 7542 } 7543 } else { 7544 // Indexed loads. 7545 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?"); 7546 if (!N->hasAnyUseOfValue(0) && !N->hasAnyUseOfValue(1)) { 7547 SDValue Undef = DAG.getUNDEF(N->getValueType(0)); 7548 DEBUG(dbgs() << "\nReplacing.7 "; 7549 N->dump(&DAG); 7550 dbgs() << "\nWith: "; 7551 Undef.getNode()->dump(&DAG); 7552 dbgs() << " and 2 other values\n"); 7553 WorkListRemover DeadNodes(*this); 7554 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef); 7555 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), 7556 DAG.getUNDEF(N->getValueType(1))); 7557 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain); 7558 removeFromWorkList(N); 7559 DAG.DeleteNode(N); 7560 return SDValue(N, 0); // Return N so it doesn't get rechecked! 7561 } 7562 } 7563 } 7564 7565 // If this load is directly stored, replace the load value with the stored 7566 // value. 7567 // TODO: Handle store large -> read small portion. 7568 // TODO: Handle TRUNCSTORE/LOADEXT 7569 if (ISD::isNormalLoad(N) && !LD->isVolatile()) { 7570 if (ISD::isNON_TRUNCStore(Chain.getNode())) { 7571 StoreSDNode *PrevST = cast<StoreSDNode>(Chain); 7572 if (PrevST->getBasePtr() == Ptr && 7573 PrevST->getValue().getValueType() == N->getValueType(0)) 7574 return CombineTo(N, Chain.getOperand(1), Chain); 7575 } 7576 } 7577 7578 // Try to infer better alignment information than the load already has. 7579 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) { 7580 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) { 7581 if (Align > LD->getMemOperand()->getBaseAlignment()) { 7582 SDValue NewLoad = 7583 DAG.getExtLoad(LD->getExtensionType(), SDLoc(N), 7584 LD->getValueType(0), 7585 Chain, Ptr, LD->getPointerInfo(), 7586 LD->getMemoryVT(), 7587 LD->isVolatile(), LD->isNonTemporal(), Align, 7588 LD->getTBAAInfo()); 7589 return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true); 7590 } 7591 } 7592 } 7593 7594 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA : 7595 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA(); 7596 if (UseAA) { 7597 // Walk up chain skipping non-aliasing memory nodes. 7598 SDValue BetterChain = FindBetterChain(N, Chain); 7599 7600 // If there is a better chain. 7601 if (Chain != BetterChain) { 7602 SDValue ReplLoad; 7603 7604 // Replace the chain to void dependency. 7605 if (LD->getExtensionType() == ISD::NON_EXTLOAD) { 7606 ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD), 7607 BetterChain, Ptr, LD->getMemOperand()); 7608 } else { 7609 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), 7610 LD->getValueType(0), 7611 BetterChain, Ptr, LD->getMemoryVT(), 7612 LD->getMemOperand()); 7613 } 7614 7615 // Create token factor to keep old chain connected. 7616 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N), 7617 MVT::Other, Chain, ReplLoad.getValue(1)); 7618 7619 // Make sure the new and old chains are cleaned up. 7620 AddToWorkList(Token.getNode()); 7621 7622 // Replace uses with load result and token factor. Don't add users 7623 // to work list. 7624 return CombineTo(N, ReplLoad.getValue(0), Token, false); 7625 } 7626 } 7627 7628 // Try transforming N to an indexed load. 7629 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N)) 7630 return SDValue(N, 0); 7631 7632 // Try to slice up N to more direct loads if the slices are mapped to 7633 // different register banks or pairing can take place. 7634 if (SliceUpLoad(N)) 7635 return SDValue(N, 0); 7636 7637 return SDValue(); 7638} 7639 7640namespace { 7641/// \brief Helper structure used to slice a load in smaller loads. 7642/// Basically a slice is obtained from the following sequence: 7643/// Origin = load Ty1, Base 7644/// Shift = srl Ty1 Origin, CstTy Amount 7645/// Inst = trunc Shift to Ty2 7646/// 7647/// Then, it will be rewriten into: 7648/// Slice = load SliceTy, Base + SliceOffset 7649/// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2 7650/// 7651/// SliceTy is deduced from the number of bits that are actually used to 7652/// build Inst. 7653struct LoadedSlice { 7654 /// \brief Helper structure used to compute the cost of a slice. 7655 struct Cost { 7656 /// Are we optimizing for code size. 7657 bool ForCodeSize; 7658 /// Various cost. 7659 unsigned Loads; 7660 unsigned Truncates; 7661 unsigned CrossRegisterBanksCopies; 7662 unsigned ZExts; 7663 unsigned Shift; 7664 7665 Cost(bool ForCodeSize = false) 7666 : ForCodeSize(ForCodeSize), Loads(0), Truncates(0), 7667 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {} 7668 7669 /// \brief Get the cost of one isolated slice. 7670 Cost(const LoadedSlice &LS, bool ForCodeSize = false) 7671 : ForCodeSize(ForCodeSize), Loads(1), Truncates(0), 7672 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) { 7673 EVT TruncType = LS.Inst->getValueType(0); 7674 EVT LoadedType = LS.getLoadedType(); 7675 if (TruncType != LoadedType && 7676 !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType)) 7677 ZExts = 1; 7678 } 7679 7680 /// \brief Account for slicing gain in the current cost. 7681 /// Slicing provide a few gains like removing a shift or a 7682 /// truncate. This method allows to grow the cost of the original 7683 /// load with the gain from this slice. 7684 void addSliceGain(const LoadedSlice &LS) { 7685 // Each slice saves a truncate. 7686 const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo(); 7687 if (!TLI.isTruncateFree(LS.Inst->getValueType(0), 7688 LS.Inst->getOperand(0).getValueType())) 7689 ++Truncates; 7690 // If there is a shift amount, this slice gets rid of it. 7691 if (LS.Shift) 7692 ++Shift; 7693 // If this slice can merge a cross register bank copy, account for it. 7694 if (LS.canMergeExpensiveCrossRegisterBankCopy()) 7695 ++CrossRegisterBanksCopies; 7696 } 7697 7698 Cost &operator+=(const Cost &RHS) { 7699 Loads += RHS.Loads; 7700 Truncates += RHS.Truncates; 7701 CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies; 7702 ZExts += RHS.ZExts; 7703 Shift += RHS.Shift; 7704 return *this; 7705 } 7706 7707 bool operator==(const Cost &RHS) const { 7708 return Loads == RHS.Loads && Truncates == RHS.Truncates && 7709 CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies && 7710 ZExts == RHS.ZExts && Shift == RHS.Shift; 7711 } 7712 7713 bool operator!=(const Cost &RHS) const { return !(*this == RHS); } 7714 7715 bool operator<(const Cost &RHS) const { 7716 // Assume cross register banks copies are as expensive as loads. 7717 // FIXME: Do we want some more target hooks? 7718 unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies; 7719 unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies; 7720 // Unless we are optimizing for code size, consider the 7721 // expensive operation first. 7722 if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS) 7723 return ExpensiveOpsLHS < ExpensiveOpsRHS; 7724 return (Truncates + ZExts + Shift + ExpensiveOpsLHS) < 7725 (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS); 7726 } 7727 7728 bool operator>(const Cost &RHS) const { return RHS < *this; } 7729 7730 bool operator<=(const Cost &RHS) const { return !(RHS < *this); } 7731 7732 bool operator>=(const Cost &RHS) const { return !(*this < RHS); } 7733 }; 7734 // The last instruction that represent the slice. This should be a 7735 // truncate instruction. 7736 SDNode *Inst; 7737 // The original load instruction. 7738 LoadSDNode *Origin; 7739 // The right shift amount in bits from the original load. 7740 unsigned Shift; 7741 // The DAG from which Origin came from. 7742 // This is used to get some contextual information about legal types, etc. 7743 SelectionDAG *DAG; 7744 7745 LoadedSlice(SDNode *Inst = NULL, LoadSDNode *Origin = NULL, 7746 unsigned Shift = 0, SelectionDAG *DAG = NULL) 7747 : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {} 7748 7749 LoadedSlice(const LoadedSlice &LS) 7750 : Inst(LS.Inst), Origin(LS.Origin), Shift(LS.Shift), DAG(LS.DAG) {} 7751 7752 /// \brief Get the bits used in a chunk of bits \p BitWidth large. 7753 /// \return Result is \p BitWidth and has used bits set to 1 and 7754 /// not used bits set to 0. 7755 APInt getUsedBits() const { 7756 // Reproduce the trunc(lshr) sequence: 7757 // - Start from the truncated value. 7758 // - Zero extend to the desired bit width. 7759 // - Shift left. 7760 assert(Origin && "No original load to compare against."); 7761 unsigned BitWidth = Origin->getValueSizeInBits(0); 7762 assert(Inst && "This slice is not bound to an instruction"); 7763 assert(Inst->getValueSizeInBits(0) <= BitWidth && 7764 "Extracted slice is bigger than the whole type!"); 7765 APInt UsedBits(Inst->getValueSizeInBits(0), 0); 7766 UsedBits.setAllBits(); 7767 UsedBits = UsedBits.zext(BitWidth); 7768 UsedBits <<= Shift; 7769 return UsedBits; 7770 } 7771 7772 /// \brief Get the size of the slice to be loaded in bytes. 7773 unsigned getLoadedSize() const { 7774 unsigned SliceSize = getUsedBits().countPopulation(); 7775 assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte."); 7776 return SliceSize / 8; 7777 } 7778 7779 /// \brief Get the type that will be loaded for this slice. 7780 /// Note: This may not be the final type for the slice. 7781 EVT getLoadedType() const { 7782 assert(DAG && "Missing context"); 7783 LLVMContext &Ctxt = *DAG->getContext(); 7784 return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8); 7785 } 7786 7787 /// \brief Get the alignment of the load used for this slice. 7788 unsigned getAlignment() const { 7789 unsigned Alignment = Origin->getAlignment(); 7790 unsigned Offset = getOffsetFromBase(); 7791 if (Offset != 0) 7792 Alignment = MinAlign(Alignment, Alignment + Offset); 7793 return Alignment; 7794 } 7795 7796 /// \brief Check if this slice can be rewritten with legal operations. 7797 bool isLegal() const { 7798 // An invalid slice is not legal. 7799 if (!Origin || !Inst || !DAG) 7800 return false; 7801 7802 // Offsets are for indexed load only, we do not handle that. 7803 if (Origin->getOffset().getOpcode() != ISD::UNDEF) 7804 return false; 7805 7806 const TargetLowering &TLI = DAG->getTargetLoweringInfo(); 7807 7808 // Check that the type is legal. 7809 EVT SliceType = getLoadedType(); 7810 if (!TLI.isTypeLegal(SliceType)) 7811 return false; 7812 7813 // Check that the load is legal for this type. 7814 if (!TLI.isOperationLegal(ISD::LOAD, SliceType)) 7815 return false; 7816 7817 // Check that the offset can be computed. 7818 // 1. Check its type. 7819 EVT PtrType = Origin->getBasePtr().getValueType(); 7820 if (PtrType == MVT::Untyped || PtrType.isExtended()) 7821 return false; 7822 7823 // 2. Check that it fits in the immediate. 7824 if (!TLI.isLegalAddImmediate(getOffsetFromBase())) 7825 return false; 7826 7827 // 3. Check that the computation is legal. 7828 if (!TLI.isOperationLegal(ISD::ADD, PtrType)) 7829 return false; 7830 7831 // Check that the zext is legal if it needs one. 7832 EVT TruncateType = Inst->getValueType(0); 7833 if (TruncateType != SliceType && 7834 !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType)) 7835 return false; 7836 7837 return true; 7838 } 7839 7840 /// \brief Get the offset in bytes of this slice in the original chunk of 7841 /// bits. 7842 /// \pre DAG != NULL. 7843 uint64_t getOffsetFromBase() const { 7844 assert(DAG && "Missing context."); 7845 bool IsBigEndian = 7846 DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian(); 7847 assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported."); 7848 uint64_t Offset = Shift / 8; 7849 unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8; 7850 assert(!(Origin->getValueSizeInBits(0) & 0x7) && 7851 "The size of the original loaded type is not a multiple of a" 7852 " byte."); 7853 // If Offset is bigger than TySizeInBytes, it means we are loading all 7854 // zeros. This should have been optimized before in the process. 7855 assert(TySizeInBytes > Offset && 7856 "Invalid shift amount for given loaded size"); 7857 if (IsBigEndian) 7858 Offset = TySizeInBytes - Offset - getLoadedSize(); 7859 return Offset; 7860 } 7861 7862 /// \brief Generate the sequence of instructions to load the slice 7863 /// represented by this object and redirect the uses of this slice to 7864 /// this new sequence of instructions. 7865 /// \pre this->Inst && this->Origin are valid Instructions and this 7866 /// object passed the legal check: LoadedSlice::isLegal returned true. 7867 /// \return The last instruction of the sequence used to load the slice. 7868 SDValue loadSlice() const { 7869 assert(Inst && Origin && "Unable to replace a non-existing slice."); 7870 const SDValue &OldBaseAddr = Origin->getBasePtr(); 7871 SDValue BaseAddr = OldBaseAddr; 7872 // Get the offset in that chunk of bytes w.r.t. the endianess. 7873 int64_t Offset = static_cast<int64_t>(getOffsetFromBase()); 7874 assert(Offset >= 0 && "Offset too big to fit in int64_t!"); 7875 if (Offset) { 7876 // BaseAddr = BaseAddr + Offset. 7877 EVT ArithType = BaseAddr.getValueType(); 7878 BaseAddr = DAG->getNode(ISD::ADD, SDLoc(Origin), ArithType, BaseAddr, 7879 DAG->getConstant(Offset, ArithType)); 7880 } 7881 7882 // Create the type of the loaded slice according to its size. 7883 EVT SliceType = getLoadedType(); 7884 7885 // Create the load for the slice. 7886 SDValue LastInst = DAG->getLoad( 7887 SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr, 7888 Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(), 7889 Origin->isNonTemporal(), Origin->isInvariant(), getAlignment()); 7890 // If the final type is not the same as the loaded type, this means that 7891 // we have to pad with zero. Create a zero extend for that. 7892 EVT FinalType = Inst->getValueType(0); 7893 if (SliceType != FinalType) 7894 LastInst = 7895 DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst); 7896 return LastInst; 7897 } 7898 7899 /// \brief Check if this slice can be merged with an expensive cross register 7900 /// bank copy. E.g., 7901 /// i = load i32 7902 /// f = bitcast i32 i to float 7903 bool canMergeExpensiveCrossRegisterBankCopy() const { 7904 if (!Inst || !Inst->hasOneUse()) 7905 return false; 7906 SDNode *Use = *Inst->use_begin(); 7907 if (Use->getOpcode() != ISD::BITCAST) 7908 return false; 7909 assert(DAG && "Missing context"); 7910 const TargetLowering &TLI = DAG->getTargetLoweringInfo(); 7911 EVT ResVT = Use->getValueType(0); 7912 const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT()); 7913 const TargetRegisterClass *ArgRC = 7914 TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT()); 7915 if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT)) 7916 return false; 7917 7918 // At this point, we know that we perform a cross-register-bank copy. 7919 // Check if it is expensive. 7920 const TargetRegisterInfo *TRI = TLI.getTargetMachine().getRegisterInfo(); 7921 // Assume bitcasts are cheap, unless both register classes do not 7922 // explicitly share a common sub class. 7923 if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC)) 7924 return false; 7925 7926 // Check if it will be merged with the load. 7927 // 1. Check the alignment constraint. 7928 unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment( 7929 ResVT.getTypeForEVT(*DAG->getContext())); 7930 7931 if (RequiredAlignment > getAlignment()) 7932 return false; 7933 7934 // 2. Check that the load is a legal operation for that type. 7935 if (!TLI.isOperationLegal(ISD::LOAD, ResVT)) 7936 return false; 7937 7938 // 3. Check that we do not have a zext in the way. 7939 if (Inst->getValueType(0) != getLoadedType()) 7940 return false; 7941 7942 return true; 7943 } 7944}; 7945} 7946 7947/// \brief Sorts LoadedSlice according to their offset. 7948struct LoadedSliceSorter { 7949 bool operator()(const LoadedSlice &LHS, const LoadedSlice &RHS) { 7950 assert(LHS.Origin == RHS.Origin && "Different bases not implemented."); 7951 return LHS.getOffsetFromBase() < RHS.getOffsetFromBase(); 7952 } 7953}; 7954 7955/// \brief Check that all bits set in \p UsedBits form a dense region, i.e., 7956/// \p UsedBits looks like 0..0 1..1 0..0. 7957static bool areUsedBitsDense(const APInt &UsedBits) { 7958 // If all the bits are one, this is dense! 7959 if (UsedBits.isAllOnesValue()) 7960 return true; 7961 7962 // Get rid of the unused bits on the right. 7963 APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros()); 7964 // Get rid of the unused bits on the left. 7965 if (NarrowedUsedBits.countLeadingZeros()) 7966 NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits()); 7967 // Check that the chunk of bits is completely used. 7968 return NarrowedUsedBits.isAllOnesValue(); 7969} 7970 7971/// \brief Check whether or not \p First and \p Second are next to each other 7972/// in memory. This means that there is no hole between the bits loaded 7973/// by \p First and the bits loaded by \p Second. 7974static bool areSlicesNextToEachOther(const LoadedSlice &First, 7975 const LoadedSlice &Second) { 7976 assert(First.Origin == Second.Origin && First.Origin && 7977 "Unable to match different memory origins."); 7978 APInt UsedBits = First.getUsedBits(); 7979 assert((UsedBits & Second.getUsedBits()) == 0 && 7980 "Slices are not supposed to overlap."); 7981 UsedBits |= Second.getUsedBits(); 7982 return areUsedBitsDense(UsedBits); 7983} 7984 7985/// \brief Adjust the \p GlobalLSCost according to the target 7986/// paring capabilities and the layout of the slices. 7987/// \pre \p GlobalLSCost should account for at least as many loads as 7988/// there is in the slices in \p LoadedSlices. 7989static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices, 7990 LoadedSlice::Cost &GlobalLSCost) { 7991 unsigned NumberOfSlices = LoadedSlices.size(); 7992 // If there is less than 2 elements, no pairing is possible. 7993 if (NumberOfSlices < 2) 7994 return; 7995 7996 // Sort the slices so that elements that are likely to be next to each 7997 // other in memory are next to each other in the list. 7998 std::sort(LoadedSlices.begin(), LoadedSlices.end(), LoadedSliceSorter()); 7999 const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo(); 8000 // First (resp. Second) is the first (resp. Second) potentially candidate 8001 // to be placed in a paired load. 8002 const LoadedSlice *First = NULL; 8003 const LoadedSlice *Second = NULL; 8004 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice, 8005 // Set the beginning of the pair. 8006 First = Second) { 8007 8008 Second = &LoadedSlices[CurrSlice]; 8009 8010 // If First is NULL, it means we start a new pair. 8011 // Get to the next slice. 8012 if (!First) 8013 continue; 8014 8015 EVT LoadedType = First->getLoadedType(); 8016 8017 // If the types of the slices are different, we cannot pair them. 8018 if (LoadedType != Second->getLoadedType()) 8019 continue; 8020 8021 // Check if the target supplies paired loads for this type. 8022 unsigned RequiredAlignment = 0; 8023 if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) { 8024 // move to the next pair, this type is hopeless. 8025 Second = NULL; 8026 continue; 8027 } 8028 // Check if we meet the alignment requirement. 8029 if (RequiredAlignment > First->getAlignment()) 8030 continue; 8031 8032 // Check that both loads are next to each other in memory. 8033 if (!areSlicesNextToEachOther(*First, *Second)) 8034 continue; 8035 8036 assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!"); 8037 --GlobalLSCost.Loads; 8038 // Move to the next pair. 8039 Second = NULL; 8040 } 8041} 8042 8043/// \brief Check the profitability of all involved LoadedSlice. 8044/// Currently, it is considered profitable if there is exactly two 8045/// involved slices (1) which are (2) next to each other in memory, and 8046/// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3). 8047/// 8048/// Note: The order of the elements in \p LoadedSlices may be modified, but not 8049/// the elements themselves. 8050/// 8051/// FIXME: When the cost model will be mature enough, we can relax 8052/// constraints (1) and (2). 8053static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices, 8054 const APInt &UsedBits, bool ForCodeSize) { 8055 unsigned NumberOfSlices = LoadedSlices.size(); 8056 if (StressLoadSlicing) 8057 return NumberOfSlices > 1; 8058 8059 // Check (1). 8060 if (NumberOfSlices != 2) 8061 return false; 8062 8063 // Check (2). 8064 if (!areUsedBitsDense(UsedBits)) 8065 return false; 8066 8067 // Check (3). 8068 LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize); 8069 // The original code has one big load. 8070 OrigCost.Loads = 1; 8071 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) { 8072 const LoadedSlice &LS = LoadedSlices[CurrSlice]; 8073 // Accumulate the cost of all the slices. 8074 LoadedSlice::Cost SliceCost(LS, ForCodeSize); 8075 GlobalSlicingCost += SliceCost; 8076 8077 // Account as cost in the original configuration the gain obtained 8078 // with the current slices. 8079 OrigCost.addSliceGain(LS); 8080 } 8081 8082 // If the target supports paired load, adjust the cost accordingly. 8083 adjustCostForPairing(LoadedSlices, GlobalSlicingCost); 8084 return OrigCost > GlobalSlicingCost; 8085} 8086 8087/// \brief If the given load, \p LI, is used only by trunc or trunc(lshr) 8088/// operations, split it in the various pieces being extracted. 8089/// 8090/// This sort of thing is introduced by SROA. 8091/// This slicing takes care not to insert overlapping loads. 8092/// \pre LI is a simple load (i.e., not an atomic or volatile load). 8093bool DAGCombiner::SliceUpLoad(SDNode *N) { 8094 if (Level < AfterLegalizeDAG) 8095 return false; 8096 8097 LoadSDNode *LD = cast<LoadSDNode>(N); 8098 if (LD->isVolatile() || !ISD::isNormalLoad(LD) || 8099 !LD->getValueType(0).isInteger()) 8100 return false; 8101 8102 // Keep track of already used bits to detect overlapping values. 8103 // In that case, we will just abort the transformation. 8104 APInt UsedBits(LD->getValueSizeInBits(0), 0); 8105 8106 SmallVector<LoadedSlice, 4> LoadedSlices; 8107 8108 // Check if this load is used as several smaller chunks of bits. 8109 // Basically, look for uses in trunc or trunc(lshr) and record a new chain 8110 // of computation for each trunc. 8111 for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end(); 8112 UI != UIEnd; ++UI) { 8113 // Skip the uses of the chain. 8114 if (UI.getUse().getResNo() != 0) 8115 continue; 8116 8117 SDNode *User = *UI; 8118 unsigned Shift = 0; 8119 8120 // Check if this is a trunc(lshr). 8121 if (User->getOpcode() == ISD::SRL && User->hasOneUse() && 8122 isa<ConstantSDNode>(User->getOperand(1))) { 8123 Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue(); 8124 User = *User->use_begin(); 8125 } 8126 8127 // At this point, User is a Truncate, iff we encountered, trunc or 8128 // trunc(lshr). 8129 if (User->getOpcode() != ISD::TRUNCATE) 8130 return false; 8131 8132 // The width of the type must be a power of 2 and greater than 8-bits. 8133 // Otherwise the load cannot be represented in LLVM IR. 8134 // Moreover, if we shifted with a non 8-bits multiple, the slice 8135 // will be accross several bytes. We do not support that. 8136 unsigned Width = User->getValueSizeInBits(0); 8137 if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7)) 8138 return 0; 8139 8140 // Build the slice for this chain of computations. 8141 LoadedSlice LS(User, LD, Shift, &DAG); 8142 APInt CurrentUsedBits = LS.getUsedBits(); 8143 8144 // Check if this slice overlaps with another. 8145 if ((CurrentUsedBits & UsedBits) != 0) 8146 return false; 8147 // Update the bits used globally. 8148 UsedBits |= CurrentUsedBits; 8149 8150 // Check if the new slice would be legal. 8151 if (!LS.isLegal()) 8152 return false; 8153 8154 // Record the slice. 8155 LoadedSlices.push_back(LS); 8156 } 8157 8158 // Abort slicing if it does not seem to be profitable. 8159 if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize)) 8160 return false; 8161 8162 ++SlicedLoads; 8163 8164 // Rewrite each chain to use an independent load. 8165 // By construction, each chain can be represented by a unique load. 8166 8167 // Prepare the argument for the new token factor for all the slices. 8168 SmallVector<SDValue, 8> ArgChains; 8169 for (SmallVectorImpl<LoadedSlice>::const_iterator 8170 LSIt = LoadedSlices.begin(), 8171 LSItEnd = LoadedSlices.end(); 8172 LSIt != LSItEnd; ++LSIt) { 8173 SDValue SliceInst = LSIt->loadSlice(); 8174 CombineTo(LSIt->Inst, SliceInst, true); 8175 if (SliceInst.getNode()->getOpcode() != ISD::LOAD) 8176 SliceInst = SliceInst.getOperand(0); 8177 assert(SliceInst->getOpcode() == ISD::LOAD && 8178 "It takes more than a zext to get to the loaded slice!!"); 8179 ArgChains.push_back(SliceInst.getValue(1)); 8180 } 8181 8182 SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other, 8183 &ArgChains[0], ArgChains.size()); 8184 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain); 8185 return true; 8186} 8187 8188/// CheckForMaskedLoad - Check to see if V is (and load (ptr), imm), where the 8189/// load is having specific bytes cleared out. If so, return the byte size 8190/// being masked out and the shift amount. 8191static std::pair<unsigned, unsigned> 8192CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) { 8193 std::pair<unsigned, unsigned> Result(0, 0); 8194 8195 // Check for the structure we're looking for. 8196 if (V->getOpcode() != ISD::AND || 8197 !isa<ConstantSDNode>(V->getOperand(1)) || 8198 !ISD::isNormalLoad(V->getOperand(0).getNode())) 8199 return Result; 8200 8201 // Check the chain and pointer. 8202 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0)); 8203 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer. 8204 8205 // The store should be chained directly to the load or be an operand of a 8206 // tokenfactor. 8207 if (LD == Chain.getNode()) 8208 ; // ok. 8209 else if (Chain->getOpcode() != ISD::TokenFactor) 8210 return Result; // Fail. 8211 else { 8212 bool isOk = false; 8213 for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i) 8214 if (Chain->getOperand(i).getNode() == LD) { 8215 isOk = true; 8216 break; 8217 } 8218 if (!isOk) return Result; 8219 } 8220 8221 // This only handles simple types. 8222 if (V.getValueType() != MVT::i16 && 8223 V.getValueType() != MVT::i32 && 8224 V.getValueType() != MVT::i64) 8225 return Result; 8226 8227 // Check the constant mask. Invert it so that the bits being masked out are 8228 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits 8229 // follow the sign bit for uniformity. 8230 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue(); 8231 unsigned NotMaskLZ = countLeadingZeros(NotMask); 8232 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte. 8233 unsigned NotMaskTZ = countTrailingZeros(NotMask); 8234 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte. 8235 if (NotMaskLZ == 64) return Result; // All zero mask. 8236 8237 // See if we have a continuous run of bits. If so, we have 0*1+0* 8238 if (CountTrailingOnes_64(NotMask >> NotMaskTZ)+NotMaskTZ+NotMaskLZ != 64) 8239 return Result; 8240 8241 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64. 8242 if (V.getValueType() != MVT::i64 && NotMaskLZ) 8243 NotMaskLZ -= 64-V.getValueSizeInBits(); 8244 8245 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8; 8246 switch (MaskedBytes) { 8247 case 1: 8248 case 2: 8249 case 4: break; 8250 default: return Result; // All one mask, or 5-byte mask. 8251 } 8252 8253 // Verify that the first bit starts at a multiple of mask so that the access 8254 // is aligned the same as the access width. 8255 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result; 8256 8257 Result.first = MaskedBytes; 8258 Result.second = NotMaskTZ/8; 8259 return Result; 8260} 8261 8262 8263/// ShrinkLoadReplaceStoreWithStore - Check to see if IVal is something that 8264/// provides a value as specified by MaskInfo. If so, replace the specified 8265/// store with a narrower store of truncated IVal. 8266static SDNode * 8267ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo, 8268 SDValue IVal, StoreSDNode *St, 8269 DAGCombiner *DC) { 8270 unsigned NumBytes = MaskInfo.first; 8271 unsigned ByteShift = MaskInfo.second; 8272 SelectionDAG &DAG = DC->getDAG(); 8273 8274 // Check to see if IVal is all zeros in the part being masked in by the 'or' 8275 // that uses this. If not, this is not a replacement. 8276 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(), 8277 ByteShift*8, (ByteShift+NumBytes)*8); 8278 if (!DAG.MaskedValueIsZero(IVal, Mask)) return 0; 8279 8280 // Check that it is legal on the target to do this. It is legal if the new 8281 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type 8282 // legalization. 8283 MVT VT = MVT::getIntegerVT(NumBytes*8); 8284 if (!DC->isTypeLegal(VT)) 8285 return 0; 8286 8287 // Okay, we can do this! Replace the 'St' store with a store of IVal that is 8288 // shifted by ByteShift and truncated down to NumBytes. 8289 if (ByteShift) 8290 IVal = DAG.getNode(ISD::SRL, SDLoc(IVal), IVal.getValueType(), IVal, 8291 DAG.getConstant(ByteShift*8, 8292 DC->getShiftAmountTy(IVal.getValueType()))); 8293 8294 // Figure out the offset for the store and the alignment of the access. 8295 unsigned StOffset; 8296 unsigned NewAlign = St->getAlignment(); 8297 8298 if (DAG.getTargetLoweringInfo().isLittleEndian()) 8299 StOffset = ByteShift; 8300 else 8301 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes; 8302 8303 SDValue Ptr = St->getBasePtr(); 8304 if (StOffset) { 8305 Ptr = DAG.getNode(ISD::ADD, SDLoc(IVal), Ptr.getValueType(), 8306 Ptr, DAG.getConstant(StOffset, Ptr.getValueType())); 8307 NewAlign = MinAlign(NewAlign, StOffset); 8308 } 8309 8310 // Truncate down to the new size. 8311 IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal); 8312 8313 ++OpsNarrowed; 8314 return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr, 8315 St->getPointerInfo().getWithOffset(StOffset), 8316 false, false, NewAlign).getNode(); 8317} 8318 8319 8320/// ReduceLoadOpStoreWidth - Look for sequence of load / op / store where op is 8321/// one of 'or', 'xor', and 'and' of immediates. If 'op' is only touching some 8322/// of the loaded bits, try narrowing the load and store if it would end up 8323/// being a win for performance or code size. 8324SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) { 8325 StoreSDNode *ST = cast<StoreSDNode>(N); 8326 if (ST->isVolatile()) 8327 return SDValue(); 8328 8329 SDValue Chain = ST->getChain(); 8330 SDValue Value = ST->getValue(); 8331 SDValue Ptr = ST->getBasePtr(); 8332 EVT VT = Value.getValueType(); 8333 8334 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse()) 8335 return SDValue(); 8336 8337 unsigned Opc = Value.getOpcode(); 8338 8339 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst 8340 // is a byte mask indicating a consecutive number of bytes, check to see if 8341 // Y is known to provide just those bytes. If so, we try to replace the 8342 // load + replace + store sequence with a single (narrower) store, which makes 8343 // the load dead. 8344 if (Opc == ISD::OR) { 8345 std::pair<unsigned, unsigned> MaskedLoad; 8346 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain); 8347 if (MaskedLoad.first) 8348 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad, 8349 Value.getOperand(1), ST,this)) 8350 return SDValue(NewST, 0); 8351 8352 // Or is commutative, so try swapping X and Y. 8353 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain); 8354 if (MaskedLoad.first) 8355 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad, 8356 Value.getOperand(0), ST,this)) 8357 return SDValue(NewST, 0); 8358 } 8359 8360 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) || 8361 Value.getOperand(1).getOpcode() != ISD::Constant) 8362 return SDValue(); 8363 8364 SDValue N0 = Value.getOperand(0); 8365 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() && 8366 Chain == SDValue(N0.getNode(), 1)) { 8367 LoadSDNode *LD = cast<LoadSDNode>(N0); 8368 if (LD->getBasePtr() != Ptr || 8369 LD->getPointerInfo().getAddrSpace() != 8370 ST->getPointerInfo().getAddrSpace()) 8371 return SDValue(); 8372 8373 // Find the type to narrow it the load / op / store to. 8374 SDValue N1 = Value.getOperand(1); 8375 unsigned BitWidth = N1.getValueSizeInBits(); 8376 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue(); 8377 if (Opc == ISD::AND) 8378 Imm ^= APInt::getAllOnesValue(BitWidth); 8379 if (Imm == 0 || Imm.isAllOnesValue()) 8380 return SDValue(); 8381 unsigned ShAmt = Imm.countTrailingZeros(); 8382 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1; 8383 unsigned NewBW = NextPowerOf2(MSB - ShAmt); 8384 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW); 8385 while (NewBW < BitWidth && 8386 !(TLI.isOperationLegalOrCustom(Opc, NewVT) && 8387 TLI.isNarrowingProfitable(VT, NewVT))) { 8388 NewBW = NextPowerOf2(NewBW); 8389 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW); 8390 } 8391 if (NewBW >= BitWidth) 8392 return SDValue(); 8393 8394 // If the lsb changed does not start at the type bitwidth boundary, 8395 // start at the previous one. 8396 if (ShAmt % NewBW) 8397 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW; 8398 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt, 8399 std::min(BitWidth, ShAmt + NewBW)); 8400 if ((Imm & Mask) == Imm) { 8401 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW); 8402 if (Opc == ISD::AND) 8403 NewImm ^= APInt::getAllOnesValue(NewBW); 8404 uint64_t PtrOff = ShAmt / 8; 8405 // For big endian targets, we need to adjust the offset to the pointer to 8406 // load the correct bytes. 8407 if (TLI.isBigEndian()) 8408 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff; 8409 8410 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff); 8411 Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext()); 8412 if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy)) 8413 return SDValue(); 8414 8415 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD), 8416 Ptr.getValueType(), Ptr, 8417 DAG.getConstant(PtrOff, Ptr.getValueType())); 8418 SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0), 8419 LD->getChain(), NewPtr, 8420 LD->getPointerInfo().getWithOffset(PtrOff), 8421 LD->isVolatile(), LD->isNonTemporal(), 8422 LD->isInvariant(), NewAlign, 8423 LD->getTBAAInfo()); 8424 SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD, 8425 DAG.getConstant(NewImm, NewVT)); 8426 SDValue NewST = DAG.getStore(Chain, SDLoc(N), 8427 NewVal, NewPtr, 8428 ST->getPointerInfo().getWithOffset(PtrOff), 8429 false, false, NewAlign); 8430 8431 AddToWorkList(NewPtr.getNode()); 8432 AddToWorkList(NewLD.getNode()); 8433 AddToWorkList(NewVal.getNode()); 8434 WorkListRemover DeadNodes(*this); 8435 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1)); 8436 ++OpsNarrowed; 8437 return NewST; 8438 } 8439 } 8440 8441 return SDValue(); 8442} 8443 8444/// TransformFPLoadStorePair - For a given floating point load / store pair, 8445/// if the load value isn't used by any other operations, then consider 8446/// transforming the pair to integer load / store operations if the target 8447/// deems the transformation profitable. 8448SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) { 8449 StoreSDNode *ST = cast<StoreSDNode>(N); 8450 SDValue Chain = ST->getChain(); 8451 SDValue Value = ST->getValue(); 8452 if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) && 8453 Value.hasOneUse() && 8454 Chain == SDValue(Value.getNode(), 1)) { 8455 LoadSDNode *LD = cast<LoadSDNode>(Value); 8456 EVT VT = LD->getMemoryVT(); 8457 if (!VT.isFloatingPoint() || 8458 VT != ST->getMemoryVT() || 8459 LD->isNonTemporal() || 8460 ST->isNonTemporal() || 8461 LD->getPointerInfo().getAddrSpace() != 0 || 8462 ST->getPointerInfo().getAddrSpace() != 0) 8463 return SDValue(); 8464 8465 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits()); 8466 if (!TLI.isOperationLegal(ISD::LOAD, IntVT) || 8467 !TLI.isOperationLegal(ISD::STORE, IntVT) || 8468 !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) || 8469 !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT)) 8470 return SDValue(); 8471 8472 unsigned LDAlign = LD->getAlignment(); 8473 unsigned STAlign = ST->getAlignment(); 8474 Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext()); 8475 unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy); 8476 if (LDAlign < ABIAlign || STAlign < ABIAlign) 8477 return SDValue(); 8478 8479 SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value), 8480 LD->getChain(), LD->getBasePtr(), 8481 LD->getPointerInfo(), 8482 false, false, false, LDAlign); 8483 8484 SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N), 8485 NewLD, ST->getBasePtr(), 8486 ST->getPointerInfo(), 8487 false, false, STAlign); 8488 8489 AddToWorkList(NewLD.getNode()); 8490 AddToWorkList(NewST.getNode()); 8491 WorkListRemover DeadNodes(*this); 8492 DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1)); 8493 ++LdStFP2Int; 8494 return NewST; 8495 } 8496 8497 return SDValue(); 8498} 8499 8500/// Helper struct to parse and store a memory address as base + index + offset. 8501/// We ignore sign extensions when it is safe to do so. 8502/// The following two expressions are not equivalent. To differentiate we need 8503/// to store whether there was a sign extension involved in the index 8504/// computation. 8505/// (load (i64 add (i64 copyfromreg %c) 8506/// (i64 signextend (add (i8 load %index) 8507/// (i8 1)))) 8508/// vs 8509/// 8510/// (load (i64 add (i64 copyfromreg %c) 8511/// (i64 signextend (i32 add (i32 signextend (i8 load %index)) 8512/// (i32 1))))) 8513struct BaseIndexOffset { 8514 SDValue Base; 8515 SDValue Index; 8516 int64_t Offset; 8517 bool IsIndexSignExt; 8518 8519 BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {} 8520 8521 BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset, 8522 bool IsIndexSignExt) : 8523 Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {} 8524 8525 bool equalBaseIndex(const BaseIndexOffset &Other) { 8526 return Other.Base == Base && Other.Index == Index && 8527 Other.IsIndexSignExt == IsIndexSignExt; 8528 } 8529 8530 /// Parses tree in Ptr for base, index, offset addresses. 8531 static BaseIndexOffset match(SDValue Ptr) { 8532 bool IsIndexSignExt = false; 8533 8534 // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD 8535 // instruction, then it could be just the BASE or everything else we don't 8536 // know how to handle. Just use Ptr as BASE and give up. 8537 if (Ptr->getOpcode() != ISD::ADD) 8538 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt); 8539 8540 // We know that we have at least an ADD instruction. Try to pattern match 8541 // the simple case of BASE + OFFSET. 8542 if (isa<ConstantSDNode>(Ptr->getOperand(1))) { 8543 int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue(); 8544 return BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset, 8545 IsIndexSignExt); 8546 } 8547 8548 // Inside a loop the current BASE pointer is calculated using an ADD and a 8549 // MUL instruction. In this case Ptr is the actual BASE pointer. 8550 // (i64 add (i64 %array_ptr) 8551 // (i64 mul (i64 %induction_var) 8552 // (i64 %element_size))) 8553 if (Ptr->getOperand(1)->getOpcode() == ISD::MUL) 8554 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt); 8555 8556 // Look at Base + Index + Offset cases. 8557 SDValue Base = Ptr->getOperand(0); 8558 SDValue IndexOffset = Ptr->getOperand(1); 8559 8560 // Skip signextends. 8561 if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) { 8562 IndexOffset = IndexOffset->getOperand(0); 8563 IsIndexSignExt = true; 8564 } 8565 8566 // Either the case of Base + Index (no offset) or something else. 8567 if (IndexOffset->getOpcode() != ISD::ADD) 8568 return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt); 8569 8570 // Now we have the case of Base + Index + offset. 8571 SDValue Index = IndexOffset->getOperand(0); 8572 SDValue Offset = IndexOffset->getOperand(1); 8573 8574 if (!isa<ConstantSDNode>(Offset)) 8575 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt); 8576 8577 // Ignore signextends. 8578 if (Index->getOpcode() == ISD::SIGN_EXTEND) { 8579 Index = Index->getOperand(0); 8580 IsIndexSignExt = true; 8581 } else IsIndexSignExt = false; 8582 8583 int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue(); 8584 return BaseIndexOffset(Base, Index, Off, IsIndexSignExt); 8585 } 8586}; 8587 8588/// Holds a pointer to an LSBaseSDNode as well as information on where it 8589/// is located in a sequence of memory operations connected by a chain. 8590struct MemOpLink { 8591 MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq): 8592 MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { } 8593 // Ptr to the mem node. 8594 LSBaseSDNode *MemNode; 8595 // Offset from the base ptr. 8596 int64_t OffsetFromBase; 8597 // What is the sequence number of this mem node. 8598 // Lowest mem operand in the DAG starts at zero. 8599 unsigned SequenceNum; 8600}; 8601 8602/// Sorts store nodes in a link according to their offset from a shared 8603// base ptr. 8604struct ConsecutiveMemoryChainSorter { 8605 bool operator()(MemOpLink LHS, MemOpLink RHS) { 8606 return LHS.OffsetFromBase < RHS.OffsetFromBase; 8607 } 8608}; 8609 8610bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) { 8611 EVT MemVT = St->getMemoryVT(); 8612 int64_t ElementSizeBytes = MemVT.getSizeInBits()/8; 8613 bool NoVectors = DAG.getMachineFunction().getFunction()->getAttributes(). 8614 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat); 8615 8616 // Don't merge vectors into wider inputs. 8617 if (MemVT.isVector() || !MemVT.isSimple()) 8618 return false; 8619 8620 // Perform an early exit check. Do not bother looking at stored values that 8621 // are not constants or loads. 8622 SDValue StoredVal = St->getValue(); 8623 bool IsLoadSrc = isa<LoadSDNode>(StoredVal); 8624 if (!isa<ConstantSDNode>(StoredVal) && !isa<ConstantFPSDNode>(StoredVal) && 8625 !IsLoadSrc) 8626 return false; 8627 8628 // Only look at ends of store sequences. 8629 SDValue Chain = SDValue(St, 1); 8630 if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE) 8631 return false; 8632 8633 // This holds the base pointer, index, and the offset in bytes from the base 8634 // pointer. 8635 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr()); 8636 8637 // We must have a base and an offset. 8638 if (!BasePtr.Base.getNode()) 8639 return false; 8640 8641 // Do not handle stores to undef base pointers. 8642 if (BasePtr.Base.getOpcode() == ISD::UNDEF) 8643 return false; 8644 8645 // Save the LoadSDNodes that we find in the chain. 8646 // We need to make sure that these nodes do not interfere with 8647 // any of the store nodes. 8648 SmallVector<LSBaseSDNode*, 8> AliasLoadNodes; 8649 8650 // Save the StoreSDNodes that we find in the chain. 8651 SmallVector<MemOpLink, 8> StoreNodes; 8652 8653 // Walk up the chain and look for nodes with offsets from the same 8654 // base pointer. Stop when reaching an instruction with a different kind 8655 // or instruction which has a different base pointer. 8656 unsigned Seq = 0; 8657 StoreSDNode *Index = St; 8658 while (Index) { 8659 // If the chain has more than one use, then we can't reorder the mem ops. 8660 if (Index != St && !SDValue(Index, 1)->hasOneUse()) 8661 break; 8662 8663 // Find the base pointer and offset for this memory node. 8664 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr()); 8665 8666 // Check that the base pointer is the same as the original one. 8667 if (!Ptr.equalBaseIndex(BasePtr)) 8668 break; 8669 8670 // Check that the alignment is the same. 8671 if (Index->getAlignment() != St->getAlignment()) 8672 break; 8673 8674 // The memory operands must not be volatile. 8675 if (Index->isVolatile() || Index->isIndexed()) 8676 break; 8677 8678 // No truncation. 8679 if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index)) 8680 if (St->isTruncatingStore()) 8681 break; 8682 8683 // The stored memory type must be the same. 8684 if (Index->getMemoryVT() != MemVT) 8685 break; 8686 8687 // We do not allow unaligned stores because we want to prevent overriding 8688 // stores. 8689 if (Index->getAlignment()*8 != MemVT.getSizeInBits()) 8690 break; 8691 8692 // We found a potential memory operand to merge. 8693 StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++)); 8694 8695 // Find the next memory operand in the chain. If the next operand in the 8696 // chain is a store then move up and continue the scan with the next 8697 // memory operand. If the next operand is a load save it and use alias 8698 // information to check if it interferes with anything. 8699 SDNode *NextInChain = Index->getChain().getNode(); 8700 while (1) { 8701 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) { 8702 // We found a store node. Use it for the next iteration. 8703 Index = STn; 8704 break; 8705 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) { 8706 if (Ldn->isVolatile()) { 8707 Index = NULL; 8708 break; 8709 } 8710 8711 // Save the load node for later. Continue the scan. 8712 AliasLoadNodes.push_back(Ldn); 8713 NextInChain = Ldn->getChain().getNode(); 8714 continue; 8715 } else { 8716 Index = NULL; 8717 break; 8718 } 8719 } 8720 } 8721 8722 // Check if there is anything to merge. 8723 if (StoreNodes.size() < 2) 8724 return false; 8725 8726 // Sort the memory operands according to their distance from the base pointer. 8727 std::sort(StoreNodes.begin(), StoreNodes.end(), 8728 ConsecutiveMemoryChainSorter()); 8729 8730 // Scan the memory operations on the chain and find the first non-consecutive 8731 // store memory address. 8732 unsigned LastConsecutiveStore = 0; 8733 int64_t StartAddress = StoreNodes[0].OffsetFromBase; 8734 for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) { 8735 8736 // Check that the addresses are consecutive starting from the second 8737 // element in the list of stores. 8738 if (i > 0) { 8739 int64_t CurrAddress = StoreNodes[i].OffsetFromBase; 8740 if (CurrAddress - StartAddress != (ElementSizeBytes * i)) 8741 break; 8742 } 8743 8744 bool Alias = false; 8745 // Check if this store interferes with any of the loads that we found. 8746 for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld) 8747 if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) { 8748 Alias = true; 8749 break; 8750 } 8751 // We found a load that alias with this store. Stop the sequence. 8752 if (Alias) 8753 break; 8754 8755 // Mark this node as useful. 8756 LastConsecutiveStore = i; 8757 } 8758 8759 // The node with the lowest store address. 8760 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode; 8761 8762 // Store the constants into memory as one consecutive store. 8763 if (!IsLoadSrc) { 8764 unsigned LastLegalType = 0; 8765 unsigned LastLegalVectorType = 0; 8766 bool NonZero = false; 8767 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) { 8768 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 8769 SDValue StoredVal = St->getValue(); 8770 8771 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) { 8772 NonZero |= !C->isNullValue(); 8773 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) { 8774 NonZero |= !C->getConstantFPValue()->isNullValue(); 8775 } else { 8776 // Non constant. 8777 break; 8778 } 8779 8780 // Find a legal type for the constant store. 8781 unsigned StoreBW = (i+1) * ElementSizeBytes * 8; 8782 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW); 8783 if (TLI.isTypeLegal(StoreTy)) 8784 LastLegalType = i+1; 8785 // Or check whether a truncstore is legal. 8786 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) == 8787 TargetLowering::TypePromoteInteger) { 8788 EVT LegalizedStoredValueTy = 8789 TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType()); 8790 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy)) 8791 LastLegalType = i+1; 8792 } 8793 8794 // Find a legal type for the vector store. 8795 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1); 8796 if (TLI.isTypeLegal(Ty)) 8797 LastLegalVectorType = i + 1; 8798 } 8799 8800 // We only use vectors if the constant is known to be zero and the 8801 // function is not marked with the noimplicitfloat attribute. 8802 if (NonZero || NoVectors) 8803 LastLegalVectorType = 0; 8804 8805 // Check if we found a legal integer type to store. 8806 if (LastLegalType == 0 && LastLegalVectorType == 0) 8807 return false; 8808 8809 bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors; 8810 unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType; 8811 8812 // Make sure we have something to merge. 8813 if (NumElem < 2) 8814 return false; 8815 8816 unsigned EarliestNodeUsed = 0; 8817 for (unsigned i=0; i < NumElem; ++i) { 8818 // Find a chain for the new wide-store operand. Notice that some 8819 // of the store nodes that we found may not be selected for inclusion 8820 // in the wide store. The chain we use needs to be the chain of the 8821 // earliest store node which is *used* and replaced by the wide store. 8822 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum) 8823 EarliestNodeUsed = i; 8824 } 8825 8826 // The earliest Node in the DAG. 8827 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode; 8828 SDLoc DL(StoreNodes[0].MemNode); 8829 8830 SDValue StoredVal; 8831 if (UseVector) { 8832 // Find a legal type for the vector store. 8833 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem); 8834 assert(TLI.isTypeLegal(Ty) && "Illegal vector store"); 8835 StoredVal = DAG.getConstant(0, Ty); 8836 } else { 8837 unsigned StoreBW = NumElem * ElementSizeBytes * 8; 8838 APInt StoreInt(StoreBW, 0); 8839 8840 // Construct a single integer constant which is made of the smaller 8841 // constant inputs. 8842 bool IsLE = TLI.isLittleEndian(); 8843 for (unsigned i = 0; i < NumElem ; ++i) { 8844 unsigned Idx = IsLE ?(NumElem - 1 - i) : i; 8845 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[Idx].MemNode); 8846 SDValue Val = St->getValue(); 8847 StoreInt<<=ElementSizeBytes*8; 8848 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) { 8849 StoreInt|=C->getAPIntValue().zext(StoreBW); 8850 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) { 8851 StoreInt|= C->getValueAPF().bitcastToAPInt().zext(StoreBW); 8852 } else { 8853 assert(false && "Invalid constant element type"); 8854 } 8855 } 8856 8857 // Create the new Load and Store operations. 8858 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW); 8859 StoredVal = DAG.getConstant(StoreInt, StoreTy); 8860 } 8861 8862 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), DL, StoredVal, 8863 FirstInChain->getBasePtr(), 8864 FirstInChain->getPointerInfo(), 8865 false, false, 8866 FirstInChain->getAlignment()); 8867 8868 // Replace the first store with the new store 8869 CombineTo(EarliestOp, NewStore); 8870 // Erase all other stores. 8871 for (unsigned i = 0; i < NumElem ; ++i) { 8872 if (StoreNodes[i].MemNode == EarliestOp) 8873 continue; 8874 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 8875 // ReplaceAllUsesWith will replace all uses that existed when it was 8876 // called, but graph optimizations may cause new ones to appear. For 8877 // example, the case in pr14333 looks like 8878 // 8879 // St's chain -> St -> another store -> X 8880 // 8881 // And the only difference from St to the other store is the chain. 8882 // When we change it's chain to be St's chain they become identical, 8883 // get CSEed and the net result is that X is now a use of St. 8884 // Since we know that St is redundant, just iterate. 8885 while (!St->use_empty()) 8886 DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain()); 8887 removeFromWorkList(St); 8888 DAG.DeleteNode(St); 8889 } 8890 8891 return true; 8892 } 8893 8894 // Below we handle the case of multiple consecutive stores that 8895 // come from multiple consecutive loads. We merge them into a single 8896 // wide load and a single wide store. 8897 8898 // Look for load nodes which are used by the stored values. 8899 SmallVector<MemOpLink, 8> LoadNodes; 8900 8901 // Find acceptable loads. Loads need to have the same chain (token factor), 8902 // must not be zext, volatile, indexed, and they must be consecutive. 8903 BaseIndexOffset LdBasePtr; 8904 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) { 8905 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 8906 LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue()); 8907 if (!Ld) break; 8908 8909 // Loads must only have one use. 8910 if (!Ld->hasNUsesOfValue(1, 0)) 8911 break; 8912 8913 // Check that the alignment is the same as the stores. 8914 if (Ld->getAlignment() != St->getAlignment()) 8915 break; 8916 8917 // The memory operands must not be volatile. 8918 if (Ld->isVolatile() || Ld->isIndexed()) 8919 break; 8920 8921 // We do not accept ext loads. 8922 if (Ld->getExtensionType() != ISD::NON_EXTLOAD) 8923 break; 8924 8925 // The stored memory type must be the same. 8926 if (Ld->getMemoryVT() != MemVT) 8927 break; 8928 8929 BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr()); 8930 // If this is not the first ptr that we check. 8931 if (LdBasePtr.Base.getNode()) { 8932 // The base ptr must be the same. 8933 if (!LdPtr.equalBaseIndex(LdBasePtr)) 8934 break; 8935 } else { 8936 // Check that all other base pointers are the same as this one. 8937 LdBasePtr = LdPtr; 8938 } 8939 8940 // We found a potential memory operand to merge. 8941 LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0)); 8942 } 8943 8944 if (LoadNodes.size() < 2) 8945 return false; 8946 8947 // Scan the memory operations on the chain and find the first non-consecutive 8948 // load memory address. These variables hold the index in the store node 8949 // array. 8950 unsigned LastConsecutiveLoad = 0; 8951 // This variable refers to the size and not index in the array. 8952 unsigned LastLegalVectorType = 0; 8953 unsigned LastLegalIntegerType = 0; 8954 StartAddress = LoadNodes[0].OffsetFromBase; 8955 SDValue FirstChain = LoadNodes[0].MemNode->getChain(); 8956 for (unsigned i = 1; i < LoadNodes.size(); ++i) { 8957 // All loads much share the same chain. 8958 if (LoadNodes[i].MemNode->getChain() != FirstChain) 8959 break; 8960 8961 int64_t CurrAddress = LoadNodes[i].OffsetFromBase; 8962 if (CurrAddress - StartAddress != (ElementSizeBytes * i)) 8963 break; 8964 LastConsecutiveLoad = i; 8965 8966 // Find a legal type for the vector store. 8967 EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1); 8968 if (TLI.isTypeLegal(StoreTy)) 8969 LastLegalVectorType = i + 1; 8970 8971 // Find a legal type for the integer store. 8972 unsigned StoreBW = (i+1) * ElementSizeBytes * 8; 8973 StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW); 8974 if (TLI.isTypeLegal(StoreTy)) 8975 LastLegalIntegerType = i + 1; 8976 // Or check whether a truncstore and extload is legal. 8977 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) == 8978 TargetLowering::TypePromoteInteger) { 8979 EVT LegalizedStoredValueTy = 8980 TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy); 8981 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) && 8982 TLI.isLoadExtLegal(ISD::ZEXTLOAD, StoreTy) && 8983 TLI.isLoadExtLegal(ISD::SEXTLOAD, StoreTy) && 8984 TLI.isLoadExtLegal(ISD::EXTLOAD, StoreTy)) 8985 LastLegalIntegerType = i+1; 8986 } 8987 } 8988 8989 // Only use vector types if the vector type is larger than the integer type. 8990 // If they are the same, use integers. 8991 bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors; 8992 unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType); 8993 8994 // We add +1 here because the LastXXX variables refer to location while 8995 // the NumElem refers to array/index size. 8996 unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1; 8997 NumElem = std::min(LastLegalType, NumElem); 8998 8999 if (NumElem < 2) 9000 return false; 9001 9002 // The earliest Node in the DAG. 9003 unsigned EarliestNodeUsed = 0; 9004 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode; 9005 for (unsigned i=1; i<NumElem; ++i) { 9006 // Find a chain for the new wide-store operand. Notice that some 9007 // of the store nodes that we found may not be selected for inclusion 9008 // in the wide store. The chain we use needs to be the chain of the 9009 // earliest store node which is *used* and replaced by the wide store. 9010 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum) 9011 EarliestNodeUsed = i; 9012 } 9013 9014 // Find if it is better to use vectors or integers to load and store 9015 // to memory. 9016 EVT JointMemOpVT; 9017 if (UseVectorTy) { 9018 JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem); 9019 } else { 9020 unsigned StoreBW = NumElem * ElementSizeBytes * 8; 9021 JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW); 9022 } 9023 9024 SDLoc LoadDL(LoadNodes[0].MemNode); 9025 SDLoc StoreDL(StoreNodes[0].MemNode); 9026 9027 LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode); 9028 SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL, 9029 FirstLoad->getChain(), 9030 FirstLoad->getBasePtr(), 9031 FirstLoad->getPointerInfo(), 9032 false, false, false, 9033 FirstLoad->getAlignment()); 9034 9035 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), StoreDL, NewLoad, 9036 FirstInChain->getBasePtr(), 9037 FirstInChain->getPointerInfo(), false, false, 9038 FirstInChain->getAlignment()); 9039 9040 // Replace one of the loads with the new load. 9041 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode); 9042 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), 9043 SDValue(NewLoad.getNode(), 1)); 9044 9045 // Remove the rest of the load chains. 9046 for (unsigned i = 1; i < NumElem ; ++i) { 9047 // Replace all chain users of the old load nodes with the chain of the new 9048 // load node. 9049 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode); 9050 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain()); 9051 } 9052 9053 // Replace the first store with the new store. 9054 CombineTo(EarliestOp, NewStore); 9055 // Erase all other stores. 9056 for (unsigned i = 0; i < NumElem ; ++i) { 9057 // Remove all Store nodes. 9058 if (StoreNodes[i].MemNode == EarliestOp) 9059 continue; 9060 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 9061 DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain()); 9062 removeFromWorkList(St); 9063 DAG.DeleteNode(St); 9064 } 9065 9066 return true; 9067} 9068 9069SDValue DAGCombiner::visitSTORE(SDNode *N) { 9070 StoreSDNode *ST = cast<StoreSDNode>(N); 9071 SDValue Chain = ST->getChain(); 9072 SDValue Value = ST->getValue(); 9073 SDValue Ptr = ST->getBasePtr(); 9074 9075 // If this is a store of a bit convert, store the input value if the 9076 // resultant store does not need a higher alignment than the original. 9077 if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() && 9078 ST->isUnindexed()) { 9079 unsigned OrigAlign = ST->getAlignment(); 9080 EVT SVT = Value.getOperand(0).getValueType(); 9081 unsigned Align = TLI.getDataLayout()-> 9082 getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext())); 9083 if (Align <= OrigAlign && 9084 ((!LegalOperations && !ST->isVolatile()) || 9085 TLI.isOperationLegalOrCustom(ISD::STORE, SVT))) 9086 return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0), 9087 Ptr, ST->getPointerInfo(), ST->isVolatile(), 9088 ST->isNonTemporal(), OrigAlign, 9089 ST->getTBAAInfo()); 9090 } 9091 9092 // Turn 'store undef, Ptr' -> nothing. 9093 if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed()) 9094 return Chain; 9095 9096 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr' 9097 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) { 9098 // NOTE: If the original store is volatile, this transform must not increase 9099 // the number of stores. For example, on x86-32 an f64 can be stored in one 9100 // processor operation but an i64 (which is not legal) requires two. So the 9101 // transform should not be done in this case. 9102 if (Value.getOpcode() != ISD::TargetConstantFP) { 9103 SDValue Tmp; 9104 switch (CFP->getSimpleValueType(0).SimpleTy) { 9105 default: llvm_unreachable("Unknown FP type"); 9106 case MVT::f16: // We don't do this for these yet. 9107 case MVT::f80: 9108 case MVT::f128: 9109 case MVT::ppcf128: 9110 break; 9111 case MVT::f32: 9112 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) || 9113 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) { 9114 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF(). 9115 bitcastToAPInt().getZExtValue(), MVT::i32); 9116 return DAG.getStore(Chain, SDLoc(N), Tmp, 9117 Ptr, ST->getMemOperand()); 9118 } 9119 break; 9120 case MVT::f64: 9121 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations && 9122 !ST->isVolatile()) || 9123 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) { 9124 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt(). 9125 getZExtValue(), MVT::i64); 9126 return DAG.getStore(Chain, SDLoc(N), Tmp, 9127 Ptr, ST->getMemOperand()); 9128 } 9129 9130 if (!ST->isVolatile() && 9131 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) { 9132 // Many FP stores are not made apparent until after legalize, e.g. for 9133 // argument passing. Since this is so common, custom legalize the 9134 // 64-bit integer store into two 32-bit stores. 9135 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue(); 9136 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32); 9137 SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32); 9138 if (TLI.isBigEndian()) std::swap(Lo, Hi); 9139 9140 unsigned Alignment = ST->getAlignment(); 9141 bool isVolatile = ST->isVolatile(); 9142 bool isNonTemporal = ST->isNonTemporal(); 9143 const MDNode *TBAAInfo = ST->getTBAAInfo(); 9144 9145 SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo, 9146 Ptr, ST->getPointerInfo(), 9147 isVolatile, isNonTemporal, 9148 ST->getAlignment(), TBAAInfo); 9149 Ptr = DAG.getNode(ISD::ADD, SDLoc(N), Ptr.getValueType(), Ptr, 9150 DAG.getConstant(4, Ptr.getValueType())); 9151 Alignment = MinAlign(Alignment, 4U); 9152 SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi, 9153 Ptr, ST->getPointerInfo().getWithOffset(4), 9154 isVolatile, isNonTemporal, 9155 Alignment, TBAAInfo); 9156 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, 9157 St0, St1); 9158 } 9159 9160 break; 9161 } 9162 } 9163 } 9164 9165 // Try to infer better alignment information than the store already has. 9166 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) { 9167 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) { 9168 if (Align > ST->getAlignment()) 9169 return DAG.getTruncStore(Chain, SDLoc(N), Value, 9170 Ptr, ST->getPointerInfo(), ST->getMemoryVT(), 9171 ST->isVolatile(), ST->isNonTemporal(), Align, 9172 ST->getTBAAInfo()); 9173 } 9174 } 9175 9176 // Try transforming a pair floating point load / store ops to integer 9177 // load / store ops. 9178 SDValue NewST = TransformFPLoadStorePair(N); 9179 if (NewST.getNode()) 9180 return NewST; 9181 9182 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA : 9183 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA(); 9184 if (UseAA) { 9185 // Walk up chain skipping non-aliasing memory nodes. 9186 SDValue BetterChain = FindBetterChain(N, Chain); 9187 9188 // If there is a better chain. 9189 if (Chain != BetterChain) { 9190 SDValue ReplStore; 9191 9192 // Replace the chain to avoid dependency. 9193 if (ST->isTruncatingStore()) { 9194 ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr, 9195 ST->getMemoryVT(), ST->getMemOperand()); 9196 } else { 9197 ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr, 9198 ST->getMemOperand()); 9199 } 9200 9201 // Create token to keep both nodes around. 9202 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N), 9203 MVT::Other, Chain, ReplStore); 9204 9205 // Make sure the new and old chains are cleaned up. 9206 AddToWorkList(Token.getNode()); 9207 9208 // Don't add users to work list. 9209 return CombineTo(N, Token, false); 9210 } 9211 } 9212 9213 // Try transforming N to an indexed store. 9214 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N)) 9215 return SDValue(N, 0); 9216 9217 // FIXME: is there such a thing as a truncating indexed store? 9218 if (ST->isTruncatingStore() && ST->isUnindexed() && 9219 Value.getValueType().isInteger()) { 9220 // See if we can simplify the input to this truncstore with knowledge that 9221 // only the low bits are being used. For example: 9222 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8" 9223 SDValue Shorter = 9224 GetDemandedBits(Value, 9225 APInt::getLowBitsSet( 9226 Value.getValueType().getScalarType().getSizeInBits(), 9227 ST->getMemoryVT().getScalarType().getSizeInBits())); 9228 AddToWorkList(Value.getNode()); 9229 if (Shorter.getNode()) 9230 return DAG.getTruncStore(Chain, SDLoc(N), Shorter, 9231 Ptr, ST->getMemoryVT(), ST->getMemOperand()); 9232 9233 // Otherwise, see if we can simplify the operation with 9234 // SimplifyDemandedBits, which only works if the value has a single use. 9235 if (SimplifyDemandedBits(Value, 9236 APInt::getLowBitsSet( 9237 Value.getValueType().getScalarType().getSizeInBits(), 9238 ST->getMemoryVT().getScalarType().getSizeInBits()))) 9239 return SDValue(N, 0); 9240 } 9241 9242 // If this is a load followed by a store to the same location, then the store 9243 // is dead/noop. 9244 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) { 9245 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() && 9246 ST->isUnindexed() && !ST->isVolatile() && 9247 // There can't be any side effects between the load and store, such as 9248 // a call or store. 9249 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) { 9250 // The store is dead, remove it. 9251 return Chain; 9252 } 9253 } 9254 9255 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a 9256 // truncating store. We can do this even if this is already a truncstore. 9257 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE) 9258 && Value.getNode()->hasOneUse() && ST->isUnindexed() && 9259 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(), 9260 ST->getMemoryVT())) { 9261 return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0), 9262 Ptr, ST->getMemoryVT(), ST->getMemOperand()); 9263 } 9264 9265 // Only perform this optimization before the types are legal, because we 9266 // don't want to perform this optimization on every DAGCombine invocation. 9267 if (!LegalTypes) { 9268 bool EverChanged = false; 9269 9270 do { 9271 // There can be multiple store sequences on the same chain. 9272 // Keep trying to merge store sequences until we are unable to do so 9273 // or until we merge the last store on the chain. 9274 bool Changed = MergeConsecutiveStores(ST); 9275 EverChanged |= Changed; 9276 if (!Changed) break; 9277 } while (ST->getOpcode() != ISD::DELETED_NODE); 9278 9279 if (EverChanged) 9280 return SDValue(N, 0); 9281 } 9282 9283 return ReduceLoadOpStoreWidth(N); 9284} 9285 9286SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) { 9287 SDValue InVec = N->getOperand(0); 9288 SDValue InVal = N->getOperand(1); 9289 SDValue EltNo = N->getOperand(2); 9290 SDLoc dl(N); 9291 9292 // If the inserted element is an UNDEF, just use the input vector. 9293 if (InVal.getOpcode() == ISD::UNDEF) 9294 return InVec; 9295 9296 EVT VT = InVec.getValueType(); 9297 9298 // If we can't generate a legal BUILD_VECTOR, exit 9299 if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT)) 9300 return SDValue(); 9301 9302 // Check that we know which element is being inserted 9303 if (!isa<ConstantSDNode>(EltNo)) 9304 return SDValue(); 9305 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue(); 9306 9307 // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially 9308 // be converted to a BUILD_VECTOR). Fill in the Ops vector with the 9309 // vector elements. 9310 SmallVector<SDValue, 8> Ops; 9311 // Do not combine these two vectors if the output vector will not replace 9312 // the input vector. 9313 if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) { 9314 Ops.append(InVec.getNode()->op_begin(), 9315 InVec.getNode()->op_end()); 9316 } else if (InVec.getOpcode() == ISD::UNDEF) { 9317 unsigned NElts = VT.getVectorNumElements(); 9318 Ops.append(NElts, DAG.getUNDEF(InVal.getValueType())); 9319 } else { 9320 return SDValue(); 9321 } 9322 9323 // Insert the element 9324 if (Elt < Ops.size()) { 9325 // All the operands of BUILD_VECTOR must have the same type; 9326 // we enforce that here. 9327 EVT OpVT = Ops[0].getValueType(); 9328 if (InVal.getValueType() != OpVT) 9329 InVal = OpVT.bitsGT(InVal.getValueType()) ? 9330 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) : 9331 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal); 9332 Ops[Elt] = InVal; 9333 } 9334 9335 // Return the new vector 9336 return DAG.getNode(ISD::BUILD_VECTOR, dl, 9337 VT, &Ops[0], Ops.size()); 9338} 9339 9340SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) { 9341 // (vextract (scalar_to_vector val, 0) -> val 9342 SDValue InVec = N->getOperand(0); 9343 EVT VT = InVec.getValueType(); 9344 EVT NVT = N->getValueType(0); 9345 9346 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) { 9347 // Check if the result type doesn't match the inserted element type. A 9348 // SCALAR_TO_VECTOR may truncate the inserted element and the 9349 // EXTRACT_VECTOR_ELT may widen the extracted vector. 9350 SDValue InOp = InVec.getOperand(0); 9351 if (InOp.getValueType() != NVT) { 9352 assert(InOp.getValueType().isInteger() && NVT.isInteger()); 9353 return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT); 9354 } 9355 return InOp; 9356 } 9357 9358 SDValue EltNo = N->getOperand(1); 9359 bool ConstEltNo = isa<ConstantSDNode>(EltNo); 9360 9361 // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT. 9362 // We only perform this optimization before the op legalization phase because 9363 // we may introduce new vector instructions which are not backed by TD 9364 // patterns. For example on AVX, extracting elements from a wide vector 9365 // without using extract_subvector. 9366 if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE 9367 && ConstEltNo && !LegalOperations) { 9368 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue(); 9369 int NumElem = VT.getVectorNumElements(); 9370 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec); 9371 // Find the new index to extract from. 9372 int OrigElt = SVOp->getMaskElt(Elt); 9373 9374 // Extracting an undef index is undef. 9375 if (OrigElt == -1) 9376 return DAG.getUNDEF(NVT); 9377 9378 // Select the right vector half to extract from. 9379 if (OrigElt < NumElem) { 9380 InVec = InVec->getOperand(0); 9381 } else { 9382 InVec = InVec->getOperand(1); 9383 OrigElt -= NumElem; 9384 } 9385 9386 EVT IndexTy = TLI.getVectorIdxTy(); 9387 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT, 9388 InVec, DAG.getConstant(OrigElt, IndexTy)); 9389 } 9390 9391 // Perform only after legalization to ensure build_vector / vector_shuffle 9392 // optimizations have already been done. 9393 if (!LegalOperations) return SDValue(); 9394 9395 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size) 9396 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size) 9397 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr) 9398 9399 if (ConstEltNo) { 9400 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue(); 9401 bool NewLoad = false; 9402 bool BCNumEltsChanged = false; 9403 EVT ExtVT = VT.getVectorElementType(); 9404 EVT LVT = ExtVT; 9405 9406 // If the result of load has to be truncated, then it's not necessarily 9407 // profitable. 9408 if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT)) 9409 return SDValue(); 9410 9411 if (InVec.getOpcode() == ISD::BITCAST) { 9412 // Don't duplicate a load with other uses. 9413 if (!InVec.hasOneUse()) 9414 return SDValue(); 9415 9416 EVT BCVT = InVec.getOperand(0).getValueType(); 9417 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType())) 9418 return SDValue(); 9419 if (VT.getVectorNumElements() != BCVT.getVectorNumElements()) 9420 BCNumEltsChanged = true; 9421 InVec = InVec.getOperand(0); 9422 ExtVT = BCVT.getVectorElementType(); 9423 NewLoad = true; 9424 } 9425 9426 LoadSDNode *LN0 = NULL; 9427 const ShuffleVectorSDNode *SVN = NULL; 9428 if (ISD::isNormalLoad(InVec.getNode())) { 9429 LN0 = cast<LoadSDNode>(InVec); 9430 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR && 9431 InVec.getOperand(0).getValueType() == ExtVT && 9432 ISD::isNormalLoad(InVec.getOperand(0).getNode())) { 9433 // Don't duplicate a load with other uses. 9434 if (!InVec.hasOneUse()) 9435 return SDValue(); 9436 9437 LN0 = cast<LoadSDNode>(InVec.getOperand(0)); 9438 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) { 9439 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1) 9440 // => 9441 // (load $addr+1*size) 9442 9443 // Don't duplicate a load with other uses. 9444 if (!InVec.hasOneUse()) 9445 return SDValue(); 9446 9447 // If the bit convert changed the number of elements, it is unsafe 9448 // to examine the mask. 9449 if (BCNumEltsChanged) 9450 return SDValue(); 9451 9452 // Select the input vector, guarding against out of range extract vector. 9453 unsigned NumElems = VT.getVectorNumElements(); 9454 int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt); 9455 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1); 9456 9457 if (InVec.getOpcode() == ISD::BITCAST) { 9458 // Don't duplicate a load with other uses. 9459 if (!InVec.hasOneUse()) 9460 return SDValue(); 9461 9462 InVec = InVec.getOperand(0); 9463 } 9464 if (ISD::isNormalLoad(InVec.getNode())) { 9465 LN0 = cast<LoadSDNode>(InVec); 9466 Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems; 9467 } 9468 } 9469 9470 // Make sure we found a non-volatile load and the extractelement is 9471 // the only use. 9472 if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile()) 9473 return SDValue(); 9474 9475 // If Idx was -1 above, Elt is going to be -1, so just return undef. 9476 if (Elt == -1) 9477 return DAG.getUNDEF(LVT); 9478 9479 unsigned Align = LN0->getAlignment(); 9480 if (NewLoad) { 9481 // Check the resultant load doesn't need a higher alignment than the 9482 // original load. 9483 unsigned NewAlign = 9484 TLI.getDataLayout() 9485 ->getABITypeAlignment(LVT.getTypeForEVT(*DAG.getContext())); 9486 9487 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, LVT)) 9488 return SDValue(); 9489 9490 Align = NewAlign; 9491 } 9492 9493 SDValue NewPtr = LN0->getBasePtr(); 9494 unsigned PtrOff = 0; 9495 9496 if (Elt) { 9497 PtrOff = LVT.getSizeInBits() * Elt / 8; 9498 EVT PtrType = NewPtr.getValueType(); 9499 if (TLI.isBigEndian()) 9500 PtrOff = VT.getSizeInBits() / 8 - PtrOff; 9501 NewPtr = DAG.getNode(ISD::ADD, SDLoc(N), PtrType, NewPtr, 9502 DAG.getConstant(PtrOff, PtrType)); 9503 } 9504 9505 // The replacement we need to do here is a little tricky: we need to 9506 // replace an extractelement of a load with a load. 9507 // Use ReplaceAllUsesOfValuesWith to do the replacement. 9508 // Note that this replacement assumes that the extractvalue is the only 9509 // use of the load; that's okay because we don't want to perform this 9510 // transformation in other cases anyway. 9511 SDValue Load; 9512 SDValue Chain; 9513 if (NVT.bitsGT(LVT)) { 9514 // If the result type of vextract is wider than the load, then issue an 9515 // extending load instead. 9516 ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, LVT) 9517 ? ISD::ZEXTLOAD : ISD::EXTLOAD; 9518 Load = DAG.getExtLoad(ExtType, SDLoc(N), NVT, LN0->getChain(), 9519 NewPtr, LN0->getPointerInfo().getWithOffset(PtrOff), 9520 LVT, LN0->isVolatile(), LN0->isNonTemporal(), 9521 Align, LN0->getTBAAInfo()); 9522 Chain = Load.getValue(1); 9523 } else { 9524 Load = DAG.getLoad(LVT, SDLoc(N), LN0->getChain(), NewPtr, 9525 LN0->getPointerInfo().getWithOffset(PtrOff), 9526 LN0->isVolatile(), LN0->isNonTemporal(), 9527 LN0->isInvariant(), Align, LN0->getTBAAInfo()); 9528 Chain = Load.getValue(1); 9529 if (NVT.bitsLT(LVT)) 9530 Load = DAG.getNode(ISD::TRUNCATE, SDLoc(N), NVT, Load); 9531 else 9532 Load = DAG.getNode(ISD::BITCAST, SDLoc(N), NVT, Load); 9533 } 9534 WorkListRemover DeadNodes(*this); 9535 SDValue From[] = { SDValue(N, 0), SDValue(LN0,1) }; 9536 SDValue To[] = { Load, Chain }; 9537 DAG.ReplaceAllUsesOfValuesWith(From, To, 2); 9538 // Since we're explcitly calling ReplaceAllUses, add the new node to the 9539 // worklist explicitly as well. 9540 AddToWorkList(Load.getNode()); 9541 AddUsersToWorkList(Load.getNode()); // Add users too 9542 // Make sure to revisit this node to clean it up; it will usually be dead. 9543 AddToWorkList(N); 9544 return SDValue(N, 0); 9545 } 9546 9547 return SDValue(); 9548} 9549 9550// Simplify (build_vec (ext )) to (bitcast (build_vec )) 9551SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) { 9552 // We perform this optimization post type-legalization because 9553 // the type-legalizer often scalarizes integer-promoted vectors. 9554 // Performing this optimization before may create bit-casts which 9555 // will be type-legalized to complex code sequences. 9556 // We perform this optimization only before the operation legalizer because we 9557 // may introduce illegal operations. 9558 if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes) 9559 return SDValue(); 9560 9561 unsigned NumInScalars = N->getNumOperands(); 9562 SDLoc dl(N); 9563 EVT VT = N->getValueType(0); 9564 9565 // Check to see if this is a BUILD_VECTOR of a bunch of values 9566 // which come from any_extend or zero_extend nodes. If so, we can create 9567 // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR 9568 // optimizations. We do not handle sign-extend because we can't fill the sign 9569 // using shuffles. 9570 EVT SourceType = MVT::Other; 9571 bool AllAnyExt = true; 9572 9573 for (unsigned i = 0; i != NumInScalars; ++i) { 9574 SDValue In = N->getOperand(i); 9575 // Ignore undef inputs. 9576 if (In.getOpcode() == ISD::UNDEF) continue; 9577 9578 bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND; 9579 bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND; 9580 9581 // Abort if the element is not an extension. 9582 if (!ZeroExt && !AnyExt) { 9583 SourceType = MVT::Other; 9584 break; 9585 } 9586 9587 // The input is a ZeroExt or AnyExt. Check the original type. 9588 EVT InTy = In.getOperand(0).getValueType(); 9589 9590 // Check that all of the widened source types are the same. 9591 if (SourceType == MVT::Other) 9592 // First time. 9593 SourceType = InTy; 9594 else if (InTy != SourceType) { 9595 // Multiple income types. Abort. 9596 SourceType = MVT::Other; 9597 break; 9598 } 9599 9600 // Check if all of the extends are ANY_EXTENDs. 9601 AllAnyExt &= AnyExt; 9602 } 9603 9604 // In order to have valid types, all of the inputs must be extended from the 9605 // same source type and all of the inputs must be any or zero extend. 9606 // Scalar sizes must be a power of two. 9607 EVT OutScalarTy = VT.getScalarType(); 9608 bool ValidTypes = SourceType != MVT::Other && 9609 isPowerOf2_32(OutScalarTy.getSizeInBits()) && 9610 isPowerOf2_32(SourceType.getSizeInBits()); 9611 9612 // Create a new simpler BUILD_VECTOR sequence which other optimizations can 9613 // turn into a single shuffle instruction. 9614 if (!ValidTypes) 9615 return SDValue(); 9616 9617 bool isLE = TLI.isLittleEndian(); 9618 unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits(); 9619 assert(ElemRatio > 1 && "Invalid element size ratio"); 9620 SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType): 9621 DAG.getConstant(0, SourceType); 9622 9623 unsigned NewBVElems = ElemRatio * VT.getVectorNumElements(); 9624 SmallVector<SDValue, 8> Ops(NewBVElems, Filler); 9625 9626 // Populate the new build_vector 9627 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 9628 SDValue Cast = N->getOperand(i); 9629 assert((Cast.getOpcode() == ISD::ANY_EXTEND || 9630 Cast.getOpcode() == ISD::ZERO_EXTEND || 9631 Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode"); 9632 SDValue In; 9633 if (Cast.getOpcode() == ISD::UNDEF) 9634 In = DAG.getUNDEF(SourceType); 9635 else 9636 In = Cast->getOperand(0); 9637 unsigned Index = isLE ? (i * ElemRatio) : 9638 (i * ElemRatio + (ElemRatio - 1)); 9639 9640 assert(Index < Ops.size() && "Invalid index"); 9641 Ops[Index] = In; 9642 } 9643 9644 // The type of the new BUILD_VECTOR node. 9645 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems); 9646 assert(VecVT.getSizeInBits() == VT.getSizeInBits() && 9647 "Invalid vector size"); 9648 // Check if the new vector type is legal. 9649 if (!isTypeLegal(VecVT)) return SDValue(); 9650 9651 // Make the new BUILD_VECTOR. 9652 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, &Ops[0], Ops.size()); 9653 9654 // The new BUILD_VECTOR node has the potential to be further optimized. 9655 AddToWorkList(BV.getNode()); 9656 // Bitcast to the desired type. 9657 return DAG.getNode(ISD::BITCAST, dl, VT, BV); 9658} 9659 9660SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) { 9661 EVT VT = N->getValueType(0); 9662 9663 unsigned NumInScalars = N->getNumOperands(); 9664 SDLoc dl(N); 9665 9666 EVT SrcVT = MVT::Other; 9667 unsigned Opcode = ISD::DELETED_NODE; 9668 unsigned NumDefs = 0; 9669 9670 for (unsigned i = 0; i != NumInScalars; ++i) { 9671 SDValue In = N->getOperand(i); 9672 unsigned Opc = In.getOpcode(); 9673 9674 if (Opc == ISD::UNDEF) 9675 continue; 9676 9677 // If all scalar values are floats and converted from integers. 9678 if (Opcode == ISD::DELETED_NODE && 9679 (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) { 9680 Opcode = Opc; 9681 } 9682 9683 if (Opc != Opcode) 9684 return SDValue(); 9685 9686 EVT InVT = In.getOperand(0).getValueType(); 9687 9688 // If all scalar values are typed differently, bail out. It's chosen to 9689 // simplify BUILD_VECTOR of integer types. 9690 if (SrcVT == MVT::Other) 9691 SrcVT = InVT; 9692 if (SrcVT != InVT) 9693 return SDValue(); 9694 NumDefs++; 9695 } 9696 9697 // If the vector has just one element defined, it's not worth to fold it into 9698 // a vectorized one. 9699 if (NumDefs < 2) 9700 return SDValue(); 9701 9702 assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP) 9703 && "Should only handle conversion from integer to float."); 9704 assert(SrcVT != MVT::Other && "Cannot determine source type!"); 9705 9706 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars); 9707 9708 if (!TLI.isOperationLegalOrCustom(Opcode, NVT)) 9709 return SDValue(); 9710 9711 SmallVector<SDValue, 8> Opnds; 9712 for (unsigned i = 0; i != NumInScalars; ++i) { 9713 SDValue In = N->getOperand(i); 9714 9715 if (In.getOpcode() == ISD::UNDEF) 9716 Opnds.push_back(DAG.getUNDEF(SrcVT)); 9717 else 9718 Opnds.push_back(In.getOperand(0)); 9719 } 9720 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, 9721 &Opnds[0], Opnds.size()); 9722 AddToWorkList(BV.getNode()); 9723 9724 return DAG.getNode(Opcode, dl, VT, BV); 9725} 9726 9727SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) { 9728 unsigned NumInScalars = N->getNumOperands(); 9729 SDLoc dl(N); 9730 EVT VT = N->getValueType(0); 9731 9732 // A vector built entirely of undefs is undef. 9733 if (ISD::allOperandsUndef(N)) 9734 return DAG.getUNDEF(VT); 9735 9736 SDValue V = reduceBuildVecExtToExtBuildVec(N); 9737 if (V.getNode()) 9738 return V; 9739 9740 V = reduceBuildVecConvertToConvertBuildVec(N); 9741 if (V.getNode()) 9742 return V; 9743 9744 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT 9745 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from 9746 // at most two distinct vectors, turn this into a shuffle node. 9747 9748 // May only combine to shuffle after legalize if shuffle is legal. 9749 if (LegalOperations && 9750 !TLI.isOperationLegalOrCustom(ISD::VECTOR_SHUFFLE, VT)) 9751 return SDValue(); 9752 9753 SDValue VecIn1, VecIn2; 9754 for (unsigned i = 0; i != NumInScalars; ++i) { 9755 // Ignore undef inputs. 9756 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue; 9757 9758 // If this input is something other than a EXTRACT_VECTOR_ELT with a 9759 // constant index, bail out. 9760 if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT || 9761 !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) { 9762 VecIn1 = VecIn2 = SDValue(0, 0); 9763 break; 9764 } 9765 9766 // We allow up to two distinct input vectors. 9767 SDValue ExtractedFromVec = N->getOperand(i).getOperand(0); 9768 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2) 9769 continue; 9770 9771 if (VecIn1.getNode() == 0) { 9772 VecIn1 = ExtractedFromVec; 9773 } else if (VecIn2.getNode() == 0) { 9774 VecIn2 = ExtractedFromVec; 9775 } else { 9776 // Too many inputs. 9777 VecIn1 = VecIn2 = SDValue(0, 0); 9778 break; 9779 } 9780 } 9781 9782 // If everything is good, we can make a shuffle operation. 9783 if (VecIn1.getNode()) { 9784 SmallVector<int, 8> Mask; 9785 for (unsigned i = 0; i != NumInScalars; ++i) { 9786 if (N->getOperand(i).getOpcode() == ISD::UNDEF) { 9787 Mask.push_back(-1); 9788 continue; 9789 } 9790 9791 // If extracting from the first vector, just use the index directly. 9792 SDValue Extract = N->getOperand(i); 9793 SDValue ExtVal = Extract.getOperand(1); 9794 if (Extract.getOperand(0) == VecIn1) { 9795 unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue(); 9796 if (ExtIndex > VT.getVectorNumElements()) 9797 return SDValue(); 9798 9799 Mask.push_back(ExtIndex); 9800 continue; 9801 } 9802 9803 // Otherwise, use InIdx + VecSize 9804 unsigned Idx = cast<ConstantSDNode>(ExtVal)->getZExtValue(); 9805 Mask.push_back(Idx+NumInScalars); 9806 } 9807 9808 // We can't generate a shuffle node with mismatched input and output types. 9809 // Attempt to transform a single input vector to the correct type. 9810 if ((VT != VecIn1.getValueType())) { 9811 // We don't support shuffeling between TWO values of different types. 9812 if (VecIn2.getNode() != 0) 9813 return SDValue(); 9814 9815 // We only support widening of vectors which are half the size of the 9816 // output registers. For example XMM->YMM widening on X86 with AVX. 9817 if (VecIn1.getValueType().getSizeInBits()*2 != VT.getSizeInBits()) 9818 return SDValue(); 9819 9820 // If the input vector type has a different base type to the output 9821 // vector type, bail out. 9822 if (VecIn1.getValueType().getVectorElementType() != 9823 VT.getVectorElementType()) 9824 return SDValue(); 9825 9826 // Widen the input vector by adding undef values. 9827 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, 9828 VecIn1, DAG.getUNDEF(VecIn1.getValueType())); 9829 } 9830 9831 // If VecIn2 is unused then change it to undef. 9832 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT); 9833 9834 // Check that we were able to transform all incoming values to the same 9835 // type. 9836 if (VecIn2.getValueType() != VecIn1.getValueType() || 9837 VecIn1.getValueType() != VT) 9838 return SDValue(); 9839 9840 // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes. 9841 if (!isTypeLegal(VT)) 9842 return SDValue(); 9843 9844 // Return the new VECTOR_SHUFFLE node. 9845 SDValue Ops[2]; 9846 Ops[0] = VecIn1; 9847 Ops[1] = VecIn2; 9848 return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]); 9849 } 9850 9851 return SDValue(); 9852} 9853 9854SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) { 9855 // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of 9856 // EXTRACT_SUBVECTOR operations. If so, and if the EXTRACT_SUBVECTOR vector 9857 // inputs come from at most two distinct vectors, turn this into a shuffle 9858 // node. 9859 9860 // If we only have one input vector, we don't need to do any concatenation. 9861 if (N->getNumOperands() == 1) 9862 return N->getOperand(0); 9863 9864 // Check if all of the operands are undefs. 9865 EVT VT = N->getValueType(0); 9866 if (ISD::allOperandsUndef(N)) 9867 return DAG.getUNDEF(VT); 9868 9869 // Optimize concat_vectors where one of the vectors is undef. 9870 if (N->getNumOperands() == 2 && 9871 N->getOperand(1)->getOpcode() == ISD::UNDEF) { 9872 SDValue In = N->getOperand(0); 9873 assert(In->getValueType(0).isVector() && "Must concat vectors"); 9874 9875 // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr). 9876 if (In->getOpcode() == ISD::BITCAST && 9877 !In->getOperand(0)->getValueType(0).isVector()) { 9878 SDValue Scalar = In->getOperand(0); 9879 EVT SclTy = Scalar->getValueType(0); 9880 9881 if (!SclTy.isFloatingPoint() && !SclTy.isInteger()) 9882 return SDValue(); 9883 9884 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy, 9885 VT.getSizeInBits() / SclTy.getSizeInBits()); 9886 if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType())) 9887 return SDValue(); 9888 9889 SDLoc dl = SDLoc(N); 9890 SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar); 9891 return DAG.getNode(ISD::BITCAST, dl, VT, Res); 9892 } 9893 } 9894 9895 // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR 9896 // nodes often generate nop CONCAT_VECTOR nodes. 9897 // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that 9898 // place the incoming vectors at the exact same location. 9899 SDValue SingleSource = SDValue(); 9900 unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements(); 9901 9902 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 9903 SDValue Op = N->getOperand(i); 9904 9905 if (Op.getOpcode() == ISD::UNDEF) 9906 continue; 9907 9908 // Check if this is the identity extract: 9909 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR) 9910 return SDValue(); 9911 9912 // Find the single incoming vector for the extract_subvector. 9913 if (SingleSource.getNode()) { 9914 if (Op.getOperand(0) != SingleSource) 9915 return SDValue(); 9916 } else { 9917 SingleSource = Op.getOperand(0); 9918 9919 // Check the source type is the same as the type of the result. 9920 // If not, this concat may extend the vector, so we can not 9921 // optimize it away. 9922 if (SingleSource.getValueType() != N->getValueType(0)) 9923 return SDValue(); 9924 } 9925 9926 unsigned IdentityIndex = i * PartNumElem; 9927 ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 9928 // The extract index must be constant. 9929 if (!CS) 9930 return SDValue(); 9931 9932 // Check that we are reading from the identity index. 9933 if (CS->getZExtValue() != IdentityIndex) 9934 return SDValue(); 9935 } 9936 9937 if (SingleSource.getNode()) 9938 return SingleSource; 9939 9940 return SDValue(); 9941} 9942 9943SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) { 9944 EVT NVT = N->getValueType(0); 9945 SDValue V = N->getOperand(0); 9946 9947 if (V->getOpcode() == ISD::CONCAT_VECTORS) { 9948 // Combine: 9949 // (extract_subvec (concat V1, V2, ...), i) 9950 // Into: 9951 // Vi if possible 9952 // Only operand 0 is checked as 'concat' assumes all inputs of the same 9953 // type. 9954 if (V->getOperand(0).getValueType() != NVT) 9955 return SDValue(); 9956 unsigned Idx = dyn_cast<ConstantSDNode>(N->getOperand(1))->getZExtValue(); 9957 unsigned NumElems = NVT.getVectorNumElements(); 9958 assert((Idx % NumElems) == 0 && 9959 "IDX in concat is not a multiple of the result vector length."); 9960 return V->getOperand(Idx / NumElems); 9961 } 9962 9963 // Skip bitcasting 9964 if (V->getOpcode() == ISD::BITCAST) 9965 V = V.getOperand(0); 9966 9967 if (V->getOpcode() == ISD::INSERT_SUBVECTOR) { 9968 SDLoc dl(N); 9969 // Handle only simple case where vector being inserted and vector 9970 // being extracted are of same type, and are half size of larger vectors. 9971 EVT BigVT = V->getOperand(0).getValueType(); 9972 EVT SmallVT = V->getOperand(1).getValueType(); 9973 if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits()) 9974 return SDValue(); 9975 9976 // Only handle cases where both indexes are constants with the same type. 9977 ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1)); 9978 ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2)); 9979 9980 if (InsIdx && ExtIdx && 9981 InsIdx->getValueType(0).getSizeInBits() <= 64 && 9982 ExtIdx->getValueType(0).getSizeInBits() <= 64) { 9983 // Combine: 9984 // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx) 9985 // Into: 9986 // indices are equal or bit offsets are equal => V1 9987 // otherwise => (extract_subvec V1, ExtIdx) 9988 if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() == 9989 ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits()) 9990 return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1)); 9991 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT, 9992 DAG.getNode(ISD::BITCAST, dl, 9993 N->getOperand(0).getValueType(), 9994 V->getOperand(0)), N->getOperand(1)); 9995 } 9996 } 9997 9998 return SDValue(); 9999} 10000 10001// Tries to turn a shuffle of two CONCAT_VECTORS into a single concat. 10002static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) { 10003 EVT VT = N->getValueType(0); 10004 unsigned NumElts = VT.getVectorNumElements(); 10005 10006 SDValue N0 = N->getOperand(0); 10007 SDValue N1 = N->getOperand(1); 10008 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N); 10009 10010 SmallVector<SDValue, 4> Ops; 10011 EVT ConcatVT = N0.getOperand(0).getValueType(); 10012 unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements(); 10013 unsigned NumConcats = NumElts / NumElemsPerConcat; 10014 10015 // Look at every vector that's inserted. We're looking for exact 10016 // subvector-sized copies from a concatenated vector 10017 for (unsigned I = 0; I != NumConcats; ++I) { 10018 // Make sure we're dealing with a copy. 10019 unsigned Begin = I * NumElemsPerConcat; 10020 bool AllUndef = true, NoUndef = true; 10021 for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) { 10022 if (SVN->getMaskElt(J) >= 0) 10023 AllUndef = false; 10024 else 10025 NoUndef = false; 10026 } 10027 10028 if (NoUndef) { 10029 if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0) 10030 return SDValue(); 10031 10032 for (unsigned J = 1; J != NumElemsPerConcat; ++J) 10033 if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J)) 10034 return SDValue(); 10035 10036 unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat; 10037 if (FirstElt < N0.getNumOperands()) 10038 Ops.push_back(N0.getOperand(FirstElt)); 10039 else 10040 Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands())); 10041 10042 } else if (AllUndef) { 10043 Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType())); 10044 } else { // Mixed with general masks and undefs, can't do optimization. 10045 return SDValue(); 10046 } 10047 } 10048 10049 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops.data(), 10050 Ops.size()); 10051} 10052 10053SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) { 10054 EVT VT = N->getValueType(0); 10055 unsigned NumElts = VT.getVectorNumElements(); 10056 10057 SDValue N0 = N->getOperand(0); 10058 SDValue N1 = N->getOperand(1); 10059 10060 assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG"); 10061 10062 // Canonicalize shuffle undef, undef -> undef 10063 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF) 10064 return DAG.getUNDEF(VT); 10065 10066 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N); 10067 10068 // Canonicalize shuffle v, v -> v, undef 10069 if (N0 == N1) { 10070 SmallVector<int, 8> NewMask; 10071 for (unsigned i = 0; i != NumElts; ++i) { 10072 int Idx = SVN->getMaskElt(i); 10073 if (Idx >= (int)NumElts) Idx -= NumElts; 10074 NewMask.push_back(Idx); 10075 } 10076 return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT), 10077 &NewMask[0]); 10078 } 10079 10080 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask. 10081 if (N0.getOpcode() == ISD::UNDEF) { 10082 SmallVector<int, 8> NewMask; 10083 for (unsigned i = 0; i != NumElts; ++i) { 10084 int Idx = SVN->getMaskElt(i); 10085 if (Idx >= 0) { 10086 if (Idx >= (int)NumElts) 10087 Idx -= NumElts; 10088 else 10089 Idx = -1; // remove reference to lhs 10090 } 10091 NewMask.push_back(Idx); 10092 } 10093 return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT), 10094 &NewMask[0]); 10095 } 10096 10097 // Remove references to rhs if it is undef 10098 if (N1.getOpcode() == ISD::UNDEF) { 10099 bool Changed = false; 10100 SmallVector<int, 8> NewMask; 10101 for (unsigned i = 0; i != NumElts; ++i) { 10102 int Idx = SVN->getMaskElt(i); 10103 if (Idx >= (int)NumElts) { 10104 Idx = -1; 10105 Changed = true; 10106 } 10107 NewMask.push_back(Idx); 10108 } 10109 if (Changed) 10110 return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]); 10111 } 10112 10113 // If it is a splat, check if the argument vector is another splat or a 10114 // build_vector with all scalar elements the same. 10115 if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) { 10116 SDNode *V = N0.getNode(); 10117 10118 // If this is a bit convert that changes the element type of the vector but 10119 // not the number of vector elements, look through it. Be careful not to 10120 // look though conversions that change things like v4f32 to v2f64. 10121 if (V->getOpcode() == ISD::BITCAST) { 10122 SDValue ConvInput = V->getOperand(0); 10123 if (ConvInput.getValueType().isVector() && 10124 ConvInput.getValueType().getVectorNumElements() == NumElts) 10125 V = ConvInput.getNode(); 10126 } 10127 10128 if (V->getOpcode() == ISD::BUILD_VECTOR) { 10129 assert(V->getNumOperands() == NumElts && 10130 "BUILD_VECTOR has wrong number of operands"); 10131 SDValue Base; 10132 bool AllSame = true; 10133 for (unsigned i = 0; i != NumElts; ++i) { 10134 if (V->getOperand(i).getOpcode() != ISD::UNDEF) { 10135 Base = V->getOperand(i); 10136 break; 10137 } 10138 } 10139 // Splat of <u, u, u, u>, return <u, u, u, u> 10140 if (!Base.getNode()) 10141 return N0; 10142 for (unsigned i = 0; i != NumElts; ++i) { 10143 if (V->getOperand(i) != Base) { 10144 AllSame = false; 10145 break; 10146 } 10147 } 10148 // Splat of <x, x, x, x>, return <x, x, x, x> 10149 if (AllSame) 10150 return N0; 10151 } 10152 } 10153 10154 if (N0.getOpcode() == ISD::CONCAT_VECTORS && 10155 Level < AfterLegalizeVectorOps && 10156 (N1.getOpcode() == ISD::UNDEF || 10157 (N1.getOpcode() == ISD::CONCAT_VECTORS && 10158 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) { 10159 SDValue V = partitionShuffleOfConcats(N, DAG); 10160 10161 if (V.getNode()) 10162 return V; 10163 } 10164 10165 // If this shuffle node is simply a swizzle of another shuffle node, 10166 // and it reverses the swizzle of the previous shuffle then we can 10167 // optimize shuffle(shuffle(x, undef), undef) -> x. 10168 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG && 10169 N1.getOpcode() == ISD::UNDEF) { 10170 10171 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0); 10172 10173 // Shuffle nodes can only reverse shuffles with a single non-undef value. 10174 if (N0.getOperand(1).getOpcode() != ISD::UNDEF) 10175 return SDValue(); 10176 10177 // The incoming shuffle must be of the same type as the result of the 10178 // current shuffle. 10179 assert(OtherSV->getOperand(0).getValueType() == VT && 10180 "Shuffle types don't match"); 10181 10182 for (unsigned i = 0; i != NumElts; ++i) { 10183 int Idx = SVN->getMaskElt(i); 10184 assert(Idx < (int)NumElts && "Index references undef operand"); 10185 // Next, this index comes from the first value, which is the incoming 10186 // shuffle. Adopt the incoming index. 10187 if (Idx >= 0) 10188 Idx = OtherSV->getMaskElt(Idx); 10189 10190 // The combined shuffle must map each index to itself. 10191 if (Idx >= 0 && (unsigned)Idx != i) 10192 return SDValue(); 10193 } 10194 10195 return OtherSV->getOperand(0); 10196 } 10197 10198 return SDValue(); 10199} 10200 10201/// XformToShuffleWithZero - Returns a vector_shuffle if it able to transform 10202/// an AND to a vector_shuffle with the destination vector and a zero vector. 10203/// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==> 10204/// vector_shuffle V, Zero, <0, 4, 2, 4> 10205SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) { 10206 EVT VT = N->getValueType(0); 10207 SDLoc dl(N); 10208 SDValue LHS = N->getOperand(0); 10209 SDValue RHS = N->getOperand(1); 10210 if (N->getOpcode() == ISD::AND) { 10211 if (RHS.getOpcode() == ISD::BITCAST) 10212 RHS = RHS.getOperand(0); 10213 if (RHS.getOpcode() == ISD::BUILD_VECTOR) { 10214 SmallVector<int, 8> Indices; 10215 unsigned NumElts = RHS.getNumOperands(); 10216 for (unsigned i = 0; i != NumElts; ++i) { 10217 SDValue Elt = RHS.getOperand(i); 10218 if (!isa<ConstantSDNode>(Elt)) 10219 return SDValue(); 10220 10221 if (cast<ConstantSDNode>(Elt)->isAllOnesValue()) 10222 Indices.push_back(i); 10223 else if (cast<ConstantSDNode>(Elt)->isNullValue()) 10224 Indices.push_back(NumElts); 10225 else 10226 return SDValue(); 10227 } 10228 10229 // Let's see if the target supports this vector_shuffle. 10230 EVT RVT = RHS.getValueType(); 10231 if (!TLI.isVectorClearMaskLegal(Indices, RVT)) 10232 return SDValue(); 10233 10234 // Return the new VECTOR_SHUFFLE node. 10235 EVT EltVT = RVT.getVectorElementType(); 10236 SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(), 10237 DAG.getConstant(0, EltVT)); 10238 SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), 10239 RVT, &ZeroOps[0], ZeroOps.size()); 10240 LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS); 10241 SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]); 10242 return DAG.getNode(ISD::BITCAST, dl, VT, Shuf); 10243 } 10244 } 10245 10246 return SDValue(); 10247} 10248 10249/// SimplifyVBinOp - Visit a binary vector operation, like ADD. 10250SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) { 10251 assert(N->getValueType(0).isVector() && 10252 "SimplifyVBinOp only works on vectors!"); 10253 10254 SDValue LHS = N->getOperand(0); 10255 SDValue RHS = N->getOperand(1); 10256 SDValue Shuffle = XformToShuffleWithZero(N); 10257 if (Shuffle.getNode()) return Shuffle; 10258 10259 // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold 10260 // this operation. 10261 if (LHS.getOpcode() == ISD::BUILD_VECTOR && 10262 RHS.getOpcode() == ISD::BUILD_VECTOR) { 10263 SmallVector<SDValue, 8> Ops; 10264 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) { 10265 SDValue LHSOp = LHS.getOperand(i); 10266 SDValue RHSOp = RHS.getOperand(i); 10267 // If these two elements can't be folded, bail out. 10268 if ((LHSOp.getOpcode() != ISD::UNDEF && 10269 LHSOp.getOpcode() != ISD::Constant && 10270 LHSOp.getOpcode() != ISD::ConstantFP) || 10271 (RHSOp.getOpcode() != ISD::UNDEF && 10272 RHSOp.getOpcode() != ISD::Constant && 10273 RHSOp.getOpcode() != ISD::ConstantFP)) 10274 break; 10275 10276 // Can't fold divide by zero. 10277 if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV || 10278 N->getOpcode() == ISD::FDIV) { 10279 if ((RHSOp.getOpcode() == ISD::Constant && 10280 cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) || 10281 (RHSOp.getOpcode() == ISD::ConstantFP && 10282 cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero())) 10283 break; 10284 } 10285 10286 EVT VT = LHSOp.getValueType(); 10287 EVT RVT = RHSOp.getValueType(); 10288 if (RVT != VT) { 10289 // Integer BUILD_VECTOR operands may have types larger than the element 10290 // size (e.g., when the element type is not legal). Prior to type 10291 // legalization, the types may not match between the two BUILD_VECTORS. 10292 // Truncate one of the operands to make them match. 10293 if (RVT.getSizeInBits() > VT.getSizeInBits()) { 10294 RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp); 10295 } else { 10296 LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp); 10297 VT = RVT; 10298 } 10299 } 10300 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT, 10301 LHSOp, RHSOp); 10302 if (FoldOp.getOpcode() != ISD::UNDEF && 10303 FoldOp.getOpcode() != ISD::Constant && 10304 FoldOp.getOpcode() != ISD::ConstantFP) 10305 break; 10306 Ops.push_back(FoldOp); 10307 AddToWorkList(FoldOp.getNode()); 10308 } 10309 10310 if (Ops.size() == LHS.getNumOperands()) 10311 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), 10312 LHS.getValueType(), &Ops[0], Ops.size()); 10313 } 10314 10315 return SDValue(); 10316} 10317 10318/// SimplifyVUnaryOp - Visit a binary vector operation, like FABS/FNEG. 10319SDValue DAGCombiner::SimplifyVUnaryOp(SDNode *N) { 10320 assert(N->getValueType(0).isVector() && 10321 "SimplifyVUnaryOp only works on vectors!"); 10322 10323 SDValue N0 = N->getOperand(0); 10324 10325 if (N0.getOpcode() != ISD::BUILD_VECTOR) 10326 return SDValue(); 10327 10328 // Operand is a BUILD_VECTOR node, see if we can constant fold it. 10329 SmallVector<SDValue, 8> Ops; 10330 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) { 10331 SDValue Op = N0.getOperand(i); 10332 if (Op.getOpcode() != ISD::UNDEF && 10333 Op.getOpcode() != ISD::ConstantFP) 10334 break; 10335 EVT EltVT = Op.getValueType(); 10336 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(N0), EltVT, Op); 10337 if (FoldOp.getOpcode() != ISD::UNDEF && 10338 FoldOp.getOpcode() != ISD::ConstantFP) 10339 break; 10340 Ops.push_back(FoldOp); 10341 AddToWorkList(FoldOp.getNode()); 10342 } 10343 10344 if (Ops.size() != N0.getNumOperands()) 10345 return SDValue(); 10346 10347 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), 10348 N0.getValueType(), &Ops[0], Ops.size()); 10349} 10350 10351SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0, 10352 SDValue N1, SDValue N2){ 10353 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!"); 10354 10355 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2, 10356 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 10357 10358 // If we got a simplified select_cc node back from SimplifySelectCC, then 10359 // break it down into a new SETCC node, and a new SELECT node, and then return 10360 // the SELECT node, since we were called with a SELECT node. 10361 if (SCC.getNode()) { 10362 // Check to see if we got a select_cc back (to turn into setcc/select). 10363 // Otherwise, just return whatever node we got back, like fabs. 10364 if (SCC.getOpcode() == ISD::SELECT_CC) { 10365 SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0), 10366 N0.getValueType(), 10367 SCC.getOperand(0), SCC.getOperand(1), 10368 SCC.getOperand(4)); 10369 AddToWorkList(SETCC.getNode()); 10370 return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), 10371 SCC.getOperand(2), SCC.getOperand(3), SETCC); 10372 } 10373 10374 return SCC; 10375 } 10376 return SDValue(); 10377} 10378 10379/// SimplifySelectOps - Given a SELECT or a SELECT_CC node, where LHS and RHS 10380/// are the two values being selected between, see if we can simplify the 10381/// select. Callers of this should assume that TheSelect is deleted if this 10382/// returns true. As such, they should return the appropriate thing (e.g. the 10383/// node) back to the top-level of the DAG combiner loop to avoid it being 10384/// looked at. 10385bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS, 10386 SDValue RHS) { 10387 10388 // Cannot simplify select with vector condition 10389 if (TheSelect->getOperand(0).getValueType().isVector()) return false; 10390 10391 // If this is a select from two identical things, try to pull the operation 10392 // through the select. 10393 if (LHS.getOpcode() != RHS.getOpcode() || 10394 !LHS.hasOneUse() || !RHS.hasOneUse()) 10395 return false; 10396 10397 // If this is a load and the token chain is identical, replace the select 10398 // of two loads with a load through a select of the address to load from. 10399 // This triggers in things like "select bool X, 10.0, 123.0" after the FP 10400 // constants have been dropped into the constant pool. 10401 if (LHS.getOpcode() == ISD::LOAD) { 10402 LoadSDNode *LLD = cast<LoadSDNode>(LHS); 10403 LoadSDNode *RLD = cast<LoadSDNode>(RHS); 10404 10405 // Token chains must be identical. 10406 if (LHS.getOperand(0) != RHS.getOperand(0) || 10407 // Do not let this transformation reduce the number of volatile loads. 10408 LLD->isVolatile() || RLD->isVolatile() || 10409 // If this is an EXTLOAD, the VT's must match. 10410 LLD->getMemoryVT() != RLD->getMemoryVT() || 10411 // If this is an EXTLOAD, the kind of extension must match. 10412 (LLD->getExtensionType() != RLD->getExtensionType() && 10413 // The only exception is if one of the extensions is anyext. 10414 LLD->getExtensionType() != ISD::EXTLOAD && 10415 RLD->getExtensionType() != ISD::EXTLOAD) || 10416 // FIXME: this discards src value information. This is 10417 // over-conservative. It would be beneficial to be able to remember 10418 // both potential memory locations. Since we are discarding 10419 // src value info, don't do the transformation if the memory 10420 // locations are not in the default address space. 10421 LLD->getPointerInfo().getAddrSpace() != 0 || 10422 RLD->getPointerInfo().getAddrSpace() != 0 || 10423 !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(), 10424 LLD->getBasePtr().getValueType())) 10425 return false; 10426 10427 // Check that the select condition doesn't reach either load. If so, 10428 // folding this will induce a cycle into the DAG. If not, this is safe to 10429 // xform, so create a select of the addresses. 10430 SDValue Addr; 10431 if (TheSelect->getOpcode() == ISD::SELECT) { 10432 SDNode *CondNode = TheSelect->getOperand(0).getNode(); 10433 if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) || 10434 (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode))) 10435 return false; 10436 // The loads must not depend on one another. 10437 if (LLD->isPredecessorOf(RLD) || 10438 RLD->isPredecessorOf(LLD)) 10439 return false; 10440 Addr = DAG.getSelect(SDLoc(TheSelect), 10441 LLD->getBasePtr().getValueType(), 10442 TheSelect->getOperand(0), LLD->getBasePtr(), 10443 RLD->getBasePtr()); 10444 } else { // Otherwise SELECT_CC 10445 SDNode *CondLHS = TheSelect->getOperand(0).getNode(); 10446 SDNode *CondRHS = TheSelect->getOperand(1).getNode(); 10447 10448 if ((LLD->hasAnyUseOfValue(1) && 10449 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) || 10450 (RLD->hasAnyUseOfValue(1) && 10451 (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS)))) 10452 return false; 10453 10454 Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect), 10455 LLD->getBasePtr().getValueType(), 10456 TheSelect->getOperand(0), 10457 TheSelect->getOperand(1), 10458 LLD->getBasePtr(), RLD->getBasePtr(), 10459 TheSelect->getOperand(4)); 10460 } 10461 10462 SDValue Load; 10463 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) { 10464 Load = DAG.getLoad(TheSelect->getValueType(0), 10465 SDLoc(TheSelect), 10466 // FIXME: Discards pointer and TBAA info. 10467 LLD->getChain(), Addr, MachinePointerInfo(), 10468 LLD->isVolatile(), LLD->isNonTemporal(), 10469 LLD->isInvariant(), LLD->getAlignment()); 10470 } else { 10471 Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ? 10472 RLD->getExtensionType() : LLD->getExtensionType(), 10473 SDLoc(TheSelect), 10474 TheSelect->getValueType(0), 10475 // FIXME: Discards pointer and TBAA info. 10476 LLD->getChain(), Addr, MachinePointerInfo(), 10477 LLD->getMemoryVT(), LLD->isVolatile(), 10478 LLD->isNonTemporal(), LLD->getAlignment()); 10479 } 10480 10481 // Users of the select now use the result of the load. 10482 CombineTo(TheSelect, Load); 10483 10484 // Users of the old loads now use the new load's chain. We know the 10485 // old-load value is dead now. 10486 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1)); 10487 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1)); 10488 return true; 10489 } 10490 10491 return false; 10492} 10493 10494/// SimplifySelectCC - Simplify an expression of the form (N0 cond N1) ? N2 : N3 10495/// where 'cond' is the comparison specified by CC. 10496SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, 10497 SDValue N2, SDValue N3, 10498 ISD::CondCode CC, bool NotExtCompare) { 10499 // (x ? y : y) -> y. 10500 if (N2 == N3) return N2; 10501 10502 EVT VT = N2.getValueType(); 10503 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode()); 10504 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode()); 10505 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode()); 10506 10507 // Determine if the condition we're dealing with is constant 10508 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()), 10509 N0, N1, CC, DL, false); 10510 if (SCC.getNode()) AddToWorkList(SCC.getNode()); 10511 ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode()); 10512 10513 // fold select_cc true, x, y -> x 10514 if (SCCC && !SCCC->isNullValue()) 10515 return N2; 10516 // fold select_cc false, x, y -> y 10517 if (SCCC && SCCC->isNullValue()) 10518 return N3; 10519 10520 // Check to see if we can simplify the select into an fabs node 10521 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) { 10522 // Allow either -0.0 or 0.0 10523 if (CFP->getValueAPF().isZero()) { 10524 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs 10525 if ((CC == ISD::SETGE || CC == ISD::SETGT) && 10526 N0 == N2 && N3.getOpcode() == ISD::FNEG && 10527 N2 == N3.getOperand(0)) 10528 return DAG.getNode(ISD::FABS, DL, VT, N0); 10529 10530 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs 10531 if ((CC == ISD::SETLT || CC == ISD::SETLE) && 10532 N0 == N3 && N2.getOpcode() == ISD::FNEG && 10533 N2.getOperand(0) == N3) 10534 return DAG.getNode(ISD::FABS, DL, VT, N3); 10535 } 10536 } 10537 10538 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)" 10539 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0 10540 // in it. This is a win when the constant is not otherwise available because 10541 // it replaces two constant pool loads with one. We only do this if the FP 10542 // type is known to be legal, because if it isn't, then we are before legalize 10543 // types an we want the other legalization to happen first (e.g. to avoid 10544 // messing with soft float) and if the ConstantFP is not legal, because if 10545 // it is legal, we may not need to store the FP constant in a constant pool. 10546 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2)) 10547 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) { 10548 if (TLI.isTypeLegal(N2.getValueType()) && 10549 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) != 10550 TargetLowering::Legal) && 10551 // If both constants have multiple uses, then we won't need to do an 10552 // extra load, they are likely around in registers for other users. 10553 (TV->hasOneUse() || FV->hasOneUse())) { 10554 Constant *Elts[] = { 10555 const_cast<ConstantFP*>(FV->getConstantFPValue()), 10556 const_cast<ConstantFP*>(TV->getConstantFPValue()) 10557 }; 10558 Type *FPTy = Elts[0]->getType(); 10559 const DataLayout &TD = *TLI.getDataLayout(); 10560 10561 // Create a ConstantArray of the two constants. 10562 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts); 10563 SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(), 10564 TD.getPrefTypeAlignment(FPTy)); 10565 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment(); 10566 10567 // Get the offsets to the 0 and 1 element of the array so that we can 10568 // select between them. 10569 SDValue Zero = DAG.getIntPtrConstant(0); 10570 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType()); 10571 SDValue One = DAG.getIntPtrConstant(EltSize); 10572 10573 SDValue Cond = DAG.getSetCC(DL, 10574 getSetCCResultType(N0.getValueType()), 10575 N0, N1, CC); 10576 AddToWorkList(Cond.getNode()); 10577 SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(), 10578 Cond, One, Zero); 10579 AddToWorkList(CstOffset.getNode()); 10580 CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx, 10581 CstOffset); 10582 AddToWorkList(CPIdx.getNode()); 10583 return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx, 10584 MachinePointerInfo::getConstantPool(), false, 10585 false, false, Alignment); 10586 10587 } 10588 } 10589 10590 // Check to see if we can perform the "gzip trick", transforming 10591 // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A) 10592 if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT && 10593 (N1C->isNullValue() || // (a < 0) ? b : 0 10594 (N1C->getAPIntValue() == 1 && N0 == N2))) { // (a < 1) ? a : 0 10595 EVT XType = N0.getValueType(); 10596 EVT AType = N2.getValueType(); 10597 if (XType.bitsGE(AType)) { 10598 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a 10599 // single-bit constant. 10600 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) { 10601 unsigned ShCtV = N2C->getAPIntValue().logBase2(); 10602 ShCtV = XType.getSizeInBits()-ShCtV-1; 10603 SDValue ShCt = DAG.getConstant(ShCtV, 10604 getShiftAmountTy(N0.getValueType())); 10605 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), 10606 XType, N0, ShCt); 10607 AddToWorkList(Shift.getNode()); 10608 10609 if (XType.bitsGT(AType)) { 10610 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift); 10611 AddToWorkList(Shift.getNode()); 10612 } 10613 10614 return DAG.getNode(ISD::AND, DL, AType, Shift, N2); 10615 } 10616 10617 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), 10618 XType, N0, 10619 DAG.getConstant(XType.getSizeInBits()-1, 10620 getShiftAmountTy(N0.getValueType()))); 10621 AddToWorkList(Shift.getNode()); 10622 10623 if (XType.bitsGT(AType)) { 10624 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift); 10625 AddToWorkList(Shift.getNode()); 10626 } 10627 10628 return DAG.getNode(ISD::AND, DL, AType, Shift, N2); 10629 } 10630 } 10631 10632 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A) 10633 // where y is has a single bit set. 10634 // A plaintext description would be, we can turn the SELECT_CC into an AND 10635 // when the condition can be materialized as an all-ones register. Any 10636 // single bit-test can be materialized as an all-ones register with 10637 // shift-left and shift-right-arith. 10638 if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND && 10639 N0->getValueType(0) == VT && 10640 N1C && N1C->isNullValue() && 10641 N2C && N2C->isNullValue()) { 10642 SDValue AndLHS = N0->getOperand(0); 10643 ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 10644 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) { 10645 // Shift the tested bit over the sign bit. 10646 APInt AndMask = ConstAndRHS->getAPIntValue(); 10647 SDValue ShlAmt = 10648 DAG.getConstant(AndMask.countLeadingZeros(), 10649 getShiftAmountTy(AndLHS.getValueType())); 10650 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt); 10651 10652 // Now arithmetic right shift it all the way over, so the result is either 10653 // all-ones, or zero. 10654 SDValue ShrAmt = 10655 DAG.getConstant(AndMask.getBitWidth()-1, 10656 getShiftAmountTy(Shl.getValueType())); 10657 SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt); 10658 10659 return DAG.getNode(ISD::AND, DL, VT, Shr, N3); 10660 } 10661 } 10662 10663 // fold select C, 16, 0 -> shl C, 4 10664 if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() && 10665 TLI.getBooleanContents(N0.getValueType().isVector()) == 10666 TargetLowering::ZeroOrOneBooleanContent) { 10667 10668 // If the caller doesn't want us to simplify this into a zext of a compare, 10669 // don't do it. 10670 if (NotExtCompare && N2C->getAPIntValue() == 1) 10671 return SDValue(); 10672 10673 // Get a SetCC of the condition 10674 // NOTE: Don't create a SETCC if it's not legal on this target. 10675 if (!LegalOperations || 10676 TLI.isOperationLegal(ISD::SETCC, 10677 LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) { 10678 SDValue Temp, SCC; 10679 // cast from setcc result type to select result type 10680 if (LegalTypes) { 10681 SCC = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()), 10682 N0, N1, CC); 10683 if (N2.getValueType().bitsLT(SCC.getValueType())) 10684 Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2), 10685 N2.getValueType()); 10686 else 10687 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2), 10688 N2.getValueType(), SCC); 10689 } else { 10690 SCC = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC); 10691 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2), 10692 N2.getValueType(), SCC); 10693 } 10694 10695 AddToWorkList(SCC.getNode()); 10696 AddToWorkList(Temp.getNode()); 10697 10698 if (N2C->getAPIntValue() == 1) 10699 return Temp; 10700 10701 // shl setcc result by log2 n2c 10702 return DAG.getNode( 10703 ISD::SHL, DL, N2.getValueType(), Temp, 10704 DAG.getConstant(N2C->getAPIntValue().logBase2(), 10705 getShiftAmountTy(Temp.getValueType()))); 10706 } 10707 } 10708 10709 // Check to see if this is the equivalent of setcc 10710 // FIXME: Turn all of these into setcc if setcc if setcc is legal 10711 // otherwise, go ahead with the folds. 10712 if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) { 10713 EVT XType = N0.getValueType(); 10714 if (!LegalOperations || 10715 TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) { 10716 SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC); 10717 if (Res.getValueType() != VT) 10718 Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res); 10719 return Res; 10720 } 10721 10722 // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X)))) 10723 if (N1C && N1C->isNullValue() && CC == ISD::SETEQ && 10724 (!LegalOperations || 10725 TLI.isOperationLegal(ISD::CTLZ, XType))) { 10726 SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0); 10727 return DAG.getNode(ISD::SRL, DL, XType, Ctlz, 10728 DAG.getConstant(Log2_32(XType.getSizeInBits()), 10729 getShiftAmountTy(Ctlz.getValueType()))); 10730 } 10731 // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1)) 10732 if (N1C && N1C->isNullValue() && CC == ISD::SETGT) { 10733 SDValue NegN0 = DAG.getNode(ISD::SUB, SDLoc(N0), 10734 XType, DAG.getConstant(0, XType), N0); 10735 SDValue NotN0 = DAG.getNOT(SDLoc(N0), N0, XType); 10736 return DAG.getNode(ISD::SRL, DL, XType, 10737 DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0), 10738 DAG.getConstant(XType.getSizeInBits()-1, 10739 getShiftAmountTy(XType))); 10740 } 10741 // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1)) 10742 if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) { 10743 SDValue Sign = DAG.getNode(ISD::SRL, SDLoc(N0), XType, N0, 10744 DAG.getConstant(XType.getSizeInBits()-1, 10745 getShiftAmountTy(N0.getValueType()))); 10746 return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType)); 10747 } 10748 } 10749 10750 // Check to see if this is an integer abs. 10751 // select_cc setg[te] X, 0, X, -X -> 10752 // select_cc setgt X, -1, X, -X -> 10753 // select_cc setl[te] X, 0, -X, X -> 10754 // select_cc setlt X, 1, -X, X -> 10755 // Y = sra (X, size(X)-1); xor (add (X, Y), Y) 10756 if (N1C) { 10757 ConstantSDNode *SubC = NULL; 10758 if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) || 10759 (N1C->isAllOnesValue() && CC == ISD::SETGT)) && 10760 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1)) 10761 SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0)); 10762 else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) || 10763 (N1C->isOne() && CC == ISD::SETLT)) && 10764 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1)) 10765 SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0)); 10766 10767 EVT XType = N0.getValueType(); 10768 if (SubC && SubC->isNullValue() && XType.isInteger()) { 10769 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), XType, 10770 N0, 10771 DAG.getConstant(XType.getSizeInBits()-1, 10772 getShiftAmountTy(N0.getValueType()))); 10773 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0), 10774 XType, N0, Shift); 10775 AddToWorkList(Shift.getNode()); 10776 AddToWorkList(Add.getNode()); 10777 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift); 10778 } 10779 } 10780 10781 return SDValue(); 10782} 10783 10784/// SimplifySetCC - This is a stub for TargetLowering::SimplifySetCC. 10785SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0, 10786 SDValue N1, ISD::CondCode Cond, 10787 SDLoc DL, bool foldBooleans) { 10788 TargetLowering::DAGCombinerInfo 10789 DagCombineInfo(DAG, Level, false, this); 10790 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL); 10791} 10792 10793/// BuildSDIVSequence - Given an ISD::SDIV node expressing a divide by constant, 10794/// return a DAG expression to select that will generate the same value by 10795/// multiplying by a magic number. See: 10796/// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html> 10797SDValue DAGCombiner::BuildSDIV(SDNode *N) { 10798 std::vector<SDNode*> Built; 10799 SDValue S = TLI.BuildSDIV(N, DAG, LegalOperations, &Built); 10800 10801 for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end(); 10802 ii != ee; ++ii) 10803 AddToWorkList(*ii); 10804 return S; 10805} 10806 10807/// BuildUDIVSequence - Given an ISD::UDIV node expressing a divide by constant, 10808/// return a DAG expression to select that will generate the same value by 10809/// multiplying by a magic number. See: 10810/// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html> 10811SDValue DAGCombiner::BuildUDIV(SDNode *N) { 10812 std::vector<SDNode*> Built; 10813 SDValue S = TLI.BuildUDIV(N, DAG, LegalOperations, &Built); 10814 10815 for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end(); 10816 ii != ee; ++ii) 10817 AddToWorkList(*ii); 10818 return S; 10819} 10820 10821/// FindBaseOffset - Return true if base is a frame index, which is known not 10822// to alias with anything but itself. Provides base object and offset as 10823// results. 10824static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset, 10825 const GlobalValue *&GV, const void *&CV) { 10826 // Assume it is a primitive operation. 10827 Base = Ptr; Offset = 0; GV = 0; CV = 0; 10828 10829 // If it's an adding a simple constant then integrate the offset. 10830 if (Base.getOpcode() == ISD::ADD) { 10831 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) { 10832 Base = Base.getOperand(0); 10833 Offset += C->getZExtValue(); 10834 } 10835 } 10836 10837 // Return the underlying GlobalValue, and update the Offset. Return false 10838 // for GlobalAddressSDNode since the same GlobalAddress may be represented 10839 // by multiple nodes with different offsets. 10840 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) { 10841 GV = G->getGlobal(); 10842 Offset += G->getOffset(); 10843 return false; 10844 } 10845 10846 // Return the underlying Constant value, and update the Offset. Return false 10847 // for ConstantSDNodes since the same constant pool entry may be represented 10848 // by multiple nodes with different offsets. 10849 if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) { 10850 CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal() 10851 : (const void *)C->getConstVal(); 10852 Offset += C->getOffset(); 10853 return false; 10854 } 10855 // If it's any of the following then it can't alias with anything but itself. 10856 return isa<FrameIndexSDNode>(Base); 10857} 10858 10859/// isAlias - Return true if there is any possibility that the two addresses 10860/// overlap. 10861bool DAGCombiner::isAlias(SDValue Ptr1, int64_t Size1, bool IsVolatile1, 10862 const Value *SrcValue1, int SrcValueOffset1, 10863 unsigned SrcValueAlign1, 10864 const MDNode *TBAAInfo1, 10865 SDValue Ptr2, int64_t Size2, bool IsVolatile2, 10866 const Value *SrcValue2, int SrcValueOffset2, 10867 unsigned SrcValueAlign2, 10868 const MDNode *TBAAInfo2) const { 10869 // If they are the same then they must be aliases. 10870 if (Ptr1 == Ptr2) return true; 10871 10872 // If they are both volatile then they cannot be reordered. 10873 if (IsVolatile1 && IsVolatile2) return true; 10874 10875 // Gather base node and offset information. 10876 SDValue Base1, Base2; 10877 int64_t Offset1, Offset2; 10878 const GlobalValue *GV1, *GV2; 10879 const void *CV1, *CV2; 10880 bool isFrameIndex1 = FindBaseOffset(Ptr1, Base1, Offset1, GV1, CV1); 10881 bool isFrameIndex2 = FindBaseOffset(Ptr2, Base2, Offset2, GV2, CV2); 10882 10883 // If they have a same base address then check to see if they overlap. 10884 if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2))) 10885 return !((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1); 10886 10887 // It is possible for different frame indices to alias each other, mostly 10888 // when tail call optimization reuses return address slots for arguments. 10889 // To catch this case, look up the actual index of frame indices to compute 10890 // the real alias relationship. 10891 if (isFrameIndex1 && isFrameIndex2) { 10892 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo(); 10893 Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex()); 10894 Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex()); 10895 return !((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1); 10896 } 10897 10898 // Otherwise, if we know what the bases are, and they aren't identical, then 10899 // we know they cannot alias. 10900 if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2)) 10901 return false; 10902 10903 // If we know required SrcValue1 and SrcValue2 have relatively large alignment 10904 // compared to the size and offset of the access, we may be able to prove they 10905 // do not alias. This check is conservative for now to catch cases created by 10906 // splitting vector types. 10907 if ((SrcValueAlign1 == SrcValueAlign2) && 10908 (SrcValueOffset1 != SrcValueOffset2) && 10909 (Size1 == Size2) && (SrcValueAlign1 > Size1)) { 10910 int64_t OffAlign1 = SrcValueOffset1 % SrcValueAlign1; 10911 int64_t OffAlign2 = SrcValueOffset2 % SrcValueAlign1; 10912 10913 // There is no overlap between these relatively aligned accesses of similar 10914 // size, return no alias. 10915 if ((OffAlign1 + Size1) <= OffAlign2 || (OffAlign2 + Size2) <= OffAlign1) 10916 return false; 10917 } 10918 10919 bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0 ? CombinerGlobalAA : 10920 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA(); 10921 if (UseAA && SrcValue1 && SrcValue2) { 10922 // Use alias analysis information. 10923 int64_t MinOffset = std::min(SrcValueOffset1, SrcValueOffset2); 10924 int64_t Overlap1 = Size1 + SrcValueOffset1 - MinOffset; 10925 int64_t Overlap2 = Size2 + SrcValueOffset2 - MinOffset; 10926 AliasAnalysis::AliasResult AAResult = 10927 AA.alias(AliasAnalysis::Location(SrcValue1, Overlap1, TBAAInfo1), 10928 AliasAnalysis::Location(SrcValue2, Overlap2, TBAAInfo2)); 10929 if (AAResult == AliasAnalysis::NoAlias) 10930 return false; 10931 } 10932 10933 // Otherwise we have to assume they alias. 10934 return true; 10935} 10936 10937bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) { 10938 SDValue Ptr0, Ptr1; 10939 int64_t Size0, Size1; 10940 bool IsVolatile0, IsVolatile1; 10941 const Value *SrcValue0, *SrcValue1; 10942 int SrcValueOffset0, SrcValueOffset1; 10943 unsigned SrcValueAlign0, SrcValueAlign1; 10944 const MDNode *SrcTBAAInfo0, *SrcTBAAInfo1; 10945 FindAliasInfo(Op0, Ptr0, Size0, IsVolatile0, SrcValue0, SrcValueOffset0, 10946 SrcValueAlign0, SrcTBAAInfo0); 10947 FindAliasInfo(Op1, Ptr1, Size1, IsVolatile1, SrcValue1, SrcValueOffset1, 10948 SrcValueAlign1, SrcTBAAInfo1); 10949 return isAlias(Ptr0, Size0, IsVolatile0, SrcValue0, SrcValueOffset0, 10950 SrcValueAlign0, SrcTBAAInfo0, 10951 Ptr1, Size1, IsVolatile1, SrcValue1, SrcValueOffset1, 10952 SrcValueAlign1, SrcTBAAInfo1); 10953} 10954 10955/// FindAliasInfo - Extracts the relevant alias information from the memory 10956/// node. Returns true if the operand was a nonvolatile load. 10957bool DAGCombiner::FindAliasInfo(SDNode *N, 10958 SDValue &Ptr, int64_t &Size, bool &IsVolatile, 10959 const Value *&SrcValue, 10960 int &SrcValueOffset, 10961 unsigned &SrcValueAlign, 10962 const MDNode *&TBAAInfo) const { 10963 LSBaseSDNode *LS = cast<LSBaseSDNode>(N); 10964 10965 Ptr = LS->getBasePtr(); 10966 Size = LS->getMemoryVT().getSizeInBits() >> 3; 10967 IsVolatile = LS->isVolatile(); 10968 SrcValue = LS->getSrcValue(); 10969 SrcValueOffset = LS->getSrcValueOffset(); 10970 SrcValueAlign = LS->getOriginalAlignment(); 10971 TBAAInfo = LS->getTBAAInfo(); 10972 return isa<LoadSDNode>(LS) && !IsVolatile; 10973} 10974 10975/// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes, 10976/// looking for aliasing nodes and adding them to the Aliases vector. 10977void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain, 10978 SmallVectorImpl<SDValue> &Aliases) { 10979 SmallVector<SDValue, 8> Chains; // List of chains to visit. 10980 SmallPtrSet<SDNode *, 16> Visited; // Visited node set. 10981 10982 // Get alias information for node. 10983 SDValue Ptr; 10984 int64_t Size; 10985 bool IsVolatile; 10986 const Value *SrcValue; 10987 int SrcValueOffset; 10988 unsigned SrcValueAlign; 10989 const MDNode *SrcTBAAInfo; 10990 bool IsLoad = FindAliasInfo(N, Ptr, Size, IsVolatile, SrcValue, 10991 SrcValueOffset, SrcValueAlign, SrcTBAAInfo); 10992 10993 // Starting off. 10994 Chains.push_back(OriginalChain); 10995 unsigned Depth = 0; 10996 10997 // Look at each chain and determine if it is an alias. If so, add it to the 10998 // aliases list. If not, then continue up the chain looking for the next 10999 // candidate. 11000 while (!Chains.empty()) { 11001 SDValue Chain = Chains.back(); 11002 Chains.pop_back(); 11003 11004 // For TokenFactor nodes, look at each operand and only continue up the 11005 // chain until we find two aliases. If we've seen two aliases, assume we'll 11006 // find more and revert to original chain since the xform is unlikely to be 11007 // profitable. 11008 // 11009 // FIXME: The depth check could be made to return the last non-aliasing 11010 // chain we found before we hit a tokenfactor rather than the original 11011 // chain. 11012 if (Depth > 6 || Aliases.size() == 2) { 11013 Aliases.clear(); 11014 Aliases.push_back(OriginalChain); 11015 break; 11016 } 11017 11018 // Don't bother if we've been before. 11019 if (!Visited.insert(Chain.getNode())) 11020 continue; 11021 11022 switch (Chain.getOpcode()) { 11023 case ISD::EntryToken: 11024 // Entry token is ideal chain operand, but handled in FindBetterChain. 11025 break; 11026 11027 case ISD::LOAD: 11028 case ISD::STORE: { 11029 // Get alias information for Chain. 11030 SDValue OpPtr; 11031 int64_t OpSize; 11032 bool OpIsVolatile; 11033 const Value *OpSrcValue; 11034 int OpSrcValueOffset; 11035 unsigned OpSrcValueAlign; 11036 const MDNode *OpSrcTBAAInfo; 11037 bool IsOpLoad = FindAliasInfo(Chain.getNode(), OpPtr, OpSize, 11038 OpIsVolatile, OpSrcValue, OpSrcValueOffset, 11039 OpSrcValueAlign, 11040 OpSrcTBAAInfo); 11041 11042 // If chain is alias then stop here. 11043 if (!(IsLoad && IsOpLoad) && 11044 isAlias(Ptr, Size, IsVolatile, SrcValue, SrcValueOffset, 11045 SrcValueAlign, SrcTBAAInfo, 11046 OpPtr, OpSize, OpIsVolatile, OpSrcValue, OpSrcValueOffset, 11047 OpSrcValueAlign, OpSrcTBAAInfo)) { 11048 Aliases.push_back(Chain); 11049 } else { 11050 // Look further up the chain. 11051 Chains.push_back(Chain.getOperand(0)); 11052 ++Depth; 11053 } 11054 break; 11055 } 11056 11057 case ISD::TokenFactor: 11058 // We have to check each of the operands of the token factor for "small" 11059 // token factors, so we queue them up. Adding the operands to the queue 11060 // (stack) in reverse order maintains the original order and increases the 11061 // likelihood that getNode will find a matching token factor (CSE.) 11062 if (Chain.getNumOperands() > 16) { 11063 Aliases.push_back(Chain); 11064 break; 11065 } 11066 for (unsigned n = Chain.getNumOperands(); n;) 11067 Chains.push_back(Chain.getOperand(--n)); 11068 ++Depth; 11069 break; 11070 11071 default: 11072 // For all other instructions we will just have to take what we can get. 11073 Aliases.push_back(Chain); 11074 break; 11075 } 11076 } 11077} 11078 11079/// FindBetterChain - Walk up chain skipping non-aliasing memory nodes, looking 11080/// for a better chain (aliasing node.) 11081SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) { 11082 SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor. 11083 11084 // Accumulate all the aliases to this node. 11085 GatherAllAliases(N, OldChain, Aliases); 11086 11087 // If no operands then chain to entry token. 11088 if (Aliases.size() == 0) 11089 return DAG.getEntryNode(); 11090 11091 // If a single operand then chain to it. We don't need to revisit it. 11092 if (Aliases.size() == 1) 11093 return Aliases[0]; 11094 11095 // Construct a custom tailored token factor. 11096 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, 11097 &Aliases[0], Aliases.size()); 11098} 11099 11100// SelectionDAG::Combine - This is the entry point for the file. 11101// 11102void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA, 11103 CodeGenOpt::Level OptLevel) { 11104 /// run - This is the main entry point to this class. 11105 /// 11106 DAGCombiner(*this, AA, OptLevel).Run(Level); 11107} 11108