1 //===-- DAGCombiner.cpp - Implement a DAG node combiner -------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This pass combines dag nodes to form fewer, simpler DAG nodes. It can be run 11 // both before and after the DAG is legalized. 12 // 13 // This pass is not a substitute for the LLVM IR instcombine pass. This pass is 14 // primarily intended to handle simplification opportunities that are implicit 15 // in the LLVM IR and exposed by the various codegen lowering phases. 16 // 17 //===----------------------------------------------------------------------===// 18 19 #define DEBUG_TYPE "dagcombine" 20 #include "llvm/CodeGen/SelectionDAG.h" 21 #include "llvm/ADT/SmallPtrSet.h" 22 #include "llvm/ADT/Statistic.h" 23 #include "llvm/Analysis/AliasAnalysis.h" 24 #include "llvm/CodeGen/MachineFrameInfo.h" 25 #include "llvm/CodeGen/MachineFunction.h" 26 #include "llvm/IR/DataLayout.h" 27 #include "llvm/IR/DerivedTypes.h" 28 #include "llvm/IR/Function.h" 29 #include "llvm/IR/LLVMContext.h" 30 #include "llvm/Support/CommandLine.h" 31 #include "llvm/Support/Debug.h" 32 #include "llvm/Support/ErrorHandling.h" 33 #include "llvm/Support/MathExtras.h" 34 #include "llvm/Support/raw_ostream.h" 35 #include "llvm/Target/TargetLowering.h" 36 #include "llvm/Target/TargetMachine.h" 37 #include "llvm/Target/TargetOptions.h" 38 #include "llvm/Target/TargetRegisterInfo.h" 39 #include "llvm/Target/TargetSubtargetInfo.h" 40 #include <algorithm> 41 using namespace llvm; 42 43 STATISTIC(NodesCombined , "Number of dag nodes combined"); 44 STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created"); 45 STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created"); 46 STATISTIC(OpsNarrowed , "Number of load/op/store narrowed"); 47 STATISTIC(LdStFP2Int , "Number of fp load/store pairs transformed to int"); 48 STATISTIC(SlicedLoads, "Number of load sliced"); 49 50 namespace { 51 static cl::opt<bool> 52 CombinerAA("combiner-alias-analysis", cl::Hidden, 53 cl::desc("Enable DAG combiner alias-analysis heuristics")); 54 55 static cl::opt<bool> 56 CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden, 57 cl::desc("Enable DAG combiner's use of IR alias analysis")); 58 59 // FIXME: Enable the use of TBAA. There are two known issues preventing this: 60 // 1. Stack coloring does not update TBAA when merging allocas 61 // 2. CGP inserts ptrtoint/inttoptr pairs when sinking address computations. 62 // Because BasicAA does not handle inttoptr, we'll often miss basic type 63 // punning idioms that we need to catch so we don't miscompile real-world 64 // code. 65 static cl::opt<bool> 66 UseTBAA("combiner-use-tbaa", cl::Hidden, cl::init(false), 67 cl::desc("Enable DAG combiner's use of TBAA")); 68 69 #ifndef NDEBUG 70 static cl::opt<std::string> 71 CombinerAAOnlyFunc("combiner-aa-only-func", cl::Hidden, 72 cl::desc("Only use DAG-combiner alias analysis in this" 73 " function")); 74 #endif 75 76 /// Hidden option to stress test load slicing, i.e., when this option 77 /// is enabled, load slicing bypasses most of its profitability guards. 78 static cl::opt<bool> 79 StressLoadSlicing("combiner-stress-load-slicing", cl::Hidden, 80 cl::desc("Bypass the profitability model of load " 81 "slicing"), 82 cl::init(false)); 83 84 //------------------------------ DAGCombiner ---------------------------------// 85 86 class DAGCombiner { 87 SelectionDAG &DAG; 88 const TargetLowering &TLI; 89 CombineLevel Level; 90 CodeGenOpt::Level OptLevel; 91 bool LegalOperations; 92 bool LegalTypes; 93 bool ForCodeSize; 94 95 // Worklist of all of the nodes that need to be simplified. 96 // 97 // This has the semantics that when adding to the worklist, 98 // the item added must be next to be processed. It should 99 // also only appear once. The naive approach to this takes 100 // linear time. 101 // 102 // To reduce the insert/remove time to logarithmic, we use 103 // a set and a vector to maintain our worklist. 104 // 105 // The set contains the items on the worklist, but does not 106 // maintain the order they should be visited. 107 // 108 // The vector maintains the order nodes should be visited, but may 109 // contain duplicate or removed nodes. When choosing a node to 110 // visit, we pop off the order stack until we find an item that is 111 // also in the contents set. All operations are O(log N). 112 SmallPtrSet<SDNode*, 64> WorkListContents; 113 SmallVector<SDNode*, 64> WorkListOrder; 114 115 // AA - Used for DAG load/store alias analysis. 116 AliasAnalysis &AA; 117 118 /// AddUsersToWorkList - When an instruction is simplified, add all users of 119 /// the instruction to the work lists because they might get more simplified 120 /// now. 121 /// 122 void AddUsersToWorkList(SDNode *N) { 123 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end(); 124 UI != UE; ++UI) 125 AddToWorkList(*UI); 126 } 127 128 /// visit - call the node-specific routine that knows how to fold each 129 /// particular type of node. 130 SDValue visit(SDNode *N); 131 132 public: 133 /// AddToWorkList - Add to the work list making sure its instance is at the 134 /// back (next to be processed.) 135 void AddToWorkList(SDNode *N) { 136 WorkListContents.insert(N); 137 WorkListOrder.push_back(N); 138 } 139 140 /// removeFromWorkList - remove all instances of N from the worklist. 141 /// 142 void removeFromWorkList(SDNode *N) { 143 WorkListContents.erase(N); 144 } 145 146 SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo, 147 bool AddTo = true); 148 149 SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) { 150 return CombineTo(N, &Res, 1, AddTo); 151 } 152 153 SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1, 154 bool AddTo = true) { 155 SDValue To[] = { Res0, Res1 }; 156 return CombineTo(N, To, 2, AddTo); 157 } 158 159 void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO); 160 161 private: 162 163 /// SimplifyDemandedBits - Check the specified integer node value to see if 164 /// it can be simplified or if things it uses can be simplified by bit 165 /// propagation. If so, return true. 166 bool SimplifyDemandedBits(SDValue Op) { 167 unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits(); 168 APInt Demanded = APInt::getAllOnesValue(BitWidth); 169 return SimplifyDemandedBits(Op, Demanded); 170 } 171 172 bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded); 173 174 bool CombineToPreIndexedLoadStore(SDNode *N); 175 bool CombineToPostIndexedLoadStore(SDNode *N); 176 bool SliceUpLoad(SDNode *N); 177 178 void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad); 179 SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace); 180 SDValue SExtPromoteOperand(SDValue Op, EVT PVT); 181 SDValue ZExtPromoteOperand(SDValue Op, EVT PVT); 182 SDValue PromoteIntBinOp(SDValue Op); 183 SDValue PromoteIntShiftOp(SDValue Op); 184 SDValue PromoteExtend(SDValue Op); 185 bool PromoteLoad(SDValue Op); 186 187 void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs, 188 SDValue Trunc, SDValue ExtLoad, SDLoc DL, 189 ISD::NodeType ExtType); 190 191 /// combine - call the node-specific routine that knows how to fold each 192 /// particular type of node. If that doesn't do anything, try the 193 /// target-specific DAG combines. 194 SDValue combine(SDNode *N); 195 196 // Visitation implementation - Implement dag node combining for different 197 // node types. The semantics are as follows: 198 // Return Value: 199 // SDValue.getNode() == 0 - No change was made 200 // SDValue.getNode() == N - N was replaced, is dead and has been handled. 201 // otherwise - N should be replaced by the returned Operand. 202 // 203 SDValue visitTokenFactor(SDNode *N); 204 SDValue visitMERGE_VALUES(SDNode *N); 205 SDValue visitADD(SDNode *N); 206 SDValue visitSUB(SDNode *N); 207 SDValue visitADDC(SDNode *N); 208 SDValue visitSUBC(SDNode *N); 209 SDValue visitADDE(SDNode *N); 210 SDValue visitSUBE(SDNode *N); 211 SDValue visitMUL(SDNode *N); 212 SDValue visitSDIV(SDNode *N); 213 SDValue visitUDIV(SDNode *N); 214 SDValue visitSREM(SDNode *N); 215 SDValue visitUREM(SDNode *N); 216 SDValue visitMULHU(SDNode *N); 217 SDValue visitMULHS(SDNode *N); 218 SDValue visitSMUL_LOHI(SDNode *N); 219 SDValue visitUMUL_LOHI(SDNode *N); 220 SDValue visitSMULO(SDNode *N); 221 SDValue visitUMULO(SDNode *N); 222 SDValue visitSDIVREM(SDNode *N); 223 SDValue visitUDIVREM(SDNode *N); 224 SDValue visitAND(SDNode *N); 225 SDValue visitOR(SDNode *N); 226 SDValue visitXOR(SDNode *N); 227 SDValue SimplifyVBinOp(SDNode *N); 228 SDValue SimplifyVUnaryOp(SDNode *N); 229 SDValue visitSHL(SDNode *N); 230 SDValue visitSRA(SDNode *N); 231 SDValue visitSRL(SDNode *N); 232 SDValue visitCTLZ(SDNode *N); 233 SDValue visitCTLZ_ZERO_UNDEF(SDNode *N); 234 SDValue visitCTTZ(SDNode *N); 235 SDValue visitCTTZ_ZERO_UNDEF(SDNode *N); 236 SDValue visitCTPOP(SDNode *N); 237 SDValue visitSELECT(SDNode *N); 238 SDValue visitVSELECT(SDNode *N); 239 SDValue visitSELECT_CC(SDNode *N); 240 SDValue visitSETCC(SDNode *N); 241 SDValue visitSIGN_EXTEND(SDNode *N); 242 SDValue visitZERO_EXTEND(SDNode *N); 243 SDValue visitANY_EXTEND(SDNode *N); 244 SDValue visitSIGN_EXTEND_INREG(SDNode *N); 245 SDValue visitTRUNCATE(SDNode *N); 246 SDValue visitBITCAST(SDNode *N); 247 SDValue visitBUILD_PAIR(SDNode *N); 248 SDValue visitFADD(SDNode *N); 249 SDValue visitFSUB(SDNode *N); 250 SDValue visitFMUL(SDNode *N); 251 SDValue visitFMA(SDNode *N); 252 SDValue visitFDIV(SDNode *N); 253 SDValue visitFREM(SDNode *N); 254 SDValue visitFCOPYSIGN(SDNode *N); 255 SDValue visitSINT_TO_FP(SDNode *N); 256 SDValue visitUINT_TO_FP(SDNode *N); 257 SDValue visitFP_TO_SINT(SDNode *N); 258 SDValue visitFP_TO_UINT(SDNode *N); 259 SDValue visitFP_ROUND(SDNode *N); 260 SDValue visitFP_ROUND_INREG(SDNode *N); 261 SDValue visitFP_EXTEND(SDNode *N); 262 SDValue visitFNEG(SDNode *N); 263 SDValue visitFABS(SDNode *N); 264 SDValue visitFCEIL(SDNode *N); 265 SDValue visitFTRUNC(SDNode *N); 266 SDValue visitFFLOOR(SDNode *N); 267 SDValue visitBRCOND(SDNode *N); 268 SDValue visitBR_CC(SDNode *N); 269 SDValue visitLOAD(SDNode *N); 270 SDValue visitSTORE(SDNode *N); 271 SDValue visitINSERT_VECTOR_ELT(SDNode *N); 272 SDValue visitEXTRACT_VECTOR_ELT(SDNode *N); 273 SDValue visitBUILD_VECTOR(SDNode *N); 274 SDValue visitCONCAT_VECTORS(SDNode *N); 275 SDValue visitEXTRACT_SUBVECTOR(SDNode *N); 276 SDValue visitVECTOR_SHUFFLE(SDNode *N); 277 278 SDValue XformToShuffleWithZero(SDNode *N); 279 SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS); 280 281 SDValue visitShiftByConstant(SDNode *N, unsigned Amt); 282 283 bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS); 284 SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N); 285 SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2); 286 SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2, 287 SDValue N3, ISD::CondCode CC, 288 bool NotExtCompare = false); 289 SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond, 290 SDLoc DL, bool foldBooleans = true); 291 SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp, 292 unsigned HiOp); 293 SDValue CombineConsecutiveLoads(SDNode *N, EVT VT); 294 SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT); 295 SDValue BuildSDIV(SDNode *N); 296 SDValue BuildUDIV(SDNode *N); 297 SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1, 298 bool DemandHighBits = true); 299 SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1); 300 SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg, 301 SDValue InnerPos, SDValue InnerNeg, 302 unsigned PosOpcode, unsigned NegOpcode, 303 SDLoc DL); 304 SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL); 305 SDValue ReduceLoadWidth(SDNode *N); 306 SDValue ReduceLoadOpStoreWidth(SDNode *N); 307 SDValue TransformFPLoadStorePair(SDNode *N); 308 SDValue reduceBuildVecExtToExtBuildVec(SDNode *N); 309 SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N); 310 311 SDValue GetDemandedBits(SDValue V, const APInt &Mask); 312 313 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes, 314 /// looking for aliasing nodes and adding them to the Aliases vector. 315 void GatherAllAliases(SDNode *N, SDValue OriginalChain, 316 SmallVectorImpl<SDValue> &Aliases); 317 318 /// isAlias - Return true if there is any possibility that the two addresses 319 /// overlap. 320 bool isAlias(SDValue Ptr1, int64_t Size1, bool IsVolatile1, 321 const Value *SrcValue1, int SrcValueOffset1, 322 unsigned SrcValueAlign1, 323 const MDNode *TBAAInfo1, 324 SDValue Ptr2, int64_t Size2, bool IsVolatile2, 325 const Value *SrcValue2, int SrcValueOffset2, 326 unsigned SrcValueAlign2, 327 const MDNode *TBAAInfo2) const; 328 329 /// isAlias - Return true if there is any possibility that the two addresses 330 /// overlap. 331 bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1); 332 333 /// FindAliasInfo - Extracts the relevant alias information from the memory 334 /// node. Returns true if the operand was a load. 335 bool FindAliasInfo(SDNode *N, 336 SDValue &Ptr, int64_t &Size, bool &IsVolatile, 337 const Value *&SrcValue, int &SrcValueOffset, 338 unsigned &SrcValueAlignment, 339 const MDNode *&TBAAInfo) const; 340 341 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes, 342 /// looking for a better chain (aliasing node.) 343 SDValue FindBetterChain(SDNode *N, SDValue Chain); 344 345 /// Merge consecutive store operations into a wide store. 346 /// This optimization uses wide integers or vectors when possible. 347 /// \return True if some memory operations were changed. 348 bool MergeConsecutiveStores(StoreSDNode *N); 349 350 public: 351 DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL) 352 : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes), 353 OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) { 354 AttributeSet FnAttrs = 355 DAG.getMachineFunction().getFunction()->getAttributes(); 356 ForCodeSize = 357 FnAttrs.hasAttribute(AttributeSet::FunctionIndex, 358 Attribute::OptimizeForSize) || 359 FnAttrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::MinSize); 360 } 361 362 /// Run - runs the dag combiner on all nodes in the work list 363 void Run(CombineLevel AtLevel); 364 365 SelectionDAG &getDAG() const { return DAG; } 366 367 /// getShiftAmountTy - Returns a type large enough to hold any valid 368 /// shift amount - before type legalization these can be huge. 369 EVT getShiftAmountTy(EVT LHSTy) { 370 assert(LHSTy.isInteger() && "Shift amount is not an integer type!"); 371 if (LHSTy.isVector()) 372 return LHSTy; 373 return LegalTypes ? TLI.getScalarShiftAmountTy(LHSTy) 374 : TLI.getPointerTy(); 375 } 376 377 /// isTypeLegal - This method returns true if we are running before type 378 /// legalization or if the specified VT is legal. 379 bool isTypeLegal(const EVT &VT) { 380 if (!LegalTypes) return true; 381 return TLI.isTypeLegal(VT); 382 } 383 384 /// getSetCCResultType - Convenience wrapper around 385 /// TargetLowering::getSetCCResultType 386 EVT getSetCCResultType(EVT VT) const { 387 return TLI.getSetCCResultType(*DAG.getContext(), VT); 388 } 389 }; 390 } 391 392 393 namespace { 394 /// WorkListRemover - This class is a DAGUpdateListener that removes any deleted 395 /// nodes from the worklist. 396 class WorkListRemover : public SelectionDAG::DAGUpdateListener { 397 DAGCombiner &DC; 398 public: 399 explicit WorkListRemover(DAGCombiner &dc) 400 : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {} 401 402 virtual void NodeDeleted(SDNode *N, SDNode *E) { 403 DC.removeFromWorkList(N); 404 } 405 }; 406 } 407 408 //===----------------------------------------------------------------------===// 409 // TargetLowering::DAGCombinerInfo implementation 410 //===----------------------------------------------------------------------===// 411 412 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) { 413 ((DAGCombiner*)DC)->AddToWorkList(N); 414 } 415 416 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) { 417 ((DAGCombiner*)DC)->removeFromWorkList(N); 418 } 419 420 SDValue TargetLowering::DAGCombinerInfo:: 421 CombineTo(SDNode *N, const std::vector<SDValue> &To, bool AddTo) { 422 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo); 423 } 424 425 SDValue TargetLowering::DAGCombinerInfo:: 426 CombineTo(SDNode *N, SDValue Res, bool AddTo) { 427 return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo); 428 } 429 430 431 SDValue TargetLowering::DAGCombinerInfo:: 432 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) { 433 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo); 434 } 435 436 void TargetLowering::DAGCombinerInfo:: 437 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) { 438 return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO); 439 } 440 441 //===----------------------------------------------------------------------===// 442 // Helper Functions 443 //===----------------------------------------------------------------------===// 444 445 /// isNegatibleForFree - Return 1 if we can compute the negated form of the 446 /// specified expression for the same cost as the expression itself, or 2 if we 447 /// can compute the negated form more cheaply than the expression itself. 448 static char isNegatibleForFree(SDValue Op, bool LegalOperations, 449 const TargetLowering &TLI, 450 const TargetOptions *Options, 451 unsigned Depth = 0) { 452 // fneg is removable even if it has multiple uses. 453 if (Op.getOpcode() == ISD::FNEG) return 2; 454 455 // Don't allow anything with multiple uses. 456 if (!Op.hasOneUse()) return 0; 457 458 // Don't recurse exponentially. 459 if (Depth > 6) return 0; 460 461 switch (Op.getOpcode()) { 462 default: return false; 463 case ISD::ConstantFP: 464 // Don't invert constant FP values after legalize. The negated constant 465 // isn't necessarily legal. 466 return LegalOperations ? 0 : 1; 467 case ISD::FADD: 468 // FIXME: determine better conditions for this xform. 469 if (!Options->UnsafeFPMath) return 0; 470 471 // After operation legalization, it might not be legal to create new FSUBs. 472 if (LegalOperations && 473 !TLI.isOperationLegalOrCustom(ISD::FSUB, Op.getValueType())) 474 return 0; 475 476 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B) 477 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, 478 Options, Depth + 1)) 479 return V; 480 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A) 481 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options, 482 Depth + 1); 483 case ISD::FSUB: 484 // We can't turn -(A-B) into B-A when we honor signed zeros. 485 if (!Options->UnsafeFPMath) return 0; 486 487 // fold (fneg (fsub A, B)) -> (fsub B, A) 488 return 1; 489 490 case ISD::FMUL: 491 case ISD::FDIV: 492 if (Options->HonorSignDependentRoundingFPMath()) return 0; 493 494 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y)) 495 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, 496 Options, Depth + 1)) 497 return V; 498 499 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options, 500 Depth + 1); 501 502 case ISD::FP_EXTEND: 503 case ISD::FP_ROUND: 504 case ISD::FSIN: 505 return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options, 506 Depth + 1); 507 } 508 } 509 510 /// GetNegatedExpression - If isNegatibleForFree returns true, this function 511 /// returns the newly negated expression. 512 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG, 513 bool LegalOperations, unsigned Depth = 0) { 514 // fneg is removable even if it has multiple uses. 515 if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0); 516 517 // Don't allow anything with multiple uses. 518 assert(Op.hasOneUse() && "Unknown reuse!"); 519 520 assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree"); 521 switch (Op.getOpcode()) { 522 default: llvm_unreachable("Unknown code"); 523 case ISD::ConstantFP: { 524 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF(); 525 V.changeSign(); 526 return DAG.getConstantFP(V, Op.getValueType()); 527 } 528 case ISD::FADD: 529 // FIXME: determine better conditions for this xform. 530 assert(DAG.getTarget().Options.UnsafeFPMath); 531 532 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B) 533 if (isNegatibleForFree(Op.getOperand(0), LegalOperations, 534 DAG.getTargetLoweringInfo(), 535 &DAG.getTarget().Options, Depth+1)) 536 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(), 537 GetNegatedExpression(Op.getOperand(0), DAG, 538 LegalOperations, Depth+1), 539 Op.getOperand(1)); 540 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A) 541 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(), 542 GetNegatedExpression(Op.getOperand(1), DAG, 543 LegalOperations, Depth+1), 544 Op.getOperand(0)); 545 case ISD::FSUB: 546 // We can't turn -(A-B) into B-A when we honor signed zeros. 547 assert(DAG.getTarget().Options.UnsafeFPMath); 548 549 // fold (fneg (fsub 0, B)) -> B 550 if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0))) 551 if (N0CFP->getValueAPF().isZero()) 552 return Op.getOperand(1); 553 554 // fold (fneg (fsub A, B)) -> (fsub B, A) 555 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(), 556 Op.getOperand(1), Op.getOperand(0)); 557 558 case ISD::FMUL: 559 case ISD::FDIV: 560 assert(!DAG.getTarget().Options.HonorSignDependentRoundingFPMath()); 561 562 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) 563 if (isNegatibleForFree(Op.getOperand(0), LegalOperations, 564 DAG.getTargetLoweringInfo(), 565 &DAG.getTarget().Options, Depth+1)) 566 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(), 567 GetNegatedExpression(Op.getOperand(0), DAG, 568 LegalOperations, Depth+1), 569 Op.getOperand(1)); 570 571 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y)) 572 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(), 573 Op.getOperand(0), 574 GetNegatedExpression(Op.getOperand(1), DAG, 575 LegalOperations, Depth+1)); 576 577 case ISD::FP_EXTEND: 578 case ISD::FSIN: 579 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(), 580 GetNegatedExpression(Op.getOperand(0), DAG, 581 LegalOperations, Depth+1)); 582 case ISD::FP_ROUND: 583 return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(), 584 GetNegatedExpression(Op.getOperand(0), DAG, 585 LegalOperations, Depth+1), 586 Op.getOperand(1)); 587 } 588 } 589 590 591 // isSetCCEquivalent - Return true if this node is a setcc, or is a select_cc 592 // that selects between the values 1 and 0, making it equivalent to a setcc. 593 // Also, set the incoming LHS, RHS, and CC references to the appropriate 594 // nodes based on the type of node we are checking. This simplifies life a 595 // bit for the callers. 596 static bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS, 597 SDValue &CC) { 598 if (N.getOpcode() == ISD::SETCC) { 599 LHS = N.getOperand(0); 600 RHS = N.getOperand(1); 601 CC = N.getOperand(2); 602 return true; 603 } 604 if (N.getOpcode() == ISD::SELECT_CC && 605 N.getOperand(2).getOpcode() == ISD::Constant && 606 N.getOperand(3).getOpcode() == ISD::Constant && 607 cast<ConstantSDNode>(N.getOperand(2))->getAPIntValue() == 1 && 608 cast<ConstantSDNode>(N.getOperand(3))->isNullValue()) { 609 LHS = N.getOperand(0); 610 RHS = N.getOperand(1); 611 CC = N.getOperand(4); 612 return true; 613 } 614 return false; 615 } 616 617 // isOneUseSetCC - Return true if this is a SetCC-equivalent operation with only 618 // one use. If this is true, it allows the users to invert the operation for 619 // free when it is profitable to do so. 620 static bool isOneUseSetCC(SDValue N) { 621 SDValue N0, N1, N2; 622 if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse()) 623 return true; 624 return false; 625 } 626 627 // \brief Returns the SDNode if it is a constant BuildVector or constant int. 628 static SDNode *isConstantBuildVectorOrConstantInt(SDValue N) { 629 if (isa<ConstantSDNode>(N)) 630 return N.getNode(); 631 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N); 632 if(BV && BV->isConstant()) 633 return BV; 634 return NULL; 635 } 636 637 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL, 638 SDValue N0, SDValue N1) { 639 EVT VT = N0.getValueType(); 640 if (N0.getOpcode() == Opc) { 641 if (SDNode *L = isConstantBuildVectorOrConstantInt(N0.getOperand(1))) { 642 if (SDNode *R = isConstantBuildVectorOrConstantInt(N1)) { 643 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2)) 644 SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, L, R); 645 if (!OpNode.getNode()) 646 return SDValue(); 647 return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode); 648 } 649 if (N0.hasOneUse()) { 650 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one 651 // use 652 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1); 653 if (!OpNode.getNode()) 654 return SDValue(); 655 AddToWorkList(OpNode.getNode()); 656 return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1)); 657 } 658 } 659 } 660 661 if (N1.getOpcode() == Opc) { 662 if (SDNode *R = isConstantBuildVectorOrConstantInt(N1.getOperand(1))) { 663 if (SDNode *L = isConstantBuildVectorOrConstantInt(N0)) { 664 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2)) 665 SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, R, L); 666 if (!OpNode.getNode()) 667 return SDValue(); 668 return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode); 669 } 670 if (N1.hasOneUse()) { 671 // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one 672 // use 673 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0); 674 if (!OpNode.getNode()) 675 return SDValue(); 676 AddToWorkList(OpNode.getNode()); 677 return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1)); 678 } 679 } 680 } 681 682 return SDValue(); 683 } 684 685 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo, 686 bool AddTo) { 687 assert(N->getNumValues() == NumTo && "Broken CombineTo call!"); 688 ++NodesCombined; 689 DEBUG(dbgs() << "\nReplacing.1 "; 690 N->dump(&DAG); 691 dbgs() << "\nWith: "; 692 To[0].getNode()->dump(&DAG); 693 dbgs() << " and " << NumTo-1 << " other values\n"; 694 for (unsigned i = 0, e = NumTo; i != e; ++i) 695 assert((!To[i].getNode() || 696 N->getValueType(i) == To[i].getValueType()) && 697 "Cannot combine value to value of different type!")); 698 WorkListRemover DeadNodes(*this); 699 DAG.ReplaceAllUsesWith(N, To); 700 if (AddTo) { 701 // Push the new nodes and any users onto the worklist 702 for (unsigned i = 0, e = NumTo; i != e; ++i) { 703 if (To[i].getNode()) { 704 AddToWorkList(To[i].getNode()); 705 AddUsersToWorkList(To[i].getNode()); 706 } 707 } 708 } 709 710 // Finally, if the node is now dead, remove it from the graph. The node 711 // may not be dead if the replacement process recursively simplified to 712 // something else needing this node. 713 if (N->use_empty()) { 714 // Nodes can be reintroduced into the worklist. Make sure we do not 715 // process a node that has been replaced. 716 removeFromWorkList(N); 717 718 // Finally, since the node is now dead, remove it from the graph. 719 DAG.DeleteNode(N); 720 } 721 return SDValue(N, 0); 722 } 723 724 void DAGCombiner:: 725 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) { 726 // Replace all uses. If any nodes become isomorphic to other nodes and 727 // are deleted, make sure to remove them from our worklist. 728 WorkListRemover DeadNodes(*this); 729 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New); 730 731 // Push the new node and any (possibly new) users onto the worklist. 732 AddToWorkList(TLO.New.getNode()); 733 AddUsersToWorkList(TLO.New.getNode()); 734 735 // Finally, if the node is now dead, remove it from the graph. The node 736 // may not be dead if the replacement process recursively simplified to 737 // something else needing this node. 738 if (TLO.Old.getNode()->use_empty()) { 739 removeFromWorkList(TLO.Old.getNode()); 740 741 // If the operands of this node are only used by the node, they will now 742 // be dead. Make sure to visit them first to delete dead nodes early. 743 for (unsigned i = 0, e = TLO.Old.getNode()->getNumOperands(); i != e; ++i) 744 if (TLO.Old.getNode()->getOperand(i).getNode()->hasOneUse()) 745 AddToWorkList(TLO.Old.getNode()->getOperand(i).getNode()); 746 747 DAG.DeleteNode(TLO.Old.getNode()); 748 } 749 } 750 751 /// SimplifyDemandedBits - Check the specified integer node value to see if 752 /// it can be simplified or if things it uses can be simplified by bit 753 /// propagation. If so, return true. 754 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) { 755 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations); 756 APInt KnownZero, KnownOne; 757 if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO)) 758 return false; 759 760 // Revisit the node. 761 AddToWorkList(Op.getNode()); 762 763 // Replace the old value with the new one. 764 ++NodesCombined; 765 DEBUG(dbgs() << "\nReplacing.2 "; 766 TLO.Old.getNode()->dump(&DAG); 767 dbgs() << "\nWith: "; 768 TLO.New.getNode()->dump(&DAG); 769 dbgs() << '\n'); 770 771 CommitTargetLoweringOpt(TLO); 772 return true; 773 } 774 775 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) { 776 SDLoc dl(Load); 777 EVT VT = Load->getValueType(0); 778 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0)); 779 780 DEBUG(dbgs() << "\nReplacing.9 "; 781 Load->dump(&DAG); 782 dbgs() << "\nWith: "; 783 Trunc.getNode()->dump(&DAG); 784 dbgs() << '\n'); 785 WorkListRemover DeadNodes(*this); 786 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc); 787 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1)); 788 removeFromWorkList(Load); 789 DAG.DeleteNode(Load); 790 AddToWorkList(Trunc.getNode()); 791 } 792 793 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) { 794 Replace = false; 795 SDLoc dl(Op); 796 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) { 797 EVT MemVT = LD->getMemoryVT(); 798 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD) 799 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD 800 : ISD::EXTLOAD) 801 : LD->getExtensionType(); 802 Replace = true; 803 return DAG.getExtLoad(ExtType, dl, PVT, 804 LD->getChain(), LD->getBasePtr(), 805 MemVT, LD->getMemOperand()); 806 } 807 808 unsigned Opc = Op.getOpcode(); 809 switch (Opc) { 810 default: break; 811 case ISD::AssertSext: 812 return DAG.getNode(ISD::AssertSext, dl, PVT, 813 SExtPromoteOperand(Op.getOperand(0), PVT), 814 Op.getOperand(1)); 815 case ISD::AssertZext: 816 return DAG.getNode(ISD::AssertZext, dl, PVT, 817 ZExtPromoteOperand(Op.getOperand(0), PVT), 818 Op.getOperand(1)); 819 case ISD::Constant: { 820 unsigned ExtOpc = 821 Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 822 return DAG.getNode(ExtOpc, dl, PVT, Op); 823 } 824 } 825 826 if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT)) 827 return SDValue(); 828 return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op); 829 } 830 831 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) { 832 if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT)) 833 return SDValue(); 834 EVT OldVT = Op.getValueType(); 835 SDLoc dl(Op); 836 bool Replace = false; 837 SDValue NewOp = PromoteOperand(Op, PVT, Replace); 838 if (NewOp.getNode() == 0) 839 return SDValue(); 840 AddToWorkList(NewOp.getNode()); 841 842 if (Replace) 843 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode()); 844 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp, 845 DAG.getValueType(OldVT)); 846 } 847 848 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) { 849 EVT OldVT = Op.getValueType(); 850 SDLoc dl(Op); 851 bool Replace = false; 852 SDValue NewOp = PromoteOperand(Op, PVT, Replace); 853 if (NewOp.getNode() == 0) 854 return SDValue(); 855 AddToWorkList(NewOp.getNode()); 856 857 if (Replace) 858 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode()); 859 return DAG.getZeroExtendInReg(NewOp, dl, OldVT); 860 } 861 862 /// PromoteIntBinOp - Promote the specified integer binary operation if the 863 /// target indicates it is beneficial. e.g. On x86, it's usually better to 864 /// promote i16 operations to i32 since i16 instructions are longer. 865 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) { 866 if (!LegalOperations) 867 return SDValue(); 868 869 EVT VT = Op.getValueType(); 870 if (VT.isVector() || !VT.isInteger()) 871 return SDValue(); 872 873 // If operation type is 'undesirable', e.g. i16 on x86, consider 874 // promoting it. 875 unsigned Opc = Op.getOpcode(); 876 if (TLI.isTypeDesirableForOp(Opc, VT)) 877 return SDValue(); 878 879 EVT PVT = VT; 880 // Consult target whether it is a good idea to promote this operation and 881 // what's the right type to promote it to. 882 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 883 assert(PVT != VT && "Don't know what type to promote to!"); 884 885 bool Replace0 = false; 886 SDValue N0 = Op.getOperand(0); 887 SDValue NN0 = PromoteOperand(N0, PVT, Replace0); 888 if (NN0.getNode() == 0) 889 return SDValue(); 890 891 bool Replace1 = false; 892 SDValue N1 = Op.getOperand(1); 893 SDValue NN1; 894 if (N0 == N1) 895 NN1 = NN0; 896 else { 897 NN1 = PromoteOperand(N1, PVT, Replace1); 898 if (NN1.getNode() == 0) 899 return SDValue(); 900 } 901 902 AddToWorkList(NN0.getNode()); 903 if (NN1.getNode()) 904 AddToWorkList(NN1.getNode()); 905 906 if (Replace0) 907 ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode()); 908 if (Replace1) 909 ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode()); 910 911 DEBUG(dbgs() << "\nPromoting "; 912 Op.getNode()->dump(&DAG)); 913 SDLoc dl(Op); 914 return DAG.getNode(ISD::TRUNCATE, dl, VT, 915 DAG.getNode(Opc, dl, PVT, NN0, NN1)); 916 } 917 return SDValue(); 918 } 919 920 /// PromoteIntShiftOp - Promote the specified integer shift operation if the 921 /// target indicates it is beneficial. e.g. On x86, it's usually better to 922 /// promote i16 operations to i32 since i16 instructions are longer. 923 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) { 924 if (!LegalOperations) 925 return SDValue(); 926 927 EVT VT = Op.getValueType(); 928 if (VT.isVector() || !VT.isInteger()) 929 return SDValue(); 930 931 // If operation type is 'undesirable', e.g. i16 on x86, consider 932 // promoting it. 933 unsigned Opc = Op.getOpcode(); 934 if (TLI.isTypeDesirableForOp(Opc, VT)) 935 return SDValue(); 936 937 EVT PVT = VT; 938 // Consult target whether it is a good idea to promote this operation and 939 // what's the right type to promote it to. 940 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 941 assert(PVT != VT && "Don't know what type to promote to!"); 942 943 bool Replace = false; 944 SDValue N0 = Op.getOperand(0); 945 if (Opc == ISD::SRA) 946 N0 = SExtPromoteOperand(Op.getOperand(0), PVT); 947 else if (Opc == ISD::SRL) 948 N0 = ZExtPromoteOperand(Op.getOperand(0), PVT); 949 else 950 N0 = PromoteOperand(N0, PVT, Replace); 951 if (N0.getNode() == 0) 952 return SDValue(); 953 954 AddToWorkList(N0.getNode()); 955 if (Replace) 956 ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode()); 957 958 DEBUG(dbgs() << "\nPromoting "; 959 Op.getNode()->dump(&DAG)); 960 SDLoc dl(Op); 961 return DAG.getNode(ISD::TRUNCATE, dl, VT, 962 DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1))); 963 } 964 return SDValue(); 965 } 966 967 SDValue DAGCombiner::PromoteExtend(SDValue Op) { 968 if (!LegalOperations) 969 return SDValue(); 970 971 EVT VT = Op.getValueType(); 972 if (VT.isVector() || !VT.isInteger()) 973 return SDValue(); 974 975 // If operation type is 'undesirable', e.g. i16 on x86, consider 976 // promoting it. 977 unsigned Opc = Op.getOpcode(); 978 if (TLI.isTypeDesirableForOp(Opc, VT)) 979 return SDValue(); 980 981 EVT PVT = VT; 982 // Consult target whether it is a good idea to promote this operation and 983 // what's the right type to promote it to. 984 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 985 assert(PVT != VT && "Don't know what type to promote to!"); 986 // fold (aext (aext x)) -> (aext x) 987 // fold (aext (zext x)) -> (zext x) 988 // fold (aext (sext x)) -> (sext x) 989 DEBUG(dbgs() << "\nPromoting "; 990 Op.getNode()->dump(&DAG)); 991 return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0)); 992 } 993 return SDValue(); 994 } 995 996 bool DAGCombiner::PromoteLoad(SDValue Op) { 997 if (!LegalOperations) 998 return false; 999 1000 EVT VT = Op.getValueType(); 1001 if (VT.isVector() || !VT.isInteger()) 1002 return false; 1003 1004 // If operation type is 'undesirable', e.g. i16 on x86, consider 1005 // promoting it. 1006 unsigned Opc = Op.getOpcode(); 1007 if (TLI.isTypeDesirableForOp(Opc, VT)) 1008 return false; 1009 1010 EVT PVT = VT; 1011 // Consult target whether it is a good idea to promote this operation and 1012 // what's the right type to promote it to. 1013 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 1014 assert(PVT != VT && "Don't know what type to promote to!"); 1015 1016 SDLoc dl(Op); 1017 SDNode *N = Op.getNode(); 1018 LoadSDNode *LD = cast<LoadSDNode>(N); 1019 EVT MemVT = LD->getMemoryVT(); 1020 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD) 1021 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD 1022 : ISD::EXTLOAD) 1023 : LD->getExtensionType(); 1024 SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT, 1025 LD->getChain(), LD->getBasePtr(), 1026 MemVT, LD->getMemOperand()); 1027 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD); 1028 1029 DEBUG(dbgs() << "\nPromoting "; 1030 N->dump(&DAG); 1031 dbgs() << "\nTo: "; 1032 Result.getNode()->dump(&DAG); 1033 dbgs() << '\n'); 1034 WorkListRemover DeadNodes(*this); 1035 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result); 1036 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1)); 1037 removeFromWorkList(N); 1038 DAG.DeleteNode(N); 1039 AddToWorkList(Result.getNode()); 1040 return true; 1041 } 1042 return false; 1043 } 1044 1045 1046 //===----------------------------------------------------------------------===// 1047 // Main DAG Combiner implementation 1048 //===----------------------------------------------------------------------===// 1049 1050 void DAGCombiner::Run(CombineLevel AtLevel) { 1051 // set the instance variables, so that the various visit routines may use it. 1052 Level = AtLevel; 1053 LegalOperations = Level >= AfterLegalizeVectorOps; 1054 LegalTypes = Level >= AfterLegalizeTypes; 1055 1056 // Add all the dag nodes to the worklist. 1057 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(), 1058 E = DAG.allnodes_end(); I != E; ++I) 1059 AddToWorkList(I); 1060 1061 // Create a dummy node (which is not added to allnodes), that adds a reference 1062 // to the root node, preventing it from being deleted, and tracking any 1063 // changes of the root. 1064 HandleSDNode Dummy(DAG.getRoot()); 1065 1066 // The root of the dag may dangle to deleted nodes until the dag combiner is 1067 // done. Set it to null to avoid confusion. 1068 DAG.setRoot(SDValue()); 1069 1070 // while the worklist isn't empty, find a node and 1071 // try and combine it. 1072 while (!WorkListContents.empty()) { 1073 SDNode *N; 1074 // The WorkListOrder holds the SDNodes in order, but it may contain 1075 // duplicates. 1076 // In order to avoid a linear scan, we use a set (O(log N)) to hold what the 1077 // worklist *should* contain, and check the node we want to visit is should 1078 // actually be visited. 1079 do { 1080 N = WorkListOrder.pop_back_val(); 1081 } while (!WorkListContents.erase(N)); 1082 1083 // If N has no uses, it is dead. Make sure to revisit all N's operands once 1084 // N is deleted from the DAG, since they too may now be dead or may have a 1085 // reduced number of uses, allowing other xforms. 1086 if (N->use_empty() && N != &Dummy) { 1087 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) 1088 AddToWorkList(N->getOperand(i).getNode()); 1089 1090 DAG.DeleteNode(N); 1091 continue; 1092 } 1093 1094 SDValue RV = combine(N); 1095 1096 if (RV.getNode() == 0) 1097 continue; 1098 1099 ++NodesCombined; 1100 1101 // If we get back the same node we passed in, rather than a new node or 1102 // zero, we know that the node must have defined multiple values and 1103 // CombineTo was used. Since CombineTo takes care of the worklist 1104 // mechanics for us, we have no work to do in this case. 1105 if (RV.getNode() == N) 1106 continue; 1107 1108 assert(N->getOpcode() != ISD::DELETED_NODE && 1109 RV.getNode()->getOpcode() != ISD::DELETED_NODE && 1110 "Node was deleted but visit returned new node!"); 1111 1112 DEBUG(dbgs() << "\nReplacing.3 "; 1113 N->dump(&DAG); 1114 dbgs() << "\nWith: "; 1115 RV.getNode()->dump(&DAG); 1116 dbgs() << '\n'); 1117 1118 // Transfer debug value. 1119 DAG.TransferDbgValues(SDValue(N, 0), RV); 1120 WorkListRemover DeadNodes(*this); 1121 if (N->getNumValues() == RV.getNode()->getNumValues()) 1122 DAG.ReplaceAllUsesWith(N, RV.getNode()); 1123 else { 1124 assert(N->getValueType(0) == RV.getValueType() && 1125 N->getNumValues() == 1 && "Type mismatch"); 1126 SDValue OpV = RV; 1127 DAG.ReplaceAllUsesWith(N, &OpV); 1128 } 1129 1130 // Push the new node and any users onto the worklist 1131 AddToWorkList(RV.getNode()); 1132 AddUsersToWorkList(RV.getNode()); 1133 1134 // Add any uses of the old node to the worklist in case this node is the 1135 // last one that uses them. They may become dead after this node is 1136 // deleted. 1137 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) 1138 AddToWorkList(N->getOperand(i).getNode()); 1139 1140 // Finally, if the node is now dead, remove it from the graph. The node 1141 // may not be dead if the replacement process recursively simplified to 1142 // something else needing this node. 1143 if (N->use_empty()) { 1144 // Nodes can be reintroduced into the worklist. Make sure we do not 1145 // process a node that has been replaced. 1146 removeFromWorkList(N); 1147 1148 // Finally, since the node is now dead, remove it from the graph. 1149 DAG.DeleteNode(N); 1150 } 1151 } 1152 1153 // If the root changed (e.g. it was a dead load, update the root). 1154 DAG.setRoot(Dummy.getValue()); 1155 DAG.RemoveDeadNodes(); 1156 } 1157 1158 SDValue DAGCombiner::visit(SDNode *N) { 1159 switch (N->getOpcode()) { 1160 default: break; 1161 case ISD::TokenFactor: return visitTokenFactor(N); 1162 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N); 1163 case ISD::ADD: return visitADD(N); 1164 case ISD::SUB: return visitSUB(N); 1165 case ISD::ADDC: return visitADDC(N); 1166 case ISD::SUBC: return visitSUBC(N); 1167 case ISD::ADDE: return visitADDE(N); 1168 case ISD::SUBE: return visitSUBE(N); 1169 case ISD::MUL: return visitMUL(N); 1170 case ISD::SDIV: return visitSDIV(N); 1171 case ISD::UDIV: return visitUDIV(N); 1172 case ISD::SREM: return visitSREM(N); 1173 case ISD::UREM: return visitUREM(N); 1174 case ISD::MULHU: return visitMULHU(N); 1175 case ISD::MULHS: return visitMULHS(N); 1176 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N); 1177 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N); 1178 case ISD::SMULO: return visitSMULO(N); 1179 case ISD::UMULO: return visitUMULO(N); 1180 case ISD::SDIVREM: return visitSDIVREM(N); 1181 case ISD::UDIVREM: return visitUDIVREM(N); 1182 case ISD::AND: return visitAND(N); 1183 case ISD::OR: return visitOR(N); 1184 case ISD::XOR: return visitXOR(N); 1185 case ISD::SHL: return visitSHL(N); 1186 case ISD::SRA: return visitSRA(N); 1187 case ISD::SRL: return visitSRL(N); 1188 case ISD::CTLZ: return visitCTLZ(N); 1189 case ISD::CTLZ_ZERO_UNDEF: return visitCTLZ_ZERO_UNDEF(N); 1190 case ISD::CTTZ: return visitCTTZ(N); 1191 case ISD::CTTZ_ZERO_UNDEF: return visitCTTZ_ZERO_UNDEF(N); 1192 case ISD::CTPOP: return visitCTPOP(N); 1193 case ISD::SELECT: return visitSELECT(N); 1194 case ISD::VSELECT: return visitVSELECT(N); 1195 case ISD::SELECT_CC: return visitSELECT_CC(N); 1196 case ISD::SETCC: return visitSETCC(N); 1197 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N); 1198 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N); 1199 case ISD::ANY_EXTEND: return visitANY_EXTEND(N); 1200 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N); 1201 case ISD::TRUNCATE: return visitTRUNCATE(N); 1202 case ISD::BITCAST: return visitBITCAST(N); 1203 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N); 1204 case ISD::FADD: return visitFADD(N); 1205 case ISD::FSUB: return visitFSUB(N); 1206 case ISD::FMUL: return visitFMUL(N); 1207 case ISD::FMA: return visitFMA(N); 1208 case ISD::FDIV: return visitFDIV(N); 1209 case ISD::FREM: return visitFREM(N); 1210 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N); 1211 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N); 1212 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N); 1213 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N); 1214 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N); 1215 case ISD::FP_ROUND: return visitFP_ROUND(N); 1216 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N); 1217 case ISD::FP_EXTEND: return visitFP_EXTEND(N); 1218 case ISD::FNEG: return visitFNEG(N); 1219 case ISD::FABS: return visitFABS(N); 1220 case ISD::FFLOOR: return visitFFLOOR(N); 1221 case ISD::FCEIL: return visitFCEIL(N); 1222 case ISD::FTRUNC: return visitFTRUNC(N); 1223 case ISD::BRCOND: return visitBRCOND(N); 1224 case ISD::BR_CC: return visitBR_CC(N); 1225 case ISD::LOAD: return visitLOAD(N); 1226 case ISD::STORE: return visitSTORE(N); 1227 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N); 1228 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N); 1229 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N); 1230 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N); 1231 case ISD::EXTRACT_SUBVECTOR: return visitEXTRACT_SUBVECTOR(N); 1232 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N); 1233 } 1234 return SDValue(); 1235 } 1236 1237 SDValue DAGCombiner::combine(SDNode *N) { 1238 SDValue RV = visit(N); 1239 1240 // If nothing happened, try a target-specific DAG combine. 1241 if (RV.getNode() == 0) { 1242 assert(N->getOpcode() != ISD::DELETED_NODE && 1243 "Node was deleted but visit returned NULL!"); 1244 1245 if (N->getOpcode() >= ISD::BUILTIN_OP_END || 1246 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) { 1247 1248 // Expose the DAG combiner to the target combiner impls. 1249 TargetLowering::DAGCombinerInfo 1250 DagCombineInfo(DAG, Level, false, this); 1251 1252 RV = TLI.PerformDAGCombine(N, DagCombineInfo); 1253 } 1254 } 1255 1256 // If nothing happened still, try promoting the operation. 1257 if (RV.getNode() == 0) { 1258 switch (N->getOpcode()) { 1259 default: break; 1260 case ISD::ADD: 1261 case ISD::SUB: 1262 case ISD::MUL: 1263 case ISD::AND: 1264 case ISD::OR: 1265 case ISD::XOR: 1266 RV = PromoteIntBinOp(SDValue(N, 0)); 1267 break; 1268 case ISD::SHL: 1269 case ISD::SRA: 1270 case ISD::SRL: 1271 RV = PromoteIntShiftOp(SDValue(N, 0)); 1272 break; 1273 case ISD::SIGN_EXTEND: 1274 case ISD::ZERO_EXTEND: 1275 case ISD::ANY_EXTEND: 1276 RV = PromoteExtend(SDValue(N, 0)); 1277 break; 1278 case ISD::LOAD: 1279 if (PromoteLoad(SDValue(N, 0))) 1280 RV = SDValue(N, 0); 1281 break; 1282 } 1283 } 1284 1285 // If N is a commutative binary node, try commuting it to enable more 1286 // sdisel CSE. 1287 if (RV.getNode() == 0 && 1288 SelectionDAG::isCommutativeBinOp(N->getOpcode()) && 1289 N->getNumValues() == 1) { 1290 SDValue N0 = N->getOperand(0); 1291 SDValue N1 = N->getOperand(1); 1292 1293 // Constant operands are canonicalized to RHS. 1294 if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) { 1295 SDValue Ops[] = { N1, N0 }; 1296 SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), 1297 Ops, 2); 1298 if (CSENode) 1299 return SDValue(CSENode, 0); 1300 } 1301 } 1302 1303 return RV; 1304 } 1305 1306 /// getInputChainForNode - Given a node, return its input chain if it has one, 1307 /// otherwise return a null sd operand. 1308 static SDValue getInputChainForNode(SDNode *N) { 1309 if (unsigned NumOps = N->getNumOperands()) { 1310 if (N->getOperand(0).getValueType() == MVT::Other) 1311 return N->getOperand(0); 1312 if (N->getOperand(NumOps-1).getValueType() == MVT::Other) 1313 return N->getOperand(NumOps-1); 1314 for (unsigned i = 1; i < NumOps-1; ++i) 1315 if (N->getOperand(i).getValueType() == MVT::Other) 1316 return N->getOperand(i); 1317 } 1318 return SDValue(); 1319 } 1320 1321 SDValue DAGCombiner::visitTokenFactor(SDNode *N) { 1322 // If N has two operands, where one has an input chain equal to the other, 1323 // the 'other' chain is redundant. 1324 if (N->getNumOperands() == 2) { 1325 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1)) 1326 return N->getOperand(0); 1327 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0)) 1328 return N->getOperand(1); 1329 } 1330 1331 SmallVector<SDNode *, 8> TFs; // List of token factors to visit. 1332 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor. 1333 SmallPtrSet<SDNode*, 16> SeenOps; 1334 bool Changed = false; // If we should replace this token factor. 1335 1336 // Start out with this token factor. 1337 TFs.push_back(N); 1338 1339 // Iterate through token factors. The TFs grows when new token factors are 1340 // encountered. 1341 for (unsigned i = 0; i < TFs.size(); ++i) { 1342 SDNode *TF = TFs[i]; 1343 1344 // Check each of the operands. 1345 for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) { 1346 SDValue Op = TF->getOperand(i); 1347 1348 switch (Op.getOpcode()) { 1349 case ISD::EntryToken: 1350 // Entry tokens don't need to be added to the list. They are 1351 // rededundant. 1352 Changed = true; 1353 break; 1354 1355 case ISD::TokenFactor: 1356 if (Op.hasOneUse() && 1357 std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) { 1358 // Queue up for processing. 1359 TFs.push_back(Op.getNode()); 1360 // Clean up in case the token factor is removed. 1361 AddToWorkList(Op.getNode()); 1362 Changed = true; 1363 break; 1364 } 1365 // Fall thru 1366 1367 default: 1368 // Only add if it isn't already in the list. 1369 if (SeenOps.insert(Op.getNode())) 1370 Ops.push_back(Op); 1371 else 1372 Changed = true; 1373 break; 1374 } 1375 } 1376 } 1377 1378 SDValue Result; 1379 1380 // If we've change things around then replace token factor. 1381 if (Changed) { 1382 if (Ops.empty()) { 1383 // The entry token is the only possible outcome. 1384 Result = DAG.getEntryNode(); 1385 } else { 1386 // New and improved token factor. 1387 Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), 1388 MVT::Other, &Ops[0], Ops.size()); 1389 } 1390 1391 // Don't add users to work list. 1392 return CombineTo(N, Result, false); 1393 } 1394 1395 return Result; 1396 } 1397 1398 /// MERGE_VALUES can always be eliminated. 1399 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) { 1400 WorkListRemover DeadNodes(*this); 1401 // Replacing results may cause a different MERGE_VALUES to suddenly 1402 // be CSE'd with N, and carry its uses with it. Iterate until no 1403 // uses remain, to ensure that the node can be safely deleted. 1404 // First add the users of this node to the work list so that they 1405 // can be tried again once they have new operands. 1406 AddUsersToWorkList(N); 1407 do { 1408 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) 1409 DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i)); 1410 } while (!N->use_empty()); 1411 removeFromWorkList(N); 1412 DAG.DeleteNode(N); 1413 return SDValue(N, 0); // Return N so it doesn't get rechecked! 1414 } 1415 1416 static 1417 SDValue combineShlAddConstant(SDLoc DL, SDValue N0, SDValue N1, 1418 SelectionDAG &DAG) { 1419 EVT VT = N0.getValueType(); 1420 SDValue N00 = N0.getOperand(0); 1421 SDValue N01 = N0.getOperand(1); 1422 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N01); 1423 1424 if (N01C && N00.getOpcode() == ISD::ADD && N00.getNode()->hasOneUse() && 1425 isa<ConstantSDNode>(N00.getOperand(1))) { 1426 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), ) 1427 N0 = DAG.getNode(ISD::ADD, SDLoc(N0), VT, 1428 DAG.getNode(ISD::SHL, SDLoc(N00), VT, 1429 N00.getOperand(0), N01), 1430 DAG.getNode(ISD::SHL, SDLoc(N01), VT, 1431 N00.getOperand(1), N01)); 1432 return DAG.getNode(ISD::ADD, DL, VT, N0, N1); 1433 } 1434 1435 return SDValue(); 1436 } 1437 1438 SDValue DAGCombiner::visitADD(SDNode *N) { 1439 SDValue N0 = N->getOperand(0); 1440 SDValue N1 = N->getOperand(1); 1441 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 1442 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 1443 EVT VT = N0.getValueType(); 1444 1445 // fold vector ops 1446 if (VT.isVector()) { 1447 SDValue FoldedVOp = SimplifyVBinOp(N); 1448 if (FoldedVOp.getNode()) return FoldedVOp; 1449 1450 // fold (add x, 0) -> x, vector edition 1451 if (ISD::isBuildVectorAllZeros(N1.getNode())) 1452 return N0; 1453 if (ISD::isBuildVectorAllZeros(N0.getNode())) 1454 return N1; 1455 } 1456 1457 // fold (add x, undef) -> undef 1458 if (N0.getOpcode() == ISD::UNDEF) 1459 return N0; 1460 if (N1.getOpcode() == ISD::UNDEF) 1461 return N1; 1462 // fold (add c1, c2) -> c1+c2 1463 if (N0C && N1C) 1464 return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C); 1465 // canonicalize constant to RHS 1466 if (N0C && !N1C) 1467 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0); 1468 // fold (add x, 0) -> x 1469 if (N1C && N1C->isNullValue()) 1470 return N0; 1471 // fold (add Sym, c) -> Sym+c 1472 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0)) 1473 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C && 1474 GA->getOpcode() == ISD::GlobalAddress) 1475 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT, 1476 GA->getOffset() + 1477 (uint64_t)N1C->getSExtValue()); 1478 // fold ((c1-A)+c2) -> (c1+c2)-A 1479 if (N1C && N0.getOpcode() == ISD::SUB) 1480 if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0))) 1481 return DAG.getNode(ISD::SUB, SDLoc(N), VT, 1482 DAG.getConstant(N1C->getAPIntValue()+ 1483 N0C->getAPIntValue(), VT), 1484 N0.getOperand(1)); 1485 // reassociate add 1486 SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1); 1487 if (RADD.getNode() != 0) 1488 return RADD; 1489 // fold ((0-A) + B) -> B-A 1490 if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) && 1491 cast<ConstantSDNode>(N0.getOperand(0))->isNullValue()) 1492 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1)); 1493 // fold (A + (0-B)) -> A-B 1494 if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) && 1495 cast<ConstantSDNode>(N1.getOperand(0))->isNullValue()) 1496 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1)); 1497 // fold (A+(B-A)) -> B 1498 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1)) 1499 return N1.getOperand(0); 1500 // fold ((B-A)+A) -> B 1501 if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1)) 1502 return N0.getOperand(0); 1503 // fold (A+(B-(A+C))) to (B-C) 1504 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD && 1505 N0 == N1.getOperand(1).getOperand(0)) 1506 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0), 1507 N1.getOperand(1).getOperand(1)); 1508 // fold (A+(B-(C+A))) to (B-C) 1509 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD && 1510 N0 == N1.getOperand(1).getOperand(1)) 1511 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0), 1512 N1.getOperand(1).getOperand(0)); 1513 // fold (A+((B-A)+or-C)) to (B+or-C) 1514 if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) && 1515 N1.getOperand(0).getOpcode() == ISD::SUB && 1516 N0 == N1.getOperand(0).getOperand(1)) 1517 return DAG.getNode(N1.getOpcode(), SDLoc(N), VT, 1518 N1.getOperand(0).getOperand(0), N1.getOperand(1)); 1519 1520 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant 1521 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) { 1522 SDValue N00 = N0.getOperand(0); 1523 SDValue N01 = N0.getOperand(1); 1524 SDValue N10 = N1.getOperand(0); 1525 SDValue N11 = N1.getOperand(1); 1526 1527 if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10)) 1528 return DAG.getNode(ISD::SUB, SDLoc(N), VT, 1529 DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10), 1530 DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11)); 1531 } 1532 1533 if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0))) 1534 return SDValue(N, 0); 1535 1536 // fold (a+b) -> (a|b) iff a and b share no bits. 1537 if (VT.isInteger() && !VT.isVector()) { 1538 APInt LHSZero, LHSOne; 1539 APInt RHSZero, RHSOne; 1540 DAG.ComputeMaskedBits(N0, LHSZero, LHSOne); 1541 1542 if (LHSZero.getBoolValue()) { 1543 DAG.ComputeMaskedBits(N1, RHSZero, RHSOne); 1544 1545 // If all possibly-set bits on the LHS are clear on the RHS, return an OR. 1546 // If all possibly-set bits on the RHS are clear on the LHS, return an OR. 1547 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero) 1548 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1); 1549 } 1550 } 1551 1552 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), ) 1553 if (N0.getOpcode() == ISD::SHL && N0.getNode()->hasOneUse()) { 1554 SDValue Result = combineShlAddConstant(SDLoc(N), N0, N1, DAG); 1555 if (Result.getNode()) return Result; 1556 } 1557 if (N1.getOpcode() == ISD::SHL && N1.getNode()->hasOneUse()) { 1558 SDValue Result = combineShlAddConstant(SDLoc(N), N1, N0, DAG); 1559 if (Result.getNode()) return Result; 1560 } 1561 1562 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n)) 1563 if (N1.getOpcode() == ISD::SHL && 1564 N1.getOperand(0).getOpcode() == ISD::SUB) 1565 if (ConstantSDNode *C = 1566 dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0))) 1567 if (C->getAPIntValue() == 0) 1568 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, 1569 DAG.getNode(ISD::SHL, SDLoc(N), VT, 1570 N1.getOperand(0).getOperand(1), 1571 N1.getOperand(1))); 1572 if (N0.getOpcode() == ISD::SHL && 1573 N0.getOperand(0).getOpcode() == ISD::SUB) 1574 if (ConstantSDNode *C = 1575 dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0))) 1576 if (C->getAPIntValue() == 0) 1577 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, 1578 DAG.getNode(ISD::SHL, SDLoc(N), VT, 1579 N0.getOperand(0).getOperand(1), 1580 N0.getOperand(1))); 1581 1582 if (N1.getOpcode() == ISD::AND) { 1583 SDValue AndOp0 = N1.getOperand(0); 1584 ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1)); 1585 unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0); 1586 unsigned DestBits = VT.getScalarType().getSizeInBits(); 1587 1588 // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x)) 1589 // and similar xforms where the inner op is either ~0 or 0. 1590 if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) { 1591 SDLoc DL(N); 1592 return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0); 1593 } 1594 } 1595 1596 // add (sext i1), X -> sub X, (zext i1) 1597 if (N0.getOpcode() == ISD::SIGN_EXTEND && 1598 N0.getOperand(0).getValueType() == MVT::i1 && 1599 !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) { 1600 SDLoc DL(N); 1601 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)); 1602 return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt); 1603 } 1604 1605 return SDValue(); 1606 } 1607 1608 SDValue DAGCombiner::visitADDC(SDNode *N) { 1609 SDValue N0 = N->getOperand(0); 1610 SDValue N1 = N->getOperand(1); 1611 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 1612 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 1613 EVT VT = N0.getValueType(); 1614 1615 // If the flag result is dead, turn this into an ADD. 1616 if (!N->hasAnyUseOfValue(1)) 1617 return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1), 1618 DAG.getNode(ISD::CARRY_FALSE, 1619 SDLoc(N), MVT::Glue)); 1620 1621 // canonicalize constant to RHS. 1622 if (N0C && !N1C) 1623 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0); 1624 1625 // fold (addc x, 0) -> x + no carry out 1626 if (N1C && N1C->isNullValue()) 1627 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, 1628 SDLoc(N), MVT::Glue)); 1629 1630 // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits. 1631 APInt LHSZero, LHSOne; 1632 APInt RHSZero, RHSOne; 1633 DAG.ComputeMaskedBits(N0, LHSZero, LHSOne); 1634 1635 if (LHSZero.getBoolValue()) { 1636 DAG.ComputeMaskedBits(N1, RHSZero, RHSOne); 1637 1638 // If all possibly-set bits on the LHS are clear on the RHS, return an OR. 1639 // If all possibly-set bits on the RHS are clear on the LHS, return an OR. 1640 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero) 1641 return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1), 1642 DAG.getNode(ISD::CARRY_FALSE, 1643 SDLoc(N), MVT::Glue)); 1644 } 1645 1646 return SDValue(); 1647 } 1648 1649 SDValue DAGCombiner::visitADDE(SDNode *N) { 1650 SDValue N0 = N->getOperand(0); 1651 SDValue N1 = N->getOperand(1); 1652 SDValue CarryIn = N->getOperand(2); 1653 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 1654 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 1655 1656 // canonicalize constant to RHS 1657 if (N0C && !N1C) 1658 return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(), 1659 N1, N0, CarryIn); 1660 1661 // fold (adde x, y, false) -> (addc x, y) 1662 if (CarryIn.getOpcode() == ISD::CARRY_FALSE) 1663 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1); 1664 1665 return SDValue(); 1666 } 1667 1668 // Since it may not be valid to emit a fold to zero for vector initializers 1669 // check if we can before folding. 1670 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT, 1671 SelectionDAG &DAG, 1672 bool LegalOperations, bool LegalTypes) { 1673 if (!VT.isVector()) 1674 return DAG.getConstant(0, VT); 1675 if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT)) 1676 return DAG.getConstant(0, VT); 1677 return SDValue(); 1678 } 1679 1680 SDValue DAGCombiner::visitSUB(SDNode *N) { 1681 SDValue N0 = N->getOperand(0); 1682 SDValue N1 = N->getOperand(1); 1683 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode()); 1684 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode()); 1685 ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? 0 : 1686 dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode()); 1687 EVT VT = N0.getValueType(); 1688 1689 // fold vector ops 1690 if (VT.isVector()) { 1691 SDValue FoldedVOp = SimplifyVBinOp(N); 1692 if (FoldedVOp.getNode()) return FoldedVOp; 1693 1694 // fold (sub x, 0) -> x, vector edition 1695 if (ISD::isBuildVectorAllZeros(N1.getNode())) 1696 return N0; 1697 } 1698 1699 // fold (sub x, x) -> 0 1700 // FIXME: Refactor this and xor and other similar operations together. 1701 if (N0 == N1) 1702 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes); 1703 // fold (sub c1, c2) -> c1-c2 1704 if (N0C && N1C) 1705 return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C); 1706 // fold (sub x, c) -> (add x, -c) 1707 if (N1C) 1708 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, 1709 DAG.getConstant(-N1C->getAPIntValue(), VT)); 1710 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) 1711 if (N0C && N0C->isAllOnesValue()) 1712 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0); 1713 // fold A-(A-B) -> B 1714 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0)) 1715 return N1.getOperand(1); 1716 // fold (A+B)-A -> B 1717 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1) 1718 return N0.getOperand(1); 1719 // fold (A+B)-B -> A 1720 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1) 1721 return N0.getOperand(0); 1722 // fold C2-(A+C1) -> (C2-C1)-A 1723 if (N1.getOpcode() == ISD::ADD && N0C && N1C1) { 1724 SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(), 1725 VT); 1726 return DAG.getNode(ISD::SUB, SDLoc(N), VT, NewC, 1727 N1.getOperand(0)); 1728 } 1729 // fold ((A+(B+or-C))-B) -> A+or-C 1730 if (N0.getOpcode() == ISD::ADD && 1731 (N0.getOperand(1).getOpcode() == ISD::SUB || 1732 N0.getOperand(1).getOpcode() == ISD::ADD) && 1733 N0.getOperand(1).getOperand(0) == N1) 1734 return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT, 1735 N0.getOperand(0), N0.getOperand(1).getOperand(1)); 1736 // fold ((A+(C+B))-B) -> A+C 1737 if (N0.getOpcode() == ISD::ADD && 1738 N0.getOperand(1).getOpcode() == ISD::ADD && 1739 N0.getOperand(1).getOperand(1) == N1) 1740 return DAG.getNode(ISD::ADD, SDLoc(N), VT, 1741 N0.getOperand(0), N0.getOperand(1).getOperand(0)); 1742 // fold ((A-(B-C))-C) -> A-B 1743 if (N0.getOpcode() == ISD::SUB && 1744 N0.getOperand(1).getOpcode() == ISD::SUB && 1745 N0.getOperand(1).getOperand(1) == N1) 1746 return DAG.getNode(ISD::SUB, SDLoc(N), VT, 1747 N0.getOperand(0), N0.getOperand(1).getOperand(0)); 1748 1749 // If either operand of a sub is undef, the result is undef 1750 if (N0.getOpcode() == ISD::UNDEF) 1751 return N0; 1752 if (N1.getOpcode() == ISD::UNDEF) 1753 return N1; 1754 1755 // If the relocation model supports it, consider symbol offsets. 1756 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0)) 1757 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) { 1758 // fold (sub Sym, c) -> Sym-c 1759 if (N1C && GA->getOpcode() == ISD::GlobalAddress) 1760 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT, 1761 GA->getOffset() - 1762 (uint64_t)N1C->getSExtValue()); 1763 // fold (sub Sym+c1, Sym+c2) -> c1-c2 1764 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1)) 1765 if (GA->getGlobal() == GB->getGlobal()) 1766 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(), 1767 VT); 1768 } 1769 1770 return SDValue(); 1771 } 1772 1773 SDValue DAGCombiner::visitSUBC(SDNode *N) { 1774 SDValue N0 = N->getOperand(0); 1775 SDValue N1 = N->getOperand(1); 1776 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 1777 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 1778 EVT VT = N0.getValueType(); 1779 1780 // If the flag result is dead, turn this into an SUB. 1781 if (!N->hasAnyUseOfValue(1)) 1782 return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1), 1783 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N), 1784 MVT::Glue)); 1785 1786 // fold (subc x, x) -> 0 + no borrow 1787 if (N0 == N1) 1788 return CombineTo(N, DAG.getConstant(0, VT), 1789 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N), 1790 MVT::Glue)); 1791 1792 // fold (subc x, 0) -> x + no borrow 1793 if (N1C && N1C->isNullValue()) 1794 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N), 1795 MVT::Glue)); 1796 1797 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow 1798 if (N0C && N0C->isAllOnesValue()) 1799 return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0), 1800 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N), 1801 MVT::Glue)); 1802 1803 return SDValue(); 1804 } 1805 1806 SDValue DAGCombiner::visitSUBE(SDNode *N) { 1807 SDValue N0 = N->getOperand(0); 1808 SDValue N1 = N->getOperand(1); 1809 SDValue CarryIn = N->getOperand(2); 1810 1811 // fold (sube x, y, false) -> (subc x, y) 1812 if (CarryIn.getOpcode() == ISD::CARRY_FALSE) 1813 return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1); 1814 1815 return SDValue(); 1816 } 1817 1818 /// isConstantSplatVector - Returns true if N is a BUILD_VECTOR node whose 1819 /// elements are all the same constant or undefined. 1820 static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) { 1821 BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N); 1822 if (!C) 1823 return false; 1824 1825 APInt SplatUndef; 1826 unsigned SplatBitSize; 1827 bool HasAnyUndefs; 1828 EVT EltVT = N->getValueType(0).getVectorElementType(); 1829 return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize, 1830 HasAnyUndefs) && 1831 EltVT.getSizeInBits() >= SplatBitSize); 1832 } 1833 1834 SDValue DAGCombiner::visitMUL(SDNode *N) { 1835 SDValue N0 = N->getOperand(0); 1836 SDValue N1 = N->getOperand(1); 1837 EVT VT = N0.getValueType(); 1838 1839 // fold (mul x, undef) -> 0 1840 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF) 1841 return DAG.getConstant(0, VT); 1842 1843 bool N0IsConst = false; 1844 bool N1IsConst = false; 1845 APInt ConstValue0, ConstValue1; 1846 // fold vector ops 1847 if (VT.isVector()) { 1848 SDValue FoldedVOp = SimplifyVBinOp(N); 1849 if (FoldedVOp.getNode()) return FoldedVOp; 1850 1851 N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0); 1852 N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1); 1853 } else { 1854 N0IsConst = dyn_cast<ConstantSDNode>(N0) != 0; 1855 ConstValue0 = N0IsConst ? (dyn_cast<ConstantSDNode>(N0))->getAPIntValue() 1856 : APInt(); 1857 N1IsConst = dyn_cast<ConstantSDNode>(N1) != 0; 1858 ConstValue1 = N1IsConst ? (dyn_cast<ConstantSDNode>(N1))->getAPIntValue() 1859 : APInt(); 1860 } 1861 1862 // fold (mul c1, c2) -> c1*c2 1863 if (N0IsConst && N1IsConst) 1864 return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0.getNode(), N1.getNode()); 1865 1866 // canonicalize constant to RHS 1867 if (N0IsConst && !N1IsConst) 1868 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0); 1869 // fold (mul x, 0) -> 0 1870 if (N1IsConst && ConstValue1 == 0) 1871 return N1; 1872 // We require a splat of the entire scalar bit width for non-contiguous 1873 // bit patterns. 1874 bool IsFullSplat = 1875 ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits(); 1876 // fold (mul x, 1) -> x 1877 if (N1IsConst && ConstValue1 == 1 && IsFullSplat) 1878 return N0; 1879 // fold (mul x, -1) -> 0-x 1880 if (N1IsConst && ConstValue1.isAllOnesValue()) 1881 return DAG.getNode(ISD::SUB, SDLoc(N), VT, 1882 DAG.getConstant(0, VT), N0); 1883 // fold (mul x, (1 << c)) -> x << c 1884 if (N1IsConst && ConstValue1.isPowerOf2() && IsFullSplat) 1885 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, 1886 DAG.getConstant(ConstValue1.logBase2(), 1887 getShiftAmountTy(N0.getValueType()))); 1888 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c 1889 if (N1IsConst && (-ConstValue1).isPowerOf2() && IsFullSplat) { 1890 unsigned Log2Val = (-ConstValue1).logBase2(); 1891 // FIXME: If the input is something that is easily negated (e.g. a 1892 // single-use add), we should put the negate there. 1893 return DAG.getNode(ISD::SUB, SDLoc(N), VT, 1894 DAG.getConstant(0, VT), 1895 DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, 1896 DAG.getConstant(Log2Val, 1897 getShiftAmountTy(N0.getValueType())))); 1898 } 1899 1900 APInt Val; 1901 // (mul (shl X, c1), c2) -> (mul X, c2 << c1) 1902 if (N1IsConst && N0.getOpcode() == ISD::SHL && 1903 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) || 1904 isa<ConstantSDNode>(N0.getOperand(1)))) { 1905 SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT, 1906 N1, N0.getOperand(1)); 1907 AddToWorkList(C3.getNode()); 1908 return DAG.getNode(ISD::MUL, SDLoc(N), VT, 1909 N0.getOperand(0), C3); 1910 } 1911 1912 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one 1913 // use. 1914 { 1915 SDValue Sh(0,0), Y(0,0); 1916 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)). 1917 if (N0.getOpcode() == ISD::SHL && 1918 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) || 1919 isa<ConstantSDNode>(N0.getOperand(1))) && 1920 N0.getNode()->hasOneUse()) { 1921 Sh = N0; Y = N1; 1922 } else if (N1.getOpcode() == ISD::SHL && 1923 isa<ConstantSDNode>(N1.getOperand(1)) && 1924 N1.getNode()->hasOneUse()) { 1925 Sh = N1; Y = N0; 1926 } 1927 1928 if (Sh.getNode()) { 1929 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT, 1930 Sh.getOperand(0), Y); 1931 return DAG.getNode(ISD::SHL, SDLoc(N), VT, 1932 Mul, Sh.getOperand(1)); 1933 } 1934 } 1935 1936 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2) 1937 if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() && 1938 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) || 1939 isa<ConstantSDNode>(N0.getOperand(1)))) 1940 return DAG.getNode(ISD::ADD, SDLoc(N), VT, 1941 DAG.getNode(ISD::MUL, SDLoc(N0), VT, 1942 N0.getOperand(0), N1), 1943 DAG.getNode(ISD::MUL, SDLoc(N1), VT, 1944 N0.getOperand(1), N1)); 1945 1946 // reassociate mul 1947 SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1); 1948 if (RMUL.getNode() != 0) 1949 return RMUL; 1950 1951 return SDValue(); 1952 } 1953 1954 SDValue DAGCombiner::visitSDIV(SDNode *N) { 1955 SDValue N0 = N->getOperand(0); 1956 SDValue N1 = N->getOperand(1); 1957 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode()); 1958 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode()); 1959 EVT VT = N->getValueType(0); 1960 1961 // fold vector ops 1962 if (VT.isVector()) { 1963 SDValue FoldedVOp = SimplifyVBinOp(N); 1964 if (FoldedVOp.getNode()) return FoldedVOp; 1965 } 1966 1967 // fold (sdiv c1, c2) -> c1/c2 1968 if (N0C && N1C && !N1C->isNullValue()) 1969 return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C); 1970 // fold (sdiv X, 1) -> X 1971 if (N1C && N1C->getAPIntValue() == 1LL) 1972 return N0; 1973 // fold (sdiv X, -1) -> 0-X 1974 if (N1C && N1C->isAllOnesValue()) 1975 return DAG.getNode(ISD::SUB, SDLoc(N), VT, 1976 DAG.getConstant(0, VT), N0); 1977 // If we know the sign bits of both operands are zero, strength reduce to a 1978 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2 1979 if (!VT.isVector()) { 1980 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0)) 1981 return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(), 1982 N0, N1); 1983 } 1984 // fold (sdiv X, pow2) -> simple ops after legalize 1985 if (N1C && !N1C->isNullValue() && 1986 (N1C->getAPIntValue().isPowerOf2() || 1987 (-N1C->getAPIntValue()).isPowerOf2())) { 1988 // If dividing by powers of two is cheap, then don't perform the following 1989 // fold. 1990 if (TLI.isPow2DivCheap()) 1991 return SDValue(); 1992 1993 unsigned lg2 = N1C->getAPIntValue().countTrailingZeros(); 1994 1995 // Splat the sign bit into the register 1996 SDValue SGN = DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, 1997 DAG.getConstant(VT.getSizeInBits()-1, 1998 getShiftAmountTy(N0.getValueType()))); 1999 AddToWorkList(SGN.getNode()); 2000 2001 // Add (N0 < 0) ? abs2 - 1 : 0; 2002 SDValue SRL = DAG.getNode(ISD::SRL, SDLoc(N), VT, SGN, 2003 DAG.getConstant(VT.getSizeInBits() - lg2, 2004 getShiftAmountTy(SGN.getValueType()))); 2005 SDValue ADD = DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, SRL); 2006 AddToWorkList(SRL.getNode()); 2007 AddToWorkList(ADD.getNode()); // Divide by pow2 2008 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), VT, ADD, 2009 DAG.getConstant(lg2, getShiftAmountTy(ADD.getValueType()))); 2010 2011 // If we're dividing by a positive value, we're done. Otherwise, we must 2012 // negate the result. 2013 if (N1C->getAPIntValue().isNonNegative()) 2014 return SRA; 2015 2016 AddToWorkList(SRA.getNode()); 2017 return DAG.getNode(ISD::SUB, SDLoc(N), VT, 2018 DAG.getConstant(0, VT), SRA); 2019 } 2020 2021 // if integer divide is expensive and we satisfy the requirements, emit an 2022 // alternate sequence. 2023 if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap()) { 2024 SDValue Op = BuildSDIV(N); 2025 if (Op.getNode()) return Op; 2026 } 2027 2028 // undef / X -> 0 2029 if (N0.getOpcode() == ISD::UNDEF) 2030 return DAG.getConstant(0, VT); 2031 // X / undef -> undef 2032 if (N1.getOpcode() == ISD::UNDEF) 2033 return N1; 2034 2035 return SDValue(); 2036 } 2037 2038 SDValue DAGCombiner::visitUDIV(SDNode *N) { 2039 SDValue N0 = N->getOperand(0); 2040 SDValue N1 = N->getOperand(1); 2041 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode()); 2042 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode()); 2043 EVT VT = N->getValueType(0); 2044 2045 // fold vector ops 2046 if (VT.isVector()) { 2047 SDValue FoldedVOp = SimplifyVBinOp(N); 2048 if (FoldedVOp.getNode()) return FoldedVOp; 2049 } 2050 2051 // fold (udiv c1, c2) -> c1/c2 2052 if (N0C && N1C && !N1C->isNullValue()) 2053 return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C); 2054 // fold (udiv x, (1 << c)) -> x >>u c 2055 if (N1C && N1C->getAPIntValue().isPowerOf2()) 2056 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, 2057 DAG.getConstant(N1C->getAPIntValue().logBase2(), 2058 getShiftAmountTy(N0.getValueType()))); 2059 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2 2060 if (N1.getOpcode() == ISD::SHL) { 2061 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) { 2062 if (SHC->getAPIntValue().isPowerOf2()) { 2063 EVT ADDVT = N1.getOperand(1).getValueType(); 2064 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N), ADDVT, 2065 N1.getOperand(1), 2066 DAG.getConstant(SHC->getAPIntValue() 2067 .logBase2(), 2068 ADDVT)); 2069 AddToWorkList(Add.getNode()); 2070 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, Add); 2071 } 2072 } 2073 } 2074 // fold (udiv x, c) -> alternate 2075 if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap()) { 2076 SDValue Op = BuildUDIV(N); 2077 if (Op.getNode()) return Op; 2078 } 2079 2080 // undef / X -> 0 2081 if (N0.getOpcode() == ISD::UNDEF) 2082 return DAG.getConstant(0, VT); 2083 // X / undef -> undef 2084 if (N1.getOpcode() == ISD::UNDEF) 2085 return N1; 2086 2087 return SDValue(); 2088 } 2089 2090 SDValue DAGCombiner::visitSREM(SDNode *N) { 2091 SDValue N0 = N->getOperand(0); 2092 SDValue N1 = N->getOperand(1); 2093 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 2094 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 2095 EVT VT = N->getValueType(0); 2096 2097 // fold (srem c1, c2) -> c1%c2 2098 if (N0C && N1C && !N1C->isNullValue()) 2099 return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C); 2100 // If we know the sign bits of both operands are zero, strength reduce to a 2101 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15 2102 if (!VT.isVector()) { 2103 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0)) 2104 return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1); 2105 } 2106 2107 // If X/C can be simplified by the division-by-constant logic, lower 2108 // X%C to the equivalent of X-X/C*C. 2109 if (N1C && !N1C->isNullValue()) { 2110 SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1); 2111 AddToWorkList(Div.getNode()); 2112 SDValue OptimizedDiv = combine(Div.getNode()); 2113 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) { 2114 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT, 2115 OptimizedDiv, N1); 2116 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul); 2117 AddToWorkList(Mul.getNode()); 2118 return Sub; 2119 } 2120 } 2121 2122 // undef % X -> 0 2123 if (N0.getOpcode() == ISD::UNDEF) 2124 return DAG.getConstant(0, VT); 2125 // X % undef -> undef 2126 if (N1.getOpcode() == ISD::UNDEF) 2127 return N1; 2128 2129 return SDValue(); 2130 } 2131 2132 SDValue DAGCombiner::visitUREM(SDNode *N) { 2133 SDValue N0 = N->getOperand(0); 2134 SDValue N1 = N->getOperand(1); 2135 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 2136 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 2137 EVT VT = N->getValueType(0); 2138 2139 // fold (urem c1, c2) -> c1%c2 2140 if (N0C && N1C && !N1C->isNullValue()) 2141 return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C); 2142 // fold (urem x, pow2) -> (and x, pow2-1) 2143 if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2()) 2144 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, 2145 DAG.getConstant(N1C->getAPIntValue()-1,VT)); 2146 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1)) 2147 if (N1.getOpcode() == ISD::SHL) { 2148 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) { 2149 if (SHC->getAPIntValue().isPowerOf2()) { 2150 SDValue Add = 2151 DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, 2152 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), 2153 VT)); 2154 AddToWorkList(Add.getNode()); 2155 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, Add); 2156 } 2157 } 2158 } 2159 2160 // If X/C can be simplified by the division-by-constant logic, lower 2161 // X%C to the equivalent of X-X/C*C. 2162 if (N1C && !N1C->isNullValue()) { 2163 SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1); 2164 AddToWorkList(Div.getNode()); 2165 SDValue OptimizedDiv = combine(Div.getNode()); 2166 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) { 2167 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT, 2168 OptimizedDiv, N1); 2169 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul); 2170 AddToWorkList(Mul.getNode()); 2171 return Sub; 2172 } 2173 } 2174 2175 // undef % X -> 0 2176 if (N0.getOpcode() == ISD::UNDEF) 2177 return DAG.getConstant(0, VT); 2178 // X % undef -> undef 2179 if (N1.getOpcode() == ISD::UNDEF) 2180 return N1; 2181 2182 return SDValue(); 2183 } 2184 2185 SDValue DAGCombiner::visitMULHS(SDNode *N) { 2186 SDValue N0 = N->getOperand(0); 2187 SDValue N1 = N->getOperand(1); 2188 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 2189 EVT VT = N->getValueType(0); 2190 SDLoc DL(N); 2191 2192 // fold (mulhs x, 0) -> 0 2193 if (N1C && N1C->isNullValue()) 2194 return N1; 2195 // fold (mulhs x, 1) -> (sra x, size(x)-1) 2196 if (N1C && N1C->getAPIntValue() == 1) 2197 return DAG.getNode(ISD::SRA, SDLoc(N), N0.getValueType(), N0, 2198 DAG.getConstant(N0.getValueType().getSizeInBits() - 1, 2199 getShiftAmountTy(N0.getValueType()))); 2200 // fold (mulhs x, undef) -> 0 2201 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF) 2202 return DAG.getConstant(0, VT); 2203 2204 // If the type twice as wide is legal, transform the mulhs to a wider multiply 2205 // plus a shift. 2206 if (VT.isSimple() && !VT.isVector()) { 2207 MVT Simple = VT.getSimpleVT(); 2208 unsigned SimpleSize = Simple.getSizeInBits(); 2209 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 2210 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 2211 N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0); 2212 N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1); 2213 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1); 2214 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1, 2215 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType()))); 2216 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1); 2217 } 2218 } 2219 2220 return SDValue(); 2221 } 2222 2223 SDValue DAGCombiner::visitMULHU(SDNode *N) { 2224 SDValue N0 = N->getOperand(0); 2225 SDValue N1 = N->getOperand(1); 2226 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 2227 EVT VT = N->getValueType(0); 2228 SDLoc DL(N); 2229 2230 // fold (mulhu x, 0) -> 0 2231 if (N1C && N1C->isNullValue()) 2232 return N1; 2233 // fold (mulhu x, 1) -> 0 2234 if (N1C && N1C->getAPIntValue() == 1) 2235 return DAG.getConstant(0, N0.getValueType()); 2236 // fold (mulhu x, undef) -> 0 2237 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF) 2238 return DAG.getConstant(0, VT); 2239 2240 // If the type twice as wide is legal, transform the mulhu to a wider multiply 2241 // plus a shift. 2242 if (VT.isSimple() && !VT.isVector()) { 2243 MVT Simple = VT.getSimpleVT(); 2244 unsigned SimpleSize = Simple.getSizeInBits(); 2245 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 2246 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 2247 N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0); 2248 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1); 2249 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1); 2250 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1, 2251 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType()))); 2252 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1); 2253 } 2254 } 2255 2256 return SDValue(); 2257 } 2258 2259 /// SimplifyNodeWithTwoResults - Perform optimizations common to nodes that 2260 /// compute two values. LoOp and HiOp give the opcodes for the two computations 2261 /// that are being performed. Return true if a simplification was made. 2262 /// 2263 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp, 2264 unsigned HiOp) { 2265 // If the high half is not needed, just compute the low half. 2266 bool HiExists = N->hasAnyUseOfValue(1); 2267 if (!HiExists && 2268 (!LegalOperations || 2269 TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) { 2270 SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), 2271 N->op_begin(), N->getNumOperands()); 2272 return CombineTo(N, Res, Res); 2273 } 2274 2275 // If the low half is not needed, just compute the high half. 2276 bool LoExists = N->hasAnyUseOfValue(0); 2277 if (!LoExists && 2278 (!LegalOperations || 2279 TLI.isOperationLegal(HiOp, N->getValueType(1)))) { 2280 SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), 2281 N->op_begin(), N->getNumOperands()); 2282 return CombineTo(N, Res, Res); 2283 } 2284 2285 // If both halves are used, return as it is. 2286 if (LoExists && HiExists) 2287 return SDValue(); 2288 2289 // If the two computed results can be simplified separately, separate them. 2290 if (LoExists) { 2291 SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), 2292 N->op_begin(), N->getNumOperands()); 2293 AddToWorkList(Lo.getNode()); 2294 SDValue LoOpt = combine(Lo.getNode()); 2295 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() && 2296 (!LegalOperations || 2297 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType()))) 2298 return CombineTo(N, LoOpt, LoOpt); 2299 } 2300 2301 if (HiExists) { 2302 SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), 2303 N->op_begin(), N->getNumOperands()); 2304 AddToWorkList(Hi.getNode()); 2305 SDValue HiOpt = combine(Hi.getNode()); 2306 if (HiOpt.getNode() && HiOpt != Hi && 2307 (!LegalOperations || 2308 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType()))) 2309 return CombineTo(N, HiOpt, HiOpt); 2310 } 2311 2312 return SDValue(); 2313 } 2314 2315 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) { 2316 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS); 2317 if (Res.getNode()) return Res; 2318 2319 EVT VT = N->getValueType(0); 2320 SDLoc DL(N); 2321 2322 // If the type twice as wide is legal, transform the mulhu to a wider multiply 2323 // plus a shift. 2324 if (VT.isSimple() && !VT.isVector()) { 2325 MVT Simple = VT.getSimpleVT(); 2326 unsigned SimpleSize = Simple.getSizeInBits(); 2327 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 2328 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 2329 SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0)); 2330 SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1)); 2331 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi); 2332 // Compute the high part as N1. 2333 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo, 2334 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType()))); 2335 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi); 2336 // Compute the low part as N0. 2337 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo); 2338 return CombineTo(N, Lo, Hi); 2339 } 2340 } 2341 2342 return SDValue(); 2343 } 2344 2345 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) { 2346 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU); 2347 if (Res.getNode()) return Res; 2348 2349 EVT VT = N->getValueType(0); 2350 SDLoc DL(N); 2351 2352 // If the type twice as wide is legal, transform the mulhu to a wider multiply 2353 // plus a shift. 2354 if (VT.isSimple() && !VT.isVector()) { 2355 MVT Simple = VT.getSimpleVT(); 2356 unsigned SimpleSize = Simple.getSizeInBits(); 2357 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 2358 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 2359 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0)); 2360 SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1)); 2361 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi); 2362 // Compute the high part as N1. 2363 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo, 2364 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType()))); 2365 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi); 2366 // Compute the low part as N0. 2367 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo); 2368 return CombineTo(N, Lo, Hi); 2369 } 2370 } 2371 2372 return SDValue(); 2373 } 2374 2375 SDValue DAGCombiner::visitSMULO(SDNode *N) { 2376 // (smulo x, 2) -> (saddo x, x) 2377 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1))) 2378 if (C2->getAPIntValue() == 2) 2379 return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(), 2380 N->getOperand(0), N->getOperand(0)); 2381 2382 return SDValue(); 2383 } 2384 2385 SDValue DAGCombiner::visitUMULO(SDNode *N) { 2386 // (umulo x, 2) -> (uaddo x, x) 2387 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1))) 2388 if (C2->getAPIntValue() == 2) 2389 return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(), 2390 N->getOperand(0), N->getOperand(0)); 2391 2392 return SDValue(); 2393 } 2394 2395 SDValue DAGCombiner::visitSDIVREM(SDNode *N) { 2396 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM); 2397 if (Res.getNode()) return Res; 2398 2399 return SDValue(); 2400 } 2401 2402 SDValue DAGCombiner::visitUDIVREM(SDNode *N) { 2403 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM); 2404 if (Res.getNode()) return Res; 2405 2406 return SDValue(); 2407 } 2408 2409 /// SimplifyBinOpWithSameOpcodeHands - If this is a binary operator with 2410 /// two operands of the same opcode, try to simplify it. 2411 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) { 2412 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1); 2413 EVT VT = N0.getValueType(); 2414 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!"); 2415 2416 // Bail early if none of these transforms apply. 2417 if (N0.getNode()->getNumOperands() == 0) return SDValue(); 2418 2419 // For each of OP in AND/OR/XOR: 2420 // fold (OP (zext x), (zext y)) -> (zext (OP x, y)) 2421 // fold (OP (sext x), (sext y)) -> (sext (OP x, y)) 2422 // fold (OP (aext x), (aext y)) -> (aext (OP x, y)) 2423 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free) 2424 // 2425 // do not sink logical op inside of a vector extend, since it may combine 2426 // into a vsetcc. 2427 EVT Op0VT = N0.getOperand(0).getValueType(); 2428 if ((N0.getOpcode() == ISD::ZERO_EXTEND || 2429 N0.getOpcode() == ISD::SIGN_EXTEND || 2430 // Avoid infinite looping with PromoteIntBinOp. 2431 (N0.getOpcode() == ISD::ANY_EXTEND && 2432 (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) || 2433 (N0.getOpcode() == ISD::TRUNCATE && 2434 (!TLI.isZExtFree(VT, Op0VT) || 2435 !TLI.isTruncateFree(Op0VT, VT)) && 2436 TLI.isTypeLegal(Op0VT))) && 2437 !VT.isVector() && 2438 Op0VT == N1.getOperand(0).getValueType() && 2439 (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) { 2440 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0), 2441 N0.getOperand(0).getValueType(), 2442 N0.getOperand(0), N1.getOperand(0)); 2443 AddToWorkList(ORNode.getNode()); 2444 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode); 2445 } 2446 2447 // For each of OP in SHL/SRL/SRA/AND... 2448 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z) 2449 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z) 2450 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z) 2451 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL || 2452 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) && 2453 N0.getOperand(1) == N1.getOperand(1)) { 2454 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0), 2455 N0.getOperand(0).getValueType(), 2456 N0.getOperand(0), N1.getOperand(0)); 2457 AddToWorkList(ORNode.getNode()); 2458 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, 2459 ORNode, N0.getOperand(1)); 2460 } 2461 2462 // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B)) 2463 // Only perform this optimization after type legalization and before 2464 // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by 2465 // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and 2466 // we don't want to undo this promotion. 2467 // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper 2468 // on scalars. 2469 if ((N0.getOpcode() == ISD::BITCAST || 2470 N0.getOpcode() == ISD::SCALAR_TO_VECTOR) && 2471 Level == AfterLegalizeTypes) { 2472 SDValue In0 = N0.getOperand(0); 2473 SDValue In1 = N1.getOperand(0); 2474 EVT In0Ty = In0.getValueType(); 2475 EVT In1Ty = In1.getValueType(); 2476 SDLoc DL(N); 2477 // If both incoming values are integers, and the original types are the 2478 // same. 2479 if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) { 2480 SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1); 2481 SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op); 2482 AddToWorkList(Op.getNode()); 2483 return BC; 2484 } 2485 } 2486 2487 // Xor/and/or are indifferent to the swizzle operation (shuffle of one value). 2488 // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B)) 2489 // If both shuffles use the same mask, and both shuffle within a single 2490 // vector, then it is worthwhile to move the swizzle after the operation. 2491 // The type-legalizer generates this pattern when loading illegal 2492 // vector types from memory. In many cases this allows additional shuffle 2493 // optimizations. 2494 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG && 2495 N0.getOperand(1).getOpcode() == ISD::UNDEF && 2496 N1.getOperand(1).getOpcode() == ISD::UNDEF) { 2497 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0); 2498 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1); 2499 2500 assert(N0.getOperand(0).getValueType() == N1.getOperand(1).getValueType() && 2501 "Inputs to shuffles are not the same type"); 2502 2503 unsigned NumElts = VT.getVectorNumElements(); 2504 2505 // Check that both shuffles use the same mask. The masks are known to be of 2506 // the same length because the result vector type is the same. 2507 bool SameMask = true; 2508 for (unsigned i = 0; i != NumElts; ++i) { 2509 int Idx0 = SVN0->getMaskElt(i); 2510 int Idx1 = SVN1->getMaskElt(i); 2511 if (Idx0 != Idx1) { 2512 SameMask = false; 2513 break; 2514 } 2515 } 2516 2517 if (SameMask) { 2518 SDValue Op = DAG.getNode(N->getOpcode(), SDLoc(N), VT, 2519 N0.getOperand(0), N1.getOperand(0)); 2520 AddToWorkList(Op.getNode()); 2521 return DAG.getVectorShuffle(VT, SDLoc(N), Op, 2522 DAG.getUNDEF(VT), &SVN0->getMask()[0]); 2523 } 2524 } 2525 2526 return SDValue(); 2527 } 2528 2529 SDValue DAGCombiner::visitAND(SDNode *N) { 2530 SDValue N0 = N->getOperand(0); 2531 SDValue N1 = N->getOperand(1); 2532 SDValue LL, LR, RL, RR, CC0, CC1; 2533 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 2534 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 2535 EVT VT = N1.getValueType(); 2536 unsigned BitWidth = VT.getScalarType().getSizeInBits(); 2537 2538 // fold vector ops 2539 if (VT.isVector()) { 2540 SDValue FoldedVOp = SimplifyVBinOp(N); 2541 if (FoldedVOp.getNode()) return FoldedVOp; 2542 2543 // fold (and x, 0) -> 0, vector edition 2544 if (ISD::isBuildVectorAllZeros(N0.getNode())) 2545 return N0; 2546 if (ISD::isBuildVectorAllZeros(N1.getNode())) 2547 return N1; 2548 2549 // fold (and x, -1) -> x, vector edition 2550 if (ISD::isBuildVectorAllOnes(N0.getNode())) 2551 return N1; 2552 if (ISD::isBuildVectorAllOnes(N1.getNode())) 2553 return N0; 2554 } 2555 2556 // fold (and x, undef) -> 0 2557 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF) 2558 return DAG.getConstant(0, VT); 2559 // fold (and c1, c2) -> c1&c2 2560 if (N0C && N1C) 2561 return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C); 2562 // canonicalize constant to RHS 2563 if (N0C && !N1C) 2564 return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0); 2565 // fold (and x, -1) -> x 2566 if (N1C && N1C->isAllOnesValue()) 2567 return N0; 2568 // if (and x, c) is known to be zero, return 0 2569 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0), 2570 APInt::getAllOnesValue(BitWidth))) 2571 return DAG.getConstant(0, VT); 2572 // reassociate and 2573 SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1); 2574 if (RAND.getNode() != 0) 2575 return RAND; 2576 // fold (and (or x, C), D) -> D if (C & D) == D 2577 if (N1C && N0.getOpcode() == ISD::OR) 2578 if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) 2579 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue()) 2580 return N1; 2581 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits. 2582 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) { 2583 SDValue N0Op0 = N0.getOperand(0); 2584 APInt Mask = ~N1C->getAPIntValue(); 2585 Mask = Mask.trunc(N0Op0.getValueSizeInBits()); 2586 if (DAG.MaskedValueIsZero(N0Op0, Mask)) { 2587 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), 2588 N0.getValueType(), N0Op0); 2589 2590 // Replace uses of the AND with uses of the Zero extend node. 2591 CombineTo(N, Zext); 2592 2593 // We actually want to replace all uses of the any_extend with the 2594 // zero_extend, to avoid duplicating things. This will later cause this 2595 // AND to be folded. 2596 CombineTo(N0.getNode(), Zext); 2597 return SDValue(N, 0); // Return N so it doesn't get rechecked! 2598 } 2599 } 2600 // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) -> 2601 // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must 2602 // already be zero by virtue of the width of the base type of the load. 2603 // 2604 // the 'X' node here can either be nothing or an extract_vector_elt to catch 2605 // more cases. 2606 if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT && 2607 N0.getOperand(0).getOpcode() == ISD::LOAD) || 2608 N0.getOpcode() == ISD::LOAD) { 2609 LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ? 2610 N0 : N0.getOperand(0) ); 2611 2612 // Get the constant (if applicable) the zero'th operand is being ANDed with. 2613 // This can be a pure constant or a vector splat, in which case we treat the 2614 // vector as a scalar and use the splat value. 2615 APInt Constant = APInt::getNullValue(1); 2616 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) { 2617 Constant = C->getAPIntValue(); 2618 } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) { 2619 APInt SplatValue, SplatUndef; 2620 unsigned SplatBitSize; 2621 bool HasAnyUndefs; 2622 bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef, 2623 SplatBitSize, HasAnyUndefs); 2624 if (IsSplat) { 2625 // Undef bits can contribute to a possible optimisation if set, so 2626 // set them. 2627 SplatValue |= SplatUndef; 2628 2629 // The splat value may be something like "0x00FFFFFF", which means 0 for 2630 // the first vector value and FF for the rest, repeating. We need a mask 2631 // that will apply equally to all members of the vector, so AND all the 2632 // lanes of the constant together. 2633 EVT VT = Vector->getValueType(0); 2634 unsigned BitWidth = VT.getVectorElementType().getSizeInBits(); 2635 2636 // If the splat value has been compressed to a bitlength lower 2637 // than the size of the vector lane, we need to re-expand it to 2638 // the lane size. 2639 if (BitWidth > SplatBitSize) 2640 for (SplatValue = SplatValue.zextOrTrunc(BitWidth); 2641 SplatBitSize < BitWidth; 2642 SplatBitSize = SplatBitSize * 2) 2643 SplatValue |= SplatValue.shl(SplatBitSize); 2644 2645 Constant = APInt::getAllOnesValue(BitWidth); 2646 for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i) 2647 Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth); 2648 } 2649 } 2650 2651 // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is 2652 // actually legal and isn't going to get expanded, else this is a false 2653 // optimisation. 2654 bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD, 2655 Load->getMemoryVT()); 2656 2657 // Resize the constant to the same size as the original memory access before 2658 // extension. If it is still the AllOnesValue then this AND is completely 2659 // unneeded. 2660 Constant = 2661 Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits()); 2662 2663 bool B; 2664 switch (Load->getExtensionType()) { 2665 default: B = false; break; 2666 case ISD::EXTLOAD: B = CanZextLoadProfitably; break; 2667 case ISD::ZEXTLOAD: 2668 case ISD::NON_EXTLOAD: B = true; break; 2669 } 2670 2671 if (B && Constant.isAllOnesValue()) { 2672 // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to 2673 // preserve semantics once we get rid of the AND. 2674 SDValue NewLoad(Load, 0); 2675 if (Load->getExtensionType() == ISD::EXTLOAD) { 2676 NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD, 2677 Load->getValueType(0), SDLoc(Load), 2678 Load->getChain(), Load->getBasePtr(), 2679 Load->getOffset(), Load->getMemoryVT(), 2680 Load->getMemOperand()); 2681 // Replace uses of the EXTLOAD with the new ZEXTLOAD. 2682 if (Load->getNumValues() == 3) { 2683 // PRE/POST_INC loads have 3 values. 2684 SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1), 2685 NewLoad.getValue(2) }; 2686 CombineTo(Load, To, 3, true); 2687 } else { 2688 CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1)); 2689 } 2690 } 2691 2692 // Fold the AND away, taking care not to fold to the old load node if we 2693 // replaced it. 2694 CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0); 2695 2696 return SDValue(N, 0); // Return N so it doesn't get rechecked! 2697 } 2698 } 2699 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y)) 2700 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){ 2701 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get(); 2702 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get(); 2703 2704 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 && 2705 LL.getValueType().isInteger()) { 2706 // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0) 2707 if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) { 2708 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0), 2709 LR.getValueType(), LL, RL); 2710 AddToWorkList(ORNode.getNode()); 2711 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1); 2712 } 2713 // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1) 2714 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) { 2715 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0), 2716 LR.getValueType(), LL, RL); 2717 AddToWorkList(ANDNode.getNode()); 2718 return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1); 2719 } 2720 // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1) 2721 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) { 2722 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0), 2723 LR.getValueType(), LL, RL); 2724 AddToWorkList(ORNode.getNode()); 2725 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1); 2726 } 2727 } 2728 // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2) 2729 if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) && 2730 Op0 == Op1 && LL.getValueType().isInteger() && 2731 Op0 == ISD::SETNE && ((cast<ConstantSDNode>(LR)->isNullValue() && 2732 cast<ConstantSDNode>(RR)->isAllOnesValue()) || 2733 (cast<ConstantSDNode>(LR)->isAllOnesValue() && 2734 cast<ConstantSDNode>(RR)->isNullValue()))) { 2735 SDValue ADDNode = DAG.getNode(ISD::ADD, SDLoc(N0), LL.getValueType(), 2736 LL, DAG.getConstant(1, LL.getValueType())); 2737 AddToWorkList(ADDNode.getNode()); 2738 return DAG.getSetCC(SDLoc(N), VT, ADDNode, 2739 DAG.getConstant(2, LL.getValueType()), ISD::SETUGE); 2740 } 2741 // canonicalize equivalent to ll == rl 2742 if (LL == RR && LR == RL) { 2743 Op1 = ISD::getSetCCSwappedOperands(Op1); 2744 std::swap(RL, RR); 2745 } 2746 if (LL == RL && LR == RR) { 2747 bool isInteger = LL.getValueType().isInteger(); 2748 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger); 2749 if (Result != ISD::SETCC_INVALID && 2750 (!LegalOperations || 2751 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) && 2752 TLI.isOperationLegal(ISD::SETCC, 2753 getSetCCResultType(N0.getSimpleValueType()))))) 2754 return DAG.getSetCC(SDLoc(N), N0.getValueType(), 2755 LL, LR, Result); 2756 } 2757 } 2758 2759 // Simplify: (and (op x...), (op y...)) -> (op (and x, y)) 2760 if (N0.getOpcode() == N1.getOpcode()) { 2761 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N); 2762 if (Tmp.getNode()) return Tmp; 2763 } 2764 2765 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1) 2766 // fold (and (sra)) -> (and (srl)) when possible. 2767 if (!VT.isVector() && 2768 SimplifyDemandedBits(SDValue(N, 0))) 2769 return SDValue(N, 0); 2770 2771 // fold (zext_inreg (extload x)) -> (zextload x) 2772 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) { 2773 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 2774 EVT MemVT = LN0->getMemoryVT(); 2775 // If we zero all the possible extended bits, then we can turn this into 2776 // a zextload if we are running before legalize or the operation is legal. 2777 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits(); 2778 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth, 2779 BitWidth - MemVT.getScalarType().getSizeInBits())) && 2780 ((!LegalOperations && !LN0->isVolatile()) || 2781 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) { 2782 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT, 2783 LN0->getChain(), LN0->getBasePtr(), 2784 MemVT, LN0->getMemOperand()); 2785 AddToWorkList(N); 2786 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 2787 return SDValue(N, 0); // Return N so it doesn't get rechecked! 2788 } 2789 } 2790 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use 2791 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 2792 N0.hasOneUse()) { 2793 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 2794 EVT MemVT = LN0->getMemoryVT(); 2795 // If we zero all the possible extended bits, then we can turn this into 2796 // a zextload if we are running before legalize or the operation is legal. 2797 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits(); 2798 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth, 2799 BitWidth - MemVT.getScalarType().getSizeInBits())) && 2800 ((!LegalOperations && !LN0->isVolatile()) || 2801 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) { 2802 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT, 2803 LN0->getChain(), LN0->getBasePtr(), 2804 MemVT, LN0->getMemOperand()); 2805 AddToWorkList(N); 2806 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 2807 return SDValue(N, 0); // Return N so it doesn't get rechecked! 2808 } 2809 } 2810 2811 // fold (and (load x), 255) -> (zextload x, i8) 2812 // fold (and (extload x, i16), 255) -> (zextload x, i8) 2813 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8) 2814 if (N1C && (N0.getOpcode() == ISD::LOAD || 2815 (N0.getOpcode() == ISD::ANY_EXTEND && 2816 N0.getOperand(0).getOpcode() == ISD::LOAD))) { 2817 bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND; 2818 LoadSDNode *LN0 = HasAnyExt 2819 ? cast<LoadSDNode>(N0.getOperand(0)) 2820 : cast<LoadSDNode>(N0); 2821 if (LN0->getExtensionType() != ISD::SEXTLOAD && 2822 LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) { 2823 uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits(); 2824 if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){ 2825 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits); 2826 EVT LoadedVT = LN0->getMemoryVT(); 2827 2828 if (ExtVT == LoadedVT && 2829 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) { 2830 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT; 2831 2832 SDValue NewLoad = 2833 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy, 2834 LN0->getChain(), LN0->getBasePtr(), ExtVT, 2835 LN0->getMemOperand()); 2836 AddToWorkList(N); 2837 CombineTo(LN0, NewLoad, NewLoad.getValue(1)); 2838 return SDValue(N, 0); // Return N so it doesn't get rechecked! 2839 } 2840 2841 // Do not change the width of a volatile load. 2842 // Do not generate loads of non-round integer types since these can 2843 // be expensive (and would be wrong if the type is not byte sized). 2844 if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() && 2845 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) { 2846 EVT PtrType = LN0->getOperand(1).getValueType(); 2847 2848 unsigned Alignment = LN0->getAlignment(); 2849 SDValue NewPtr = LN0->getBasePtr(); 2850 2851 // For big endian targets, we need to add an offset to the pointer 2852 // to load the correct bytes. For little endian systems, we merely 2853 // need to read fewer bytes from the same pointer. 2854 if (TLI.isBigEndian()) { 2855 unsigned LVTStoreBytes = LoadedVT.getStoreSize(); 2856 unsigned EVTStoreBytes = ExtVT.getStoreSize(); 2857 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes; 2858 NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0), PtrType, 2859 NewPtr, DAG.getConstant(PtrOff, PtrType)); 2860 Alignment = MinAlign(Alignment, PtrOff); 2861 } 2862 2863 AddToWorkList(NewPtr.getNode()); 2864 2865 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT; 2866 SDValue Load = 2867 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy, 2868 LN0->getChain(), NewPtr, 2869 LN0->getPointerInfo(), 2870 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(), 2871 Alignment, LN0->getTBAAInfo()); 2872 AddToWorkList(N); 2873 CombineTo(LN0, Load, Load.getValue(1)); 2874 return SDValue(N, 0); // Return N so it doesn't get rechecked! 2875 } 2876 } 2877 } 2878 } 2879 2880 if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL && 2881 VT.getSizeInBits() <= 64) { 2882 if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 2883 APInt ADDC = ADDI->getAPIntValue(); 2884 if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) { 2885 // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal 2886 // immediate for an add, but it is legal if its top c2 bits are set, 2887 // transform the ADD so the immediate doesn't need to be materialized 2888 // in a register. 2889 if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) { 2890 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(), 2891 SRLI->getZExtValue()); 2892 if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) { 2893 ADDC |= Mask; 2894 if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) { 2895 SDValue NewAdd = 2896 DAG.getNode(ISD::ADD, SDLoc(N0), VT, 2897 N0.getOperand(0), DAG.getConstant(ADDC, VT)); 2898 CombineTo(N0.getNode(), NewAdd); 2899 return SDValue(N, 0); // Return N so it doesn't get rechecked! 2900 } 2901 } 2902 } 2903 } 2904 } 2905 } 2906 2907 // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const) 2908 if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) { 2909 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0), 2910 N0.getOperand(1), false); 2911 if (BSwap.getNode()) 2912 return BSwap; 2913 } 2914 2915 return SDValue(); 2916 } 2917 2918 /// MatchBSwapHWord - Match (a >> 8) | (a << 8) as (bswap a) >> 16 2919 /// 2920 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1, 2921 bool DemandHighBits) { 2922 if (!LegalOperations) 2923 return SDValue(); 2924 2925 EVT VT = N->getValueType(0); 2926 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16) 2927 return SDValue(); 2928 if (!TLI.isOperationLegal(ISD::BSWAP, VT)) 2929 return SDValue(); 2930 2931 // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00) 2932 bool LookPassAnd0 = false; 2933 bool LookPassAnd1 = false; 2934 if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL) 2935 std::swap(N0, N1); 2936 if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL) 2937 std::swap(N0, N1); 2938 if (N0.getOpcode() == ISD::AND) { 2939 if (!N0.getNode()->hasOneUse()) 2940 return SDValue(); 2941 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 2942 if (!N01C || N01C->getZExtValue() != 0xFF00) 2943 return SDValue(); 2944 N0 = N0.getOperand(0); 2945 LookPassAnd0 = true; 2946 } 2947 2948 if (N1.getOpcode() == ISD::AND) { 2949 if (!N1.getNode()->hasOneUse()) 2950 return SDValue(); 2951 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 2952 if (!N11C || N11C->getZExtValue() != 0xFF) 2953 return SDValue(); 2954 N1 = N1.getOperand(0); 2955 LookPassAnd1 = true; 2956 } 2957 2958 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL) 2959 std::swap(N0, N1); 2960 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL) 2961 return SDValue(); 2962 if (!N0.getNode()->hasOneUse() || 2963 !N1.getNode()->hasOneUse()) 2964 return SDValue(); 2965 2966 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 2967 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 2968 if (!N01C || !N11C) 2969 return SDValue(); 2970 if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8) 2971 return SDValue(); 2972 2973 // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8) 2974 SDValue N00 = N0->getOperand(0); 2975 if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) { 2976 if (!N00.getNode()->hasOneUse()) 2977 return SDValue(); 2978 ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1)); 2979 if (!N001C || N001C->getZExtValue() != 0xFF) 2980 return SDValue(); 2981 N00 = N00.getOperand(0); 2982 LookPassAnd0 = true; 2983 } 2984 2985 SDValue N10 = N1->getOperand(0); 2986 if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) { 2987 if (!N10.getNode()->hasOneUse()) 2988 return SDValue(); 2989 ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1)); 2990 if (!N101C || N101C->getZExtValue() != 0xFF00) 2991 return SDValue(); 2992 N10 = N10.getOperand(0); 2993 LookPassAnd1 = true; 2994 } 2995 2996 if (N00 != N10) 2997 return SDValue(); 2998 2999 // Make sure everything beyond the low halfword gets set to zero since the SRL 3000 // 16 will clear the top bits. 3001 unsigned OpSizeInBits = VT.getSizeInBits(); 3002 if (DemandHighBits && OpSizeInBits > 16) { 3003 // If the left-shift isn't masked out then the only way this is a bswap is 3004 // if all bits beyond the low 8 are 0. In that case the entire pattern 3005 // reduces to a left shift anyway: leave it for other parts of the combiner. 3006 if (!LookPassAnd0) 3007 return SDValue(); 3008 3009 // However, if the right shift isn't masked out then it might be because 3010 // it's not needed. See if we can spot that too. 3011 if (!LookPassAnd1 && 3012 !DAG.MaskedValueIsZero( 3013 N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16))) 3014 return SDValue(); 3015 } 3016 3017 SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00); 3018 if (OpSizeInBits > 16) 3019 Res = DAG.getNode(ISD::SRL, SDLoc(N), VT, Res, 3020 DAG.getConstant(OpSizeInBits-16, getShiftAmountTy(VT))); 3021 return Res; 3022 } 3023 3024 /// isBSwapHWordElement - Return true if the specified node is an element 3025 /// that makes up a 32-bit packed halfword byteswap. i.e. 3026 /// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8) 3027 static bool isBSwapHWordElement(SDValue N, SmallVectorImpl<SDNode *> &Parts) { 3028 if (!N.getNode()->hasOneUse()) 3029 return false; 3030 3031 unsigned Opc = N.getOpcode(); 3032 if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL) 3033 return false; 3034 3035 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1)); 3036 if (!N1C) 3037 return false; 3038 3039 unsigned Num; 3040 switch (N1C->getZExtValue()) { 3041 default: 3042 return false; 3043 case 0xFF: Num = 0; break; 3044 case 0xFF00: Num = 1; break; 3045 case 0xFF0000: Num = 2; break; 3046 case 0xFF000000: Num = 3; break; 3047 } 3048 3049 // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00). 3050 SDValue N0 = N.getOperand(0); 3051 if (Opc == ISD::AND) { 3052 if (Num == 0 || Num == 2) { 3053 // (x >> 8) & 0xff 3054 // (x >> 8) & 0xff0000 3055 if (N0.getOpcode() != ISD::SRL) 3056 return false; 3057 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 3058 if (!C || C->getZExtValue() != 8) 3059 return false; 3060 } else { 3061 // (x << 8) & 0xff00 3062 // (x << 8) & 0xff000000 3063 if (N0.getOpcode() != ISD::SHL) 3064 return false; 3065 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 3066 if (!C || C->getZExtValue() != 8) 3067 return false; 3068 } 3069 } else if (Opc == ISD::SHL) { 3070 // (x & 0xff) << 8 3071 // (x & 0xff0000) << 8 3072 if (Num != 0 && Num != 2) 3073 return false; 3074 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1)); 3075 if (!C || C->getZExtValue() != 8) 3076 return false; 3077 } else { // Opc == ISD::SRL 3078 // (x & 0xff00) >> 8 3079 // (x & 0xff000000) >> 8 3080 if (Num != 1 && Num != 3) 3081 return false; 3082 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1)); 3083 if (!C || C->getZExtValue() != 8) 3084 return false; 3085 } 3086 3087 if (Parts[Num]) 3088 return false; 3089 3090 Parts[Num] = N0.getOperand(0).getNode(); 3091 return true; 3092 } 3093 3094 /// MatchBSwapHWord - Match a 32-bit packed halfword bswap. That is 3095 /// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8) 3096 /// => (rotl (bswap x), 16) 3097 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) { 3098 if (!LegalOperations) 3099 return SDValue(); 3100 3101 EVT VT = N->getValueType(0); 3102 if (VT != MVT::i32) 3103 return SDValue(); 3104 if (!TLI.isOperationLegal(ISD::BSWAP, VT)) 3105 return SDValue(); 3106 3107 SmallVector<SDNode*,4> Parts(4, (SDNode*)0); 3108 // Look for either 3109 // (or (or (and), (and)), (or (and), (and))) 3110 // (or (or (or (and), (and)), (and)), (and)) 3111 if (N0.getOpcode() != ISD::OR) 3112 return SDValue(); 3113 SDValue N00 = N0.getOperand(0); 3114 SDValue N01 = N0.getOperand(1); 3115 3116 if (N1.getOpcode() == ISD::OR && 3117 N00.getNumOperands() == 2 && N01.getNumOperands() == 2) { 3118 // (or (or (and), (and)), (or (and), (and))) 3119 SDValue N000 = N00.getOperand(0); 3120 if (!isBSwapHWordElement(N000, Parts)) 3121 return SDValue(); 3122 3123 SDValue N001 = N00.getOperand(1); 3124 if (!isBSwapHWordElement(N001, Parts)) 3125 return SDValue(); 3126 SDValue N010 = N01.getOperand(0); 3127 if (!isBSwapHWordElement(N010, Parts)) 3128 return SDValue(); 3129 SDValue N011 = N01.getOperand(1); 3130 if (!isBSwapHWordElement(N011, Parts)) 3131 return SDValue(); 3132 } else { 3133 // (or (or (or (and), (and)), (and)), (and)) 3134 if (!isBSwapHWordElement(N1, Parts)) 3135 return SDValue(); 3136 if (!isBSwapHWordElement(N01, Parts)) 3137 return SDValue(); 3138 if (N00.getOpcode() != ISD::OR) 3139 return SDValue(); 3140 SDValue N000 = N00.getOperand(0); 3141 if (!isBSwapHWordElement(N000, Parts)) 3142 return SDValue(); 3143 SDValue N001 = N00.getOperand(1); 3144 if (!isBSwapHWordElement(N001, Parts)) 3145 return SDValue(); 3146 } 3147 3148 // Make sure the parts are all coming from the same node. 3149 if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3]) 3150 return SDValue(); 3151 3152 SDValue BSwap = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, 3153 SDValue(Parts[0],0)); 3154 3155 // Result of the bswap should be rotated by 16. If it's not legal, then 3156 // do (x << 16) | (x >> 16). 3157 SDValue ShAmt = DAG.getConstant(16, getShiftAmountTy(VT)); 3158 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT)) 3159 return DAG.getNode(ISD::ROTL, SDLoc(N), VT, BSwap, ShAmt); 3160 if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT)) 3161 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, BSwap, ShAmt); 3162 return DAG.getNode(ISD::OR, SDLoc(N), VT, 3163 DAG.getNode(ISD::SHL, SDLoc(N), VT, BSwap, ShAmt), 3164 DAG.getNode(ISD::SRL, SDLoc(N), VT, BSwap, ShAmt)); 3165 } 3166 3167 SDValue DAGCombiner::visitOR(SDNode *N) { 3168 SDValue N0 = N->getOperand(0); 3169 SDValue N1 = N->getOperand(1); 3170 SDValue LL, LR, RL, RR, CC0, CC1; 3171 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 3172 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 3173 EVT VT = N1.getValueType(); 3174 3175 // fold vector ops 3176 if (VT.isVector()) { 3177 SDValue FoldedVOp = SimplifyVBinOp(N); 3178 if (FoldedVOp.getNode()) return FoldedVOp; 3179 3180 // fold (or x, 0) -> x, vector edition 3181 if (ISD::isBuildVectorAllZeros(N0.getNode())) 3182 return N1; 3183 if (ISD::isBuildVectorAllZeros(N1.getNode())) 3184 return N0; 3185 3186 // fold (or x, -1) -> -1, vector edition 3187 if (ISD::isBuildVectorAllOnes(N0.getNode())) 3188 return N0; 3189 if (ISD::isBuildVectorAllOnes(N1.getNode())) 3190 return N1; 3191 } 3192 3193 // fold (or x, undef) -> -1 3194 if (!LegalOperations && 3195 (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) { 3196 EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT; 3197 return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT); 3198 } 3199 // fold (or c1, c2) -> c1|c2 3200 if (N0C && N1C) 3201 return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C); 3202 // canonicalize constant to RHS 3203 if (N0C && !N1C) 3204 return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0); 3205 // fold (or x, 0) -> x 3206 if (N1C && N1C->isNullValue()) 3207 return N0; 3208 // fold (or x, -1) -> -1 3209 if (N1C && N1C->isAllOnesValue()) 3210 return N1; 3211 // fold (or x, c) -> c iff (x & ~c) == 0 3212 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue())) 3213 return N1; 3214 3215 // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16) 3216 SDValue BSwap = MatchBSwapHWord(N, N0, N1); 3217 if (BSwap.getNode() != 0) 3218 return BSwap; 3219 BSwap = MatchBSwapHWordLow(N, N0, N1); 3220 if (BSwap.getNode() != 0) 3221 return BSwap; 3222 3223 // reassociate or 3224 SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1); 3225 if (ROR.getNode() != 0) 3226 return ROR; 3227 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2) 3228 // iff (c1 & c2) == 0. 3229 if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() && 3230 isa<ConstantSDNode>(N0.getOperand(1))) { 3231 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1)); 3232 if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) { 3233 SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1); 3234 if (!COR.getNode()) 3235 return SDValue(); 3236 return DAG.getNode(ISD::AND, SDLoc(N), VT, 3237 DAG.getNode(ISD::OR, SDLoc(N0), VT, 3238 N0.getOperand(0), N1), COR); 3239 } 3240 } 3241 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y)) 3242 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){ 3243 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get(); 3244 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get(); 3245 3246 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 && 3247 LL.getValueType().isInteger()) { 3248 // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0) 3249 // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0) 3250 if (cast<ConstantSDNode>(LR)->isNullValue() && 3251 (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) { 3252 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR), 3253 LR.getValueType(), LL, RL); 3254 AddToWorkList(ORNode.getNode()); 3255 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1); 3256 } 3257 // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1) 3258 // fold (or (setgt X, -1), (setgt Y -1)) -> (setgt (and X, Y), -1) 3259 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && 3260 (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) { 3261 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR), 3262 LR.getValueType(), LL, RL); 3263 AddToWorkList(ANDNode.getNode()); 3264 return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1); 3265 } 3266 } 3267 // canonicalize equivalent to ll == rl 3268 if (LL == RR && LR == RL) { 3269 Op1 = ISD::getSetCCSwappedOperands(Op1); 3270 std::swap(RL, RR); 3271 } 3272 if (LL == RL && LR == RR) { 3273 bool isInteger = LL.getValueType().isInteger(); 3274 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger); 3275 if (Result != ISD::SETCC_INVALID && 3276 (!LegalOperations || 3277 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) && 3278 TLI.isOperationLegal(ISD::SETCC, 3279 getSetCCResultType(N0.getValueType()))))) 3280 return DAG.getSetCC(SDLoc(N), N0.getValueType(), 3281 LL, LR, Result); 3282 } 3283 } 3284 3285 // Simplify: (or (op x...), (op y...)) -> (op (or x, y)) 3286 if (N0.getOpcode() == N1.getOpcode()) { 3287 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N); 3288 if (Tmp.getNode()) return Tmp; 3289 } 3290 3291 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible. 3292 if (N0.getOpcode() == ISD::AND && 3293 N1.getOpcode() == ISD::AND && 3294 N0.getOperand(1).getOpcode() == ISD::Constant && 3295 N1.getOperand(1).getOpcode() == ISD::Constant && 3296 // Don't increase # computations. 3297 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) { 3298 // We can only do this xform if we know that bits from X that are set in C2 3299 // but not in C1 are already zero. Likewise for Y. 3300 const APInt &LHSMask = 3301 cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 3302 const APInt &RHSMask = 3303 cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue(); 3304 3305 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) && 3306 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) { 3307 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT, 3308 N0.getOperand(0), N1.getOperand(0)); 3309 return DAG.getNode(ISD::AND, SDLoc(N), VT, X, 3310 DAG.getConstant(LHSMask | RHSMask, VT)); 3311 } 3312 } 3313 3314 // See if this is some rotate idiom. 3315 if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N))) 3316 return SDValue(Rot, 0); 3317 3318 // Simplify the operands using demanded-bits information. 3319 if (!VT.isVector() && 3320 SimplifyDemandedBits(SDValue(N, 0))) 3321 return SDValue(N, 0); 3322 3323 return SDValue(); 3324 } 3325 3326 /// MatchRotateHalf - Match "(X shl/srl V1) & V2" where V2 may not be present. 3327 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) { 3328 if (Op.getOpcode() == ISD::AND) { 3329 if (isa<ConstantSDNode>(Op.getOperand(1))) { 3330 Mask = Op.getOperand(1); 3331 Op = Op.getOperand(0); 3332 } else { 3333 return false; 3334 } 3335 } 3336 3337 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) { 3338 Shift = Op; 3339 return true; 3340 } 3341 3342 return false; 3343 } 3344 3345 // Return true if we can prove that, whenever Neg and Pos are both in the 3346 // range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos). This means that 3347 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits: 3348 // 3349 // (or (shift1 X, Neg), (shift2 X, Pos)) 3350 // 3351 // reduces to a rotate in direction shift2 by Pos and a rotate in direction 3352 // shift1 by Neg. The range [0, OpSize) means that we only need to consider 3353 // shift amounts with defined behavior. 3354 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) { 3355 // If OpSize is a power of 2 then: 3356 // 3357 // (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1) 3358 // (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize). 3359 // 3360 // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check 3361 // for the stronger condition: 3362 // 3363 // Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1) [A] 3364 // 3365 // for all Neg and Pos. Since Neg & (OpSize - 1) == Neg' & (OpSize - 1) 3366 // we can just replace Neg with Neg' for the rest of the function. 3367 // 3368 // In other cases we check for the even stronger condition: 3369 // 3370 // Neg == OpSize - Pos [B] 3371 // 3372 // for all Neg and Pos. Note that the (or ...) then invokes undefined 3373 // behavior if Pos == 0 (and consequently Neg == OpSize). 3374 // 3375 // We could actually use [A] whenever OpSize is a power of 2, but the 3376 // only extra cases that it would match are those uninteresting ones 3377 // where Neg and Pos are never in range at the same time. E.g. for 3378 // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos) 3379 // as well as (sub 32, Pos), but: 3380 // 3381 // (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos)) 3382 // 3383 // always invokes undefined behavior for 32-bit X. 3384 // 3385 // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise. 3386 unsigned LoBits = 0; 3387 if (Neg.getOpcode() == ISD::AND && 3388 isPowerOf2_64(OpSize) && 3389 Neg.getOperand(1).getOpcode() == ISD::Constant && 3390 cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) { 3391 Neg = Neg.getOperand(0); 3392 LoBits = Log2_64(OpSize); 3393 } 3394 3395 // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1. 3396 if (Neg.getOpcode() != ISD::SUB) 3397 return 0; 3398 ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0)); 3399 if (!NegC) 3400 return 0; 3401 SDValue NegOp1 = Neg.getOperand(1); 3402 3403 // The condition we need is now: 3404 // 3405 // (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask 3406 // 3407 // If NegOp1 == Pos then we need: 3408 // 3409 // OpSize & Mask == NegC & Mask 3410 // 3411 // (because "x & Mask" is a truncation and distributes through subtraction). 3412 APInt Width; 3413 if (Pos == NegOp1) 3414 Width = NegC->getAPIntValue(); 3415 // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC. 3416 // Then the condition we want to prove becomes: 3417 // 3418 // (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask 3419 // 3420 // which, again because "x & Mask" is a truncation, becomes: 3421 // 3422 // NegC & Mask == (OpSize - PosC) & Mask 3423 // OpSize & Mask == (NegC + PosC) & Mask 3424 else if (Pos.getOpcode() == ISD::ADD && 3425 Pos.getOperand(0) == NegOp1 && 3426 Pos.getOperand(1).getOpcode() == ISD::Constant) 3427 Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() + 3428 NegC->getAPIntValue()); 3429 else 3430 return false; 3431 3432 // Now we just need to check that OpSize & Mask == Width & Mask. 3433 if (LoBits) 3434 return Width.getLoBits(LoBits) == 0; 3435 return Width == OpSize; 3436 } 3437 3438 // A subroutine of MatchRotate used once we have found an OR of two opposite 3439 // shifts of Shifted. If Neg == <operand size> - Pos then the OR reduces 3440 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the 3441 // former being preferred if supported. InnerPos and InnerNeg are Pos and 3442 // Neg with outer conversions stripped away. 3443 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos, 3444 SDValue Neg, SDValue InnerPos, 3445 SDValue InnerNeg, unsigned PosOpcode, 3446 unsigned NegOpcode, SDLoc DL) { 3447 // fold (or (shl x, (*ext y)), 3448 // (srl x, (*ext (sub 32, y)))) -> 3449 // (rotl x, y) or (rotr x, (sub 32, y)) 3450 // 3451 // fold (or (shl x, (*ext (sub 32, y))), 3452 // (srl x, (*ext y))) -> 3453 // (rotr x, y) or (rotl x, (sub 32, y)) 3454 EVT VT = Shifted.getValueType(); 3455 if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) { 3456 bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT); 3457 return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted, 3458 HasPos ? Pos : Neg).getNode(); 3459 } 3460 3461 // fold (or (shl (*ext x), (*ext y)), 3462 // (srl (*ext x), (*ext (sub 32, y)))) -> 3463 // (*ext (rotl x, y)) or (*ext (rotr x, (sub 32, y))) 3464 // 3465 // fold (or (shl (*ext x), (*ext (sub 32, y))), 3466 // (srl (*ext x), (*ext y))) -> 3467 // (*ext (rotr x, y)) or (*ext (rotl x, (sub 32, y))) 3468 if (Shifted.getOpcode() == ISD::ZERO_EXTEND || 3469 Shifted.getOpcode() == ISD::ANY_EXTEND) { 3470 SDValue InnerShifted = Shifted.getOperand(0); 3471 EVT InnerVT = InnerShifted.getValueType(); 3472 bool HasPosInner = TLI.isOperationLegalOrCustom(PosOpcode, InnerVT); 3473 if (HasPosInner || TLI.isOperationLegalOrCustom(NegOpcode, InnerVT)) { 3474 if (matchRotateSub(InnerPos, InnerNeg, InnerVT.getSizeInBits())) { 3475 SDValue V = DAG.getNode(HasPosInner ? PosOpcode : NegOpcode, DL, 3476 InnerVT, InnerShifted, HasPosInner ? Pos : Neg); 3477 return DAG.getNode(Shifted.getOpcode(), DL, VT, V).getNode(); 3478 } 3479 } 3480 } 3481 3482 return 0; 3483 } 3484 3485 // MatchRotate - Handle an 'or' of two operands. If this is one of the many 3486 // idioms for rotate, and if the target supports rotation instructions, generate 3487 // a rot[lr]. 3488 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) { 3489 // Must be a legal type. Expanded 'n promoted things won't work with rotates. 3490 EVT VT = LHS.getValueType(); 3491 if (!TLI.isTypeLegal(VT)) return 0; 3492 3493 // The target must have at least one rotate flavor. 3494 bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT); 3495 bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT); 3496 if (!HasROTL && !HasROTR) return 0; 3497 3498 // Match "(X shl/srl V1) & V2" where V2 may not be present. 3499 SDValue LHSShift; // The shift. 3500 SDValue LHSMask; // AND value if any. 3501 if (!MatchRotateHalf(LHS, LHSShift, LHSMask)) 3502 return 0; // Not part of a rotate. 3503 3504 SDValue RHSShift; // The shift. 3505 SDValue RHSMask; // AND value if any. 3506 if (!MatchRotateHalf(RHS, RHSShift, RHSMask)) 3507 return 0; // Not part of a rotate. 3508 3509 if (LHSShift.getOperand(0) != RHSShift.getOperand(0)) 3510 return 0; // Not shifting the same value. 3511 3512 if (LHSShift.getOpcode() == RHSShift.getOpcode()) 3513 return 0; // Shifts must disagree. 3514 3515 // Canonicalize shl to left side in a shl/srl pair. 3516 if (RHSShift.getOpcode() == ISD::SHL) { 3517 std::swap(LHS, RHS); 3518 std::swap(LHSShift, RHSShift); 3519 std::swap(LHSMask , RHSMask ); 3520 } 3521 3522 unsigned OpSizeInBits = VT.getSizeInBits(); 3523 SDValue LHSShiftArg = LHSShift.getOperand(0); 3524 SDValue LHSShiftAmt = LHSShift.getOperand(1); 3525 SDValue RHSShiftArg = RHSShift.getOperand(0); 3526 SDValue RHSShiftAmt = RHSShift.getOperand(1); 3527 3528 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1) 3529 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2) 3530 if (LHSShiftAmt.getOpcode() == ISD::Constant && 3531 RHSShiftAmt.getOpcode() == ISD::Constant) { 3532 uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue(); 3533 uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue(); 3534 if ((LShVal + RShVal) != OpSizeInBits) 3535 return 0; 3536 3537 SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT, 3538 LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt); 3539 3540 // If there is an AND of either shifted operand, apply it to the result. 3541 if (LHSMask.getNode() || RHSMask.getNode()) { 3542 APInt Mask = APInt::getAllOnesValue(OpSizeInBits); 3543 3544 if (LHSMask.getNode()) { 3545 APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal); 3546 Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits; 3547 } 3548 if (RHSMask.getNode()) { 3549 APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal); 3550 Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits; 3551 } 3552 3553 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT)); 3554 } 3555 3556 return Rot.getNode(); 3557 } 3558 3559 // If there is a mask here, and we have a variable shift, we can't be sure 3560 // that we're masking out the right stuff. 3561 if (LHSMask.getNode() || RHSMask.getNode()) 3562 return 0; 3563 3564 // If the shift amount is sign/zext/any-extended just peel it off. 3565 SDValue LExtOp0 = LHSShiftAmt; 3566 SDValue RExtOp0 = RHSShiftAmt; 3567 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND || 3568 LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND || 3569 LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND || 3570 LHSShiftAmt.getOpcode() == ISD::TRUNCATE) && 3571 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND || 3572 RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND || 3573 RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND || 3574 RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) { 3575 LExtOp0 = LHSShiftAmt.getOperand(0); 3576 RExtOp0 = RHSShiftAmt.getOperand(0); 3577 } 3578 3579 SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt, 3580 LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL); 3581 if (TryL) 3582 return TryL; 3583 3584 SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt, 3585 RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL); 3586 if (TryR) 3587 return TryR; 3588 3589 return 0; 3590 } 3591 3592 SDValue DAGCombiner::visitXOR(SDNode *N) { 3593 SDValue N0 = N->getOperand(0); 3594 SDValue N1 = N->getOperand(1); 3595 SDValue LHS, RHS, CC; 3596 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 3597 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 3598 EVT VT = N0.getValueType(); 3599 3600 // fold vector ops 3601 if (VT.isVector()) { 3602 SDValue FoldedVOp = SimplifyVBinOp(N); 3603 if (FoldedVOp.getNode()) return FoldedVOp; 3604 3605 // fold (xor x, 0) -> x, vector edition 3606 if (ISD::isBuildVectorAllZeros(N0.getNode())) 3607 return N1; 3608 if (ISD::isBuildVectorAllZeros(N1.getNode())) 3609 return N0; 3610 } 3611 3612 // fold (xor undef, undef) -> 0. This is a common idiom (misuse). 3613 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF) 3614 return DAG.getConstant(0, VT); 3615 // fold (xor x, undef) -> undef 3616 if (N0.getOpcode() == ISD::UNDEF) 3617 return N0; 3618 if (N1.getOpcode() == ISD::UNDEF) 3619 return N1; 3620 // fold (xor c1, c2) -> c1^c2 3621 if (N0C && N1C) 3622 return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C); 3623 // canonicalize constant to RHS 3624 if (N0C && !N1C) 3625 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0); 3626 // fold (xor x, 0) -> x 3627 if (N1C && N1C->isNullValue()) 3628 return N0; 3629 // reassociate xor 3630 SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1); 3631 if (RXOR.getNode() != 0) 3632 return RXOR; 3633 3634 // fold !(x cc y) -> (x !cc y) 3635 if (N1C && N1C->getAPIntValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) { 3636 bool isInt = LHS.getValueType().isInteger(); 3637 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(), 3638 isInt); 3639 3640 if (!LegalOperations || 3641 TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) { 3642 switch (N0.getOpcode()) { 3643 default: 3644 llvm_unreachable("Unhandled SetCC Equivalent!"); 3645 case ISD::SETCC: 3646 return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC); 3647 case ISD::SELECT_CC: 3648 return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2), 3649 N0.getOperand(3), NotCC); 3650 } 3651 } 3652 } 3653 3654 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y))) 3655 if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND && 3656 N0.getNode()->hasOneUse() && 3657 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){ 3658 SDValue V = N0.getOperand(0); 3659 V = DAG.getNode(ISD::XOR, SDLoc(N0), V.getValueType(), V, 3660 DAG.getConstant(1, V.getValueType())); 3661 AddToWorkList(V.getNode()); 3662 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V); 3663 } 3664 3665 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc 3666 if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 && 3667 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) { 3668 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1); 3669 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) { 3670 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND; 3671 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS 3672 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS 3673 AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode()); 3674 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS); 3675 } 3676 } 3677 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants 3678 if (N1C && N1C->isAllOnesValue() && 3679 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) { 3680 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1); 3681 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) { 3682 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND; 3683 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS 3684 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS 3685 AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode()); 3686 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS); 3687 } 3688 } 3689 // fold (xor (and x, y), y) -> (and (not x), y) 3690 if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() && 3691 N0->getOperand(1) == N1) { 3692 SDValue X = N0->getOperand(0); 3693 SDValue NotX = DAG.getNOT(SDLoc(X), X, VT); 3694 AddToWorkList(NotX.getNode()); 3695 return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1); 3696 } 3697 // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2)) 3698 if (N1C && N0.getOpcode() == ISD::XOR) { 3699 ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0)); 3700 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 3701 if (N00C) 3702 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(1), 3703 DAG.getConstant(N1C->getAPIntValue() ^ 3704 N00C->getAPIntValue(), VT)); 3705 if (N01C) 3706 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(0), 3707 DAG.getConstant(N1C->getAPIntValue() ^ 3708 N01C->getAPIntValue(), VT)); 3709 } 3710 // fold (xor x, x) -> 0 3711 if (N0 == N1) 3712 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes); 3713 3714 // Simplify: xor (op x...), (op y...) -> (op (xor x, y)) 3715 if (N0.getOpcode() == N1.getOpcode()) { 3716 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N); 3717 if (Tmp.getNode()) return Tmp; 3718 } 3719 3720 // Simplify the expression using non-local knowledge. 3721 if (!VT.isVector() && 3722 SimplifyDemandedBits(SDValue(N, 0))) 3723 return SDValue(N, 0); 3724 3725 return SDValue(); 3726 } 3727 3728 /// visitShiftByConstant - Handle transforms common to the three shifts, when 3729 /// the shift amount is a constant. 3730 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, unsigned Amt) { 3731 SDNode *LHS = N->getOperand(0).getNode(); 3732 if (!LHS->hasOneUse()) return SDValue(); 3733 3734 // We want to pull some binops through shifts, so that we have (and (shift)) 3735 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of 3736 // thing happens with address calculations, so it's important to canonicalize 3737 // it. 3738 bool HighBitSet = false; // Can we transform this if the high bit is set? 3739 3740 switch (LHS->getOpcode()) { 3741 default: return SDValue(); 3742 case ISD::OR: 3743 case ISD::XOR: 3744 HighBitSet = false; // We can only transform sra if the high bit is clear. 3745 break; 3746 case ISD::AND: 3747 HighBitSet = true; // We can only transform sra if the high bit is set. 3748 break; 3749 case ISD::ADD: 3750 if (N->getOpcode() != ISD::SHL) 3751 return SDValue(); // only shl(add) not sr[al](add). 3752 HighBitSet = false; // We can only transform sra if the high bit is clear. 3753 break; 3754 } 3755 3756 // We require the RHS of the binop to be a constant as well. 3757 ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1)); 3758 if (!BinOpCst) return SDValue(); 3759 3760 // FIXME: disable this unless the input to the binop is a shift by a constant. 3761 // If it is not a shift, it pessimizes some common cases like: 3762 // 3763 // void foo(int *X, int i) { X[i & 1235] = 1; } 3764 // int bar(int *X, int i) { return X[i & 255]; } 3765 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode(); 3766 if ((BinOpLHSVal->getOpcode() != ISD::SHL && 3767 BinOpLHSVal->getOpcode() != ISD::SRA && 3768 BinOpLHSVal->getOpcode() != ISD::SRL) || 3769 !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1))) 3770 return SDValue(); 3771 3772 EVT VT = N->getValueType(0); 3773 3774 // If this is a signed shift right, and the high bit is modified by the 3775 // logical operation, do not perform the transformation. The highBitSet 3776 // boolean indicates the value of the high bit of the constant which would 3777 // cause it to be modified for this operation. 3778 if (N->getOpcode() == ISD::SRA) { 3779 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative(); 3780 if (BinOpRHSSignSet != HighBitSet) 3781 return SDValue(); 3782 } 3783 3784 // Fold the constants, shifting the binop RHS by the shift amount. 3785 SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)), 3786 N->getValueType(0), 3787 LHS->getOperand(1), N->getOperand(1)); 3788 3789 // Create the new shift. 3790 SDValue NewShift = DAG.getNode(N->getOpcode(), 3791 SDLoc(LHS->getOperand(0)), 3792 VT, LHS->getOperand(0), N->getOperand(1)); 3793 3794 // Create the new binop. 3795 return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS); 3796 } 3797 3798 SDValue DAGCombiner::visitSHL(SDNode *N) { 3799 SDValue N0 = N->getOperand(0); 3800 SDValue N1 = N->getOperand(1); 3801 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 3802 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 3803 EVT VT = N0.getValueType(); 3804 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits(); 3805 3806 // fold vector ops 3807 if (VT.isVector()) { 3808 SDValue FoldedVOp = SimplifyVBinOp(N); 3809 if (FoldedVOp.getNode()) return FoldedVOp; 3810 } 3811 3812 // fold (shl c1, c2) -> c1<<c2 3813 if (N0C && N1C) 3814 return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C); 3815 // fold (shl 0, x) -> 0 3816 if (N0C && N0C->isNullValue()) 3817 return N0; 3818 // fold (shl x, c >= size(x)) -> undef 3819 if (N1C && N1C->getZExtValue() >= OpSizeInBits) 3820 return DAG.getUNDEF(VT); 3821 // fold (shl x, 0) -> x 3822 if (N1C && N1C->isNullValue()) 3823 return N0; 3824 // fold (shl undef, x) -> 0 3825 if (N0.getOpcode() == ISD::UNDEF) 3826 return DAG.getConstant(0, VT); 3827 // if (shl x, c) is known to be zero, return 0 3828 if (DAG.MaskedValueIsZero(SDValue(N, 0), 3829 APInt::getAllOnesValue(OpSizeInBits))) 3830 return DAG.getConstant(0, VT); 3831 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))). 3832 if (N1.getOpcode() == ISD::TRUNCATE && 3833 N1.getOperand(0).getOpcode() == ISD::AND && 3834 N1.hasOneUse() && N1.getOperand(0).hasOneUse()) { 3835 SDValue N101 = N1.getOperand(0).getOperand(1); 3836 if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) { 3837 EVT TruncVT = N1.getValueType(); 3838 SDValue N100 = N1.getOperand(0).getOperand(0); 3839 APInt TruncC = N101C->getAPIntValue(); 3840 TruncC = TruncC.trunc(TruncVT.getSizeInBits()); 3841 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, 3842 DAG.getNode(ISD::AND, SDLoc(N), TruncVT, 3843 DAG.getNode(ISD::TRUNCATE, 3844 SDLoc(N), 3845 TruncVT, N100), 3846 DAG.getConstant(TruncC, TruncVT))); 3847 } 3848 } 3849 3850 if (N1C && SimplifyDemandedBits(SDValue(N, 0))) 3851 return SDValue(N, 0); 3852 3853 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2)) 3854 if (N1C && N0.getOpcode() == ISD::SHL && 3855 N0.getOperand(1).getOpcode() == ISD::Constant) { 3856 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue(); 3857 uint64_t c2 = N1C->getZExtValue(); 3858 if (c1 + c2 >= OpSizeInBits) 3859 return DAG.getConstant(0, VT); 3860 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0), 3861 DAG.getConstant(c1 + c2, N1.getValueType())); 3862 } 3863 3864 // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2))) 3865 // For this to be valid, the second form must not preserve any of the bits 3866 // that are shifted out by the inner shift in the first form. This means 3867 // the outer shift size must be >= the number of bits added by the ext. 3868 // As a corollary, we don't care what kind of ext it is. 3869 if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND || 3870 N0.getOpcode() == ISD::ANY_EXTEND || 3871 N0.getOpcode() == ISD::SIGN_EXTEND) && 3872 N0.getOperand(0).getOpcode() == ISD::SHL && 3873 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) { 3874 uint64_t c1 = 3875 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue(); 3876 uint64_t c2 = N1C->getZExtValue(); 3877 EVT InnerShiftVT = N0.getOperand(0).getValueType(); 3878 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits(); 3879 if (c2 >= OpSizeInBits - InnerShiftSize) { 3880 if (c1 + c2 >= OpSizeInBits) 3881 return DAG.getConstant(0, VT); 3882 return DAG.getNode(ISD::SHL, SDLoc(N0), VT, 3883 DAG.getNode(N0.getOpcode(), SDLoc(N0), VT, 3884 N0.getOperand(0)->getOperand(0)), 3885 DAG.getConstant(c1 + c2, N1.getValueType())); 3886 } 3887 } 3888 3889 // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C)) 3890 // Only fold this if the inner zext has no other uses to avoid increasing 3891 // the total number of instructions. 3892 if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() && 3893 N0.getOperand(0).getOpcode() == ISD::SRL && 3894 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) { 3895 uint64_t c1 = 3896 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue(); 3897 if (c1 < VT.getSizeInBits()) { 3898 uint64_t c2 = N1C->getZExtValue(); 3899 if (c1 == c2) { 3900 SDValue NewOp0 = N0.getOperand(0); 3901 EVT CountVT = NewOp0.getOperand(1).getValueType(); 3902 SDValue NewSHL = DAG.getNode(ISD::SHL, SDLoc(N), NewOp0.getValueType(), 3903 NewOp0, DAG.getConstant(c2, CountVT)); 3904 AddToWorkList(NewSHL.getNode()); 3905 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL); 3906 } 3907 } 3908 } 3909 3910 // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or 3911 // (and (srl x, (sub c1, c2), MASK) 3912 // Only fold this if the inner shift has no other uses -- if it does, folding 3913 // this will increase the total number of instructions. 3914 if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse() && 3915 N0.getOperand(1).getOpcode() == ISD::Constant) { 3916 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue(); 3917 if (c1 < VT.getSizeInBits()) { 3918 uint64_t c2 = N1C->getZExtValue(); 3919 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(), 3920 VT.getSizeInBits() - c1); 3921 SDValue Shift; 3922 if (c2 > c1) { 3923 Mask = Mask.shl(c2-c1); 3924 Shift = DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0), 3925 DAG.getConstant(c2-c1, N1.getValueType())); 3926 } else { 3927 Mask = Mask.lshr(c1-c2); 3928 Shift = DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), 3929 DAG.getConstant(c1-c2, N1.getValueType())); 3930 } 3931 return DAG.getNode(ISD::AND, SDLoc(N0), VT, Shift, 3932 DAG.getConstant(Mask, VT)); 3933 } 3934 } 3935 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1)) 3936 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) { 3937 SDValue HiBitsMask = 3938 DAG.getConstant(APInt::getHighBitsSet(VT.getSizeInBits(), 3939 VT.getSizeInBits() - 3940 N1C->getZExtValue()), 3941 VT); 3942 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0), 3943 HiBitsMask); 3944 } 3945 3946 if (N1C) { 3947 SDValue NewSHL = visitShiftByConstant(N, N1C->getZExtValue()); 3948 if (NewSHL.getNode()) 3949 return NewSHL; 3950 } 3951 3952 return SDValue(); 3953 } 3954 3955 SDValue DAGCombiner::visitSRA(SDNode *N) { 3956 SDValue N0 = N->getOperand(0); 3957 SDValue N1 = N->getOperand(1); 3958 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 3959 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 3960 EVT VT = N0.getValueType(); 3961 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits(); 3962 3963 // fold vector ops 3964 if (VT.isVector()) { 3965 SDValue FoldedVOp = SimplifyVBinOp(N); 3966 if (FoldedVOp.getNode()) return FoldedVOp; 3967 } 3968 3969 // fold (sra c1, c2) -> (sra c1, c2) 3970 if (N0C && N1C) 3971 return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C); 3972 // fold (sra 0, x) -> 0 3973 if (N0C && N0C->isNullValue()) 3974 return N0; 3975 // fold (sra -1, x) -> -1 3976 if (N0C && N0C->isAllOnesValue()) 3977 return N0; 3978 // fold (sra x, (setge c, size(x))) -> undef 3979 if (N1C && N1C->getZExtValue() >= OpSizeInBits) 3980 return DAG.getUNDEF(VT); 3981 // fold (sra x, 0) -> x 3982 if (N1C && N1C->isNullValue()) 3983 return N0; 3984 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports 3985 // sext_inreg. 3986 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) { 3987 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue(); 3988 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits); 3989 if (VT.isVector()) 3990 ExtVT = EVT::getVectorVT(*DAG.getContext(), 3991 ExtVT, VT.getVectorNumElements()); 3992 if ((!LegalOperations || 3993 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT))) 3994 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, 3995 N0.getOperand(0), DAG.getValueType(ExtVT)); 3996 } 3997 3998 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2)) 3999 if (N1C && N0.getOpcode() == ISD::SRA) { 4000 if (ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 4001 unsigned Sum = N1C->getZExtValue() + C1->getZExtValue(); 4002 if (Sum >= OpSizeInBits) Sum = OpSizeInBits-1; 4003 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0.getOperand(0), 4004 DAG.getConstant(Sum, N1C->getValueType(0))); 4005 } 4006 } 4007 4008 // fold (sra (shl X, m), (sub result_size, n)) 4009 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for 4010 // result_size - n != m. 4011 // If truncate is free for the target sext(shl) is likely to result in better 4012 // code. 4013 if (N0.getOpcode() == ISD::SHL) { 4014 // Get the two constanst of the shifts, CN0 = m, CN = n. 4015 const ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 4016 if (N01C && N1C) { 4017 // Determine what the truncate's result bitsize and type would be. 4018 EVT TruncVT = 4019 EVT::getIntegerVT(*DAG.getContext(), 4020 OpSizeInBits - N1C->getZExtValue()); 4021 // Determine the residual right-shift amount. 4022 signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue(); 4023 4024 // If the shift is not a no-op (in which case this should be just a sign 4025 // extend already), the truncated to type is legal, sign_extend is legal 4026 // on that type, and the truncate to that type is both legal and free, 4027 // perform the transform. 4028 if ((ShiftAmt > 0) && 4029 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) && 4030 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) && 4031 TLI.isTruncateFree(VT, TruncVT)) { 4032 4033 SDValue Amt = DAG.getConstant(ShiftAmt, 4034 getShiftAmountTy(N0.getOperand(0).getValueType())); 4035 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), VT, 4036 N0.getOperand(0), Amt); 4037 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), TruncVT, 4038 Shift); 4039 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), 4040 N->getValueType(0), Trunc); 4041 } 4042 } 4043 } 4044 4045 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))). 4046 if (N1.getOpcode() == ISD::TRUNCATE && 4047 N1.getOperand(0).getOpcode() == ISD::AND && 4048 N1.hasOneUse() && N1.getOperand(0).hasOneUse()) { 4049 SDValue N101 = N1.getOperand(0).getOperand(1); 4050 if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) { 4051 EVT TruncVT = N1.getValueType(); 4052 SDValue N100 = N1.getOperand(0).getOperand(0); 4053 APInt TruncC = N101C->getAPIntValue(); 4054 TruncC = TruncC.trunc(TruncVT.getScalarType().getSizeInBits()); 4055 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, 4056 DAG.getNode(ISD::AND, SDLoc(N), 4057 TruncVT, 4058 DAG.getNode(ISD::TRUNCATE, 4059 SDLoc(N), 4060 TruncVT, N100), 4061 DAG.getConstant(TruncC, TruncVT))); 4062 } 4063 } 4064 4065 // fold (sra (trunc (sr x, c1)), c2) -> (trunc (sra x, c1+c2)) 4066 // if c1 is equal to the number of bits the trunc removes 4067 if (N0.getOpcode() == ISD::TRUNCATE && 4068 (N0.getOperand(0).getOpcode() == ISD::SRL || 4069 N0.getOperand(0).getOpcode() == ISD::SRA) && 4070 N0.getOperand(0).hasOneUse() && 4071 N0.getOperand(0).getOperand(1).hasOneUse() && 4072 N1C && isa<ConstantSDNode>(N0.getOperand(0).getOperand(1))) { 4073 EVT LargeVT = N0.getOperand(0).getValueType(); 4074 ConstantSDNode *LargeShiftAmt = 4075 cast<ConstantSDNode>(N0.getOperand(0).getOperand(1)); 4076 4077 if (LargeVT.getScalarType().getSizeInBits() - OpSizeInBits == 4078 LargeShiftAmt->getZExtValue()) { 4079 SDValue Amt = 4080 DAG.getConstant(LargeShiftAmt->getZExtValue() + N1C->getZExtValue(), 4081 getShiftAmountTy(N0.getOperand(0).getOperand(0).getValueType())); 4082 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), LargeVT, 4083 N0.getOperand(0).getOperand(0), Amt); 4084 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, SRA); 4085 } 4086 } 4087 4088 // Simplify, based on bits shifted out of the LHS. 4089 if (N1C && SimplifyDemandedBits(SDValue(N, 0))) 4090 return SDValue(N, 0); 4091 4092 4093 // If the sign bit is known to be zero, switch this to a SRL. 4094 if (DAG.SignBitIsZero(N0)) 4095 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1); 4096 4097 if (N1C) { 4098 SDValue NewSRA = visitShiftByConstant(N, N1C->getZExtValue()); 4099 if (NewSRA.getNode()) 4100 return NewSRA; 4101 } 4102 4103 return SDValue(); 4104 } 4105 4106 SDValue DAGCombiner::visitSRL(SDNode *N) { 4107 SDValue N0 = N->getOperand(0); 4108 SDValue N1 = N->getOperand(1); 4109 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 4110 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 4111 EVT VT = N0.getValueType(); 4112 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits(); 4113 4114 // fold vector ops 4115 if (VT.isVector()) { 4116 SDValue FoldedVOp = SimplifyVBinOp(N); 4117 if (FoldedVOp.getNode()) return FoldedVOp; 4118 } 4119 4120 // fold (srl c1, c2) -> c1 >>u c2 4121 if (N0C && N1C) 4122 return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C); 4123 // fold (srl 0, x) -> 0 4124 if (N0C && N0C->isNullValue()) 4125 return N0; 4126 // fold (srl x, c >= size(x)) -> undef 4127 if (N1C && N1C->getZExtValue() >= OpSizeInBits) 4128 return DAG.getUNDEF(VT); 4129 // fold (srl x, 0) -> x 4130 if (N1C && N1C->isNullValue()) 4131 return N0; 4132 // if (srl x, c) is known to be zero, return 0 4133 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0), 4134 APInt::getAllOnesValue(OpSizeInBits))) 4135 return DAG.getConstant(0, VT); 4136 4137 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2)) 4138 if (N1C && N0.getOpcode() == ISD::SRL && 4139 N0.getOperand(1).getOpcode() == ISD::Constant) { 4140 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue(); 4141 uint64_t c2 = N1C->getZExtValue(); 4142 if (c1 + c2 >= OpSizeInBits) 4143 return DAG.getConstant(0, VT); 4144 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), 4145 DAG.getConstant(c1 + c2, N1.getValueType())); 4146 } 4147 4148 // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2))) 4149 if (N1C && N0.getOpcode() == ISD::TRUNCATE && 4150 N0.getOperand(0).getOpcode() == ISD::SRL && 4151 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) { 4152 uint64_t c1 = 4153 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue(); 4154 uint64_t c2 = N1C->getZExtValue(); 4155 EVT InnerShiftVT = N0.getOperand(0).getValueType(); 4156 EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType(); 4157 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits(); 4158 // This is only valid if the OpSizeInBits + c1 = size of inner shift. 4159 if (c1 + OpSizeInBits == InnerShiftSize) { 4160 if (c1 + c2 >= InnerShiftSize) 4161 return DAG.getConstant(0, VT); 4162 return DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, 4163 DAG.getNode(ISD::SRL, SDLoc(N0), InnerShiftVT, 4164 N0.getOperand(0)->getOperand(0), 4165 DAG.getConstant(c1 + c2, ShiftCountVT))); 4166 } 4167 } 4168 4169 // fold (srl (shl x, c), c) -> (and x, cst2) 4170 if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1 && 4171 N0.getValueSizeInBits() <= 64) { 4172 uint64_t ShAmt = N1C->getZExtValue()+64-N0.getValueSizeInBits(); 4173 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0), 4174 DAG.getConstant(~0ULL >> ShAmt, VT)); 4175 } 4176 4177 // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask) 4178 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) { 4179 // Shifting in all undef bits? 4180 EVT SmallVT = N0.getOperand(0).getValueType(); 4181 if (N1C->getZExtValue() >= SmallVT.getSizeInBits()) 4182 return DAG.getUNDEF(VT); 4183 4184 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) { 4185 uint64_t ShiftAmt = N1C->getZExtValue(); 4186 SDValue SmallShift = DAG.getNode(ISD::SRL, SDLoc(N0), SmallVT, 4187 N0.getOperand(0), 4188 DAG.getConstant(ShiftAmt, getShiftAmountTy(SmallVT))); 4189 AddToWorkList(SmallShift.getNode()); 4190 APInt Mask = APInt::getAllOnesValue(VT.getSizeInBits()).lshr(ShiftAmt); 4191 return DAG.getNode(ISD::AND, SDLoc(N), VT, 4192 DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, SmallShift), 4193 DAG.getConstant(Mask, VT)); 4194 } 4195 } 4196 4197 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign 4198 // bit, which is unmodified by sra. 4199 if (N1C && N1C->getZExtValue() + 1 == VT.getSizeInBits()) { 4200 if (N0.getOpcode() == ISD::SRA) 4201 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1); 4202 } 4203 4204 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit). 4205 if (N1C && N0.getOpcode() == ISD::CTLZ && 4206 N1C->getAPIntValue() == Log2_32(VT.getSizeInBits())) { 4207 APInt KnownZero, KnownOne; 4208 DAG.ComputeMaskedBits(N0.getOperand(0), KnownZero, KnownOne); 4209 4210 // If any of the input bits are KnownOne, then the input couldn't be all 4211 // zeros, thus the result of the srl will always be zero. 4212 if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT); 4213 4214 // If all of the bits input the to ctlz node are known to be zero, then 4215 // the result of the ctlz is "32" and the result of the shift is one. 4216 APInt UnknownBits = ~KnownZero; 4217 if (UnknownBits == 0) return DAG.getConstant(1, VT); 4218 4219 // Otherwise, check to see if there is exactly one bit input to the ctlz. 4220 if ((UnknownBits & (UnknownBits - 1)) == 0) { 4221 // Okay, we know that only that the single bit specified by UnknownBits 4222 // could be set on input to the CTLZ node. If this bit is set, the SRL 4223 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair 4224 // to an SRL/XOR pair, which is likely to simplify more. 4225 unsigned ShAmt = UnknownBits.countTrailingZeros(); 4226 SDValue Op = N0.getOperand(0); 4227 4228 if (ShAmt) { 4229 Op = DAG.getNode(ISD::SRL, SDLoc(N0), VT, Op, 4230 DAG.getConstant(ShAmt, getShiftAmountTy(Op.getValueType()))); 4231 AddToWorkList(Op.getNode()); 4232 } 4233 4234 return DAG.getNode(ISD::XOR, SDLoc(N), VT, 4235 Op, DAG.getConstant(1, VT)); 4236 } 4237 } 4238 4239 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))). 4240 if (N1.getOpcode() == ISD::TRUNCATE && 4241 N1.getOperand(0).getOpcode() == ISD::AND && 4242 N1.hasOneUse() && N1.getOperand(0).hasOneUse()) { 4243 SDValue N101 = N1.getOperand(0).getOperand(1); 4244 if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) { 4245 EVT TruncVT = N1.getValueType(); 4246 SDValue N100 = N1.getOperand(0).getOperand(0); 4247 APInt TruncC = N101C->getAPIntValue(); 4248 TruncC = TruncC.trunc(TruncVT.getSizeInBits()); 4249 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, 4250 DAG.getNode(ISD::AND, SDLoc(N), 4251 TruncVT, 4252 DAG.getNode(ISD::TRUNCATE, 4253 SDLoc(N), 4254 TruncVT, N100), 4255 DAG.getConstant(TruncC, TruncVT))); 4256 } 4257 } 4258 4259 // fold operands of srl based on knowledge that the low bits are not 4260 // demanded. 4261 if (N1C && SimplifyDemandedBits(SDValue(N, 0))) 4262 return SDValue(N, 0); 4263 4264 if (N1C) { 4265 SDValue NewSRL = visitShiftByConstant(N, N1C->getZExtValue()); 4266 if (NewSRL.getNode()) 4267 return NewSRL; 4268 } 4269 4270 // Attempt to convert a srl of a load into a narrower zero-extending load. 4271 SDValue NarrowLoad = ReduceLoadWidth(N); 4272 if (NarrowLoad.getNode()) 4273 return NarrowLoad; 4274 4275 // Here is a common situation. We want to optimize: 4276 // 4277 // %a = ... 4278 // %b = and i32 %a, 2 4279 // %c = srl i32 %b, 1 4280 // brcond i32 %c ... 4281 // 4282 // into 4283 // 4284 // %a = ... 4285 // %b = and %a, 2 4286 // %c = setcc eq %b, 0 4287 // brcond %c ... 4288 // 4289 // However when after the source operand of SRL is optimized into AND, the SRL 4290 // itself may not be optimized further. Look for it and add the BRCOND into 4291 // the worklist. 4292 if (N->hasOneUse()) { 4293 SDNode *Use = *N->use_begin(); 4294 if (Use->getOpcode() == ISD::BRCOND) 4295 AddToWorkList(Use); 4296 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) { 4297 // Also look pass the truncate. 4298 Use = *Use->use_begin(); 4299 if (Use->getOpcode() == ISD::BRCOND) 4300 AddToWorkList(Use); 4301 } 4302 } 4303 4304 return SDValue(); 4305 } 4306 4307 SDValue DAGCombiner::visitCTLZ(SDNode *N) { 4308 SDValue N0 = N->getOperand(0); 4309 EVT VT = N->getValueType(0); 4310 4311 // fold (ctlz c1) -> c2 4312 if (isa<ConstantSDNode>(N0)) 4313 return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0); 4314 return SDValue(); 4315 } 4316 4317 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) { 4318 SDValue N0 = N->getOperand(0); 4319 EVT VT = N->getValueType(0); 4320 4321 // fold (ctlz_zero_undef c1) -> c2 4322 if (isa<ConstantSDNode>(N0)) 4323 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0); 4324 return SDValue(); 4325 } 4326 4327 SDValue DAGCombiner::visitCTTZ(SDNode *N) { 4328 SDValue N0 = N->getOperand(0); 4329 EVT VT = N->getValueType(0); 4330 4331 // fold (cttz c1) -> c2 4332 if (isa<ConstantSDNode>(N0)) 4333 return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0); 4334 return SDValue(); 4335 } 4336 4337 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) { 4338 SDValue N0 = N->getOperand(0); 4339 EVT VT = N->getValueType(0); 4340 4341 // fold (cttz_zero_undef c1) -> c2 4342 if (isa<ConstantSDNode>(N0)) 4343 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0); 4344 return SDValue(); 4345 } 4346 4347 SDValue DAGCombiner::visitCTPOP(SDNode *N) { 4348 SDValue N0 = N->getOperand(0); 4349 EVT VT = N->getValueType(0); 4350 4351 // fold (ctpop c1) -> c2 4352 if (isa<ConstantSDNode>(N0)) 4353 return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0); 4354 return SDValue(); 4355 } 4356 4357 SDValue DAGCombiner::visitSELECT(SDNode *N) { 4358 SDValue N0 = N->getOperand(0); 4359 SDValue N1 = N->getOperand(1); 4360 SDValue N2 = N->getOperand(2); 4361 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 4362 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 4363 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2); 4364 EVT VT = N->getValueType(0); 4365 EVT VT0 = N0.getValueType(); 4366 4367 // fold (select C, X, X) -> X 4368 if (N1 == N2) 4369 return N1; 4370 // fold (select true, X, Y) -> X 4371 if (N0C && !N0C->isNullValue()) 4372 return N1; 4373 // fold (select false, X, Y) -> Y 4374 if (N0C && N0C->isNullValue()) 4375 return N2; 4376 // fold (select C, 1, X) -> (or C, X) 4377 if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1) 4378 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2); 4379 // fold (select C, 0, 1) -> (xor C, 1) 4380 if (VT.isInteger() && 4381 (VT0 == MVT::i1 || 4382 (VT0.isInteger() && 4383 TLI.getBooleanContents(false) == 4384 TargetLowering::ZeroOrOneBooleanContent)) && 4385 N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) { 4386 SDValue XORNode; 4387 if (VT == VT0) 4388 return DAG.getNode(ISD::XOR, SDLoc(N), VT0, 4389 N0, DAG.getConstant(1, VT0)); 4390 XORNode = DAG.getNode(ISD::XOR, SDLoc(N0), VT0, 4391 N0, DAG.getConstant(1, VT0)); 4392 AddToWorkList(XORNode.getNode()); 4393 if (VT.bitsGT(VT0)) 4394 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode); 4395 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode); 4396 } 4397 // fold (select C, 0, X) -> (and (not C), X) 4398 if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) { 4399 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT); 4400 AddToWorkList(NOTNode.getNode()); 4401 return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2); 4402 } 4403 // fold (select C, X, 1) -> (or (not C), X) 4404 if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) { 4405 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT); 4406 AddToWorkList(NOTNode.getNode()); 4407 return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1); 4408 } 4409 // fold (select C, X, 0) -> (and C, X) 4410 if (VT == MVT::i1 && N2C && N2C->isNullValue()) 4411 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1); 4412 // fold (select X, X, Y) -> (or X, Y) 4413 // fold (select X, 1, Y) -> (or X, Y) 4414 if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1))) 4415 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2); 4416 // fold (select X, Y, X) -> (and X, Y) 4417 // fold (select X, Y, 0) -> (and X, Y) 4418 if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0))) 4419 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1); 4420 4421 // If we can fold this based on the true/false value, do so. 4422 if (SimplifySelectOps(N, N1, N2)) 4423 return SDValue(N, 0); // Don't revisit N. 4424 4425 // fold selects based on a setcc into other things, such as min/max/abs 4426 if (N0.getOpcode() == ISD::SETCC) { 4427 // FIXME: 4428 // Check against MVT::Other for SELECT_CC, which is a workaround for targets 4429 // having to say they don't support SELECT_CC on every type the DAG knows 4430 // about, since there is no way to mark an opcode illegal at all value types 4431 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other) && 4432 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) 4433 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, 4434 N0.getOperand(0), N0.getOperand(1), 4435 N1, N2, N0.getOperand(2)); 4436 return SimplifySelect(SDLoc(N), N0, N1, N2); 4437 } 4438 4439 return SDValue(); 4440 } 4441 4442 static 4443 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) { 4444 SDLoc DL(N); 4445 EVT LoVT, HiVT; 4446 llvm::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0)); 4447 4448 // Split the inputs. 4449 SDValue Lo, Hi, LL, LH, RL, RH; 4450 llvm::tie(LL, LH) = DAG.SplitVectorOperand(N, 0); 4451 llvm::tie(RL, RH) = DAG.SplitVectorOperand(N, 1); 4452 4453 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2)); 4454 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2)); 4455 4456 return std::make_pair(Lo, Hi); 4457 } 4458 4459 SDValue DAGCombiner::visitVSELECT(SDNode *N) { 4460 SDValue N0 = N->getOperand(0); 4461 SDValue N1 = N->getOperand(1); 4462 SDValue N2 = N->getOperand(2); 4463 SDLoc DL(N); 4464 4465 // Canonicalize integer abs. 4466 // vselect (setg[te] X, 0), X, -X -> 4467 // vselect (setgt X, -1), X, -X -> 4468 // vselect (setl[te] X, 0), -X, X -> 4469 // Y = sra (X, size(X)-1); xor (add (X, Y), Y) 4470 if (N0.getOpcode() == ISD::SETCC) { 4471 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1); 4472 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get(); 4473 bool isAbs = false; 4474 bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode()); 4475 4476 if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) || 4477 (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) && 4478 N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1)) 4479 isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode()); 4480 else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) && 4481 N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1)) 4482 isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode()); 4483 4484 if (isAbs) { 4485 EVT VT = LHS.getValueType(); 4486 SDValue Shift = DAG.getNode( 4487 ISD::SRA, DL, VT, LHS, 4488 DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, VT)); 4489 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift); 4490 AddToWorkList(Shift.getNode()); 4491 AddToWorkList(Add.getNode()); 4492 return DAG.getNode(ISD::XOR, DL, VT, Add, Shift); 4493 } 4494 } 4495 4496 // If the VSELECT result requires splitting and the mask is provided by a 4497 // SETCC, then split both nodes and its operands before legalization. This 4498 // prevents the type legalizer from unrolling SETCC into scalar comparisons 4499 // and enables future optimizations (e.g. min/max pattern matching on X86). 4500 if (N0.getOpcode() == ISD::SETCC) { 4501 EVT VT = N->getValueType(0); 4502 4503 // Check if any splitting is required. 4504 if (TLI.getTypeAction(*DAG.getContext(), VT) != 4505 TargetLowering::TypeSplitVector) 4506 return SDValue(); 4507 4508 SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH; 4509 llvm::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG); 4510 llvm::tie(LL, LH) = DAG.SplitVectorOperand(N, 1); 4511 llvm::tie(RL, RH) = DAG.SplitVectorOperand(N, 2); 4512 4513 Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL); 4514 Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH); 4515 4516 // Add the new VSELECT nodes to the work list in case they need to be split 4517 // again. 4518 AddToWorkList(Lo.getNode()); 4519 AddToWorkList(Hi.getNode()); 4520 4521 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi); 4522 } 4523 4524 // Fold (vselect (build_vector all_ones), N1, N2) -> N1 4525 if (ISD::isBuildVectorAllOnes(N0.getNode())) 4526 return N1; 4527 // Fold (vselect (build_vector all_zeros), N1, N2) -> N2 4528 if (ISD::isBuildVectorAllZeros(N0.getNode())) 4529 return N2; 4530 4531 return SDValue(); 4532 } 4533 4534 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) { 4535 SDValue N0 = N->getOperand(0); 4536 SDValue N1 = N->getOperand(1); 4537 SDValue N2 = N->getOperand(2); 4538 SDValue N3 = N->getOperand(3); 4539 SDValue N4 = N->getOperand(4); 4540 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get(); 4541 4542 // fold select_cc lhs, rhs, x, x, cc -> x 4543 if (N2 == N3) 4544 return N2; 4545 4546 // Determine if the condition we're dealing with is constant 4547 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()), 4548 N0, N1, CC, SDLoc(N), false); 4549 if (SCC.getNode()) { 4550 AddToWorkList(SCC.getNode()); 4551 4552 if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) { 4553 if (!SCCC->isNullValue()) 4554 return N2; // cond always true -> true val 4555 else 4556 return N3; // cond always false -> false val 4557 } 4558 4559 // Fold to a simpler select_cc 4560 if (SCC.getOpcode() == ISD::SETCC) 4561 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(), 4562 SCC.getOperand(0), SCC.getOperand(1), N2, N3, 4563 SCC.getOperand(2)); 4564 } 4565 4566 // If we can fold this based on the true/false value, do so. 4567 if (SimplifySelectOps(N, N2, N3)) 4568 return SDValue(N, 0); // Don't revisit N. 4569 4570 // fold select_cc into other things, such as min/max/abs 4571 return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC); 4572 } 4573 4574 SDValue DAGCombiner::visitSETCC(SDNode *N) { 4575 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1), 4576 cast<CondCodeSDNode>(N->getOperand(2))->get(), 4577 SDLoc(N)); 4578 } 4579 4580 // tryToFoldExtendOfConstant - Try to fold a sext/zext/aext 4581 // dag node into a ConstantSDNode or a build_vector of constants. 4582 // This function is called by the DAGCombiner when visiting sext/zext/aext 4583 // dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND). 4584 // Vector extends are not folded if operations are legal; this is to 4585 // avoid introducing illegal build_vector dag nodes. 4586 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI, 4587 SelectionDAG &DAG, bool LegalTypes, 4588 bool LegalOperations) { 4589 unsigned Opcode = N->getOpcode(); 4590 SDValue N0 = N->getOperand(0); 4591 EVT VT = N->getValueType(0); 4592 4593 assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND || 4594 Opcode == ISD::ANY_EXTEND) && "Expected EXTEND dag node in input!"); 4595 4596 // fold (sext c1) -> c1 4597 // fold (zext c1) -> c1 4598 // fold (aext c1) -> c1 4599 if (isa<ConstantSDNode>(N0)) 4600 return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode(); 4601 4602 // fold (sext (build_vector AllConstants) -> (build_vector AllConstants) 4603 // fold (zext (build_vector AllConstants) -> (build_vector AllConstants) 4604 // fold (aext (build_vector AllConstants) -> (build_vector AllConstants) 4605 EVT SVT = VT.getScalarType(); 4606 if (!(VT.isVector() && 4607 (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) && 4608 ISD::isBuildVectorOfConstantSDNodes(N0.getNode()))) 4609 return 0; 4610 4611 // We can fold this node into a build_vector. 4612 unsigned VTBits = SVT.getSizeInBits(); 4613 unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits(); 4614 unsigned ShAmt = VTBits - EVTBits; 4615 SmallVector<SDValue, 8> Elts; 4616 unsigned NumElts = N0->getNumOperands(); 4617 SDLoc DL(N); 4618 4619 for (unsigned i=0; i != NumElts; ++i) { 4620 SDValue Op = N0->getOperand(i); 4621 if (Op->getOpcode() == ISD::UNDEF) { 4622 Elts.push_back(DAG.getUNDEF(SVT)); 4623 continue; 4624 } 4625 4626 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op); 4627 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue()); 4628 if (Opcode == ISD::SIGN_EXTEND) 4629 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(), 4630 SVT)); 4631 else 4632 Elts.push_back(DAG.getConstant(C.shl(ShAmt).lshr(ShAmt).getZExtValue(), 4633 SVT)); 4634 } 4635 4636 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, &Elts[0], NumElts).getNode(); 4637 } 4638 4639 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this: 4640 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))" 4641 // transformation. Returns true if extension are possible and the above 4642 // mentioned transformation is profitable. 4643 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0, 4644 unsigned ExtOpc, 4645 SmallVectorImpl<SDNode *> &ExtendNodes, 4646 const TargetLowering &TLI) { 4647 bool HasCopyToRegUses = false; 4648 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType()); 4649 for (SDNode::use_iterator UI = N0.getNode()->use_begin(), 4650 UE = N0.getNode()->use_end(); 4651 UI != UE; ++UI) { 4652 SDNode *User = *UI; 4653 if (User == N) 4654 continue; 4655 if (UI.getUse().getResNo() != N0.getResNo()) 4656 continue; 4657 // FIXME: Only extend SETCC N, N and SETCC N, c for now. 4658 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) { 4659 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get(); 4660 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC)) 4661 // Sign bits will be lost after a zext. 4662 return false; 4663 bool Add = false; 4664 for (unsigned i = 0; i != 2; ++i) { 4665 SDValue UseOp = User->getOperand(i); 4666 if (UseOp == N0) 4667 continue; 4668 if (!isa<ConstantSDNode>(UseOp)) 4669 return false; 4670 Add = true; 4671 } 4672 if (Add) 4673 ExtendNodes.push_back(User); 4674 continue; 4675 } 4676 // If truncates aren't free and there are users we can't 4677 // extend, it isn't worthwhile. 4678 if (!isTruncFree) 4679 return false; 4680 // Remember if this value is live-out. 4681 if (User->getOpcode() == ISD::CopyToReg) 4682 HasCopyToRegUses = true; 4683 } 4684 4685 if (HasCopyToRegUses) { 4686 bool BothLiveOut = false; 4687 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end(); 4688 UI != UE; ++UI) { 4689 SDUse &Use = UI.getUse(); 4690 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) { 4691 BothLiveOut = true; 4692 break; 4693 } 4694 } 4695 if (BothLiveOut) 4696 // Both unextended and extended values are live out. There had better be 4697 // a good reason for the transformation. 4698 return ExtendNodes.size(); 4699 } 4700 return true; 4701 } 4702 4703 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs, 4704 SDValue Trunc, SDValue ExtLoad, SDLoc DL, 4705 ISD::NodeType ExtType) { 4706 // Extend SetCC uses if necessary. 4707 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) { 4708 SDNode *SetCC = SetCCs[i]; 4709 SmallVector<SDValue, 4> Ops; 4710 4711 for (unsigned j = 0; j != 2; ++j) { 4712 SDValue SOp = SetCC->getOperand(j); 4713 if (SOp == Trunc) 4714 Ops.push_back(ExtLoad); 4715 else 4716 Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp)); 4717 } 4718 4719 Ops.push_back(SetCC->getOperand(2)); 4720 CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), 4721 &Ops[0], Ops.size())); 4722 } 4723 } 4724 4725 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) { 4726 SDValue N0 = N->getOperand(0); 4727 EVT VT = N->getValueType(0); 4728 4729 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes, 4730 LegalOperations)) 4731 return SDValue(Res, 0); 4732 4733 // fold (sext (sext x)) -> (sext x) 4734 // fold (sext (aext x)) -> (sext x) 4735 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) 4736 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, 4737 N0.getOperand(0)); 4738 4739 if (N0.getOpcode() == ISD::TRUNCATE) { 4740 // fold (sext (truncate (load x))) -> (sext (smaller load x)) 4741 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n))) 4742 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode()); 4743 if (NarrowLoad.getNode()) { 4744 SDNode* oye = N0.getNode()->getOperand(0).getNode(); 4745 if (NarrowLoad.getNode() != N0.getNode()) { 4746 CombineTo(N0.getNode(), NarrowLoad); 4747 // CombineTo deleted the truncate, if needed, but not what's under it. 4748 AddToWorkList(oye); 4749 } 4750 return SDValue(N, 0); // Return N so it doesn't get rechecked! 4751 } 4752 4753 // See if the value being truncated is already sign extended. If so, just 4754 // eliminate the trunc/sext pair. 4755 SDValue Op = N0.getOperand(0); 4756 unsigned OpBits = Op.getValueType().getScalarType().getSizeInBits(); 4757 unsigned MidBits = N0.getValueType().getScalarType().getSizeInBits(); 4758 unsigned DestBits = VT.getScalarType().getSizeInBits(); 4759 unsigned NumSignBits = DAG.ComputeNumSignBits(Op); 4760 4761 if (OpBits == DestBits) { 4762 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign 4763 // bits, it is already ready. 4764 if (NumSignBits > DestBits-MidBits) 4765 return Op; 4766 } else if (OpBits < DestBits) { 4767 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign 4768 // bits, just sext from i32. 4769 if (NumSignBits > OpBits-MidBits) 4770 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op); 4771 } else { 4772 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign 4773 // bits, just truncate to i32. 4774 if (NumSignBits > OpBits-MidBits) 4775 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op); 4776 } 4777 4778 // fold (sext (truncate x)) -> (sextinreg x). 4779 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, 4780 N0.getValueType())) { 4781 if (OpBits < DestBits) 4782 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op); 4783 else if (OpBits > DestBits) 4784 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op); 4785 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op, 4786 DAG.getValueType(N0.getValueType())); 4787 } 4788 } 4789 4790 // fold (sext (load x)) -> (sext (truncate (sextload x))) 4791 // None of the supported targets knows how to perform load and sign extend 4792 // on vectors in one instruction. We only perform this transformation on 4793 // scalars. 4794 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() && 4795 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) || 4796 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()))) { 4797 bool DoXform = true; 4798 SmallVector<SDNode*, 4> SetCCs; 4799 if (!N0.hasOneUse()) 4800 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI); 4801 if (DoXform) { 4802 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 4803 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT, 4804 LN0->getChain(), 4805 LN0->getBasePtr(), N0.getValueType(), 4806 LN0->getMemOperand()); 4807 CombineTo(N, ExtLoad); 4808 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 4809 N0.getValueType(), ExtLoad); 4810 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1)); 4811 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N), 4812 ISD::SIGN_EXTEND); 4813 return SDValue(N, 0); // Return N so it doesn't get rechecked! 4814 } 4815 } 4816 4817 // fold (sext (sextload x)) -> (sext (truncate (sextload x))) 4818 // fold (sext ( extload x)) -> (sext (truncate (sextload x))) 4819 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) && 4820 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) { 4821 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 4822 EVT MemVT = LN0->getMemoryVT(); 4823 if ((!LegalOperations && !LN0->isVolatile()) || 4824 TLI.isLoadExtLegal(ISD::SEXTLOAD, MemVT)) { 4825 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT, 4826 LN0->getChain(), 4827 LN0->getBasePtr(), MemVT, 4828 LN0->getMemOperand()); 4829 CombineTo(N, ExtLoad); 4830 CombineTo(N0.getNode(), 4831 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 4832 N0.getValueType(), ExtLoad), 4833 ExtLoad.getValue(1)); 4834 return SDValue(N, 0); // Return N so it doesn't get rechecked! 4835 } 4836 } 4837 4838 // fold (sext (and/or/xor (load x), cst)) -> 4839 // (and/or/xor (sextload x), (sext cst)) 4840 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR || 4841 N0.getOpcode() == ISD::XOR) && 4842 isa<LoadSDNode>(N0.getOperand(0)) && 4843 N0.getOperand(1).getOpcode() == ISD::Constant && 4844 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()) && 4845 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) { 4846 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0)); 4847 if (LN0->getExtensionType() != ISD::ZEXTLOAD) { 4848 bool DoXform = true; 4849 SmallVector<SDNode*, 4> SetCCs; 4850 if (!N0.hasOneUse()) 4851 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND, 4852 SetCCs, TLI); 4853 if (DoXform) { 4854 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT, 4855 LN0->getChain(), LN0->getBasePtr(), 4856 LN0->getMemoryVT(), 4857 LN0->getMemOperand()); 4858 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 4859 Mask = Mask.sext(VT.getSizeInBits()); 4860 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT, 4861 ExtLoad, DAG.getConstant(Mask, VT)); 4862 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, 4863 SDLoc(N0.getOperand(0)), 4864 N0.getOperand(0).getValueType(), ExtLoad); 4865 CombineTo(N, And); 4866 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1)); 4867 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N), 4868 ISD::SIGN_EXTEND); 4869 return SDValue(N, 0); // Return N so it doesn't get rechecked! 4870 } 4871 } 4872 } 4873 4874 if (N0.getOpcode() == ISD::SETCC) { 4875 // sext(setcc) -> sext_in_reg(vsetcc) for vectors. 4876 // Only do this before legalize for now. 4877 if (VT.isVector() && !LegalOperations && 4878 TLI.getBooleanContents(true) == 4879 TargetLowering::ZeroOrNegativeOneBooleanContent) { 4880 EVT N0VT = N0.getOperand(0).getValueType(); 4881 // On some architectures (such as SSE/NEON/etc) the SETCC result type is 4882 // of the same size as the compared operands. Only optimize sext(setcc()) 4883 // if this is the case. 4884 EVT SVT = getSetCCResultType(N0VT); 4885 4886 // We know that the # elements of the results is the same as the 4887 // # elements of the compare (and the # elements of the compare result 4888 // for that matter). Check to see that they are the same size. If so, 4889 // we know that the element size of the sext'd result matches the 4890 // element size of the compare operands. 4891 if (VT.getSizeInBits() == SVT.getSizeInBits()) 4892 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0), 4893 N0.getOperand(1), 4894 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 4895 4896 // If the desired elements are smaller or larger than the source 4897 // elements we can use a matching integer vector type and then 4898 // truncate/sign extend 4899 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger(); 4900 if (SVT == MatchingVectorType) { 4901 SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType, 4902 N0.getOperand(0), N0.getOperand(1), 4903 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 4904 return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT); 4905 } 4906 } 4907 4908 // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0) 4909 unsigned ElementWidth = VT.getScalarType().getSizeInBits(); 4910 SDValue NegOne = 4911 DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT); 4912 SDValue SCC = 4913 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1), 4914 NegOne, DAG.getConstant(0, VT), 4915 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true); 4916 if (SCC.getNode()) return SCC; 4917 4918 if (!VT.isVector()) { 4919 EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType()); 4920 if (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, SetCCVT)) { 4921 SDLoc DL(N); 4922 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get(); 4923 SDValue SetCC = DAG.getSetCC(DL, 4924 SetCCVT, 4925 N0.getOperand(0), N0.getOperand(1), CC); 4926 EVT SelectVT = getSetCCResultType(VT); 4927 return DAG.getSelect(DL, VT, 4928 DAG.getSExtOrTrunc(SetCC, DL, SelectVT), 4929 NegOne, DAG.getConstant(0, VT)); 4930 4931 } 4932 } 4933 } 4934 4935 // fold (sext x) -> (zext x) if the sign bit is known zero. 4936 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) && 4937 DAG.SignBitIsZero(N0)) 4938 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0); 4939 4940 return SDValue(); 4941 } 4942 4943 // isTruncateOf - If N is a truncate of some other value, return true, record 4944 // the value being truncated in Op and which of Op's bits are zero in KnownZero. 4945 // This function computes KnownZero to avoid a duplicated call to 4946 // ComputeMaskedBits in the caller. 4947 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op, 4948 APInt &KnownZero) { 4949 APInt KnownOne; 4950 if (N->getOpcode() == ISD::TRUNCATE) { 4951 Op = N->getOperand(0); 4952 DAG.ComputeMaskedBits(Op, KnownZero, KnownOne); 4953 return true; 4954 } 4955 4956 if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 || 4957 cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE) 4958 return false; 4959 4960 SDValue Op0 = N->getOperand(0); 4961 SDValue Op1 = N->getOperand(1); 4962 assert(Op0.getValueType() == Op1.getValueType()); 4963 4964 ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0); 4965 ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1); 4966 if (COp0 && COp0->isNullValue()) 4967 Op = Op1; 4968 else if (COp1 && COp1->isNullValue()) 4969 Op = Op0; 4970 else 4971 return false; 4972 4973 DAG.ComputeMaskedBits(Op, KnownZero, KnownOne); 4974 4975 if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue()) 4976 return false; 4977 4978 return true; 4979 } 4980 4981 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) { 4982 SDValue N0 = N->getOperand(0); 4983 EVT VT = N->getValueType(0); 4984 4985 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes, 4986 LegalOperations)) 4987 return SDValue(Res, 0); 4988 4989 // fold (zext (zext x)) -> (zext x) 4990 // fold (zext (aext x)) -> (zext x) 4991 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) 4992 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, 4993 N0.getOperand(0)); 4994 4995 // fold (zext (truncate x)) -> (zext x) or 4996 // (zext (truncate x)) -> (truncate x) 4997 // This is valid when the truncated bits of x are already zero. 4998 // FIXME: We should extend this to work for vectors too. 4999 SDValue Op; 5000 APInt KnownZero; 5001 if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) { 5002 APInt TruncatedBits = 5003 (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ? 5004 APInt(Op.getValueSizeInBits(), 0) : 5005 APInt::getBitsSet(Op.getValueSizeInBits(), 5006 N0.getValueSizeInBits(), 5007 std::min(Op.getValueSizeInBits(), 5008 VT.getSizeInBits())); 5009 if (TruncatedBits == (KnownZero & TruncatedBits)) { 5010 if (VT.bitsGT(Op.getValueType())) 5011 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op); 5012 if (VT.bitsLT(Op.getValueType())) 5013 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op); 5014 5015 return Op; 5016 } 5017 } 5018 5019 // fold (zext (truncate (load x))) -> (zext (smaller load x)) 5020 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n))) 5021 if (N0.getOpcode() == ISD::TRUNCATE) { 5022 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode()); 5023 if (NarrowLoad.getNode()) { 5024 SDNode* oye = N0.getNode()->getOperand(0).getNode(); 5025 if (NarrowLoad.getNode() != N0.getNode()) { 5026 CombineTo(N0.getNode(), NarrowLoad); 5027 // CombineTo deleted the truncate, if needed, but not what's under it. 5028 AddToWorkList(oye); 5029 } 5030 return SDValue(N, 0); // Return N so it doesn't get rechecked! 5031 } 5032 } 5033 5034 // fold (zext (truncate x)) -> (and x, mask) 5035 if (N0.getOpcode() == ISD::TRUNCATE && 5036 (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) { 5037 5038 // fold (zext (truncate (load x))) -> (zext (smaller load x)) 5039 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n))) 5040 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode()); 5041 if (NarrowLoad.getNode()) { 5042 SDNode* oye = N0.getNode()->getOperand(0).getNode(); 5043 if (NarrowLoad.getNode() != N0.getNode()) { 5044 CombineTo(N0.getNode(), NarrowLoad); 5045 // CombineTo deleted the truncate, if needed, but not what's under it. 5046 AddToWorkList(oye); 5047 } 5048 return SDValue(N, 0); // Return N so it doesn't get rechecked! 5049 } 5050 5051 SDValue Op = N0.getOperand(0); 5052 if (Op.getValueType().bitsLT(VT)) { 5053 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op); 5054 AddToWorkList(Op.getNode()); 5055 } else if (Op.getValueType().bitsGT(VT)) { 5056 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op); 5057 AddToWorkList(Op.getNode()); 5058 } 5059 return DAG.getZeroExtendInReg(Op, SDLoc(N), 5060 N0.getValueType().getScalarType()); 5061 } 5062 5063 // Fold (zext (and (trunc x), cst)) -> (and x, cst), 5064 // if either of the casts is not free. 5065 if (N0.getOpcode() == ISD::AND && 5066 N0.getOperand(0).getOpcode() == ISD::TRUNCATE && 5067 N0.getOperand(1).getOpcode() == ISD::Constant && 5068 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(), 5069 N0.getValueType()) || 5070 !TLI.isZExtFree(N0.getValueType(), VT))) { 5071 SDValue X = N0.getOperand(0).getOperand(0); 5072 if (X.getValueType().bitsLT(VT)) { 5073 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X); 5074 } else if (X.getValueType().bitsGT(VT)) { 5075 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X); 5076 } 5077 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 5078 Mask = Mask.zext(VT.getSizeInBits()); 5079 return DAG.getNode(ISD::AND, SDLoc(N), VT, 5080 X, DAG.getConstant(Mask, VT)); 5081 } 5082 5083 // fold (zext (load x)) -> (zext (truncate (zextload x))) 5084 // None of the supported targets knows how to perform load and vector_zext 5085 // on vectors in one instruction. We only perform this transformation on 5086 // scalars. 5087 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() && 5088 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) || 5089 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()))) { 5090 bool DoXform = true; 5091 SmallVector<SDNode*, 4> SetCCs; 5092 if (!N0.hasOneUse()) 5093 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI); 5094 if (DoXform) { 5095 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 5096 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT, 5097 LN0->getChain(), 5098 LN0->getBasePtr(), N0.getValueType(), 5099 LN0->getMemOperand()); 5100 CombineTo(N, ExtLoad); 5101 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 5102 N0.getValueType(), ExtLoad); 5103 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1)); 5104 5105 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N), 5106 ISD::ZERO_EXTEND); 5107 return SDValue(N, 0); // Return N so it doesn't get rechecked! 5108 } 5109 } 5110 5111 // fold (zext (and/or/xor (load x), cst)) -> 5112 // (and/or/xor (zextload x), (zext cst)) 5113 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR || 5114 N0.getOpcode() == ISD::XOR) && 5115 isa<LoadSDNode>(N0.getOperand(0)) && 5116 N0.getOperand(1).getOpcode() == ISD::Constant && 5117 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()) && 5118 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) { 5119 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0)); 5120 if (LN0->getExtensionType() != ISD::SEXTLOAD) { 5121 bool DoXform = true; 5122 SmallVector<SDNode*, 4> SetCCs; 5123 if (!N0.hasOneUse()) 5124 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND, 5125 SetCCs, TLI); 5126 if (DoXform) { 5127 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT, 5128 LN0->getChain(), LN0->getBasePtr(), 5129 LN0->getMemoryVT(), 5130 LN0->getMemOperand()); 5131 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 5132 Mask = Mask.zext(VT.getSizeInBits()); 5133 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT, 5134 ExtLoad, DAG.getConstant(Mask, VT)); 5135 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, 5136 SDLoc(N0.getOperand(0)), 5137 N0.getOperand(0).getValueType(), ExtLoad); 5138 CombineTo(N, And); 5139 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1)); 5140 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N), 5141 ISD::ZERO_EXTEND); 5142 return SDValue(N, 0); // Return N so it doesn't get rechecked! 5143 } 5144 } 5145 } 5146 5147 // fold (zext (zextload x)) -> (zext (truncate (zextload x))) 5148 // fold (zext ( extload x)) -> (zext (truncate (zextload x))) 5149 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) && 5150 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) { 5151 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 5152 EVT MemVT = LN0->getMemoryVT(); 5153 if ((!LegalOperations && !LN0->isVolatile()) || 5154 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT)) { 5155 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT, 5156 LN0->getChain(), 5157 LN0->getBasePtr(), MemVT, 5158 LN0->getMemOperand()); 5159 CombineTo(N, ExtLoad); 5160 CombineTo(N0.getNode(), 5161 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), 5162 ExtLoad), 5163 ExtLoad.getValue(1)); 5164 return SDValue(N, 0); // Return N so it doesn't get rechecked! 5165 } 5166 } 5167 5168 if (N0.getOpcode() == ISD::SETCC) { 5169 if (!LegalOperations && VT.isVector() && 5170 N0.getValueType().getVectorElementType() == MVT::i1) { 5171 EVT N0VT = N0.getOperand(0).getValueType(); 5172 if (getSetCCResultType(N0VT) == N0.getValueType()) 5173 return SDValue(); 5174 5175 // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors. 5176 // Only do this before legalize for now. 5177 EVT EltVT = VT.getVectorElementType(); 5178 SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(), 5179 DAG.getConstant(1, EltVT)); 5180 if (VT.getSizeInBits() == N0VT.getSizeInBits()) 5181 // We know that the # elements of the results is the same as the 5182 // # elements of the compare (and the # elements of the compare result 5183 // for that matter). Check to see that they are the same size. If so, 5184 // we know that the element size of the sext'd result matches the 5185 // element size of the compare operands. 5186 return DAG.getNode(ISD::AND, SDLoc(N), VT, 5187 DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0), 5188 N0.getOperand(1), 5189 cast<CondCodeSDNode>(N0.getOperand(2))->get()), 5190 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, 5191 &OneOps[0], OneOps.size())); 5192 5193 // If the desired elements are smaller or larger than the source 5194 // elements we can use a matching integer vector type and then 5195 // truncate/sign extend 5196 EVT MatchingElementType = 5197 EVT::getIntegerVT(*DAG.getContext(), 5198 N0VT.getScalarType().getSizeInBits()); 5199 EVT MatchingVectorType = 5200 EVT::getVectorVT(*DAG.getContext(), MatchingElementType, 5201 N0VT.getVectorNumElements()); 5202 SDValue VsetCC = 5203 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0), 5204 N0.getOperand(1), 5205 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 5206 return DAG.getNode(ISD::AND, SDLoc(N), VT, 5207 DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT), 5208 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, 5209 &OneOps[0], OneOps.size())); 5210 } 5211 5212 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc 5213 SDValue SCC = 5214 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1), 5215 DAG.getConstant(1, VT), DAG.getConstant(0, VT), 5216 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true); 5217 if (SCC.getNode()) return SCC; 5218 } 5219 5220 // (zext (shl (zext x), cst)) -> (shl (zext x), cst) 5221 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) && 5222 isa<ConstantSDNode>(N0.getOperand(1)) && 5223 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND && 5224 N0.hasOneUse()) { 5225 SDValue ShAmt = N0.getOperand(1); 5226 unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue(); 5227 if (N0.getOpcode() == ISD::SHL) { 5228 SDValue InnerZExt = N0.getOperand(0); 5229 // If the original shl may be shifting out bits, do not perform this 5230 // transformation. 5231 unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() - 5232 InnerZExt.getOperand(0).getValueType().getSizeInBits(); 5233 if (ShAmtVal > KnownZeroBits) 5234 return SDValue(); 5235 } 5236 5237 SDLoc DL(N); 5238 5239 // Ensure that the shift amount is wide enough for the shifted value. 5240 if (VT.getSizeInBits() >= 256) 5241 ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt); 5242 5243 return DAG.getNode(N0.getOpcode(), DL, VT, 5244 DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)), 5245 ShAmt); 5246 } 5247 5248 return SDValue(); 5249 } 5250 5251 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) { 5252 SDValue N0 = N->getOperand(0); 5253 EVT VT = N->getValueType(0); 5254 5255 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes, 5256 LegalOperations)) 5257 return SDValue(Res, 0); 5258 5259 // fold (aext (aext x)) -> (aext x) 5260 // fold (aext (zext x)) -> (zext x) 5261 // fold (aext (sext x)) -> (sext x) 5262 if (N0.getOpcode() == ISD::ANY_EXTEND || 5263 N0.getOpcode() == ISD::ZERO_EXTEND || 5264 N0.getOpcode() == ISD::SIGN_EXTEND) 5265 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0)); 5266 5267 // fold (aext (truncate (load x))) -> (aext (smaller load x)) 5268 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n))) 5269 if (N0.getOpcode() == ISD::TRUNCATE) { 5270 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode()); 5271 if (NarrowLoad.getNode()) { 5272 SDNode* oye = N0.getNode()->getOperand(0).getNode(); 5273 if (NarrowLoad.getNode() != N0.getNode()) { 5274 CombineTo(N0.getNode(), NarrowLoad); 5275 // CombineTo deleted the truncate, if needed, but not what's under it. 5276 AddToWorkList(oye); 5277 } 5278 return SDValue(N, 0); // Return N so it doesn't get rechecked! 5279 } 5280 } 5281 5282 // fold (aext (truncate x)) 5283 if (N0.getOpcode() == ISD::TRUNCATE) { 5284 SDValue TruncOp = N0.getOperand(0); 5285 if (TruncOp.getValueType() == VT) 5286 return TruncOp; // x iff x size == zext size. 5287 if (TruncOp.getValueType().bitsGT(VT)) 5288 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp); 5289 return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp); 5290 } 5291 5292 // Fold (aext (and (trunc x), cst)) -> (and x, cst) 5293 // if the trunc is not free. 5294 if (N0.getOpcode() == ISD::AND && 5295 N0.getOperand(0).getOpcode() == ISD::TRUNCATE && 5296 N0.getOperand(1).getOpcode() == ISD::Constant && 5297 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(), 5298 N0.getValueType())) { 5299 SDValue X = N0.getOperand(0).getOperand(0); 5300 if (X.getValueType().bitsLT(VT)) { 5301 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X); 5302 } else if (X.getValueType().bitsGT(VT)) { 5303 X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X); 5304 } 5305 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 5306 Mask = Mask.zext(VT.getSizeInBits()); 5307 return DAG.getNode(ISD::AND, SDLoc(N), VT, 5308 X, DAG.getConstant(Mask, VT)); 5309 } 5310 5311 // fold (aext (load x)) -> (aext (truncate (extload x))) 5312 // None of the supported targets knows how to perform load and any_ext 5313 // on vectors in one instruction. We only perform this transformation on 5314 // scalars. 5315 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() && 5316 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) || 5317 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) { 5318 bool DoXform = true; 5319 SmallVector<SDNode*, 4> SetCCs; 5320 if (!N0.hasOneUse()) 5321 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI); 5322 if (DoXform) { 5323 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 5324 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT, 5325 LN0->getChain(), 5326 LN0->getBasePtr(), N0.getValueType(), 5327 LN0->getMemOperand()); 5328 CombineTo(N, ExtLoad); 5329 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 5330 N0.getValueType(), ExtLoad); 5331 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1)); 5332 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N), 5333 ISD::ANY_EXTEND); 5334 return SDValue(N, 0); // Return N so it doesn't get rechecked! 5335 } 5336 } 5337 5338 // fold (aext (zextload x)) -> (aext (truncate (zextload x))) 5339 // fold (aext (sextload x)) -> (aext (truncate (sextload x))) 5340 // fold (aext ( extload x)) -> (aext (truncate (extload x))) 5341 if (N0.getOpcode() == ISD::LOAD && 5342 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 5343 N0.hasOneUse()) { 5344 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 5345 EVT MemVT = LN0->getMemoryVT(); 5346 SDValue ExtLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(N), 5347 VT, LN0->getChain(), LN0->getBasePtr(), 5348 MemVT, LN0->getMemOperand()); 5349 CombineTo(N, ExtLoad); 5350 CombineTo(N0.getNode(), 5351 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 5352 N0.getValueType(), ExtLoad), 5353 ExtLoad.getValue(1)); 5354 return SDValue(N, 0); // Return N so it doesn't get rechecked! 5355 } 5356 5357 if (N0.getOpcode() == ISD::SETCC) { 5358 // aext(setcc) -> sext_in_reg(vsetcc) for vectors. 5359 // Only do this before legalize for now. 5360 if (VT.isVector() && !LegalOperations) { 5361 EVT N0VT = N0.getOperand(0).getValueType(); 5362 // We know that the # elements of the results is the same as the 5363 // # elements of the compare (and the # elements of the compare result 5364 // for that matter). Check to see that they are the same size. If so, 5365 // we know that the element size of the sext'd result matches the 5366 // element size of the compare operands. 5367 if (VT.getSizeInBits() == N0VT.getSizeInBits()) 5368 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0), 5369 N0.getOperand(1), 5370 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 5371 // If the desired elements are smaller or larger than the source 5372 // elements we can use a matching integer vector type and then 5373 // truncate/sign extend 5374 else { 5375 EVT MatchingElementType = 5376 EVT::getIntegerVT(*DAG.getContext(), 5377 N0VT.getScalarType().getSizeInBits()); 5378 EVT MatchingVectorType = 5379 EVT::getVectorVT(*DAG.getContext(), MatchingElementType, 5380 N0VT.getVectorNumElements()); 5381 SDValue VsetCC = 5382 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0), 5383 N0.getOperand(1), 5384 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 5385 return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT); 5386 } 5387 } 5388 5389 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc 5390 SDValue SCC = 5391 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1), 5392 DAG.getConstant(1, VT), DAG.getConstant(0, VT), 5393 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true); 5394 if (SCC.getNode()) 5395 return SCC; 5396 } 5397 5398 return SDValue(); 5399 } 5400 5401 /// GetDemandedBits - See if the specified operand can be simplified with the 5402 /// knowledge that only the bits specified by Mask are used. If so, return the 5403 /// simpler operand, otherwise return a null SDValue. 5404 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) { 5405 switch (V.getOpcode()) { 5406 default: break; 5407 case ISD::Constant: { 5408 const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode()); 5409 assert(CV != 0 && "Const value should be ConstSDNode."); 5410 const APInt &CVal = CV->getAPIntValue(); 5411 APInt NewVal = CVal & Mask; 5412 if (NewVal != CVal) 5413 return DAG.getConstant(NewVal, V.getValueType()); 5414 break; 5415 } 5416 case ISD::OR: 5417 case ISD::XOR: 5418 // If the LHS or RHS don't contribute bits to the or, drop them. 5419 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask)) 5420 return V.getOperand(1); 5421 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask)) 5422 return V.getOperand(0); 5423 break; 5424 case ISD::SRL: 5425 // Only look at single-use SRLs. 5426 if (!V.getNode()->hasOneUse()) 5427 break; 5428 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) { 5429 // See if we can recursively simplify the LHS. 5430 unsigned Amt = RHSC->getZExtValue(); 5431 5432 // Watch out for shift count overflow though. 5433 if (Amt >= Mask.getBitWidth()) break; 5434 APInt NewMask = Mask << Amt; 5435 SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask); 5436 if (SimplifyLHS.getNode()) 5437 return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(), 5438 SimplifyLHS, V.getOperand(1)); 5439 } 5440 } 5441 return SDValue(); 5442 } 5443 5444 /// ReduceLoadWidth - If the result of a wider load is shifted to right of N 5445 /// bits and then truncated to a narrower type and where N is a multiple 5446 /// of number of bits of the narrower type, transform it to a narrower load 5447 /// from address + N / num of bits of new type. If the result is to be 5448 /// extended, also fold the extension to form a extending load. 5449 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) { 5450 unsigned Opc = N->getOpcode(); 5451 5452 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD; 5453 SDValue N0 = N->getOperand(0); 5454 EVT VT = N->getValueType(0); 5455 EVT ExtVT = VT; 5456 5457 // This transformation isn't valid for vector loads. 5458 if (VT.isVector()) 5459 return SDValue(); 5460 5461 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then 5462 // extended to VT. 5463 if (Opc == ISD::SIGN_EXTEND_INREG) { 5464 ExtType = ISD::SEXTLOAD; 5465 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT(); 5466 } else if (Opc == ISD::SRL) { 5467 // Another special-case: SRL is basically zero-extending a narrower value. 5468 ExtType = ISD::ZEXTLOAD; 5469 N0 = SDValue(N, 0); 5470 ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 5471 if (!N01) return SDValue(); 5472 ExtVT = EVT::getIntegerVT(*DAG.getContext(), 5473 VT.getSizeInBits() - N01->getZExtValue()); 5474 } 5475 if (LegalOperations && !TLI.isLoadExtLegal(ExtType, ExtVT)) 5476 return SDValue(); 5477 5478 unsigned EVTBits = ExtVT.getSizeInBits(); 5479 5480 // Do not generate loads of non-round integer types since these can 5481 // be expensive (and would be wrong if the type is not byte sized). 5482 if (!ExtVT.isRound()) 5483 return SDValue(); 5484 5485 unsigned ShAmt = 0; 5486 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) { 5487 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 5488 ShAmt = N01->getZExtValue(); 5489 // Is the shift amount a multiple of size of VT? 5490 if ((ShAmt & (EVTBits-1)) == 0) { 5491 N0 = N0.getOperand(0); 5492 // Is the load width a multiple of size of VT? 5493 if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0) 5494 return SDValue(); 5495 } 5496 5497 // At this point, we must have a load or else we can't do the transform. 5498 if (!isa<LoadSDNode>(N0)) return SDValue(); 5499 5500 // Because a SRL must be assumed to *need* to zero-extend the high bits 5501 // (as opposed to anyext the high bits), we can't combine the zextload 5502 // lowering of SRL and an sextload. 5503 if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD) 5504 return SDValue(); 5505 5506 // If the shift amount is larger than the input type then we're not 5507 // accessing any of the loaded bytes. If the load was a zextload/extload 5508 // then the result of the shift+trunc is zero/undef (handled elsewhere). 5509 if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits()) 5510 return SDValue(); 5511 } 5512 } 5513 5514 // If the load is shifted left (and the result isn't shifted back right), 5515 // we can fold the truncate through the shift. 5516 unsigned ShLeftAmt = 0; 5517 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() && 5518 ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) { 5519 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 5520 ShLeftAmt = N01->getZExtValue(); 5521 N0 = N0.getOperand(0); 5522 } 5523 } 5524 5525 // If we haven't found a load, we can't narrow it. Don't transform one with 5526 // multiple uses, this would require adding a new load. 5527 if (!isa<LoadSDNode>(N0) || !N0.hasOneUse()) 5528 return SDValue(); 5529 5530 // Don't change the width of a volatile load. 5531 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 5532 if (LN0->isVolatile()) 5533 return SDValue(); 5534 5535 // Verify that we are actually reducing a load width here. 5536 if (LN0->getMemoryVT().getSizeInBits() < EVTBits) 5537 return SDValue(); 5538 5539 // For the transform to be legal, the load must produce only two values 5540 // (the value loaded and the chain). Don't transform a pre-increment 5541 // load, for example, which produces an extra value. Otherwise the 5542 // transformation is not equivalent, and the downstream logic to replace 5543 // uses gets things wrong. 5544 if (LN0->getNumValues() > 2) 5545 return SDValue(); 5546 5547 // If the load that we're shrinking is an extload and we're not just 5548 // discarding the extension we can't simply shrink the load. Bail. 5549 // TODO: It would be possible to merge the extensions in some cases. 5550 if (LN0->getExtensionType() != ISD::NON_EXTLOAD && 5551 LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt) 5552 return SDValue(); 5553 5554 EVT PtrType = N0.getOperand(1).getValueType(); 5555 5556 if (PtrType == MVT::Untyped || PtrType.isExtended()) 5557 // It's not possible to generate a constant of extended or untyped type. 5558 return SDValue(); 5559 5560 // For big endian targets, we need to adjust the offset to the pointer to 5561 // load the correct bytes. 5562 if (TLI.isBigEndian()) { 5563 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits(); 5564 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits(); 5565 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt; 5566 } 5567 5568 uint64_t PtrOff = ShAmt / 8; 5569 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff); 5570 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0), 5571 PtrType, LN0->getBasePtr(), 5572 DAG.getConstant(PtrOff, PtrType)); 5573 AddToWorkList(NewPtr.getNode()); 5574 5575 SDValue Load; 5576 if (ExtType == ISD::NON_EXTLOAD) 5577 Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr, 5578 LN0->getPointerInfo().getWithOffset(PtrOff), 5579 LN0->isVolatile(), LN0->isNonTemporal(), 5580 LN0->isInvariant(), NewAlign, LN0->getTBAAInfo()); 5581 else 5582 Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr, 5583 LN0->getPointerInfo().getWithOffset(PtrOff), 5584 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(), 5585 NewAlign, LN0->getTBAAInfo()); 5586 5587 // Replace the old load's chain with the new load's chain. 5588 WorkListRemover DeadNodes(*this); 5589 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1)); 5590 5591 // Shift the result left, if we've swallowed a left shift. 5592 SDValue Result = Load; 5593 if (ShLeftAmt != 0) { 5594 EVT ShImmTy = getShiftAmountTy(Result.getValueType()); 5595 if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt)) 5596 ShImmTy = VT; 5597 // If the shift amount is as large as the result size (but, presumably, 5598 // no larger than the source) then the useful bits of the result are 5599 // zero; we can't simply return the shortened shift, because the result 5600 // of that operation is undefined. 5601 if (ShLeftAmt >= VT.getSizeInBits()) 5602 Result = DAG.getConstant(0, VT); 5603 else 5604 Result = DAG.getNode(ISD::SHL, SDLoc(N0), VT, 5605 Result, DAG.getConstant(ShLeftAmt, ShImmTy)); 5606 } 5607 5608 // Return the new loaded value. 5609 return Result; 5610 } 5611 5612 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) { 5613 SDValue N0 = N->getOperand(0); 5614 SDValue N1 = N->getOperand(1); 5615 EVT VT = N->getValueType(0); 5616 EVT EVT = cast<VTSDNode>(N1)->getVT(); 5617 unsigned VTBits = VT.getScalarType().getSizeInBits(); 5618 unsigned EVTBits = EVT.getScalarType().getSizeInBits(); 5619 5620 // fold (sext_in_reg c1) -> c1 5621 if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF) 5622 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1); 5623 5624 // If the input is already sign extended, just drop the extension. 5625 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1) 5626 return N0; 5627 5628 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2 5629 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG && 5630 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT())) 5631 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, 5632 N0.getOperand(0), N1); 5633 5634 // fold (sext_in_reg (sext x)) -> (sext x) 5635 // fold (sext_in_reg (aext x)) -> (sext x) 5636 // if x is small enough. 5637 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) { 5638 SDValue N00 = N0.getOperand(0); 5639 if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits && 5640 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT))) 5641 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1); 5642 } 5643 5644 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero. 5645 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits))) 5646 return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT); 5647 5648 // fold operands of sext_in_reg based on knowledge that the top bits are not 5649 // demanded. 5650 if (SimplifyDemandedBits(SDValue(N, 0))) 5651 return SDValue(N, 0); 5652 5653 // fold (sext_in_reg (load x)) -> (smaller sextload x) 5654 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits)) 5655 SDValue NarrowLoad = ReduceLoadWidth(N); 5656 if (NarrowLoad.getNode()) 5657 return NarrowLoad; 5658 5659 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24) 5660 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible. 5661 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above. 5662 if (N0.getOpcode() == ISD::SRL) { 5663 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1))) 5664 if (ShAmt->getZExtValue()+EVTBits <= VTBits) { 5665 // We can turn this into an SRA iff the input to the SRL is already sign 5666 // extended enough. 5667 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0)); 5668 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits) 5669 return DAG.getNode(ISD::SRA, SDLoc(N), VT, 5670 N0.getOperand(0), N0.getOperand(1)); 5671 } 5672 } 5673 5674 // fold (sext_inreg (extload x)) -> (sextload x) 5675 if (ISD::isEXTLoad(N0.getNode()) && 5676 ISD::isUNINDEXEDLoad(N0.getNode()) && 5677 EVT == cast<LoadSDNode>(N0)->getMemoryVT() && 5678 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) || 5679 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) { 5680 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 5681 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT, 5682 LN0->getChain(), 5683 LN0->getBasePtr(), EVT, 5684 LN0->getMemOperand()); 5685 CombineTo(N, ExtLoad); 5686 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 5687 AddToWorkList(ExtLoad.getNode()); 5688 return SDValue(N, 0); // Return N so it doesn't get rechecked! 5689 } 5690 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use 5691 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 5692 N0.hasOneUse() && 5693 EVT == cast<LoadSDNode>(N0)->getMemoryVT() && 5694 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) || 5695 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) { 5696 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 5697 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT, 5698 LN0->getChain(), 5699 LN0->getBasePtr(), EVT, 5700 LN0->getMemOperand()); 5701 CombineTo(N, ExtLoad); 5702 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 5703 return SDValue(N, 0); // Return N so it doesn't get rechecked! 5704 } 5705 5706 // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16)) 5707 if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) { 5708 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0), 5709 N0.getOperand(1), false); 5710 if (BSwap.getNode() != 0) 5711 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, 5712 BSwap, N1); 5713 } 5714 5715 // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs 5716 // into a build_vector. 5717 if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) { 5718 SmallVector<SDValue, 8> Elts; 5719 unsigned NumElts = N0->getNumOperands(); 5720 unsigned ShAmt = VTBits - EVTBits; 5721 5722 for (unsigned i = 0; i != NumElts; ++i) { 5723 SDValue Op = N0->getOperand(i); 5724 if (Op->getOpcode() == ISD::UNDEF) { 5725 Elts.push_back(Op); 5726 continue; 5727 } 5728 5729 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op); 5730 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue()); 5731 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(), 5732 Op.getValueType())); 5733 } 5734 5735 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, &Elts[0], NumElts); 5736 } 5737 5738 return SDValue(); 5739 } 5740 5741 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) { 5742 SDValue N0 = N->getOperand(0); 5743 EVT VT = N->getValueType(0); 5744 bool isLE = TLI.isLittleEndian(); 5745 5746 // noop truncate 5747 if (N0.getValueType() == N->getValueType(0)) 5748 return N0; 5749 // fold (truncate c1) -> c1 5750 if (isa<ConstantSDNode>(N0)) 5751 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0); 5752 // fold (truncate (truncate x)) -> (truncate x) 5753 if (N0.getOpcode() == ISD::TRUNCATE) 5754 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0)); 5755 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x 5756 if (N0.getOpcode() == ISD::ZERO_EXTEND || 5757 N0.getOpcode() == ISD::SIGN_EXTEND || 5758 N0.getOpcode() == ISD::ANY_EXTEND) { 5759 if (N0.getOperand(0).getValueType().bitsLT(VT)) 5760 // if the source is smaller than the dest, we still need an extend 5761 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, 5762 N0.getOperand(0)); 5763 if (N0.getOperand(0).getValueType().bitsGT(VT)) 5764 // if the source is larger than the dest, than we just need the truncate 5765 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0)); 5766 // if the source and dest are the same type, we can drop both the extend 5767 // and the truncate. 5768 return N0.getOperand(0); 5769 } 5770 5771 // Fold extract-and-trunc into a narrow extract. For example: 5772 // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1) 5773 // i32 y = TRUNCATE(i64 x) 5774 // -- becomes -- 5775 // v16i8 b = BITCAST (v2i64 val) 5776 // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8) 5777 // 5778 // Note: We only run this optimization after type legalization (which often 5779 // creates this pattern) and before operation legalization after which 5780 // we need to be more careful about the vector instructions that we generate. 5781 if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT && 5782 LegalTypes && !LegalOperations && N0->hasOneUse()) { 5783 5784 EVT VecTy = N0.getOperand(0).getValueType(); 5785 EVT ExTy = N0.getValueType(); 5786 EVT TrTy = N->getValueType(0); 5787 5788 unsigned NumElem = VecTy.getVectorNumElements(); 5789 unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits(); 5790 5791 EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem); 5792 assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size"); 5793 5794 SDValue EltNo = N0->getOperand(1); 5795 if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) { 5796 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue(); 5797 EVT IndexTy = TLI.getVectorIdxTy(); 5798 int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1)); 5799 5800 SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N), 5801 NVT, N0.getOperand(0)); 5802 5803 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, 5804 SDLoc(N), TrTy, V, 5805 DAG.getConstant(Index, IndexTy)); 5806 } 5807 } 5808 5809 // Fold a series of buildvector, bitcast, and truncate if possible. 5810 // For example fold 5811 // (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to 5812 // (2xi32 (buildvector x, y)). 5813 if (Level == AfterLegalizeVectorOps && VT.isVector() && 5814 N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() && 5815 N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR && 5816 N0.getOperand(0).hasOneUse()) { 5817 5818 SDValue BuildVect = N0.getOperand(0); 5819 EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType(); 5820 EVT TruncVecEltTy = VT.getVectorElementType(); 5821 5822 // Check that the element types match. 5823 if (BuildVectEltTy == TruncVecEltTy) { 5824 // Now we only need to compute the offset of the truncated elements. 5825 unsigned BuildVecNumElts = BuildVect.getNumOperands(); 5826 unsigned TruncVecNumElts = VT.getVectorNumElements(); 5827 unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts; 5828 5829 assert((BuildVecNumElts % TruncVecNumElts) == 0 && 5830 "Invalid number of elements"); 5831 5832 SmallVector<SDValue, 8> Opnds; 5833 for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset) 5834 Opnds.push_back(BuildVect.getOperand(i)); 5835 5836 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, &Opnds[0], 5837 Opnds.size()); 5838 } 5839 } 5840 5841 // See if we can simplify the input to this truncate through knowledge that 5842 // only the low bits are being used. 5843 // For example "trunc (or (shl x, 8), y)" // -> trunc y 5844 // Currently we only perform this optimization on scalars because vectors 5845 // may have different active low bits. 5846 if (!VT.isVector()) { 5847 SDValue Shorter = 5848 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(), 5849 VT.getSizeInBits())); 5850 if (Shorter.getNode()) 5851 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter); 5852 } 5853 // fold (truncate (load x)) -> (smaller load x) 5854 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits)) 5855 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) { 5856 SDValue Reduced = ReduceLoadWidth(N); 5857 if (Reduced.getNode()) 5858 return Reduced; 5859 // Handle the case where the load remains an extending load even 5860 // after truncation. 5861 if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) { 5862 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 5863 if (!LN0->isVolatile() && 5864 LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) { 5865 SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0), 5866 VT, LN0->getChain(), LN0->getBasePtr(), 5867 LN0->getMemoryVT(), 5868 LN0->getMemOperand()); 5869 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1)); 5870 return NewLoad; 5871 } 5872 } 5873 } 5874 // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)), 5875 // where ... are all 'undef'. 5876 if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) { 5877 SmallVector<EVT, 8> VTs; 5878 SDValue V; 5879 unsigned Idx = 0; 5880 unsigned NumDefs = 0; 5881 5882 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) { 5883 SDValue X = N0.getOperand(i); 5884 if (X.getOpcode() != ISD::UNDEF) { 5885 V = X; 5886 Idx = i; 5887 NumDefs++; 5888 } 5889 // Stop if more than one members are non-undef. 5890 if (NumDefs > 1) 5891 break; 5892 VTs.push_back(EVT::getVectorVT(*DAG.getContext(), 5893 VT.getVectorElementType(), 5894 X.getValueType().getVectorNumElements())); 5895 } 5896 5897 if (NumDefs == 0) 5898 return DAG.getUNDEF(VT); 5899 5900 if (NumDefs == 1) { 5901 assert(V.getNode() && "The single defined operand is empty!"); 5902 SmallVector<SDValue, 8> Opnds; 5903 for (unsigned i = 0, e = VTs.size(); i != e; ++i) { 5904 if (i != Idx) { 5905 Opnds.push_back(DAG.getUNDEF(VTs[i])); 5906 continue; 5907 } 5908 SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V); 5909 AddToWorkList(NV.getNode()); 5910 Opnds.push_back(NV); 5911 } 5912 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, 5913 &Opnds[0], Opnds.size()); 5914 } 5915 } 5916 5917 // Simplify the operands using demanded-bits information. 5918 if (!VT.isVector() && 5919 SimplifyDemandedBits(SDValue(N, 0))) 5920 return SDValue(N, 0); 5921 5922 return SDValue(); 5923 } 5924 5925 static SDNode *getBuildPairElt(SDNode *N, unsigned i) { 5926 SDValue Elt = N->getOperand(i); 5927 if (Elt.getOpcode() != ISD::MERGE_VALUES) 5928 return Elt.getNode(); 5929 return Elt.getOperand(Elt.getResNo()).getNode(); 5930 } 5931 5932 /// CombineConsecutiveLoads - build_pair (load, load) -> load 5933 /// if load locations are consecutive. 5934 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) { 5935 assert(N->getOpcode() == ISD::BUILD_PAIR); 5936 5937 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0)); 5938 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1)); 5939 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() || 5940 LD1->getPointerInfo().getAddrSpace() != 5941 LD2->getPointerInfo().getAddrSpace()) 5942 return SDValue(); 5943 EVT LD1VT = LD1->getValueType(0); 5944 5945 if (ISD::isNON_EXTLoad(LD2) && 5946 LD2->hasOneUse() && 5947 // If both are volatile this would reduce the number of volatile loads. 5948 // If one is volatile it might be ok, but play conservative and bail out. 5949 !LD1->isVolatile() && 5950 !LD2->isVolatile() && 5951 DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) { 5952 unsigned Align = LD1->getAlignment(); 5953 unsigned NewAlign = TLI.getDataLayout()-> 5954 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext())); 5955 5956 if (NewAlign <= Align && 5957 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT))) 5958 return DAG.getLoad(VT, SDLoc(N), LD1->getChain(), 5959 LD1->getBasePtr(), LD1->getPointerInfo(), 5960 false, false, false, Align); 5961 } 5962 5963 return SDValue(); 5964 } 5965 5966 SDValue DAGCombiner::visitBITCAST(SDNode *N) { 5967 SDValue N0 = N->getOperand(0); 5968 EVT VT = N->getValueType(0); 5969 5970 // If the input is a BUILD_VECTOR with all constant elements, fold this now. 5971 // Only do this before legalize, since afterward the target may be depending 5972 // on the bitconvert. 5973 // First check to see if this is all constant. 5974 if (!LegalTypes && 5975 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() && 5976 VT.isVector()) { 5977 bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant(); 5978 5979 EVT DestEltVT = N->getValueType(0).getVectorElementType(); 5980 assert(!DestEltVT.isVector() && 5981 "Element type of vector ValueType must not be vector!"); 5982 if (isSimple) 5983 return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT); 5984 } 5985 5986 // If the input is a constant, let getNode fold it. 5987 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) { 5988 SDValue Res = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0); 5989 if (Res.getNode() != N) { 5990 if (!LegalOperations || 5991 TLI.isOperationLegal(Res.getNode()->getOpcode(), VT)) 5992 return Res; 5993 5994 // Folding it resulted in an illegal node, and it's too late to 5995 // do that. Clean up the old node and forego the transformation. 5996 // Ideally this won't happen very often, because instcombine 5997 // and the earlier dagcombine runs (where illegal nodes are 5998 // permitted) should have folded most of them already. 5999 DAG.DeleteNode(Res.getNode()); 6000 } 6001 } 6002 6003 // (conv (conv x, t1), t2) -> (conv x, t2) 6004 if (N0.getOpcode() == ISD::BITCAST) 6005 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, 6006 N0.getOperand(0)); 6007 6008 // fold (conv (load x)) -> (load (conv*)x) 6009 // If the resultant load doesn't need a higher alignment than the original! 6010 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() && 6011 // Do not change the width of a volatile load. 6012 !cast<LoadSDNode>(N0)->isVolatile() && 6013 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) && 6014 TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) { 6015 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6016 unsigned Align = TLI.getDataLayout()-> 6017 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext())); 6018 unsigned OrigAlign = LN0->getAlignment(); 6019 6020 if (Align <= OrigAlign) { 6021 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(), 6022 LN0->getBasePtr(), LN0->getPointerInfo(), 6023 LN0->isVolatile(), LN0->isNonTemporal(), 6024 LN0->isInvariant(), OrigAlign, 6025 LN0->getTBAAInfo()); 6026 AddToWorkList(N); 6027 CombineTo(N0.getNode(), 6028 DAG.getNode(ISD::BITCAST, SDLoc(N0), 6029 N0.getValueType(), Load), 6030 Load.getValue(1)); 6031 return Load; 6032 } 6033 } 6034 6035 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit) 6036 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit)) 6037 // This often reduces constant pool loads. 6038 if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) || 6039 (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) && 6040 N0.getNode()->hasOneUse() && VT.isInteger() && 6041 !VT.isVector() && !N0.getValueType().isVector()) { 6042 SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT, 6043 N0.getOperand(0)); 6044 AddToWorkList(NewConv.getNode()); 6045 6046 APInt SignBit = APInt::getSignBit(VT.getSizeInBits()); 6047 if (N0.getOpcode() == ISD::FNEG) 6048 return DAG.getNode(ISD::XOR, SDLoc(N), VT, 6049 NewConv, DAG.getConstant(SignBit, VT)); 6050 assert(N0.getOpcode() == ISD::FABS); 6051 return DAG.getNode(ISD::AND, SDLoc(N), VT, 6052 NewConv, DAG.getConstant(~SignBit, VT)); 6053 } 6054 6055 // fold (bitconvert (fcopysign cst, x)) -> 6056 // (or (and (bitconvert x), sign), (and cst, (not sign))) 6057 // Note that we don't handle (copysign x, cst) because this can always be 6058 // folded to an fneg or fabs. 6059 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() && 6060 isa<ConstantFPSDNode>(N0.getOperand(0)) && 6061 VT.isInteger() && !VT.isVector()) { 6062 unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits(); 6063 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth); 6064 if (isTypeLegal(IntXVT)) { 6065 SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0), 6066 IntXVT, N0.getOperand(1)); 6067 AddToWorkList(X.getNode()); 6068 6069 // If X has a different width than the result/lhs, sext it or truncate it. 6070 unsigned VTWidth = VT.getSizeInBits(); 6071 if (OrigXWidth < VTWidth) { 6072 X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X); 6073 AddToWorkList(X.getNode()); 6074 } else if (OrigXWidth > VTWidth) { 6075 // To get the sign bit in the right place, we have to shift it right 6076 // before truncating. 6077 X = DAG.getNode(ISD::SRL, SDLoc(X), 6078 X.getValueType(), X, 6079 DAG.getConstant(OrigXWidth-VTWidth, X.getValueType())); 6080 AddToWorkList(X.getNode()); 6081 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X); 6082 AddToWorkList(X.getNode()); 6083 } 6084 6085 APInt SignBit = APInt::getSignBit(VT.getSizeInBits()); 6086 X = DAG.getNode(ISD::AND, SDLoc(X), VT, 6087 X, DAG.getConstant(SignBit, VT)); 6088 AddToWorkList(X.getNode()); 6089 6090 SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0), 6091 VT, N0.getOperand(0)); 6092 Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT, 6093 Cst, DAG.getConstant(~SignBit, VT)); 6094 AddToWorkList(Cst.getNode()); 6095 6096 return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst); 6097 } 6098 } 6099 6100 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive. 6101 if (N0.getOpcode() == ISD::BUILD_PAIR) { 6102 SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT); 6103 if (CombineLD.getNode()) 6104 return CombineLD; 6105 } 6106 6107 return SDValue(); 6108 } 6109 6110 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) { 6111 EVT VT = N->getValueType(0); 6112 return CombineConsecutiveLoads(N, VT); 6113 } 6114 6115 /// ConstantFoldBITCASTofBUILD_VECTOR - We know that BV is a build_vector 6116 /// node with Constant, ConstantFP or Undef operands. DstEltVT indicates the 6117 /// destination element value type. 6118 SDValue DAGCombiner:: 6119 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) { 6120 EVT SrcEltVT = BV->getValueType(0).getVectorElementType(); 6121 6122 // If this is already the right type, we're done. 6123 if (SrcEltVT == DstEltVT) return SDValue(BV, 0); 6124 6125 unsigned SrcBitSize = SrcEltVT.getSizeInBits(); 6126 unsigned DstBitSize = DstEltVT.getSizeInBits(); 6127 6128 // If this is a conversion of N elements of one type to N elements of another 6129 // type, convert each element. This handles FP<->INT cases. 6130 if (SrcBitSize == DstBitSize) { 6131 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, 6132 BV->getValueType(0).getVectorNumElements()); 6133 6134 // Due to the FP element handling below calling this routine recursively, 6135 // we can end up with a scalar-to-vector node here. 6136 if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR) 6137 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT, 6138 DAG.getNode(ISD::BITCAST, SDLoc(BV), 6139 DstEltVT, BV->getOperand(0))); 6140 6141 SmallVector<SDValue, 8> Ops; 6142 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) { 6143 SDValue Op = BV->getOperand(i); 6144 // If the vector element type is not legal, the BUILD_VECTOR operands 6145 // are promoted and implicitly truncated. Make that explicit here. 6146 if (Op.getValueType() != SrcEltVT) 6147 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op); 6148 Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV), 6149 DstEltVT, Op)); 6150 AddToWorkList(Ops.back().getNode()); 6151 } 6152 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, 6153 &Ops[0], Ops.size()); 6154 } 6155 6156 // Otherwise, we're growing or shrinking the elements. To avoid having to 6157 // handle annoying details of growing/shrinking FP values, we convert them to 6158 // int first. 6159 if (SrcEltVT.isFloatingPoint()) { 6160 // Convert the input float vector to a int vector where the elements are the 6161 // same sizes. 6162 assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!"); 6163 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits()); 6164 BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode(); 6165 SrcEltVT = IntVT; 6166 } 6167 6168 // Now we know the input is an integer vector. If the output is a FP type, 6169 // convert to integer first, then to FP of the right size. 6170 if (DstEltVT.isFloatingPoint()) { 6171 assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!"); 6172 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits()); 6173 SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode(); 6174 6175 // Next, convert to FP elements of the same size. 6176 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT); 6177 } 6178 6179 // Okay, we know the src/dst types are both integers of differing types. 6180 // Handling growing first. 6181 assert(SrcEltVT.isInteger() && DstEltVT.isInteger()); 6182 if (SrcBitSize < DstBitSize) { 6183 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize; 6184 6185 SmallVector<SDValue, 8> Ops; 6186 for (unsigned i = 0, e = BV->getNumOperands(); i != e; 6187 i += NumInputsPerOutput) { 6188 bool isLE = TLI.isLittleEndian(); 6189 APInt NewBits = APInt(DstBitSize, 0); 6190 bool EltIsUndef = true; 6191 for (unsigned j = 0; j != NumInputsPerOutput; ++j) { 6192 // Shift the previously computed bits over. 6193 NewBits <<= SrcBitSize; 6194 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j)); 6195 if (Op.getOpcode() == ISD::UNDEF) continue; 6196 EltIsUndef = false; 6197 6198 NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue(). 6199 zextOrTrunc(SrcBitSize).zext(DstBitSize); 6200 } 6201 6202 if (EltIsUndef) 6203 Ops.push_back(DAG.getUNDEF(DstEltVT)); 6204 else 6205 Ops.push_back(DAG.getConstant(NewBits, DstEltVT)); 6206 } 6207 6208 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size()); 6209 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, 6210 &Ops[0], Ops.size()); 6211 } 6212 6213 // Finally, this must be the case where we are shrinking elements: each input 6214 // turns into multiple outputs. 6215 bool isS2V = ISD::isScalarToVector(BV); 6216 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize; 6217 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, 6218 NumOutputsPerInput*BV->getNumOperands()); 6219 SmallVector<SDValue, 8> Ops; 6220 6221 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) { 6222 if (BV->getOperand(i).getOpcode() == ISD::UNDEF) { 6223 for (unsigned j = 0; j != NumOutputsPerInput; ++j) 6224 Ops.push_back(DAG.getUNDEF(DstEltVT)); 6225 continue; 6226 } 6227 6228 APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))-> 6229 getAPIntValue().zextOrTrunc(SrcBitSize); 6230 6231 for (unsigned j = 0; j != NumOutputsPerInput; ++j) { 6232 APInt ThisVal = OpVal.trunc(DstBitSize); 6233 Ops.push_back(DAG.getConstant(ThisVal, DstEltVT)); 6234 if (isS2V && i == 0 && j == 0 && ThisVal.zext(SrcBitSize) == OpVal) 6235 // Simply turn this into a SCALAR_TO_VECTOR of the new type. 6236 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT, 6237 Ops[0]); 6238 OpVal = OpVal.lshr(DstBitSize); 6239 } 6240 6241 // For big endian targets, swap the order of the pieces of each element. 6242 if (TLI.isBigEndian()) 6243 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end()); 6244 } 6245 6246 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, 6247 &Ops[0], Ops.size()); 6248 } 6249 6250 SDValue DAGCombiner::visitFADD(SDNode *N) { 6251 SDValue N0 = N->getOperand(0); 6252 SDValue N1 = N->getOperand(1); 6253 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 6254 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 6255 EVT VT = N->getValueType(0); 6256 6257 // fold vector ops 6258 if (VT.isVector()) { 6259 SDValue FoldedVOp = SimplifyVBinOp(N); 6260 if (FoldedVOp.getNode()) return FoldedVOp; 6261 } 6262 6263 // fold (fadd c1, c2) -> c1 + c2 6264 if (N0CFP && N1CFP) 6265 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N1); 6266 // canonicalize constant to RHS 6267 if (N0CFP && !N1CFP) 6268 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N0); 6269 // fold (fadd A, 0) -> A 6270 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP && 6271 N1CFP->getValueAPF().isZero()) 6272 return N0; 6273 // fold (fadd A, (fneg B)) -> (fsub A, B) 6274 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) && 6275 isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options) == 2) 6276 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0, 6277 GetNegatedExpression(N1, DAG, LegalOperations)); 6278 // fold (fadd (fneg A), B) -> (fsub B, A) 6279 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) && 6280 isNegatibleForFree(N0, LegalOperations, TLI, &DAG.getTarget().Options) == 2) 6281 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N1, 6282 GetNegatedExpression(N0, DAG, LegalOperations)); 6283 6284 // If allowed, fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2)) 6285 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP && 6286 N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() && 6287 isa<ConstantFPSDNode>(N0.getOperand(1))) 6288 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0.getOperand(0), 6289 DAG.getNode(ISD::FADD, SDLoc(N), VT, 6290 N0.getOperand(1), N1)); 6291 6292 // No FP constant should be created after legalization as Instruction 6293 // Selection pass has hard time in dealing with FP constant. 6294 // 6295 // We don't need test this condition for transformation like following, as 6296 // the DAG being transformed implies it is legal to take FP constant as 6297 // operand. 6298 // 6299 // (fadd (fmul c, x), x) -> (fmul c+1, x) 6300 // 6301 bool AllowNewFpConst = (Level < AfterLegalizeDAG); 6302 6303 // If allow, fold (fadd (fneg x), x) -> 0.0 6304 if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath && 6305 N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1) 6306 return DAG.getConstantFP(0.0, VT); 6307 6308 // If allow, fold (fadd x, (fneg x)) -> 0.0 6309 if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath && 6310 N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0) 6311 return DAG.getConstantFP(0.0, VT); 6312 6313 // In unsafe math mode, we can fold chains of FADD's of the same value 6314 // into multiplications. This transform is not safe in general because 6315 // we are reducing the number of rounding steps. 6316 if (DAG.getTarget().Options.UnsafeFPMath && 6317 TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && 6318 !N0CFP && !N1CFP) { 6319 if (N0.getOpcode() == ISD::FMUL) { 6320 ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0)); 6321 ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1)); 6322 6323 // (fadd (fmul c, x), x) -> (fmul x, c+1) 6324 if (CFP00 && !CFP01 && N0.getOperand(1) == N1) { 6325 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT, 6326 SDValue(CFP00, 0), 6327 DAG.getConstantFP(1.0, VT)); 6328 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, 6329 N1, NewCFP); 6330 } 6331 6332 // (fadd (fmul x, c), x) -> (fmul x, c+1) 6333 if (CFP01 && !CFP00 && N0.getOperand(0) == N1) { 6334 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT, 6335 SDValue(CFP01, 0), 6336 DAG.getConstantFP(1.0, VT)); 6337 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, 6338 N1, NewCFP); 6339 } 6340 6341 // (fadd (fmul c, x), (fadd x, x)) -> (fmul x, c+2) 6342 if (CFP00 && !CFP01 && N1.getOpcode() == ISD::FADD && 6343 N1.getOperand(0) == N1.getOperand(1) && 6344 N0.getOperand(1) == N1.getOperand(0)) { 6345 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT, 6346 SDValue(CFP00, 0), 6347 DAG.getConstantFP(2.0, VT)); 6348 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, 6349 N0.getOperand(1), NewCFP); 6350 } 6351 6352 // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2) 6353 if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD && 6354 N1.getOperand(0) == N1.getOperand(1) && 6355 N0.getOperand(0) == N1.getOperand(0)) { 6356 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT, 6357 SDValue(CFP01, 0), 6358 DAG.getConstantFP(2.0, VT)); 6359 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, 6360 N0.getOperand(0), NewCFP); 6361 } 6362 } 6363 6364 if (N1.getOpcode() == ISD::FMUL) { 6365 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0)); 6366 ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1)); 6367 6368 // (fadd x, (fmul c, x)) -> (fmul x, c+1) 6369 if (CFP10 && !CFP11 && N1.getOperand(1) == N0) { 6370 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT, 6371 SDValue(CFP10, 0), 6372 DAG.getConstantFP(1.0, VT)); 6373 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, 6374 N0, NewCFP); 6375 } 6376 6377 // (fadd x, (fmul x, c)) -> (fmul x, c+1) 6378 if (CFP11 && !CFP10 && N1.getOperand(0) == N0) { 6379 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT, 6380 SDValue(CFP11, 0), 6381 DAG.getConstantFP(1.0, VT)); 6382 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, 6383 N0, NewCFP); 6384 } 6385 6386 6387 // (fadd (fadd x, x), (fmul c, x)) -> (fmul x, c+2) 6388 if (CFP10 && !CFP11 && N0.getOpcode() == ISD::FADD && 6389 N0.getOperand(0) == N0.getOperand(1) && 6390 N1.getOperand(1) == N0.getOperand(0)) { 6391 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT, 6392 SDValue(CFP10, 0), 6393 DAG.getConstantFP(2.0, VT)); 6394 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, 6395 N1.getOperand(1), NewCFP); 6396 } 6397 6398 // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2) 6399 if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD && 6400 N0.getOperand(0) == N0.getOperand(1) && 6401 N1.getOperand(0) == N0.getOperand(0)) { 6402 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT, 6403 SDValue(CFP11, 0), 6404 DAG.getConstantFP(2.0, VT)); 6405 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, 6406 N1.getOperand(0), NewCFP); 6407 } 6408 } 6409 6410 if (N0.getOpcode() == ISD::FADD && AllowNewFpConst) { 6411 ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0)); 6412 // (fadd (fadd x, x), x) -> (fmul x, 3.0) 6413 if (!CFP && N0.getOperand(0) == N0.getOperand(1) && 6414 (N0.getOperand(0) == N1)) 6415 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, 6416 N1, DAG.getConstantFP(3.0, VT)); 6417 } 6418 6419 if (N1.getOpcode() == ISD::FADD && AllowNewFpConst) { 6420 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0)); 6421 // (fadd x, (fadd x, x)) -> (fmul x, 3.0) 6422 if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) && 6423 N1.getOperand(0) == N0) 6424 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, 6425 N0, DAG.getConstantFP(3.0, VT)); 6426 } 6427 6428 // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0) 6429 if (AllowNewFpConst && 6430 N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD && 6431 N0.getOperand(0) == N0.getOperand(1) && 6432 N1.getOperand(0) == N1.getOperand(1) && 6433 N0.getOperand(0) == N1.getOperand(0)) 6434 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, 6435 N0.getOperand(0), 6436 DAG.getConstantFP(4.0, VT)); 6437 } 6438 6439 // FADD -> FMA combines: 6440 if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast || 6441 DAG.getTarget().Options.UnsafeFPMath) && 6442 DAG.getTarget().getTargetLowering()->isFMAFasterThanFMulAndFAdd(VT) && 6443 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) { 6444 6445 // fold (fadd (fmul x, y), z) -> (fma x, y, z) 6446 if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse()) 6447 return DAG.getNode(ISD::FMA, SDLoc(N), VT, 6448 N0.getOperand(0), N0.getOperand(1), N1); 6449 6450 // fold (fadd x, (fmul y, z)) -> (fma y, z, x) 6451 // Note: Commutes FADD operands. 6452 if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse()) 6453 return DAG.getNode(ISD::FMA, SDLoc(N), VT, 6454 N1.getOperand(0), N1.getOperand(1), N0); 6455 } 6456 6457 return SDValue(); 6458 } 6459 6460 SDValue DAGCombiner::visitFSUB(SDNode *N) { 6461 SDValue N0 = N->getOperand(0); 6462 SDValue N1 = N->getOperand(1); 6463 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 6464 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 6465 EVT VT = N->getValueType(0); 6466 SDLoc dl(N); 6467 6468 // fold vector ops 6469 if (VT.isVector()) { 6470 SDValue FoldedVOp = SimplifyVBinOp(N); 6471 if (FoldedVOp.getNode()) return FoldedVOp; 6472 } 6473 6474 // fold (fsub c1, c2) -> c1-c2 6475 if (N0CFP && N1CFP) 6476 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0, N1); 6477 // fold (fsub A, 0) -> A 6478 if (DAG.getTarget().Options.UnsafeFPMath && 6479 N1CFP && N1CFP->getValueAPF().isZero()) 6480 return N0; 6481 // fold (fsub 0, B) -> -B 6482 if (DAG.getTarget().Options.UnsafeFPMath && 6483 N0CFP && N0CFP->getValueAPF().isZero()) { 6484 if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options)) 6485 return GetNegatedExpression(N1, DAG, LegalOperations); 6486 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT)) 6487 return DAG.getNode(ISD::FNEG, dl, VT, N1); 6488 } 6489 // fold (fsub A, (fneg B)) -> (fadd A, B) 6490 if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options)) 6491 return DAG.getNode(ISD::FADD, dl, VT, N0, 6492 GetNegatedExpression(N1, DAG, LegalOperations)); 6493 6494 // If 'unsafe math' is enabled, fold 6495 // (fsub x, x) -> 0.0 & 6496 // (fsub x, (fadd x, y)) -> (fneg y) & 6497 // (fsub x, (fadd y, x)) -> (fneg y) 6498 if (DAG.getTarget().Options.UnsafeFPMath) { 6499 if (N0 == N1) 6500 return DAG.getConstantFP(0.0f, VT); 6501 6502 if (N1.getOpcode() == ISD::FADD) { 6503 SDValue N10 = N1->getOperand(0); 6504 SDValue N11 = N1->getOperand(1); 6505 6506 if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, 6507 &DAG.getTarget().Options)) 6508 return GetNegatedExpression(N11, DAG, LegalOperations); 6509 6510 if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, 6511 &DAG.getTarget().Options)) 6512 return GetNegatedExpression(N10, DAG, LegalOperations); 6513 } 6514 } 6515 6516 // FSUB -> FMA combines: 6517 if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast || 6518 DAG.getTarget().Options.UnsafeFPMath) && 6519 DAG.getTarget().getTargetLowering()->isFMAFasterThanFMulAndFAdd(VT) && 6520 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) { 6521 6522 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z)) 6523 if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse()) 6524 return DAG.getNode(ISD::FMA, dl, VT, 6525 N0.getOperand(0), N0.getOperand(1), 6526 DAG.getNode(ISD::FNEG, dl, VT, N1)); 6527 6528 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x) 6529 // Note: Commutes FSUB operands. 6530 if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse()) 6531 return DAG.getNode(ISD::FMA, dl, VT, 6532 DAG.getNode(ISD::FNEG, dl, VT, 6533 N1.getOperand(0)), 6534 N1.getOperand(1), N0); 6535 6536 // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z)) 6537 if (N0.getOpcode() == ISD::FNEG && 6538 N0.getOperand(0).getOpcode() == ISD::FMUL && 6539 N0->hasOneUse() && N0.getOperand(0).hasOneUse()) { 6540 SDValue N00 = N0.getOperand(0).getOperand(0); 6541 SDValue N01 = N0.getOperand(0).getOperand(1); 6542 return DAG.getNode(ISD::FMA, dl, VT, 6543 DAG.getNode(ISD::FNEG, dl, VT, N00), N01, 6544 DAG.getNode(ISD::FNEG, dl, VT, N1)); 6545 } 6546 } 6547 6548 return SDValue(); 6549 } 6550 6551 SDValue DAGCombiner::visitFMUL(SDNode *N) { 6552 SDValue N0 = N->getOperand(0); 6553 SDValue N1 = N->getOperand(1); 6554 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 6555 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 6556 EVT VT = N->getValueType(0); 6557 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6558 6559 // fold vector ops 6560 if (VT.isVector()) { 6561 SDValue FoldedVOp = SimplifyVBinOp(N); 6562 if (FoldedVOp.getNode()) return FoldedVOp; 6563 } 6564 6565 // fold (fmul c1, c2) -> c1*c2 6566 if (N0CFP && N1CFP) 6567 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, N1); 6568 // canonicalize constant to RHS 6569 if (N0CFP && !N1CFP) 6570 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, N0); 6571 // fold (fmul A, 0) -> 0 6572 if (DAG.getTarget().Options.UnsafeFPMath && 6573 N1CFP && N1CFP->getValueAPF().isZero()) 6574 return N1; 6575 // fold (fmul A, 0) -> 0, vector edition. 6576 if (DAG.getTarget().Options.UnsafeFPMath && 6577 ISD::isBuildVectorAllZeros(N1.getNode())) 6578 return N1; 6579 // fold (fmul A, 1.0) -> A 6580 if (N1CFP && N1CFP->isExactlyValue(1.0)) 6581 return N0; 6582 // fold (fmul X, 2.0) -> (fadd X, X) 6583 if (N1CFP && N1CFP->isExactlyValue(+2.0)) 6584 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N0); 6585 // fold (fmul X, -1.0) -> (fneg X) 6586 if (N1CFP && N1CFP->isExactlyValue(-1.0)) 6587 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT)) 6588 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0); 6589 6590 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y) 6591 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, 6592 &DAG.getTarget().Options)) { 6593 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, 6594 &DAG.getTarget().Options)) { 6595 // Both can be negated for free, check to see if at least one is cheaper 6596 // negated. 6597 if (LHSNeg == 2 || RHSNeg == 2) 6598 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, 6599 GetNegatedExpression(N0, DAG, LegalOperations), 6600 GetNegatedExpression(N1, DAG, LegalOperations)); 6601 } 6602 } 6603 6604 // If allowed, fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2)) 6605 if (DAG.getTarget().Options.UnsafeFPMath && 6606 N1CFP && N0.getOpcode() == ISD::FMUL && 6607 N0.getNode()->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1))) 6608 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0), 6609 DAG.getNode(ISD::FMUL, SDLoc(N), VT, 6610 N0.getOperand(1), N1)); 6611 6612 return SDValue(); 6613 } 6614 6615 SDValue DAGCombiner::visitFMA(SDNode *N) { 6616 SDValue N0 = N->getOperand(0); 6617 SDValue N1 = N->getOperand(1); 6618 SDValue N2 = N->getOperand(2); 6619 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 6620 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 6621 EVT VT = N->getValueType(0); 6622 SDLoc dl(N); 6623 6624 if (DAG.getTarget().Options.UnsafeFPMath) { 6625 if (N0CFP && N0CFP->isZero()) 6626 return N2; 6627 if (N1CFP && N1CFP->isZero()) 6628 return N2; 6629 } 6630 if (N0CFP && N0CFP->isExactlyValue(1.0)) 6631 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2); 6632 if (N1CFP && N1CFP->isExactlyValue(1.0)) 6633 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2); 6634 6635 // Canonicalize (fma c, x, y) -> (fma x, c, y) 6636 if (N0CFP && !N1CFP) 6637 return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2); 6638 6639 // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2) 6640 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP && 6641 N2.getOpcode() == ISD::FMUL && 6642 N0 == N2.getOperand(0) && 6643 N2.getOperand(1).getOpcode() == ISD::ConstantFP) { 6644 return DAG.getNode(ISD::FMUL, dl, VT, N0, 6645 DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1))); 6646 } 6647 6648 6649 // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y) 6650 if (DAG.getTarget().Options.UnsafeFPMath && 6651 N0.getOpcode() == ISD::FMUL && N1CFP && 6652 N0.getOperand(1).getOpcode() == ISD::ConstantFP) { 6653 return DAG.getNode(ISD::FMA, dl, VT, 6654 N0.getOperand(0), 6655 DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)), 6656 N2); 6657 } 6658 6659 // (fma x, 1, y) -> (fadd x, y) 6660 // (fma x, -1, y) -> (fadd (fneg x), y) 6661 if (N1CFP) { 6662 if (N1CFP->isExactlyValue(1.0)) 6663 return DAG.getNode(ISD::FADD, dl, VT, N0, N2); 6664 6665 if (N1CFP->isExactlyValue(-1.0) && 6666 (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) { 6667 SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0); 6668 AddToWorkList(RHSNeg.getNode()); 6669 return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg); 6670 } 6671 } 6672 6673 // (fma x, c, x) -> (fmul x, (c+1)) 6674 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP && N0 == N2) 6675 return DAG.getNode(ISD::FMUL, dl, VT, N0, 6676 DAG.getNode(ISD::FADD, dl, VT, 6677 N1, DAG.getConstantFP(1.0, VT))); 6678 6679 // (fma x, c, (fneg x)) -> (fmul x, (c-1)) 6680 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP && 6681 N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0) 6682 return DAG.getNode(ISD::FMUL, dl, VT, N0, 6683 DAG.getNode(ISD::FADD, dl, VT, 6684 N1, DAG.getConstantFP(-1.0, VT))); 6685 6686 6687 return SDValue(); 6688 } 6689 6690 SDValue DAGCombiner::visitFDIV(SDNode *N) { 6691 SDValue N0 = N->getOperand(0); 6692 SDValue N1 = N->getOperand(1); 6693 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 6694 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 6695 EVT VT = N->getValueType(0); 6696 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6697 6698 // fold vector ops 6699 if (VT.isVector()) { 6700 SDValue FoldedVOp = SimplifyVBinOp(N); 6701 if (FoldedVOp.getNode()) return FoldedVOp; 6702 } 6703 6704 // fold (fdiv c1, c2) -> c1/c2 6705 if (N0CFP && N1CFP) 6706 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1); 6707 6708 // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable. 6709 if (N1CFP && DAG.getTarget().Options.UnsafeFPMath) { 6710 // Compute the reciprocal 1.0 / c2. 6711 APFloat N1APF = N1CFP->getValueAPF(); 6712 APFloat Recip(N1APF.getSemantics(), 1); // 1.0 6713 APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven); 6714 // Only do the transform if the reciprocal is a legal fp immediate that 6715 // isn't too nasty (eg NaN, denormal, ...). 6716 if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty 6717 (!LegalOperations || 6718 // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM 6719 // backend)... we should handle this gracefully after Legalize. 6720 // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) || 6721 TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) || 6722 TLI.isFPImmLegal(Recip, VT))) 6723 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, 6724 DAG.getConstantFP(Recip, VT)); 6725 } 6726 6727 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y) 6728 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, 6729 &DAG.getTarget().Options)) { 6730 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, 6731 &DAG.getTarget().Options)) { 6732 // Both can be negated for free, check to see if at least one is cheaper 6733 // negated. 6734 if (LHSNeg == 2 || RHSNeg == 2) 6735 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, 6736 GetNegatedExpression(N0, DAG, LegalOperations), 6737 GetNegatedExpression(N1, DAG, LegalOperations)); 6738 } 6739 } 6740 6741 return SDValue(); 6742 } 6743 6744 SDValue DAGCombiner::visitFREM(SDNode *N) { 6745 SDValue N0 = N->getOperand(0); 6746 SDValue N1 = N->getOperand(1); 6747 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 6748 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 6749 EVT VT = N->getValueType(0); 6750 6751 // fold (frem c1, c2) -> fmod(c1,c2) 6752 if (N0CFP && N1CFP) 6753 return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1); 6754 6755 return SDValue(); 6756 } 6757 6758 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) { 6759 SDValue N0 = N->getOperand(0); 6760 SDValue N1 = N->getOperand(1); 6761 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 6762 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 6763 EVT VT = N->getValueType(0); 6764 6765 if (N0CFP && N1CFP) // Constant fold 6766 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1); 6767 6768 if (N1CFP) { 6769 const APFloat& V = N1CFP->getValueAPF(); 6770 // copysign(x, c1) -> fabs(x) iff ispos(c1) 6771 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1) 6772 if (!V.isNegative()) { 6773 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT)) 6774 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0); 6775 } else { 6776 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT)) 6777 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, 6778 DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0)); 6779 } 6780 } 6781 6782 // copysign(fabs(x), y) -> copysign(x, y) 6783 // copysign(fneg(x), y) -> copysign(x, y) 6784 // copysign(copysign(x,z), y) -> copysign(x, y) 6785 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG || 6786 N0.getOpcode() == ISD::FCOPYSIGN) 6787 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, 6788 N0.getOperand(0), N1); 6789 6790 // copysign(x, abs(y)) -> abs(x) 6791 if (N1.getOpcode() == ISD::FABS) 6792 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0); 6793 6794 // copysign(x, copysign(y,z)) -> copysign(x, z) 6795 if (N1.getOpcode() == ISD::FCOPYSIGN) 6796 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, 6797 N0, N1.getOperand(1)); 6798 6799 // copysign(x, fp_extend(y)) -> copysign(x, y) 6800 // copysign(x, fp_round(y)) -> copysign(x, y) 6801 if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND) 6802 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, 6803 N0, N1.getOperand(0)); 6804 6805 return SDValue(); 6806 } 6807 6808 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) { 6809 SDValue N0 = N->getOperand(0); 6810 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 6811 EVT VT = N->getValueType(0); 6812 EVT OpVT = N0.getValueType(); 6813 6814 // fold (sint_to_fp c1) -> c1fp 6815 if (N0C && 6816 // ...but only if the target supports immediate floating-point values 6817 (!LegalOperations || 6818 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) 6819 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0); 6820 6821 // If the input is a legal type, and SINT_TO_FP is not legal on this target, 6822 // but UINT_TO_FP is legal on this target, try to convert. 6823 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) && 6824 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) { 6825 // If the sign bit is known to be zero, we can change this to UINT_TO_FP. 6826 if (DAG.SignBitIsZero(N0)) 6827 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0); 6828 } 6829 6830 // The next optimizations are desirable only if SELECT_CC can be lowered. 6831 // Check against MVT::Other for SELECT_CC, which is a workaround for targets 6832 // having to say they don't support SELECT_CC on every type the DAG knows 6833 // about, since there is no way to mark an opcode illegal at all value types 6834 // (See also visitSELECT) 6835 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other)) { 6836 // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc) 6837 if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 && 6838 !VT.isVector() && 6839 (!LegalOperations || 6840 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) { 6841 SDValue Ops[] = 6842 { N0.getOperand(0), N0.getOperand(1), 6843 DAG.getConstantFP(-1.0, VT) , DAG.getConstantFP(0.0, VT), 6844 N0.getOperand(2) }; 6845 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops, 5); 6846 } 6847 6848 // fold (sint_to_fp (zext (setcc x, y, cc))) -> 6849 // (select_cc x, y, 1.0, 0.0,, cc) 6850 if (N0.getOpcode() == ISD::ZERO_EXTEND && 6851 N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() && 6852 (!LegalOperations || 6853 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) { 6854 SDValue Ops[] = 6855 { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1), 6856 DAG.getConstantFP(1.0, VT) , DAG.getConstantFP(0.0, VT), 6857 N0.getOperand(0).getOperand(2) }; 6858 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops, 5); 6859 } 6860 } 6861 6862 return SDValue(); 6863 } 6864 6865 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) { 6866 SDValue N0 = N->getOperand(0); 6867 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 6868 EVT VT = N->getValueType(0); 6869 EVT OpVT = N0.getValueType(); 6870 6871 // fold (uint_to_fp c1) -> c1fp 6872 if (N0C && 6873 // ...but only if the target supports immediate floating-point values 6874 (!LegalOperations || 6875 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) 6876 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0); 6877 6878 // If the input is a legal type, and UINT_TO_FP is not legal on this target, 6879 // but SINT_TO_FP is legal on this target, try to convert. 6880 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) && 6881 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) { 6882 // If the sign bit is known to be zero, we can change this to SINT_TO_FP. 6883 if (DAG.SignBitIsZero(N0)) 6884 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0); 6885 } 6886 6887 // The next optimizations are desirable only if SELECT_CC can be lowered. 6888 // Check against MVT::Other for SELECT_CC, which is a workaround for targets 6889 // having to say they don't support SELECT_CC on every type the DAG knows 6890 // about, since there is no way to mark an opcode illegal at all value types 6891 // (See also visitSELECT) 6892 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other)) { 6893 // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc) 6894 6895 if (N0.getOpcode() == ISD::SETCC && !VT.isVector() && 6896 (!LegalOperations || 6897 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) { 6898 SDValue Ops[] = 6899 { N0.getOperand(0), N0.getOperand(1), 6900 DAG.getConstantFP(1.0, VT), DAG.getConstantFP(0.0, VT), 6901 N0.getOperand(2) }; 6902 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops, 5); 6903 } 6904 } 6905 6906 return SDValue(); 6907 } 6908 6909 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) { 6910 SDValue N0 = N->getOperand(0); 6911 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 6912 EVT VT = N->getValueType(0); 6913 6914 // fold (fp_to_sint c1fp) -> c1 6915 if (N0CFP) 6916 return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0); 6917 6918 return SDValue(); 6919 } 6920 6921 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) { 6922 SDValue N0 = N->getOperand(0); 6923 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 6924 EVT VT = N->getValueType(0); 6925 6926 // fold (fp_to_uint c1fp) -> c1 6927 if (N0CFP) 6928 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0); 6929 6930 return SDValue(); 6931 } 6932 6933 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) { 6934 SDValue N0 = N->getOperand(0); 6935 SDValue N1 = N->getOperand(1); 6936 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 6937 EVT VT = N->getValueType(0); 6938 6939 // fold (fp_round c1fp) -> c1fp 6940 if (N0CFP) 6941 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1); 6942 6943 // fold (fp_round (fp_extend x)) -> x 6944 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType()) 6945 return N0.getOperand(0); 6946 6947 // fold (fp_round (fp_round x)) -> (fp_round x) 6948 if (N0.getOpcode() == ISD::FP_ROUND) { 6949 // This is a value preserving truncation if both round's are. 6950 bool IsTrunc = N->getConstantOperandVal(1) == 1 && 6951 N0.getNode()->getConstantOperandVal(1) == 1; 6952 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0.getOperand(0), 6953 DAG.getIntPtrConstant(IsTrunc)); 6954 } 6955 6956 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y) 6957 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) { 6958 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT, 6959 N0.getOperand(0), N1); 6960 AddToWorkList(Tmp.getNode()); 6961 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, 6962 Tmp, N0.getOperand(1)); 6963 } 6964 6965 return SDValue(); 6966 } 6967 6968 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) { 6969 SDValue N0 = N->getOperand(0); 6970 EVT VT = N->getValueType(0); 6971 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT(); 6972 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 6973 6974 // fold (fp_round_inreg c1fp) -> c1fp 6975 if (N0CFP && isTypeLegal(EVT)) { 6976 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT); 6977 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, Round); 6978 } 6979 6980 return SDValue(); 6981 } 6982 6983 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) { 6984 SDValue N0 = N->getOperand(0); 6985 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 6986 EVT VT = N->getValueType(0); 6987 6988 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded. 6989 if (N->hasOneUse() && 6990 N->use_begin()->getOpcode() == ISD::FP_ROUND) 6991 return SDValue(); 6992 6993 // fold (fp_extend c1fp) -> c1fp 6994 if (N0CFP) 6995 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0); 6996 6997 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the 6998 // value of X. 6999 if (N0.getOpcode() == ISD::FP_ROUND 7000 && N0.getNode()->getConstantOperandVal(1) == 1) { 7001 SDValue In = N0.getOperand(0); 7002 if (In.getValueType() == VT) return In; 7003 if (VT.bitsLT(In.getValueType())) 7004 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, 7005 In, N0.getOperand(1)); 7006 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In); 7007 } 7008 7009 // fold (fpext (load x)) -> (fpext (fptrunc (extload x))) 7010 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() && 7011 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) || 7012 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) { 7013 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 7014 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT, 7015 LN0->getChain(), 7016 LN0->getBasePtr(), N0.getValueType(), 7017 LN0->getMemOperand()); 7018 CombineTo(N, ExtLoad); 7019 CombineTo(N0.getNode(), 7020 DAG.getNode(ISD::FP_ROUND, SDLoc(N0), 7021 N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)), 7022 ExtLoad.getValue(1)); 7023 return SDValue(N, 0); // Return N so it doesn't get rechecked! 7024 } 7025 7026 return SDValue(); 7027 } 7028 7029 SDValue DAGCombiner::visitFNEG(SDNode *N) { 7030 SDValue N0 = N->getOperand(0); 7031 EVT VT = N->getValueType(0); 7032 7033 if (VT.isVector()) { 7034 SDValue FoldedVOp = SimplifyVUnaryOp(N); 7035 if (FoldedVOp.getNode()) return FoldedVOp; 7036 } 7037 7038 if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(), 7039 &DAG.getTarget().Options)) 7040 return GetNegatedExpression(N0, DAG, LegalOperations); 7041 7042 // Transform fneg(bitconvert(x)) -> bitconvert(x^sign) to avoid loading 7043 // constant pool values. 7044 if (!TLI.isFNegFree(VT) && N0.getOpcode() == ISD::BITCAST && 7045 !VT.isVector() && 7046 N0.getNode()->hasOneUse() && 7047 N0.getOperand(0).getValueType().isInteger()) { 7048 SDValue Int = N0.getOperand(0); 7049 EVT IntVT = Int.getValueType(); 7050 if (IntVT.isInteger() && !IntVT.isVector()) { 7051 Int = DAG.getNode(ISD::XOR, SDLoc(N0), IntVT, Int, 7052 DAG.getConstant(APInt::getSignBit(IntVT.getSizeInBits()), IntVT)); 7053 AddToWorkList(Int.getNode()); 7054 return DAG.getNode(ISD::BITCAST, SDLoc(N), 7055 VT, Int); 7056 } 7057 } 7058 7059 // (fneg (fmul c, x)) -> (fmul -c, x) 7060 if (N0.getOpcode() == ISD::FMUL) { 7061 ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1)); 7062 if (CFP1) 7063 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, 7064 N0.getOperand(0), 7065 DAG.getNode(ISD::FNEG, SDLoc(N), VT, 7066 N0.getOperand(1))); 7067 } 7068 7069 return SDValue(); 7070 } 7071 7072 SDValue DAGCombiner::visitFCEIL(SDNode *N) { 7073 SDValue N0 = N->getOperand(0); 7074 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 7075 EVT VT = N->getValueType(0); 7076 7077 // fold (fceil c1) -> fceil(c1) 7078 if (N0CFP) 7079 return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0); 7080 7081 return SDValue(); 7082 } 7083 7084 SDValue DAGCombiner::visitFTRUNC(SDNode *N) { 7085 SDValue N0 = N->getOperand(0); 7086 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 7087 EVT VT = N->getValueType(0); 7088 7089 // fold (ftrunc c1) -> ftrunc(c1) 7090 if (N0CFP) 7091 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0); 7092 7093 return SDValue(); 7094 } 7095 7096 SDValue DAGCombiner::visitFFLOOR(SDNode *N) { 7097 SDValue N0 = N->getOperand(0); 7098 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 7099 EVT VT = N->getValueType(0); 7100 7101 // fold (ffloor c1) -> ffloor(c1) 7102 if (N0CFP) 7103 return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0); 7104 7105 return SDValue(); 7106 } 7107 7108 SDValue DAGCombiner::visitFABS(SDNode *N) { 7109 SDValue N0 = N->getOperand(0); 7110 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 7111 EVT VT = N->getValueType(0); 7112 7113 if (VT.isVector()) { 7114 SDValue FoldedVOp = SimplifyVUnaryOp(N); 7115 if (FoldedVOp.getNode()) return FoldedVOp; 7116 } 7117 7118 // fold (fabs c1) -> fabs(c1) 7119 if (N0CFP) 7120 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0); 7121 // fold (fabs (fabs x)) -> (fabs x) 7122 if (N0.getOpcode() == ISD::FABS) 7123 return N->getOperand(0); 7124 // fold (fabs (fneg x)) -> (fabs x) 7125 // fold (fabs (fcopysign x, y)) -> (fabs x) 7126 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN) 7127 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0)); 7128 7129 // Transform fabs(bitconvert(x)) -> bitconvert(x&~sign) to avoid loading 7130 // constant pool values. 7131 if (!TLI.isFAbsFree(VT) && 7132 N0.getOpcode() == ISD::BITCAST && N0.getNode()->hasOneUse() && 7133 N0.getOperand(0).getValueType().isInteger() && 7134 !N0.getOperand(0).getValueType().isVector()) { 7135 SDValue Int = N0.getOperand(0); 7136 EVT IntVT = Int.getValueType(); 7137 if (IntVT.isInteger() && !IntVT.isVector()) { 7138 Int = DAG.getNode(ISD::AND, SDLoc(N0), IntVT, Int, 7139 DAG.getConstant(~APInt::getSignBit(IntVT.getSizeInBits()), IntVT)); 7140 AddToWorkList(Int.getNode()); 7141 return DAG.getNode(ISD::BITCAST, SDLoc(N), 7142 N->getValueType(0), Int); 7143 } 7144 } 7145 7146 return SDValue(); 7147 } 7148 7149 SDValue DAGCombiner::visitBRCOND(SDNode *N) { 7150 SDValue Chain = N->getOperand(0); 7151 SDValue N1 = N->getOperand(1); 7152 SDValue N2 = N->getOperand(2); 7153 7154 // If N is a constant we could fold this into a fallthrough or unconditional 7155 // branch. However that doesn't happen very often in normal code, because 7156 // Instcombine/SimplifyCFG should have handled the available opportunities. 7157 // If we did this folding here, it would be necessary to update the 7158 // MachineBasicBlock CFG, which is awkward. 7159 7160 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal 7161 // on the target. 7162 if (N1.getOpcode() == ISD::SETCC && 7163 TLI.isOperationLegalOrCustom(ISD::BR_CC, 7164 N1.getOperand(0).getValueType())) { 7165 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other, 7166 Chain, N1.getOperand(2), 7167 N1.getOperand(0), N1.getOperand(1), N2); 7168 } 7169 7170 if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) || 7171 ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) && 7172 (N1.getOperand(0).hasOneUse() && 7173 N1.getOperand(0).getOpcode() == ISD::SRL))) { 7174 SDNode *Trunc = 0; 7175 if (N1.getOpcode() == ISD::TRUNCATE) { 7176 // Look pass the truncate. 7177 Trunc = N1.getNode(); 7178 N1 = N1.getOperand(0); 7179 } 7180 7181 // Match this pattern so that we can generate simpler code: 7182 // 7183 // %a = ... 7184 // %b = and i32 %a, 2 7185 // %c = srl i32 %b, 1 7186 // brcond i32 %c ... 7187 // 7188 // into 7189 // 7190 // %a = ... 7191 // %b = and i32 %a, 2 7192 // %c = setcc eq %b, 0 7193 // brcond %c ... 7194 // 7195 // This applies only when the AND constant value has one bit set and the 7196 // SRL constant is equal to the log2 of the AND constant. The back-end is 7197 // smart enough to convert the result into a TEST/JMP sequence. 7198 SDValue Op0 = N1.getOperand(0); 7199 SDValue Op1 = N1.getOperand(1); 7200 7201 if (Op0.getOpcode() == ISD::AND && 7202 Op1.getOpcode() == ISD::Constant) { 7203 SDValue AndOp1 = Op0.getOperand(1); 7204 7205 if (AndOp1.getOpcode() == ISD::Constant) { 7206 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue(); 7207 7208 if (AndConst.isPowerOf2() && 7209 cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) { 7210 SDValue SetCC = 7211 DAG.getSetCC(SDLoc(N), 7212 getSetCCResultType(Op0.getValueType()), 7213 Op0, DAG.getConstant(0, Op0.getValueType()), 7214 ISD::SETNE); 7215 7216 SDValue NewBRCond = DAG.getNode(ISD::BRCOND, SDLoc(N), 7217 MVT::Other, Chain, SetCC, N2); 7218 // Don't add the new BRCond into the worklist or else SimplifySelectCC 7219 // will convert it back to (X & C1) >> C2. 7220 CombineTo(N, NewBRCond, false); 7221 // Truncate is dead. 7222 if (Trunc) { 7223 removeFromWorkList(Trunc); 7224 DAG.DeleteNode(Trunc); 7225 } 7226 // Replace the uses of SRL with SETCC 7227 WorkListRemover DeadNodes(*this); 7228 DAG.ReplaceAllUsesOfValueWith(N1, SetCC); 7229 removeFromWorkList(N1.getNode()); 7230 DAG.DeleteNode(N1.getNode()); 7231 return SDValue(N, 0); // Return N so it doesn't get rechecked! 7232 } 7233 } 7234 } 7235 7236 if (Trunc) 7237 // Restore N1 if the above transformation doesn't match. 7238 N1 = N->getOperand(1); 7239 } 7240 7241 // Transform br(xor(x, y)) -> br(x != y) 7242 // Transform br(xor(xor(x,y), 1)) -> br (x == y) 7243 if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) { 7244 SDNode *TheXor = N1.getNode(); 7245 SDValue Op0 = TheXor->getOperand(0); 7246 SDValue Op1 = TheXor->getOperand(1); 7247 if (Op0.getOpcode() == Op1.getOpcode()) { 7248 // Avoid missing important xor optimizations. 7249 SDValue Tmp = visitXOR(TheXor); 7250 if (Tmp.getNode()) { 7251 if (Tmp.getNode() != TheXor) { 7252 DEBUG(dbgs() << "\nReplacing.8 "; 7253 TheXor->dump(&DAG); 7254 dbgs() << "\nWith: "; 7255 Tmp.getNode()->dump(&DAG); 7256 dbgs() << '\n'); 7257 WorkListRemover DeadNodes(*this); 7258 DAG.ReplaceAllUsesOfValueWith(N1, Tmp); 7259 removeFromWorkList(TheXor); 7260 DAG.DeleteNode(TheXor); 7261 return DAG.getNode(ISD::BRCOND, SDLoc(N), 7262 MVT::Other, Chain, Tmp, N2); 7263 } 7264 7265 // visitXOR has changed XOR's operands or replaced the XOR completely, 7266 // bail out. 7267 return SDValue(N, 0); 7268 } 7269 } 7270 7271 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) { 7272 bool Equal = false; 7273 if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0)) 7274 if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() && 7275 Op0.getOpcode() == ISD::XOR) { 7276 TheXor = Op0.getNode(); 7277 Equal = true; 7278 } 7279 7280 EVT SetCCVT = N1.getValueType(); 7281 if (LegalTypes) 7282 SetCCVT = getSetCCResultType(SetCCVT); 7283 SDValue SetCC = DAG.getSetCC(SDLoc(TheXor), 7284 SetCCVT, 7285 Op0, Op1, 7286 Equal ? ISD::SETEQ : ISD::SETNE); 7287 // Replace the uses of XOR with SETCC 7288 WorkListRemover DeadNodes(*this); 7289 DAG.ReplaceAllUsesOfValueWith(N1, SetCC); 7290 removeFromWorkList(N1.getNode()); 7291 DAG.DeleteNode(N1.getNode()); 7292 return DAG.getNode(ISD::BRCOND, SDLoc(N), 7293 MVT::Other, Chain, SetCC, N2); 7294 } 7295 } 7296 7297 return SDValue(); 7298 } 7299 7300 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB. 7301 // 7302 SDValue DAGCombiner::visitBR_CC(SDNode *N) { 7303 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1)); 7304 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3); 7305 7306 // If N is a constant we could fold this into a fallthrough or unconditional 7307 // branch. However that doesn't happen very often in normal code, because 7308 // Instcombine/SimplifyCFG should have handled the available opportunities. 7309 // If we did this folding here, it would be necessary to update the 7310 // MachineBasicBlock CFG, which is awkward. 7311 7312 // Use SimplifySetCC to simplify SETCC's. 7313 SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()), 7314 CondLHS, CondRHS, CC->get(), SDLoc(N), 7315 false); 7316 if (Simp.getNode()) AddToWorkList(Simp.getNode()); 7317 7318 // fold to a simpler setcc 7319 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC) 7320 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other, 7321 N->getOperand(0), Simp.getOperand(2), 7322 Simp.getOperand(0), Simp.getOperand(1), 7323 N->getOperand(4)); 7324 7325 return SDValue(); 7326 } 7327 7328 /// canFoldInAddressingMode - Return true if 'Use' is a load or a store that 7329 /// uses N as its base pointer and that N may be folded in the load / store 7330 /// addressing mode. 7331 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use, 7332 SelectionDAG &DAG, 7333 const TargetLowering &TLI) { 7334 EVT VT; 7335 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) { 7336 if (LD->isIndexed() || LD->getBasePtr().getNode() != N) 7337 return false; 7338 VT = Use->getValueType(0); 7339 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) { 7340 if (ST->isIndexed() || ST->getBasePtr().getNode() != N) 7341 return false; 7342 VT = ST->getValue().getValueType(); 7343 } else 7344 return false; 7345 7346 TargetLowering::AddrMode AM; 7347 if (N->getOpcode() == ISD::ADD) { 7348 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1)); 7349 if (Offset) 7350 // [reg +/- imm] 7351 AM.BaseOffs = Offset->getSExtValue(); 7352 else 7353 // [reg +/- reg] 7354 AM.Scale = 1; 7355 } else if (N->getOpcode() == ISD::SUB) { 7356 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1)); 7357 if (Offset) 7358 // [reg +/- imm] 7359 AM.BaseOffs = -Offset->getSExtValue(); 7360 else 7361 // [reg +/- reg] 7362 AM.Scale = 1; 7363 } else 7364 return false; 7365 7366 return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext())); 7367 } 7368 7369 /// CombineToPreIndexedLoadStore - Try turning a load / store into a 7370 /// pre-indexed load / store when the base pointer is an add or subtract 7371 /// and it has other uses besides the load / store. After the 7372 /// transformation, the new indexed load / store has effectively folded 7373 /// the add / subtract in and all of its other uses are redirected to the 7374 /// new load / store. 7375 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) { 7376 if (Level < AfterLegalizeDAG) 7377 return false; 7378 7379 bool isLoad = true; 7380 SDValue Ptr; 7381 EVT VT; 7382 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 7383 if (LD->isIndexed()) 7384 return false; 7385 VT = LD->getMemoryVT(); 7386 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) && 7387 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT)) 7388 return false; 7389 Ptr = LD->getBasePtr(); 7390 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 7391 if (ST->isIndexed()) 7392 return false; 7393 VT = ST->getMemoryVT(); 7394 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) && 7395 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT)) 7396 return false; 7397 Ptr = ST->getBasePtr(); 7398 isLoad = false; 7399 } else { 7400 return false; 7401 } 7402 7403 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail 7404 // out. There is no reason to make this a preinc/predec. 7405 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) || 7406 Ptr.getNode()->hasOneUse()) 7407 return false; 7408 7409 // Ask the target to do addressing mode selection. 7410 SDValue BasePtr; 7411 SDValue Offset; 7412 ISD::MemIndexedMode AM = ISD::UNINDEXED; 7413 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG)) 7414 return false; 7415 7416 // Backends without true r+i pre-indexed forms may need to pass a 7417 // constant base with a variable offset so that constant coercion 7418 // will work with the patterns in canonical form. 7419 bool Swapped = false; 7420 if (isa<ConstantSDNode>(BasePtr)) { 7421 std::swap(BasePtr, Offset); 7422 Swapped = true; 7423 } 7424 7425 // Don't create a indexed load / store with zero offset. 7426 if (isa<ConstantSDNode>(Offset) && 7427 cast<ConstantSDNode>(Offset)->isNullValue()) 7428 return false; 7429 7430 // Try turning it into a pre-indexed load / store except when: 7431 // 1) The new base ptr is a frame index. 7432 // 2) If N is a store and the new base ptr is either the same as or is a 7433 // predecessor of the value being stored. 7434 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded 7435 // that would create a cycle. 7436 // 4) All uses are load / store ops that use it as old base ptr. 7437 7438 // Check #1. Preinc'ing a frame index would require copying the stack pointer 7439 // (plus the implicit offset) to a register to preinc anyway. 7440 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr)) 7441 return false; 7442 7443 // Check #2. 7444 if (!isLoad) { 7445 SDValue Val = cast<StoreSDNode>(N)->getValue(); 7446 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode())) 7447 return false; 7448 } 7449 7450 // If the offset is a constant, there may be other adds of constants that 7451 // can be folded with this one. We should do this to avoid having to keep 7452 // a copy of the original base pointer. 7453 SmallVector<SDNode *, 16> OtherUses; 7454 if (isa<ConstantSDNode>(Offset)) 7455 for (SDNode::use_iterator I = BasePtr.getNode()->use_begin(), 7456 E = BasePtr.getNode()->use_end(); I != E; ++I) { 7457 SDNode *Use = *I; 7458 if (Use == Ptr.getNode()) 7459 continue; 7460 7461 if (Use->isPredecessorOf(N)) 7462 continue; 7463 7464 if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) { 7465 OtherUses.clear(); 7466 break; 7467 } 7468 7469 SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1); 7470 if (Op1.getNode() == BasePtr.getNode()) 7471 std::swap(Op0, Op1); 7472 assert(Op0.getNode() == BasePtr.getNode() && 7473 "Use of ADD/SUB but not an operand"); 7474 7475 if (!isa<ConstantSDNode>(Op1)) { 7476 OtherUses.clear(); 7477 break; 7478 } 7479 7480 // FIXME: In some cases, we can be smarter about this. 7481 if (Op1.getValueType() != Offset.getValueType()) { 7482 OtherUses.clear(); 7483 break; 7484 } 7485 7486 OtherUses.push_back(Use); 7487 } 7488 7489 if (Swapped) 7490 std::swap(BasePtr, Offset); 7491 7492 // Now check for #3 and #4. 7493 bool RealUse = false; 7494 7495 // Caches for hasPredecessorHelper 7496 SmallPtrSet<const SDNode *, 32> Visited; 7497 SmallVector<const SDNode *, 16> Worklist; 7498 7499 for (SDNode::use_iterator I = Ptr.getNode()->use_begin(), 7500 E = Ptr.getNode()->use_end(); I != E; ++I) { 7501 SDNode *Use = *I; 7502 if (Use == N) 7503 continue; 7504 if (N->hasPredecessorHelper(Use, Visited, Worklist)) 7505 return false; 7506 7507 // If Ptr may be folded in addressing mode of other use, then it's 7508 // not profitable to do this transformation. 7509 if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI)) 7510 RealUse = true; 7511 } 7512 7513 if (!RealUse) 7514 return false; 7515 7516 SDValue Result; 7517 if (isLoad) 7518 Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N), 7519 BasePtr, Offset, AM); 7520 else 7521 Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N), 7522 BasePtr, Offset, AM); 7523 ++PreIndexedNodes; 7524 ++NodesCombined; 7525 DEBUG(dbgs() << "\nReplacing.4 "; 7526 N->dump(&DAG); 7527 dbgs() << "\nWith: "; 7528 Result.getNode()->dump(&DAG); 7529 dbgs() << '\n'); 7530 WorkListRemover DeadNodes(*this); 7531 if (isLoad) { 7532 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0)); 7533 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2)); 7534 } else { 7535 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1)); 7536 } 7537 7538 // Finally, since the node is now dead, remove it from the graph. 7539 DAG.DeleteNode(N); 7540 7541 if (Swapped) 7542 std::swap(BasePtr, Offset); 7543 7544 // Replace other uses of BasePtr that can be updated to use Ptr 7545 for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) { 7546 unsigned OffsetIdx = 1; 7547 if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode()) 7548 OffsetIdx = 0; 7549 assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() == 7550 BasePtr.getNode() && "Expected BasePtr operand"); 7551 7552 // We need to replace ptr0 in the following expression: 7553 // x0 * offset0 + y0 * ptr0 = t0 7554 // knowing that 7555 // x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store) 7556 // 7557 // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the 7558 // indexed load/store and the expresion that needs to be re-written. 7559 // 7560 // Therefore, we have: 7561 // t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1 7562 7563 ConstantSDNode *CN = 7564 cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx)); 7565 int X0, X1, Y0, Y1; 7566 APInt Offset0 = CN->getAPIntValue(); 7567 APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue(); 7568 7569 X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1; 7570 Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1; 7571 X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1; 7572 Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1; 7573 7574 unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD; 7575 7576 APInt CNV = Offset0; 7577 if (X0 < 0) CNV = -CNV; 7578 if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1; 7579 else CNV = CNV - Offset1; 7580 7581 // We can now generate the new expression. 7582 SDValue NewOp1 = DAG.getConstant(CNV, CN->getValueType(0)); 7583 SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0); 7584 7585 SDValue NewUse = DAG.getNode(Opcode, 7586 SDLoc(OtherUses[i]), 7587 OtherUses[i]->getValueType(0), NewOp1, NewOp2); 7588 DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse); 7589 removeFromWorkList(OtherUses[i]); 7590 DAG.DeleteNode(OtherUses[i]); 7591 } 7592 7593 // Replace the uses of Ptr with uses of the updated base value. 7594 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0)); 7595 removeFromWorkList(Ptr.getNode()); 7596 DAG.DeleteNode(Ptr.getNode()); 7597 7598 return true; 7599 } 7600 7601 /// CombineToPostIndexedLoadStore - Try to combine a load / store with a 7602 /// add / sub of the base pointer node into a post-indexed load / store. 7603 /// The transformation folded the add / subtract into the new indexed 7604 /// load / store effectively and all of its uses are redirected to the 7605 /// new load / store. 7606 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) { 7607 if (Level < AfterLegalizeDAG) 7608 return false; 7609 7610 bool isLoad = true; 7611 SDValue Ptr; 7612 EVT VT; 7613 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 7614 if (LD->isIndexed()) 7615 return false; 7616 VT = LD->getMemoryVT(); 7617 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) && 7618 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT)) 7619 return false; 7620 Ptr = LD->getBasePtr(); 7621 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 7622 if (ST->isIndexed()) 7623 return false; 7624 VT = ST->getMemoryVT(); 7625 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) && 7626 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT)) 7627 return false; 7628 Ptr = ST->getBasePtr(); 7629 isLoad = false; 7630 } else { 7631 return false; 7632 } 7633 7634 if (Ptr.getNode()->hasOneUse()) 7635 return false; 7636 7637 for (SDNode::use_iterator I = Ptr.getNode()->use_begin(), 7638 E = Ptr.getNode()->use_end(); I != E; ++I) { 7639 SDNode *Op = *I; 7640 if (Op == N || 7641 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB)) 7642 continue; 7643 7644 SDValue BasePtr; 7645 SDValue Offset; 7646 ISD::MemIndexedMode AM = ISD::UNINDEXED; 7647 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) { 7648 // Don't create a indexed load / store with zero offset. 7649 if (isa<ConstantSDNode>(Offset) && 7650 cast<ConstantSDNode>(Offset)->isNullValue()) 7651 continue; 7652 7653 // Try turning it into a post-indexed load / store except when 7654 // 1) All uses are load / store ops that use it as base ptr (and 7655 // it may be folded as addressing mmode). 7656 // 2) Op must be independent of N, i.e. Op is neither a predecessor 7657 // nor a successor of N. Otherwise, if Op is folded that would 7658 // create a cycle. 7659 7660 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr)) 7661 continue; 7662 7663 // Check for #1. 7664 bool TryNext = false; 7665 for (SDNode::use_iterator II = BasePtr.getNode()->use_begin(), 7666 EE = BasePtr.getNode()->use_end(); II != EE; ++II) { 7667 SDNode *Use = *II; 7668 if (Use == Ptr.getNode()) 7669 continue; 7670 7671 // If all the uses are load / store addresses, then don't do the 7672 // transformation. 7673 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){ 7674 bool RealUse = false; 7675 for (SDNode::use_iterator III = Use->use_begin(), 7676 EEE = Use->use_end(); III != EEE; ++III) { 7677 SDNode *UseUse = *III; 7678 if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI)) 7679 RealUse = true; 7680 } 7681 7682 if (!RealUse) { 7683 TryNext = true; 7684 break; 7685 } 7686 } 7687 } 7688 7689 if (TryNext) 7690 continue; 7691 7692 // Check for #2 7693 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) { 7694 SDValue Result = isLoad 7695 ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N), 7696 BasePtr, Offset, AM) 7697 : DAG.getIndexedStore(SDValue(N,0), SDLoc(N), 7698 BasePtr, Offset, AM); 7699 ++PostIndexedNodes; 7700 ++NodesCombined; 7701 DEBUG(dbgs() << "\nReplacing.5 "; 7702 N->dump(&DAG); 7703 dbgs() << "\nWith: "; 7704 Result.getNode()->dump(&DAG); 7705 dbgs() << '\n'); 7706 WorkListRemover DeadNodes(*this); 7707 if (isLoad) { 7708 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0)); 7709 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2)); 7710 } else { 7711 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1)); 7712 } 7713 7714 // Finally, since the node is now dead, remove it from the graph. 7715 DAG.DeleteNode(N); 7716 7717 // Replace the uses of Use with uses of the updated base value. 7718 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0), 7719 Result.getValue(isLoad ? 1 : 0)); 7720 removeFromWorkList(Op); 7721 DAG.DeleteNode(Op); 7722 return true; 7723 } 7724 } 7725 } 7726 7727 return false; 7728 } 7729 7730 SDValue DAGCombiner::visitLOAD(SDNode *N) { 7731 LoadSDNode *LD = cast<LoadSDNode>(N); 7732 SDValue Chain = LD->getChain(); 7733 SDValue Ptr = LD->getBasePtr(); 7734 7735 // If load is not volatile and there are no uses of the loaded value (and 7736 // the updated indexed value in case of indexed loads), change uses of the 7737 // chain value into uses of the chain input (i.e. delete the dead load). 7738 if (!LD->isVolatile()) { 7739 if (N->getValueType(1) == MVT::Other) { 7740 // Unindexed loads. 7741 if (!N->hasAnyUseOfValue(0)) { 7742 // It's not safe to use the two value CombineTo variant here. e.g. 7743 // v1, chain2 = load chain1, loc 7744 // v2, chain3 = load chain2, loc 7745 // v3 = add v2, c 7746 // Now we replace use of chain2 with chain1. This makes the second load 7747 // isomorphic to the one we are deleting, and thus makes this load live. 7748 DEBUG(dbgs() << "\nReplacing.6 "; 7749 N->dump(&DAG); 7750 dbgs() << "\nWith chain: "; 7751 Chain.getNode()->dump(&DAG); 7752 dbgs() << "\n"); 7753 WorkListRemover DeadNodes(*this); 7754 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain); 7755 7756 if (N->use_empty()) { 7757 removeFromWorkList(N); 7758 DAG.DeleteNode(N); 7759 } 7760 7761 return SDValue(N, 0); // Return N so it doesn't get rechecked! 7762 } 7763 } else { 7764 // Indexed loads. 7765 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?"); 7766 if (!N->hasAnyUseOfValue(0) && !N->hasAnyUseOfValue(1)) { 7767 SDValue Undef = DAG.getUNDEF(N->getValueType(0)); 7768 DEBUG(dbgs() << "\nReplacing.7 "; 7769 N->dump(&DAG); 7770 dbgs() << "\nWith: "; 7771 Undef.getNode()->dump(&DAG); 7772 dbgs() << " and 2 other values\n"); 7773 WorkListRemover DeadNodes(*this); 7774 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef); 7775 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), 7776 DAG.getUNDEF(N->getValueType(1))); 7777 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain); 7778 removeFromWorkList(N); 7779 DAG.DeleteNode(N); 7780 return SDValue(N, 0); // Return N so it doesn't get rechecked! 7781 } 7782 } 7783 } 7784 7785 // If this load is directly stored, replace the load value with the stored 7786 // value. 7787 // TODO: Handle store large -> read small portion. 7788 // TODO: Handle TRUNCSTORE/LOADEXT 7789 if (ISD::isNormalLoad(N) && !LD->isVolatile()) { 7790 if (ISD::isNON_TRUNCStore(Chain.getNode())) { 7791 StoreSDNode *PrevST = cast<StoreSDNode>(Chain); 7792 if (PrevST->getBasePtr() == Ptr && 7793 PrevST->getValue().getValueType() == N->getValueType(0)) 7794 return CombineTo(N, Chain.getOperand(1), Chain); 7795 } 7796 } 7797 7798 // Try to infer better alignment information than the load already has. 7799 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) { 7800 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) { 7801 if (Align > LD->getMemOperand()->getBaseAlignment()) { 7802 SDValue NewLoad = 7803 DAG.getExtLoad(LD->getExtensionType(), SDLoc(N), 7804 LD->getValueType(0), 7805 Chain, Ptr, LD->getPointerInfo(), 7806 LD->getMemoryVT(), 7807 LD->isVolatile(), LD->isNonTemporal(), Align, 7808 LD->getTBAAInfo()); 7809 return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true); 7810 } 7811 } 7812 } 7813 7814 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA : 7815 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA(); 7816 #ifndef NDEBUG 7817 if (CombinerAAOnlyFunc.getNumOccurrences() && 7818 CombinerAAOnlyFunc != DAG.getMachineFunction().getName()) 7819 UseAA = false; 7820 #endif 7821 if (UseAA && LD->isUnindexed()) { 7822 // Walk up chain skipping non-aliasing memory nodes. 7823 SDValue BetterChain = FindBetterChain(N, Chain); 7824 7825 // If there is a better chain. 7826 if (Chain != BetterChain) { 7827 SDValue ReplLoad; 7828 7829 // Replace the chain to void dependency. 7830 if (LD->getExtensionType() == ISD::NON_EXTLOAD) { 7831 ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD), 7832 BetterChain, Ptr, LD->getMemOperand()); 7833 } else { 7834 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), 7835 LD->getValueType(0), 7836 BetterChain, Ptr, LD->getMemoryVT(), 7837 LD->getMemOperand()); 7838 } 7839 7840 // Create token factor to keep old chain connected. 7841 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N), 7842 MVT::Other, Chain, ReplLoad.getValue(1)); 7843 7844 // Make sure the new and old chains are cleaned up. 7845 AddToWorkList(Token.getNode()); 7846 7847 // Replace uses with load result and token factor. Don't add users 7848 // to work list. 7849 return CombineTo(N, ReplLoad.getValue(0), Token, false); 7850 } 7851 } 7852 7853 // Try transforming N to an indexed load. 7854 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N)) 7855 return SDValue(N, 0); 7856 7857 // Try to slice up N to more direct loads if the slices are mapped to 7858 // different register banks or pairing can take place. 7859 if (SliceUpLoad(N)) 7860 return SDValue(N, 0); 7861 7862 return SDValue(); 7863 } 7864 7865 namespace { 7866 /// \brief Helper structure used to slice a load in smaller loads. 7867 /// Basically a slice is obtained from the following sequence: 7868 /// Origin = load Ty1, Base 7869 /// Shift = srl Ty1 Origin, CstTy Amount 7870 /// Inst = trunc Shift to Ty2 7871 /// 7872 /// Then, it will be rewriten into: 7873 /// Slice = load SliceTy, Base + SliceOffset 7874 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2 7875 /// 7876 /// SliceTy is deduced from the number of bits that are actually used to 7877 /// build Inst. 7878 struct LoadedSlice { 7879 /// \brief Helper structure used to compute the cost of a slice. 7880 struct Cost { 7881 /// Are we optimizing for code size. 7882 bool ForCodeSize; 7883 /// Various cost. 7884 unsigned Loads; 7885 unsigned Truncates; 7886 unsigned CrossRegisterBanksCopies; 7887 unsigned ZExts; 7888 unsigned Shift; 7889 7890 Cost(bool ForCodeSize = false) 7891 : ForCodeSize(ForCodeSize), Loads(0), Truncates(0), 7892 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {} 7893 7894 /// \brief Get the cost of one isolated slice. 7895 Cost(const LoadedSlice &LS, bool ForCodeSize = false) 7896 : ForCodeSize(ForCodeSize), Loads(1), Truncates(0), 7897 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) { 7898 EVT TruncType = LS.Inst->getValueType(0); 7899 EVT LoadedType = LS.getLoadedType(); 7900 if (TruncType != LoadedType && 7901 !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType)) 7902 ZExts = 1; 7903 } 7904 7905 /// \brief Account for slicing gain in the current cost. 7906 /// Slicing provide a few gains like removing a shift or a 7907 /// truncate. This method allows to grow the cost of the original 7908 /// load with the gain from this slice. 7909 void addSliceGain(const LoadedSlice &LS) { 7910 // Each slice saves a truncate. 7911 const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo(); 7912 if (!TLI.isTruncateFree(LS.Inst->getValueType(0), 7913 LS.Inst->getOperand(0).getValueType())) 7914 ++Truncates; 7915 // If there is a shift amount, this slice gets rid of it. 7916 if (LS.Shift) 7917 ++Shift; 7918 // If this slice can merge a cross register bank copy, account for it. 7919 if (LS.canMergeExpensiveCrossRegisterBankCopy()) 7920 ++CrossRegisterBanksCopies; 7921 } 7922 7923 Cost &operator+=(const Cost &RHS) { 7924 Loads += RHS.Loads; 7925 Truncates += RHS.Truncates; 7926 CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies; 7927 ZExts += RHS.ZExts; 7928 Shift += RHS.Shift; 7929 return *this; 7930 } 7931 7932 bool operator==(const Cost &RHS) const { 7933 return Loads == RHS.Loads && Truncates == RHS.Truncates && 7934 CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies && 7935 ZExts == RHS.ZExts && Shift == RHS.Shift; 7936 } 7937 7938 bool operator!=(const Cost &RHS) const { return !(*this == RHS); } 7939 7940 bool operator<(const Cost &RHS) const { 7941 // Assume cross register banks copies are as expensive as loads. 7942 // FIXME: Do we want some more target hooks? 7943 unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies; 7944 unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies; 7945 // Unless we are optimizing for code size, consider the 7946 // expensive operation first. 7947 if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS) 7948 return ExpensiveOpsLHS < ExpensiveOpsRHS; 7949 return (Truncates + ZExts + Shift + ExpensiveOpsLHS) < 7950 (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS); 7951 } 7952 7953 bool operator>(const Cost &RHS) const { return RHS < *this; } 7954 7955 bool operator<=(const Cost &RHS) const { return !(RHS < *this); } 7956 7957 bool operator>=(const Cost &RHS) const { return !(*this < RHS); } 7958 }; 7959 // The last instruction that represent the slice. This should be a 7960 // truncate instruction. 7961 SDNode *Inst; 7962 // The original load instruction. 7963 LoadSDNode *Origin; 7964 // The right shift amount in bits from the original load. 7965 unsigned Shift; 7966 // The DAG from which Origin came from. 7967 // This is used to get some contextual information about legal types, etc. 7968 SelectionDAG *DAG; 7969 7970 LoadedSlice(SDNode *Inst = NULL, LoadSDNode *Origin = NULL, 7971 unsigned Shift = 0, SelectionDAG *DAG = NULL) 7972 : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {} 7973 7974 LoadedSlice(const LoadedSlice &LS) 7975 : Inst(LS.Inst), Origin(LS.Origin), Shift(LS.Shift), DAG(LS.DAG) {} 7976 7977 /// \brief Get the bits used in a chunk of bits \p BitWidth large. 7978 /// \return Result is \p BitWidth and has used bits set to 1 and 7979 /// not used bits set to 0. 7980 APInt getUsedBits() const { 7981 // Reproduce the trunc(lshr) sequence: 7982 // - Start from the truncated value. 7983 // - Zero extend to the desired bit width. 7984 // - Shift left. 7985 assert(Origin && "No original load to compare against."); 7986 unsigned BitWidth = Origin->getValueSizeInBits(0); 7987 assert(Inst && "This slice is not bound to an instruction"); 7988 assert(Inst->getValueSizeInBits(0) <= BitWidth && 7989 "Extracted slice is bigger than the whole type!"); 7990 APInt UsedBits(Inst->getValueSizeInBits(0), 0); 7991 UsedBits.setAllBits(); 7992 UsedBits = UsedBits.zext(BitWidth); 7993 UsedBits <<= Shift; 7994 return UsedBits; 7995 } 7996 7997 /// \brief Get the size of the slice to be loaded in bytes. 7998 unsigned getLoadedSize() const { 7999 unsigned SliceSize = getUsedBits().countPopulation(); 8000 assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte."); 8001 return SliceSize / 8; 8002 } 8003 8004 /// \brief Get the type that will be loaded for this slice. 8005 /// Note: This may not be the final type for the slice. 8006 EVT getLoadedType() const { 8007 assert(DAG && "Missing context"); 8008 LLVMContext &Ctxt = *DAG->getContext(); 8009 return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8); 8010 } 8011 8012 /// \brief Get the alignment of the load used for this slice. 8013 unsigned getAlignment() const { 8014 unsigned Alignment = Origin->getAlignment(); 8015 unsigned Offset = getOffsetFromBase(); 8016 if (Offset != 0) 8017 Alignment = MinAlign(Alignment, Alignment + Offset); 8018 return Alignment; 8019 } 8020 8021 /// \brief Check if this slice can be rewritten with legal operations. 8022 bool isLegal() const { 8023 // An invalid slice is not legal. 8024 if (!Origin || !Inst || !DAG) 8025 return false; 8026 8027 // Offsets are for indexed load only, we do not handle that. 8028 if (Origin->getOffset().getOpcode() != ISD::UNDEF) 8029 return false; 8030 8031 const TargetLowering &TLI = DAG->getTargetLoweringInfo(); 8032 8033 // Check that the type is legal. 8034 EVT SliceType = getLoadedType(); 8035 if (!TLI.isTypeLegal(SliceType)) 8036 return false; 8037 8038 // Check that the load is legal for this type. 8039 if (!TLI.isOperationLegal(ISD::LOAD, SliceType)) 8040 return false; 8041 8042 // Check that the offset can be computed. 8043 // 1. Check its type. 8044 EVT PtrType = Origin->getBasePtr().getValueType(); 8045 if (PtrType == MVT::Untyped || PtrType.isExtended()) 8046 return false; 8047 8048 // 2. Check that it fits in the immediate. 8049 if (!TLI.isLegalAddImmediate(getOffsetFromBase())) 8050 return false; 8051 8052 // 3. Check that the computation is legal. 8053 if (!TLI.isOperationLegal(ISD::ADD, PtrType)) 8054 return false; 8055 8056 // Check that the zext is legal if it needs one. 8057 EVT TruncateType = Inst->getValueType(0); 8058 if (TruncateType != SliceType && 8059 !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType)) 8060 return false; 8061 8062 return true; 8063 } 8064 8065 /// \brief Get the offset in bytes of this slice in the original chunk of 8066 /// bits. 8067 /// \pre DAG != NULL. 8068 uint64_t getOffsetFromBase() const { 8069 assert(DAG && "Missing context."); 8070 bool IsBigEndian = 8071 DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian(); 8072 assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported."); 8073 uint64_t Offset = Shift / 8; 8074 unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8; 8075 assert(!(Origin->getValueSizeInBits(0) & 0x7) && 8076 "The size of the original loaded type is not a multiple of a" 8077 " byte."); 8078 // If Offset is bigger than TySizeInBytes, it means we are loading all 8079 // zeros. This should have been optimized before in the process. 8080 assert(TySizeInBytes > Offset && 8081 "Invalid shift amount for given loaded size"); 8082 if (IsBigEndian) 8083 Offset = TySizeInBytes - Offset - getLoadedSize(); 8084 return Offset; 8085 } 8086 8087 /// \brief Generate the sequence of instructions to load the slice 8088 /// represented by this object and redirect the uses of this slice to 8089 /// this new sequence of instructions. 8090 /// \pre this->Inst && this->Origin are valid Instructions and this 8091 /// object passed the legal check: LoadedSlice::isLegal returned true. 8092 /// \return The last instruction of the sequence used to load the slice. 8093 SDValue loadSlice() const { 8094 assert(Inst && Origin && "Unable to replace a non-existing slice."); 8095 const SDValue &OldBaseAddr = Origin->getBasePtr(); 8096 SDValue BaseAddr = OldBaseAddr; 8097 // Get the offset in that chunk of bytes w.r.t. the endianess. 8098 int64_t Offset = static_cast<int64_t>(getOffsetFromBase()); 8099 assert(Offset >= 0 && "Offset too big to fit in int64_t!"); 8100 if (Offset) { 8101 // BaseAddr = BaseAddr + Offset. 8102 EVT ArithType = BaseAddr.getValueType(); 8103 BaseAddr = DAG->getNode(ISD::ADD, SDLoc(Origin), ArithType, BaseAddr, 8104 DAG->getConstant(Offset, ArithType)); 8105 } 8106 8107 // Create the type of the loaded slice according to its size. 8108 EVT SliceType = getLoadedType(); 8109 8110 // Create the load for the slice. 8111 SDValue LastInst = DAG->getLoad( 8112 SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr, 8113 Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(), 8114 Origin->isNonTemporal(), Origin->isInvariant(), getAlignment()); 8115 // If the final type is not the same as the loaded type, this means that 8116 // we have to pad with zero. Create a zero extend for that. 8117 EVT FinalType = Inst->getValueType(0); 8118 if (SliceType != FinalType) 8119 LastInst = 8120 DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst); 8121 return LastInst; 8122 } 8123 8124 /// \brief Check if this slice can be merged with an expensive cross register 8125 /// bank copy. E.g., 8126 /// i = load i32 8127 /// f = bitcast i32 i to float 8128 bool canMergeExpensiveCrossRegisterBankCopy() const { 8129 if (!Inst || !Inst->hasOneUse()) 8130 return false; 8131 SDNode *Use = *Inst->use_begin(); 8132 if (Use->getOpcode() != ISD::BITCAST) 8133 return false; 8134 assert(DAG && "Missing context"); 8135 const TargetLowering &TLI = DAG->getTargetLoweringInfo(); 8136 EVT ResVT = Use->getValueType(0); 8137 const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT()); 8138 const TargetRegisterClass *ArgRC = 8139 TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT()); 8140 if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT)) 8141 return false; 8142 8143 // At this point, we know that we perform a cross-register-bank copy. 8144 // Check if it is expensive. 8145 const TargetRegisterInfo *TRI = TLI.getTargetMachine().getRegisterInfo(); 8146 // Assume bitcasts are cheap, unless both register classes do not 8147 // explicitly share a common sub class. 8148 if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC)) 8149 return false; 8150 8151 // Check if it will be merged with the load. 8152 // 1. Check the alignment constraint. 8153 unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment( 8154 ResVT.getTypeForEVT(*DAG->getContext())); 8155 8156 if (RequiredAlignment > getAlignment()) 8157 return false; 8158 8159 // 2. Check that the load is a legal operation for that type. 8160 if (!TLI.isOperationLegal(ISD::LOAD, ResVT)) 8161 return false; 8162 8163 // 3. Check that we do not have a zext in the way. 8164 if (Inst->getValueType(0) != getLoadedType()) 8165 return false; 8166 8167 return true; 8168 } 8169 }; 8170 } 8171 8172 /// \brief Sorts LoadedSlice according to their offset. 8173 struct LoadedSliceSorter { 8174 bool operator()(const LoadedSlice &LHS, const LoadedSlice &RHS) { 8175 assert(LHS.Origin == RHS.Origin && "Different bases not implemented."); 8176 return LHS.getOffsetFromBase() < RHS.getOffsetFromBase(); 8177 } 8178 }; 8179 8180 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e., 8181 /// \p UsedBits looks like 0..0 1..1 0..0. 8182 static bool areUsedBitsDense(const APInt &UsedBits) { 8183 // If all the bits are one, this is dense! 8184 if (UsedBits.isAllOnesValue()) 8185 return true; 8186 8187 // Get rid of the unused bits on the right. 8188 APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros()); 8189 // Get rid of the unused bits on the left. 8190 if (NarrowedUsedBits.countLeadingZeros()) 8191 NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits()); 8192 // Check that the chunk of bits is completely used. 8193 return NarrowedUsedBits.isAllOnesValue(); 8194 } 8195 8196 /// \brief Check whether or not \p First and \p Second are next to each other 8197 /// in memory. This means that there is no hole between the bits loaded 8198 /// by \p First and the bits loaded by \p Second. 8199 static bool areSlicesNextToEachOther(const LoadedSlice &First, 8200 const LoadedSlice &Second) { 8201 assert(First.Origin == Second.Origin && First.Origin && 8202 "Unable to match different memory origins."); 8203 APInt UsedBits = First.getUsedBits(); 8204 assert((UsedBits & Second.getUsedBits()) == 0 && 8205 "Slices are not supposed to overlap."); 8206 UsedBits |= Second.getUsedBits(); 8207 return areUsedBitsDense(UsedBits); 8208 } 8209 8210 /// \brief Adjust the \p GlobalLSCost according to the target 8211 /// paring capabilities and the layout of the slices. 8212 /// \pre \p GlobalLSCost should account for at least as many loads as 8213 /// there is in the slices in \p LoadedSlices. 8214 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices, 8215 LoadedSlice::Cost &GlobalLSCost) { 8216 unsigned NumberOfSlices = LoadedSlices.size(); 8217 // If there is less than 2 elements, no pairing is possible. 8218 if (NumberOfSlices < 2) 8219 return; 8220 8221 // Sort the slices so that elements that are likely to be next to each 8222 // other in memory are next to each other in the list. 8223 std::sort(LoadedSlices.begin(), LoadedSlices.end(), LoadedSliceSorter()); 8224 const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo(); 8225 // First (resp. Second) is the first (resp. Second) potentially candidate 8226 // to be placed in a paired load. 8227 const LoadedSlice *First = NULL; 8228 const LoadedSlice *Second = NULL; 8229 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice, 8230 // Set the beginning of the pair. 8231 First = Second) { 8232 8233 Second = &LoadedSlices[CurrSlice]; 8234 8235 // If First is NULL, it means we start a new pair. 8236 // Get to the next slice. 8237 if (!First) 8238 continue; 8239 8240 EVT LoadedType = First->getLoadedType(); 8241 8242 // If the types of the slices are different, we cannot pair them. 8243 if (LoadedType != Second->getLoadedType()) 8244 continue; 8245 8246 // Check if the target supplies paired loads for this type. 8247 unsigned RequiredAlignment = 0; 8248 if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) { 8249 // move to the next pair, this type is hopeless. 8250 Second = NULL; 8251 continue; 8252 } 8253 // Check if we meet the alignment requirement. 8254 if (RequiredAlignment > First->getAlignment()) 8255 continue; 8256 8257 // Check that both loads are next to each other in memory. 8258 if (!areSlicesNextToEachOther(*First, *Second)) 8259 continue; 8260 8261 assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!"); 8262 --GlobalLSCost.Loads; 8263 // Move to the next pair. 8264 Second = NULL; 8265 } 8266 } 8267 8268 /// \brief Check the profitability of all involved LoadedSlice. 8269 /// Currently, it is considered profitable if there is exactly two 8270 /// involved slices (1) which are (2) next to each other in memory, and 8271 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3). 8272 /// 8273 /// Note: The order of the elements in \p LoadedSlices may be modified, but not 8274 /// the elements themselves. 8275 /// 8276 /// FIXME: When the cost model will be mature enough, we can relax 8277 /// constraints (1) and (2). 8278 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices, 8279 const APInt &UsedBits, bool ForCodeSize) { 8280 unsigned NumberOfSlices = LoadedSlices.size(); 8281 if (StressLoadSlicing) 8282 return NumberOfSlices > 1; 8283 8284 // Check (1). 8285 if (NumberOfSlices != 2) 8286 return false; 8287 8288 // Check (2). 8289 if (!areUsedBitsDense(UsedBits)) 8290 return false; 8291 8292 // Check (3). 8293 LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize); 8294 // The original code has one big load. 8295 OrigCost.Loads = 1; 8296 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) { 8297 const LoadedSlice &LS = LoadedSlices[CurrSlice]; 8298 // Accumulate the cost of all the slices. 8299 LoadedSlice::Cost SliceCost(LS, ForCodeSize); 8300 GlobalSlicingCost += SliceCost; 8301 8302 // Account as cost in the original configuration the gain obtained 8303 // with the current slices. 8304 OrigCost.addSliceGain(LS); 8305 } 8306 8307 // If the target supports paired load, adjust the cost accordingly. 8308 adjustCostForPairing(LoadedSlices, GlobalSlicingCost); 8309 return OrigCost > GlobalSlicingCost; 8310 } 8311 8312 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr) 8313 /// operations, split it in the various pieces being extracted. 8314 /// 8315 /// This sort of thing is introduced by SROA. 8316 /// This slicing takes care not to insert overlapping loads. 8317 /// \pre LI is a simple load (i.e., not an atomic or volatile load). 8318 bool DAGCombiner::SliceUpLoad(SDNode *N) { 8319 if (Level < AfterLegalizeDAG) 8320 return false; 8321 8322 LoadSDNode *LD = cast<LoadSDNode>(N); 8323 if (LD->isVolatile() || !ISD::isNormalLoad(LD) || 8324 !LD->getValueType(0).isInteger()) 8325 return false; 8326 8327 // Keep track of already used bits to detect overlapping values. 8328 // In that case, we will just abort the transformation. 8329 APInt UsedBits(LD->getValueSizeInBits(0), 0); 8330 8331 SmallVector<LoadedSlice, 4> LoadedSlices; 8332 8333 // Check if this load is used as several smaller chunks of bits. 8334 // Basically, look for uses in trunc or trunc(lshr) and record a new chain 8335 // of computation for each trunc. 8336 for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end(); 8337 UI != UIEnd; ++UI) { 8338 // Skip the uses of the chain. 8339 if (UI.getUse().getResNo() != 0) 8340 continue; 8341 8342 SDNode *User = *UI; 8343 unsigned Shift = 0; 8344 8345 // Check if this is a trunc(lshr). 8346 if (User->getOpcode() == ISD::SRL && User->hasOneUse() && 8347 isa<ConstantSDNode>(User->getOperand(1))) { 8348 Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue(); 8349 User = *User->use_begin(); 8350 } 8351 8352 // At this point, User is a Truncate, iff we encountered, trunc or 8353 // trunc(lshr). 8354 if (User->getOpcode() != ISD::TRUNCATE) 8355 return false; 8356 8357 // The width of the type must be a power of 2 and greater than 8-bits. 8358 // Otherwise the load cannot be represented in LLVM IR. 8359 // Moreover, if we shifted with a non-8-bits multiple, the slice 8360 // will be across several bytes. We do not support that. 8361 unsigned Width = User->getValueSizeInBits(0); 8362 if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7)) 8363 return 0; 8364 8365 // Build the slice for this chain of computations. 8366 LoadedSlice LS(User, LD, Shift, &DAG); 8367 APInt CurrentUsedBits = LS.getUsedBits(); 8368 8369 // Check if this slice overlaps with another. 8370 if ((CurrentUsedBits & UsedBits) != 0) 8371 return false; 8372 // Update the bits used globally. 8373 UsedBits |= CurrentUsedBits; 8374 8375 // Check if the new slice would be legal. 8376 if (!LS.isLegal()) 8377 return false; 8378 8379 // Record the slice. 8380 LoadedSlices.push_back(LS); 8381 } 8382 8383 // Abort slicing if it does not seem to be profitable. 8384 if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize)) 8385 return false; 8386 8387 ++SlicedLoads; 8388 8389 // Rewrite each chain to use an independent load. 8390 // By construction, each chain can be represented by a unique load. 8391 8392 // Prepare the argument for the new token factor for all the slices. 8393 SmallVector<SDValue, 8> ArgChains; 8394 for (SmallVectorImpl<LoadedSlice>::const_iterator 8395 LSIt = LoadedSlices.begin(), 8396 LSItEnd = LoadedSlices.end(); 8397 LSIt != LSItEnd; ++LSIt) { 8398 SDValue SliceInst = LSIt->loadSlice(); 8399 CombineTo(LSIt->Inst, SliceInst, true); 8400 if (SliceInst.getNode()->getOpcode() != ISD::LOAD) 8401 SliceInst = SliceInst.getOperand(0); 8402 assert(SliceInst->getOpcode() == ISD::LOAD && 8403 "It takes more than a zext to get to the loaded slice!!"); 8404 ArgChains.push_back(SliceInst.getValue(1)); 8405 } 8406 8407 SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other, 8408 &ArgChains[0], ArgChains.size()); 8409 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain); 8410 return true; 8411 } 8412 8413 /// CheckForMaskedLoad - Check to see if V is (and load (ptr), imm), where the 8414 /// load is having specific bytes cleared out. If so, return the byte size 8415 /// being masked out and the shift amount. 8416 static std::pair<unsigned, unsigned> 8417 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) { 8418 std::pair<unsigned, unsigned> Result(0, 0); 8419 8420 // Check for the structure we're looking for. 8421 if (V->getOpcode() != ISD::AND || 8422 !isa<ConstantSDNode>(V->getOperand(1)) || 8423 !ISD::isNormalLoad(V->getOperand(0).getNode())) 8424 return Result; 8425 8426 // Check the chain and pointer. 8427 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0)); 8428 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer. 8429 8430 // The store should be chained directly to the load or be an operand of a 8431 // tokenfactor. 8432 if (LD == Chain.getNode()) 8433 ; // ok. 8434 else if (Chain->getOpcode() != ISD::TokenFactor) 8435 return Result; // Fail. 8436 else { 8437 bool isOk = false; 8438 for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i) 8439 if (Chain->getOperand(i).getNode() == LD) { 8440 isOk = true; 8441 break; 8442 } 8443 if (!isOk) return Result; 8444 } 8445 8446 // This only handles simple types. 8447 if (V.getValueType() != MVT::i16 && 8448 V.getValueType() != MVT::i32 && 8449 V.getValueType() != MVT::i64) 8450 return Result; 8451 8452 // Check the constant mask. Invert it so that the bits being masked out are 8453 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits 8454 // follow the sign bit for uniformity. 8455 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue(); 8456 unsigned NotMaskLZ = countLeadingZeros(NotMask); 8457 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte. 8458 unsigned NotMaskTZ = countTrailingZeros(NotMask); 8459 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte. 8460 if (NotMaskLZ == 64) return Result; // All zero mask. 8461 8462 // See if we have a continuous run of bits. If so, we have 0*1+0* 8463 if (CountTrailingOnes_64(NotMask >> NotMaskTZ)+NotMaskTZ+NotMaskLZ != 64) 8464 return Result; 8465 8466 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64. 8467 if (V.getValueType() != MVT::i64 && NotMaskLZ) 8468 NotMaskLZ -= 64-V.getValueSizeInBits(); 8469 8470 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8; 8471 switch (MaskedBytes) { 8472 case 1: 8473 case 2: 8474 case 4: break; 8475 default: return Result; // All one mask, or 5-byte mask. 8476 } 8477 8478 // Verify that the first bit starts at a multiple of mask so that the access 8479 // is aligned the same as the access width. 8480 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result; 8481 8482 Result.first = MaskedBytes; 8483 Result.second = NotMaskTZ/8; 8484 return Result; 8485 } 8486 8487 8488 /// ShrinkLoadReplaceStoreWithStore - Check to see if IVal is something that 8489 /// provides a value as specified by MaskInfo. If so, replace the specified 8490 /// store with a narrower store of truncated IVal. 8491 static SDNode * 8492 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo, 8493 SDValue IVal, StoreSDNode *St, 8494 DAGCombiner *DC) { 8495 unsigned NumBytes = MaskInfo.first; 8496 unsigned ByteShift = MaskInfo.second; 8497 SelectionDAG &DAG = DC->getDAG(); 8498 8499 // Check to see if IVal is all zeros in the part being masked in by the 'or' 8500 // that uses this. If not, this is not a replacement. 8501 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(), 8502 ByteShift*8, (ByteShift+NumBytes)*8); 8503 if (!DAG.MaskedValueIsZero(IVal, Mask)) return 0; 8504 8505 // Check that it is legal on the target to do this. It is legal if the new 8506 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type 8507 // legalization. 8508 MVT VT = MVT::getIntegerVT(NumBytes*8); 8509 if (!DC->isTypeLegal(VT)) 8510 return 0; 8511 8512 // Okay, we can do this! Replace the 'St' store with a store of IVal that is 8513 // shifted by ByteShift and truncated down to NumBytes. 8514 if (ByteShift) 8515 IVal = DAG.getNode(ISD::SRL, SDLoc(IVal), IVal.getValueType(), IVal, 8516 DAG.getConstant(ByteShift*8, 8517 DC->getShiftAmountTy(IVal.getValueType()))); 8518 8519 // Figure out the offset for the store and the alignment of the access. 8520 unsigned StOffset; 8521 unsigned NewAlign = St->getAlignment(); 8522 8523 if (DAG.getTargetLoweringInfo().isLittleEndian()) 8524 StOffset = ByteShift; 8525 else 8526 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes; 8527 8528 SDValue Ptr = St->getBasePtr(); 8529 if (StOffset) { 8530 Ptr = DAG.getNode(ISD::ADD, SDLoc(IVal), Ptr.getValueType(), 8531 Ptr, DAG.getConstant(StOffset, Ptr.getValueType())); 8532 NewAlign = MinAlign(NewAlign, StOffset); 8533 } 8534 8535 // Truncate down to the new size. 8536 IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal); 8537 8538 ++OpsNarrowed; 8539 return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr, 8540 St->getPointerInfo().getWithOffset(StOffset), 8541 false, false, NewAlign).getNode(); 8542 } 8543 8544 8545 /// ReduceLoadOpStoreWidth - Look for sequence of load / op / store where op is 8546 /// one of 'or', 'xor', and 'and' of immediates. If 'op' is only touching some 8547 /// of the loaded bits, try narrowing the load and store if it would end up 8548 /// being a win for performance or code size. 8549 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) { 8550 StoreSDNode *ST = cast<StoreSDNode>(N); 8551 if (ST->isVolatile()) 8552 return SDValue(); 8553 8554 SDValue Chain = ST->getChain(); 8555 SDValue Value = ST->getValue(); 8556 SDValue Ptr = ST->getBasePtr(); 8557 EVT VT = Value.getValueType(); 8558 8559 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse()) 8560 return SDValue(); 8561 8562 unsigned Opc = Value.getOpcode(); 8563 8564 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst 8565 // is a byte mask indicating a consecutive number of bytes, check to see if 8566 // Y is known to provide just those bytes. If so, we try to replace the 8567 // load + replace + store sequence with a single (narrower) store, which makes 8568 // the load dead. 8569 if (Opc == ISD::OR) { 8570 std::pair<unsigned, unsigned> MaskedLoad; 8571 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain); 8572 if (MaskedLoad.first) 8573 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad, 8574 Value.getOperand(1), ST,this)) 8575 return SDValue(NewST, 0); 8576 8577 // Or is commutative, so try swapping X and Y. 8578 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain); 8579 if (MaskedLoad.first) 8580 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad, 8581 Value.getOperand(0), ST,this)) 8582 return SDValue(NewST, 0); 8583 } 8584 8585 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) || 8586 Value.getOperand(1).getOpcode() != ISD::Constant) 8587 return SDValue(); 8588 8589 SDValue N0 = Value.getOperand(0); 8590 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() && 8591 Chain == SDValue(N0.getNode(), 1)) { 8592 LoadSDNode *LD = cast<LoadSDNode>(N0); 8593 if (LD->getBasePtr() != Ptr || 8594 LD->getPointerInfo().getAddrSpace() != 8595 ST->getPointerInfo().getAddrSpace()) 8596 return SDValue(); 8597 8598 // Find the type to narrow it the load / op / store to. 8599 SDValue N1 = Value.getOperand(1); 8600 unsigned BitWidth = N1.getValueSizeInBits(); 8601 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue(); 8602 if (Opc == ISD::AND) 8603 Imm ^= APInt::getAllOnesValue(BitWidth); 8604 if (Imm == 0 || Imm.isAllOnesValue()) 8605 return SDValue(); 8606 unsigned ShAmt = Imm.countTrailingZeros(); 8607 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1; 8608 unsigned NewBW = NextPowerOf2(MSB - ShAmt); 8609 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW); 8610 while (NewBW < BitWidth && 8611 !(TLI.isOperationLegalOrCustom(Opc, NewVT) && 8612 TLI.isNarrowingProfitable(VT, NewVT))) { 8613 NewBW = NextPowerOf2(NewBW); 8614 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW); 8615 } 8616 if (NewBW >= BitWidth) 8617 return SDValue(); 8618 8619 // If the lsb changed does not start at the type bitwidth boundary, 8620 // start at the previous one. 8621 if (ShAmt % NewBW) 8622 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW; 8623 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt, 8624 std::min(BitWidth, ShAmt + NewBW)); 8625 if ((Imm & Mask) == Imm) { 8626 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW); 8627 if (Opc == ISD::AND) 8628 NewImm ^= APInt::getAllOnesValue(NewBW); 8629 uint64_t PtrOff = ShAmt / 8; 8630 // For big endian targets, we need to adjust the offset to the pointer to 8631 // load the correct bytes. 8632 if (TLI.isBigEndian()) 8633 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff; 8634 8635 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff); 8636 Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext()); 8637 if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy)) 8638 return SDValue(); 8639 8640 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD), 8641 Ptr.getValueType(), Ptr, 8642 DAG.getConstant(PtrOff, Ptr.getValueType())); 8643 SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0), 8644 LD->getChain(), NewPtr, 8645 LD->getPointerInfo().getWithOffset(PtrOff), 8646 LD->isVolatile(), LD->isNonTemporal(), 8647 LD->isInvariant(), NewAlign, 8648 LD->getTBAAInfo()); 8649 SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD, 8650 DAG.getConstant(NewImm, NewVT)); 8651 SDValue NewST = DAG.getStore(Chain, SDLoc(N), 8652 NewVal, NewPtr, 8653 ST->getPointerInfo().getWithOffset(PtrOff), 8654 false, false, NewAlign); 8655 8656 AddToWorkList(NewPtr.getNode()); 8657 AddToWorkList(NewLD.getNode()); 8658 AddToWorkList(NewVal.getNode()); 8659 WorkListRemover DeadNodes(*this); 8660 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1)); 8661 ++OpsNarrowed; 8662 return NewST; 8663 } 8664 } 8665 8666 return SDValue(); 8667 } 8668 8669 /// TransformFPLoadStorePair - For a given floating point load / store pair, 8670 /// if the load value isn't used by any other operations, then consider 8671 /// transforming the pair to integer load / store operations if the target 8672 /// deems the transformation profitable. 8673 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) { 8674 StoreSDNode *ST = cast<StoreSDNode>(N); 8675 SDValue Chain = ST->getChain(); 8676 SDValue Value = ST->getValue(); 8677 if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) && 8678 Value.hasOneUse() && 8679 Chain == SDValue(Value.getNode(), 1)) { 8680 LoadSDNode *LD = cast<LoadSDNode>(Value); 8681 EVT VT = LD->getMemoryVT(); 8682 if (!VT.isFloatingPoint() || 8683 VT != ST->getMemoryVT() || 8684 LD->isNonTemporal() || 8685 ST->isNonTemporal() || 8686 LD->getPointerInfo().getAddrSpace() != 0 || 8687 ST->getPointerInfo().getAddrSpace() != 0) 8688 return SDValue(); 8689 8690 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits()); 8691 if (!TLI.isOperationLegal(ISD::LOAD, IntVT) || 8692 !TLI.isOperationLegal(ISD::STORE, IntVT) || 8693 !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) || 8694 !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT)) 8695 return SDValue(); 8696 8697 unsigned LDAlign = LD->getAlignment(); 8698 unsigned STAlign = ST->getAlignment(); 8699 Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext()); 8700 unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy); 8701 if (LDAlign < ABIAlign || STAlign < ABIAlign) 8702 return SDValue(); 8703 8704 SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value), 8705 LD->getChain(), LD->getBasePtr(), 8706 LD->getPointerInfo(), 8707 false, false, false, LDAlign); 8708 8709 SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N), 8710 NewLD, ST->getBasePtr(), 8711 ST->getPointerInfo(), 8712 false, false, STAlign); 8713 8714 AddToWorkList(NewLD.getNode()); 8715 AddToWorkList(NewST.getNode()); 8716 WorkListRemover DeadNodes(*this); 8717 DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1)); 8718 ++LdStFP2Int; 8719 return NewST; 8720 } 8721 8722 return SDValue(); 8723 } 8724 8725 /// Helper struct to parse and store a memory address as base + index + offset. 8726 /// We ignore sign extensions when it is safe to do so. 8727 /// The following two expressions are not equivalent. To differentiate we need 8728 /// to store whether there was a sign extension involved in the index 8729 /// computation. 8730 /// (load (i64 add (i64 copyfromreg %c) 8731 /// (i64 signextend (add (i8 load %index) 8732 /// (i8 1)))) 8733 /// vs 8734 /// 8735 /// (load (i64 add (i64 copyfromreg %c) 8736 /// (i64 signextend (i32 add (i32 signextend (i8 load %index)) 8737 /// (i32 1))))) 8738 struct BaseIndexOffset { 8739 SDValue Base; 8740 SDValue Index; 8741 int64_t Offset; 8742 bool IsIndexSignExt; 8743 8744 BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {} 8745 8746 BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset, 8747 bool IsIndexSignExt) : 8748 Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {} 8749 8750 bool equalBaseIndex(const BaseIndexOffset &Other) { 8751 return Other.Base == Base && Other.Index == Index && 8752 Other.IsIndexSignExt == IsIndexSignExt; 8753 } 8754 8755 /// Parses tree in Ptr for base, index, offset addresses. 8756 static BaseIndexOffset match(SDValue Ptr) { 8757 bool IsIndexSignExt = false; 8758 8759 // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD 8760 // instruction, then it could be just the BASE or everything else we don't 8761 // know how to handle. Just use Ptr as BASE and give up. 8762 if (Ptr->getOpcode() != ISD::ADD) 8763 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt); 8764 8765 // We know that we have at least an ADD instruction. Try to pattern match 8766 // the simple case of BASE + OFFSET. 8767 if (isa<ConstantSDNode>(Ptr->getOperand(1))) { 8768 int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue(); 8769 return BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset, 8770 IsIndexSignExt); 8771 } 8772 8773 // Inside a loop the current BASE pointer is calculated using an ADD and a 8774 // MUL instruction. In this case Ptr is the actual BASE pointer. 8775 // (i64 add (i64 %array_ptr) 8776 // (i64 mul (i64 %induction_var) 8777 // (i64 %element_size))) 8778 if (Ptr->getOperand(1)->getOpcode() == ISD::MUL) 8779 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt); 8780 8781 // Look at Base + Index + Offset cases. 8782 SDValue Base = Ptr->getOperand(0); 8783 SDValue IndexOffset = Ptr->getOperand(1); 8784 8785 // Skip signextends. 8786 if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) { 8787 IndexOffset = IndexOffset->getOperand(0); 8788 IsIndexSignExt = true; 8789 } 8790 8791 // Either the case of Base + Index (no offset) or something else. 8792 if (IndexOffset->getOpcode() != ISD::ADD) 8793 return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt); 8794 8795 // Now we have the case of Base + Index + offset. 8796 SDValue Index = IndexOffset->getOperand(0); 8797 SDValue Offset = IndexOffset->getOperand(1); 8798 8799 if (!isa<ConstantSDNode>(Offset)) 8800 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt); 8801 8802 // Ignore signextends. 8803 if (Index->getOpcode() == ISD::SIGN_EXTEND) { 8804 Index = Index->getOperand(0); 8805 IsIndexSignExt = true; 8806 } else IsIndexSignExt = false; 8807 8808 int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue(); 8809 return BaseIndexOffset(Base, Index, Off, IsIndexSignExt); 8810 } 8811 }; 8812 8813 /// Holds a pointer to an LSBaseSDNode as well as information on where it 8814 /// is located in a sequence of memory operations connected by a chain. 8815 struct MemOpLink { 8816 MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq): 8817 MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { } 8818 // Ptr to the mem node. 8819 LSBaseSDNode *MemNode; 8820 // Offset from the base ptr. 8821 int64_t OffsetFromBase; 8822 // What is the sequence number of this mem node. 8823 // Lowest mem operand in the DAG starts at zero. 8824 unsigned SequenceNum; 8825 }; 8826 8827 /// Sorts store nodes in a link according to their offset from a shared 8828 // base ptr. 8829 struct ConsecutiveMemoryChainSorter { 8830 bool operator()(MemOpLink LHS, MemOpLink RHS) { 8831 return 8832 LHS.OffsetFromBase < RHS.OffsetFromBase || 8833 (LHS.OffsetFromBase == RHS.OffsetFromBase && 8834 LHS.SequenceNum > RHS.SequenceNum); 8835 } 8836 }; 8837 8838 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) { 8839 EVT MemVT = St->getMemoryVT(); 8840 int64_t ElementSizeBytes = MemVT.getSizeInBits()/8; 8841 bool NoVectors = DAG.getMachineFunction().getFunction()->getAttributes(). 8842 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat); 8843 8844 // Don't merge vectors into wider inputs. 8845 if (MemVT.isVector() || !MemVT.isSimple()) 8846 return false; 8847 8848 // Perform an early exit check. Do not bother looking at stored values that 8849 // are not constants or loads. 8850 SDValue StoredVal = St->getValue(); 8851 bool IsLoadSrc = isa<LoadSDNode>(StoredVal); 8852 if (!isa<ConstantSDNode>(StoredVal) && !isa<ConstantFPSDNode>(StoredVal) && 8853 !IsLoadSrc) 8854 return false; 8855 8856 // Only look at ends of store sequences. 8857 SDValue Chain = SDValue(St, 1); 8858 if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE) 8859 return false; 8860 8861 // This holds the base pointer, index, and the offset in bytes from the base 8862 // pointer. 8863 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr()); 8864 8865 // We must have a base and an offset. 8866 if (!BasePtr.Base.getNode()) 8867 return false; 8868 8869 // Do not handle stores to undef base pointers. 8870 if (BasePtr.Base.getOpcode() == ISD::UNDEF) 8871 return false; 8872 8873 // Save the LoadSDNodes that we find in the chain. 8874 // We need to make sure that these nodes do not interfere with 8875 // any of the store nodes. 8876 SmallVector<LSBaseSDNode*, 8> AliasLoadNodes; 8877 8878 // Save the StoreSDNodes that we find in the chain. 8879 SmallVector<MemOpLink, 8> StoreNodes; 8880 8881 // Walk up the chain and look for nodes with offsets from the same 8882 // base pointer. Stop when reaching an instruction with a different kind 8883 // or instruction which has a different base pointer. 8884 unsigned Seq = 0; 8885 StoreSDNode *Index = St; 8886 while (Index) { 8887 // If the chain has more than one use, then we can't reorder the mem ops. 8888 if (Index != St && !SDValue(Index, 1)->hasOneUse()) 8889 break; 8890 8891 // Find the base pointer and offset for this memory node. 8892 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr()); 8893 8894 // Check that the base pointer is the same as the original one. 8895 if (!Ptr.equalBaseIndex(BasePtr)) 8896 break; 8897 8898 // Check that the alignment is the same. 8899 if (Index->getAlignment() != St->getAlignment()) 8900 break; 8901 8902 // The memory operands must not be volatile. 8903 if (Index->isVolatile() || Index->isIndexed()) 8904 break; 8905 8906 // No truncation. 8907 if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index)) 8908 if (St->isTruncatingStore()) 8909 break; 8910 8911 // The stored memory type must be the same. 8912 if (Index->getMemoryVT() != MemVT) 8913 break; 8914 8915 // We do not allow unaligned stores because we want to prevent overriding 8916 // stores. 8917 if (Index->getAlignment()*8 != MemVT.getSizeInBits()) 8918 break; 8919 8920 // We found a potential memory operand to merge. 8921 StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++)); 8922 8923 // Find the next memory operand in the chain. If the next operand in the 8924 // chain is a store then move up and continue the scan with the next 8925 // memory operand. If the next operand is a load save it and use alias 8926 // information to check if it interferes with anything. 8927 SDNode *NextInChain = Index->getChain().getNode(); 8928 while (1) { 8929 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) { 8930 // We found a store node. Use it for the next iteration. 8931 Index = STn; 8932 break; 8933 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) { 8934 if (Ldn->isVolatile()) { 8935 Index = NULL; 8936 break; 8937 } 8938 8939 // Save the load node for later. Continue the scan. 8940 AliasLoadNodes.push_back(Ldn); 8941 NextInChain = Ldn->getChain().getNode(); 8942 continue; 8943 } else { 8944 Index = NULL; 8945 break; 8946 } 8947 } 8948 } 8949 8950 // Check if there is anything to merge. 8951 if (StoreNodes.size() < 2) 8952 return false; 8953 8954 // Sort the memory operands according to their distance from the base pointer. 8955 std::sort(StoreNodes.begin(), StoreNodes.end(), 8956 ConsecutiveMemoryChainSorter()); 8957 8958 // Scan the memory operations on the chain and find the first non-consecutive 8959 // store memory address. 8960 unsigned LastConsecutiveStore = 0; 8961 int64_t StartAddress = StoreNodes[0].OffsetFromBase; 8962 for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) { 8963 8964 // Check that the addresses are consecutive starting from the second 8965 // element in the list of stores. 8966 if (i > 0) { 8967 int64_t CurrAddress = StoreNodes[i].OffsetFromBase; 8968 if (CurrAddress - StartAddress != (ElementSizeBytes * i)) 8969 break; 8970 } 8971 8972 bool Alias = false; 8973 // Check if this store interferes with any of the loads that we found. 8974 for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld) 8975 if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) { 8976 Alias = true; 8977 break; 8978 } 8979 // We found a load that alias with this store. Stop the sequence. 8980 if (Alias) 8981 break; 8982 8983 // Mark this node as useful. 8984 LastConsecutiveStore = i; 8985 } 8986 8987 // The node with the lowest store address. 8988 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode; 8989 8990 // Store the constants into memory as one consecutive store. 8991 if (!IsLoadSrc) { 8992 unsigned LastLegalType = 0; 8993 unsigned LastLegalVectorType = 0; 8994 bool NonZero = false; 8995 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) { 8996 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 8997 SDValue StoredVal = St->getValue(); 8998 8999 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) { 9000 NonZero |= !C->isNullValue(); 9001 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) { 9002 NonZero |= !C->getConstantFPValue()->isNullValue(); 9003 } else { 9004 // Non-constant. 9005 break; 9006 } 9007 9008 // Find a legal type for the constant store. 9009 unsigned StoreBW = (i+1) * ElementSizeBytes * 8; 9010 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW); 9011 if (TLI.isTypeLegal(StoreTy)) 9012 LastLegalType = i+1; 9013 // Or check whether a truncstore is legal. 9014 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) == 9015 TargetLowering::TypePromoteInteger) { 9016 EVT LegalizedStoredValueTy = 9017 TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType()); 9018 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy)) 9019 LastLegalType = i+1; 9020 } 9021 9022 // Find a legal type for the vector store. 9023 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1); 9024 if (TLI.isTypeLegal(Ty)) 9025 LastLegalVectorType = i + 1; 9026 } 9027 9028 // We only use vectors if the constant is known to be zero and the 9029 // function is not marked with the noimplicitfloat attribute. 9030 if (NonZero || NoVectors) 9031 LastLegalVectorType = 0; 9032 9033 // Check if we found a legal integer type to store. 9034 if (LastLegalType == 0 && LastLegalVectorType == 0) 9035 return false; 9036 9037 bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors; 9038 unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType; 9039 9040 // Make sure we have something to merge. 9041 if (NumElem < 2) 9042 return false; 9043 9044 unsigned EarliestNodeUsed = 0; 9045 for (unsigned i=0; i < NumElem; ++i) { 9046 // Find a chain for the new wide-store operand. Notice that some 9047 // of the store nodes that we found may not be selected for inclusion 9048 // in the wide store. The chain we use needs to be the chain of the 9049 // earliest store node which is *used* and replaced by the wide store. 9050 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum) 9051 EarliestNodeUsed = i; 9052 } 9053 9054 // The earliest Node in the DAG. 9055 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode; 9056 SDLoc DL(StoreNodes[0].MemNode); 9057 9058 SDValue StoredVal; 9059 if (UseVector) { 9060 // Find a legal type for the vector store. 9061 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem); 9062 assert(TLI.isTypeLegal(Ty) && "Illegal vector store"); 9063 StoredVal = DAG.getConstant(0, Ty); 9064 } else { 9065 unsigned StoreBW = NumElem * ElementSizeBytes * 8; 9066 APInt StoreInt(StoreBW, 0); 9067 9068 // Construct a single integer constant which is made of the smaller 9069 // constant inputs. 9070 bool IsLE = TLI.isLittleEndian(); 9071 for (unsigned i = 0; i < NumElem ; ++i) { 9072 unsigned Idx = IsLE ?(NumElem - 1 - i) : i; 9073 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[Idx].MemNode); 9074 SDValue Val = St->getValue(); 9075 StoreInt<<=ElementSizeBytes*8; 9076 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) { 9077 StoreInt|=C->getAPIntValue().zext(StoreBW); 9078 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) { 9079 StoreInt|= C->getValueAPF().bitcastToAPInt().zext(StoreBW); 9080 } else { 9081 assert(false && "Invalid constant element type"); 9082 } 9083 } 9084 9085 // Create the new Load and Store operations. 9086 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW); 9087 StoredVal = DAG.getConstant(StoreInt, StoreTy); 9088 } 9089 9090 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), DL, StoredVal, 9091 FirstInChain->getBasePtr(), 9092 FirstInChain->getPointerInfo(), 9093 false, false, 9094 FirstInChain->getAlignment()); 9095 9096 // Replace the first store with the new store 9097 CombineTo(EarliestOp, NewStore); 9098 // Erase all other stores. 9099 for (unsigned i = 0; i < NumElem ; ++i) { 9100 if (StoreNodes[i].MemNode == EarliestOp) 9101 continue; 9102 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 9103 // ReplaceAllUsesWith will replace all uses that existed when it was 9104 // called, but graph optimizations may cause new ones to appear. For 9105 // example, the case in pr14333 looks like 9106 // 9107 // St's chain -> St -> another store -> X 9108 // 9109 // And the only difference from St to the other store is the chain. 9110 // When we change it's chain to be St's chain they become identical, 9111 // get CSEed and the net result is that X is now a use of St. 9112 // Since we know that St is redundant, just iterate. 9113 while (!St->use_empty()) 9114 DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain()); 9115 removeFromWorkList(St); 9116 DAG.DeleteNode(St); 9117 } 9118 9119 return true; 9120 } 9121 9122 // Below we handle the case of multiple consecutive stores that 9123 // come from multiple consecutive loads. We merge them into a single 9124 // wide load and a single wide store. 9125 9126 // Look for load nodes which are used by the stored values. 9127 SmallVector<MemOpLink, 8> LoadNodes; 9128 9129 // Find acceptable loads. Loads need to have the same chain (token factor), 9130 // must not be zext, volatile, indexed, and they must be consecutive. 9131 BaseIndexOffset LdBasePtr; 9132 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) { 9133 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 9134 LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue()); 9135 if (!Ld) break; 9136 9137 // Loads must only have one use. 9138 if (!Ld->hasNUsesOfValue(1, 0)) 9139 break; 9140 9141 // Check that the alignment is the same as the stores. 9142 if (Ld->getAlignment() != St->getAlignment()) 9143 break; 9144 9145 // The memory operands must not be volatile. 9146 if (Ld->isVolatile() || Ld->isIndexed()) 9147 break; 9148 9149 // We do not accept ext loads. 9150 if (Ld->getExtensionType() != ISD::NON_EXTLOAD) 9151 break; 9152 9153 // The stored memory type must be the same. 9154 if (Ld->getMemoryVT() != MemVT) 9155 break; 9156 9157 BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr()); 9158 // If this is not the first ptr that we check. 9159 if (LdBasePtr.Base.getNode()) { 9160 // The base ptr must be the same. 9161 if (!LdPtr.equalBaseIndex(LdBasePtr)) 9162 break; 9163 } else { 9164 // Check that all other base pointers are the same as this one. 9165 LdBasePtr = LdPtr; 9166 } 9167 9168 // We found a potential memory operand to merge. 9169 LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0)); 9170 } 9171 9172 if (LoadNodes.size() < 2) 9173 return false; 9174 9175 // Scan the memory operations on the chain and find the first non-consecutive 9176 // load memory address. These variables hold the index in the store node 9177 // array. 9178 unsigned LastConsecutiveLoad = 0; 9179 // This variable refers to the size and not index in the array. 9180 unsigned LastLegalVectorType = 0; 9181 unsigned LastLegalIntegerType = 0; 9182 StartAddress = LoadNodes[0].OffsetFromBase; 9183 SDValue FirstChain = LoadNodes[0].MemNode->getChain(); 9184 for (unsigned i = 1; i < LoadNodes.size(); ++i) { 9185 // All loads much share the same chain. 9186 if (LoadNodes[i].MemNode->getChain() != FirstChain) 9187 break; 9188 9189 int64_t CurrAddress = LoadNodes[i].OffsetFromBase; 9190 if (CurrAddress - StartAddress != (ElementSizeBytes * i)) 9191 break; 9192 LastConsecutiveLoad = i; 9193 9194 // Find a legal type for the vector store. 9195 EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1); 9196 if (TLI.isTypeLegal(StoreTy)) 9197 LastLegalVectorType = i + 1; 9198 9199 // Find a legal type for the integer store. 9200 unsigned StoreBW = (i+1) * ElementSizeBytes * 8; 9201 StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW); 9202 if (TLI.isTypeLegal(StoreTy)) 9203 LastLegalIntegerType = i + 1; 9204 // Or check whether a truncstore and extload is legal. 9205 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) == 9206 TargetLowering::TypePromoteInteger) { 9207 EVT LegalizedStoredValueTy = 9208 TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy); 9209 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) && 9210 TLI.isLoadExtLegal(ISD::ZEXTLOAD, StoreTy) && 9211 TLI.isLoadExtLegal(ISD::SEXTLOAD, StoreTy) && 9212 TLI.isLoadExtLegal(ISD::EXTLOAD, StoreTy)) 9213 LastLegalIntegerType = i+1; 9214 } 9215 } 9216 9217 // Only use vector types if the vector type is larger than the integer type. 9218 // If they are the same, use integers. 9219 bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors; 9220 unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType); 9221 9222 // We add +1 here because the LastXXX variables refer to location while 9223 // the NumElem refers to array/index size. 9224 unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1; 9225 NumElem = std::min(LastLegalType, NumElem); 9226 9227 if (NumElem < 2) 9228 return false; 9229 9230 // The earliest Node in the DAG. 9231 unsigned EarliestNodeUsed = 0; 9232 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode; 9233 for (unsigned i=1; i<NumElem; ++i) { 9234 // Find a chain for the new wide-store operand. Notice that some 9235 // of the store nodes that we found may not be selected for inclusion 9236 // in the wide store. The chain we use needs to be the chain of the 9237 // earliest store node which is *used* and replaced by the wide store. 9238 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum) 9239 EarliestNodeUsed = i; 9240 } 9241 9242 // Find if it is better to use vectors or integers to load and store 9243 // to memory. 9244 EVT JointMemOpVT; 9245 if (UseVectorTy) { 9246 JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem); 9247 } else { 9248 unsigned StoreBW = NumElem * ElementSizeBytes * 8; 9249 JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW); 9250 } 9251 9252 SDLoc LoadDL(LoadNodes[0].MemNode); 9253 SDLoc StoreDL(StoreNodes[0].MemNode); 9254 9255 LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode); 9256 SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL, 9257 FirstLoad->getChain(), 9258 FirstLoad->getBasePtr(), 9259 FirstLoad->getPointerInfo(), 9260 false, false, false, 9261 FirstLoad->getAlignment()); 9262 9263 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), StoreDL, NewLoad, 9264 FirstInChain->getBasePtr(), 9265 FirstInChain->getPointerInfo(), false, false, 9266 FirstInChain->getAlignment()); 9267 9268 // Replace one of the loads with the new load. 9269 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode); 9270 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), 9271 SDValue(NewLoad.getNode(), 1)); 9272 9273 // Remove the rest of the load chains. 9274 for (unsigned i = 1; i < NumElem ; ++i) { 9275 // Replace all chain users of the old load nodes with the chain of the new 9276 // load node. 9277 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode); 9278 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain()); 9279 } 9280 9281 // Replace the first store with the new store. 9282 CombineTo(EarliestOp, NewStore); 9283 // Erase all other stores. 9284 for (unsigned i = 0; i < NumElem ; ++i) { 9285 // Remove all Store nodes. 9286 if (StoreNodes[i].MemNode == EarliestOp) 9287 continue; 9288 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 9289 DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain()); 9290 removeFromWorkList(St); 9291 DAG.DeleteNode(St); 9292 } 9293 9294 return true; 9295 } 9296 9297 SDValue DAGCombiner::visitSTORE(SDNode *N) { 9298 StoreSDNode *ST = cast<StoreSDNode>(N); 9299 SDValue Chain = ST->getChain(); 9300 SDValue Value = ST->getValue(); 9301 SDValue Ptr = ST->getBasePtr(); 9302 9303 // If this is a store of a bit convert, store the input value if the 9304 // resultant store does not need a higher alignment than the original. 9305 if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() && 9306 ST->isUnindexed()) { 9307 unsigned OrigAlign = ST->getAlignment(); 9308 EVT SVT = Value.getOperand(0).getValueType(); 9309 unsigned Align = TLI.getDataLayout()-> 9310 getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext())); 9311 if (Align <= OrigAlign && 9312 ((!LegalOperations && !ST->isVolatile()) || 9313 TLI.isOperationLegalOrCustom(ISD::STORE, SVT))) 9314 return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0), 9315 Ptr, ST->getPointerInfo(), ST->isVolatile(), 9316 ST->isNonTemporal(), OrigAlign, 9317 ST->getTBAAInfo()); 9318 } 9319 9320 // Turn 'store undef, Ptr' -> nothing. 9321 if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed()) 9322 return Chain; 9323 9324 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr' 9325 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) { 9326 // NOTE: If the original store is volatile, this transform must not increase 9327 // the number of stores. For example, on x86-32 an f64 can be stored in one 9328 // processor operation but an i64 (which is not legal) requires two. So the 9329 // transform should not be done in this case. 9330 if (Value.getOpcode() != ISD::TargetConstantFP) { 9331 SDValue Tmp; 9332 switch (CFP->getSimpleValueType(0).SimpleTy) { 9333 default: llvm_unreachable("Unknown FP type"); 9334 case MVT::f16: // We don't do this for these yet. 9335 case MVT::f80: 9336 case MVT::f128: 9337 case MVT::ppcf128: 9338 break; 9339 case MVT::f32: 9340 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) || 9341 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) { 9342 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF(). 9343 bitcastToAPInt().getZExtValue(), MVT::i32); 9344 return DAG.getStore(Chain, SDLoc(N), Tmp, 9345 Ptr, ST->getMemOperand()); 9346 } 9347 break; 9348 case MVT::f64: 9349 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations && 9350 !ST->isVolatile()) || 9351 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) { 9352 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt(). 9353 getZExtValue(), MVT::i64); 9354 return DAG.getStore(Chain, SDLoc(N), Tmp, 9355 Ptr, ST->getMemOperand()); 9356 } 9357 9358 if (!ST->isVolatile() && 9359 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) { 9360 // Many FP stores are not made apparent until after legalize, e.g. for 9361 // argument passing. Since this is so common, custom legalize the 9362 // 64-bit integer store into two 32-bit stores. 9363 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue(); 9364 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32); 9365 SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32); 9366 if (TLI.isBigEndian()) std::swap(Lo, Hi); 9367 9368 unsigned Alignment = ST->getAlignment(); 9369 bool isVolatile = ST->isVolatile(); 9370 bool isNonTemporal = ST->isNonTemporal(); 9371 const MDNode *TBAAInfo = ST->getTBAAInfo(); 9372 9373 SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo, 9374 Ptr, ST->getPointerInfo(), 9375 isVolatile, isNonTemporal, 9376 ST->getAlignment(), TBAAInfo); 9377 Ptr = DAG.getNode(ISD::ADD, SDLoc(N), Ptr.getValueType(), Ptr, 9378 DAG.getConstant(4, Ptr.getValueType())); 9379 Alignment = MinAlign(Alignment, 4U); 9380 SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi, 9381 Ptr, ST->getPointerInfo().getWithOffset(4), 9382 isVolatile, isNonTemporal, 9383 Alignment, TBAAInfo); 9384 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, 9385 St0, St1); 9386 } 9387 9388 break; 9389 } 9390 } 9391 } 9392 9393 // Try to infer better alignment information than the store already has. 9394 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) { 9395 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) { 9396 if (Align > ST->getAlignment()) 9397 return DAG.getTruncStore(Chain, SDLoc(N), Value, 9398 Ptr, ST->getPointerInfo(), ST->getMemoryVT(), 9399 ST->isVolatile(), ST->isNonTemporal(), Align, 9400 ST->getTBAAInfo()); 9401 } 9402 } 9403 9404 // Try transforming a pair floating point load / store ops to integer 9405 // load / store ops. 9406 SDValue NewST = TransformFPLoadStorePair(N); 9407 if (NewST.getNode()) 9408 return NewST; 9409 9410 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA : 9411 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA(); 9412 #ifndef NDEBUG 9413 if (CombinerAAOnlyFunc.getNumOccurrences() && 9414 CombinerAAOnlyFunc != DAG.getMachineFunction().getName()) 9415 UseAA = false; 9416 #endif 9417 if (UseAA && ST->isUnindexed()) { 9418 // Walk up chain skipping non-aliasing memory nodes. 9419 SDValue BetterChain = FindBetterChain(N, Chain); 9420 9421 // If there is a better chain. 9422 if (Chain != BetterChain) { 9423 SDValue ReplStore; 9424 9425 // Replace the chain to avoid dependency. 9426 if (ST->isTruncatingStore()) { 9427 ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr, 9428 ST->getMemoryVT(), ST->getMemOperand()); 9429 } else { 9430 ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr, 9431 ST->getMemOperand()); 9432 } 9433 9434 // Create token to keep both nodes around. 9435 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N), 9436 MVT::Other, Chain, ReplStore); 9437 9438 // Make sure the new and old chains are cleaned up. 9439 AddToWorkList(Token.getNode()); 9440 9441 // Don't add users to work list. 9442 return CombineTo(N, Token, false); 9443 } 9444 } 9445 9446 // Try transforming N to an indexed store. 9447 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N)) 9448 return SDValue(N, 0); 9449 9450 // FIXME: is there such a thing as a truncating indexed store? 9451 if (ST->isTruncatingStore() && ST->isUnindexed() && 9452 Value.getValueType().isInteger()) { 9453 // See if we can simplify the input to this truncstore with knowledge that 9454 // only the low bits are being used. For example: 9455 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8" 9456 SDValue Shorter = 9457 GetDemandedBits(Value, 9458 APInt::getLowBitsSet( 9459 Value.getValueType().getScalarType().getSizeInBits(), 9460 ST->getMemoryVT().getScalarType().getSizeInBits())); 9461 AddToWorkList(Value.getNode()); 9462 if (Shorter.getNode()) 9463 return DAG.getTruncStore(Chain, SDLoc(N), Shorter, 9464 Ptr, ST->getMemoryVT(), ST->getMemOperand()); 9465 9466 // Otherwise, see if we can simplify the operation with 9467 // SimplifyDemandedBits, which only works if the value has a single use. 9468 if (SimplifyDemandedBits(Value, 9469 APInt::getLowBitsSet( 9470 Value.getValueType().getScalarType().getSizeInBits(), 9471 ST->getMemoryVT().getScalarType().getSizeInBits()))) 9472 return SDValue(N, 0); 9473 } 9474 9475 // If this is a load followed by a store to the same location, then the store 9476 // is dead/noop. 9477 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) { 9478 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() && 9479 ST->isUnindexed() && !ST->isVolatile() && 9480 // There can't be any side effects between the load and store, such as 9481 // a call or store. 9482 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) { 9483 // The store is dead, remove it. 9484 return Chain; 9485 } 9486 } 9487 9488 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a 9489 // truncating store. We can do this even if this is already a truncstore. 9490 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE) 9491 && Value.getNode()->hasOneUse() && ST->isUnindexed() && 9492 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(), 9493 ST->getMemoryVT())) { 9494 return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0), 9495 Ptr, ST->getMemoryVT(), ST->getMemOperand()); 9496 } 9497 9498 // Only perform this optimization before the types are legal, because we 9499 // don't want to perform this optimization on every DAGCombine invocation. 9500 if (!LegalTypes) { 9501 bool EverChanged = false; 9502 9503 do { 9504 // There can be multiple store sequences on the same chain. 9505 // Keep trying to merge store sequences until we are unable to do so 9506 // or until we merge the last store on the chain. 9507 bool Changed = MergeConsecutiveStores(ST); 9508 EverChanged |= Changed; 9509 if (!Changed) break; 9510 } while (ST->getOpcode() != ISD::DELETED_NODE); 9511 9512 if (EverChanged) 9513 return SDValue(N, 0); 9514 } 9515 9516 return ReduceLoadOpStoreWidth(N); 9517 } 9518 9519 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) { 9520 SDValue InVec = N->getOperand(0); 9521 SDValue InVal = N->getOperand(1); 9522 SDValue EltNo = N->getOperand(2); 9523 SDLoc dl(N); 9524 9525 // If the inserted element is an UNDEF, just use the input vector. 9526 if (InVal.getOpcode() == ISD::UNDEF) 9527 return InVec; 9528 9529 EVT VT = InVec.getValueType(); 9530 9531 // If we can't generate a legal BUILD_VECTOR, exit 9532 if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT)) 9533 return SDValue(); 9534 9535 // Check that we know which element is being inserted 9536 if (!isa<ConstantSDNode>(EltNo)) 9537 return SDValue(); 9538 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue(); 9539 9540 // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially 9541 // be converted to a BUILD_VECTOR). Fill in the Ops vector with the 9542 // vector elements. 9543 SmallVector<SDValue, 8> Ops; 9544 // Do not combine these two vectors if the output vector will not replace 9545 // the input vector. 9546 if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) { 9547 Ops.append(InVec.getNode()->op_begin(), 9548 InVec.getNode()->op_end()); 9549 } else if (InVec.getOpcode() == ISD::UNDEF) { 9550 unsigned NElts = VT.getVectorNumElements(); 9551 Ops.append(NElts, DAG.getUNDEF(InVal.getValueType())); 9552 } else { 9553 return SDValue(); 9554 } 9555 9556 // Insert the element 9557 if (Elt < Ops.size()) { 9558 // All the operands of BUILD_VECTOR must have the same type; 9559 // we enforce that here. 9560 EVT OpVT = Ops[0].getValueType(); 9561 if (InVal.getValueType() != OpVT) 9562 InVal = OpVT.bitsGT(InVal.getValueType()) ? 9563 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) : 9564 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal); 9565 Ops[Elt] = InVal; 9566 } 9567 9568 // Return the new vector 9569 return DAG.getNode(ISD::BUILD_VECTOR, dl, 9570 VT, &Ops[0], Ops.size()); 9571 } 9572 9573 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) { 9574 // (vextract (scalar_to_vector val, 0) -> val 9575 SDValue InVec = N->getOperand(0); 9576 EVT VT = InVec.getValueType(); 9577 EVT NVT = N->getValueType(0); 9578 9579 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) { 9580 // Check if the result type doesn't match the inserted element type. A 9581 // SCALAR_TO_VECTOR may truncate the inserted element and the 9582 // EXTRACT_VECTOR_ELT may widen the extracted vector. 9583 SDValue InOp = InVec.getOperand(0); 9584 if (InOp.getValueType() != NVT) { 9585 assert(InOp.getValueType().isInteger() && NVT.isInteger()); 9586 return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT); 9587 } 9588 return InOp; 9589 } 9590 9591 SDValue EltNo = N->getOperand(1); 9592 bool ConstEltNo = isa<ConstantSDNode>(EltNo); 9593 9594 // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT. 9595 // We only perform this optimization before the op legalization phase because 9596 // we may introduce new vector instructions which are not backed by TD 9597 // patterns. For example on AVX, extracting elements from a wide vector 9598 // without using extract_subvector. 9599 if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE 9600 && ConstEltNo && !LegalOperations) { 9601 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue(); 9602 int NumElem = VT.getVectorNumElements(); 9603 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec); 9604 // Find the new index to extract from. 9605 int OrigElt = SVOp->getMaskElt(Elt); 9606 9607 // Extracting an undef index is undef. 9608 if (OrigElt == -1) 9609 return DAG.getUNDEF(NVT); 9610 9611 // Select the right vector half to extract from. 9612 if (OrigElt < NumElem) { 9613 InVec = InVec->getOperand(0); 9614 } else { 9615 InVec = InVec->getOperand(1); 9616 OrigElt -= NumElem; 9617 } 9618 9619 EVT IndexTy = TLI.getVectorIdxTy(); 9620 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT, 9621 InVec, DAG.getConstant(OrigElt, IndexTy)); 9622 } 9623 9624 // Perform only after legalization to ensure build_vector / vector_shuffle 9625 // optimizations have already been done. 9626 if (!LegalOperations) return SDValue(); 9627 9628 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size) 9629 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size) 9630 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr) 9631 9632 if (ConstEltNo) { 9633 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue(); 9634 bool NewLoad = false; 9635 bool BCNumEltsChanged = false; 9636 EVT ExtVT = VT.getVectorElementType(); 9637 EVT LVT = ExtVT; 9638 9639 // If the result of load has to be truncated, then it's not necessarily 9640 // profitable. 9641 if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT)) 9642 return SDValue(); 9643 9644 if (InVec.getOpcode() == ISD::BITCAST) { 9645 // Don't duplicate a load with other uses. 9646 if (!InVec.hasOneUse()) 9647 return SDValue(); 9648 9649 EVT BCVT = InVec.getOperand(0).getValueType(); 9650 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType())) 9651 return SDValue(); 9652 if (VT.getVectorNumElements() != BCVT.getVectorNumElements()) 9653 BCNumEltsChanged = true; 9654 InVec = InVec.getOperand(0); 9655 ExtVT = BCVT.getVectorElementType(); 9656 NewLoad = true; 9657 } 9658 9659 LoadSDNode *LN0 = NULL; 9660 const ShuffleVectorSDNode *SVN = NULL; 9661 if (ISD::isNormalLoad(InVec.getNode())) { 9662 LN0 = cast<LoadSDNode>(InVec); 9663 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR && 9664 InVec.getOperand(0).getValueType() == ExtVT && 9665 ISD::isNormalLoad(InVec.getOperand(0).getNode())) { 9666 // Don't duplicate a load with other uses. 9667 if (!InVec.hasOneUse()) 9668 return SDValue(); 9669 9670 LN0 = cast<LoadSDNode>(InVec.getOperand(0)); 9671 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) { 9672 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1) 9673 // => 9674 // (load $addr+1*size) 9675 9676 // Don't duplicate a load with other uses. 9677 if (!InVec.hasOneUse()) 9678 return SDValue(); 9679 9680 // If the bit convert changed the number of elements, it is unsafe 9681 // to examine the mask. 9682 if (BCNumEltsChanged) 9683 return SDValue(); 9684 9685 // Select the input vector, guarding against out of range extract vector. 9686 unsigned NumElems = VT.getVectorNumElements(); 9687 int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt); 9688 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1); 9689 9690 if (InVec.getOpcode() == ISD::BITCAST) { 9691 // Don't duplicate a load with other uses. 9692 if (!InVec.hasOneUse()) 9693 return SDValue(); 9694 9695 InVec = InVec.getOperand(0); 9696 } 9697 if (ISD::isNormalLoad(InVec.getNode())) { 9698 LN0 = cast<LoadSDNode>(InVec); 9699 Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems; 9700 } 9701 } 9702 9703 // Make sure we found a non-volatile load and the extractelement is 9704 // the only use. 9705 if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile()) 9706 return SDValue(); 9707 9708 // If Idx was -1 above, Elt is going to be -1, so just return undef. 9709 if (Elt == -1) 9710 return DAG.getUNDEF(LVT); 9711 9712 unsigned Align = LN0->getAlignment(); 9713 if (NewLoad) { 9714 // Check the resultant load doesn't need a higher alignment than the 9715 // original load. 9716 unsigned NewAlign = 9717 TLI.getDataLayout() 9718 ->getABITypeAlignment(LVT.getTypeForEVT(*DAG.getContext())); 9719 9720 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, LVT)) 9721 return SDValue(); 9722 9723 Align = NewAlign; 9724 } 9725 9726 SDValue NewPtr = LN0->getBasePtr(); 9727 unsigned PtrOff = 0; 9728 9729 if (Elt) { 9730 PtrOff = LVT.getSizeInBits() * Elt / 8; 9731 EVT PtrType = NewPtr.getValueType(); 9732 if (TLI.isBigEndian()) 9733 PtrOff = VT.getSizeInBits() / 8 - PtrOff; 9734 NewPtr = DAG.getNode(ISD::ADD, SDLoc(N), PtrType, NewPtr, 9735 DAG.getConstant(PtrOff, PtrType)); 9736 } 9737 9738 // The replacement we need to do here is a little tricky: we need to 9739 // replace an extractelement of a load with a load. 9740 // Use ReplaceAllUsesOfValuesWith to do the replacement. 9741 // Note that this replacement assumes that the extractvalue is the only 9742 // use of the load; that's okay because we don't want to perform this 9743 // transformation in other cases anyway. 9744 SDValue Load; 9745 SDValue Chain; 9746 if (NVT.bitsGT(LVT)) { 9747 // If the result type of vextract is wider than the load, then issue an 9748 // extending load instead. 9749 ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, LVT) 9750 ? ISD::ZEXTLOAD : ISD::EXTLOAD; 9751 Load = DAG.getExtLoad(ExtType, SDLoc(N), NVT, LN0->getChain(), 9752 NewPtr, LN0->getPointerInfo().getWithOffset(PtrOff), 9753 LVT, LN0->isVolatile(), LN0->isNonTemporal(), 9754 Align, LN0->getTBAAInfo()); 9755 Chain = Load.getValue(1); 9756 } else { 9757 Load = DAG.getLoad(LVT, SDLoc(N), LN0->getChain(), NewPtr, 9758 LN0->getPointerInfo().getWithOffset(PtrOff), 9759 LN0->isVolatile(), LN0->isNonTemporal(), 9760 LN0->isInvariant(), Align, LN0->getTBAAInfo()); 9761 Chain = Load.getValue(1); 9762 if (NVT.bitsLT(LVT)) 9763 Load = DAG.getNode(ISD::TRUNCATE, SDLoc(N), NVT, Load); 9764 else 9765 Load = DAG.getNode(ISD::BITCAST, SDLoc(N), NVT, Load); 9766 } 9767 WorkListRemover DeadNodes(*this); 9768 SDValue From[] = { SDValue(N, 0), SDValue(LN0,1) }; 9769 SDValue To[] = { Load, Chain }; 9770 DAG.ReplaceAllUsesOfValuesWith(From, To, 2); 9771 // Since we're explcitly calling ReplaceAllUses, add the new node to the 9772 // worklist explicitly as well. 9773 AddToWorkList(Load.getNode()); 9774 AddUsersToWorkList(Load.getNode()); // Add users too 9775 // Make sure to revisit this node to clean it up; it will usually be dead. 9776 AddToWorkList(N); 9777 return SDValue(N, 0); 9778 } 9779 9780 return SDValue(); 9781 } 9782 9783 // Simplify (build_vec (ext )) to (bitcast (build_vec )) 9784 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) { 9785 // We perform this optimization post type-legalization because 9786 // the type-legalizer often scalarizes integer-promoted vectors. 9787 // Performing this optimization before may create bit-casts which 9788 // will be type-legalized to complex code sequences. 9789 // We perform this optimization only before the operation legalizer because we 9790 // may introduce illegal operations. 9791 if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes) 9792 return SDValue(); 9793 9794 unsigned NumInScalars = N->getNumOperands(); 9795 SDLoc dl(N); 9796 EVT VT = N->getValueType(0); 9797 9798 // Check to see if this is a BUILD_VECTOR of a bunch of values 9799 // which come from any_extend or zero_extend nodes. If so, we can create 9800 // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR 9801 // optimizations. We do not handle sign-extend because we can't fill the sign 9802 // using shuffles. 9803 EVT SourceType = MVT::Other; 9804 bool AllAnyExt = true; 9805 9806 for (unsigned i = 0; i != NumInScalars; ++i) { 9807 SDValue In = N->getOperand(i); 9808 // Ignore undef inputs. 9809 if (In.getOpcode() == ISD::UNDEF) continue; 9810 9811 bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND; 9812 bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND; 9813 9814 // Abort if the element is not an extension. 9815 if (!ZeroExt && !AnyExt) { 9816 SourceType = MVT::Other; 9817 break; 9818 } 9819 9820 // The input is a ZeroExt or AnyExt. Check the original type. 9821 EVT InTy = In.getOperand(0).getValueType(); 9822 9823 // Check that all of the widened source types are the same. 9824 if (SourceType == MVT::Other) 9825 // First time. 9826 SourceType = InTy; 9827 else if (InTy != SourceType) { 9828 // Multiple income types. Abort. 9829 SourceType = MVT::Other; 9830 break; 9831 } 9832 9833 // Check if all of the extends are ANY_EXTENDs. 9834 AllAnyExt &= AnyExt; 9835 } 9836 9837 // In order to have valid types, all of the inputs must be extended from the 9838 // same source type and all of the inputs must be any or zero extend. 9839 // Scalar sizes must be a power of two. 9840 EVT OutScalarTy = VT.getScalarType(); 9841 bool ValidTypes = SourceType != MVT::Other && 9842 isPowerOf2_32(OutScalarTy.getSizeInBits()) && 9843 isPowerOf2_32(SourceType.getSizeInBits()); 9844 9845 // Create a new simpler BUILD_VECTOR sequence which other optimizations can 9846 // turn into a single shuffle instruction. 9847 if (!ValidTypes) 9848 return SDValue(); 9849 9850 bool isLE = TLI.isLittleEndian(); 9851 unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits(); 9852 assert(ElemRatio > 1 && "Invalid element size ratio"); 9853 SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType): 9854 DAG.getConstant(0, SourceType); 9855 9856 unsigned NewBVElems = ElemRatio * VT.getVectorNumElements(); 9857 SmallVector<SDValue, 8> Ops(NewBVElems, Filler); 9858 9859 // Populate the new build_vector 9860 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 9861 SDValue Cast = N->getOperand(i); 9862 assert((Cast.getOpcode() == ISD::ANY_EXTEND || 9863 Cast.getOpcode() == ISD::ZERO_EXTEND || 9864 Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode"); 9865 SDValue In; 9866 if (Cast.getOpcode() == ISD::UNDEF) 9867 In = DAG.getUNDEF(SourceType); 9868 else 9869 In = Cast->getOperand(0); 9870 unsigned Index = isLE ? (i * ElemRatio) : 9871 (i * ElemRatio + (ElemRatio - 1)); 9872 9873 assert(Index < Ops.size() && "Invalid index"); 9874 Ops[Index] = In; 9875 } 9876 9877 // The type of the new BUILD_VECTOR node. 9878 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems); 9879 assert(VecVT.getSizeInBits() == VT.getSizeInBits() && 9880 "Invalid vector size"); 9881 // Check if the new vector type is legal. 9882 if (!isTypeLegal(VecVT)) return SDValue(); 9883 9884 // Make the new BUILD_VECTOR. 9885 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, &Ops[0], Ops.size()); 9886 9887 // The new BUILD_VECTOR node has the potential to be further optimized. 9888 AddToWorkList(BV.getNode()); 9889 // Bitcast to the desired type. 9890 return DAG.getNode(ISD::BITCAST, dl, VT, BV); 9891 } 9892 9893 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) { 9894 EVT VT = N->getValueType(0); 9895 9896 unsigned NumInScalars = N->getNumOperands(); 9897 SDLoc dl(N); 9898 9899 EVT SrcVT = MVT::Other; 9900 unsigned Opcode = ISD::DELETED_NODE; 9901 unsigned NumDefs = 0; 9902 9903 for (unsigned i = 0; i != NumInScalars; ++i) { 9904 SDValue In = N->getOperand(i); 9905 unsigned Opc = In.getOpcode(); 9906 9907 if (Opc == ISD::UNDEF) 9908 continue; 9909 9910 // If all scalar values are floats and converted from integers. 9911 if (Opcode == ISD::DELETED_NODE && 9912 (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) { 9913 Opcode = Opc; 9914 } 9915 9916 if (Opc != Opcode) 9917 return SDValue(); 9918 9919 EVT InVT = In.getOperand(0).getValueType(); 9920 9921 // If all scalar values are typed differently, bail out. It's chosen to 9922 // simplify BUILD_VECTOR of integer types. 9923 if (SrcVT == MVT::Other) 9924 SrcVT = InVT; 9925 if (SrcVT != InVT) 9926 return SDValue(); 9927 NumDefs++; 9928 } 9929 9930 // If the vector has just one element defined, it's not worth to fold it into 9931 // a vectorized one. 9932 if (NumDefs < 2) 9933 return SDValue(); 9934 9935 assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP) 9936 && "Should only handle conversion from integer to float."); 9937 assert(SrcVT != MVT::Other && "Cannot determine source type!"); 9938 9939 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars); 9940 9941 if (!TLI.isOperationLegalOrCustom(Opcode, NVT)) 9942 return SDValue(); 9943 9944 SmallVector<SDValue, 8> Opnds; 9945 for (unsigned i = 0; i != NumInScalars; ++i) { 9946 SDValue In = N->getOperand(i); 9947 9948 if (In.getOpcode() == ISD::UNDEF) 9949 Opnds.push_back(DAG.getUNDEF(SrcVT)); 9950 else 9951 Opnds.push_back(In.getOperand(0)); 9952 } 9953 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, 9954 &Opnds[0], Opnds.size()); 9955 AddToWorkList(BV.getNode()); 9956 9957 return DAG.getNode(Opcode, dl, VT, BV); 9958 } 9959 9960 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) { 9961 unsigned NumInScalars = N->getNumOperands(); 9962 SDLoc dl(N); 9963 EVT VT = N->getValueType(0); 9964 9965 // A vector built entirely of undefs is undef. 9966 if (ISD::allOperandsUndef(N)) 9967 return DAG.getUNDEF(VT); 9968 9969 SDValue V = reduceBuildVecExtToExtBuildVec(N); 9970 if (V.getNode()) 9971 return V; 9972 9973 V = reduceBuildVecConvertToConvertBuildVec(N); 9974 if (V.getNode()) 9975 return V; 9976 9977 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT 9978 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from 9979 // at most two distinct vectors, turn this into a shuffle node. 9980 9981 // May only combine to shuffle after legalize if shuffle is legal. 9982 if (LegalOperations && 9983 !TLI.isOperationLegalOrCustom(ISD::VECTOR_SHUFFLE, VT)) 9984 return SDValue(); 9985 9986 SDValue VecIn1, VecIn2; 9987 for (unsigned i = 0; i != NumInScalars; ++i) { 9988 // Ignore undef inputs. 9989 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue; 9990 9991 // If this input is something other than a EXTRACT_VECTOR_ELT with a 9992 // constant index, bail out. 9993 if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT || 9994 !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) { 9995 VecIn1 = VecIn2 = SDValue(0, 0); 9996 break; 9997 } 9998 9999 // We allow up to two distinct input vectors. 10000 SDValue ExtractedFromVec = N->getOperand(i).getOperand(0); 10001 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2) 10002 continue; 10003 10004 if (VecIn1.getNode() == 0) { 10005 VecIn1 = ExtractedFromVec; 10006 } else if (VecIn2.getNode() == 0) { 10007 VecIn2 = ExtractedFromVec; 10008 } else { 10009 // Too many inputs. 10010 VecIn1 = VecIn2 = SDValue(0, 0); 10011 break; 10012 } 10013 } 10014 10015 // If everything is good, we can make a shuffle operation. 10016 if (VecIn1.getNode()) { 10017 SmallVector<int, 8> Mask; 10018 for (unsigned i = 0; i != NumInScalars; ++i) { 10019 if (N->getOperand(i).getOpcode() == ISD::UNDEF) { 10020 Mask.push_back(-1); 10021 continue; 10022 } 10023 10024 // If extracting from the first vector, just use the index directly. 10025 SDValue Extract = N->getOperand(i); 10026 SDValue ExtVal = Extract.getOperand(1); 10027 if (Extract.getOperand(0) == VecIn1) { 10028 unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue(); 10029 if (ExtIndex > VT.getVectorNumElements()) 10030 return SDValue(); 10031 10032 Mask.push_back(ExtIndex); 10033 continue; 10034 } 10035 10036 // Otherwise, use InIdx + VecSize 10037 unsigned Idx = cast<ConstantSDNode>(ExtVal)->getZExtValue(); 10038 Mask.push_back(Idx+NumInScalars); 10039 } 10040 10041 // We can't generate a shuffle node with mismatched input and output types. 10042 // Attempt to transform a single input vector to the correct type. 10043 if ((VT != VecIn1.getValueType())) { 10044 // We don't support shuffeling between TWO values of different types. 10045 if (VecIn2.getNode() != 0) 10046 return SDValue(); 10047 10048 // We only support widening of vectors which are half the size of the 10049 // output registers. For example XMM->YMM widening on X86 with AVX. 10050 if (VecIn1.getValueType().getSizeInBits()*2 != VT.getSizeInBits()) 10051 return SDValue(); 10052 10053 // If the input vector type has a different base type to the output 10054 // vector type, bail out. 10055 if (VecIn1.getValueType().getVectorElementType() != 10056 VT.getVectorElementType()) 10057 return SDValue(); 10058 10059 // Widen the input vector by adding undef values. 10060 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, 10061 VecIn1, DAG.getUNDEF(VecIn1.getValueType())); 10062 } 10063 10064 // If VecIn2 is unused then change it to undef. 10065 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT); 10066 10067 // Check that we were able to transform all incoming values to the same 10068 // type. 10069 if (VecIn2.getValueType() != VecIn1.getValueType() || 10070 VecIn1.getValueType() != VT) 10071 return SDValue(); 10072 10073 // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes. 10074 if (!isTypeLegal(VT)) 10075 return SDValue(); 10076 10077 // Return the new VECTOR_SHUFFLE node. 10078 SDValue Ops[2]; 10079 Ops[0] = VecIn1; 10080 Ops[1] = VecIn2; 10081 return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]); 10082 } 10083 10084 return SDValue(); 10085 } 10086 10087 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) { 10088 // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of 10089 // EXTRACT_SUBVECTOR operations. If so, and if the EXTRACT_SUBVECTOR vector 10090 // inputs come from at most two distinct vectors, turn this into a shuffle 10091 // node. 10092 10093 // If we only have one input vector, we don't need to do any concatenation. 10094 if (N->getNumOperands() == 1) 10095 return N->getOperand(0); 10096 10097 // Check if all of the operands are undefs. 10098 EVT VT = N->getValueType(0); 10099 if (ISD::allOperandsUndef(N)) 10100 return DAG.getUNDEF(VT); 10101 10102 // Optimize concat_vectors where one of the vectors is undef. 10103 if (N->getNumOperands() == 2 && 10104 N->getOperand(1)->getOpcode() == ISD::UNDEF) { 10105 SDValue In = N->getOperand(0); 10106 assert(In.getValueType().isVector() && "Must concat vectors"); 10107 10108 // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr). 10109 if (In->getOpcode() == ISD::BITCAST && 10110 !In->getOperand(0)->getValueType(0).isVector()) { 10111 SDValue Scalar = In->getOperand(0); 10112 EVT SclTy = Scalar->getValueType(0); 10113 10114 if (!SclTy.isFloatingPoint() && !SclTy.isInteger()) 10115 return SDValue(); 10116 10117 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy, 10118 VT.getSizeInBits() / SclTy.getSizeInBits()); 10119 if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType())) 10120 return SDValue(); 10121 10122 SDLoc dl = SDLoc(N); 10123 SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar); 10124 return DAG.getNode(ISD::BITCAST, dl, VT, Res); 10125 } 10126 } 10127 10128 // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR 10129 // nodes often generate nop CONCAT_VECTOR nodes. 10130 // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that 10131 // place the incoming vectors at the exact same location. 10132 SDValue SingleSource = SDValue(); 10133 unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements(); 10134 10135 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 10136 SDValue Op = N->getOperand(i); 10137 10138 if (Op.getOpcode() == ISD::UNDEF) 10139 continue; 10140 10141 // Check if this is the identity extract: 10142 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR) 10143 return SDValue(); 10144 10145 // Find the single incoming vector for the extract_subvector. 10146 if (SingleSource.getNode()) { 10147 if (Op.getOperand(0) != SingleSource) 10148 return SDValue(); 10149 } else { 10150 SingleSource = Op.getOperand(0); 10151 10152 // Check the source type is the same as the type of the result. 10153 // If not, this concat may extend the vector, so we can not 10154 // optimize it away. 10155 if (SingleSource.getValueType() != N->getValueType(0)) 10156 return SDValue(); 10157 } 10158 10159 unsigned IdentityIndex = i * PartNumElem; 10160 ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 10161 // The extract index must be constant. 10162 if (!CS) 10163 return SDValue(); 10164 10165 // Check that we are reading from the identity index. 10166 if (CS->getZExtValue() != IdentityIndex) 10167 return SDValue(); 10168 } 10169 10170 if (SingleSource.getNode()) 10171 return SingleSource; 10172 10173 return SDValue(); 10174 } 10175 10176 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) { 10177 EVT NVT = N->getValueType(0); 10178 SDValue V = N->getOperand(0); 10179 10180 if (V->getOpcode() == ISD::CONCAT_VECTORS) { 10181 // Combine: 10182 // (extract_subvec (concat V1, V2, ...), i) 10183 // Into: 10184 // Vi if possible 10185 // Only operand 0 is checked as 'concat' assumes all inputs of the same 10186 // type. 10187 if (V->getOperand(0).getValueType() != NVT) 10188 return SDValue(); 10189 unsigned Idx = dyn_cast<ConstantSDNode>(N->getOperand(1))->getZExtValue(); 10190 unsigned NumElems = NVT.getVectorNumElements(); 10191 assert((Idx % NumElems) == 0 && 10192 "IDX in concat is not a multiple of the result vector length."); 10193 return V->getOperand(Idx / NumElems); 10194 } 10195 10196 // Skip bitcasting 10197 if (V->getOpcode() == ISD::BITCAST) 10198 V = V.getOperand(0); 10199 10200 if (V->getOpcode() == ISD::INSERT_SUBVECTOR) { 10201 SDLoc dl(N); 10202 // Handle only simple case where vector being inserted and vector 10203 // being extracted are of same type, and are half size of larger vectors. 10204 EVT BigVT = V->getOperand(0).getValueType(); 10205 EVT SmallVT = V->getOperand(1).getValueType(); 10206 if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits()) 10207 return SDValue(); 10208 10209 // Only handle cases where both indexes are constants with the same type. 10210 ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1)); 10211 ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2)); 10212 10213 if (InsIdx && ExtIdx && 10214 InsIdx->getValueType(0).getSizeInBits() <= 64 && 10215 ExtIdx->getValueType(0).getSizeInBits() <= 64) { 10216 // Combine: 10217 // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx) 10218 // Into: 10219 // indices are equal or bit offsets are equal => V1 10220 // otherwise => (extract_subvec V1, ExtIdx) 10221 if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() == 10222 ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits()) 10223 return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1)); 10224 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT, 10225 DAG.getNode(ISD::BITCAST, dl, 10226 N->getOperand(0).getValueType(), 10227 V->getOperand(0)), N->getOperand(1)); 10228 } 10229 } 10230 10231 return SDValue(); 10232 } 10233 10234 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat. 10235 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) { 10236 EVT VT = N->getValueType(0); 10237 unsigned NumElts = VT.getVectorNumElements(); 10238 10239 SDValue N0 = N->getOperand(0); 10240 SDValue N1 = N->getOperand(1); 10241 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N); 10242 10243 SmallVector<SDValue, 4> Ops; 10244 EVT ConcatVT = N0.getOperand(0).getValueType(); 10245 unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements(); 10246 unsigned NumConcats = NumElts / NumElemsPerConcat; 10247 10248 // Look at every vector that's inserted. We're looking for exact 10249 // subvector-sized copies from a concatenated vector 10250 for (unsigned I = 0; I != NumConcats; ++I) { 10251 // Make sure we're dealing with a copy. 10252 unsigned Begin = I * NumElemsPerConcat; 10253 bool AllUndef = true, NoUndef = true; 10254 for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) { 10255 if (SVN->getMaskElt(J) >= 0) 10256 AllUndef = false; 10257 else 10258 NoUndef = false; 10259 } 10260 10261 if (NoUndef) { 10262 if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0) 10263 return SDValue(); 10264 10265 for (unsigned J = 1; J != NumElemsPerConcat; ++J) 10266 if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J)) 10267 return SDValue(); 10268 10269 unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat; 10270 if (FirstElt < N0.getNumOperands()) 10271 Ops.push_back(N0.getOperand(FirstElt)); 10272 else 10273 Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands())); 10274 10275 } else if (AllUndef) { 10276 Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType())); 10277 } else { // Mixed with general masks and undefs, can't do optimization. 10278 return SDValue(); 10279 } 10280 } 10281 10282 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops.data(), 10283 Ops.size()); 10284 } 10285 10286 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) { 10287 EVT VT = N->getValueType(0); 10288 unsigned NumElts = VT.getVectorNumElements(); 10289 10290 SDValue N0 = N->getOperand(0); 10291 SDValue N1 = N->getOperand(1); 10292 10293 assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG"); 10294 10295 // Canonicalize shuffle undef, undef -> undef 10296 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF) 10297 return DAG.getUNDEF(VT); 10298 10299 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N); 10300 10301 // Canonicalize shuffle v, v -> v, undef 10302 if (N0 == N1) { 10303 SmallVector<int, 8> NewMask; 10304 for (unsigned i = 0; i != NumElts; ++i) { 10305 int Idx = SVN->getMaskElt(i); 10306 if (Idx >= (int)NumElts) Idx -= NumElts; 10307 NewMask.push_back(Idx); 10308 } 10309 return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT), 10310 &NewMask[0]); 10311 } 10312 10313 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask. 10314 if (N0.getOpcode() == ISD::UNDEF) { 10315 SmallVector<int, 8> NewMask; 10316 for (unsigned i = 0; i != NumElts; ++i) { 10317 int Idx = SVN->getMaskElt(i); 10318 if (Idx >= 0) { 10319 if (Idx >= (int)NumElts) 10320 Idx -= NumElts; 10321 else 10322 Idx = -1; // remove reference to lhs 10323 } 10324 NewMask.push_back(Idx); 10325 } 10326 return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT), 10327 &NewMask[0]); 10328 } 10329 10330 // Remove references to rhs if it is undef 10331 if (N1.getOpcode() == ISD::UNDEF) { 10332 bool Changed = false; 10333 SmallVector<int, 8> NewMask; 10334 for (unsigned i = 0; i != NumElts; ++i) { 10335 int Idx = SVN->getMaskElt(i); 10336 if (Idx >= (int)NumElts) { 10337 Idx = -1; 10338 Changed = true; 10339 } 10340 NewMask.push_back(Idx); 10341 } 10342 if (Changed) 10343 return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]); 10344 } 10345 10346 // If it is a splat, check if the argument vector is another splat or a 10347 // build_vector with all scalar elements the same. 10348 if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) { 10349 SDNode *V = N0.getNode(); 10350 10351 // If this is a bit convert that changes the element type of the vector but 10352 // not the number of vector elements, look through it. Be careful not to 10353 // look though conversions that change things like v4f32 to v2f64. 10354 if (V->getOpcode() == ISD::BITCAST) { 10355 SDValue ConvInput = V->getOperand(0); 10356 if (ConvInput.getValueType().isVector() && 10357 ConvInput.getValueType().getVectorNumElements() == NumElts) 10358 V = ConvInput.getNode(); 10359 } 10360 10361 if (V->getOpcode() == ISD::BUILD_VECTOR) { 10362 assert(V->getNumOperands() == NumElts && 10363 "BUILD_VECTOR has wrong number of operands"); 10364 SDValue Base; 10365 bool AllSame = true; 10366 for (unsigned i = 0; i != NumElts; ++i) { 10367 if (V->getOperand(i).getOpcode() != ISD::UNDEF) { 10368 Base = V->getOperand(i); 10369 break; 10370 } 10371 } 10372 // Splat of <u, u, u, u>, return <u, u, u, u> 10373 if (!Base.getNode()) 10374 return N0; 10375 for (unsigned i = 0; i != NumElts; ++i) { 10376 if (V->getOperand(i) != Base) { 10377 AllSame = false; 10378 break; 10379 } 10380 } 10381 // Splat of <x, x, x, x>, return <x, x, x, x> 10382 if (AllSame) 10383 return N0; 10384 } 10385 } 10386 10387 if (N0.getOpcode() == ISD::CONCAT_VECTORS && 10388 Level < AfterLegalizeVectorOps && 10389 (N1.getOpcode() == ISD::UNDEF || 10390 (N1.getOpcode() == ISD::CONCAT_VECTORS && 10391 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) { 10392 SDValue V = partitionShuffleOfConcats(N, DAG); 10393 10394 if (V.getNode()) 10395 return V; 10396 } 10397 10398 // If this shuffle node is simply a swizzle of another shuffle node, 10399 // and it reverses the swizzle of the previous shuffle then we can 10400 // optimize shuffle(shuffle(x, undef), undef) -> x. 10401 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG && 10402 N1.getOpcode() == ISD::UNDEF) { 10403 10404 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0); 10405 10406 // Shuffle nodes can only reverse shuffles with a single non-undef value. 10407 if (N0.getOperand(1).getOpcode() != ISD::UNDEF) 10408 return SDValue(); 10409 10410 // The incoming shuffle must be of the same type as the result of the 10411 // current shuffle. 10412 assert(OtherSV->getOperand(0).getValueType() == VT && 10413 "Shuffle types don't match"); 10414 10415 for (unsigned i = 0; i != NumElts; ++i) { 10416 int Idx = SVN->getMaskElt(i); 10417 assert(Idx < (int)NumElts && "Index references undef operand"); 10418 // Next, this index comes from the first value, which is the incoming 10419 // shuffle. Adopt the incoming index. 10420 if (Idx >= 0) 10421 Idx = OtherSV->getMaskElt(Idx); 10422 10423 // The combined shuffle must map each index to itself. 10424 if (Idx >= 0 && (unsigned)Idx != i) 10425 return SDValue(); 10426 } 10427 10428 return OtherSV->getOperand(0); 10429 } 10430 10431 return SDValue(); 10432 } 10433 10434 /// XformToShuffleWithZero - Returns a vector_shuffle if it able to transform 10435 /// an AND to a vector_shuffle with the destination vector and a zero vector. 10436 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==> 10437 /// vector_shuffle V, Zero, <0, 4, 2, 4> 10438 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) { 10439 EVT VT = N->getValueType(0); 10440 SDLoc dl(N); 10441 SDValue LHS = N->getOperand(0); 10442 SDValue RHS = N->getOperand(1); 10443 if (N->getOpcode() == ISD::AND) { 10444 if (RHS.getOpcode() == ISD::BITCAST) 10445 RHS = RHS.getOperand(0); 10446 if (RHS.getOpcode() == ISD::BUILD_VECTOR) { 10447 SmallVector<int, 8> Indices; 10448 unsigned NumElts = RHS.getNumOperands(); 10449 for (unsigned i = 0; i != NumElts; ++i) { 10450 SDValue Elt = RHS.getOperand(i); 10451 if (!isa<ConstantSDNode>(Elt)) 10452 return SDValue(); 10453 10454 if (cast<ConstantSDNode>(Elt)->isAllOnesValue()) 10455 Indices.push_back(i); 10456 else if (cast<ConstantSDNode>(Elt)->isNullValue()) 10457 Indices.push_back(NumElts); 10458 else 10459 return SDValue(); 10460 } 10461 10462 // Let's see if the target supports this vector_shuffle. 10463 EVT RVT = RHS.getValueType(); 10464 if (!TLI.isVectorClearMaskLegal(Indices, RVT)) 10465 return SDValue(); 10466 10467 // Return the new VECTOR_SHUFFLE node. 10468 EVT EltVT = RVT.getVectorElementType(); 10469 SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(), 10470 DAG.getConstant(0, EltVT)); 10471 SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), 10472 RVT, &ZeroOps[0], ZeroOps.size()); 10473 LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS); 10474 SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]); 10475 return DAG.getNode(ISD::BITCAST, dl, VT, Shuf); 10476 } 10477 } 10478 10479 return SDValue(); 10480 } 10481 10482 /// SimplifyVBinOp - Visit a binary vector operation, like ADD. 10483 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) { 10484 assert(N->getValueType(0).isVector() && 10485 "SimplifyVBinOp only works on vectors!"); 10486 10487 SDValue LHS = N->getOperand(0); 10488 SDValue RHS = N->getOperand(1); 10489 SDValue Shuffle = XformToShuffleWithZero(N); 10490 if (Shuffle.getNode()) return Shuffle; 10491 10492 // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold 10493 // this operation. 10494 if (LHS.getOpcode() == ISD::BUILD_VECTOR && 10495 RHS.getOpcode() == ISD::BUILD_VECTOR) { 10496 // Check if both vectors are constants. If not bail out. 10497 if (!(cast<BuildVectorSDNode>(LHS)->isConstant() && 10498 cast<BuildVectorSDNode>(RHS)->isConstant())) 10499 return SDValue(); 10500 10501 SmallVector<SDValue, 8> Ops; 10502 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) { 10503 SDValue LHSOp = LHS.getOperand(i); 10504 SDValue RHSOp = RHS.getOperand(i); 10505 10506 // Can't fold divide by zero. 10507 if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV || 10508 N->getOpcode() == ISD::FDIV) { 10509 if ((RHSOp.getOpcode() == ISD::Constant && 10510 cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) || 10511 (RHSOp.getOpcode() == ISD::ConstantFP && 10512 cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero())) 10513 break; 10514 } 10515 10516 EVT VT = LHSOp.getValueType(); 10517 EVT RVT = RHSOp.getValueType(); 10518 if (RVT != VT) { 10519 // Integer BUILD_VECTOR operands may have types larger than the element 10520 // size (e.g., when the element type is not legal). Prior to type 10521 // legalization, the types may not match between the two BUILD_VECTORS. 10522 // Truncate one of the operands to make them match. 10523 if (RVT.getSizeInBits() > VT.getSizeInBits()) { 10524 RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp); 10525 } else { 10526 LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp); 10527 VT = RVT; 10528 } 10529 } 10530 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT, 10531 LHSOp, RHSOp); 10532 if (FoldOp.getOpcode() != ISD::UNDEF && 10533 FoldOp.getOpcode() != ISD::Constant && 10534 FoldOp.getOpcode() != ISD::ConstantFP) 10535 break; 10536 Ops.push_back(FoldOp); 10537 AddToWorkList(FoldOp.getNode()); 10538 } 10539 10540 if (Ops.size() == LHS.getNumOperands()) 10541 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), 10542 LHS.getValueType(), &Ops[0], Ops.size()); 10543 } 10544 10545 return SDValue(); 10546 } 10547 10548 /// SimplifyVUnaryOp - Visit a binary vector operation, like FABS/FNEG. 10549 SDValue DAGCombiner::SimplifyVUnaryOp(SDNode *N) { 10550 assert(N->getValueType(0).isVector() && 10551 "SimplifyVUnaryOp only works on vectors!"); 10552 10553 SDValue N0 = N->getOperand(0); 10554 10555 if (N0.getOpcode() != ISD::BUILD_VECTOR) 10556 return SDValue(); 10557 10558 // Operand is a BUILD_VECTOR node, see if we can constant fold it. 10559 SmallVector<SDValue, 8> Ops; 10560 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) { 10561 SDValue Op = N0.getOperand(i); 10562 if (Op.getOpcode() != ISD::UNDEF && 10563 Op.getOpcode() != ISD::ConstantFP) 10564 break; 10565 EVT EltVT = Op.getValueType(); 10566 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(N0), EltVT, Op); 10567 if (FoldOp.getOpcode() != ISD::UNDEF && 10568 FoldOp.getOpcode() != ISD::ConstantFP) 10569 break; 10570 Ops.push_back(FoldOp); 10571 AddToWorkList(FoldOp.getNode()); 10572 } 10573 10574 if (Ops.size() != N0.getNumOperands()) 10575 return SDValue(); 10576 10577 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), 10578 N0.getValueType(), &Ops[0], Ops.size()); 10579 } 10580 10581 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0, 10582 SDValue N1, SDValue N2){ 10583 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!"); 10584 10585 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2, 10586 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 10587 10588 // If we got a simplified select_cc node back from SimplifySelectCC, then 10589 // break it down into a new SETCC node, and a new SELECT node, and then return 10590 // the SELECT node, since we were called with a SELECT node. 10591 if (SCC.getNode()) { 10592 // Check to see if we got a select_cc back (to turn into setcc/select). 10593 // Otherwise, just return whatever node we got back, like fabs. 10594 if (SCC.getOpcode() == ISD::SELECT_CC) { 10595 SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0), 10596 N0.getValueType(), 10597 SCC.getOperand(0), SCC.getOperand(1), 10598 SCC.getOperand(4)); 10599 AddToWorkList(SETCC.getNode()); 10600 return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), 10601 SCC.getOperand(2), SCC.getOperand(3), SETCC); 10602 } 10603 10604 return SCC; 10605 } 10606 return SDValue(); 10607 } 10608 10609 /// SimplifySelectOps - Given a SELECT or a SELECT_CC node, where LHS and RHS 10610 /// are the two values being selected between, see if we can simplify the 10611 /// select. Callers of this should assume that TheSelect is deleted if this 10612 /// returns true. As such, they should return the appropriate thing (e.g. the 10613 /// node) back to the top-level of the DAG combiner loop to avoid it being 10614 /// looked at. 10615 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS, 10616 SDValue RHS) { 10617 10618 // Cannot simplify select with vector condition 10619 if (TheSelect->getOperand(0).getValueType().isVector()) return false; 10620 10621 // If this is a select from two identical things, try to pull the operation 10622 // through the select. 10623 if (LHS.getOpcode() != RHS.getOpcode() || 10624 !LHS.hasOneUse() || !RHS.hasOneUse()) 10625 return false; 10626 10627 // If this is a load and the token chain is identical, replace the select 10628 // of two loads with a load through a select of the address to load from. 10629 // This triggers in things like "select bool X, 10.0, 123.0" after the FP 10630 // constants have been dropped into the constant pool. 10631 if (LHS.getOpcode() == ISD::LOAD) { 10632 LoadSDNode *LLD = cast<LoadSDNode>(LHS); 10633 LoadSDNode *RLD = cast<LoadSDNode>(RHS); 10634 10635 // Token chains must be identical. 10636 if (LHS.getOperand(0) != RHS.getOperand(0) || 10637 // Do not let this transformation reduce the number of volatile loads. 10638 LLD->isVolatile() || RLD->isVolatile() || 10639 // If this is an EXTLOAD, the VT's must match. 10640 LLD->getMemoryVT() != RLD->getMemoryVT() || 10641 // If this is an EXTLOAD, the kind of extension must match. 10642 (LLD->getExtensionType() != RLD->getExtensionType() && 10643 // The only exception is if one of the extensions is anyext. 10644 LLD->getExtensionType() != ISD::EXTLOAD && 10645 RLD->getExtensionType() != ISD::EXTLOAD) || 10646 // FIXME: this discards src value information. This is 10647 // over-conservative. It would be beneficial to be able to remember 10648 // both potential memory locations. Since we are discarding 10649 // src value info, don't do the transformation if the memory 10650 // locations are not in the default address space. 10651 LLD->getPointerInfo().getAddrSpace() != 0 || 10652 RLD->getPointerInfo().getAddrSpace() != 0 || 10653 !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(), 10654 LLD->getBasePtr().getValueType())) 10655 return false; 10656 10657 // Check that the select condition doesn't reach either load. If so, 10658 // folding this will induce a cycle into the DAG. If not, this is safe to 10659 // xform, so create a select of the addresses. 10660 SDValue Addr; 10661 if (TheSelect->getOpcode() == ISD::SELECT) { 10662 SDNode *CondNode = TheSelect->getOperand(0).getNode(); 10663 if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) || 10664 (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode))) 10665 return false; 10666 // The loads must not depend on one another. 10667 if (LLD->isPredecessorOf(RLD) || 10668 RLD->isPredecessorOf(LLD)) 10669 return false; 10670 Addr = DAG.getSelect(SDLoc(TheSelect), 10671 LLD->getBasePtr().getValueType(), 10672 TheSelect->getOperand(0), LLD->getBasePtr(), 10673 RLD->getBasePtr()); 10674 } else { // Otherwise SELECT_CC 10675 SDNode *CondLHS = TheSelect->getOperand(0).getNode(); 10676 SDNode *CondRHS = TheSelect->getOperand(1).getNode(); 10677 10678 if ((LLD->hasAnyUseOfValue(1) && 10679 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) || 10680 (RLD->hasAnyUseOfValue(1) && 10681 (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS)))) 10682 return false; 10683 10684 Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect), 10685 LLD->getBasePtr().getValueType(), 10686 TheSelect->getOperand(0), 10687 TheSelect->getOperand(1), 10688 LLD->getBasePtr(), RLD->getBasePtr(), 10689 TheSelect->getOperand(4)); 10690 } 10691 10692 SDValue Load; 10693 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) { 10694 Load = DAG.getLoad(TheSelect->getValueType(0), 10695 SDLoc(TheSelect), 10696 // FIXME: Discards pointer and TBAA info. 10697 LLD->getChain(), Addr, MachinePointerInfo(), 10698 LLD->isVolatile(), LLD->isNonTemporal(), 10699 LLD->isInvariant(), LLD->getAlignment()); 10700 } else { 10701 Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ? 10702 RLD->getExtensionType() : LLD->getExtensionType(), 10703 SDLoc(TheSelect), 10704 TheSelect->getValueType(0), 10705 // FIXME: Discards pointer and TBAA info. 10706 LLD->getChain(), Addr, MachinePointerInfo(), 10707 LLD->getMemoryVT(), LLD->isVolatile(), 10708 LLD->isNonTemporal(), LLD->getAlignment()); 10709 } 10710 10711 // Users of the select now use the result of the load. 10712 CombineTo(TheSelect, Load); 10713 10714 // Users of the old loads now use the new load's chain. We know the 10715 // old-load value is dead now. 10716 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1)); 10717 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1)); 10718 return true; 10719 } 10720 10721 return false; 10722 } 10723 10724 /// SimplifySelectCC - Simplify an expression of the form (N0 cond N1) ? N2 : N3 10725 /// where 'cond' is the comparison specified by CC. 10726 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, 10727 SDValue N2, SDValue N3, 10728 ISD::CondCode CC, bool NotExtCompare) { 10729 // (x ? y : y) -> y. 10730 if (N2 == N3) return N2; 10731 10732 EVT VT = N2.getValueType(); 10733 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode()); 10734 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode()); 10735 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode()); 10736 10737 // Determine if the condition we're dealing with is constant 10738 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()), 10739 N0, N1, CC, DL, false); 10740 if (SCC.getNode()) AddToWorkList(SCC.getNode()); 10741 ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode()); 10742 10743 // fold select_cc true, x, y -> x 10744 if (SCCC && !SCCC->isNullValue()) 10745 return N2; 10746 // fold select_cc false, x, y -> y 10747 if (SCCC && SCCC->isNullValue()) 10748 return N3; 10749 10750 // Check to see if we can simplify the select into an fabs node 10751 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) { 10752 // Allow either -0.0 or 0.0 10753 if (CFP->getValueAPF().isZero()) { 10754 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs 10755 if ((CC == ISD::SETGE || CC == ISD::SETGT) && 10756 N0 == N2 && N3.getOpcode() == ISD::FNEG && 10757 N2 == N3.getOperand(0)) 10758 return DAG.getNode(ISD::FABS, DL, VT, N0); 10759 10760 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs 10761 if ((CC == ISD::SETLT || CC == ISD::SETLE) && 10762 N0 == N3 && N2.getOpcode() == ISD::FNEG && 10763 N2.getOperand(0) == N3) 10764 return DAG.getNode(ISD::FABS, DL, VT, N3); 10765 } 10766 } 10767 10768 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)" 10769 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0 10770 // in it. This is a win when the constant is not otherwise available because 10771 // it replaces two constant pool loads with one. We only do this if the FP 10772 // type is known to be legal, because if it isn't, then we are before legalize 10773 // types an we want the other legalization to happen first (e.g. to avoid 10774 // messing with soft float) and if the ConstantFP is not legal, because if 10775 // it is legal, we may not need to store the FP constant in a constant pool. 10776 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2)) 10777 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) { 10778 if (TLI.isTypeLegal(N2.getValueType()) && 10779 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) != 10780 TargetLowering::Legal) && 10781 // If both constants have multiple uses, then we won't need to do an 10782 // extra load, they are likely around in registers for other users. 10783 (TV->hasOneUse() || FV->hasOneUse())) { 10784 Constant *Elts[] = { 10785 const_cast<ConstantFP*>(FV->getConstantFPValue()), 10786 const_cast<ConstantFP*>(TV->getConstantFPValue()) 10787 }; 10788 Type *FPTy = Elts[0]->getType(); 10789 const DataLayout &TD = *TLI.getDataLayout(); 10790 10791 // Create a ConstantArray of the two constants. 10792 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts); 10793 SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(), 10794 TD.getPrefTypeAlignment(FPTy)); 10795 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment(); 10796 10797 // Get the offsets to the 0 and 1 element of the array so that we can 10798 // select between them. 10799 SDValue Zero = DAG.getIntPtrConstant(0); 10800 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType()); 10801 SDValue One = DAG.getIntPtrConstant(EltSize); 10802 10803 SDValue Cond = DAG.getSetCC(DL, 10804 getSetCCResultType(N0.getValueType()), 10805 N0, N1, CC); 10806 AddToWorkList(Cond.getNode()); 10807 SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(), 10808 Cond, One, Zero); 10809 AddToWorkList(CstOffset.getNode()); 10810 CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx, 10811 CstOffset); 10812 AddToWorkList(CPIdx.getNode()); 10813 return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx, 10814 MachinePointerInfo::getConstantPool(), false, 10815 false, false, Alignment); 10816 10817 } 10818 } 10819 10820 // Check to see if we can perform the "gzip trick", transforming 10821 // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A) 10822 if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT && 10823 (N1C->isNullValue() || // (a < 0) ? b : 0 10824 (N1C->getAPIntValue() == 1 && N0 == N2))) { // (a < 1) ? a : 0 10825 EVT XType = N0.getValueType(); 10826 EVT AType = N2.getValueType(); 10827 if (XType.bitsGE(AType)) { 10828 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a 10829 // single-bit constant. 10830 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) { 10831 unsigned ShCtV = N2C->getAPIntValue().logBase2(); 10832 ShCtV = XType.getSizeInBits()-ShCtV-1; 10833 SDValue ShCt = DAG.getConstant(ShCtV, 10834 getShiftAmountTy(N0.getValueType())); 10835 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), 10836 XType, N0, ShCt); 10837 AddToWorkList(Shift.getNode()); 10838 10839 if (XType.bitsGT(AType)) { 10840 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift); 10841 AddToWorkList(Shift.getNode()); 10842 } 10843 10844 return DAG.getNode(ISD::AND, DL, AType, Shift, N2); 10845 } 10846 10847 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), 10848 XType, N0, 10849 DAG.getConstant(XType.getSizeInBits()-1, 10850 getShiftAmountTy(N0.getValueType()))); 10851 AddToWorkList(Shift.getNode()); 10852 10853 if (XType.bitsGT(AType)) { 10854 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift); 10855 AddToWorkList(Shift.getNode()); 10856 } 10857 10858 return DAG.getNode(ISD::AND, DL, AType, Shift, N2); 10859 } 10860 } 10861 10862 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A) 10863 // where y is has a single bit set. 10864 // A plaintext description would be, we can turn the SELECT_CC into an AND 10865 // when the condition can be materialized as an all-ones register. Any 10866 // single bit-test can be materialized as an all-ones register with 10867 // shift-left and shift-right-arith. 10868 if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND && 10869 N0->getValueType(0) == VT && 10870 N1C && N1C->isNullValue() && 10871 N2C && N2C->isNullValue()) { 10872 SDValue AndLHS = N0->getOperand(0); 10873 ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 10874 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) { 10875 // Shift the tested bit over the sign bit. 10876 APInt AndMask = ConstAndRHS->getAPIntValue(); 10877 SDValue ShlAmt = 10878 DAG.getConstant(AndMask.countLeadingZeros(), 10879 getShiftAmountTy(AndLHS.getValueType())); 10880 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt); 10881 10882 // Now arithmetic right shift it all the way over, so the result is either 10883 // all-ones, or zero. 10884 SDValue ShrAmt = 10885 DAG.getConstant(AndMask.getBitWidth()-1, 10886 getShiftAmountTy(Shl.getValueType())); 10887 SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt); 10888 10889 return DAG.getNode(ISD::AND, DL, VT, Shr, N3); 10890 } 10891 } 10892 10893 // fold select C, 16, 0 -> shl C, 4 10894 if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() && 10895 TLI.getBooleanContents(N0.getValueType().isVector()) == 10896 TargetLowering::ZeroOrOneBooleanContent) { 10897 10898 // If the caller doesn't want us to simplify this into a zext of a compare, 10899 // don't do it. 10900 if (NotExtCompare && N2C->getAPIntValue() == 1) 10901 return SDValue(); 10902 10903 // Get a SetCC of the condition 10904 // NOTE: Don't create a SETCC if it's not legal on this target. 10905 if (!LegalOperations || 10906 TLI.isOperationLegal(ISD::SETCC, 10907 LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) { 10908 SDValue Temp, SCC; 10909 // cast from setcc result type to select result type 10910 if (LegalTypes) { 10911 SCC = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()), 10912 N0, N1, CC); 10913 if (N2.getValueType().bitsLT(SCC.getValueType())) 10914 Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2), 10915 N2.getValueType()); 10916 else 10917 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2), 10918 N2.getValueType(), SCC); 10919 } else { 10920 SCC = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC); 10921 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2), 10922 N2.getValueType(), SCC); 10923 } 10924 10925 AddToWorkList(SCC.getNode()); 10926 AddToWorkList(Temp.getNode()); 10927 10928 if (N2C->getAPIntValue() == 1) 10929 return Temp; 10930 10931 // shl setcc result by log2 n2c 10932 return DAG.getNode( 10933 ISD::SHL, DL, N2.getValueType(), Temp, 10934 DAG.getConstant(N2C->getAPIntValue().logBase2(), 10935 getShiftAmountTy(Temp.getValueType()))); 10936 } 10937 } 10938 10939 // Check to see if this is the equivalent of setcc 10940 // FIXME: Turn all of these into setcc if setcc if setcc is legal 10941 // otherwise, go ahead with the folds. 10942 if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) { 10943 EVT XType = N0.getValueType(); 10944 if (!LegalOperations || 10945 TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) { 10946 SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC); 10947 if (Res.getValueType() != VT) 10948 Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res); 10949 return Res; 10950 } 10951 10952 // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X)))) 10953 if (N1C && N1C->isNullValue() && CC == ISD::SETEQ && 10954 (!LegalOperations || 10955 TLI.isOperationLegal(ISD::CTLZ, XType))) { 10956 SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0); 10957 return DAG.getNode(ISD::SRL, DL, XType, Ctlz, 10958 DAG.getConstant(Log2_32(XType.getSizeInBits()), 10959 getShiftAmountTy(Ctlz.getValueType()))); 10960 } 10961 // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1)) 10962 if (N1C && N1C->isNullValue() && CC == ISD::SETGT) { 10963 SDValue NegN0 = DAG.getNode(ISD::SUB, SDLoc(N0), 10964 XType, DAG.getConstant(0, XType), N0); 10965 SDValue NotN0 = DAG.getNOT(SDLoc(N0), N0, XType); 10966 return DAG.getNode(ISD::SRL, DL, XType, 10967 DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0), 10968 DAG.getConstant(XType.getSizeInBits()-1, 10969 getShiftAmountTy(XType))); 10970 } 10971 // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1)) 10972 if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) { 10973 SDValue Sign = DAG.getNode(ISD::SRL, SDLoc(N0), XType, N0, 10974 DAG.getConstant(XType.getSizeInBits()-1, 10975 getShiftAmountTy(N0.getValueType()))); 10976 return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType)); 10977 } 10978 } 10979 10980 // Check to see if this is an integer abs. 10981 // select_cc setg[te] X, 0, X, -X -> 10982 // select_cc setgt X, -1, X, -X -> 10983 // select_cc setl[te] X, 0, -X, X -> 10984 // select_cc setlt X, 1, -X, X -> 10985 // Y = sra (X, size(X)-1); xor (add (X, Y), Y) 10986 if (N1C) { 10987 ConstantSDNode *SubC = NULL; 10988 if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) || 10989 (N1C->isAllOnesValue() && CC == ISD::SETGT)) && 10990 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1)) 10991 SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0)); 10992 else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) || 10993 (N1C->isOne() && CC == ISD::SETLT)) && 10994 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1)) 10995 SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0)); 10996 10997 EVT XType = N0.getValueType(); 10998 if (SubC && SubC->isNullValue() && XType.isInteger()) { 10999 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), XType, 11000 N0, 11001 DAG.getConstant(XType.getSizeInBits()-1, 11002 getShiftAmountTy(N0.getValueType()))); 11003 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0), 11004 XType, N0, Shift); 11005 AddToWorkList(Shift.getNode()); 11006 AddToWorkList(Add.getNode()); 11007 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift); 11008 } 11009 } 11010 11011 return SDValue(); 11012 } 11013 11014 /// SimplifySetCC - This is a stub for TargetLowering::SimplifySetCC. 11015 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0, 11016 SDValue N1, ISD::CondCode Cond, 11017 SDLoc DL, bool foldBooleans) { 11018 TargetLowering::DAGCombinerInfo 11019 DagCombineInfo(DAG, Level, false, this); 11020 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL); 11021 } 11022 11023 /// BuildSDIVSequence - Given an ISD::SDIV node expressing a divide by constant, 11024 /// return a DAG expression to select that will generate the same value by 11025 /// multiplying by a magic number. See: 11026 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html> 11027 SDValue DAGCombiner::BuildSDIV(SDNode *N) { 11028 std::vector<SDNode*> Built; 11029 SDValue S = TLI.BuildSDIV(N, DAG, LegalOperations, &Built); 11030 11031 for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end(); 11032 ii != ee; ++ii) 11033 AddToWorkList(*ii); 11034 return S; 11035 } 11036 11037 /// BuildUDIVSequence - Given an ISD::UDIV node expressing a divide by constant, 11038 /// return a DAG expression to select that will generate the same value by 11039 /// multiplying by a magic number. See: 11040 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html> 11041 SDValue DAGCombiner::BuildUDIV(SDNode *N) { 11042 std::vector<SDNode*> Built; 11043 SDValue S = TLI.BuildUDIV(N, DAG, LegalOperations, &Built); 11044 11045 for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end(); 11046 ii != ee; ++ii) 11047 AddToWorkList(*ii); 11048 return S; 11049 } 11050 11051 /// FindBaseOffset - Return true if base is a frame index, which is known not 11052 // to alias with anything but itself. Provides base object and offset as 11053 // results. 11054 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset, 11055 const GlobalValue *&GV, const void *&CV) { 11056 // Assume it is a primitive operation. 11057 Base = Ptr; Offset = 0; GV = 0; CV = 0; 11058 11059 // If it's an adding a simple constant then integrate the offset. 11060 if (Base.getOpcode() == ISD::ADD) { 11061 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) { 11062 Base = Base.getOperand(0); 11063 Offset += C->getZExtValue(); 11064 } 11065 } 11066 11067 // Return the underlying GlobalValue, and update the Offset. Return false 11068 // for GlobalAddressSDNode since the same GlobalAddress may be represented 11069 // by multiple nodes with different offsets. 11070 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) { 11071 GV = G->getGlobal(); 11072 Offset += G->getOffset(); 11073 return false; 11074 } 11075 11076 // Return the underlying Constant value, and update the Offset. Return false 11077 // for ConstantSDNodes since the same constant pool entry may be represented 11078 // by multiple nodes with different offsets. 11079 if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) { 11080 CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal() 11081 : (const void *)C->getConstVal(); 11082 Offset += C->getOffset(); 11083 return false; 11084 } 11085 // If it's any of the following then it can't alias with anything but itself. 11086 return isa<FrameIndexSDNode>(Base); 11087 } 11088 11089 /// isAlias - Return true if there is any possibility that the two addresses 11090 /// overlap. 11091 bool DAGCombiner::isAlias(SDValue Ptr1, int64_t Size1, bool IsVolatile1, 11092 const Value *SrcValue1, int SrcValueOffset1, 11093 unsigned SrcValueAlign1, 11094 const MDNode *TBAAInfo1, 11095 SDValue Ptr2, int64_t Size2, bool IsVolatile2, 11096 const Value *SrcValue2, int SrcValueOffset2, 11097 unsigned SrcValueAlign2, 11098 const MDNode *TBAAInfo2) const { 11099 // If they are the same then they must be aliases. 11100 if (Ptr1 == Ptr2) return true; 11101 11102 // If they are both volatile then they cannot be reordered. 11103 if (IsVolatile1 && IsVolatile2) return true; 11104 11105 // Gather base node and offset information. 11106 SDValue Base1, Base2; 11107 int64_t Offset1, Offset2; 11108 const GlobalValue *GV1, *GV2; 11109 const void *CV1, *CV2; 11110 bool isFrameIndex1 = FindBaseOffset(Ptr1, Base1, Offset1, GV1, CV1); 11111 bool isFrameIndex2 = FindBaseOffset(Ptr2, Base2, Offset2, GV2, CV2); 11112 11113 // If they have a same base address then check to see if they overlap. 11114 if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2))) 11115 return !((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1); 11116 11117 // It is possible for different frame indices to alias each other, mostly 11118 // when tail call optimization reuses return address slots for arguments. 11119 // To catch this case, look up the actual index of frame indices to compute 11120 // the real alias relationship. 11121 if (isFrameIndex1 && isFrameIndex2) { 11122 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo(); 11123 Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex()); 11124 Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex()); 11125 return !((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1); 11126 } 11127 11128 // Otherwise, if we know what the bases are, and they aren't identical, then 11129 // we know they cannot alias. 11130 if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2)) 11131 return false; 11132 11133 // If we know required SrcValue1 and SrcValue2 have relatively large alignment 11134 // compared to the size and offset of the access, we may be able to prove they 11135 // do not alias. This check is conservative for now to catch cases created by 11136 // splitting vector types. 11137 if ((SrcValueAlign1 == SrcValueAlign2) && 11138 (SrcValueOffset1 != SrcValueOffset2) && 11139 (Size1 == Size2) && (SrcValueAlign1 > Size1)) { 11140 int64_t OffAlign1 = SrcValueOffset1 % SrcValueAlign1; 11141 int64_t OffAlign2 = SrcValueOffset2 % SrcValueAlign1; 11142 11143 // There is no overlap between these relatively aligned accesses of similar 11144 // size, return no alias. 11145 if ((OffAlign1 + Size1) <= OffAlign2 || (OffAlign2 + Size2) <= OffAlign1) 11146 return false; 11147 } 11148 11149 bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0 ? CombinerGlobalAA : 11150 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA(); 11151 #ifndef NDEBUG 11152 if (CombinerAAOnlyFunc.getNumOccurrences() && 11153 CombinerAAOnlyFunc != DAG.getMachineFunction().getName()) 11154 UseAA = false; 11155 #endif 11156 if (UseAA && SrcValue1 && SrcValue2) { 11157 // Use alias analysis information. 11158 int64_t MinOffset = std::min(SrcValueOffset1, SrcValueOffset2); 11159 int64_t Overlap1 = Size1 + SrcValueOffset1 - MinOffset; 11160 int64_t Overlap2 = Size2 + SrcValueOffset2 - MinOffset; 11161 AliasAnalysis::AliasResult AAResult = 11162 AA.alias(AliasAnalysis::Location(SrcValue1, Overlap1, 11163 UseTBAA ? TBAAInfo1 : 0), 11164 AliasAnalysis::Location(SrcValue2, Overlap2, 11165 UseTBAA ? TBAAInfo2 : 0)); 11166 if (AAResult == AliasAnalysis::NoAlias) 11167 return false; 11168 } 11169 11170 // Otherwise we have to assume they alias. 11171 return true; 11172 } 11173 11174 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) { 11175 SDValue Ptr0, Ptr1; 11176 int64_t Size0, Size1; 11177 bool IsVolatile0, IsVolatile1; 11178 const Value *SrcValue0, *SrcValue1; 11179 int SrcValueOffset0, SrcValueOffset1; 11180 unsigned SrcValueAlign0, SrcValueAlign1; 11181 const MDNode *SrcTBAAInfo0, *SrcTBAAInfo1; 11182 FindAliasInfo(Op0, Ptr0, Size0, IsVolatile0, SrcValue0, SrcValueOffset0, 11183 SrcValueAlign0, SrcTBAAInfo0); 11184 FindAliasInfo(Op1, Ptr1, Size1, IsVolatile1, SrcValue1, SrcValueOffset1, 11185 SrcValueAlign1, SrcTBAAInfo1); 11186 return isAlias(Ptr0, Size0, IsVolatile0, SrcValue0, SrcValueOffset0, 11187 SrcValueAlign0, SrcTBAAInfo0, 11188 Ptr1, Size1, IsVolatile1, SrcValue1, SrcValueOffset1, 11189 SrcValueAlign1, SrcTBAAInfo1); 11190 } 11191 11192 /// FindAliasInfo - Extracts the relevant alias information from the memory 11193 /// node. Returns true if the operand was a nonvolatile load. 11194 bool DAGCombiner::FindAliasInfo(SDNode *N, 11195 SDValue &Ptr, int64_t &Size, bool &IsVolatile, 11196 const Value *&SrcValue, 11197 int &SrcValueOffset, 11198 unsigned &SrcValueAlign, 11199 const MDNode *&TBAAInfo) const { 11200 LSBaseSDNode *LS = cast<LSBaseSDNode>(N); 11201 11202 Ptr = LS->getBasePtr(); 11203 Size = LS->getMemoryVT().getSizeInBits() >> 3; 11204 IsVolatile = LS->isVolatile(); 11205 SrcValue = LS->getSrcValue(); 11206 SrcValueOffset = LS->getSrcValueOffset(); 11207 SrcValueAlign = LS->getOriginalAlignment(); 11208 TBAAInfo = LS->getTBAAInfo(); 11209 return isa<LoadSDNode>(LS) && !IsVolatile; 11210 } 11211 11212 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes, 11213 /// looking for aliasing nodes and adding them to the Aliases vector. 11214 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain, 11215 SmallVectorImpl<SDValue> &Aliases) { 11216 SmallVector<SDValue, 8> Chains; // List of chains to visit. 11217 SmallPtrSet<SDNode *, 16> Visited; // Visited node set. 11218 11219 // Get alias information for node. 11220 SDValue Ptr; 11221 int64_t Size; 11222 bool IsVolatile; 11223 const Value *SrcValue; 11224 int SrcValueOffset; 11225 unsigned SrcValueAlign; 11226 const MDNode *SrcTBAAInfo; 11227 bool IsLoad = FindAliasInfo(N, Ptr, Size, IsVolatile, SrcValue, 11228 SrcValueOffset, SrcValueAlign, SrcTBAAInfo); 11229 11230 // Starting off. 11231 Chains.push_back(OriginalChain); 11232 unsigned Depth = 0; 11233 11234 // Look at each chain and determine if it is an alias. If so, add it to the 11235 // aliases list. If not, then continue up the chain looking for the next 11236 // candidate. 11237 while (!Chains.empty()) { 11238 SDValue Chain = Chains.back(); 11239 Chains.pop_back(); 11240 11241 // For TokenFactor nodes, look at each operand and only continue up the 11242 // chain until we find two aliases. If we've seen two aliases, assume we'll 11243 // find more and revert to original chain since the xform is unlikely to be 11244 // profitable. 11245 // 11246 // FIXME: The depth check could be made to return the last non-aliasing 11247 // chain we found before we hit a tokenfactor rather than the original 11248 // chain. 11249 if (Depth > 6 || Aliases.size() == 2) { 11250 Aliases.clear(); 11251 Aliases.push_back(OriginalChain); 11252 return; 11253 } 11254 11255 // Don't bother if we've been before. 11256 if (!Visited.insert(Chain.getNode())) 11257 continue; 11258 11259 switch (Chain.getOpcode()) { 11260 case ISD::EntryToken: 11261 // Entry token is ideal chain operand, but handled in FindBetterChain. 11262 break; 11263 11264 case ISD::LOAD: 11265 case ISD::STORE: { 11266 // Get alias information for Chain. 11267 SDValue OpPtr; 11268 int64_t OpSize; 11269 bool OpIsVolatile; 11270 const Value *OpSrcValue; 11271 int OpSrcValueOffset; 11272 unsigned OpSrcValueAlign; 11273 const MDNode *OpSrcTBAAInfo; 11274 bool IsOpLoad = FindAliasInfo(Chain.getNode(), OpPtr, OpSize, 11275 OpIsVolatile, OpSrcValue, OpSrcValueOffset, 11276 OpSrcValueAlign, 11277 OpSrcTBAAInfo); 11278 11279 // If chain is alias then stop here. 11280 if (!(IsLoad && IsOpLoad) && 11281 isAlias(Ptr, Size, IsVolatile, SrcValue, SrcValueOffset, 11282 SrcValueAlign, SrcTBAAInfo, 11283 OpPtr, OpSize, OpIsVolatile, OpSrcValue, OpSrcValueOffset, 11284 OpSrcValueAlign, OpSrcTBAAInfo)) { 11285 Aliases.push_back(Chain); 11286 } else { 11287 // Look further up the chain. 11288 Chains.push_back(Chain.getOperand(0)); 11289 ++Depth; 11290 } 11291 break; 11292 } 11293 11294 case ISD::TokenFactor: 11295 // We have to check each of the operands of the token factor for "small" 11296 // token factors, so we queue them up. Adding the operands to the queue 11297 // (stack) in reverse order maintains the original order and increases the 11298 // likelihood that getNode will find a matching token factor (CSE.) 11299 if (Chain.getNumOperands() > 16) { 11300 Aliases.push_back(Chain); 11301 break; 11302 } 11303 for (unsigned n = Chain.getNumOperands(); n;) 11304 Chains.push_back(Chain.getOperand(--n)); 11305 ++Depth; 11306 break; 11307 11308 default: 11309 // For all other instructions we will just have to take what we can get. 11310 Aliases.push_back(Chain); 11311 break; 11312 } 11313 } 11314 11315 // We need to be careful here to also search for aliases through the 11316 // value operand of a store, etc. Consider the following situation: 11317 // Token1 = ... 11318 // L1 = load Token1, %52 11319 // S1 = store Token1, L1, %51 11320 // L2 = load Token1, %52+8 11321 // S2 = store Token1, L2, %51+8 11322 // Token2 = Token(S1, S2) 11323 // L3 = load Token2, %53 11324 // S3 = store Token2, L3, %52 11325 // L4 = load Token2, %53+8 11326 // S4 = store Token2, L4, %52+8 11327 // If we search for aliases of S3 (which loads address %52), and we look 11328 // only through the chain, then we'll miss the trivial dependence on L1 11329 // (which also loads from %52). We then might change all loads and 11330 // stores to use Token1 as their chain operand, which could result in 11331 // copying %53 into %52 before copying %52 into %51 (which should 11332 // happen first). 11333 // 11334 // The problem is, however, that searching for such data dependencies 11335 // can become expensive, and the cost is not directly related to the 11336 // chain depth. Instead, we'll rule out such configurations here by 11337 // insisting that we've visited all chain users (except for users 11338 // of the original chain, which is not necessary). When doing this, 11339 // we need to look through nodes we don't care about (otherwise, things 11340 // like register copies will interfere with trivial cases). 11341 11342 SmallVector<const SDNode *, 16> Worklist; 11343 for (SmallPtrSet<SDNode *, 16>::iterator I = Visited.begin(), 11344 IE = Visited.end(); I != IE; ++I) 11345 if (*I != OriginalChain.getNode()) 11346 Worklist.push_back(*I); 11347 11348 while (!Worklist.empty()) { 11349 const SDNode *M = Worklist.pop_back_val(); 11350 11351 // We have already visited M, and want to make sure we've visited any uses 11352 // of M that we care about. For uses that we've not visisted, and don't 11353 // care about, queue them to the worklist. 11354 11355 for (SDNode::use_iterator UI = M->use_begin(), 11356 UIE = M->use_end(); UI != UIE; ++UI) 11357 if (UI.getUse().getValueType() == MVT::Other && Visited.insert(*UI)) { 11358 if (isa<MemIntrinsicSDNode>(*UI) || isa<MemSDNode>(*UI)) { 11359 // We've not visited this use, and we care about it (it could have an 11360 // ordering dependency with the original node). 11361 Aliases.clear(); 11362 Aliases.push_back(OriginalChain); 11363 return; 11364 } 11365 11366 // We've not visited this use, but we don't care about it. Mark it as 11367 // visited and enqueue it to the worklist. 11368 Worklist.push_back(*UI); 11369 } 11370 } 11371 } 11372 11373 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes, looking 11374 /// for a better chain (aliasing node.) 11375 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) { 11376 SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor. 11377 11378 // Accumulate all the aliases to this node. 11379 GatherAllAliases(N, OldChain, Aliases); 11380 11381 // If no operands then chain to entry token. 11382 if (Aliases.size() == 0) 11383 return DAG.getEntryNode(); 11384 11385 // If a single operand then chain to it. We don't need to revisit it. 11386 if (Aliases.size() == 1) 11387 return Aliases[0]; 11388 11389 // Construct a custom tailored token factor. 11390 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, 11391 &Aliases[0], Aliases.size()); 11392 } 11393 11394 // SelectionDAG::Combine - This is the entry point for the file. 11395 // 11396 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA, 11397 CodeGenOpt::Level OptLevel) { 11398 /// run - This is the main entry point to this class. 11399 /// 11400 DAGCombiner(*this, AA, OptLevel).Run(Level); 11401 } 11402