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 SDValue visitINSERT_SUBVECTOR(SDNode *N); 278 279 SDValue XformToShuffleWithZero(SDNode *N); 280 SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS); 281 282 SDValue visitShiftByConstant(SDNode *N, unsigned Amt); 283 284 bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS); 285 SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N); 286 SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2); 287 SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2, 288 SDValue N3, ISD::CondCode CC, 289 bool NotExtCompare = false); 290 SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond, 291 SDLoc DL, bool foldBooleans = true); 292 SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp, 293 unsigned HiOp); 294 SDValue CombineConsecutiveLoads(SDNode *N, EVT VT); 295 SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT); 296 SDValue BuildSDIV(SDNode *N); 297 SDValue BuildUDIV(SDNode *N); 298 SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1, 299 bool DemandHighBits = true); 300 SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1); 301 SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg, 302 SDValue InnerPos, SDValue InnerNeg, 303 unsigned PosOpcode, unsigned NegOpcode, 304 SDLoc DL); 305 SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL); 306 SDValue ReduceLoadWidth(SDNode *N); 307 SDValue ReduceLoadOpStoreWidth(SDNode *N); 308 SDValue TransformFPLoadStorePair(SDNode *N); 309 SDValue reduceBuildVecExtToExtBuildVec(SDNode *N); 310 SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N); 311 312 SDValue GetDemandedBits(SDValue V, const APInt &Mask); 313 314 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes, 315 /// looking for aliasing nodes and adding them to the Aliases vector. 316 void GatherAllAliases(SDNode *N, SDValue OriginalChain, 317 SmallVectorImpl<SDValue> &Aliases); 318 319 /// isAlias - Return true if there is any possibility that the two addresses 320 /// overlap. 321 bool isAlias(SDValue Ptr1, int64_t Size1, bool IsVolatile1, 322 const Value *SrcValue1, int SrcValueOffset1, 323 unsigned SrcValueAlign1, 324 const MDNode *TBAAInfo1, 325 SDValue Ptr2, int64_t Size2, bool IsVolatile2, 326 const Value *SrcValue2, int SrcValueOffset2, 327 unsigned SrcValueAlign2, 328 const MDNode *TBAAInfo2) const; 329 330 /// isAlias - Return true if there is any possibility that the two addresses 331 /// overlap. 332 bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1); 333 334 /// FindAliasInfo - Extracts the relevant alias information from the memory 335 /// node. Returns true if the operand was a load. 336 bool FindAliasInfo(SDNode *N, 337 SDValue &Ptr, int64_t &Size, bool &IsVolatile, 338 const Value *&SrcValue, int &SrcValueOffset, 339 unsigned &SrcValueAlignment, 340 const MDNode *&TBAAInfo) const; 341 342 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes, 343 /// looking for a better chain (aliasing node.) 344 SDValue FindBetterChain(SDNode *N, SDValue Chain); 345 346 /// Merge consecutive store operations into a wide store. 347 /// This optimization uses wide integers or vectors when possible. 348 /// \return True if some memory operations were changed. 349 bool MergeConsecutiveStores(StoreSDNode *N); 350 351 public: 352 DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL) 353 : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes), 354 OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) { 355 AttributeSet FnAttrs = 356 DAG.getMachineFunction().getFunction()->getAttributes(); 357 ForCodeSize = 358 FnAttrs.hasAttribute(AttributeSet::FunctionIndex, 359 Attribute::OptimizeForSize) || 360 FnAttrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::MinSize); 361 } 362 363 /// Run - runs the dag combiner on all nodes in the work list 364 void Run(CombineLevel AtLevel); 365 366 SelectionDAG &getDAG() const { return DAG; } 367 368 /// getShiftAmountTy - Returns a type large enough to hold any valid 369 /// shift amount - before type legalization these can be huge. 370 EVT getShiftAmountTy(EVT LHSTy) { 371 assert(LHSTy.isInteger() && "Shift amount is not an integer type!"); 372 if (LHSTy.isVector()) 373 return LHSTy; 374 return LegalTypes ? TLI.getScalarShiftAmountTy(LHSTy) 375 : TLI.getPointerTy(); 376 } 377 378 /// isTypeLegal - This method returns true if we are running before type 379 /// legalization or if the specified VT is legal. 380 bool isTypeLegal(const EVT &VT) { 381 if (!LegalTypes) return true; 382 return TLI.isTypeLegal(VT); 383 } 384 385 /// getSetCCResultType - Convenience wrapper around 386 /// TargetLowering::getSetCCResultType 387 EVT getSetCCResultType(EVT VT) const { 388 return TLI.getSetCCResultType(*DAG.getContext(), VT); 389 } 390 }; 391 } 392 393 394 namespace { 395 /// WorkListRemover - This class is a DAGUpdateListener that removes any deleted 396 /// nodes from the worklist. 397 class WorkListRemover : public SelectionDAG::DAGUpdateListener { 398 DAGCombiner &DC; 399 public: 400 explicit WorkListRemover(DAGCombiner &dc) 401 : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {} 402 403 virtual void NodeDeleted(SDNode *N, SDNode *E) { 404 DC.removeFromWorkList(N); 405 } 406 }; 407 } 408 409 //===----------------------------------------------------------------------===// 410 // TargetLowering::DAGCombinerInfo implementation 411 //===----------------------------------------------------------------------===// 412 413 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) { 414 ((DAGCombiner*)DC)->AddToWorkList(N); 415 } 416 417 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) { 418 ((DAGCombiner*)DC)->removeFromWorkList(N); 419 } 420 421 SDValue TargetLowering::DAGCombinerInfo:: 422 CombineTo(SDNode *N, const std::vector<SDValue> &To, bool AddTo) { 423 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo); 424 } 425 426 SDValue TargetLowering::DAGCombinerInfo:: 427 CombineTo(SDNode *N, SDValue Res, bool AddTo) { 428 return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo); 429 } 430 431 432 SDValue TargetLowering::DAGCombinerInfo:: 433 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) { 434 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo); 435 } 436 437 void TargetLowering::DAGCombinerInfo:: 438 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) { 439 return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO); 440 } 441 442 //===----------------------------------------------------------------------===// 443 // Helper Functions 444 //===----------------------------------------------------------------------===// 445 446 /// isNegatibleForFree - Return 1 if we can compute the negated form of the 447 /// specified expression for the same cost as the expression itself, or 2 if we 448 /// can compute the negated form more cheaply than the expression itself. 449 static char isNegatibleForFree(SDValue Op, bool LegalOperations, 450 const TargetLowering &TLI, 451 const TargetOptions *Options, 452 unsigned Depth = 0) { 453 // fneg is removable even if it has multiple uses. 454 if (Op.getOpcode() == ISD::FNEG) return 2; 455 456 // Don't allow anything with multiple uses. 457 if (!Op.hasOneUse()) return 0; 458 459 // Don't recurse exponentially. 460 if (Depth > 6) return 0; 461 462 switch (Op.getOpcode()) { 463 default: return false; 464 case ISD::ConstantFP: 465 // Don't invert constant FP values after legalize. The negated constant 466 // isn't necessarily legal. 467 return LegalOperations ? 0 : 1; 468 case ISD::FADD: 469 // FIXME: determine better conditions for this xform. 470 if (!Options->UnsafeFPMath) return 0; 471 472 // After operation legalization, it might not be legal to create new FSUBs. 473 if (LegalOperations && 474 !TLI.isOperationLegalOrCustom(ISD::FSUB, Op.getValueType())) 475 return 0; 476 477 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B) 478 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, 479 Options, Depth + 1)) 480 return V; 481 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A) 482 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options, 483 Depth + 1); 484 case ISD::FSUB: 485 // We can't turn -(A-B) into B-A when we honor signed zeros. 486 if (!Options->UnsafeFPMath) return 0; 487 488 // fold (fneg (fsub A, B)) -> (fsub B, A) 489 return 1; 490 491 case ISD::FMUL: 492 case ISD::FDIV: 493 if (Options->HonorSignDependentRoundingFPMath()) return 0; 494 495 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y)) 496 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, 497 Options, Depth + 1)) 498 return V; 499 500 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options, 501 Depth + 1); 502 503 case ISD::FP_EXTEND: 504 case ISD::FP_ROUND: 505 case ISD::FSIN: 506 return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options, 507 Depth + 1); 508 } 509 } 510 511 /// GetNegatedExpression - If isNegatibleForFree returns true, this function 512 /// returns the newly negated expression. 513 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG, 514 bool LegalOperations, unsigned Depth = 0) { 515 // fneg is removable even if it has multiple uses. 516 if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0); 517 518 // Don't allow anything with multiple uses. 519 assert(Op.hasOneUse() && "Unknown reuse!"); 520 521 assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree"); 522 switch (Op.getOpcode()) { 523 default: llvm_unreachable("Unknown code"); 524 case ISD::ConstantFP: { 525 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF(); 526 V.changeSign(); 527 return DAG.getConstantFP(V, Op.getValueType()); 528 } 529 case ISD::FADD: 530 // FIXME: determine better conditions for this xform. 531 assert(DAG.getTarget().Options.UnsafeFPMath); 532 533 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B) 534 if (isNegatibleForFree(Op.getOperand(0), LegalOperations, 535 DAG.getTargetLoweringInfo(), 536 &DAG.getTarget().Options, Depth+1)) 537 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(), 538 GetNegatedExpression(Op.getOperand(0), DAG, 539 LegalOperations, Depth+1), 540 Op.getOperand(1)); 541 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A) 542 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(), 543 GetNegatedExpression(Op.getOperand(1), DAG, 544 LegalOperations, Depth+1), 545 Op.getOperand(0)); 546 case ISD::FSUB: 547 // We can't turn -(A-B) into B-A when we honor signed zeros. 548 assert(DAG.getTarget().Options.UnsafeFPMath); 549 550 // fold (fneg (fsub 0, B)) -> B 551 if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0))) 552 if (N0CFP->getValueAPF().isZero()) 553 return Op.getOperand(1); 554 555 // fold (fneg (fsub A, B)) -> (fsub B, A) 556 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(), 557 Op.getOperand(1), Op.getOperand(0)); 558 559 case ISD::FMUL: 560 case ISD::FDIV: 561 assert(!DAG.getTarget().Options.HonorSignDependentRoundingFPMath()); 562 563 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) 564 if (isNegatibleForFree(Op.getOperand(0), LegalOperations, 565 DAG.getTargetLoweringInfo(), 566 &DAG.getTarget().Options, Depth+1)) 567 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(), 568 GetNegatedExpression(Op.getOperand(0), DAG, 569 LegalOperations, Depth+1), 570 Op.getOperand(1)); 571 572 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y)) 573 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(), 574 Op.getOperand(0), 575 GetNegatedExpression(Op.getOperand(1), DAG, 576 LegalOperations, Depth+1)); 577 578 case ISD::FP_EXTEND: 579 case ISD::FSIN: 580 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(), 581 GetNegatedExpression(Op.getOperand(0), DAG, 582 LegalOperations, Depth+1)); 583 case ISD::FP_ROUND: 584 return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(), 585 GetNegatedExpression(Op.getOperand(0), DAG, 586 LegalOperations, Depth+1), 587 Op.getOperand(1)); 588 } 589 } 590 591 592 // isSetCCEquivalent - Return true if this node is a setcc, or is a select_cc 593 // that selects between the values 1 and 0, making it equivalent to a setcc. 594 // Also, set the incoming LHS, RHS, and CC references to the appropriate 595 // nodes based on the type of node we are checking. This simplifies life a 596 // bit for the callers. 597 static bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS, 598 SDValue &CC) { 599 if (N.getOpcode() == ISD::SETCC) { 600 LHS = N.getOperand(0); 601 RHS = N.getOperand(1); 602 CC = N.getOperand(2); 603 return true; 604 } 605 if (N.getOpcode() == ISD::SELECT_CC && 606 N.getOperand(2).getOpcode() == ISD::Constant && 607 N.getOperand(3).getOpcode() == ISD::Constant && 608 cast<ConstantSDNode>(N.getOperand(2))->getAPIntValue() == 1 && 609 cast<ConstantSDNode>(N.getOperand(3))->isNullValue()) { 610 LHS = N.getOperand(0); 611 RHS = N.getOperand(1); 612 CC = N.getOperand(4); 613 return true; 614 } 615 return false; 616 } 617 618 // isOneUseSetCC - Return true if this is a SetCC-equivalent operation with only 619 // one use. If this is true, it allows the users to invert the operation for 620 // free when it is profitable to do so. 621 static bool isOneUseSetCC(SDValue N) { 622 SDValue N0, N1, N2; 623 if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse()) 624 return true; 625 return false; 626 } 627 628 // \brief Returns the SDNode if it is a constant BuildVector or constant int. 629 static SDNode *isConstantBuildVectorOrConstantInt(SDValue N) { 630 if (isa<ConstantSDNode>(N)) 631 return N.getNode(); 632 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N); 633 if(BV && BV->isConstant()) 634 return BV; 635 return NULL; 636 } 637 638 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL, 639 SDValue N0, SDValue N1) { 640 EVT VT = N0.getValueType(); 641 if (N0.getOpcode() == Opc) { 642 if (SDNode *L = isConstantBuildVectorOrConstantInt(N0.getOperand(1))) { 643 if (SDNode *R = isConstantBuildVectorOrConstantInt(N1)) { 644 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2)) 645 SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, L, R); 646 if (!OpNode.getNode()) 647 return SDValue(); 648 return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode); 649 } 650 if (N0.hasOneUse()) { 651 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one 652 // use 653 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1); 654 if (!OpNode.getNode()) 655 return SDValue(); 656 AddToWorkList(OpNode.getNode()); 657 return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1)); 658 } 659 } 660 } 661 662 if (N1.getOpcode() == Opc) { 663 if (SDNode *R = isConstantBuildVectorOrConstantInt(N1.getOperand(1))) { 664 if (SDNode *L = isConstantBuildVectorOrConstantInt(N0)) { 665 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2)) 666 SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, R, L); 667 if (!OpNode.getNode()) 668 return SDValue(); 669 return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode); 670 } 671 if (N1.hasOneUse()) { 672 // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one 673 // use 674 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0); 675 if (!OpNode.getNode()) 676 return SDValue(); 677 AddToWorkList(OpNode.getNode()); 678 return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1)); 679 } 680 } 681 } 682 683 return SDValue(); 684 } 685 686 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo, 687 bool AddTo) { 688 assert(N->getNumValues() == NumTo && "Broken CombineTo call!"); 689 ++NodesCombined; 690 DEBUG(dbgs() << "\nReplacing.1 "; 691 N->dump(&DAG); 692 dbgs() << "\nWith: "; 693 To[0].getNode()->dump(&DAG); 694 dbgs() << " and " << NumTo-1 << " other values\n"; 695 for (unsigned i = 0, e = NumTo; i != e; ++i) 696 assert((!To[i].getNode() || 697 N->getValueType(i) == To[i].getValueType()) && 698 "Cannot combine value to value of different type!")); 699 WorkListRemover DeadNodes(*this); 700 DAG.ReplaceAllUsesWith(N, To); 701 if (AddTo) { 702 // Push the new nodes and any users onto the worklist 703 for (unsigned i = 0, e = NumTo; i != e; ++i) { 704 if (To[i].getNode()) { 705 AddToWorkList(To[i].getNode()); 706 AddUsersToWorkList(To[i].getNode()); 707 } 708 } 709 } 710 711 // Finally, if the node is now dead, remove it from the graph. The node 712 // may not be dead if the replacement process recursively simplified to 713 // something else needing this node. 714 if (N->use_empty()) { 715 // Nodes can be reintroduced into the worklist. Make sure we do not 716 // process a node that has been replaced. 717 removeFromWorkList(N); 718 719 // Finally, since the node is now dead, remove it from the graph. 720 DAG.DeleteNode(N); 721 } 722 return SDValue(N, 0); 723 } 724 725 void DAGCombiner:: 726 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) { 727 // Replace all uses. If any nodes become isomorphic to other nodes and 728 // are deleted, make sure to remove them from our worklist. 729 WorkListRemover DeadNodes(*this); 730 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New); 731 732 // Push the new node and any (possibly new) users onto the worklist. 733 AddToWorkList(TLO.New.getNode()); 734 AddUsersToWorkList(TLO.New.getNode()); 735 736 // Finally, if the node is now dead, remove it from the graph. The node 737 // may not be dead if the replacement process recursively simplified to 738 // something else needing this node. 739 if (TLO.Old.getNode()->use_empty()) { 740 removeFromWorkList(TLO.Old.getNode()); 741 742 // If the operands of this node are only used by the node, they will now 743 // be dead. Make sure to visit them first to delete dead nodes early. 744 for (unsigned i = 0, e = TLO.Old.getNode()->getNumOperands(); i != e; ++i) 745 if (TLO.Old.getNode()->getOperand(i).getNode()->hasOneUse()) 746 AddToWorkList(TLO.Old.getNode()->getOperand(i).getNode()); 747 748 DAG.DeleteNode(TLO.Old.getNode()); 749 } 750 } 751 752 /// SimplifyDemandedBits - Check the specified integer node value to see if 753 /// it can be simplified or if things it uses can be simplified by bit 754 /// propagation. If so, return true. 755 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) { 756 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations); 757 APInt KnownZero, KnownOne; 758 if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO)) 759 return false; 760 761 // Revisit the node. 762 AddToWorkList(Op.getNode()); 763 764 // Replace the old value with the new one. 765 ++NodesCombined; 766 DEBUG(dbgs() << "\nReplacing.2 "; 767 TLO.Old.getNode()->dump(&DAG); 768 dbgs() << "\nWith: "; 769 TLO.New.getNode()->dump(&DAG); 770 dbgs() << '\n'); 771 772 CommitTargetLoweringOpt(TLO); 773 return true; 774 } 775 776 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) { 777 SDLoc dl(Load); 778 EVT VT = Load->getValueType(0); 779 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0)); 780 781 DEBUG(dbgs() << "\nReplacing.9 "; 782 Load->dump(&DAG); 783 dbgs() << "\nWith: "; 784 Trunc.getNode()->dump(&DAG); 785 dbgs() << '\n'); 786 WorkListRemover DeadNodes(*this); 787 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc); 788 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1)); 789 removeFromWorkList(Load); 790 DAG.DeleteNode(Load); 791 AddToWorkList(Trunc.getNode()); 792 } 793 794 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) { 795 Replace = false; 796 SDLoc dl(Op); 797 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) { 798 EVT MemVT = LD->getMemoryVT(); 799 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD) 800 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD 801 : ISD::EXTLOAD) 802 : LD->getExtensionType(); 803 Replace = true; 804 return DAG.getExtLoad(ExtType, dl, PVT, 805 LD->getChain(), LD->getBasePtr(), 806 MemVT, LD->getMemOperand()); 807 } 808 809 unsigned Opc = Op.getOpcode(); 810 switch (Opc) { 811 default: break; 812 case ISD::AssertSext: 813 return DAG.getNode(ISD::AssertSext, dl, PVT, 814 SExtPromoteOperand(Op.getOperand(0), PVT), 815 Op.getOperand(1)); 816 case ISD::AssertZext: 817 return DAG.getNode(ISD::AssertZext, dl, PVT, 818 ZExtPromoteOperand(Op.getOperand(0), PVT), 819 Op.getOperand(1)); 820 case ISD::Constant: { 821 unsigned ExtOpc = 822 Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 823 return DAG.getNode(ExtOpc, dl, PVT, Op); 824 } 825 } 826 827 if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT)) 828 return SDValue(); 829 return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op); 830 } 831 832 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) { 833 if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT)) 834 return SDValue(); 835 EVT OldVT = Op.getValueType(); 836 SDLoc dl(Op); 837 bool Replace = false; 838 SDValue NewOp = PromoteOperand(Op, PVT, Replace); 839 if (NewOp.getNode() == 0) 840 return SDValue(); 841 AddToWorkList(NewOp.getNode()); 842 843 if (Replace) 844 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode()); 845 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp, 846 DAG.getValueType(OldVT)); 847 } 848 849 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) { 850 EVT OldVT = Op.getValueType(); 851 SDLoc dl(Op); 852 bool Replace = false; 853 SDValue NewOp = PromoteOperand(Op, PVT, Replace); 854 if (NewOp.getNode() == 0) 855 return SDValue(); 856 AddToWorkList(NewOp.getNode()); 857 858 if (Replace) 859 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode()); 860 return DAG.getZeroExtendInReg(NewOp, dl, OldVT); 861 } 862 863 /// PromoteIntBinOp - Promote the specified integer binary operation if the 864 /// target indicates it is beneficial. e.g. On x86, it's usually better to 865 /// promote i16 operations to i32 since i16 instructions are longer. 866 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) { 867 if (!LegalOperations) 868 return SDValue(); 869 870 EVT VT = Op.getValueType(); 871 if (VT.isVector() || !VT.isInteger()) 872 return SDValue(); 873 874 // If operation type is 'undesirable', e.g. i16 on x86, consider 875 // promoting it. 876 unsigned Opc = Op.getOpcode(); 877 if (TLI.isTypeDesirableForOp(Opc, VT)) 878 return SDValue(); 879 880 EVT PVT = VT; 881 // Consult target whether it is a good idea to promote this operation and 882 // what's the right type to promote it to. 883 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 884 assert(PVT != VT && "Don't know what type to promote to!"); 885 886 bool Replace0 = false; 887 SDValue N0 = Op.getOperand(0); 888 SDValue NN0 = PromoteOperand(N0, PVT, Replace0); 889 if (NN0.getNode() == 0) 890 return SDValue(); 891 892 bool Replace1 = false; 893 SDValue N1 = Op.getOperand(1); 894 SDValue NN1; 895 if (N0 == N1) 896 NN1 = NN0; 897 else { 898 NN1 = PromoteOperand(N1, PVT, Replace1); 899 if (NN1.getNode() == 0) 900 return SDValue(); 901 } 902 903 AddToWorkList(NN0.getNode()); 904 if (NN1.getNode()) 905 AddToWorkList(NN1.getNode()); 906 907 if (Replace0) 908 ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode()); 909 if (Replace1) 910 ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode()); 911 912 DEBUG(dbgs() << "\nPromoting "; 913 Op.getNode()->dump(&DAG)); 914 SDLoc dl(Op); 915 return DAG.getNode(ISD::TRUNCATE, dl, VT, 916 DAG.getNode(Opc, dl, PVT, NN0, NN1)); 917 } 918 return SDValue(); 919 } 920 921 /// PromoteIntShiftOp - Promote the specified integer shift operation if the 922 /// target indicates it is beneficial. e.g. On x86, it's usually better to 923 /// promote i16 operations to i32 since i16 instructions are longer. 924 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) { 925 if (!LegalOperations) 926 return SDValue(); 927 928 EVT VT = Op.getValueType(); 929 if (VT.isVector() || !VT.isInteger()) 930 return SDValue(); 931 932 // If operation type is 'undesirable', e.g. i16 on x86, consider 933 // promoting it. 934 unsigned Opc = Op.getOpcode(); 935 if (TLI.isTypeDesirableForOp(Opc, VT)) 936 return SDValue(); 937 938 EVT PVT = VT; 939 // Consult target whether it is a good idea to promote this operation and 940 // what's the right type to promote it to. 941 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 942 assert(PVT != VT && "Don't know what type to promote to!"); 943 944 bool Replace = false; 945 SDValue N0 = Op.getOperand(0); 946 if (Opc == ISD::SRA) 947 N0 = SExtPromoteOperand(Op.getOperand(0), PVT); 948 else if (Opc == ISD::SRL) 949 N0 = ZExtPromoteOperand(Op.getOperand(0), PVT); 950 else 951 N0 = PromoteOperand(N0, PVT, Replace); 952 if (N0.getNode() == 0) 953 return SDValue(); 954 955 AddToWorkList(N0.getNode()); 956 if (Replace) 957 ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode()); 958 959 DEBUG(dbgs() << "\nPromoting "; 960 Op.getNode()->dump(&DAG)); 961 SDLoc dl(Op); 962 return DAG.getNode(ISD::TRUNCATE, dl, VT, 963 DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1))); 964 } 965 return SDValue(); 966 } 967 968 SDValue DAGCombiner::PromoteExtend(SDValue Op) { 969 if (!LegalOperations) 970 return SDValue(); 971 972 EVT VT = Op.getValueType(); 973 if (VT.isVector() || !VT.isInteger()) 974 return SDValue(); 975 976 // If operation type is 'undesirable', e.g. i16 on x86, consider 977 // promoting it. 978 unsigned Opc = Op.getOpcode(); 979 if (TLI.isTypeDesirableForOp(Opc, VT)) 980 return SDValue(); 981 982 EVT PVT = VT; 983 // Consult target whether it is a good idea to promote this operation and 984 // what's the right type to promote it to. 985 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 986 assert(PVT != VT && "Don't know what type to promote to!"); 987 // fold (aext (aext x)) -> (aext x) 988 // fold (aext (zext x)) -> (zext x) 989 // fold (aext (sext x)) -> (sext x) 990 DEBUG(dbgs() << "\nPromoting "; 991 Op.getNode()->dump(&DAG)); 992 return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0)); 993 } 994 return SDValue(); 995 } 996 997 bool DAGCombiner::PromoteLoad(SDValue Op) { 998 if (!LegalOperations) 999 return false; 1000 1001 EVT VT = Op.getValueType(); 1002 if (VT.isVector() || !VT.isInteger()) 1003 return false; 1004 1005 // If operation type is 'undesirable', e.g. i16 on x86, consider 1006 // promoting it. 1007 unsigned Opc = Op.getOpcode(); 1008 if (TLI.isTypeDesirableForOp(Opc, VT)) 1009 return false; 1010 1011 EVT PVT = VT; 1012 // Consult target whether it is a good idea to promote this operation and 1013 // what's the right type to promote it to. 1014 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 1015 assert(PVT != VT && "Don't know what type to promote to!"); 1016 1017 SDLoc dl(Op); 1018 SDNode *N = Op.getNode(); 1019 LoadSDNode *LD = cast<LoadSDNode>(N); 1020 EVT MemVT = LD->getMemoryVT(); 1021 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD) 1022 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD 1023 : ISD::EXTLOAD) 1024 : LD->getExtensionType(); 1025 SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT, 1026 LD->getChain(), LD->getBasePtr(), 1027 MemVT, LD->getMemOperand()); 1028 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD); 1029 1030 DEBUG(dbgs() << "\nPromoting "; 1031 N->dump(&DAG); 1032 dbgs() << "\nTo: "; 1033 Result.getNode()->dump(&DAG); 1034 dbgs() << '\n'); 1035 WorkListRemover DeadNodes(*this); 1036 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result); 1037 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1)); 1038 removeFromWorkList(N); 1039 DAG.DeleteNode(N); 1040 AddToWorkList(Result.getNode()); 1041 return true; 1042 } 1043 return false; 1044 } 1045 1046 1047 //===----------------------------------------------------------------------===// 1048 // Main DAG Combiner implementation 1049 //===----------------------------------------------------------------------===// 1050 1051 void DAGCombiner::Run(CombineLevel AtLevel) { 1052 // set the instance variables, so that the various visit routines may use it. 1053 Level = AtLevel; 1054 LegalOperations = Level >= AfterLegalizeVectorOps; 1055 LegalTypes = Level >= AfterLegalizeTypes; 1056 1057 // Add all the dag nodes to the worklist. 1058 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(), 1059 E = DAG.allnodes_end(); I != E; ++I) 1060 AddToWorkList(I); 1061 1062 // Create a dummy node (which is not added to allnodes), that adds a reference 1063 // to the root node, preventing it from being deleted, and tracking any 1064 // changes of the root. 1065 HandleSDNode Dummy(DAG.getRoot()); 1066 1067 // The root of the dag may dangle to deleted nodes until the dag combiner is 1068 // done. Set it to null to avoid confusion. 1069 DAG.setRoot(SDValue()); 1070 1071 // while the worklist isn't empty, find a node and 1072 // try and combine it. 1073 while (!WorkListContents.empty()) { 1074 SDNode *N; 1075 // The WorkListOrder holds the SDNodes in order, but it may contain 1076 // duplicates. 1077 // In order to avoid a linear scan, we use a set (O(log N)) to hold what the 1078 // worklist *should* contain, and check the node we want to visit is should 1079 // actually be visited. 1080 do { 1081 N = WorkListOrder.pop_back_val(); 1082 } while (!WorkListContents.erase(N)); 1083 1084 // If N has no uses, it is dead. Make sure to revisit all N's operands once 1085 // N is deleted from the DAG, since they too may now be dead or may have a 1086 // reduced number of uses, allowing other xforms. 1087 if (N->use_empty() && N != &Dummy) { 1088 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) 1089 AddToWorkList(N->getOperand(i).getNode()); 1090 1091 DAG.DeleteNode(N); 1092 continue; 1093 } 1094 1095 SDValue RV = combine(N); 1096 1097 if (RV.getNode() == 0) 1098 continue; 1099 1100 ++NodesCombined; 1101 1102 // If we get back the same node we passed in, rather than a new node or 1103 // zero, we know that the node must have defined multiple values and 1104 // CombineTo was used. Since CombineTo takes care of the worklist 1105 // mechanics for us, we have no work to do in this case. 1106 if (RV.getNode() == N) 1107 continue; 1108 1109 assert(N->getOpcode() != ISD::DELETED_NODE && 1110 RV.getNode()->getOpcode() != ISD::DELETED_NODE && 1111 "Node was deleted but visit returned new node!"); 1112 1113 DEBUG(dbgs() << "\nReplacing.3 "; 1114 N->dump(&DAG); 1115 dbgs() << "\nWith: "; 1116 RV.getNode()->dump(&DAG); 1117 dbgs() << '\n'); 1118 1119 // Transfer debug value. 1120 DAG.TransferDbgValues(SDValue(N, 0), RV); 1121 WorkListRemover DeadNodes(*this); 1122 if (N->getNumValues() == RV.getNode()->getNumValues()) 1123 DAG.ReplaceAllUsesWith(N, RV.getNode()); 1124 else { 1125 assert(N->getValueType(0) == RV.getValueType() && 1126 N->getNumValues() == 1 && "Type mismatch"); 1127 SDValue OpV = RV; 1128 DAG.ReplaceAllUsesWith(N, &OpV); 1129 } 1130 1131 // Push the new node and any users onto the worklist 1132 AddToWorkList(RV.getNode()); 1133 AddUsersToWorkList(RV.getNode()); 1134 1135 // Add any uses of the old node to the worklist in case this node is the 1136 // last one that uses them. They may become dead after this node is 1137 // deleted. 1138 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) 1139 AddToWorkList(N->getOperand(i).getNode()); 1140 1141 // Finally, if the node is now dead, remove it from the graph. The node 1142 // may not be dead if the replacement process recursively simplified to 1143 // something else needing this node. 1144 if (N->use_empty()) { 1145 // Nodes can be reintroduced into the worklist. Make sure we do not 1146 // process a node that has been replaced. 1147 removeFromWorkList(N); 1148 1149 // Finally, since the node is now dead, remove it from the graph. 1150 DAG.DeleteNode(N); 1151 } 1152 } 1153 1154 // If the root changed (e.g. it was a dead load, update the root). 1155 DAG.setRoot(Dummy.getValue()); 1156 DAG.RemoveDeadNodes(); 1157 } 1158 1159 SDValue DAGCombiner::visit(SDNode *N) { 1160 switch (N->getOpcode()) { 1161 default: break; 1162 case ISD::TokenFactor: return visitTokenFactor(N); 1163 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N); 1164 case ISD::ADD: return visitADD(N); 1165 case ISD::SUB: return visitSUB(N); 1166 case ISD::ADDC: return visitADDC(N); 1167 case ISD::SUBC: return visitSUBC(N); 1168 case ISD::ADDE: return visitADDE(N); 1169 case ISD::SUBE: return visitSUBE(N); 1170 case ISD::MUL: return visitMUL(N); 1171 case ISD::SDIV: return visitSDIV(N); 1172 case ISD::UDIV: return visitUDIV(N); 1173 case ISD::SREM: return visitSREM(N); 1174 case ISD::UREM: return visitUREM(N); 1175 case ISD::MULHU: return visitMULHU(N); 1176 case ISD::MULHS: return visitMULHS(N); 1177 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N); 1178 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N); 1179 case ISD::SMULO: return visitSMULO(N); 1180 case ISD::UMULO: return visitUMULO(N); 1181 case ISD::SDIVREM: return visitSDIVREM(N); 1182 case ISD::UDIVREM: return visitUDIVREM(N); 1183 case ISD::AND: return visitAND(N); 1184 case ISD::OR: return visitOR(N); 1185 case ISD::XOR: return visitXOR(N); 1186 case ISD::SHL: return visitSHL(N); 1187 case ISD::SRA: return visitSRA(N); 1188 case ISD::SRL: return visitSRL(N); 1189 case ISD::CTLZ: return visitCTLZ(N); 1190 case ISD::CTLZ_ZERO_UNDEF: return visitCTLZ_ZERO_UNDEF(N); 1191 case ISD::CTTZ: return visitCTTZ(N); 1192 case ISD::CTTZ_ZERO_UNDEF: return visitCTTZ_ZERO_UNDEF(N); 1193 case ISD::CTPOP: return visitCTPOP(N); 1194 case ISD::SELECT: return visitSELECT(N); 1195 case ISD::VSELECT: return visitVSELECT(N); 1196 case ISD::SELECT_CC: return visitSELECT_CC(N); 1197 case ISD::SETCC: return visitSETCC(N); 1198 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N); 1199 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N); 1200 case ISD::ANY_EXTEND: return visitANY_EXTEND(N); 1201 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N); 1202 case ISD::TRUNCATE: return visitTRUNCATE(N); 1203 case ISD::BITCAST: return visitBITCAST(N); 1204 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N); 1205 case ISD::FADD: return visitFADD(N); 1206 case ISD::FSUB: return visitFSUB(N); 1207 case ISD::FMUL: return visitFMUL(N); 1208 case ISD::FMA: return visitFMA(N); 1209 case ISD::FDIV: return visitFDIV(N); 1210 case ISD::FREM: return visitFREM(N); 1211 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N); 1212 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N); 1213 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N); 1214 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N); 1215 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N); 1216 case ISD::FP_ROUND: return visitFP_ROUND(N); 1217 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N); 1218 case ISD::FP_EXTEND: return visitFP_EXTEND(N); 1219 case ISD::FNEG: return visitFNEG(N); 1220 case ISD::FABS: return visitFABS(N); 1221 case ISD::FFLOOR: return visitFFLOOR(N); 1222 case ISD::FCEIL: return visitFCEIL(N); 1223 case ISD::FTRUNC: return visitFTRUNC(N); 1224 case ISD::BRCOND: return visitBRCOND(N); 1225 case ISD::BR_CC: return visitBR_CC(N); 1226 case ISD::LOAD: return visitLOAD(N); 1227 case ISD::STORE: return visitSTORE(N); 1228 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N); 1229 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N); 1230 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N); 1231 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N); 1232 case ISD::EXTRACT_SUBVECTOR: return visitEXTRACT_SUBVECTOR(N); 1233 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N); 1234 case ISD::INSERT_SUBVECTOR: return visitINSERT_SUBVECTOR(N); 1235 } 1236 return SDValue(); 1237 } 1238 1239 SDValue DAGCombiner::combine(SDNode *N) { 1240 SDValue RV = visit(N); 1241 1242 // If nothing happened, try a target-specific DAG combine. 1243 if (RV.getNode() == 0) { 1244 assert(N->getOpcode() != ISD::DELETED_NODE && 1245 "Node was deleted but visit returned NULL!"); 1246 1247 if (N->getOpcode() >= ISD::BUILTIN_OP_END || 1248 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) { 1249 1250 // Expose the DAG combiner to the target combiner impls. 1251 TargetLowering::DAGCombinerInfo 1252 DagCombineInfo(DAG, Level, false, this); 1253 1254 RV = TLI.PerformDAGCombine(N, DagCombineInfo); 1255 } 1256 } 1257 1258 // If nothing happened still, try promoting the operation. 1259 if (RV.getNode() == 0) { 1260 switch (N->getOpcode()) { 1261 default: break; 1262 case ISD::ADD: 1263 case ISD::SUB: 1264 case ISD::MUL: 1265 case ISD::AND: 1266 case ISD::OR: 1267 case ISD::XOR: 1268 RV = PromoteIntBinOp(SDValue(N, 0)); 1269 break; 1270 case ISD::SHL: 1271 case ISD::SRA: 1272 case ISD::SRL: 1273 RV = PromoteIntShiftOp(SDValue(N, 0)); 1274 break; 1275 case ISD::SIGN_EXTEND: 1276 case ISD::ZERO_EXTEND: 1277 case ISD::ANY_EXTEND: 1278 RV = PromoteExtend(SDValue(N, 0)); 1279 break; 1280 case ISD::LOAD: 1281 if (PromoteLoad(SDValue(N, 0))) 1282 RV = SDValue(N, 0); 1283 break; 1284 } 1285 } 1286 1287 // If N is a commutative binary node, try commuting it to enable more 1288 // sdisel CSE. 1289 if (RV.getNode() == 0 && 1290 SelectionDAG::isCommutativeBinOp(N->getOpcode()) && 1291 N->getNumValues() == 1) { 1292 SDValue N0 = N->getOperand(0); 1293 SDValue N1 = N->getOperand(1); 1294 1295 // Constant operands are canonicalized to RHS. 1296 if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) { 1297 SDValue Ops[] = { N1, N0 }; 1298 SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), 1299 Ops, 2); 1300 if (CSENode) 1301 return SDValue(CSENode, 0); 1302 } 1303 } 1304 1305 return RV; 1306 } 1307 1308 /// getInputChainForNode - Given a node, return its input chain if it has one, 1309 /// otherwise return a null sd operand. 1310 static SDValue getInputChainForNode(SDNode *N) { 1311 if (unsigned NumOps = N->getNumOperands()) { 1312 if (N->getOperand(0).getValueType() == MVT::Other) 1313 return N->getOperand(0); 1314 if (N->getOperand(NumOps-1).getValueType() == MVT::Other) 1315 return N->getOperand(NumOps-1); 1316 for (unsigned i = 1; i < NumOps-1; ++i) 1317 if (N->getOperand(i).getValueType() == MVT::Other) 1318 return N->getOperand(i); 1319 } 1320 return SDValue(); 1321 } 1322 1323 SDValue DAGCombiner::visitTokenFactor(SDNode *N) { 1324 // If N has two operands, where one has an input chain equal to the other, 1325 // the 'other' chain is redundant. 1326 if (N->getNumOperands() == 2) { 1327 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1)) 1328 return N->getOperand(0); 1329 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0)) 1330 return N->getOperand(1); 1331 } 1332 1333 SmallVector<SDNode *, 8> TFs; // List of token factors to visit. 1334 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor. 1335 SmallPtrSet<SDNode*, 16> SeenOps; 1336 bool Changed = false; // If we should replace this token factor. 1337 1338 // Start out with this token factor. 1339 TFs.push_back(N); 1340 1341 // Iterate through token factors. The TFs grows when new token factors are 1342 // encountered. 1343 for (unsigned i = 0; i < TFs.size(); ++i) { 1344 SDNode *TF = TFs[i]; 1345 1346 // Check each of the operands. 1347 for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) { 1348 SDValue Op = TF->getOperand(i); 1349 1350 switch (Op.getOpcode()) { 1351 case ISD::EntryToken: 1352 // Entry tokens don't need to be added to the list. They are 1353 // rededundant. 1354 Changed = true; 1355 break; 1356 1357 case ISD::TokenFactor: 1358 if (Op.hasOneUse() && 1359 std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) { 1360 // Queue up for processing. 1361 TFs.push_back(Op.getNode()); 1362 // Clean up in case the token factor is removed. 1363 AddToWorkList(Op.getNode()); 1364 Changed = true; 1365 break; 1366 } 1367 // Fall thru 1368 1369 default: 1370 // Only add if it isn't already in the list. 1371 if (SeenOps.insert(Op.getNode())) 1372 Ops.push_back(Op); 1373 else 1374 Changed = true; 1375 break; 1376 } 1377 } 1378 } 1379 1380 SDValue Result; 1381 1382 // If we've change things around then replace token factor. 1383 if (Changed) { 1384 if (Ops.empty()) { 1385 // The entry token is the only possible outcome. 1386 Result = DAG.getEntryNode(); 1387 } else { 1388 // New and improved token factor. 1389 Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), 1390 MVT::Other, &Ops[0], Ops.size()); 1391 } 1392 1393 // Don't add users to work list. 1394 return CombineTo(N, Result, false); 1395 } 1396 1397 return Result; 1398 } 1399 1400 /// MERGE_VALUES can always be eliminated. 1401 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) { 1402 WorkListRemover DeadNodes(*this); 1403 // Replacing results may cause a different MERGE_VALUES to suddenly 1404 // be CSE'd with N, and carry its uses with it. Iterate until no 1405 // uses remain, to ensure that the node can be safely deleted. 1406 // First add the users of this node to the work list so that they 1407 // can be tried again once they have new operands. 1408 AddUsersToWorkList(N); 1409 do { 1410 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) 1411 DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i)); 1412 } while (!N->use_empty()); 1413 removeFromWorkList(N); 1414 DAG.DeleteNode(N); 1415 return SDValue(N, 0); // Return N so it doesn't get rechecked! 1416 } 1417 1418 static 1419 SDValue combineShlAddConstant(SDLoc DL, SDValue N0, SDValue N1, 1420 SelectionDAG &DAG) { 1421 EVT VT = N0.getValueType(); 1422 SDValue N00 = N0.getOperand(0); 1423 SDValue N01 = N0.getOperand(1); 1424 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N01); 1425 1426 if (N01C && N00.getOpcode() == ISD::ADD && N00.getNode()->hasOneUse() && 1427 isa<ConstantSDNode>(N00.getOperand(1))) { 1428 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), ) 1429 N0 = DAG.getNode(ISD::ADD, SDLoc(N0), VT, 1430 DAG.getNode(ISD::SHL, SDLoc(N00), VT, 1431 N00.getOperand(0), N01), 1432 DAG.getNode(ISD::SHL, SDLoc(N01), VT, 1433 N00.getOperand(1), N01)); 1434 return DAG.getNode(ISD::ADD, DL, VT, N0, N1); 1435 } 1436 1437 return SDValue(); 1438 } 1439 1440 SDValue DAGCombiner::visitADD(SDNode *N) { 1441 SDValue N0 = N->getOperand(0); 1442 SDValue N1 = N->getOperand(1); 1443 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 1444 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 1445 EVT VT = N0.getValueType(); 1446 1447 // fold vector ops 1448 if (VT.isVector()) { 1449 SDValue FoldedVOp = SimplifyVBinOp(N); 1450 if (FoldedVOp.getNode()) return FoldedVOp; 1451 1452 // fold (add x, 0) -> x, vector edition 1453 if (ISD::isBuildVectorAllZeros(N1.getNode())) 1454 return N0; 1455 if (ISD::isBuildVectorAllZeros(N0.getNode())) 1456 return N1; 1457 } 1458 1459 // fold (add x, undef) -> undef 1460 if (N0.getOpcode() == ISD::UNDEF) 1461 return N0; 1462 if (N1.getOpcode() == ISD::UNDEF) 1463 return N1; 1464 // fold (add c1, c2) -> c1+c2 1465 if (N0C && N1C) 1466 return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C); 1467 // canonicalize constant to RHS 1468 if (N0C && !N1C) 1469 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0); 1470 // fold (add x, 0) -> x 1471 if (N1C && N1C->isNullValue()) 1472 return N0; 1473 // fold (add Sym, c) -> Sym+c 1474 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0)) 1475 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C && 1476 GA->getOpcode() == ISD::GlobalAddress) 1477 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT, 1478 GA->getOffset() + 1479 (uint64_t)N1C->getSExtValue()); 1480 // fold ((c1-A)+c2) -> (c1+c2)-A 1481 if (N1C && N0.getOpcode() == ISD::SUB) 1482 if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0))) 1483 return DAG.getNode(ISD::SUB, SDLoc(N), VT, 1484 DAG.getConstant(N1C->getAPIntValue()+ 1485 N0C->getAPIntValue(), VT), 1486 N0.getOperand(1)); 1487 // reassociate add 1488 SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1); 1489 if (RADD.getNode() != 0) 1490 return RADD; 1491 // fold ((0-A) + B) -> B-A 1492 if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) && 1493 cast<ConstantSDNode>(N0.getOperand(0))->isNullValue()) 1494 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1)); 1495 // fold (A + (0-B)) -> A-B 1496 if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) && 1497 cast<ConstantSDNode>(N1.getOperand(0))->isNullValue()) 1498 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1)); 1499 // fold (A+(B-A)) -> B 1500 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1)) 1501 return N1.getOperand(0); 1502 // fold ((B-A)+A) -> B 1503 if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1)) 1504 return N0.getOperand(0); 1505 // fold (A+(B-(A+C))) to (B-C) 1506 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD && 1507 N0 == N1.getOperand(1).getOperand(0)) 1508 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0), 1509 N1.getOperand(1).getOperand(1)); 1510 // fold (A+(B-(C+A))) to (B-C) 1511 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD && 1512 N0 == N1.getOperand(1).getOperand(1)) 1513 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0), 1514 N1.getOperand(1).getOperand(0)); 1515 // fold (A+((B-A)+or-C)) to (B+or-C) 1516 if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) && 1517 N1.getOperand(0).getOpcode() == ISD::SUB && 1518 N0 == N1.getOperand(0).getOperand(1)) 1519 return DAG.getNode(N1.getOpcode(), SDLoc(N), VT, 1520 N1.getOperand(0).getOperand(0), N1.getOperand(1)); 1521 1522 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant 1523 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) { 1524 SDValue N00 = N0.getOperand(0); 1525 SDValue N01 = N0.getOperand(1); 1526 SDValue N10 = N1.getOperand(0); 1527 SDValue N11 = N1.getOperand(1); 1528 1529 if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10)) 1530 return DAG.getNode(ISD::SUB, SDLoc(N), VT, 1531 DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10), 1532 DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11)); 1533 } 1534 1535 if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0))) 1536 return SDValue(N, 0); 1537 1538 // fold (a+b) -> (a|b) iff a and b share no bits. 1539 if (VT.isInteger() && !VT.isVector()) { 1540 APInt LHSZero, LHSOne; 1541 APInt RHSZero, RHSOne; 1542 DAG.ComputeMaskedBits(N0, LHSZero, LHSOne); 1543 1544 if (LHSZero.getBoolValue()) { 1545 DAG.ComputeMaskedBits(N1, RHSZero, RHSOne); 1546 1547 // If all possibly-set bits on the LHS are clear on the RHS, return an OR. 1548 // If all possibly-set bits on the RHS are clear on the LHS, return an OR. 1549 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){ 1550 if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT)) 1551 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1); 1552 } 1553 } 1554 } 1555 1556 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), ) 1557 if (N0.getOpcode() == ISD::SHL && N0.getNode()->hasOneUse()) { 1558 SDValue Result = combineShlAddConstant(SDLoc(N), N0, N1, DAG); 1559 if (Result.getNode()) return Result; 1560 } 1561 if (N1.getOpcode() == ISD::SHL && N1.getNode()->hasOneUse()) { 1562 SDValue Result = combineShlAddConstant(SDLoc(N), N1, N0, DAG); 1563 if (Result.getNode()) return Result; 1564 } 1565 1566 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n)) 1567 if (N1.getOpcode() == ISD::SHL && 1568 N1.getOperand(0).getOpcode() == ISD::SUB) 1569 if (ConstantSDNode *C = 1570 dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0))) 1571 if (C->getAPIntValue() == 0) 1572 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, 1573 DAG.getNode(ISD::SHL, SDLoc(N), VT, 1574 N1.getOperand(0).getOperand(1), 1575 N1.getOperand(1))); 1576 if (N0.getOpcode() == ISD::SHL && 1577 N0.getOperand(0).getOpcode() == ISD::SUB) 1578 if (ConstantSDNode *C = 1579 dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0))) 1580 if (C->getAPIntValue() == 0) 1581 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, 1582 DAG.getNode(ISD::SHL, SDLoc(N), VT, 1583 N0.getOperand(0).getOperand(1), 1584 N0.getOperand(1))); 1585 1586 if (N1.getOpcode() == ISD::AND) { 1587 SDValue AndOp0 = N1.getOperand(0); 1588 ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1)); 1589 unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0); 1590 unsigned DestBits = VT.getScalarType().getSizeInBits(); 1591 1592 // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x)) 1593 // and similar xforms where the inner op is either ~0 or 0. 1594 if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) { 1595 SDLoc DL(N); 1596 return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0); 1597 } 1598 } 1599 1600 // add (sext i1), X -> sub X, (zext i1) 1601 if (N0.getOpcode() == ISD::SIGN_EXTEND && 1602 N0.getOperand(0).getValueType() == MVT::i1 && 1603 !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) { 1604 SDLoc DL(N); 1605 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)); 1606 return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt); 1607 } 1608 1609 return SDValue(); 1610 } 1611 1612 SDValue DAGCombiner::visitADDC(SDNode *N) { 1613 SDValue N0 = N->getOperand(0); 1614 SDValue N1 = N->getOperand(1); 1615 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 1616 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 1617 EVT VT = N0.getValueType(); 1618 1619 // If the flag result is dead, turn this into an ADD. 1620 if (!N->hasAnyUseOfValue(1)) 1621 return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1), 1622 DAG.getNode(ISD::CARRY_FALSE, 1623 SDLoc(N), MVT::Glue)); 1624 1625 // canonicalize constant to RHS. 1626 if (N0C && !N1C) 1627 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0); 1628 1629 // fold (addc x, 0) -> x + no carry out 1630 if (N1C && N1C->isNullValue()) 1631 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, 1632 SDLoc(N), MVT::Glue)); 1633 1634 // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits. 1635 APInt LHSZero, LHSOne; 1636 APInt RHSZero, RHSOne; 1637 DAG.ComputeMaskedBits(N0, LHSZero, LHSOne); 1638 1639 if (LHSZero.getBoolValue()) { 1640 DAG.ComputeMaskedBits(N1, RHSZero, RHSOne); 1641 1642 // If all possibly-set bits on the LHS are clear on the RHS, return an OR. 1643 // If all possibly-set bits on the RHS are clear on the LHS, return an OR. 1644 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero) 1645 return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1), 1646 DAG.getNode(ISD::CARRY_FALSE, 1647 SDLoc(N), MVT::Glue)); 1648 } 1649 1650 return SDValue(); 1651 } 1652 1653 SDValue DAGCombiner::visitADDE(SDNode *N) { 1654 SDValue N0 = N->getOperand(0); 1655 SDValue N1 = N->getOperand(1); 1656 SDValue CarryIn = N->getOperand(2); 1657 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 1658 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 1659 1660 // canonicalize constant to RHS 1661 if (N0C && !N1C) 1662 return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(), 1663 N1, N0, CarryIn); 1664 1665 // fold (adde x, y, false) -> (addc x, y) 1666 if (CarryIn.getOpcode() == ISD::CARRY_FALSE) 1667 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1); 1668 1669 return SDValue(); 1670 } 1671 1672 // Since it may not be valid to emit a fold to zero for vector initializers 1673 // check if we can before folding. 1674 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT, 1675 SelectionDAG &DAG, 1676 bool LegalOperations, bool LegalTypes) { 1677 if (!VT.isVector()) 1678 return DAG.getConstant(0, VT); 1679 if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT)) 1680 return DAG.getConstant(0, VT); 1681 return SDValue(); 1682 } 1683 1684 SDValue DAGCombiner::visitSUB(SDNode *N) { 1685 SDValue N0 = N->getOperand(0); 1686 SDValue N1 = N->getOperand(1); 1687 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode()); 1688 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode()); 1689 ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? 0 : 1690 dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode()); 1691 EVT VT = N0.getValueType(); 1692 1693 // fold vector ops 1694 if (VT.isVector()) { 1695 SDValue FoldedVOp = SimplifyVBinOp(N); 1696 if (FoldedVOp.getNode()) return FoldedVOp; 1697 1698 // fold (sub x, 0) -> x, vector edition 1699 if (ISD::isBuildVectorAllZeros(N1.getNode())) 1700 return N0; 1701 } 1702 1703 // fold (sub x, x) -> 0 1704 // FIXME: Refactor this and xor and other similar operations together. 1705 if (N0 == N1) 1706 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes); 1707 // fold (sub c1, c2) -> c1-c2 1708 if (N0C && N1C) 1709 return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C); 1710 // fold (sub x, c) -> (add x, -c) 1711 if (N1C) 1712 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, 1713 DAG.getConstant(-N1C->getAPIntValue(), VT)); 1714 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) 1715 if (N0C && N0C->isAllOnesValue()) 1716 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0); 1717 // fold A-(A-B) -> B 1718 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0)) 1719 return N1.getOperand(1); 1720 // fold (A+B)-A -> B 1721 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1) 1722 return N0.getOperand(1); 1723 // fold (A+B)-B -> A 1724 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1) 1725 return N0.getOperand(0); 1726 // fold C2-(A+C1) -> (C2-C1)-A 1727 if (N1.getOpcode() == ISD::ADD && N0C && N1C1) { 1728 SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(), 1729 VT); 1730 return DAG.getNode(ISD::SUB, SDLoc(N), VT, NewC, 1731 N1.getOperand(0)); 1732 } 1733 // fold ((A+(B+or-C))-B) -> A+or-C 1734 if (N0.getOpcode() == ISD::ADD && 1735 (N0.getOperand(1).getOpcode() == ISD::SUB || 1736 N0.getOperand(1).getOpcode() == ISD::ADD) && 1737 N0.getOperand(1).getOperand(0) == N1) 1738 return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT, 1739 N0.getOperand(0), N0.getOperand(1).getOperand(1)); 1740 // fold ((A+(C+B))-B) -> A+C 1741 if (N0.getOpcode() == ISD::ADD && 1742 N0.getOperand(1).getOpcode() == ISD::ADD && 1743 N0.getOperand(1).getOperand(1) == N1) 1744 return DAG.getNode(ISD::ADD, SDLoc(N), VT, 1745 N0.getOperand(0), N0.getOperand(1).getOperand(0)); 1746 // fold ((A-(B-C))-C) -> A-B 1747 if (N0.getOpcode() == ISD::SUB && 1748 N0.getOperand(1).getOpcode() == ISD::SUB && 1749 N0.getOperand(1).getOperand(1) == N1) 1750 return DAG.getNode(ISD::SUB, SDLoc(N), VT, 1751 N0.getOperand(0), N0.getOperand(1).getOperand(0)); 1752 1753 // If either operand of a sub is undef, the result is undef 1754 if (N0.getOpcode() == ISD::UNDEF) 1755 return N0; 1756 if (N1.getOpcode() == ISD::UNDEF) 1757 return N1; 1758 1759 // If the relocation model supports it, consider symbol offsets. 1760 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0)) 1761 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) { 1762 // fold (sub Sym, c) -> Sym-c 1763 if (N1C && GA->getOpcode() == ISD::GlobalAddress) 1764 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT, 1765 GA->getOffset() - 1766 (uint64_t)N1C->getSExtValue()); 1767 // fold (sub Sym+c1, Sym+c2) -> c1-c2 1768 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1)) 1769 if (GA->getGlobal() == GB->getGlobal()) 1770 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(), 1771 VT); 1772 } 1773 1774 return SDValue(); 1775 } 1776 1777 SDValue DAGCombiner::visitSUBC(SDNode *N) { 1778 SDValue N0 = N->getOperand(0); 1779 SDValue N1 = N->getOperand(1); 1780 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 1781 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 1782 EVT VT = N0.getValueType(); 1783 1784 // If the flag result is dead, turn this into an SUB. 1785 if (!N->hasAnyUseOfValue(1)) 1786 return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1), 1787 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N), 1788 MVT::Glue)); 1789 1790 // fold (subc x, x) -> 0 + no borrow 1791 if (N0 == N1) 1792 return CombineTo(N, DAG.getConstant(0, VT), 1793 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N), 1794 MVT::Glue)); 1795 1796 // fold (subc x, 0) -> x + no borrow 1797 if (N1C && N1C->isNullValue()) 1798 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N), 1799 MVT::Glue)); 1800 1801 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow 1802 if (N0C && N0C->isAllOnesValue()) 1803 return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0), 1804 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N), 1805 MVT::Glue)); 1806 1807 return SDValue(); 1808 } 1809 1810 SDValue DAGCombiner::visitSUBE(SDNode *N) { 1811 SDValue N0 = N->getOperand(0); 1812 SDValue N1 = N->getOperand(1); 1813 SDValue CarryIn = N->getOperand(2); 1814 1815 // fold (sube x, y, false) -> (subc x, y) 1816 if (CarryIn.getOpcode() == ISD::CARRY_FALSE) 1817 return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1); 1818 1819 return SDValue(); 1820 } 1821 1822 /// isConstantSplatVector - Returns true if N is a BUILD_VECTOR node whose 1823 /// elements are all the same constant or undefined. 1824 static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) { 1825 BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N); 1826 if (!C) 1827 return false; 1828 1829 APInt SplatUndef; 1830 unsigned SplatBitSize; 1831 bool HasAnyUndefs; 1832 EVT EltVT = N->getValueType(0).getVectorElementType(); 1833 return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize, 1834 HasAnyUndefs) && 1835 EltVT.getSizeInBits() >= SplatBitSize); 1836 } 1837 1838 SDValue DAGCombiner::visitMUL(SDNode *N) { 1839 SDValue N0 = N->getOperand(0); 1840 SDValue N1 = N->getOperand(1); 1841 EVT VT = N0.getValueType(); 1842 1843 // fold (mul x, undef) -> 0 1844 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF) 1845 return DAG.getConstant(0, VT); 1846 1847 bool N0IsConst = false; 1848 bool N1IsConst = false; 1849 APInt ConstValue0, ConstValue1; 1850 // fold vector ops 1851 if (VT.isVector()) { 1852 SDValue FoldedVOp = SimplifyVBinOp(N); 1853 if (FoldedVOp.getNode()) return FoldedVOp; 1854 1855 N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0); 1856 N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1); 1857 } else { 1858 N0IsConst = dyn_cast<ConstantSDNode>(N0) != 0; 1859 ConstValue0 = N0IsConst ? (dyn_cast<ConstantSDNode>(N0))->getAPIntValue() 1860 : APInt(); 1861 N1IsConst = dyn_cast<ConstantSDNode>(N1) != 0; 1862 ConstValue1 = N1IsConst ? (dyn_cast<ConstantSDNode>(N1))->getAPIntValue() 1863 : APInt(); 1864 } 1865 1866 // fold (mul c1, c2) -> c1*c2 1867 if (N0IsConst && N1IsConst) 1868 return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0.getNode(), N1.getNode()); 1869 1870 // canonicalize constant to RHS 1871 if (N0IsConst && !N1IsConst) 1872 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0); 1873 // fold (mul x, 0) -> 0 1874 if (N1IsConst && ConstValue1 == 0) 1875 return N1; 1876 // We require a splat of the entire scalar bit width for non-contiguous 1877 // bit patterns. 1878 bool IsFullSplat = 1879 ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits(); 1880 // fold (mul x, 1) -> x 1881 if (N1IsConst && ConstValue1 == 1 && IsFullSplat) 1882 return N0; 1883 // fold (mul x, -1) -> 0-x 1884 if (N1IsConst && ConstValue1.isAllOnesValue()) 1885 return DAG.getNode(ISD::SUB, SDLoc(N), VT, 1886 DAG.getConstant(0, VT), N0); 1887 // fold (mul x, (1 << c)) -> x << c 1888 if (N1IsConst && ConstValue1.isPowerOf2() && IsFullSplat) 1889 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, 1890 DAG.getConstant(ConstValue1.logBase2(), 1891 getShiftAmountTy(N0.getValueType()))); 1892 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c 1893 if (N1IsConst && (-ConstValue1).isPowerOf2() && IsFullSplat) { 1894 unsigned Log2Val = (-ConstValue1).logBase2(); 1895 // FIXME: If the input is something that is easily negated (e.g. a 1896 // single-use add), we should put the negate there. 1897 return DAG.getNode(ISD::SUB, SDLoc(N), VT, 1898 DAG.getConstant(0, VT), 1899 DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, 1900 DAG.getConstant(Log2Val, 1901 getShiftAmountTy(N0.getValueType())))); 1902 } 1903 1904 APInt Val; 1905 // (mul (shl X, c1), c2) -> (mul X, c2 << c1) 1906 if (N1IsConst && N0.getOpcode() == ISD::SHL && 1907 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) || 1908 isa<ConstantSDNode>(N0.getOperand(1)))) { 1909 SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT, 1910 N1, N0.getOperand(1)); 1911 AddToWorkList(C3.getNode()); 1912 return DAG.getNode(ISD::MUL, SDLoc(N), VT, 1913 N0.getOperand(0), C3); 1914 } 1915 1916 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one 1917 // use. 1918 { 1919 SDValue Sh(0,0), Y(0,0); 1920 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)). 1921 if (N0.getOpcode() == ISD::SHL && 1922 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) || 1923 isa<ConstantSDNode>(N0.getOperand(1))) && 1924 N0.getNode()->hasOneUse()) { 1925 Sh = N0; Y = N1; 1926 } else if (N1.getOpcode() == ISD::SHL && 1927 isa<ConstantSDNode>(N1.getOperand(1)) && 1928 N1.getNode()->hasOneUse()) { 1929 Sh = N1; Y = N0; 1930 } 1931 1932 if (Sh.getNode()) { 1933 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT, 1934 Sh.getOperand(0), Y); 1935 return DAG.getNode(ISD::SHL, SDLoc(N), VT, 1936 Mul, Sh.getOperand(1)); 1937 } 1938 } 1939 1940 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2) 1941 if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() && 1942 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) || 1943 isa<ConstantSDNode>(N0.getOperand(1)))) 1944 return DAG.getNode(ISD::ADD, SDLoc(N), VT, 1945 DAG.getNode(ISD::MUL, SDLoc(N0), VT, 1946 N0.getOperand(0), N1), 1947 DAG.getNode(ISD::MUL, SDLoc(N1), VT, 1948 N0.getOperand(1), N1)); 1949 1950 // reassociate mul 1951 SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1); 1952 if (RMUL.getNode() != 0) 1953 return RMUL; 1954 1955 return SDValue(); 1956 } 1957 1958 SDValue DAGCombiner::visitSDIV(SDNode *N) { 1959 SDValue N0 = N->getOperand(0); 1960 SDValue N1 = N->getOperand(1); 1961 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode()); 1962 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode()); 1963 EVT VT = N->getValueType(0); 1964 1965 // fold vector ops 1966 if (VT.isVector()) { 1967 SDValue FoldedVOp = SimplifyVBinOp(N); 1968 if (FoldedVOp.getNode()) return FoldedVOp; 1969 } 1970 1971 // fold (sdiv c1, c2) -> c1/c2 1972 if (N0C && N1C && !N1C->isNullValue()) 1973 return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C); 1974 // fold (sdiv X, 1) -> X 1975 if (N1C && N1C->getAPIntValue() == 1LL) 1976 return N0; 1977 // fold (sdiv X, -1) -> 0-X 1978 if (N1C && N1C->isAllOnesValue()) 1979 return DAG.getNode(ISD::SUB, SDLoc(N), VT, 1980 DAG.getConstant(0, VT), N0); 1981 // If we know the sign bits of both operands are zero, strength reduce to a 1982 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2 1983 if (!VT.isVector()) { 1984 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0)) 1985 return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(), 1986 N0, N1); 1987 } 1988 // fold (sdiv X, pow2) -> simple ops after legalize 1989 if (N1C && !N1C->isNullValue() && 1990 (N1C->getAPIntValue().isPowerOf2() || 1991 (-N1C->getAPIntValue()).isPowerOf2())) { 1992 // If dividing by powers of two is cheap, then don't perform the following 1993 // fold. 1994 if (TLI.isPow2DivCheap()) 1995 return SDValue(); 1996 1997 unsigned lg2 = N1C->getAPIntValue().countTrailingZeros(); 1998 1999 // Splat the sign bit into the register 2000 SDValue SGN = DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, 2001 DAG.getConstant(VT.getSizeInBits()-1, 2002 getShiftAmountTy(N0.getValueType()))); 2003 AddToWorkList(SGN.getNode()); 2004 2005 // Add (N0 < 0) ? abs2 - 1 : 0; 2006 SDValue SRL = DAG.getNode(ISD::SRL, SDLoc(N), VT, SGN, 2007 DAG.getConstant(VT.getSizeInBits() - lg2, 2008 getShiftAmountTy(SGN.getValueType()))); 2009 SDValue ADD = DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, SRL); 2010 AddToWorkList(SRL.getNode()); 2011 AddToWorkList(ADD.getNode()); // Divide by pow2 2012 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), VT, ADD, 2013 DAG.getConstant(lg2, getShiftAmountTy(ADD.getValueType()))); 2014 2015 // If we're dividing by a positive value, we're done. Otherwise, we must 2016 // negate the result. 2017 if (N1C->getAPIntValue().isNonNegative()) 2018 return SRA; 2019 2020 AddToWorkList(SRA.getNode()); 2021 return DAG.getNode(ISD::SUB, SDLoc(N), VT, 2022 DAG.getConstant(0, VT), SRA); 2023 } 2024 2025 // if integer divide is expensive and we satisfy the requirements, emit an 2026 // alternate sequence. 2027 if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap()) { 2028 SDValue Op = BuildSDIV(N); 2029 if (Op.getNode()) return Op; 2030 } 2031 2032 // undef / X -> 0 2033 if (N0.getOpcode() == ISD::UNDEF) 2034 return DAG.getConstant(0, VT); 2035 // X / undef -> undef 2036 if (N1.getOpcode() == ISD::UNDEF) 2037 return N1; 2038 2039 return SDValue(); 2040 } 2041 2042 SDValue DAGCombiner::visitUDIV(SDNode *N) { 2043 SDValue N0 = N->getOperand(0); 2044 SDValue N1 = N->getOperand(1); 2045 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode()); 2046 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode()); 2047 EVT VT = N->getValueType(0); 2048 2049 // fold vector ops 2050 if (VT.isVector()) { 2051 SDValue FoldedVOp = SimplifyVBinOp(N); 2052 if (FoldedVOp.getNode()) return FoldedVOp; 2053 } 2054 2055 // fold (udiv c1, c2) -> c1/c2 2056 if (N0C && N1C && !N1C->isNullValue()) 2057 return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C); 2058 // fold (udiv x, (1 << c)) -> x >>u c 2059 if (N1C && N1C->getAPIntValue().isPowerOf2()) 2060 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, 2061 DAG.getConstant(N1C->getAPIntValue().logBase2(), 2062 getShiftAmountTy(N0.getValueType()))); 2063 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2 2064 if (N1.getOpcode() == ISD::SHL) { 2065 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) { 2066 if (SHC->getAPIntValue().isPowerOf2()) { 2067 EVT ADDVT = N1.getOperand(1).getValueType(); 2068 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N), ADDVT, 2069 N1.getOperand(1), 2070 DAG.getConstant(SHC->getAPIntValue() 2071 .logBase2(), 2072 ADDVT)); 2073 AddToWorkList(Add.getNode()); 2074 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, Add); 2075 } 2076 } 2077 } 2078 // fold (udiv x, c) -> alternate 2079 if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap()) { 2080 SDValue Op = BuildUDIV(N); 2081 if (Op.getNode()) return Op; 2082 } 2083 2084 // undef / X -> 0 2085 if (N0.getOpcode() == ISD::UNDEF) 2086 return DAG.getConstant(0, VT); 2087 // X / undef -> undef 2088 if (N1.getOpcode() == ISD::UNDEF) 2089 return N1; 2090 2091 return SDValue(); 2092 } 2093 2094 SDValue DAGCombiner::visitSREM(SDNode *N) { 2095 SDValue N0 = N->getOperand(0); 2096 SDValue N1 = N->getOperand(1); 2097 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 2098 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 2099 EVT VT = N->getValueType(0); 2100 2101 // fold (srem c1, c2) -> c1%c2 2102 if (N0C && N1C && !N1C->isNullValue()) 2103 return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C); 2104 // If we know the sign bits of both operands are zero, strength reduce to a 2105 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15 2106 if (!VT.isVector()) { 2107 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0)) 2108 return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1); 2109 } 2110 2111 // If X/C can be simplified by the division-by-constant logic, lower 2112 // X%C to the equivalent of X-X/C*C. 2113 if (N1C && !N1C->isNullValue()) { 2114 SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1); 2115 AddToWorkList(Div.getNode()); 2116 SDValue OptimizedDiv = combine(Div.getNode()); 2117 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) { 2118 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT, 2119 OptimizedDiv, N1); 2120 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul); 2121 AddToWorkList(Mul.getNode()); 2122 return Sub; 2123 } 2124 } 2125 2126 // undef % X -> 0 2127 if (N0.getOpcode() == ISD::UNDEF) 2128 return DAG.getConstant(0, VT); 2129 // X % undef -> undef 2130 if (N1.getOpcode() == ISD::UNDEF) 2131 return N1; 2132 2133 return SDValue(); 2134 } 2135 2136 SDValue DAGCombiner::visitUREM(SDNode *N) { 2137 SDValue N0 = N->getOperand(0); 2138 SDValue N1 = N->getOperand(1); 2139 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 2140 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 2141 EVT VT = N->getValueType(0); 2142 2143 // fold (urem c1, c2) -> c1%c2 2144 if (N0C && N1C && !N1C->isNullValue()) 2145 return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C); 2146 // fold (urem x, pow2) -> (and x, pow2-1) 2147 if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2()) 2148 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, 2149 DAG.getConstant(N1C->getAPIntValue()-1,VT)); 2150 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1)) 2151 if (N1.getOpcode() == ISD::SHL) { 2152 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) { 2153 if (SHC->getAPIntValue().isPowerOf2()) { 2154 SDValue Add = 2155 DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, 2156 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), 2157 VT)); 2158 AddToWorkList(Add.getNode()); 2159 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, Add); 2160 } 2161 } 2162 } 2163 2164 // If X/C can be simplified by the division-by-constant logic, lower 2165 // X%C to the equivalent of X-X/C*C. 2166 if (N1C && !N1C->isNullValue()) { 2167 SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1); 2168 AddToWorkList(Div.getNode()); 2169 SDValue OptimizedDiv = combine(Div.getNode()); 2170 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) { 2171 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT, 2172 OptimizedDiv, N1); 2173 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul); 2174 AddToWorkList(Mul.getNode()); 2175 return Sub; 2176 } 2177 } 2178 2179 // undef % X -> 0 2180 if (N0.getOpcode() == ISD::UNDEF) 2181 return DAG.getConstant(0, VT); 2182 // X % undef -> undef 2183 if (N1.getOpcode() == ISD::UNDEF) 2184 return N1; 2185 2186 return SDValue(); 2187 } 2188 2189 SDValue DAGCombiner::visitMULHS(SDNode *N) { 2190 SDValue N0 = N->getOperand(0); 2191 SDValue N1 = N->getOperand(1); 2192 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 2193 EVT VT = N->getValueType(0); 2194 SDLoc DL(N); 2195 2196 // fold (mulhs x, 0) -> 0 2197 if (N1C && N1C->isNullValue()) 2198 return N1; 2199 // fold (mulhs x, 1) -> (sra x, size(x)-1) 2200 if (N1C && N1C->getAPIntValue() == 1) 2201 return DAG.getNode(ISD::SRA, SDLoc(N), N0.getValueType(), N0, 2202 DAG.getConstant(N0.getValueType().getSizeInBits() - 1, 2203 getShiftAmountTy(N0.getValueType()))); 2204 // fold (mulhs x, undef) -> 0 2205 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF) 2206 return DAG.getConstant(0, VT); 2207 2208 // If the type twice as wide is legal, transform the mulhs to a wider multiply 2209 // plus a shift. 2210 if (VT.isSimple() && !VT.isVector()) { 2211 MVT Simple = VT.getSimpleVT(); 2212 unsigned SimpleSize = Simple.getSizeInBits(); 2213 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 2214 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 2215 N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0); 2216 N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1); 2217 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1); 2218 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1, 2219 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType()))); 2220 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1); 2221 } 2222 } 2223 2224 return SDValue(); 2225 } 2226 2227 SDValue DAGCombiner::visitMULHU(SDNode *N) { 2228 SDValue N0 = N->getOperand(0); 2229 SDValue N1 = N->getOperand(1); 2230 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 2231 EVT VT = N->getValueType(0); 2232 SDLoc DL(N); 2233 2234 // fold (mulhu x, 0) -> 0 2235 if (N1C && N1C->isNullValue()) 2236 return N1; 2237 // fold (mulhu x, 1) -> 0 2238 if (N1C && N1C->getAPIntValue() == 1) 2239 return DAG.getConstant(0, N0.getValueType()); 2240 // fold (mulhu x, undef) -> 0 2241 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF) 2242 return DAG.getConstant(0, VT); 2243 2244 // If the type twice as wide is legal, transform the mulhu to a wider multiply 2245 // plus a shift. 2246 if (VT.isSimple() && !VT.isVector()) { 2247 MVT Simple = VT.getSimpleVT(); 2248 unsigned SimpleSize = Simple.getSizeInBits(); 2249 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 2250 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 2251 N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0); 2252 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1); 2253 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1); 2254 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1, 2255 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType()))); 2256 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1); 2257 } 2258 } 2259 2260 return SDValue(); 2261 } 2262 2263 /// SimplifyNodeWithTwoResults - Perform optimizations common to nodes that 2264 /// compute two values. LoOp and HiOp give the opcodes for the two computations 2265 /// that are being performed. Return true if a simplification was made. 2266 /// 2267 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp, 2268 unsigned HiOp) { 2269 // If the high half is not needed, just compute the low half. 2270 bool HiExists = N->hasAnyUseOfValue(1); 2271 if (!HiExists && 2272 (!LegalOperations || 2273 TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) { 2274 SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), 2275 N->op_begin(), N->getNumOperands()); 2276 return CombineTo(N, Res, Res); 2277 } 2278 2279 // If the low half is not needed, just compute the high half. 2280 bool LoExists = N->hasAnyUseOfValue(0); 2281 if (!LoExists && 2282 (!LegalOperations || 2283 TLI.isOperationLegal(HiOp, N->getValueType(1)))) { 2284 SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), 2285 N->op_begin(), N->getNumOperands()); 2286 return CombineTo(N, Res, Res); 2287 } 2288 2289 // If both halves are used, return as it is. 2290 if (LoExists && HiExists) 2291 return SDValue(); 2292 2293 // If the two computed results can be simplified separately, separate them. 2294 if (LoExists) { 2295 SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), 2296 N->op_begin(), N->getNumOperands()); 2297 AddToWorkList(Lo.getNode()); 2298 SDValue LoOpt = combine(Lo.getNode()); 2299 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() && 2300 (!LegalOperations || 2301 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType()))) 2302 return CombineTo(N, LoOpt, LoOpt); 2303 } 2304 2305 if (HiExists) { 2306 SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), 2307 N->op_begin(), N->getNumOperands()); 2308 AddToWorkList(Hi.getNode()); 2309 SDValue HiOpt = combine(Hi.getNode()); 2310 if (HiOpt.getNode() && HiOpt != Hi && 2311 (!LegalOperations || 2312 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType()))) 2313 return CombineTo(N, HiOpt, HiOpt); 2314 } 2315 2316 return SDValue(); 2317 } 2318 2319 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) { 2320 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS); 2321 if (Res.getNode()) return Res; 2322 2323 EVT VT = N->getValueType(0); 2324 SDLoc DL(N); 2325 2326 // If the type twice as wide is legal, transform the mulhu to a wider multiply 2327 // plus a shift. 2328 if (VT.isSimple() && !VT.isVector()) { 2329 MVT Simple = VT.getSimpleVT(); 2330 unsigned SimpleSize = Simple.getSizeInBits(); 2331 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 2332 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 2333 SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0)); 2334 SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1)); 2335 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi); 2336 // Compute the high part as N1. 2337 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo, 2338 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType()))); 2339 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi); 2340 // Compute the low part as N0. 2341 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo); 2342 return CombineTo(N, Lo, Hi); 2343 } 2344 } 2345 2346 return SDValue(); 2347 } 2348 2349 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) { 2350 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU); 2351 if (Res.getNode()) return Res; 2352 2353 EVT VT = N->getValueType(0); 2354 SDLoc DL(N); 2355 2356 // If the type twice as wide is legal, transform the mulhu to a wider multiply 2357 // plus a shift. 2358 if (VT.isSimple() && !VT.isVector()) { 2359 MVT Simple = VT.getSimpleVT(); 2360 unsigned SimpleSize = Simple.getSizeInBits(); 2361 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 2362 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 2363 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0)); 2364 SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1)); 2365 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi); 2366 // Compute the high part as N1. 2367 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo, 2368 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType()))); 2369 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi); 2370 // Compute the low part as N0. 2371 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo); 2372 return CombineTo(N, Lo, Hi); 2373 } 2374 } 2375 2376 return SDValue(); 2377 } 2378 2379 SDValue DAGCombiner::visitSMULO(SDNode *N) { 2380 // (smulo x, 2) -> (saddo x, x) 2381 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1))) 2382 if (C2->getAPIntValue() == 2) 2383 return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(), 2384 N->getOperand(0), N->getOperand(0)); 2385 2386 return SDValue(); 2387 } 2388 2389 SDValue DAGCombiner::visitUMULO(SDNode *N) { 2390 // (umulo x, 2) -> (uaddo x, x) 2391 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1))) 2392 if (C2->getAPIntValue() == 2) 2393 return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(), 2394 N->getOperand(0), N->getOperand(0)); 2395 2396 return SDValue(); 2397 } 2398 2399 SDValue DAGCombiner::visitSDIVREM(SDNode *N) { 2400 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM); 2401 if (Res.getNode()) return Res; 2402 2403 return SDValue(); 2404 } 2405 2406 SDValue DAGCombiner::visitUDIVREM(SDNode *N) { 2407 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM); 2408 if (Res.getNode()) return Res; 2409 2410 return SDValue(); 2411 } 2412 2413 /// SimplifyBinOpWithSameOpcodeHands - If this is a binary operator with 2414 /// two operands of the same opcode, try to simplify it. 2415 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) { 2416 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1); 2417 EVT VT = N0.getValueType(); 2418 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!"); 2419 2420 // Bail early if none of these transforms apply. 2421 if (N0.getNode()->getNumOperands() == 0) return SDValue(); 2422 2423 // For each of OP in AND/OR/XOR: 2424 // fold (OP (zext x), (zext y)) -> (zext (OP x, y)) 2425 // fold (OP (sext x), (sext y)) -> (sext (OP x, y)) 2426 // fold (OP (aext x), (aext y)) -> (aext (OP x, y)) 2427 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free) 2428 // 2429 // do not sink logical op inside of a vector extend, since it may combine 2430 // into a vsetcc. 2431 EVT Op0VT = N0.getOperand(0).getValueType(); 2432 if ((N0.getOpcode() == ISD::ZERO_EXTEND || 2433 N0.getOpcode() == ISD::SIGN_EXTEND || 2434 // Avoid infinite looping with PromoteIntBinOp. 2435 (N0.getOpcode() == ISD::ANY_EXTEND && 2436 (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) || 2437 (N0.getOpcode() == ISD::TRUNCATE && 2438 (!TLI.isZExtFree(VT, Op0VT) || 2439 !TLI.isTruncateFree(Op0VT, VT)) && 2440 TLI.isTypeLegal(Op0VT))) && 2441 !VT.isVector() && 2442 Op0VT == N1.getOperand(0).getValueType() && 2443 (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) { 2444 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0), 2445 N0.getOperand(0).getValueType(), 2446 N0.getOperand(0), N1.getOperand(0)); 2447 AddToWorkList(ORNode.getNode()); 2448 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode); 2449 } 2450 2451 // For each of OP in SHL/SRL/SRA/AND... 2452 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z) 2453 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z) 2454 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z) 2455 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL || 2456 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) && 2457 N0.getOperand(1) == N1.getOperand(1)) { 2458 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0), 2459 N0.getOperand(0).getValueType(), 2460 N0.getOperand(0), N1.getOperand(0)); 2461 AddToWorkList(ORNode.getNode()); 2462 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, 2463 ORNode, N0.getOperand(1)); 2464 } 2465 2466 // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B)) 2467 // Only perform this optimization after type legalization and before 2468 // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by 2469 // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and 2470 // we don't want to undo this promotion. 2471 // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper 2472 // on scalars. 2473 if ((N0.getOpcode() == ISD::BITCAST || 2474 N0.getOpcode() == ISD::SCALAR_TO_VECTOR) && 2475 Level == AfterLegalizeTypes) { 2476 SDValue In0 = N0.getOperand(0); 2477 SDValue In1 = N1.getOperand(0); 2478 EVT In0Ty = In0.getValueType(); 2479 EVT In1Ty = In1.getValueType(); 2480 SDLoc DL(N); 2481 // If both incoming values are integers, and the original types are the 2482 // same. 2483 if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) { 2484 SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1); 2485 SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op); 2486 AddToWorkList(Op.getNode()); 2487 return BC; 2488 } 2489 } 2490 2491 // Xor/and/or are indifferent to the swizzle operation (shuffle of one value). 2492 // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B)) 2493 // If both shuffles use the same mask, and both shuffle within a single 2494 // vector, then it is worthwhile to move the swizzle after the operation. 2495 // The type-legalizer generates this pattern when loading illegal 2496 // vector types from memory. In many cases this allows additional shuffle 2497 // optimizations. 2498 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG && 2499 N0.getOperand(1).getOpcode() == ISD::UNDEF && 2500 N1.getOperand(1).getOpcode() == ISD::UNDEF) { 2501 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0); 2502 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1); 2503 2504 assert(N0.getOperand(0).getValueType() == N1.getOperand(1).getValueType() && 2505 "Inputs to shuffles are not the same type"); 2506 2507 unsigned NumElts = VT.getVectorNumElements(); 2508 2509 // Check that both shuffles use the same mask. The masks are known to be of 2510 // the same length because the result vector type is the same. 2511 bool SameMask = true; 2512 for (unsigned i = 0; i != NumElts; ++i) { 2513 int Idx0 = SVN0->getMaskElt(i); 2514 int Idx1 = SVN1->getMaskElt(i); 2515 if (Idx0 != Idx1) { 2516 SameMask = false; 2517 break; 2518 } 2519 } 2520 2521 if (SameMask) { 2522 SDValue Op = DAG.getNode(N->getOpcode(), SDLoc(N), VT, 2523 N0.getOperand(0), N1.getOperand(0)); 2524 AddToWorkList(Op.getNode()); 2525 return DAG.getVectorShuffle(VT, SDLoc(N), Op, 2526 DAG.getUNDEF(VT), &SVN0->getMask()[0]); 2527 } 2528 } 2529 2530 return SDValue(); 2531 } 2532 2533 SDValue DAGCombiner::visitAND(SDNode *N) { 2534 SDValue N0 = N->getOperand(0); 2535 SDValue N1 = N->getOperand(1); 2536 SDValue LL, LR, RL, RR, CC0, CC1; 2537 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 2538 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 2539 EVT VT = N1.getValueType(); 2540 unsigned BitWidth = VT.getScalarType().getSizeInBits(); 2541 2542 // fold vector ops 2543 if (VT.isVector()) { 2544 SDValue FoldedVOp = SimplifyVBinOp(N); 2545 if (FoldedVOp.getNode()) return FoldedVOp; 2546 2547 // fold (and x, 0) -> 0, vector edition 2548 if (ISD::isBuildVectorAllZeros(N0.getNode())) 2549 return N0; 2550 if (ISD::isBuildVectorAllZeros(N1.getNode())) 2551 return N1; 2552 2553 // fold (and x, -1) -> x, vector edition 2554 if (ISD::isBuildVectorAllOnes(N0.getNode())) 2555 return N1; 2556 if (ISD::isBuildVectorAllOnes(N1.getNode())) 2557 return N0; 2558 } 2559 2560 // fold (and x, undef) -> 0 2561 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF) 2562 return DAG.getConstant(0, VT); 2563 // fold (and c1, c2) -> c1&c2 2564 if (N0C && N1C) 2565 return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C); 2566 // canonicalize constant to RHS 2567 if (N0C && !N1C) 2568 return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0); 2569 // fold (and x, -1) -> x 2570 if (N1C && N1C->isAllOnesValue()) 2571 return N0; 2572 // if (and x, c) is known to be zero, return 0 2573 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0), 2574 APInt::getAllOnesValue(BitWidth))) 2575 return DAG.getConstant(0, VT); 2576 // reassociate and 2577 SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1); 2578 if (RAND.getNode() != 0) 2579 return RAND; 2580 // fold (and (or x, C), D) -> D if (C & D) == D 2581 if (N1C && N0.getOpcode() == ISD::OR) 2582 if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) 2583 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue()) 2584 return N1; 2585 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits. 2586 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) { 2587 SDValue N0Op0 = N0.getOperand(0); 2588 APInt Mask = ~N1C->getAPIntValue(); 2589 Mask = Mask.trunc(N0Op0.getValueSizeInBits()); 2590 if (DAG.MaskedValueIsZero(N0Op0, Mask)) { 2591 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), 2592 N0.getValueType(), N0Op0); 2593 2594 // Replace uses of the AND with uses of the Zero extend node. 2595 CombineTo(N, Zext); 2596 2597 // We actually want to replace all uses of the any_extend with the 2598 // zero_extend, to avoid duplicating things. This will later cause this 2599 // AND to be folded. 2600 CombineTo(N0.getNode(), Zext); 2601 return SDValue(N, 0); // Return N so it doesn't get rechecked! 2602 } 2603 } 2604 // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) -> 2605 // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must 2606 // already be zero by virtue of the width of the base type of the load. 2607 // 2608 // the 'X' node here can either be nothing or an extract_vector_elt to catch 2609 // more cases. 2610 if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT && 2611 N0.getOperand(0).getOpcode() == ISD::LOAD) || 2612 N0.getOpcode() == ISD::LOAD) { 2613 LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ? 2614 N0 : N0.getOperand(0) ); 2615 2616 // Get the constant (if applicable) the zero'th operand is being ANDed with. 2617 // This can be a pure constant or a vector splat, in which case we treat the 2618 // vector as a scalar and use the splat value. 2619 APInt Constant = APInt::getNullValue(1); 2620 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) { 2621 Constant = C->getAPIntValue(); 2622 } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) { 2623 APInt SplatValue, SplatUndef; 2624 unsigned SplatBitSize; 2625 bool HasAnyUndefs; 2626 bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef, 2627 SplatBitSize, HasAnyUndefs); 2628 if (IsSplat) { 2629 // Undef bits can contribute to a possible optimisation if set, so 2630 // set them. 2631 SplatValue |= SplatUndef; 2632 2633 // The splat value may be something like "0x00FFFFFF", which means 0 for 2634 // the first vector value and FF for the rest, repeating. We need a mask 2635 // that will apply equally to all members of the vector, so AND all the 2636 // lanes of the constant together. 2637 EVT VT = Vector->getValueType(0); 2638 unsigned BitWidth = VT.getVectorElementType().getSizeInBits(); 2639 2640 // If the splat value has been compressed to a bitlength lower 2641 // than the size of the vector lane, we need to re-expand it to 2642 // the lane size. 2643 if (BitWidth > SplatBitSize) 2644 for (SplatValue = SplatValue.zextOrTrunc(BitWidth); 2645 SplatBitSize < BitWidth; 2646 SplatBitSize = SplatBitSize * 2) 2647 SplatValue |= SplatValue.shl(SplatBitSize); 2648 2649 Constant = APInt::getAllOnesValue(BitWidth); 2650 for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i) 2651 Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth); 2652 } 2653 } 2654 2655 // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is 2656 // actually legal and isn't going to get expanded, else this is a false 2657 // optimisation. 2658 bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD, 2659 Load->getMemoryVT()); 2660 2661 // Resize the constant to the same size as the original memory access before 2662 // extension. If it is still the AllOnesValue then this AND is completely 2663 // unneeded. 2664 Constant = 2665 Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits()); 2666 2667 bool B; 2668 switch (Load->getExtensionType()) { 2669 default: B = false; break; 2670 case ISD::EXTLOAD: B = CanZextLoadProfitably; break; 2671 case ISD::ZEXTLOAD: 2672 case ISD::NON_EXTLOAD: B = true; break; 2673 } 2674 2675 if (B && Constant.isAllOnesValue()) { 2676 // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to 2677 // preserve semantics once we get rid of the AND. 2678 SDValue NewLoad(Load, 0); 2679 if (Load->getExtensionType() == ISD::EXTLOAD) { 2680 NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD, 2681 Load->getValueType(0), SDLoc(Load), 2682 Load->getChain(), Load->getBasePtr(), 2683 Load->getOffset(), Load->getMemoryVT(), 2684 Load->getMemOperand()); 2685 // Replace uses of the EXTLOAD with the new ZEXTLOAD. 2686 if (Load->getNumValues() == 3) { 2687 // PRE/POST_INC loads have 3 values. 2688 SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1), 2689 NewLoad.getValue(2) }; 2690 CombineTo(Load, To, 3, true); 2691 } else { 2692 CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1)); 2693 } 2694 } 2695 2696 // Fold the AND away, taking care not to fold to the old load node if we 2697 // replaced it. 2698 CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0); 2699 2700 return SDValue(N, 0); // Return N so it doesn't get rechecked! 2701 } 2702 } 2703 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y)) 2704 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){ 2705 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get(); 2706 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get(); 2707 2708 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 && 2709 LL.getValueType().isInteger()) { 2710 // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0) 2711 if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) { 2712 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0), 2713 LR.getValueType(), LL, RL); 2714 AddToWorkList(ORNode.getNode()); 2715 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1); 2716 } 2717 // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1) 2718 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) { 2719 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0), 2720 LR.getValueType(), LL, RL); 2721 AddToWorkList(ANDNode.getNode()); 2722 return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1); 2723 } 2724 // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1) 2725 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) { 2726 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0), 2727 LR.getValueType(), LL, RL); 2728 AddToWorkList(ORNode.getNode()); 2729 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1); 2730 } 2731 } 2732 // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2) 2733 if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) && 2734 Op0 == Op1 && LL.getValueType().isInteger() && 2735 Op0 == ISD::SETNE && ((cast<ConstantSDNode>(LR)->isNullValue() && 2736 cast<ConstantSDNode>(RR)->isAllOnesValue()) || 2737 (cast<ConstantSDNode>(LR)->isAllOnesValue() && 2738 cast<ConstantSDNode>(RR)->isNullValue()))) { 2739 SDValue ADDNode = DAG.getNode(ISD::ADD, SDLoc(N0), LL.getValueType(), 2740 LL, DAG.getConstant(1, LL.getValueType())); 2741 AddToWorkList(ADDNode.getNode()); 2742 return DAG.getSetCC(SDLoc(N), VT, ADDNode, 2743 DAG.getConstant(2, LL.getValueType()), ISD::SETUGE); 2744 } 2745 // canonicalize equivalent to ll == rl 2746 if (LL == RR && LR == RL) { 2747 Op1 = ISD::getSetCCSwappedOperands(Op1); 2748 std::swap(RL, RR); 2749 } 2750 if (LL == RL && LR == RR) { 2751 bool isInteger = LL.getValueType().isInteger(); 2752 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger); 2753 if (Result != ISD::SETCC_INVALID && 2754 (!LegalOperations || 2755 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) && 2756 TLI.isOperationLegal(ISD::SETCC, 2757 getSetCCResultType(N0.getSimpleValueType()))))) 2758 return DAG.getSetCC(SDLoc(N), N0.getValueType(), 2759 LL, LR, Result); 2760 } 2761 } 2762 2763 // Simplify: (and (op x...), (op y...)) -> (op (and x, y)) 2764 if (N0.getOpcode() == N1.getOpcode()) { 2765 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N); 2766 if (Tmp.getNode()) return Tmp; 2767 } 2768 2769 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1) 2770 // fold (and (sra)) -> (and (srl)) when possible. 2771 if (!VT.isVector() && 2772 SimplifyDemandedBits(SDValue(N, 0))) 2773 return SDValue(N, 0); 2774 2775 // fold (zext_inreg (extload x)) -> (zextload x) 2776 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) { 2777 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 2778 EVT MemVT = LN0->getMemoryVT(); 2779 // If we zero all the possible extended bits, then we can turn this into 2780 // a zextload if we are running before legalize or the operation is legal. 2781 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits(); 2782 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth, 2783 BitWidth - MemVT.getScalarType().getSizeInBits())) && 2784 ((!LegalOperations && !LN0->isVolatile()) || 2785 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) { 2786 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT, 2787 LN0->getChain(), LN0->getBasePtr(), 2788 MemVT, LN0->getMemOperand()); 2789 AddToWorkList(N); 2790 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 2791 return SDValue(N, 0); // Return N so it doesn't get rechecked! 2792 } 2793 } 2794 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use 2795 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 2796 N0.hasOneUse()) { 2797 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 2798 EVT MemVT = LN0->getMemoryVT(); 2799 // If we zero all the possible extended bits, then we can turn this into 2800 // a zextload if we are running before legalize or the operation is legal. 2801 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits(); 2802 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth, 2803 BitWidth - MemVT.getScalarType().getSizeInBits())) && 2804 ((!LegalOperations && !LN0->isVolatile()) || 2805 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) { 2806 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT, 2807 LN0->getChain(), LN0->getBasePtr(), 2808 MemVT, LN0->getMemOperand()); 2809 AddToWorkList(N); 2810 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 2811 return SDValue(N, 0); // Return N so it doesn't get rechecked! 2812 } 2813 } 2814 2815 // fold (and (load x), 255) -> (zextload x, i8) 2816 // fold (and (extload x, i16), 255) -> (zextload x, i8) 2817 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8) 2818 if (N1C && (N0.getOpcode() == ISD::LOAD || 2819 (N0.getOpcode() == ISD::ANY_EXTEND && 2820 N0.getOperand(0).getOpcode() == ISD::LOAD))) { 2821 bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND; 2822 LoadSDNode *LN0 = HasAnyExt 2823 ? cast<LoadSDNode>(N0.getOperand(0)) 2824 : cast<LoadSDNode>(N0); 2825 if (LN0->getExtensionType() != ISD::SEXTLOAD && 2826 LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) { 2827 uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits(); 2828 if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){ 2829 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits); 2830 EVT LoadedVT = LN0->getMemoryVT(); 2831 2832 if (ExtVT == LoadedVT && 2833 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) { 2834 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT; 2835 2836 SDValue NewLoad = 2837 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy, 2838 LN0->getChain(), LN0->getBasePtr(), ExtVT, 2839 LN0->getMemOperand()); 2840 AddToWorkList(N); 2841 CombineTo(LN0, NewLoad, NewLoad.getValue(1)); 2842 return SDValue(N, 0); // Return N so it doesn't get rechecked! 2843 } 2844 2845 // Do not change the width of a volatile load. 2846 // Do not generate loads of non-round integer types since these can 2847 // be expensive (and would be wrong if the type is not byte sized). 2848 if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() && 2849 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) { 2850 EVT PtrType = LN0->getOperand(1).getValueType(); 2851 2852 unsigned Alignment = LN0->getAlignment(); 2853 SDValue NewPtr = LN0->getBasePtr(); 2854 2855 // For big endian targets, we need to add an offset to the pointer 2856 // to load the correct bytes. For little endian systems, we merely 2857 // need to read fewer bytes from the same pointer. 2858 if (TLI.isBigEndian()) { 2859 unsigned LVTStoreBytes = LoadedVT.getStoreSize(); 2860 unsigned EVTStoreBytes = ExtVT.getStoreSize(); 2861 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes; 2862 NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0), PtrType, 2863 NewPtr, DAG.getConstant(PtrOff, PtrType)); 2864 Alignment = MinAlign(Alignment, PtrOff); 2865 } 2866 2867 AddToWorkList(NewPtr.getNode()); 2868 2869 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT; 2870 SDValue Load = 2871 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy, 2872 LN0->getChain(), NewPtr, 2873 LN0->getPointerInfo(), 2874 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(), 2875 Alignment, LN0->getTBAAInfo()); 2876 AddToWorkList(N); 2877 CombineTo(LN0, Load, Load.getValue(1)); 2878 return SDValue(N, 0); // Return N so it doesn't get rechecked! 2879 } 2880 } 2881 } 2882 } 2883 2884 if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL && 2885 VT.getSizeInBits() <= 64) { 2886 if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 2887 APInt ADDC = ADDI->getAPIntValue(); 2888 if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) { 2889 // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal 2890 // immediate for an add, but it is legal if its top c2 bits are set, 2891 // transform the ADD so the immediate doesn't need to be materialized 2892 // in a register. 2893 if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) { 2894 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(), 2895 SRLI->getZExtValue()); 2896 if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) { 2897 ADDC |= Mask; 2898 if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) { 2899 SDValue NewAdd = 2900 DAG.getNode(ISD::ADD, SDLoc(N0), VT, 2901 N0.getOperand(0), DAG.getConstant(ADDC, VT)); 2902 CombineTo(N0.getNode(), NewAdd); 2903 return SDValue(N, 0); // Return N so it doesn't get rechecked! 2904 } 2905 } 2906 } 2907 } 2908 } 2909 } 2910 2911 // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const) 2912 if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) { 2913 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0), 2914 N0.getOperand(1), false); 2915 if (BSwap.getNode()) 2916 return BSwap; 2917 } 2918 2919 return SDValue(); 2920 } 2921 2922 /// MatchBSwapHWord - Match (a >> 8) | (a << 8) as (bswap a) >> 16 2923 /// 2924 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1, 2925 bool DemandHighBits) { 2926 if (!LegalOperations) 2927 return SDValue(); 2928 2929 EVT VT = N->getValueType(0); 2930 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16) 2931 return SDValue(); 2932 if (!TLI.isOperationLegal(ISD::BSWAP, VT)) 2933 return SDValue(); 2934 2935 // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00) 2936 bool LookPassAnd0 = false; 2937 bool LookPassAnd1 = false; 2938 if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL) 2939 std::swap(N0, N1); 2940 if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL) 2941 std::swap(N0, N1); 2942 if (N0.getOpcode() == ISD::AND) { 2943 if (!N0.getNode()->hasOneUse()) 2944 return SDValue(); 2945 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 2946 if (!N01C || N01C->getZExtValue() != 0xFF00) 2947 return SDValue(); 2948 N0 = N0.getOperand(0); 2949 LookPassAnd0 = true; 2950 } 2951 2952 if (N1.getOpcode() == ISD::AND) { 2953 if (!N1.getNode()->hasOneUse()) 2954 return SDValue(); 2955 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 2956 if (!N11C || N11C->getZExtValue() != 0xFF) 2957 return SDValue(); 2958 N1 = N1.getOperand(0); 2959 LookPassAnd1 = true; 2960 } 2961 2962 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL) 2963 std::swap(N0, N1); 2964 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL) 2965 return SDValue(); 2966 if (!N0.getNode()->hasOneUse() || 2967 !N1.getNode()->hasOneUse()) 2968 return SDValue(); 2969 2970 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 2971 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 2972 if (!N01C || !N11C) 2973 return SDValue(); 2974 if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8) 2975 return SDValue(); 2976 2977 // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8) 2978 SDValue N00 = N0->getOperand(0); 2979 if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) { 2980 if (!N00.getNode()->hasOneUse()) 2981 return SDValue(); 2982 ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1)); 2983 if (!N001C || N001C->getZExtValue() != 0xFF) 2984 return SDValue(); 2985 N00 = N00.getOperand(0); 2986 LookPassAnd0 = true; 2987 } 2988 2989 SDValue N10 = N1->getOperand(0); 2990 if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) { 2991 if (!N10.getNode()->hasOneUse()) 2992 return SDValue(); 2993 ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1)); 2994 if (!N101C || N101C->getZExtValue() != 0xFF00) 2995 return SDValue(); 2996 N10 = N10.getOperand(0); 2997 LookPassAnd1 = true; 2998 } 2999 3000 if (N00 != N10) 3001 return SDValue(); 3002 3003 // Make sure everything beyond the low halfword gets set to zero since the SRL 3004 // 16 will clear the top bits. 3005 unsigned OpSizeInBits = VT.getSizeInBits(); 3006 if (DemandHighBits && OpSizeInBits > 16) { 3007 // If the left-shift isn't masked out then the only way this is a bswap is 3008 // if all bits beyond the low 8 are 0. In that case the entire pattern 3009 // reduces to a left shift anyway: leave it for other parts of the combiner. 3010 if (!LookPassAnd0) 3011 return SDValue(); 3012 3013 // However, if the right shift isn't masked out then it might be because 3014 // it's not needed. See if we can spot that too. 3015 if (!LookPassAnd1 && 3016 !DAG.MaskedValueIsZero( 3017 N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16))) 3018 return SDValue(); 3019 } 3020 3021 SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00); 3022 if (OpSizeInBits > 16) 3023 Res = DAG.getNode(ISD::SRL, SDLoc(N), VT, Res, 3024 DAG.getConstant(OpSizeInBits-16, getShiftAmountTy(VT))); 3025 return Res; 3026 } 3027 3028 /// isBSwapHWordElement - Return true if the specified node is an element 3029 /// that makes up a 32-bit packed halfword byteswap. i.e. 3030 /// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8) 3031 static bool isBSwapHWordElement(SDValue N, SmallVectorImpl<SDNode *> &Parts) { 3032 if (!N.getNode()->hasOneUse()) 3033 return false; 3034 3035 unsigned Opc = N.getOpcode(); 3036 if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL) 3037 return false; 3038 3039 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1)); 3040 if (!N1C) 3041 return false; 3042 3043 unsigned Num; 3044 switch (N1C->getZExtValue()) { 3045 default: 3046 return false; 3047 case 0xFF: Num = 0; break; 3048 case 0xFF00: Num = 1; break; 3049 case 0xFF0000: Num = 2; break; 3050 case 0xFF000000: Num = 3; break; 3051 } 3052 3053 // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00). 3054 SDValue N0 = N.getOperand(0); 3055 if (Opc == ISD::AND) { 3056 if (Num == 0 || Num == 2) { 3057 // (x >> 8) & 0xff 3058 // (x >> 8) & 0xff0000 3059 if (N0.getOpcode() != ISD::SRL) 3060 return false; 3061 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 3062 if (!C || C->getZExtValue() != 8) 3063 return false; 3064 } else { 3065 // (x << 8) & 0xff00 3066 // (x << 8) & 0xff000000 3067 if (N0.getOpcode() != ISD::SHL) 3068 return false; 3069 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 3070 if (!C || C->getZExtValue() != 8) 3071 return false; 3072 } 3073 } else if (Opc == ISD::SHL) { 3074 // (x & 0xff) << 8 3075 // (x & 0xff0000) << 8 3076 if (Num != 0 && Num != 2) 3077 return false; 3078 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1)); 3079 if (!C || C->getZExtValue() != 8) 3080 return false; 3081 } else { // Opc == ISD::SRL 3082 // (x & 0xff00) >> 8 3083 // (x & 0xff000000) >> 8 3084 if (Num != 1 && Num != 3) 3085 return false; 3086 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1)); 3087 if (!C || C->getZExtValue() != 8) 3088 return false; 3089 } 3090 3091 if (Parts[Num]) 3092 return false; 3093 3094 Parts[Num] = N0.getOperand(0).getNode(); 3095 return true; 3096 } 3097 3098 /// MatchBSwapHWord - Match a 32-bit packed halfword bswap. That is 3099 /// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8) 3100 /// => (rotl (bswap x), 16) 3101 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) { 3102 if (!LegalOperations) 3103 return SDValue(); 3104 3105 EVT VT = N->getValueType(0); 3106 if (VT != MVT::i32) 3107 return SDValue(); 3108 if (!TLI.isOperationLegal(ISD::BSWAP, VT)) 3109 return SDValue(); 3110 3111 SmallVector<SDNode*,4> Parts(4, (SDNode*)0); 3112 // Look for either 3113 // (or (or (and), (and)), (or (and), (and))) 3114 // (or (or (or (and), (and)), (and)), (and)) 3115 if (N0.getOpcode() != ISD::OR) 3116 return SDValue(); 3117 SDValue N00 = N0.getOperand(0); 3118 SDValue N01 = N0.getOperand(1); 3119 3120 if (N1.getOpcode() == ISD::OR && 3121 N00.getNumOperands() == 2 && N01.getNumOperands() == 2) { 3122 // (or (or (and), (and)), (or (and), (and))) 3123 SDValue N000 = N00.getOperand(0); 3124 if (!isBSwapHWordElement(N000, Parts)) 3125 return SDValue(); 3126 3127 SDValue N001 = N00.getOperand(1); 3128 if (!isBSwapHWordElement(N001, Parts)) 3129 return SDValue(); 3130 SDValue N010 = N01.getOperand(0); 3131 if (!isBSwapHWordElement(N010, Parts)) 3132 return SDValue(); 3133 SDValue N011 = N01.getOperand(1); 3134 if (!isBSwapHWordElement(N011, Parts)) 3135 return SDValue(); 3136 } else { 3137 // (or (or (or (and), (and)), (and)), (and)) 3138 if (!isBSwapHWordElement(N1, Parts)) 3139 return SDValue(); 3140 if (!isBSwapHWordElement(N01, Parts)) 3141 return SDValue(); 3142 if (N00.getOpcode() != ISD::OR) 3143 return SDValue(); 3144 SDValue N000 = N00.getOperand(0); 3145 if (!isBSwapHWordElement(N000, Parts)) 3146 return SDValue(); 3147 SDValue N001 = N00.getOperand(1); 3148 if (!isBSwapHWordElement(N001, Parts)) 3149 return SDValue(); 3150 } 3151 3152 // Make sure the parts are all coming from the same node. 3153 if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3]) 3154 return SDValue(); 3155 3156 SDValue BSwap = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, 3157 SDValue(Parts[0],0)); 3158 3159 // Result of the bswap should be rotated by 16. If it's not legal, then 3160 // do (x << 16) | (x >> 16). 3161 SDValue ShAmt = DAG.getConstant(16, getShiftAmountTy(VT)); 3162 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT)) 3163 return DAG.getNode(ISD::ROTL, SDLoc(N), VT, BSwap, ShAmt); 3164 if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT)) 3165 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, BSwap, ShAmt); 3166 return DAG.getNode(ISD::OR, SDLoc(N), VT, 3167 DAG.getNode(ISD::SHL, SDLoc(N), VT, BSwap, ShAmt), 3168 DAG.getNode(ISD::SRL, SDLoc(N), VT, BSwap, ShAmt)); 3169 } 3170 3171 SDValue DAGCombiner::visitOR(SDNode *N) { 3172 SDValue N0 = N->getOperand(0); 3173 SDValue N1 = N->getOperand(1); 3174 SDValue LL, LR, RL, RR, CC0, CC1; 3175 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 3176 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 3177 EVT VT = N1.getValueType(); 3178 3179 // fold vector ops 3180 if (VT.isVector()) { 3181 SDValue FoldedVOp = SimplifyVBinOp(N); 3182 if (FoldedVOp.getNode()) return FoldedVOp; 3183 3184 // fold (or x, 0) -> x, vector edition 3185 if (ISD::isBuildVectorAllZeros(N0.getNode())) 3186 return N1; 3187 if (ISD::isBuildVectorAllZeros(N1.getNode())) 3188 return N0; 3189 3190 // fold (or x, -1) -> -1, vector edition 3191 if (ISD::isBuildVectorAllOnes(N0.getNode())) 3192 return N0; 3193 if (ISD::isBuildVectorAllOnes(N1.getNode())) 3194 return N1; 3195 } 3196 3197 // fold (or x, undef) -> -1 3198 if (!LegalOperations && 3199 (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) { 3200 EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT; 3201 return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT); 3202 } 3203 // fold (or c1, c2) -> c1|c2 3204 if (N0C && N1C) 3205 return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C); 3206 // canonicalize constant to RHS 3207 if (N0C && !N1C) 3208 return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0); 3209 // fold (or x, 0) -> x 3210 if (N1C && N1C->isNullValue()) 3211 return N0; 3212 // fold (or x, -1) -> -1 3213 if (N1C && N1C->isAllOnesValue()) 3214 return N1; 3215 // fold (or x, c) -> c iff (x & ~c) == 0 3216 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue())) 3217 return N1; 3218 3219 // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16) 3220 SDValue BSwap = MatchBSwapHWord(N, N0, N1); 3221 if (BSwap.getNode() != 0) 3222 return BSwap; 3223 BSwap = MatchBSwapHWordLow(N, N0, N1); 3224 if (BSwap.getNode() != 0) 3225 return BSwap; 3226 3227 // reassociate or 3228 SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1); 3229 if (ROR.getNode() != 0) 3230 return ROR; 3231 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2) 3232 // iff (c1 & c2) == 0. 3233 if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() && 3234 isa<ConstantSDNode>(N0.getOperand(1))) { 3235 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1)); 3236 if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) { 3237 SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1); 3238 if (!COR.getNode()) 3239 return SDValue(); 3240 return DAG.getNode(ISD::AND, SDLoc(N), VT, 3241 DAG.getNode(ISD::OR, SDLoc(N0), VT, 3242 N0.getOperand(0), N1), COR); 3243 } 3244 } 3245 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y)) 3246 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){ 3247 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get(); 3248 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get(); 3249 3250 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 && 3251 LL.getValueType().isInteger()) { 3252 // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0) 3253 // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0) 3254 if (cast<ConstantSDNode>(LR)->isNullValue() && 3255 (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) { 3256 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR), 3257 LR.getValueType(), LL, RL); 3258 AddToWorkList(ORNode.getNode()); 3259 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1); 3260 } 3261 // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1) 3262 // fold (or (setgt X, -1), (setgt Y -1)) -> (setgt (and X, Y), -1) 3263 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && 3264 (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) { 3265 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR), 3266 LR.getValueType(), LL, RL); 3267 AddToWorkList(ANDNode.getNode()); 3268 return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1); 3269 } 3270 } 3271 // canonicalize equivalent to ll == rl 3272 if (LL == RR && LR == RL) { 3273 Op1 = ISD::getSetCCSwappedOperands(Op1); 3274 std::swap(RL, RR); 3275 } 3276 if (LL == RL && LR == RR) { 3277 bool isInteger = LL.getValueType().isInteger(); 3278 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger); 3279 if (Result != ISD::SETCC_INVALID && 3280 (!LegalOperations || 3281 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) && 3282 TLI.isOperationLegal(ISD::SETCC, 3283 getSetCCResultType(N0.getValueType()))))) 3284 return DAG.getSetCC(SDLoc(N), N0.getValueType(), 3285 LL, LR, Result); 3286 } 3287 } 3288 3289 // Simplify: (or (op x...), (op y...)) -> (op (or x, y)) 3290 if (N0.getOpcode() == N1.getOpcode()) { 3291 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N); 3292 if (Tmp.getNode()) return Tmp; 3293 } 3294 3295 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible. 3296 if (N0.getOpcode() == ISD::AND && 3297 N1.getOpcode() == ISD::AND && 3298 N0.getOperand(1).getOpcode() == ISD::Constant && 3299 N1.getOperand(1).getOpcode() == ISD::Constant && 3300 // Don't increase # computations. 3301 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) { 3302 // We can only do this xform if we know that bits from X that are set in C2 3303 // but not in C1 are already zero. Likewise for Y. 3304 const APInt &LHSMask = 3305 cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 3306 const APInt &RHSMask = 3307 cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue(); 3308 3309 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) && 3310 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) { 3311 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT, 3312 N0.getOperand(0), N1.getOperand(0)); 3313 return DAG.getNode(ISD::AND, SDLoc(N), VT, X, 3314 DAG.getConstant(LHSMask | RHSMask, VT)); 3315 } 3316 } 3317 3318 // See if this is some rotate idiom. 3319 if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N))) 3320 return SDValue(Rot, 0); 3321 3322 // Simplify the operands using demanded-bits information. 3323 if (!VT.isVector() && 3324 SimplifyDemandedBits(SDValue(N, 0))) 3325 return SDValue(N, 0); 3326 3327 return SDValue(); 3328 } 3329 3330 /// MatchRotateHalf - Match "(X shl/srl V1) & V2" where V2 may not be present. 3331 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) { 3332 if (Op.getOpcode() == ISD::AND) { 3333 if (isa<ConstantSDNode>(Op.getOperand(1))) { 3334 Mask = Op.getOperand(1); 3335 Op = Op.getOperand(0); 3336 } else { 3337 return false; 3338 } 3339 } 3340 3341 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) { 3342 Shift = Op; 3343 return true; 3344 } 3345 3346 return false; 3347 } 3348 3349 // Return true if we can prove that, whenever Neg and Pos are both in the 3350 // range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos). This means that 3351 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits: 3352 // 3353 // (or (shift1 X, Neg), (shift2 X, Pos)) 3354 // 3355 // reduces to a rotate in direction shift2 by Pos and a rotate in direction 3356 // shift1 by Neg. The range [0, OpSize) means that we only need to consider 3357 // shift amounts with defined behavior. 3358 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) { 3359 // If OpSize is a power of 2 then: 3360 // 3361 // (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1) 3362 // (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize). 3363 // 3364 // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check 3365 // for the stronger condition: 3366 // 3367 // Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1) [A] 3368 // 3369 // for all Neg and Pos. Since Neg & (OpSize - 1) == Neg' & (OpSize - 1) 3370 // we can just replace Neg with Neg' for the rest of the function. 3371 // 3372 // In other cases we check for the even stronger condition: 3373 // 3374 // Neg == OpSize - Pos [B] 3375 // 3376 // for all Neg and Pos. Note that the (or ...) then invokes undefined 3377 // behavior if Pos == 0 (and consequently Neg == OpSize). 3378 // 3379 // We could actually use [A] whenever OpSize is a power of 2, but the 3380 // only extra cases that it would match are those uninteresting ones 3381 // where Neg and Pos are never in range at the same time. E.g. for 3382 // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos) 3383 // as well as (sub 32, Pos), but: 3384 // 3385 // (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos)) 3386 // 3387 // always invokes undefined behavior for 32-bit X. 3388 // 3389 // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise. 3390 unsigned LoBits = 0; 3391 if (Neg.getOpcode() == ISD::AND && 3392 isPowerOf2_64(OpSize) && 3393 Neg.getOperand(1).getOpcode() == ISD::Constant && 3394 cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) { 3395 Neg = Neg.getOperand(0); 3396 LoBits = Log2_64(OpSize); 3397 } 3398 3399 // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1. 3400 if (Neg.getOpcode() != ISD::SUB) 3401 return 0; 3402 ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0)); 3403 if (!NegC) 3404 return 0; 3405 SDValue NegOp1 = Neg.getOperand(1); 3406 3407 // The condition we need is now: 3408 // 3409 // (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask 3410 // 3411 // If NegOp1 == Pos then we need: 3412 // 3413 // OpSize & Mask == NegC & Mask 3414 // 3415 // (because "x & Mask" is a truncation and distributes through subtraction). 3416 APInt Width; 3417 if (Pos == NegOp1) 3418 Width = NegC->getAPIntValue(); 3419 // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC. 3420 // Then the condition we want to prove becomes: 3421 // 3422 // (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask 3423 // 3424 // which, again because "x & Mask" is a truncation, becomes: 3425 // 3426 // NegC & Mask == (OpSize - PosC) & Mask 3427 // OpSize & Mask == (NegC + PosC) & Mask 3428 else if (Pos.getOpcode() == ISD::ADD && 3429 Pos.getOperand(0) == NegOp1 && 3430 Pos.getOperand(1).getOpcode() == ISD::Constant) 3431 Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() + 3432 NegC->getAPIntValue()); 3433 else 3434 return false; 3435 3436 // Now we just need to check that OpSize & Mask == Width & Mask. 3437 if (LoBits) 3438 return Width.getLoBits(LoBits) == 0; 3439 return Width == OpSize; 3440 } 3441 3442 // A subroutine of MatchRotate used once we have found an OR of two opposite 3443 // shifts of Shifted. If Neg == <operand size> - Pos then the OR reduces 3444 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the 3445 // former being preferred if supported. InnerPos and InnerNeg are Pos and 3446 // Neg with outer conversions stripped away. 3447 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos, 3448 SDValue Neg, SDValue InnerPos, 3449 SDValue InnerNeg, unsigned PosOpcode, 3450 unsigned NegOpcode, SDLoc DL) { 3451 // fold (or (shl x, (*ext y)), 3452 // (srl x, (*ext (sub 32, y)))) -> 3453 // (rotl x, y) or (rotr x, (sub 32, y)) 3454 // 3455 // fold (or (shl x, (*ext (sub 32, y))), 3456 // (srl x, (*ext y))) -> 3457 // (rotr x, y) or (rotl x, (sub 32, y)) 3458 EVT VT = Shifted.getValueType(); 3459 if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) { 3460 bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT); 3461 return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted, 3462 HasPos ? Pos : Neg).getNode(); 3463 } 3464 3465 // fold (or (shl (*ext x), (*ext y)), 3466 // (srl (*ext x), (*ext (sub 32, y)))) -> 3467 // (*ext (rotl x, y)) or (*ext (rotr x, (sub 32, y))) 3468 // 3469 // fold (or (shl (*ext x), (*ext (sub 32, y))), 3470 // (srl (*ext x), (*ext y))) -> 3471 // (*ext (rotr x, y)) or (*ext (rotl x, (sub 32, y))) 3472 if (Shifted.getOpcode() == ISD::ZERO_EXTEND || 3473 Shifted.getOpcode() == ISD::ANY_EXTEND) { 3474 SDValue InnerShifted = Shifted.getOperand(0); 3475 EVT InnerVT = InnerShifted.getValueType(); 3476 bool HasPosInner = TLI.isOperationLegalOrCustom(PosOpcode, InnerVT); 3477 if (HasPosInner || TLI.isOperationLegalOrCustom(NegOpcode, InnerVT)) { 3478 if (matchRotateSub(InnerPos, InnerNeg, InnerVT.getSizeInBits())) { 3479 SDValue V = DAG.getNode(HasPosInner ? PosOpcode : NegOpcode, DL, 3480 InnerVT, InnerShifted, HasPosInner ? Pos : Neg); 3481 return DAG.getNode(Shifted.getOpcode(), DL, VT, V).getNode(); 3482 } 3483 } 3484 } 3485 3486 return 0; 3487 } 3488 3489 // MatchRotate - Handle an 'or' of two operands. If this is one of the many 3490 // idioms for rotate, and if the target supports rotation instructions, generate 3491 // a rot[lr]. 3492 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) { 3493 // Must be a legal type. Expanded 'n promoted things won't work with rotates. 3494 EVT VT = LHS.getValueType(); 3495 if (!TLI.isTypeLegal(VT)) return 0; 3496 3497 // The target must have at least one rotate flavor. 3498 bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT); 3499 bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT); 3500 if (!HasROTL && !HasROTR) return 0; 3501 3502 // Match "(X shl/srl V1) & V2" where V2 may not be present. 3503 SDValue LHSShift; // The shift. 3504 SDValue LHSMask; // AND value if any. 3505 if (!MatchRotateHalf(LHS, LHSShift, LHSMask)) 3506 return 0; // Not part of a rotate. 3507 3508 SDValue RHSShift; // The shift. 3509 SDValue RHSMask; // AND value if any. 3510 if (!MatchRotateHalf(RHS, RHSShift, RHSMask)) 3511 return 0; // Not part of a rotate. 3512 3513 if (LHSShift.getOperand(0) != RHSShift.getOperand(0)) 3514 return 0; // Not shifting the same value. 3515 3516 if (LHSShift.getOpcode() == RHSShift.getOpcode()) 3517 return 0; // Shifts must disagree. 3518 3519 // Canonicalize shl to left side in a shl/srl pair. 3520 if (RHSShift.getOpcode() == ISD::SHL) { 3521 std::swap(LHS, RHS); 3522 std::swap(LHSShift, RHSShift); 3523 std::swap(LHSMask , RHSMask ); 3524 } 3525 3526 unsigned OpSizeInBits = VT.getSizeInBits(); 3527 SDValue LHSShiftArg = LHSShift.getOperand(0); 3528 SDValue LHSShiftAmt = LHSShift.getOperand(1); 3529 SDValue RHSShiftArg = RHSShift.getOperand(0); 3530 SDValue RHSShiftAmt = RHSShift.getOperand(1); 3531 3532 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1) 3533 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2) 3534 if (LHSShiftAmt.getOpcode() == ISD::Constant && 3535 RHSShiftAmt.getOpcode() == ISD::Constant) { 3536 uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue(); 3537 uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue(); 3538 if ((LShVal + RShVal) != OpSizeInBits) 3539 return 0; 3540 3541 SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT, 3542 LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt); 3543 3544 // If there is an AND of either shifted operand, apply it to the result. 3545 if (LHSMask.getNode() || RHSMask.getNode()) { 3546 APInt Mask = APInt::getAllOnesValue(OpSizeInBits); 3547 3548 if (LHSMask.getNode()) { 3549 APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal); 3550 Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits; 3551 } 3552 if (RHSMask.getNode()) { 3553 APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal); 3554 Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits; 3555 } 3556 3557 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT)); 3558 } 3559 3560 return Rot.getNode(); 3561 } 3562 3563 // If there is a mask here, and we have a variable shift, we can't be sure 3564 // that we're masking out the right stuff. 3565 if (LHSMask.getNode() || RHSMask.getNode()) 3566 return 0; 3567 3568 // If the shift amount is sign/zext/any-extended just peel it off. 3569 SDValue LExtOp0 = LHSShiftAmt; 3570 SDValue RExtOp0 = RHSShiftAmt; 3571 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND || 3572 LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND || 3573 LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND || 3574 LHSShiftAmt.getOpcode() == ISD::TRUNCATE) && 3575 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND || 3576 RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND || 3577 RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND || 3578 RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) { 3579 LExtOp0 = LHSShiftAmt.getOperand(0); 3580 RExtOp0 = RHSShiftAmt.getOperand(0); 3581 } 3582 3583 SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt, 3584 LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL); 3585 if (TryL) 3586 return TryL; 3587 3588 SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt, 3589 RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL); 3590 if (TryR) 3591 return TryR; 3592 3593 return 0; 3594 } 3595 3596 SDValue DAGCombiner::visitXOR(SDNode *N) { 3597 SDValue N0 = N->getOperand(0); 3598 SDValue N1 = N->getOperand(1); 3599 SDValue LHS, RHS, CC; 3600 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 3601 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 3602 EVT VT = N0.getValueType(); 3603 3604 // fold vector ops 3605 if (VT.isVector()) { 3606 SDValue FoldedVOp = SimplifyVBinOp(N); 3607 if (FoldedVOp.getNode()) return FoldedVOp; 3608 3609 // fold (xor x, 0) -> x, vector edition 3610 if (ISD::isBuildVectorAllZeros(N0.getNode())) 3611 return N1; 3612 if (ISD::isBuildVectorAllZeros(N1.getNode())) 3613 return N0; 3614 } 3615 3616 // fold (xor undef, undef) -> 0. This is a common idiom (misuse). 3617 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF) 3618 return DAG.getConstant(0, VT); 3619 // fold (xor x, undef) -> undef 3620 if (N0.getOpcode() == ISD::UNDEF) 3621 return N0; 3622 if (N1.getOpcode() == ISD::UNDEF) 3623 return N1; 3624 // fold (xor c1, c2) -> c1^c2 3625 if (N0C && N1C) 3626 return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C); 3627 // canonicalize constant to RHS 3628 if (N0C && !N1C) 3629 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0); 3630 // fold (xor x, 0) -> x 3631 if (N1C && N1C->isNullValue()) 3632 return N0; 3633 // reassociate xor 3634 SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1); 3635 if (RXOR.getNode() != 0) 3636 return RXOR; 3637 3638 // fold !(x cc y) -> (x !cc y) 3639 if (N1C && N1C->getAPIntValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) { 3640 bool isInt = LHS.getValueType().isInteger(); 3641 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(), 3642 isInt); 3643 3644 if (!LegalOperations || 3645 TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) { 3646 switch (N0.getOpcode()) { 3647 default: 3648 llvm_unreachable("Unhandled SetCC Equivalent!"); 3649 case ISD::SETCC: 3650 return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC); 3651 case ISD::SELECT_CC: 3652 return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2), 3653 N0.getOperand(3), NotCC); 3654 } 3655 } 3656 } 3657 3658 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y))) 3659 if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND && 3660 N0.getNode()->hasOneUse() && 3661 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){ 3662 SDValue V = N0.getOperand(0); 3663 V = DAG.getNode(ISD::XOR, SDLoc(N0), V.getValueType(), V, 3664 DAG.getConstant(1, V.getValueType())); 3665 AddToWorkList(V.getNode()); 3666 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V); 3667 } 3668 3669 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc 3670 if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 && 3671 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) { 3672 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1); 3673 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) { 3674 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND; 3675 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS 3676 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS 3677 AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode()); 3678 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS); 3679 } 3680 } 3681 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants 3682 if (N1C && N1C->isAllOnesValue() && 3683 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) { 3684 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1); 3685 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) { 3686 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND; 3687 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS 3688 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS 3689 AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode()); 3690 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS); 3691 } 3692 } 3693 // fold (xor (and x, y), y) -> (and (not x), y) 3694 if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() && 3695 N0->getOperand(1) == N1) { 3696 SDValue X = N0->getOperand(0); 3697 SDValue NotX = DAG.getNOT(SDLoc(X), X, VT); 3698 AddToWorkList(NotX.getNode()); 3699 return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1); 3700 } 3701 // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2)) 3702 if (N1C && N0.getOpcode() == ISD::XOR) { 3703 ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0)); 3704 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 3705 if (N00C) 3706 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(1), 3707 DAG.getConstant(N1C->getAPIntValue() ^ 3708 N00C->getAPIntValue(), VT)); 3709 if (N01C) 3710 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(0), 3711 DAG.getConstant(N1C->getAPIntValue() ^ 3712 N01C->getAPIntValue(), VT)); 3713 } 3714 // fold (xor x, x) -> 0 3715 if (N0 == N1) 3716 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes); 3717 3718 // Simplify: xor (op x...), (op y...) -> (op (xor x, y)) 3719 if (N0.getOpcode() == N1.getOpcode()) { 3720 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N); 3721 if (Tmp.getNode()) return Tmp; 3722 } 3723 3724 // Simplify the expression using non-local knowledge. 3725 if (!VT.isVector() && 3726 SimplifyDemandedBits(SDValue(N, 0))) 3727 return SDValue(N, 0); 3728 3729 return SDValue(); 3730 } 3731 3732 /// visitShiftByConstant - Handle transforms common to the three shifts, when 3733 /// the shift amount is a constant. 3734 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, unsigned Amt) { 3735 assert(isa<ConstantSDNode>(N->getOperand(1)) && 3736 "Expected an ConstantSDNode operand."); 3737 // We can't and shouldn't fold opaque constants. 3738 if (cast<ConstantSDNode>(N->getOperand(1))->isOpaque()) 3739 return SDValue(); 3740 3741 SDNode *LHS = N->getOperand(0).getNode(); 3742 if (!LHS->hasOneUse()) return SDValue(); 3743 3744 // We want to pull some binops through shifts, so that we have (and (shift)) 3745 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of 3746 // thing happens with address calculations, so it's important to canonicalize 3747 // it. 3748 bool HighBitSet = false; // Can we transform this if the high bit is set? 3749 3750 switch (LHS->getOpcode()) { 3751 default: return SDValue(); 3752 case ISD::OR: 3753 case ISD::XOR: 3754 HighBitSet = false; // We can only transform sra if the high bit is clear. 3755 break; 3756 case ISD::AND: 3757 HighBitSet = true; // We can only transform sra if the high bit is set. 3758 break; 3759 case ISD::ADD: 3760 if (N->getOpcode() != ISD::SHL) 3761 return SDValue(); // only shl(add) not sr[al](add). 3762 HighBitSet = false; // We can only transform sra if the high bit is clear. 3763 break; 3764 } 3765 3766 // We require the RHS of the binop to be a constant and not opaque as well. 3767 ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1)); 3768 if (!BinOpCst || BinOpCst->isOpaque()) return SDValue(); 3769 3770 // FIXME: disable this unless the input to the binop is a shift by a constant. 3771 // If it is not a shift, it pessimizes some common cases like: 3772 // 3773 // void foo(int *X, int i) { X[i & 1235] = 1; } 3774 // int bar(int *X, int i) { return X[i & 255]; } 3775 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode(); 3776 if ((BinOpLHSVal->getOpcode() != ISD::SHL && 3777 BinOpLHSVal->getOpcode() != ISD::SRA && 3778 BinOpLHSVal->getOpcode() != ISD::SRL) || 3779 !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1))) 3780 return SDValue(); 3781 3782 EVT VT = N->getValueType(0); 3783 3784 // If this is a signed shift right, and the high bit is modified by the 3785 // logical operation, do not perform the transformation. The highBitSet 3786 // boolean indicates the value of the high bit of the constant which would 3787 // cause it to be modified for this operation. 3788 if (N->getOpcode() == ISD::SRA) { 3789 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative(); 3790 if (BinOpRHSSignSet != HighBitSet) 3791 return SDValue(); 3792 } 3793 3794 // Fold the constants, shifting the binop RHS by the shift amount. 3795 SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)), 3796 N->getValueType(0), 3797 LHS->getOperand(1), N->getOperand(1)); 3798 assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!"); 3799 3800 // Create the new shift. 3801 SDValue NewShift = DAG.getNode(N->getOpcode(), 3802 SDLoc(LHS->getOperand(0)), 3803 VT, LHS->getOperand(0), N->getOperand(1)); 3804 3805 // Create the new binop. 3806 return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS); 3807 } 3808 3809 SDValue DAGCombiner::visitSHL(SDNode *N) { 3810 SDValue N0 = N->getOperand(0); 3811 SDValue N1 = N->getOperand(1); 3812 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 3813 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 3814 EVT VT = N0.getValueType(); 3815 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits(); 3816 3817 // fold vector ops 3818 if (VT.isVector()) { 3819 SDValue FoldedVOp = SimplifyVBinOp(N); 3820 if (FoldedVOp.getNode()) return FoldedVOp; 3821 3822 BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1); 3823 // If setcc produces all-one true value then: 3824 // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV) 3825 if (N1CV && N1CV->isConstant() && 3826 TLI.getBooleanContents(true) == 3827 TargetLowering::ZeroOrNegativeOneBooleanContent && 3828 N0.getOpcode() == ISD::AND) { 3829 SDValue N00 = N0->getOperand(0); 3830 SDValue N01 = N0->getOperand(1); 3831 BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01); 3832 3833 if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC) { 3834 SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, VT, N01CV, N1CV); 3835 if (C.getNode()) 3836 return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C); 3837 } 3838 } 3839 } 3840 3841 // fold (shl c1, c2) -> c1<<c2 3842 if (N0C && N1C) 3843 return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C); 3844 // fold (shl 0, x) -> 0 3845 if (N0C && N0C->isNullValue()) 3846 return N0; 3847 // fold (shl x, c >= size(x)) -> undef 3848 if (N1C && N1C->getZExtValue() >= OpSizeInBits) 3849 return DAG.getUNDEF(VT); 3850 // fold (shl x, 0) -> x 3851 if (N1C && N1C->isNullValue()) 3852 return N0; 3853 // fold (shl undef, x) -> 0 3854 if (N0.getOpcode() == ISD::UNDEF) 3855 return DAG.getConstant(0, VT); 3856 // if (shl x, c) is known to be zero, return 0 3857 if (DAG.MaskedValueIsZero(SDValue(N, 0), 3858 APInt::getAllOnesValue(OpSizeInBits))) 3859 return DAG.getConstant(0, VT); 3860 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))). 3861 if (N1.getOpcode() == ISD::TRUNCATE && 3862 N1.getOperand(0).getOpcode() == ISD::AND && 3863 N1.hasOneUse() && N1.getOperand(0).hasOneUse()) { 3864 SDValue N101 = N1.getOperand(0).getOperand(1); 3865 if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) { 3866 EVT TruncVT = N1.getValueType(); 3867 SDValue N100 = N1.getOperand(0).getOperand(0); 3868 APInt TruncC = N101C->getAPIntValue(); 3869 TruncC = TruncC.trunc(TruncVT.getSizeInBits()); 3870 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, 3871 DAG.getNode(ISD::AND, SDLoc(N), TruncVT, 3872 DAG.getNode(ISD::TRUNCATE, 3873 SDLoc(N), 3874 TruncVT, N100), 3875 DAG.getConstant(TruncC, TruncVT))); 3876 } 3877 } 3878 3879 if (N1C && SimplifyDemandedBits(SDValue(N, 0))) 3880 return SDValue(N, 0); 3881 3882 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2)) 3883 if (N1C && N0.getOpcode() == ISD::SHL && 3884 N0.getOperand(1).getOpcode() == ISD::Constant) { 3885 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue(); 3886 uint64_t c2 = N1C->getZExtValue(); 3887 if (c1 + c2 >= OpSizeInBits) 3888 return DAG.getConstant(0, VT); 3889 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0), 3890 DAG.getConstant(c1 + c2, N1.getValueType())); 3891 } 3892 3893 // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2))) 3894 // For this to be valid, the second form must not preserve any of the bits 3895 // that are shifted out by the inner shift in the first form. This means 3896 // the outer shift size must be >= the number of bits added by the ext. 3897 // As a corollary, we don't care what kind of ext it is. 3898 if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND || 3899 N0.getOpcode() == ISD::ANY_EXTEND || 3900 N0.getOpcode() == ISD::SIGN_EXTEND) && 3901 N0.getOperand(0).getOpcode() == ISD::SHL && 3902 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) { 3903 uint64_t c1 = 3904 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue(); 3905 uint64_t c2 = N1C->getZExtValue(); 3906 EVT InnerShiftVT = N0.getOperand(0).getValueType(); 3907 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits(); 3908 if (c2 >= OpSizeInBits - InnerShiftSize) { 3909 if (c1 + c2 >= OpSizeInBits) 3910 return DAG.getConstant(0, VT); 3911 return DAG.getNode(ISD::SHL, SDLoc(N0), VT, 3912 DAG.getNode(N0.getOpcode(), SDLoc(N0), VT, 3913 N0.getOperand(0)->getOperand(0)), 3914 DAG.getConstant(c1 + c2, N1.getValueType())); 3915 } 3916 } 3917 3918 // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C)) 3919 // Only fold this if the inner zext has no other uses to avoid increasing 3920 // the total number of instructions. 3921 if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() && 3922 N0.getOperand(0).getOpcode() == ISD::SRL && 3923 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) { 3924 uint64_t c1 = 3925 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue(); 3926 if (c1 < VT.getSizeInBits()) { 3927 uint64_t c2 = N1C->getZExtValue(); 3928 if (c1 == c2) { 3929 SDValue NewOp0 = N0.getOperand(0); 3930 EVT CountVT = NewOp0.getOperand(1).getValueType(); 3931 SDValue NewSHL = DAG.getNode(ISD::SHL, SDLoc(N), NewOp0.getValueType(), 3932 NewOp0, DAG.getConstant(c2, CountVT)); 3933 AddToWorkList(NewSHL.getNode()); 3934 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL); 3935 } 3936 } 3937 } 3938 3939 // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or 3940 // (and (srl x, (sub c1, c2), MASK) 3941 // Only fold this if the inner shift has no other uses -- if it does, folding 3942 // this will increase the total number of instructions. 3943 if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse() && 3944 N0.getOperand(1).getOpcode() == ISD::Constant) { 3945 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue(); 3946 if (c1 < VT.getSizeInBits()) { 3947 uint64_t c2 = N1C->getZExtValue(); 3948 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(), 3949 VT.getSizeInBits() - c1); 3950 SDValue Shift; 3951 if (c2 > c1) { 3952 Mask = Mask.shl(c2-c1); 3953 Shift = DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0), 3954 DAG.getConstant(c2-c1, N1.getValueType())); 3955 } else { 3956 Mask = Mask.lshr(c1-c2); 3957 Shift = DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), 3958 DAG.getConstant(c1-c2, N1.getValueType())); 3959 } 3960 return DAG.getNode(ISD::AND, SDLoc(N0), VT, Shift, 3961 DAG.getConstant(Mask, VT)); 3962 } 3963 } 3964 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1)) 3965 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) { 3966 SDValue HiBitsMask = 3967 DAG.getConstant(APInt::getHighBitsSet(VT.getSizeInBits(), 3968 VT.getSizeInBits() - 3969 N1C->getZExtValue()), 3970 VT); 3971 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0), 3972 HiBitsMask); 3973 } 3974 3975 if (N1C) { 3976 SDValue NewSHL = visitShiftByConstant(N, N1C->getZExtValue()); 3977 if (NewSHL.getNode()) 3978 return NewSHL; 3979 } 3980 3981 return SDValue(); 3982 } 3983 3984 SDValue DAGCombiner::visitSRA(SDNode *N) { 3985 SDValue N0 = N->getOperand(0); 3986 SDValue N1 = N->getOperand(1); 3987 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 3988 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 3989 EVT VT = N0.getValueType(); 3990 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits(); 3991 3992 // fold vector ops 3993 if (VT.isVector()) { 3994 SDValue FoldedVOp = SimplifyVBinOp(N); 3995 if (FoldedVOp.getNode()) return FoldedVOp; 3996 } 3997 3998 // fold (sra c1, c2) -> (sra c1, c2) 3999 if (N0C && N1C) 4000 return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C); 4001 // fold (sra 0, x) -> 0 4002 if (N0C && N0C->isNullValue()) 4003 return N0; 4004 // fold (sra -1, x) -> -1 4005 if (N0C && N0C->isAllOnesValue()) 4006 return N0; 4007 // fold (sra x, (setge c, size(x))) -> undef 4008 if (N1C && N1C->getZExtValue() >= OpSizeInBits) 4009 return DAG.getUNDEF(VT); 4010 // fold (sra x, 0) -> x 4011 if (N1C && N1C->isNullValue()) 4012 return N0; 4013 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports 4014 // sext_inreg. 4015 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) { 4016 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue(); 4017 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits); 4018 if (VT.isVector()) 4019 ExtVT = EVT::getVectorVT(*DAG.getContext(), 4020 ExtVT, VT.getVectorNumElements()); 4021 if ((!LegalOperations || 4022 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT))) 4023 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, 4024 N0.getOperand(0), DAG.getValueType(ExtVT)); 4025 } 4026 4027 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2)) 4028 if (N1C && N0.getOpcode() == ISD::SRA) { 4029 if (ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 4030 unsigned Sum = N1C->getZExtValue() + C1->getZExtValue(); 4031 if (Sum >= OpSizeInBits) Sum = OpSizeInBits-1; 4032 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0.getOperand(0), 4033 DAG.getConstant(Sum, N1C->getValueType(0))); 4034 } 4035 } 4036 4037 // fold (sra (shl X, m), (sub result_size, n)) 4038 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for 4039 // result_size - n != m. 4040 // If truncate is free for the target sext(shl) is likely to result in better 4041 // code. 4042 if (N0.getOpcode() == ISD::SHL) { 4043 // Get the two constanst of the shifts, CN0 = m, CN = n. 4044 const ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 4045 if (N01C && N1C) { 4046 // Determine what the truncate's result bitsize and type would be. 4047 EVT TruncVT = 4048 EVT::getIntegerVT(*DAG.getContext(), 4049 OpSizeInBits - N1C->getZExtValue()); 4050 // Determine the residual right-shift amount. 4051 signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue(); 4052 4053 // If the shift is not a no-op (in which case this should be just a sign 4054 // extend already), the truncated to type is legal, sign_extend is legal 4055 // on that type, and the truncate to that type is both legal and free, 4056 // perform the transform. 4057 if ((ShiftAmt > 0) && 4058 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) && 4059 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) && 4060 TLI.isTruncateFree(VT, TruncVT)) { 4061 4062 SDValue Amt = DAG.getConstant(ShiftAmt, 4063 getShiftAmountTy(N0.getOperand(0).getValueType())); 4064 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), VT, 4065 N0.getOperand(0), Amt); 4066 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), TruncVT, 4067 Shift); 4068 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), 4069 N->getValueType(0), Trunc); 4070 } 4071 } 4072 } 4073 4074 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))). 4075 if (N1.getOpcode() == ISD::TRUNCATE && 4076 N1.getOperand(0).getOpcode() == ISD::AND && 4077 N1.hasOneUse() && N1.getOperand(0).hasOneUse()) { 4078 SDValue N101 = N1.getOperand(0).getOperand(1); 4079 if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) { 4080 EVT TruncVT = N1.getValueType(); 4081 SDValue N100 = N1.getOperand(0).getOperand(0); 4082 APInt TruncC = N101C->getAPIntValue(); 4083 TruncC = TruncC.trunc(TruncVT.getScalarType().getSizeInBits()); 4084 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, 4085 DAG.getNode(ISD::AND, SDLoc(N), 4086 TruncVT, 4087 DAG.getNode(ISD::TRUNCATE, 4088 SDLoc(N), 4089 TruncVT, N100), 4090 DAG.getConstant(TruncC, TruncVT))); 4091 } 4092 } 4093 4094 // fold (sra (trunc (sr x, c1)), c2) -> (trunc (sra x, c1+c2)) 4095 // if c1 is equal to the number of bits the trunc removes 4096 if (N0.getOpcode() == ISD::TRUNCATE && 4097 (N0.getOperand(0).getOpcode() == ISD::SRL || 4098 N0.getOperand(0).getOpcode() == ISD::SRA) && 4099 N0.getOperand(0).hasOneUse() && 4100 N0.getOperand(0).getOperand(1).hasOneUse() && 4101 N1C && isa<ConstantSDNode>(N0.getOperand(0).getOperand(1))) { 4102 EVT LargeVT = N0.getOperand(0).getValueType(); 4103 ConstantSDNode *LargeShiftAmt = 4104 cast<ConstantSDNode>(N0.getOperand(0).getOperand(1)); 4105 4106 if (LargeVT.getScalarType().getSizeInBits() - OpSizeInBits == 4107 LargeShiftAmt->getZExtValue()) { 4108 SDValue Amt = 4109 DAG.getConstant(LargeShiftAmt->getZExtValue() + N1C->getZExtValue(), 4110 getShiftAmountTy(N0.getOperand(0).getOperand(0).getValueType())); 4111 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), LargeVT, 4112 N0.getOperand(0).getOperand(0), Amt); 4113 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, SRA); 4114 } 4115 } 4116 4117 // Simplify, based on bits shifted out of the LHS. 4118 if (N1C && SimplifyDemandedBits(SDValue(N, 0))) 4119 return SDValue(N, 0); 4120 4121 4122 // If the sign bit is known to be zero, switch this to a SRL. 4123 if (DAG.SignBitIsZero(N0)) 4124 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1); 4125 4126 if (N1C) { 4127 SDValue NewSRA = visitShiftByConstant(N, N1C->getZExtValue()); 4128 if (NewSRA.getNode()) 4129 return NewSRA; 4130 } 4131 4132 return SDValue(); 4133 } 4134 4135 SDValue DAGCombiner::visitSRL(SDNode *N) { 4136 SDValue N0 = N->getOperand(0); 4137 SDValue N1 = N->getOperand(1); 4138 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 4139 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 4140 EVT VT = N0.getValueType(); 4141 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits(); 4142 4143 // fold vector ops 4144 if (VT.isVector()) { 4145 SDValue FoldedVOp = SimplifyVBinOp(N); 4146 if (FoldedVOp.getNode()) return FoldedVOp; 4147 } 4148 4149 // fold (srl c1, c2) -> c1 >>u c2 4150 if (N0C && N1C) 4151 return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C); 4152 // fold (srl 0, x) -> 0 4153 if (N0C && N0C->isNullValue()) 4154 return N0; 4155 // fold (srl x, c >= size(x)) -> undef 4156 if (N1C && N1C->getZExtValue() >= OpSizeInBits) 4157 return DAG.getUNDEF(VT); 4158 // fold (srl x, 0) -> x 4159 if (N1C && N1C->isNullValue()) 4160 return N0; 4161 // if (srl x, c) is known to be zero, return 0 4162 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0), 4163 APInt::getAllOnesValue(OpSizeInBits))) 4164 return DAG.getConstant(0, VT); 4165 4166 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2)) 4167 if (N1C && N0.getOpcode() == ISD::SRL && 4168 N0.getOperand(1).getOpcode() == ISD::Constant) { 4169 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue(); 4170 uint64_t c2 = N1C->getZExtValue(); 4171 if (c1 + c2 >= OpSizeInBits) 4172 return DAG.getConstant(0, VT); 4173 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), 4174 DAG.getConstant(c1 + c2, N1.getValueType())); 4175 } 4176 4177 // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2))) 4178 if (N1C && N0.getOpcode() == ISD::TRUNCATE && 4179 N0.getOperand(0).getOpcode() == ISD::SRL && 4180 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) { 4181 uint64_t c1 = 4182 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue(); 4183 uint64_t c2 = N1C->getZExtValue(); 4184 EVT InnerShiftVT = N0.getOperand(0).getValueType(); 4185 EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType(); 4186 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits(); 4187 // This is only valid if the OpSizeInBits + c1 = size of inner shift. 4188 if (c1 + OpSizeInBits == InnerShiftSize) { 4189 if (c1 + c2 >= InnerShiftSize) 4190 return DAG.getConstant(0, VT); 4191 return DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, 4192 DAG.getNode(ISD::SRL, SDLoc(N0), InnerShiftVT, 4193 N0.getOperand(0)->getOperand(0), 4194 DAG.getConstant(c1 + c2, ShiftCountVT))); 4195 } 4196 } 4197 4198 // fold (srl (shl x, c), c) -> (and x, cst2) 4199 if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1 && 4200 N0.getValueSizeInBits() <= 64) { 4201 uint64_t ShAmt = N1C->getZExtValue()+64-N0.getValueSizeInBits(); 4202 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0), 4203 DAG.getConstant(~0ULL >> ShAmt, VT)); 4204 } 4205 4206 // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask) 4207 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) { 4208 // Shifting in all undef bits? 4209 EVT SmallVT = N0.getOperand(0).getValueType(); 4210 if (N1C->getZExtValue() >= SmallVT.getSizeInBits()) 4211 return DAG.getUNDEF(VT); 4212 4213 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) { 4214 uint64_t ShiftAmt = N1C->getZExtValue(); 4215 SDValue SmallShift = DAG.getNode(ISD::SRL, SDLoc(N0), SmallVT, 4216 N0.getOperand(0), 4217 DAG.getConstant(ShiftAmt, getShiftAmountTy(SmallVT))); 4218 AddToWorkList(SmallShift.getNode()); 4219 APInt Mask = APInt::getAllOnesValue(VT.getSizeInBits()).lshr(ShiftAmt); 4220 return DAG.getNode(ISD::AND, SDLoc(N), VT, 4221 DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, SmallShift), 4222 DAG.getConstant(Mask, VT)); 4223 } 4224 } 4225 4226 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign 4227 // bit, which is unmodified by sra. 4228 if (N1C && N1C->getZExtValue() + 1 == VT.getSizeInBits()) { 4229 if (N0.getOpcode() == ISD::SRA) 4230 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1); 4231 } 4232 4233 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit). 4234 if (N1C && N0.getOpcode() == ISD::CTLZ && 4235 N1C->getAPIntValue() == Log2_32(VT.getSizeInBits())) { 4236 APInt KnownZero, KnownOne; 4237 DAG.ComputeMaskedBits(N0.getOperand(0), KnownZero, KnownOne); 4238 4239 // If any of the input bits are KnownOne, then the input couldn't be all 4240 // zeros, thus the result of the srl will always be zero. 4241 if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT); 4242 4243 // If all of the bits input the to ctlz node are known to be zero, then 4244 // the result of the ctlz is "32" and the result of the shift is one. 4245 APInt UnknownBits = ~KnownZero; 4246 if (UnknownBits == 0) return DAG.getConstant(1, VT); 4247 4248 // Otherwise, check to see if there is exactly one bit input to the ctlz. 4249 if ((UnknownBits & (UnknownBits - 1)) == 0) { 4250 // Okay, we know that only that the single bit specified by UnknownBits 4251 // could be set on input to the CTLZ node. If this bit is set, the SRL 4252 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair 4253 // to an SRL/XOR pair, which is likely to simplify more. 4254 unsigned ShAmt = UnknownBits.countTrailingZeros(); 4255 SDValue Op = N0.getOperand(0); 4256 4257 if (ShAmt) { 4258 Op = DAG.getNode(ISD::SRL, SDLoc(N0), VT, Op, 4259 DAG.getConstant(ShAmt, getShiftAmountTy(Op.getValueType()))); 4260 AddToWorkList(Op.getNode()); 4261 } 4262 4263 return DAG.getNode(ISD::XOR, SDLoc(N), VT, 4264 Op, DAG.getConstant(1, VT)); 4265 } 4266 } 4267 4268 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))). 4269 if (N1.getOpcode() == ISD::TRUNCATE && 4270 N1.getOperand(0).getOpcode() == ISD::AND && 4271 N1.hasOneUse() && N1.getOperand(0).hasOneUse()) { 4272 SDValue N101 = N1.getOperand(0).getOperand(1); 4273 if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) { 4274 EVT TruncVT = N1.getValueType(); 4275 SDValue N100 = N1.getOperand(0).getOperand(0); 4276 APInt TruncC = N101C->getAPIntValue(); 4277 TruncC = TruncC.trunc(TruncVT.getSizeInBits()); 4278 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, 4279 DAG.getNode(ISD::AND, SDLoc(N), 4280 TruncVT, 4281 DAG.getNode(ISD::TRUNCATE, 4282 SDLoc(N), 4283 TruncVT, N100), 4284 DAG.getConstant(TruncC, TruncVT))); 4285 } 4286 } 4287 4288 // fold operands of srl based on knowledge that the low bits are not 4289 // demanded. 4290 if (N1C && SimplifyDemandedBits(SDValue(N, 0))) 4291 return SDValue(N, 0); 4292 4293 if (N1C) { 4294 SDValue NewSRL = visitShiftByConstant(N, N1C->getZExtValue()); 4295 if (NewSRL.getNode()) 4296 return NewSRL; 4297 } 4298 4299 // Attempt to convert a srl of a load into a narrower zero-extending load. 4300 SDValue NarrowLoad = ReduceLoadWidth(N); 4301 if (NarrowLoad.getNode()) 4302 return NarrowLoad; 4303 4304 // Here is a common situation. We want to optimize: 4305 // 4306 // %a = ... 4307 // %b = and i32 %a, 2 4308 // %c = srl i32 %b, 1 4309 // brcond i32 %c ... 4310 // 4311 // into 4312 // 4313 // %a = ... 4314 // %b = and %a, 2 4315 // %c = setcc eq %b, 0 4316 // brcond %c ... 4317 // 4318 // However when after the source operand of SRL is optimized into AND, the SRL 4319 // itself may not be optimized further. Look for it and add the BRCOND into 4320 // the worklist. 4321 if (N->hasOneUse()) { 4322 SDNode *Use = *N->use_begin(); 4323 if (Use->getOpcode() == ISD::BRCOND) 4324 AddToWorkList(Use); 4325 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) { 4326 // Also look pass the truncate. 4327 Use = *Use->use_begin(); 4328 if (Use->getOpcode() == ISD::BRCOND) 4329 AddToWorkList(Use); 4330 } 4331 } 4332 4333 return SDValue(); 4334 } 4335 4336 SDValue DAGCombiner::visitCTLZ(SDNode *N) { 4337 SDValue N0 = N->getOperand(0); 4338 EVT VT = N->getValueType(0); 4339 4340 // fold (ctlz c1) -> c2 4341 if (isa<ConstantSDNode>(N0)) 4342 return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0); 4343 return SDValue(); 4344 } 4345 4346 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) { 4347 SDValue N0 = N->getOperand(0); 4348 EVT VT = N->getValueType(0); 4349 4350 // fold (ctlz_zero_undef c1) -> c2 4351 if (isa<ConstantSDNode>(N0)) 4352 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0); 4353 return SDValue(); 4354 } 4355 4356 SDValue DAGCombiner::visitCTTZ(SDNode *N) { 4357 SDValue N0 = N->getOperand(0); 4358 EVT VT = N->getValueType(0); 4359 4360 // fold (cttz c1) -> c2 4361 if (isa<ConstantSDNode>(N0)) 4362 return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0); 4363 return SDValue(); 4364 } 4365 4366 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) { 4367 SDValue N0 = N->getOperand(0); 4368 EVT VT = N->getValueType(0); 4369 4370 // fold (cttz_zero_undef c1) -> c2 4371 if (isa<ConstantSDNode>(N0)) 4372 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0); 4373 return SDValue(); 4374 } 4375 4376 SDValue DAGCombiner::visitCTPOP(SDNode *N) { 4377 SDValue N0 = N->getOperand(0); 4378 EVT VT = N->getValueType(0); 4379 4380 // fold (ctpop c1) -> c2 4381 if (isa<ConstantSDNode>(N0)) 4382 return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0); 4383 return SDValue(); 4384 } 4385 4386 SDValue DAGCombiner::visitSELECT(SDNode *N) { 4387 SDValue N0 = N->getOperand(0); 4388 SDValue N1 = N->getOperand(1); 4389 SDValue N2 = N->getOperand(2); 4390 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 4391 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 4392 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2); 4393 EVT VT = N->getValueType(0); 4394 EVT VT0 = N0.getValueType(); 4395 4396 // fold (select C, X, X) -> X 4397 if (N1 == N2) 4398 return N1; 4399 // fold (select true, X, Y) -> X 4400 if (N0C && !N0C->isNullValue()) 4401 return N1; 4402 // fold (select false, X, Y) -> Y 4403 if (N0C && N0C->isNullValue()) 4404 return N2; 4405 // fold (select C, 1, X) -> (or C, X) 4406 if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1) 4407 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2); 4408 // fold (select C, 0, 1) -> (xor C, 1) 4409 if (VT.isInteger() && 4410 (VT0 == MVT::i1 || 4411 (VT0.isInteger() && 4412 TLI.getBooleanContents(false) == 4413 TargetLowering::ZeroOrOneBooleanContent)) && 4414 N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) { 4415 SDValue XORNode; 4416 if (VT == VT0) 4417 return DAG.getNode(ISD::XOR, SDLoc(N), VT0, 4418 N0, DAG.getConstant(1, VT0)); 4419 XORNode = DAG.getNode(ISD::XOR, SDLoc(N0), VT0, 4420 N0, DAG.getConstant(1, VT0)); 4421 AddToWorkList(XORNode.getNode()); 4422 if (VT.bitsGT(VT0)) 4423 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode); 4424 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode); 4425 } 4426 // fold (select C, 0, X) -> (and (not C), X) 4427 if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) { 4428 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT); 4429 AddToWorkList(NOTNode.getNode()); 4430 return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2); 4431 } 4432 // fold (select C, X, 1) -> (or (not C), X) 4433 if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) { 4434 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT); 4435 AddToWorkList(NOTNode.getNode()); 4436 return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1); 4437 } 4438 // fold (select C, X, 0) -> (and C, X) 4439 if (VT == MVT::i1 && N2C && N2C->isNullValue()) 4440 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1); 4441 // fold (select X, X, Y) -> (or X, Y) 4442 // fold (select X, 1, Y) -> (or X, Y) 4443 if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1))) 4444 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2); 4445 // fold (select X, Y, X) -> (and X, Y) 4446 // fold (select X, Y, 0) -> (and X, Y) 4447 if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0))) 4448 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1); 4449 4450 // If we can fold this based on the true/false value, do so. 4451 if (SimplifySelectOps(N, N1, N2)) 4452 return SDValue(N, 0); // Don't revisit N. 4453 4454 // fold selects based on a setcc into other things, such as min/max/abs 4455 if (N0.getOpcode() == ISD::SETCC) { 4456 // FIXME: 4457 // Check against MVT::Other for SELECT_CC, which is a workaround for targets 4458 // having to say they don't support SELECT_CC on every type the DAG knows 4459 // about, since there is no way to mark an opcode illegal at all value types 4460 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other) && 4461 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) 4462 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, 4463 N0.getOperand(0), N0.getOperand(1), 4464 N1, N2, N0.getOperand(2)); 4465 return SimplifySelect(SDLoc(N), N0, N1, N2); 4466 } 4467 4468 return SDValue(); 4469 } 4470 4471 static 4472 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) { 4473 SDLoc DL(N); 4474 EVT LoVT, HiVT; 4475 llvm::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0)); 4476 4477 // Split the inputs. 4478 SDValue Lo, Hi, LL, LH, RL, RH; 4479 llvm::tie(LL, LH) = DAG.SplitVectorOperand(N, 0); 4480 llvm::tie(RL, RH) = DAG.SplitVectorOperand(N, 1); 4481 4482 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2)); 4483 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2)); 4484 4485 return std::make_pair(Lo, Hi); 4486 } 4487 4488 SDValue DAGCombiner::visitVSELECT(SDNode *N) { 4489 SDValue N0 = N->getOperand(0); 4490 SDValue N1 = N->getOperand(1); 4491 SDValue N2 = N->getOperand(2); 4492 SDLoc DL(N); 4493 4494 // Canonicalize integer abs. 4495 // vselect (setg[te] X, 0), X, -X -> 4496 // vselect (setgt X, -1), X, -X -> 4497 // vselect (setl[te] X, 0), -X, X -> 4498 // Y = sra (X, size(X)-1); xor (add (X, Y), Y) 4499 if (N0.getOpcode() == ISD::SETCC) { 4500 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1); 4501 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get(); 4502 bool isAbs = false; 4503 bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode()); 4504 4505 if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) || 4506 (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) && 4507 N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1)) 4508 isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode()); 4509 else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) && 4510 N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1)) 4511 isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode()); 4512 4513 if (isAbs) { 4514 EVT VT = LHS.getValueType(); 4515 SDValue Shift = DAG.getNode( 4516 ISD::SRA, DL, VT, LHS, 4517 DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, VT)); 4518 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift); 4519 AddToWorkList(Shift.getNode()); 4520 AddToWorkList(Add.getNode()); 4521 return DAG.getNode(ISD::XOR, DL, VT, Add, Shift); 4522 } 4523 } 4524 4525 // If the VSELECT result requires splitting and the mask is provided by a 4526 // SETCC, then split both nodes and its operands before legalization. This 4527 // prevents the type legalizer from unrolling SETCC into scalar comparisons 4528 // and enables future optimizations (e.g. min/max pattern matching on X86). 4529 if (N0.getOpcode() == ISD::SETCC) { 4530 EVT VT = N->getValueType(0); 4531 4532 // Check if any splitting is required. 4533 if (TLI.getTypeAction(*DAG.getContext(), VT) != 4534 TargetLowering::TypeSplitVector) 4535 return SDValue(); 4536 4537 SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH; 4538 llvm::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG); 4539 llvm::tie(LL, LH) = DAG.SplitVectorOperand(N, 1); 4540 llvm::tie(RL, RH) = DAG.SplitVectorOperand(N, 2); 4541 4542 Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL); 4543 Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH); 4544 4545 // Add the new VSELECT nodes to the work list in case they need to be split 4546 // again. 4547 AddToWorkList(Lo.getNode()); 4548 AddToWorkList(Hi.getNode()); 4549 4550 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi); 4551 } 4552 4553 // Fold (vselect (build_vector all_ones), N1, N2) -> N1 4554 if (ISD::isBuildVectorAllOnes(N0.getNode())) 4555 return N1; 4556 // Fold (vselect (build_vector all_zeros), N1, N2) -> N2 4557 if (ISD::isBuildVectorAllZeros(N0.getNode())) 4558 return N2; 4559 4560 return SDValue(); 4561 } 4562 4563 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) { 4564 SDValue N0 = N->getOperand(0); 4565 SDValue N1 = N->getOperand(1); 4566 SDValue N2 = N->getOperand(2); 4567 SDValue N3 = N->getOperand(3); 4568 SDValue N4 = N->getOperand(4); 4569 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get(); 4570 4571 // fold select_cc lhs, rhs, x, x, cc -> x 4572 if (N2 == N3) 4573 return N2; 4574 4575 // Determine if the condition we're dealing with is constant 4576 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()), 4577 N0, N1, CC, SDLoc(N), false); 4578 if (SCC.getNode()) { 4579 AddToWorkList(SCC.getNode()); 4580 4581 if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) { 4582 if (!SCCC->isNullValue()) 4583 return N2; // cond always true -> true val 4584 else 4585 return N3; // cond always false -> false val 4586 } 4587 4588 // Fold to a simpler select_cc 4589 if (SCC.getOpcode() == ISD::SETCC) 4590 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(), 4591 SCC.getOperand(0), SCC.getOperand(1), N2, N3, 4592 SCC.getOperand(2)); 4593 } 4594 4595 // If we can fold this based on the true/false value, do so. 4596 if (SimplifySelectOps(N, N2, N3)) 4597 return SDValue(N, 0); // Don't revisit N. 4598 4599 // fold select_cc into other things, such as min/max/abs 4600 return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC); 4601 } 4602 4603 SDValue DAGCombiner::visitSETCC(SDNode *N) { 4604 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1), 4605 cast<CondCodeSDNode>(N->getOperand(2))->get(), 4606 SDLoc(N)); 4607 } 4608 4609 // tryToFoldExtendOfConstant - Try to fold a sext/zext/aext 4610 // dag node into a ConstantSDNode or a build_vector of constants. 4611 // This function is called by the DAGCombiner when visiting sext/zext/aext 4612 // dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND). 4613 // Vector extends are not folded if operations are legal; this is to 4614 // avoid introducing illegal build_vector dag nodes. 4615 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI, 4616 SelectionDAG &DAG, bool LegalTypes, 4617 bool LegalOperations) { 4618 unsigned Opcode = N->getOpcode(); 4619 SDValue N0 = N->getOperand(0); 4620 EVT VT = N->getValueType(0); 4621 4622 assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND || 4623 Opcode == ISD::ANY_EXTEND) && "Expected EXTEND dag node in input!"); 4624 4625 // fold (sext c1) -> c1 4626 // fold (zext c1) -> c1 4627 // fold (aext c1) -> c1 4628 if (isa<ConstantSDNode>(N0)) 4629 return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode(); 4630 4631 // fold (sext (build_vector AllConstants) -> (build_vector AllConstants) 4632 // fold (zext (build_vector AllConstants) -> (build_vector AllConstants) 4633 // fold (aext (build_vector AllConstants) -> (build_vector AllConstants) 4634 EVT SVT = VT.getScalarType(); 4635 if (!(VT.isVector() && 4636 (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) && 4637 ISD::isBuildVectorOfConstantSDNodes(N0.getNode()))) 4638 return 0; 4639 4640 // We can fold this node into a build_vector. 4641 unsigned VTBits = SVT.getSizeInBits(); 4642 unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits(); 4643 unsigned ShAmt = VTBits - EVTBits; 4644 SmallVector<SDValue, 8> Elts; 4645 unsigned NumElts = N0->getNumOperands(); 4646 SDLoc DL(N); 4647 4648 for (unsigned i=0; i != NumElts; ++i) { 4649 SDValue Op = N0->getOperand(i); 4650 if (Op->getOpcode() == ISD::UNDEF) { 4651 Elts.push_back(DAG.getUNDEF(SVT)); 4652 continue; 4653 } 4654 4655 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op); 4656 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue()); 4657 if (Opcode == ISD::SIGN_EXTEND) 4658 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(), 4659 SVT)); 4660 else 4661 Elts.push_back(DAG.getConstant(C.shl(ShAmt).lshr(ShAmt).getZExtValue(), 4662 SVT)); 4663 } 4664 4665 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, &Elts[0], NumElts).getNode(); 4666 } 4667 4668 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this: 4669 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))" 4670 // transformation. Returns true if extension are possible and the above 4671 // mentioned transformation is profitable. 4672 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0, 4673 unsigned ExtOpc, 4674 SmallVectorImpl<SDNode *> &ExtendNodes, 4675 const TargetLowering &TLI) { 4676 bool HasCopyToRegUses = false; 4677 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType()); 4678 for (SDNode::use_iterator UI = N0.getNode()->use_begin(), 4679 UE = N0.getNode()->use_end(); 4680 UI != UE; ++UI) { 4681 SDNode *User = *UI; 4682 if (User == N) 4683 continue; 4684 if (UI.getUse().getResNo() != N0.getResNo()) 4685 continue; 4686 // FIXME: Only extend SETCC N, N and SETCC N, c for now. 4687 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) { 4688 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get(); 4689 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC)) 4690 // Sign bits will be lost after a zext. 4691 return false; 4692 bool Add = false; 4693 for (unsigned i = 0; i != 2; ++i) { 4694 SDValue UseOp = User->getOperand(i); 4695 if (UseOp == N0) 4696 continue; 4697 if (!isa<ConstantSDNode>(UseOp)) 4698 return false; 4699 Add = true; 4700 } 4701 if (Add) 4702 ExtendNodes.push_back(User); 4703 continue; 4704 } 4705 // If truncates aren't free and there are users we can't 4706 // extend, it isn't worthwhile. 4707 if (!isTruncFree) 4708 return false; 4709 // Remember if this value is live-out. 4710 if (User->getOpcode() == ISD::CopyToReg) 4711 HasCopyToRegUses = true; 4712 } 4713 4714 if (HasCopyToRegUses) { 4715 bool BothLiveOut = false; 4716 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end(); 4717 UI != UE; ++UI) { 4718 SDUse &Use = UI.getUse(); 4719 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) { 4720 BothLiveOut = true; 4721 break; 4722 } 4723 } 4724 if (BothLiveOut) 4725 // Both unextended and extended values are live out. There had better be 4726 // a good reason for the transformation. 4727 return ExtendNodes.size(); 4728 } 4729 return true; 4730 } 4731 4732 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs, 4733 SDValue Trunc, SDValue ExtLoad, SDLoc DL, 4734 ISD::NodeType ExtType) { 4735 // Extend SetCC uses if necessary. 4736 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) { 4737 SDNode *SetCC = SetCCs[i]; 4738 SmallVector<SDValue, 4> Ops; 4739 4740 for (unsigned j = 0; j != 2; ++j) { 4741 SDValue SOp = SetCC->getOperand(j); 4742 if (SOp == Trunc) 4743 Ops.push_back(ExtLoad); 4744 else 4745 Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp)); 4746 } 4747 4748 Ops.push_back(SetCC->getOperand(2)); 4749 CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), 4750 &Ops[0], Ops.size())); 4751 } 4752 } 4753 4754 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) { 4755 SDValue N0 = N->getOperand(0); 4756 EVT VT = N->getValueType(0); 4757 4758 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes, 4759 LegalOperations)) 4760 return SDValue(Res, 0); 4761 4762 // fold (sext (sext x)) -> (sext x) 4763 // fold (sext (aext x)) -> (sext x) 4764 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) 4765 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, 4766 N0.getOperand(0)); 4767 4768 if (N0.getOpcode() == ISD::TRUNCATE) { 4769 // fold (sext (truncate (load x))) -> (sext (smaller load x)) 4770 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n))) 4771 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode()); 4772 if (NarrowLoad.getNode()) { 4773 SDNode* oye = N0.getNode()->getOperand(0).getNode(); 4774 if (NarrowLoad.getNode() != N0.getNode()) { 4775 CombineTo(N0.getNode(), NarrowLoad); 4776 // CombineTo deleted the truncate, if needed, but not what's under it. 4777 AddToWorkList(oye); 4778 } 4779 return SDValue(N, 0); // Return N so it doesn't get rechecked! 4780 } 4781 4782 // See if the value being truncated is already sign extended. If so, just 4783 // eliminate the trunc/sext pair. 4784 SDValue Op = N0.getOperand(0); 4785 unsigned OpBits = Op.getValueType().getScalarType().getSizeInBits(); 4786 unsigned MidBits = N0.getValueType().getScalarType().getSizeInBits(); 4787 unsigned DestBits = VT.getScalarType().getSizeInBits(); 4788 unsigned NumSignBits = DAG.ComputeNumSignBits(Op); 4789 4790 if (OpBits == DestBits) { 4791 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign 4792 // bits, it is already ready. 4793 if (NumSignBits > DestBits-MidBits) 4794 return Op; 4795 } else if (OpBits < DestBits) { 4796 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign 4797 // bits, just sext from i32. 4798 if (NumSignBits > OpBits-MidBits) 4799 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op); 4800 } else { 4801 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign 4802 // bits, just truncate to i32. 4803 if (NumSignBits > OpBits-MidBits) 4804 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op); 4805 } 4806 4807 // fold (sext (truncate x)) -> (sextinreg x). 4808 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, 4809 N0.getValueType())) { 4810 if (OpBits < DestBits) 4811 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op); 4812 else if (OpBits > DestBits) 4813 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op); 4814 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op, 4815 DAG.getValueType(N0.getValueType())); 4816 } 4817 } 4818 4819 // fold (sext (load x)) -> (sext (truncate (sextload x))) 4820 // None of the supported targets knows how to perform load and sign extend 4821 // on vectors in one instruction. We only perform this transformation on 4822 // scalars. 4823 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() && 4824 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) || 4825 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()))) { 4826 bool DoXform = true; 4827 SmallVector<SDNode*, 4> SetCCs; 4828 if (!N0.hasOneUse()) 4829 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI); 4830 if (DoXform) { 4831 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 4832 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT, 4833 LN0->getChain(), 4834 LN0->getBasePtr(), N0.getValueType(), 4835 LN0->getMemOperand()); 4836 CombineTo(N, ExtLoad); 4837 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 4838 N0.getValueType(), ExtLoad); 4839 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1)); 4840 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N), 4841 ISD::SIGN_EXTEND); 4842 return SDValue(N, 0); // Return N so it doesn't get rechecked! 4843 } 4844 } 4845 4846 // fold (sext (sextload x)) -> (sext (truncate (sextload x))) 4847 // fold (sext ( extload x)) -> (sext (truncate (sextload x))) 4848 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) && 4849 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) { 4850 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 4851 EVT MemVT = LN0->getMemoryVT(); 4852 if ((!LegalOperations && !LN0->isVolatile()) || 4853 TLI.isLoadExtLegal(ISD::SEXTLOAD, MemVT)) { 4854 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT, 4855 LN0->getChain(), 4856 LN0->getBasePtr(), MemVT, 4857 LN0->getMemOperand()); 4858 CombineTo(N, ExtLoad); 4859 CombineTo(N0.getNode(), 4860 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 4861 N0.getValueType(), ExtLoad), 4862 ExtLoad.getValue(1)); 4863 return SDValue(N, 0); // Return N so it doesn't get rechecked! 4864 } 4865 } 4866 4867 // fold (sext (and/or/xor (load x), cst)) -> 4868 // (and/or/xor (sextload x), (sext cst)) 4869 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR || 4870 N0.getOpcode() == ISD::XOR) && 4871 isa<LoadSDNode>(N0.getOperand(0)) && 4872 N0.getOperand(1).getOpcode() == ISD::Constant && 4873 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()) && 4874 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) { 4875 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0)); 4876 if (LN0->getExtensionType() != ISD::ZEXTLOAD) { 4877 bool DoXform = true; 4878 SmallVector<SDNode*, 4> SetCCs; 4879 if (!N0.hasOneUse()) 4880 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND, 4881 SetCCs, TLI); 4882 if (DoXform) { 4883 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT, 4884 LN0->getChain(), LN0->getBasePtr(), 4885 LN0->getMemoryVT(), 4886 LN0->getMemOperand()); 4887 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 4888 Mask = Mask.sext(VT.getSizeInBits()); 4889 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT, 4890 ExtLoad, DAG.getConstant(Mask, VT)); 4891 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, 4892 SDLoc(N0.getOperand(0)), 4893 N0.getOperand(0).getValueType(), ExtLoad); 4894 CombineTo(N, And); 4895 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1)); 4896 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N), 4897 ISD::SIGN_EXTEND); 4898 return SDValue(N, 0); // Return N so it doesn't get rechecked! 4899 } 4900 } 4901 } 4902 4903 if (N0.getOpcode() == ISD::SETCC) { 4904 // sext(setcc) -> sext_in_reg(vsetcc) for vectors. 4905 // Only do this before legalize for now. 4906 if (VT.isVector() && !LegalOperations && 4907 TLI.getBooleanContents(true) == 4908 TargetLowering::ZeroOrNegativeOneBooleanContent) { 4909 EVT N0VT = N0.getOperand(0).getValueType(); 4910 // On some architectures (such as SSE/NEON/etc) the SETCC result type is 4911 // of the same size as the compared operands. Only optimize sext(setcc()) 4912 // if this is the case. 4913 EVT SVT = getSetCCResultType(N0VT); 4914 4915 // We know that the # elements of the results is the same as the 4916 // # elements of the compare (and the # elements of the compare result 4917 // for that matter). Check to see that they are the same size. If so, 4918 // we know that the element size of the sext'd result matches the 4919 // element size of the compare operands. 4920 if (VT.getSizeInBits() == SVT.getSizeInBits()) 4921 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0), 4922 N0.getOperand(1), 4923 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 4924 4925 // If the desired elements are smaller or larger than the source 4926 // elements we can use a matching integer vector type and then 4927 // truncate/sign extend 4928 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger(); 4929 if (SVT == MatchingVectorType) { 4930 SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType, 4931 N0.getOperand(0), N0.getOperand(1), 4932 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 4933 return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT); 4934 } 4935 } 4936 4937 // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0) 4938 unsigned ElementWidth = VT.getScalarType().getSizeInBits(); 4939 SDValue NegOne = 4940 DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT); 4941 SDValue SCC = 4942 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1), 4943 NegOne, DAG.getConstant(0, VT), 4944 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true); 4945 if (SCC.getNode()) return SCC; 4946 4947 if (!VT.isVector()) { 4948 EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType()); 4949 if (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, SetCCVT)) { 4950 SDLoc DL(N); 4951 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get(); 4952 SDValue SetCC = DAG.getSetCC(DL, 4953 SetCCVT, 4954 N0.getOperand(0), N0.getOperand(1), CC); 4955 EVT SelectVT = getSetCCResultType(VT); 4956 return DAG.getSelect(DL, VT, 4957 DAG.getSExtOrTrunc(SetCC, DL, SelectVT), 4958 NegOne, DAG.getConstant(0, VT)); 4959 4960 } 4961 } 4962 } 4963 4964 // fold (sext x) -> (zext x) if the sign bit is known zero. 4965 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) && 4966 DAG.SignBitIsZero(N0)) 4967 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0); 4968 4969 return SDValue(); 4970 } 4971 4972 // isTruncateOf - If N is a truncate of some other value, return true, record 4973 // the value being truncated in Op and which of Op's bits are zero in KnownZero. 4974 // This function computes KnownZero to avoid a duplicated call to 4975 // ComputeMaskedBits in the caller. 4976 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op, 4977 APInt &KnownZero) { 4978 APInt KnownOne; 4979 if (N->getOpcode() == ISD::TRUNCATE) { 4980 Op = N->getOperand(0); 4981 DAG.ComputeMaskedBits(Op, KnownZero, KnownOne); 4982 return true; 4983 } 4984 4985 if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 || 4986 cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE) 4987 return false; 4988 4989 SDValue Op0 = N->getOperand(0); 4990 SDValue Op1 = N->getOperand(1); 4991 assert(Op0.getValueType() == Op1.getValueType()); 4992 4993 ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0); 4994 ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1); 4995 if (COp0 && COp0->isNullValue()) 4996 Op = Op1; 4997 else if (COp1 && COp1->isNullValue()) 4998 Op = Op0; 4999 else 5000 return false; 5001 5002 DAG.ComputeMaskedBits(Op, KnownZero, KnownOne); 5003 5004 if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue()) 5005 return false; 5006 5007 return true; 5008 } 5009 5010 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) { 5011 SDValue N0 = N->getOperand(0); 5012 EVT VT = N->getValueType(0); 5013 5014 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes, 5015 LegalOperations)) 5016 return SDValue(Res, 0); 5017 5018 // fold (zext (zext x)) -> (zext x) 5019 // fold (zext (aext x)) -> (zext x) 5020 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) 5021 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, 5022 N0.getOperand(0)); 5023 5024 // fold (zext (truncate x)) -> (zext x) or 5025 // (zext (truncate x)) -> (truncate x) 5026 // This is valid when the truncated bits of x are already zero. 5027 // FIXME: We should extend this to work for vectors too. 5028 SDValue Op; 5029 APInt KnownZero; 5030 if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) { 5031 APInt TruncatedBits = 5032 (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ? 5033 APInt(Op.getValueSizeInBits(), 0) : 5034 APInt::getBitsSet(Op.getValueSizeInBits(), 5035 N0.getValueSizeInBits(), 5036 std::min(Op.getValueSizeInBits(), 5037 VT.getSizeInBits())); 5038 if (TruncatedBits == (KnownZero & TruncatedBits)) { 5039 if (VT.bitsGT(Op.getValueType())) 5040 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op); 5041 if (VT.bitsLT(Op.getValueType())) 5042 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op); 5043 5044 return Op; 5045 } 5046 } 5047 5048 // fold (zext (truncate (load x))) -> (zext (smaller load x)) 5049 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n))) 5050 if (N0.getOpcode() == ISD::TRUNCATE) { 5051 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode()); 5052 if (NarrowLoad.getNode()) { 5053 SDNode* oye = N0.getNode()->getOperand(0).getNode(); 5054 if (NarrowLoad.getNode() != N0.getNode()) { 5055 CombineTo(N0.getNode(), NarrowLoad); 5056 // CombineTo deleted the truncate, if needed, but not what's under it. 5057 AddToWorkList(oye); 5058 } 5059 return SDValue(N, 0); // Return N so it doesn't get rechecked! 5060 } 5061 } 5062 5063 // fold (zext (truncate x)) -> (and x, mask) 5064 if (N0.getOpcode() == ISD::TRUNCATE && 5065 (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) { 5066 5067 // fold (zext (truncate (load x))) -> (zext (smaller load x)) 5068 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n))) 5069 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode()); 5070 if (NarrowLoad.getNode()) { 5071 SDNode* oye = N0.getNode()->getOperand(0).getNode(); 5072 if (NarrowLoad.getNode() != N0.getNode()) { 5073 CombineTo(N0.getNode(), NarrowLoad); 5074 // CombineTo deleted the truncate, if needed, but not what's under it. 5075 AddToWorkList(oye); 5076 } 5077 return SDValue(N, 0); // Return N so it doesn't get rechecked! 5078 } 5079 5080 SDValue Op = N0.getOperand(0); 5081 if (Op.getValueType().bitsLT(VT)) { 5082 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op); 5083 AddToWorkList(Op.getNode()); 5084 } else if (Op.getValueType().bitsGT(VT)) { 5085 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op); 5086 AddToWorkList(Op.getNode()); 5087 } 5088 return DAG.getZeroExtendInReg(Op, SDLoc(N), 5089 N0.getValueType().getScalarType()); 5090 } 5091 5092 // Fold (zext (and (trunc x), cst)) -> (and x, cst), 5093 // if either of the casts is not free. 5094 if (N0.getOpcode() == ISD::AND && 5095 N0.getOperand(0).getOpcode() == ISD::TRUNCATE && 5096 N0.getOperand(1).getOpcode() == ISD::Constant && 5097 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(), 5098 N0.getValueType()) || 5099 !TLI.isZExtFree(N0.getValueType(), VT))) { 5100 SDValue X = N0.getOperand(0).getOperand(0); 5101 if (X.getValueType().bitsLT(VT)) { 5102 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X); 5103 } else if (X.getValueType().bitsGT(VT)) { 5104 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X); 5105 } 5106 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 5107 Mask = Mask.zext(VT.getSizeInBits()); 5108 return DAG.getNode(ISD::AND, SDLoc(N), VT, 5109 X, DAG.getConstant(Mask, VT)); 5110 } 5111 5112 // fold (zext (load x)) -> (zext (truncate (zextload x))) 5113 // None of the supported targets knows how to perform load and vector_zext 5114 // on vectors in one instruction. We only perform this transformation on 5115 // scalars. 5116 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() && 5117 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) || 5118 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()))) { 5119 bool DoXform = true; 5120 SmallVector<SDNode*, 4> SetCCs; 5121 if (!N0.hasOneUse()) 5122 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI); 5123 if (DoXform) { 5124 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 5125 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT, 5126 LN0->getChain(), 5127 LN0->getBasePtr(), N0.getValueType(), 5128 LN0->getMemOperand()); 5129 CombineTo(N, ExtLoad); 5130 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 5131 N0.getValueType(), ExtLoad); 5132 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1)); 5133 5134 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N), 5135 ISD::ZERO_EXTEND); 5136 return SDValue(N, 0); // Return N so it doesn't get rechecked! 5137 } 5138 } 5139 5140 // fold (zext (and/or/xor (load x), cst)) -> 5141 // (and/or/xor (zextload x), (zext cst)) 5142 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR || 5143 N0.getOpcode() == ISD::XOR) && 5144 isa<LoadSDNode>(N0.getOperand(0)) && 5145 N0.getOperand(1).getOpcode() == ISD::Constant && 5146 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()) && 5147 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) { 5148 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0)); 5149 if (LN0->getExtensionType() != ISD::SEXTLOAD) { 5150 bool DoXform = true; 5151 SmallVector<SDNode*, 4> SetCCs; 5152 if (!N0.hasOneUse()) 5153 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND, 5154 SetCCs, TLI); 5155 if (DoXform) { 5156 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT, 5157 LN0->getChain(), LN0->getBasePtr(), 5158 LN0->getMemoryVT(), 5159 LN0->getMemOperand()); 5160 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 5161 Mask = Mask.zext(VT.getSizeInBits()); 5162 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT, 5163 ExtLoad, DAG.getConstant(Mask, VT)); 5164 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, 5165 SDLoc(N0.getOperand(0)), 5166 N0.getOperand(0).getValueType(), ExtLoad); 5167 CombineTo(N, And); 5168 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1)); 5169 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N), 5170 ISD::ZERO_EXTEND); 5171 return SDValue(N, 0); // Return N so it doesn't get rechecked! 5172 } 5173 } 5174 } 5175 5176 // fold (zext (zextload x)) -> (zext (truncate (zextload x))) 5177 // fold (zext ( extload x)) -> (zext (truncate (zextload x))) 5178 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) && 5179 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) { 5180 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 5181 EVT MemVT = LN0->getMemoryVT(); 5182 if ((!LegalOperations && !LN0->isVolatile()) || 5183 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT)) { 5184 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT, 5185 LN0->getChain(), 5186 LN0->getBasePtr(), MemVT, 5187 LN0->getMemOperand()); 5188 CombineTo(N, ExtLoad); 5189 CombineTo(N0.getNode(), 5190 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), 5191 ExtLoad), 5192 ExtLoad.getValue(1)); 5193 return SDValue(N, 0); // Return N so it doesn't get rechecked! 5194 } 5195 } 5196 5197 if (N0.getOpcode() == ISD::SETCC) { 5198 if (!LegalOperations && VT.isVector() && 5199 N0.getValueType().getVectorElementType() == MVT::i1) { 5200 EVT N0VT = N0.getOperand(0).getValueType(); 5201 if (getSetCCResultType(N0VT) == N0.getValueType()) 5202 return SDValue(); 5203 5204 // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors. 5205 // Only do this before legalize for now. 5206 EVT EltVT = VT.getVectorElementType(); 5207 SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(), 5208 DAG.getConstant(1, EltVT)); 5209 if (VT.getSizeInBits() == N0VT.getSizeInBits()) 5210 // We know that the # elements of the results is the same as the 5211 // # elements of the compare (and the # elements of the compare result 5212 // for that matter). Check to see that they are the same size. If so, 5213 // we know that the element size of the sext'd result matches the 5214 // element size of the compare operands. 5215 return DAG.getNode(ISD::AND, SDLoc(N), VT, 5216 DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0), 5217 N0.getOperand(1), 5218 cast<CondCodeSDNode>(N0.getOperand(2))->get()), 5219 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, 5220 &OneOps[0], OneOps.size())); 5221 5222 // If the desired elements are smaller or larger than the source 5223 // elements we can use a matching integer vector type and then 5224 // truncate/sign extend 5225 EVT MatchingElementType = 5226 EVT::getIntegerVT(*DAG.getContext(), 5227 N0VT.getScalarType().getSizeInBits()); 5228 EVT MatchingVectorType = 5229 EVT::getVectorVT(*DAG.getContext(), MatchingElementType, 5230 N0VT.getVectorNumElements()); 5231 SDValue VsetCC = 5232 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0), 5233 N0.getOperand(1), 5234 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 5235 return DAG.getNode(ISD::AND, SDLoc(N), VT, 5236 DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT), 5237 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, 5238 &OneOps[0], OneOps.size())); 5239 } 5240 5241 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc 5242 SDValue SCC = 5243 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1), 5244 DAG.getConstant(1, VT), DAG.getConstant(0, VT), 5245 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true); 5246 if (SCC.getNode()) return SCC; 5247 } 5248 5249 // (zext (shl (zext x), cst)) -> (shl (zext x), cst) 5250 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) && 5251 isa<ConstantSDNode>(N0.getOperand(1)) && 5252 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND && 5253 N0.hasOneUse()) { 5254 SDValue ShAmt = N0.getOperand(1); 5255 unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue(); 5256 if (N0.getOpcode() == ISD::SHL) { 5257 SDValue InnerZExt = N0.getOperand(0); 5258 // If the original shl may be shifting out bits, do not perform this 5259 // transformation. 5260 unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() - 5261 InnerZExt.getOperand(0).getValueType().getSizeInBits(); 5262 if (ShAmtVal > KnownZeroBits) 5263 return SDValue(); 5264 } 5265 5266 SDLoc DL(N); 5267 5268 // Ensure that the shift amount is wide enough for the shifted value. 5269 if (VT.getSizeInBits() >= 256) 5270 ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt); 5271 5272 return DAG.getNode(N0.getOpcode(), DL, VT, 5273 DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)), 5274 ShAmt); 5275 } 5276 5277 return SDValue(); 5278 } 5279 5280 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) { 5281 SDValue N0 = N->getOperand(0); 5282 EVT VT = N->getValueType(0); 5283 5284 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes, 5285 LegalOperations)) 5286 return SDValue(Res, 0); 5287 5288 // fold (aext (aext x)) -> (aext x) 5289 // fold (aext (zext x)) -> (zext x) 5290 // fold (aext (sext x)) -> (sext x) 5291 if (N0.getOpcode() == ISD::ANY_EXTEND || 5292 N0.getOpcode() == ISD::ZERO_EXTEND || 5293 N0.getOpcode() == ISD::SIGN_EXTEND) 5294 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0)); 5295 5296 // fold (aext (truncate (load x))) -> (aext (smaller load x)) 5297 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n))) 5298 if (N0.getOpcode() == ISD::TRUNCATE) { 5299 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode()); 5300 if (NarrowLoad.getNode()) { 5301 SDNode* oye = N0.getNode()->getOperand(0).getNode(); 5302 if (NarrowLoad.getNode() != N0.getNode()) { 5303 CombineTo(N0.getNode(), NarrowLoad); 5304 // CombineTo deleted the truncate, if needed, but not what's under it. 5305 AddToWorkList(oye); 5306 } 5307 return SDValue(N, 0); // Return N so it doesn't get rechecked! 5308 } 5309 } 5310 5311 // fold (aext (truncate x)) 5312 if (N0.getOpcode() == ISD::TRUNCATE) { 5313 SDValue TruncOp = N0.getOperand(0); 5314 if (TruncOp.getValueType() == VT) 5315 return TruncOp; // x iff x size == zext size. 5316 if (TruncOp.getValueType().bitsGT(VT)) 5317 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp); 5318 return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp); 5319 } 5320 5321 // Fold (aext (and (trunc x), cst)) -> (and x, cst) 5322 // if the trunc is not free. 5323 if (N0.getOpcode() == ISD::AND && 5324 N0.getOperand(0).getOpcode() == ISD::TRUNCATE && 5325 N0.getOperand(1).getOpcode() == ISD::Constant && 5326 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(), 5327 N0.getValueType())) { 5328 SDValue X = N0.getOperand(0).getOperand(0); 5329 if (X.getValueType().bitsLT(VT)) { 5330 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X); 5331 } else if (X.getValueType().bitsGT(VT)) { 5332 X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X); 5333 } 5334 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 5335 Mask = Mask.zext(VT.getSizeInBits()); 5336 return DAG.getNode(ISD::AND, SDLoc(N), VT, 5337 X, DAG.getConstant(Mask, VT)); 5338 } 5339 5340 // fold (aext (load x)) -> (aext (truncate (extload x))) 5341 // None of the supported targets knows how to perform load and any_ext 5342 // on vectors in one instruction. We only perform this transformation on 5343 // scalars. 5344 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() && 5345 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) || 5346 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) { 5347 bool DoXform = true; 5348 SmallVector<SDNode*, 4> SetCCs; 5349 if (!N0.hasOneUse()) 5350 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI); 5351 if (DoXform) { 5352 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 5353 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT, 5354 LN0->getChain(), 5355 LN0->getBasePtr(), N0.getValueType(), 5356 LN0->getMemOperand()); 5357 CombineTo(N, ExtLoad); 5358 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 5359 N0.getValueType(), ExtLoad); 5360 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1)); 5361 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N), 5362 ISD::ANY_EXTEND); 5363 return SDValue(N, 0); // Return N so it doesn't get rechecked! 5364 } 5365 } 5366 5367 // fold (aext (zextload x)) -> (aext (truncate (zextload x))) 5368 // fold (aext (sextload x)) -> (aext (truncate (sextload x))) 5369 // fold (aext ( extload x)) -> (aext (truncate (extload x))) 5370 if (N0.getOpcode() == ISD::LOAD && 5371 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 5372 N0.hasOneUse()) { 5373 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 5374 EVT MemVT = LN0->getMemoryVT(); 5375 SDValue ExtLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(N), 5376 VT, LN0->getChain(), LN0->getBasePtr(), 5377 MemVT, LN0->getMemOperand()); 5378 CombineTo(N, ExtLoad); 5379 CombineTo(N0.getNode(), 5380 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 5381 N0.getValueType(), ExtLoad), 5382 ExtLoad.getValue(1)); 5383 return SDValue(N, 0); // Return N so it doesn't get rechecked! 5384 } 5385 5386 if (N0.getOpcode() == ISD::SETCC) { 5387 // aext(setcc) -> sext_in_reg(vsetcc) for vectors. 5388 // Only do this before legalize for now. 5389 if (VT.isVector() && !LegalOperations) { 5390 EVT N0VT = N0.getOperand(0).getValueType(); 5391 // We know that the # elements of the results is the same as the 5392 // # elements of the compare (and the # elements of the compare result 5393 // for that matter). Check to see that they are the same size. If so, 5394 // we know that the element size of the sext'd result matches the 5395 // element size of the compare operands. 5396 if (VT.getSizeInBits() == N0VT.getSizeInBits()) 5397 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0), 5398 N0.getOperand(1), 5399 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 5400 // If the desired elements are smaller or larger than the source 5401 // elements we can use a matching integer vector type and then 5402 // truncate/sign extend 5403 else { 5404 EVT MatchingElementType = 5405 EVT::getIntegerVT(*DAG.getContext(), 5406 N0VT.getScalarType().getSizeInBits()); 5407 EVT MatchingVectorType = 5408 EVT::getVectorVT(*DAG.getContext(), MatchingElementType, 5409 N0VT.getVectorNumElements()); 5410 SDValue VsetCC = 5411 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0), 5412 N0.getOperand(1), 5413 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 5414 return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT); 5415 } 5416 } 5417 5418 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc 5419 SDValue SCC = 5420 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1), 5421 DAG.getConstant(1, VT), DAG.getConstant(0, VT), 5422 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true); 5423 if (SCC.getNode()) 5424 return SCC; 5425 } 5426 5427 return SDValue(); 5428 } 5429 5430 /// GetDemandedBits - See if the specified operand can be simplified with the 5431 /// knowledge that only the bits specified by Mask are used. If so, return the 5432 /// simpler operand, otherwise return a null SDValue. 5433 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) { 5434 switch (V.getOpcode()) { 5435 default: break; 5436 case ISD::Constant: { 5437 const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode()); 5438 assert(CV != 0 && "Const value should be ConstSDNode."); 5439 const APInt &CVal = CV->getAPIntValue(); 5440 APInt NewVal = CVal & Mask; 5441 if (NewVal != CVal) 5442 return DAG.getConstant(NewVal, V.getValueType()); 5443 break; 5444 } 5445 case ISD::OR: 5446 case ISD::XOR: 5447 // If the LHS or RHS don't contribute bits to the or, drop them. 5448 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask)) 5449 return V.getOperand(1); 5450 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask)) 5451 return V.getOperand(0); 5452 break; 5453 case ISD::SRL: 5454 // Only look at single-use SRLs. 5455 if (!V.getNode()->hasOneUse()) 5456 break; 5457 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) { 5458 // See if we can recursively simplify the LHS. 5459 unsigned Amt = RHSC->getZExtValue(); 5460 5461 // Watch out for shift count overflow though. 5462 if (Amt >= Mask.getBitWidth()) break; 5463 APInt NewMask = Mask << Amt; 5464 SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask); 5465 if (SimplifyLHS.getNode()) 5466 return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(), 5467 SimplifyLHS, V.getOperand(1)); 5468 } 5469 } 5470 return SDValue(); 5471 } 5472 5473 /// ReduceLoadWidth - If the result of a wider load is shifted to right of N 5474 /// bits and then truncated to a narrower type and where N is a multiple 5475 /// of number of bits of the narrower type, transform it to a narrower load 5476 /// from address + N / num of bits of new type. If the result is to be 5477 /// extended, also fold the extension to form a extending load. 5478 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) { 5479 unsigned Opc = N->getOpcode(); 5480 5481 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD; 5482 SDValue N0 = N->getOperand(0); 5483 EVT VT = N->getValueType(0); 5484 EVT ExtVT = VT; 5485 5486 // This transformation isn't valid for vector loads. 5487 if (VT.isVector()) 5488 return SDValue(); 5489 5490 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then 5491 // extended to VT. 5492 if (Opc == ISD::SIGN_EXTEND_INREG) { 5493 ExtType = ISD::SEXTLOAD; 5494 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT(); 5495 } else if (Opc == ISD::SRL) { 5496 // Another special-case: SRL is basically zero-extending a narrower value. 5497 ExtType = ISD::ZEXTLOAD; 5498 N0 = SDValue(N, 0); 5499 ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 5500 if (!N01) return SDValue(); 5501 ExtVT = EVT::getIntegerVT(*DAG.getContext(), 5502 VT.getSizeInBits() - N01->getZExtValue()); 5503 } 5504 if (LegalOperations && !TLI.isLoadExtLegal(ExtType, ExtVT)) 5505 return SDValue(); 5506 5507 unsigned EVTBits = ExtVT.getSizeInBits(); 5508 5509 // Do not generate loads of non-round integer types since these can 5510 // be expensive (and would be wrong if the type is not byte sized). 5511 if (!ExtVT.isRound()) 5512 return SDValue(); 5513 5514 unsigned ShAmt = 0; 5515 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) { 5516 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 5517 ShAmt = N01->getZExtValue(); 5518 // Is the shift amount a multiple of size of VT? 5519 if ((ShAmt & (EVTBits-1)) == 0) { 5520 N0 = N0.getOperand(0); 5521 // Is the load width a multiple of size of VT? 5522 if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0) 5523 return SDValue(); 5524 } 5525 5526 // At this point, we must have a load or else we can't do the transform. 5527 if (!isa<LoadSDNode>(N0)) return SDValue(); 5528 5529 // Because a SRL must be assumed to *need* to zero-extend the high bits 5530 // (as opposed to anyext the high bits), we can't combine the zextload 5531 // lowering of SRL and an sextload. 5532 if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD) 5533 return SDValue(); 5534 5535 // If the shift amount is larger than the input type then we're not 5536 // accessing any of the loaded bytes. If the load was a zextload/extload 5537 // then the result of the shift+trunc is zero/undef (handled elsewhere). 5538 if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits()) 5539 return SDValue(); 5540 } 5541 } 5542 5543 // If the load is shifted left (and the result isn't shifted back right), 5544 // we can fold the truncate through the shift. 5545 unsigned ShLeftAmt = 0; 5546 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() && 5547 ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) { 5548 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 5549 ShLeftAmt = N01->getZExtValue(); 5550 N0 = N0.getOperand(0); 5551 } 5552 } 5553 5554 // If we haven't found a load, we can't narrow it. Don't transform one with 5555 // multiple uses, this would require adding a new load. 5556 if (!isa<LoadSDNode>(N0) || !N0.hasOneUse()) 5557 return SDValue(); 5558 5559 // Don't change the width of a volatile load. 5560 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 5561 if (LN0->isVolatile()) 5562 return SDValue(); 5563 5564 // Verify that we are actually reducing a load width here. 5565 if (LN0->getMemoryVT().getSizeInBits() < EVTBits) 5566 return SDValue(); 5567 5568 // For the transform to be legal, the load must produce only two values 5569 // (the value loaded and the chain). Don't transform a pre-increment 5570 // load, for example, which produces an extra value. Otherwise the 5571 // transformation is not equivalent, and the downstream logic to replace 5572 // uses gets things wrong. 5573 if (LN0->getNumValues() > 2) 5574 return SDValue(); 5575 5576 // If the load that we're shrinking is an extload and we're not just 5577 // discarding the extension we can't simply shrink the load. Bail. 5578 // TODO: It would be possible to merge the extensions in some cases. 5579 if (LN0->getExtensionType() != ISD::NON_EXTLOAD && 5580 LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt) 5581 return SDValue(); 5582 5583 EVT PtrType = N0.getOperand(1).getValueType(); 5584 5585 if (PtrType == MVT::Untyped || PtrType.isExtended()) 5586 // It's not possible to generate a constant of extended or untyped type. 5587 return SDValue(); 5588 5589 // For big endian targets, we need to adjust the offset to the pointer to 5590 // load the correct bytes. 5591 if (TLI.isBigEndian()) { 5592 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits(); 5593 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits(); 5594 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt; 5595 } 5596 5597 uint64_t PtrOff = ShAmt / 8; 5598 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff); 5599 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0), 5600 PtrType, LN0->getBasePtr(), 5601 DAG.getConstant(PtrOff, PtrType)); 5602 AddToWorkList(NewPtr.getNode()); 5603 5604 SDValue Load; 5605 if (ExtType == ISD::NON_EXTLOAD) 5606 Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr, 5607 LN0->getPointerInfo().getWithOffset(PtrOff), 5608 LN0->isVolatile(), LN0->isNonTemporal(), 5609 LN0->isInvariant(), NewAlign, LN0->getTBAAInfo()); 5610 else 5611 Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr, 5612 LN0->getPointerInfo().getWithOffset(PtrOff), 5613 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(), 5614 NewAlign, LN0->getTBAAInfo()); 5615 5616 // Replace the old load's chain with the new load's chain. 5617 WorkListRemover DeadNodes(*this); 5618 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1)); 5619 5620 // Shift the result left, if we've swallowed a left shift. 5621 SDValue Result = Load; 5622 if (ShLeftAmt != 0) { 5623 EVT ShImmTy = getShiftAmountTy(Result.getValueType()); 5624 if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt)) 5625 ShImmTy = VT; 5626 // If the shift amount is as large as the result size (but, presumably, 5627 // no larger than the source) then the useful bits of the result are 5628 // zero; we can't simply return the shortened shift, because the result 5629 // of that operation is undefined. 5630 if (ShLeftAmt >= VT.getSizeInBits()) 5631 Result = DAG.getConstant(0, VT); 5632 else 5633 Result = DAG.getNode(ISD::SHL, SDLoc(N0), VT, 5634 Result, DAG.getConstant(ShLeftAmt, ShImmTy)); 5635 } 5636 5637 // Return the new loaded value. 5638 return Result; 5639 } 5640 5641 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) { 5642 SDValue N0 = N->getOperand(0); 5643 SDValue N1 = N->getOperand(1); 5644 EVT VT = N->getValueType(0); 5645 EVT EVT = cast<VTSDNode>(N1)->getVT(); 5646 unsigned VTBits = VT.getScalarType().getSizeInBits(); 5647 unsigned EVTBits = EVT.getScalarType().getSizeInBits(); 5648 5649 // fold (sext_in_reg c1) -> c1 5650 if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF) 5651 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1); 5652 5653 // If the input is already sign extended, just drop the extension. 5654 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1) 5655 return N0; 5656 5657 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2 5658 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG && 5659 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT())) 5660 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, 5661 N0.getOperand(0), N1); 5662 5663 // fold (sext_in_reg (sext x)) -> (sext x) 5664 // fold (sext_in_reg (aext x)) -> (sext x) 5665 // if x is small enough. 5666 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) { 5667 SDValue N00 = N0.getOperand(0); 5668 if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits && 5669 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT))) 5670 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1); 5671 } 5672 5673 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero. 5674 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits))) 5675 return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT); 5676 5677 // fold operands of sext_in_reg based on knowledge that the top bits are not 5678 // demanded. 5679 if (SimplifyDemandedBits(SDValue(N, 0))) 5680 return SDValue(N, 0); 5681 5682 // fold (sext_in_reg (load x)) -> (smaller sextload x) 5683 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits)) 5684 SDValue NarrowLoad = ReduceLoadWidth(N); 5685 if (NarrowLoad.getNode()) 5686 return NarrowLoad; 5687 5688 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24) 5689 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible. 5690 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above. 5691 if (N0.getOpcode() == ISD::SRL) { 5692 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1))) 5693 if (ShAmt->getZExtValue()+EVTBits <= VTBits) { 5694 // We can turn this into an SRA iff the input to the SRL is already sign 5695 // extended enough. 5696 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0)); 5697 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits) 5698 return DAG.getNode(ISD::SRA, SDLoc(N), VT, 5699 N0.getOperand(0), N0.getOperand(1)); 5700 } 5701 } 5702 5703 // fold (sext_inreg (extload x)) -> (sextload x) 5704 if (ISD::isEXTLoad(N0.getNode()) && 5705 ISD::isUNINDEXEDLoad(N0.getNode()) && 5706 EVT == cast<LoadSDNode>(N0)->getMemoryVT() && 5707 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) || 5708 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) { 5709 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 5710 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT, 5711 LN0->getChain(), 5712 LN0->getBasePtr(), EVT, 5713 LN0->getMemOperand()); 5714 CombineTo(N, ExtLoad); 5715 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 5716 AddToWorkList(ExtLoad.getNode()); 5717 return SDValue(N, 0); // Return N so it doesn't get rechecked! 5718 } 5719 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use 5720 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 5721 N0.hasOneUse() && 5722 EVT == cast<LoadSDNode>(N0)->getMemoryVT() && 5723 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) || 5724 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) { 5725 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 5726 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT, 5727 LN0->getChain(), 5728 LN0->getBasePtr(), EVT, 5729 LN0->getMemOperand()); 5730 CombineTo(N, ExtLoad); 5731 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 5732 return SDValue(N, 0); // Return N so it doesn't get rechecked! 5733 } 5734 5735 // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16)) 5736 if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) { 5737 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0), 5738 N0.getOperand(1), false); 5739 if (BSwap.getNode() != 0) 5740 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, 5741 BSwap, N1); 5742 } 5743 5744 // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs 5745 // into a build_vector. 5746 if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) { 5747 SmallVector<SDValue, 8> Elts; 5748 unsigned NumElts = N0->getNumOperands(); 5749 unsigned ShAmt = VTBits - EVTBits; 5750 5751 for (unsigned i = 0; i != NumElts; ++i) { 5752 SDValue Op = N0->getOperand(i); 5753 if (Op->getOpcode() == ISD::UNDEF) { 5754 Elts.push_back(Op); 5755 continue; 5756 } 5757 5758 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op); 5759 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue()); 5760 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(), 5761 Op.getValueType())); 5762 } 5763 5764 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, &Elts[0], NumElts); 5765 } 5766 5767 return SDValue(); 5768 } 5769 5770 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) { 5771 SDValue N0 = N->getOperand(0); 5772 EVT VT = N->getValueType(0); 5773 bool isLE = TLI.isLittleEndian(); 5774 5775 // noop truncate 5776 if (N0.getValueType() == N->getValueType(0)) 5777 return N0; 5778 // fold (truncate c1) -> c1 5779 if (isa<ConstantSDNode>(N0)) 5780 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0); 5781 // fold (truncate (truncate x)) -> (truncate x) 5782 if (N0.getOpcode() == ISD::TRUNCATE) 5783 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0)); 5784 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x 5785 if (N0.getOpcode() == ISD::ZERO_EXTEND || 5786 N0.getOpcode() == ISD::SIGN_EXTEND || 5787 N0.getOpcode() == ISD::ANY_EXTEND) { 5788 if (N0.getOperand(0).getValueType().bitsLT(VT)) 5789 // if the source is smaller than the dest, we still need an extend 5790 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, 5791 N0.getOperand(0)); 5792 if (N0.getOperand(0).getValueType().bitsGT(VT)) 5793 // if the source is larger than the dest, than we just need the truncate 5794 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0)); 5795 // if the source and dest are the same type, we can drop both the extend 5796 // and the truncate. 5797 return N0.getOperand(0); 5798 } 5799 5800 // Fold extract-and-trunc into a narrow extract. For example: 5801 // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1) 5802 // i32 y = TRUNCATE(i64 x) 5803 // -- becomes -- 5804 // v16i8 b = BITCAST (v2i64 val) 5805 // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8) 5806 // 5807 // Note: We only run this optimization after type legalization (which often 5808 // creates this pattern) and before operation legalization after which 5809 // we need to be more careful about the vector instructions that we generate. 5810 if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT && 5811 LegalTypes && !LegalOperations && N0->hasOneUse()) { 5812 5813 EVT VecTy = N0.getOperand(0).getValueType(); 5814 EVT ExTy = N0.getValueType(); 5815 EVT TrTy = N->getValueType(0); 5816 5817 unsigned NumElem = VecTy.getVectorNumElements(); 5818 unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits(); 5819 5820 EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem); 5821 assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size"); 5822 5823 SDValue EltNo = N0->getOperand(1); 5824 if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) { 5825 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue(); 5826 EVT IndexTy = TLI.getVectorIdxTy(); 5827 int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1)); 5828 5829 SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N), 5830 NVT, N0.getOperand(0)); 5831 5832 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, 5833 SDLoc(N), TrTy, V, 5834 DAG.getConstant(Index, IndexTy)); 5835 } 5836 } 5837 5838 // Fold a series of buildvector, bitcast, and truncate if possible. 5839 // For example fold 5840 // (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to 5841 // (2xi32 (buildvector x, y)). 5842 if (Level == AfterLegalizeVectorOps && VT.isVector() && 5843 N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() && 5844 N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR && 5845 N0.getOperand(0).hasOneUse()) { 5846 5847 SDValue BuildVect = N0.getOperand(0); 5848 EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType(); 5849 EVT TruncVecEltTy = VT.getVectorElementType(); 5850 5851 // Check that the element types match. 5852 if (BuildVectEltTy == TruncVecEltTy) { 5853 // Now we only need to compute the offset of the truncated elements. 5854 unsigned BuildVecNumElts = BuildVect.getNumOperands(); 5855 unsigned TruncVecNumElts = VT.getVectorNumElements(); 5856 unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts; 5857 5858 assert((BuildVecNumElts % TruncVecNumElts) == 0 && 5859 "Invalid number of elements"); 5860 5861 SmallVector<SDValue, 8> Opnds; 5862 for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset) 5863 Opnds.push_back(BuildVect.getOperand(i)); 5864 5865 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, &Opnds[0], 5866 Opnds.size()); 5867 } 5868 } 5869 5870 // See if we can simplify the input to this truncate through knowledge that 5871 // only the low bits are being used. 5872 // For example "trunc (or (shl x, 8), y)" // -> trunc y 5873 // Currently we only perform this optimization on scalars because vectors 5874 // may have different active low bits. 5875 if (!VT.isVector()) { 5876 SDValue Shorter = 5877 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(), 5878 VT.getSizeInBits())); 5879 if (Shorter.getNode()) 5880 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter); 5881 } 5882 // fold (truncate (load x)) -> (smaller load x) 5883 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits)) 5884 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) { 5885 SDValue Reduced = ReduceLoadWidth(N); 5886 if (Reduced.getNode()) 5887 return Reduced; 5888 // Handle the case where the load remains an extending load even 5889 // after truncation. 5890 if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) { 5891 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 5892 if (!LN0->isVolatile() && 5893 LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) { 5894 SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0), 5895 VT, LN0->getChain(), LN0->getBasePtr(), 5896 LN0->getMemoryVT(), 5897 LN0->getMemOperand()); 5898 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1)); 5899 return NewLoad; 5900 } 5901 } 5902 } 5903 // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)), 5904 // where ... are all 'undef'. 5905 if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) { 5906 SmallVector<EVT, 8> VTs; 5907 SDValue V; 5908 unsigned Idx = 0; 5909 unsigned NumDefs = 0; 5910 5911 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) { 5912 SDValue X = N0.getOperand(i); 5913 if (X.getOpcode() != ISD::UNDEF) { 5914 V = X; 5915 Idx = i; 5916 NumDefs++; 5917 } 5918 // Stop if more than one members are non-undef. 5919 if (NumDefs > 1) 5920 break; 5921 VTs.push_back(EVT::getVectorVT(*DAG.getContext(), 5922 VT.getVectorElementType(), 5923 X.getValueType().getVectorNumElements())); 5924 } 5925 5926 if (NumDefs == 0) 5927 return DAG.getUNDEF(VT); 5928 5929 if (NumDefs == 1) { 5930 assert(V.getNode() && "The single defined operand is empty!"); 5931 SmallVector<SDValue, 8> Opnds; 5932 for (unsigned i = 0, e = VTs.size(); i != e; ++i) { 5933 if (i != Idx) { 5934 Opnds.push_back(DAG.getUNDEF(VTs[i])); 5935 continue; 5936 } 5937 SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V); 5938 AddToWorkList(NV.getNode()); 5939 Opnds.push_back(NV); 5940 } 5941 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, 5942 &Opnds[0], Opnds.size()); 5943 } 5944 } 5945 5946 // Simplify the operands using demanded-bits information. 5947 if (!VT.isVector() && 5948 SimplifyDemandedBits(SDValue(N, 0))) 5949 return SDValue(N, 0); 5950 5951 return SDValue(); 5952 } 5953 5954 static SDNode *getBuildPairElt(SDNode *N, unsigned i) { 5955 SDValue Elt = N->getOperand(i); 5956 if (Elt.getOpcode() != ISD::MERGE_VALUES) 5957 return Elt.getNode(); 5958 return Elt.getOperand(Elt.getResNo()).getNode(); 5959 } 5960 5961 /// CombineConsecutiveLoads - build_pair (load, load) -> load 5962 /// if load locations are consecutive. 5963 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) { 5964 assert(N->getOpcode() == ISD::BUILD_PAIR); 5965 5966 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0)); 5967 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1)); 5968 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() || 5969 LD1->getAddressSpace() != LD2->getAddressSpace()) 5970 return SDValue(); 5971 EVT LD1VT = LD1->getValueType(0); 5972 5973 if (ISD::isNON_EXTLoad(LD2) && 5974 LD2->hasOneUse() && 5975 // If both are volatile this would reduce the number of volatile loads. 5976 // If one is volatile it might be ok, but play conservative and bail out. 5977 !LD1->isVolatile() && 5978 !LD2->isVolatile() && 5979 DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) { 5980 unsigned Align = LD1->getAlignment(); 5981 unsigned NewAlign = TLI.getDataLayout()-> 5982 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext())); 5983 5984 if (NewAlign <= Align && 5985 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT))) 5986 return DAG.getLoad(VT, SDLoc(N), LD1->getChain(), 5987 LD1->getBasePtr(), LD1->getPointerInfo(), 5988 false, false, false, Align); 5989 } 5990 5991 return SDValue(); 5992 } 5993 5994 SDValue DAGCombiner::visitBITCAST(SDNode *N) { 5995 SDValue N0 = N->getOperand(0); 5996 EVT VT = N->getValueType(0); 5997 5998 // If the input is a BUILD_VECTOR with all constant elements, fold this now. 5999 // Only do this before legalize, since afterward the target may be depending 6000 // on the bitconvert. 6001 // First check to see if this is all constant. 6002 if (!LegalTypes && 6003 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() && 6004 VT.isVector()) { 6005 bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant(); 6006 6007 EVT DestEltVT = N->getValueType(0).getVectorElementType(); 6008 assert(!DestEltVT.isVector() && 6009 "Element type of vector ValueType must not be vector!"); 6010 if (isSimple) 6011 return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT); 6012 } 6013 6014 // If the input is a constant, let getNode fold it. 6015 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) { 6016 SDValue Res = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0); 6017 if (Res.getNode() != N) { 6018 if (!LegalOperations || 6019 TLI.isOperationLegal(Res.getNode()->getOpcode(), VT)) 6020 return Res; 6021 6022 // Folding it resulted in an illegal node, and it's too late to 6023 // do that. Clean up the old node and forego the transformation. 6024 // Ideally this won't happen very often, because instcombine 6025 // and the earlier dagcombine runs (where illegal nodes are 6026 // permitted) should have folded most of them already. 6027 DAG.DeleteNode(Res.getNode()); 6028 } 6029 } 6030 6031 // (conv (conv x, t1), t2) -> (conv x, t2) 6032 if (N0.getOpcode() == ISD::BITCAST) 6033 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, 6034 N0.getOperand(0)); 6035 6036 // fold (conv (load x)) -> (load (conv*)x) 6037 // If the resultant load doesn't need a higher alignment than the original! 6038 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() && 6039 // Do not change the width of a volatile load. 6040 !cast<LoadSDNode>(N0)->isVolatile() && 6041 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) && 6042 TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) { 6043 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6044 unsigned Align = TLI.getDataLayout()-> 6045 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext())); 6046 unsigned OrigAlign = LN0->getAlignment(); 6047 6048 if (Align <= OrigAlign) { 6049 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(), 6050 LN0->getBasePtr(), LN0->getPointerInfo(), 6051 LN0->isVolatile(), LN0->isNonTemporal(), 6052 LN0->isInvariant(), OrigAlign, 6053 LN0->getTBAAInfo()); 6054 AddToWorkList(N); 6055 CombineTo(N0.getNode(), 6056 DAG.getNode(ISD::BITCAST, SDLoc(N0), 6057 N0.getValueType(), Load), 6058 Load.getValue(1)); 6059 return Load; 6060 } 6061 } 6062 6063 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit) 6064 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit)) 6065 // This often reduces constant pool loads. 6066 if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) || 6067 (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) && 6068 N0.getNode()->hasOneUse() && VT.isInteger() && 6069 !VT.isVector() && !N0.getValueType().isVector()) { 6070 SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT, 6071 N0.getOperand(0)); 6072 AddToWorkList(NewConv.getNode()); 6073 6074 APInt SignBit = APInt::getSignBit(VT.getSizeInBits()); 6075 if (N0.getOpcode() == ISD::FNEG) 6076 return DAG.getNode(ISD::XOR, SDLoc(N), VT, 6077 NewConv, DAG.getConstant(SignBit, VT)); 6078 assert(N0.getOpcode() == ISD::FABS); 6079 return DAG.getNode(ISD::AND, SDLoc(N), VT, 6080 NewConv, DAG.getConstant(~SignBit, VT)); 6081 } 6082 6083 // fold (bitconvert (fcopysign cst, x)) -> 6084 // (or (and (bitconvert x), sign), (and cst, (not sign))) 6085 // Note that we don't handle (copysign x, cst) because this can always be 6086 // folded to an fneg or fabs. 6087 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() && 6088 isa<ConstantFPSDNode>(N0.getOperand(0)) && 6089 VT.isInteger() && !VT.isVector()) { 6090 unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits(); 6091 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth); 6092 if (isTypeLegal(IntXVT)) { 6093 SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0), 6094 IntXVT, N0.getOperand(1)); 6095 AddToWorkList(X.getNode()); 6096 6097 // If X has a different width than the result/lhs, sext it or truncate it. 6098 unsigned VTWidth = VT.getSizeInBits(); 6099 if (OrigXWidth < VTWidth) { 6100 X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X); 6101 AddToWorkList(X.getNode()); 6102 } else if (OrigXWidth > VTWidth) { 6103 // To get the sign bit in the right place, we have to shift it right 6104 // before truncating. 6105 X = DAG.getNode(ISD::SRL, SDLoc(X), 6106 X.getValueType(), X, 6107 DAG.getConstant(OrigXWidth-VTWidth, X.getValueType())); 6108 AddToWorkList(X.getNode()); 6109 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X); 6110 AddToWorkList(X.getNode()); 6111 } 6112 6113 APInt SignBit = APInt::getSignBit(VT.getSizeInBits()); 6114 X = DAG.getNode(ISD::AND, SDLoc(X), VT, 6115 X, DAG.getConstant(SignBit, VT)); 6116 AddToWorkList(X.getNode()); 6117 6118 SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0), 6119 VT, N0.getOperand(0)); 6120 Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT, 6121 Cst, DAG.getConstant(~SignBit, VT)); 6122 AddToWorkList(Cst.getNode()); 6123 6124 return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst); 6125 } 6126 } 6127 6128 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive. 6129 if (N0.getOpcode() == ISD::BUILD_PAIR) { 6130 SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT); 6131 if (CombineLD.getNode()) 6132 return CombineLD; 6133 } 6134 6135 return SDValue(); 6136 } 6137 6138 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) { 6139 EVT VT = N->getValueType(0); 6140 return CombineConsecutiveLoads(N, VT); 6141 } 6142 6143 /// ConstantFoldBITCASTofBUILD_VECTOR - We know that BV is a build_vector 6144 /// node with Constant, ConstantFP or Undef operands. DstEltVT indicates the 6145 /// destination element value type. 6146 SDValue DAGCombiner:: 6147 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) { 6148 EVT SrcEltVT = BV->getValueType(0).getVectorElementType(); 6149 6150 // If this is already the right type, we're done. 6151 if (SrcEltVT == DstEltVT) return SDValue(BV, 0); 6152 6153 unsigned SrcBitSize = SrcEltVT.getSizeInBits(); 6154 unsigned DstBitSize = DstEltVT.getSizeInBits(); 6155 6156 // If this is a conversion of N elements of one type to N elements of another 6157 // type, convert each element. This handles FP<->INT cases. 6158 if (SrcBitSize == DstBitSize) { 6159 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, 6160 BV->getValueType(0).getVectorNumElements()); 6161 6162 // Due to the FP element handling below calling this routine recursively, 6163 // we can end up with a scalar-to-vector node here. 6164 if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR) 6165 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT, 6166 DAG.getNode(ISD::BITCAST, SDLoc(BV), 6167 DstEltVT, BV->getOperand(0))); 6168 6169 SmallVector<SDValue, 8> Ops; 6170 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) { 6171 SDValue Op = BV->getOperand(i); 6172 // If the vector element type is not legal, the BUILD_VECTOR operands 6173 // are promoted and implicitly truncated. Make that explicit here. 6174 if (Op.getValueType() != SrcEltVT) 6175 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op); 6176 Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV), 6177 DstEltVT, Op)); 6178 AddToWorkList(Ops.back().getNode()); 6179 } 6180 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, 6181 &Ops[0], Ops.size()); 6182 } 6183 6184 // Otherwise, we're growing or shrinking the elements. To avoid having to 6185 // handle annoying details of growing/shrinking FP values, we convert them to 6186 // int first. 6187 if (SrcEltVT.isFloatingPoint()) { 6188 // Convert the input float vector to a int vector where the elements are the 6189 // same sizes. 6190 assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!"); 6191 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits()); 6192 BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode(); 6193 SrcEltVT = IntVT; 6194 } 6195 6196 // Now we know the input is an integer vector. If the output is a FP type, 6197 // convert to integer first, then to FP of the right size. 6198 if (DstEltVT.isFloatingPoint()) { 6199 assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!"); 6200 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits()); 6201 SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode(); 6202 6203 // Next, convert to FP elements of the same size. 6204 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT); 6205 } 6206 6207 // Okay, we know the src/dst types are both integers of differing types. 6208 // Handling growing first. 6209 assert(SrcEltVT.isInteger() && DstEltVT.isInteger()); 6210 if (SrcBitSize < DstBitSize) { 6211 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize; 6212 6213 SmallVector<SDValue, 8> Ops; 6214 for (unsigned i = 0, e = BV->getNumOperands(); i != e; 6215 i += NumInputsPerOutput) { 6216 bool isLE = TLI.isLittleEndian(); 6217 APInt NewBits = APInt(DstBitSize, 0); 6218 bool EltIsUndef = true; 6219 for (unsigned j = 0; j != NumInputsPerOutput; ++j) { 6220 // Shift the previously computed bits over. 6221 NewBits <<= SrcBitSize; 6222 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j)); 6223 if (Op.getOpcode() == ISD::UNDEF) continue; 6224 EltIsUndef = false; 6225 6226 NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue(). 6227 zextOrTrunc(SrcBitSize).zext(DstBitSize); 6228 } 6229 6230 if (EltIsUndef) 6231 Ops.push_back(DAG.getUNDEF(DstEltVT)); 6232 else 6233 Ops.push_back(DAG.getConstant(NewBits, DstEltVT)); 6234 } 6235 6236 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size()); 6237 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, 6238 &Ops[0], Ops.size()); 6239 } 6240 6241 // Finally, this must be the case where we are shrinking elements: each input 6242 // turns into multiple outputs. 6243 bool isS2V = ISD::isScalarToVector(BV); 6244 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize; 6245 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, 6246 NumOutputsPerInput*BV->getNumOperands()); 6247 SmallVector<SDValue, 8> Ops; 6248 6249 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) { 6250 if (BV->getOperand(i).getOpcode() == ISD::UNDEF) { 6251 for (unsigned j = 0; j != NumOutputsPerInput; ++j) 6252 Ops.push_back(DAG.getUNDEF(DstEltVT)); 6253 continue; 6254 } 6255 6256 APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))-> 6257 getAPIntValue().zextOrTrunc(SrcBitSize); 6258 6259 for (unsigned j = 0; j != NumOutputsPerInput; ++j) { 6260 APInt ThisVal = OpVal.trunc(DstBitSize); 6261 Ops.push_back(DAG.getConstant(ThisVal, DstEltVT)); 6262 if (isS2V && i == 0 && j == 0 && ThisVal.zext(SrcBitSize) == OpVal) 6263 // Simply turn this into a SCALAR_TO_VECTOR of the new type. 6264 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT, 6265 Ops[0]); 6266 OpVal = OpVal.lshr(DstBitSize); 6267 } 6268 6269 // For big endian targets, swap the order of the pieces of each element. 6270 if (TLI.isBigEndian()) 6271 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end()); 6272 } 6273 6274 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, 6275 &Ops[0], Ops.size()); 6276 } 6277 6278 SDValue DAGCombiner::visitFADD(SDNode *N) { 6279 SDValue N0 = N->getOperand(0); 6280 SDValue N1 = N->getOperand(1); 6281 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 6282 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 6283 EVT VT = N->getValueType(0); 6284 6285 // fold vector ops 6286 if (VT.isVector()) { 6287 SDValue FoldedVOp = SimplifyVBinOp(N); 6288 if (FoldedVOp.getNode()) return FoldedVOp; 6289 } 6290 6291 // fold (fadd c1, c2) -> c1 + c2 6292 if (N0CFP && N1CFP) 6293 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N1); 6294 // canonicalize constant to RHS 6295 if (N0CFP && !N1CFP) 6296 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N0); 6297 // fold (fadd A, 0) -> A 6298 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP && 6299 N1CFP->getValueAPF().isZero()) 6300 return N0; 6301 // fold (fadd A, (fneg B)) -> (fsub A, B) 6302 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) && 6303 isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options) == 2) 6304 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0, 6305 GetNegatedExpression(N1, DAG, LegalOperations)); 6306 // fold (fadd (fneg A), B) -> (fsub B, A) 6307 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) && 6308 isNegatibleForFree(N0, LegalOperations, TLI, &DAG.getTarget().Options) == 2) 6309 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N1, 6310 GetNegatedExpression(N0, DAG, LegalOperations)); 6311 6312 // If allowed, fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2)) 6313 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP && 6314 N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() && 6315 isa<ConstantFPSDNode>(N0.getOperand(1))) 6316 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0.getOperand(0), 6317 DAG.getNode(ISD::FADD, SDLoc(N), VT, 6318 N0.getOperand(1), N1)); 6319 6320 // No FP constant should be created after legalization as Instruction 6321 // Selection pass has hard time in dealing with FP constant. 6322 // 6323 // We don't need test this condition for transformation like following, as 6324 // the DAG being transformed implies it is legal to take FP constant as 6325 // operand. 6326 // 6327 // (fadd (fmul c, x), x) -> (fmul c+1, x) 6328 // 6329 bool AllowNewFpConst = (Level < AfterLegalizeDAG); 6330 6331 // If allow, fold (fadd (fneg x), x) -> 0.0 6332 if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath && 6333 N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1) 6334 return DAG.getConstantFP(0.0, VT); 6335 6336 // If allow, fold (fadd x, (fneg x)) -> 0.0 6337 if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath && 6338 N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0) 6339 return DAG.getConstantFP(0.0, VT); 6340 6341 // In unsafe math mode, we can fold chains of FADD's of the same value 6342 // into multiplications. This transform is not safe in general because 6343 // we are reducing the number of rounding steps. 6344 if (DAG.getTarget().Options.UnsafeFPMath && 6345 TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && 6346 !N0CFP && !N1CFP) { 6347 if (N0.getOpcode() == ISD::FMUL) { 6348 ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0)); 6349 ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1)); 6350 6351 // (fadd (fmul c, x), x) -> (fmul x, c+1) 6352 if (CFP00 && !CFP01 && N0.getOperand(1) == N1) { 6353 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT, 6354 SDValue(CFP00, 0), 6355 DAG.getConstantFP(1.0, VT)); 6356 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, 6357 N1, NewCFP); 6358 } 6359 6360 // (fadd (fmul x, c), x) -> (fmul x, c+1) 6361 if (CFP01 && !CFP00 && N0.getOperand(0) == N1) { 6362 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT, 6363 SDValue(CFP01, 0), 6364 DAG.getConstantFP(1.0, VT)); 6365 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, 6366 N1, NewCFP); 6367 } 6368 6369 // (fadd (fmul c, x), (fadd x, x)) -> (fmul x, c+2) 6370 if (CFP00 && !CFP01 && N1.getOpcode() == ISD::FADD && 6371 N1.getOperand(0) == N1.getOperand(1) && 6372 N0.getOperand(1) == N1.getOperand(0)) { 6373 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT, 6374 SDValue(CFP00, 0), 6375 DAG.getConstantFP(2.0, VT)); 6376 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, 6377 N0.getOperand(1), NewCFP); 6378 } 6379 6380 // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2) 6381 if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD && 6382 N1.getOperand(0) == N1.getOperand(1) && 6383 N0.getOperand(0) == N1.getOperand(0)) { 6384 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT, 6385 SDValue(CFP01, 0), 6386 DAG.getConstantFP(2.0, VT)); 6387 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, 6388 N0.getOperand(0), NewCFP); 6389 } 6390 } 6391 6392 if (N1.getOpcode() == ISD::FMUL) { 6393 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0)); 6394 ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1)); 6395 6396 // (fadd x, (fmul c, x)) -> (fmul x, c+1) 6397 if (CFP10 && !CFP11 && N1.getOperand(1) == N0) { 6398 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT, 6399 SDValue(CFP10, 0), 6400 DAG.getConstantFP(1.0, VT)); 6401 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, 6402 N0, NewCFP); 6403 } 6404 6405 // (fadd x, (fmul x, c)) -> (fmul x, c+1) 6406 if (CFP11 && !CFP10 && N1.getOperand(0) == N0) { 6407 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT, 6408 SDValue(CFP11, 0), 6409 DAG.getConstantFP(1.0, VT)); 6410 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, 6411 N0, NewCFP); 6412 } 6413 6414 6415 // (fadd (fadd x, x), (fmul c, x)) -> (fmul x, c+2) 6416 if (CFP10 && !CFP11 && N0.getOpcode() == ISD::FADD && 6417 N0.getOperand(0) == N0.getOperand(1) && 6418 N1.getOperand(1) == N0.getOperand(0)) { 6419 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT, 6420 SDValue(CFP10, 0), 6421 DAG.getConstantFP(2.0, VT)); 6422 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, 6423 N1.getOperand(1), NewCFP); 6424 } 6425 6426 // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2) 6427 if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD && 6428 N0.getOperand(0) == N0.getOperand(1) && 6429 N1.getOperand(0) == N0.getOperand(0)) { 6430 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT, 6431 SDValue(CFP11, 0), 6432 DAG.getConstantFP(2.0, VT)); 6433 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, 6434 N1.getOperand(0), NewCFP); 6435 } 6436 } 6437 6438 if (N0.getOpcode() == ISD::FADD && AllowNewFpConst) { 6439 ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0)); 6440 // (fadd (fadd x, x), x) -> (fmul x, 3.0) 6441 if (!CFP && N0.getOperand(0) == N0.getOperand(1) && 6442 (N0.getOperand(0) == N1)) 6443 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, 6444 N1, DAG.getConstantFP(3.0, VT)); 6445 } 6446 6447 if (N1.getOpcode() == ISD::FADD && AllowNewFpConst) { 6448 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0)); 6449 // (fadd x, (fadd x, x)) -> (fmul x, 3.0) 6450 if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) && 6451 N1.getOperand(0) == N0) 6452 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, 6453 N0, DAG.getConstantFP(3.0, VT)); 6454 } 6455 6456 // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0) 6457 if (AllowNewFpConst && 6458 N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD && 6459 N0.getOperand(0) == N0.getOperand(1) && 6460 N1.getOperand(0) == N1.getOperand(1) && 6461 N0.getOperand(0) == N1.getOperand(0)) 6462 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, 6463 N0.getOperand(0), 6464 DAG.getConstantFP(4.0, VT)); 6465 } 6466 6467 // FADD -> FMA combines: 6468 if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast || 6469 DAG.getTarget().Options.UnsafeFPMath) && 6470 DAG.getTarget().getTargetLowering()->isFMAFasterThanFMulAndFAdd(VT) && 6471 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) { 6472 6473 // fold (fadd (fmul x, y), z) -> (fma x, y, z) 6474 if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse()) 6475 return DAG.getNode(ISD::FMA, SDLoc(N), VT, 6476 N0.getOperand(0), N0.getOperand(1), N1); 6477 6478 // fold (fadd x, (fmul y, z)) -> (fma y, z, x) 6479 // Note: Commutes FADD operands. 6480 if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse()) 6481 return DAG.getNode(ISD::FMA, SDLoc(N), VT, 6482 N1.getOperand(0), N1.getOperand(1), N0); 6483 } 6484 6485 return SDValue(); 6486 } 6487 6488 SDValue DAGCombiner::visitFSUB(SDNode *N) { 6489 SDValue N0 = N->getOperand(0); 6490 SDValue N1 = N->getOperand(1); 6491 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 6492 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 6493 EVT VT = N->getValueType(0); 6494 SDLoc dl(N); 6495 6496 // fold vector ops 6497 if (VT.isVector()) { 6498 SDValue FoldedVOp = SimplifyVBinOp(N); 6499 if (FoldedVOp.getNode()) return FoldedVOp; 6500 } 6501 6502 // fold (fsub c1, c2) -> c1-c2 6503 if (N0CFP && N1CFP) 6504 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0, N1); 6505 // fold (fsub A, 0) -> A 6506 if (DAG.getTarget().Options.UnsafeFPMath && 6507 N1CFP && N1CFP->getValueAPF().isZero()) 6508 return N0; 6509 // fold (fsub 0, B) -> -B 6510 if (DAG.getTarget().Options.UnsafeFPMath && 6511 N0CFP && N0CFP->getValueAPF().isZero()) { 6512 if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options)) 6513 return GetNegatedExpression(N1, DAG, LegalOperations); 6514 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT)) 6515 return DAG.getNode(ISD::FNEG, dl, VT, N1); 6516 } 6517 // fold (fsub A, (fneg B)) -> (fadd A, B) 6518 if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options)) 6519 return DAG.getNode(ISD::FADD, dl, VT, N0, 6520 GetNegatedExpression(N1, DAG, LegalOperations)); 6521 6522 // If 'unsafe math' is enabled, fold 6523 // (fsub x, x) -> 0.0 & 6524 // (fsub x, (fadd x, y)) -> (fneg y) & 6525 // (fsub x, (fadd y, x)) -> (fneg y) 6526 if (DAG.getTarget().Options.UnsafeFPMath) { 6527 if (N0 == N1) 6528 return DAG.getConstantFP(0.0f, VT); 6529 6530 if (N1.getOpcode() == ISD::FADD) { 6531 SDValue N10 = N1->getOperand(0); 6532 SDValue N11 = N1->getOperand(1); 6533 6534 if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, 6535 &DAG.getTarget().Options)) 6536 return GetNegatedExpression(N11, DAG, LegalOperations); 6537 6538 if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, 6539 &DAG.getTarget().Options)) 6540 return GetNegatedExpression(N10, DAG, LegalOperations); 6541 } 6542 } 6543 6544 // FSUB -> FMA combines: 6545 if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast || 6546 DAG.getTarget().Options.UnsafeFPMath) && 6547 DAG.getTarget().getTargetLowering()->isFMAFasterThanFMulAndFAdd(VT) && 6548 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) { 6549 6550 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z)) 6551 if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse()) 6552 return DAG.getNode(ISD::FMA, dl, VT, 6553 N0.getOperand(0), N0.getOperand(1), 6554 DAG.getNode(ISD::FNEG, dl, VT, N1)); 6555 6556 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x) 6557 // Note: Commutes FSUB operands. 6558 if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse()) 6559 return DAG.getNode(ISD::FMA, dl, VT, 6560 DAG.getNode(ISD::FNEG, dl, VT, 6561 N1.getOperand(0)), 6562 N1.getOperand(1), N0); 6563 6564 // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z)) 6565 if (N0.getOpcode() == ISD::FNEG && 6566 N0.getOperand(0).getOpcode() == ISD::FMUL && 6567 N0->hasOneUse() && N0.getOperand(0).hasOneUse()) { 6568 SDValue N00 = N0.getOperand(0).getOperand(0); 6569 SDValue N01 = N0.getOperand(0).getOperand(1); 6570 return DAG.getNode(ISD::FMA, dl, VT, 6571 DAG.getNode(ISD::FNEG, dl, VT, N00), N01, 6572 DAG.getNode(ISD::FNEG, dl, VT, N1)); 6573 } 6574 } 6575 6576 return SDValue(); 6577 } 6578 6579 SDValue DAGCombiner::visitFMUL(SDNode *N) { 6580 SDValue N0 = N->getOperand(0); 6581 SDValue N1 = N->getOperand(1); 6582 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 6583 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 6584 EVT VT = N->getValueType(0); 6585 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6586 6587 // fold vector ops 6588 if (VT.isVector()) { 6589 SDValue FoldedVOp = SimplifyVBinOp(N); 6590 if (FoldedVOp.getNode()) return FoldedVOp; 6591 } 6592 6593 // fold (fmul c1, c2) -> c1*c2 6594 if (N0CFP && N1CFP) 6595 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, N1); 6596 // canonicalize constant to RHS 6597 if (N0CFP && !N1CFP) 6598 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, N0); 6599 // fold (fmul A, 0) -> 0 6600 if (DAG.getTarget().Options.UnsafeFPMath && 6601 N1CFP && N1CFP->getValueAPF().isZero()) 6602 return N1; 6603 // fold (fmul A, 0) -> 0, vector edition. 6604 if (DAG.getTarget().Options.UnsafeFPMath && 6605 ISD::isBuildVectorAllZeros(N1.getNode())) 6606 return N1; 6607 // fold (fmul A, 1.0) -> A 6608 if (N1CFP && N1CFP->isExactlyValue(1.0)) 6609 return N0; 6610 // fold (fmul X, 2.0) -> (fadd X, X) 6611 if (N1CFP && N1CFP->isExactlyValue(+2.0)) 6612 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N0); 6613 // fold (fmul X, -1.0) -> (fneg X) 6614 if (N1CFP && N1CFP->isExactlyValue(-1.0)) 6615 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT)) 6616 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0); 6617 6618 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y) 6619 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, 6620 &DAG.getTarget().Options)) { 6621 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, 6622 &DAG.getTarget().Options)) { 6623 // Both can be negated for free, check to see if at least one is cheaper 6624 // negated. 6625 if (LHSNeg == 2 || RHSNeg == 2) 6626 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, 6627 GetNegatedExpression(N0, DAG, LegalOperations), 6628 GetNegatedExpression(N1, DAG, LegalOperations)); 6629 } 6630 } 6631 6632 // If allowed, fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2)) 6633 if (DAG.getTarget().Options.UnsafeFPMath && 6634 N1CFP && N0.getOpcode() == ISD::FMUL && 6635 N0.getNode()->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1))) 6636 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0), 6637 DAG.getNode(ISD::FMUL, SDLoc(N), VT, 6638 N0.getOperand(1), N1)); 6639 6640 return SDValue(); 6641 } 6642 6643 SDValue DAGCombiner::visitFMA(SDNode *N) { 6644 SDValue N0 = N->getOperand(0); 6645 SDValue N1 = N->getOperand(1); 6646 SDValue N2 = N->getOperand(2); 6647 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 6648 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 6649 EVT VT = N->getValueType(0); 6650 SDLoc dl(N); 6651 6652 if (DAG.getTarget().Options.UnsafeFPMath) { 6653 if (N0CFP && N0CFP->isZero()) 6654 return N2; 6655 if (N1CFP && N1CFP->isZero()) 6656 return N2; 6657 } 6658 if (N0CFP && N0CFP->isExactlyValue(1.0)) 6659 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2); 6660 if (N1CFP && N1CFP->isExactlyValue(1.0)) 6661 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2); 6662 6663 // Canonicalize (fma c, x, y) -> (fma x, c, y) 6664 if (N0CFP && !N1CFP) 6665 return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2); 6666 6667 // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2) 6668 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP && 6669 N2.getOpcode() == ISD::FMUL && 6670 N0 == N2.getOperand(0) && 6671 N2.getOperand(1).getOpcode() == ISD::ConstantFP) { 6672 return DAG.getNode(ISD::FMUL, dl, VT, N0, 6673 DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1))); 6674 } 6675 6676 6677 // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y) 6678 if (DAG.getTarget().Options.UnsafeFPMath && 6679 N0.getOpcode() == ISD::FMUL && N1CFP && 6680 N0.getOperand(1).getOpcode() == ISD::ConstantFP) { 6681 return DAG.getNode(ISD::FMA, dl, VT, 6682 N0.getOperand(0), 6683 DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)), 6684 N2); 6685 } 6686 6687 // (fma x, 1, y) -> (fadd x, y) 6688 // (fma x, -1, y) -> (fadd (fneg x), y) 6689 if (N1CFP) { 6690 if (N1CFP->isExactlyValue(1.0)) 6691 return DAG.getNode(ISD::FADD, dl, VT, N0, N2); 6692 6693 if (N1CFP->isExactlyValue(-1.0) && 6694 (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) { 6695 SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0); 6696 AddToWorkList(RHSNeg.getNode()); 6697 return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg); 6698 } 6699 } 6700 6701 // (fma x, c, x) -> (fmul x, (c+1)) 6702 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP && N0 == N2) 6703 return DAG.getNode(ISD::FMUL, dl, VT, N0, 6704 DAG.getNode(ISD::FADD, dl, VT, 6705 N1, DAG.getConstantFP(1.0, VT))); 6706 6707 // (fma x, c, (fneg x)) -> (fmul x, (c-1)) 6708 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP && 6709 N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0) 6710 return DAG.getNode(ISD::FMUL, dl, VT, N0, 6711 DAG.getNode(ISD::FADD, dl, VT, 6712 N1, DAG.getConstantFP(-1.0, VT))); 6713 6714 6715 return SDValue(); 6716 } 6717 6718 SDValue DAGCombiner::visitFDIV(SDNode *N) { 6719 SDValue N0 = N->getOperand(0); 6720 SDValue N1 = N->getOperand(1); 6721 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 6722 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 6723 EVT VT = N->getValueType(0); 6724 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6725 6726 // fold vector ops 6727 if (VT.isVector()) { 6728 SDValue FoldedVOp = SimplifyVBinOp(N); 6729 if (FoldedVOp.getNode()) return FoldedVOp; 6730 } 6731 6732 // fold (fdiv c1, c2) -> c1/c2 6733 if (N0CFP && N1CFP) 6734 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1); 6735 6736 // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable. 6737 if (N1CFP && DAG.getTarget().Options.UnsafeFPMath) { 6738 // Compute the reciprocal 1.0 / c2. 6739 APFloat N1APF = N1CFP->getValueAPF(); 6740 APFloat Recip(N1APF.getSemantics(), 1); // 1.0 6741 APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven); 6742 // Only do the transform if the reciprocal is a legal fp immediate that 6743 // isn't too nasty (eg NaN, denormal, ...). 6744 if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty 6745 (!LegalOperations || 6746 // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM 6747 // backend)... we should handle this gracefully after Legalize. 6748 // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) || 6749 TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) || 6750 TLI.isFPImmLegal(Recip, VT))) 6751 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, 6752 DAG.getConstantFP(Recip, VT)); 6753 } 6754 6755 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y) 6756 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, 6757 &DAG.getTarget().Options)) { 6758 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, 6759 &DAG.getTarget().Options)) { 6760 // Both can be negated for free, check to see if at least one is cheaper 6761 // negated. 6762 if (LHSNeg == 2 || RHSNeg == 2) 6763 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, 6764 GetNegatedExpression(N0, DAG, LegalOperations), 6765 GetNegatedExpression(N1, DAG, LegalOperations)); 6766 } 6767 } 6768 6769 return SDValue(); 6770 } 6771 6772 SDValue DAGCombiner::visitFREM(SDNode *N) { 6773 SDValue N0 = N->getOperand(0); 6774 SDValue N1 = N->getOperand(1); 6775 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 6776 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 6777 EVT VT = N->getValueType(0); 6778 6779 // fold (frem c1, c2) -> fmod(c1,c2) 6780 if (N0CFP && N1CFP) 6781 return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1); 6782 6783 return SDValue(); 6784 } 6785 6786 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) { 6787 SDValue N0 = N->getOperand(0); 6788 SDValue N1 = N->getOperand(1); 6789 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 6790 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 6791 EVT VT = N->getValueType(0); 6792 6793 if (N0CFP && N1CFP) // Constant fold 6794 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1); 6795 6796 if (N1CFP) { 6797 const APFloat& V = N1CFP->getValueAPF(); 6798 // copysign(x, c1) -> fabs(x) iff ispos(c1) 6799 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1) 6800 if (!V.isNegative()) { 6801 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT)) 6802 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0); 6803 } else { 6804 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT)) 6805 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, 6806 DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0)); 6807 } 6808 } 6809 6810 // copysign(fabs(x), y) -> copysign(x, y) 6811 // copysign(fneg(x), y) -> copysign(x, y) 6812 // copysign(copysign(x,z), y) -> copysign(x, y) 6813 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG || 6814 N0.getOpcode() == ISD::FCOPYSIGN) 6815 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, 6816 N0.getOperand(0), N1); 6817 6818 // copysign(x, abs(y)) -> abs(x) 6819 if (N1.getOpcode() == ISD::FABS) 6820 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0); 6821 6822 // copysign(x, copysign(y,z)) -> copysign(x, z) 6823 if (N1.getOpcode() == ISD::FCOPYSIGN) 6824 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, 6825 N0, N1.getOperand(1)); 6826 6827 // copysign(x, fp_extend(y)) -> copysign(x, y) 6828 // copysign(x, fp_round(y)) -> copysign(x, y) 6829 if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND) 6830 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, 6831 N0, N1.getOperand(0)); 6832 6833 return SDValue(); 6834 } 6835 6836 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) { 6837 SDValue N0 = N->getOperand(0); 6838 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 6839 EVT VT = N->getValueType(0); 6840 EVT OpVT = N0.getValueType(); 6841 6842 // fold (sint_to_fp c1) -> c1fp 6843 if (N0C && 6844 // ...but only if the target supports immediate floating-point values 6845 (!LegalOperations || 6846 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) 6847 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0); 6848 6849 // If the input is a legal type, and SINT_TO_FP is not legal on this target, 6850 // but UINT_TO_FP is legal on this target, try to convert. 6851 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) && 6852 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) { 6853 // If the sign bit is known to be zero, we can change this to UINT_TO_FP. 6854 if (DAG.SignBitIsZero(N0)) 6855 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0); 6856 } 6857 6858 // The next optimizations are desirable only if SELECT_CC can be lowered. 6859 // Check against MVT::Other for SELECT_CC, which is a workaround for targets 6860 // having to say they don't support SELECT_CC on every type the DAG knows 6861 // about, since there is no way to mark an opcode illegal at all value types 6862 // (See also visitSELECT) 6863 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other)) { 6864 // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc) 6865 if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 && 6866 !VT.isVector() && 6867 (!LegalOperations || 6868 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) { 6869 SDValue Ops[] = 6870 { N0.getOperand(0), N0.getOperand(1), 6871 DAG.getConstantFP(-1.0, VT) , DAG.getConstantFP(0.0, VT), 6872 N0.getOperand(2) }; 6873 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops, 5); 6874 } 6875 6876 // fold (sint_to_fp (zext (setcc x, y, cc))) -> 6877 // (select_cc x, y, 1.0, 0.0,, cc) 6878 if (N0.getOpcode() == ISD::ZERO_EXTEND && 6879 N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() && 6880 (!LegalOperations || 6881 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) { 6882 SDValue Ops[] = 6883 { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1), 6884 DAG.getConstantFP(1.0, VT) , DAG.getConstantFP(0.0, VT), 6885 N0.getOperand(0).getOperand(2) }; 6886 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops, 5); 6887 } 6888 } 6889 6890 return SDValue(); 6891 } 6892 6893 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) { 6894 SDValue N0 = N->getOperand(0); 6895 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 6896 EVT VT = N->getValueType(0); 6897 EVT OpVT = N0.getValueType(); 6898 6899 // fold (uint_to_fp c1) -> c1fp 6900 if (N0C && 6901 // ...but only if the target supports immediate floating-point values 6902 (!LegalOperations || 6903 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) 6904 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0); 6905 6906 // If the input is a legal type, and UINT_TO_FP is not legal on this target, 6907 // but SINT_TO_FP is legal on this target, try to convert. 6908 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) && 6909 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) { 6910 // If the sign bit is known to be zero, we can change this to SINT_TO_FP. 6911 if (DAG.SignBitIsZero(N0)) 6912 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0); 6913 } 6914 6915 // The next optimizations are desirable only if SELECT_CC can be lowered. 6916 // Check against MVT::Other for SELECT_CC, which is a workaround for targets 6917 // having to say they don't support SELECT_CC on every type the DAG knows 6918 // about, since there is no way to mark an opcode illegal at all value types 6919 // (See also visitSELECT) 6920 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other)) { 6921 // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc) 6922 6923 if (N0.getOpcode() == ISD::SETCC && !VT.isVector() && 6924 (!LegalOperations || 6925 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) { 6926 SDValue Ops[] = 6927 { N0.getOperand(0), N0.getOperand(1), 6928 DAG.getConstantFP(1.0, VT), DAG.getConstantFP(0.0, VT), 6929 N0.getOperand(2) }; 6930 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops, 5); 6931 } 6932 } 6933 6934 return SDValue(); 6935 } 6936 6937 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) { 6938 SDValue N0 = N->getOperand(0); 6939 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 6940 EVT VT = N->getValueType(0); 6941 6942 // fold (fp_to_sint c1fp) -> c1 6943 if (N0CFP) 6944 return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0); 6945 6946 return SDValue(); 6947 } 6948 6949 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) { 6950 SDValue N0 = N->getOperand(0); 6951 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 6952 EVT VT = N->getValueType(0); 6953 6954 // fold (fp_to_uint c1fp) -> c1 6955 if (N0CFP) 6956 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0); 6957 6958 return SDValue(); 6959 } 6960 6961 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) { 6962 SDValue N0 = N->getOperand(0); 6963 SDValue N1 = N->getOperand(1); 6964 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 6965 EVT VT = N->getValueType(0); 6966 6967 // fold (fp_round c1fp) -> c1fp 6968 if (N0CFP) 6969 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1); 6970 6971 // fold (fp_round (fp_extend x)) -> x 6972 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType()) 6973 return N0.getOperand(0); 6974 6975 // fold (fp_round (fp_round x)) -> (fp_round x) 6976 if (N0.getOpcode() == ISD::FP_ROUND) { 6977 // This is a value preserving truncation if both round's are. 6978 bool IsTrunc = N->getConstantOperandVal(1) == 1 && 6979 N0.getNode()->getConstantOperandVal(1) == 1; 6980 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0.getOperand(0), 6981 DAG.getIntPtrConstant(IsTrunc)); 6982 } 6983 6984 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y) 6985 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) { 6986 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT, 6987 N0.getOperand(0), N1); 6988 AddToWorkList(Tmp.getNode()); 6989 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, 6990 Tmp, N0.getOperand(1)); 6991 } 6992 6993 return SDValue(); 6994 } 6995 6996 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) { 6997 SDValue N0 = N->getOperand(0); 6998 EVT VT = N->getValueType(0); 6999 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT(); 7000 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 7001 7002 // fold (fp_round_inreg c1fp) -> c1fp 7003 if (N0CFP && isTypeLegal(EVT)) { 7004 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT); 7005 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, Round); 7006 } 7007 7008 return SDValue(); 7009 } 7010 7011 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) { 7012 SDValue N0 = N->getOperand(0); 7013 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 7014 EVT VT = N->getValueType(0); 7015 7016 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded. 7017 if (N->hasOneUse() && 7018 N->use_begin()->getOpcode() == ISD::FP_ROUND) 7019 return SDValue(); 7020 7021 // fold (fp_extend c1fp) -> c1fp 7022 if (N0CFP) 7023 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0); 7024 7025 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the 7026 // value of X. 7027 if (N0.getOpcode() == ISD::FP_ROUND 7028 && N0.getNode()->getConstantOperandVal(1) == 1) { 7029 SDValue In = N0.getOperand(0); 7030 if (In.getValueType() == VT) return In; 7031 if (VT.bitsLT(In.getValueType())) 7032 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, 7033 In, N0.getOperand(1)); 7034 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In); 7035 } 7036 7037 // fold (fpext (load x)) -> (fpext (fptrunc (extload x))) 7038 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() && 7039 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) || 7040 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) { 7041 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 7042 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT, 7043 LN0->getChain(), 7044 LN0->getBasePtr(), N0.getValueType(), 7045 LN0->getMemOperand()); 7046 CombineTo(N, ExtLoad); 7047 CombineTo(N0.getNode(), 7048 DAG.getNode(ISD::FP_ROUND, SDLoc(N0), 7049 N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)), 7050 ExtLoad.getValue(1)); 7051 return SDValue(N, 0); // Return N so it doesn't get rechecked! 7052 } 7053 7054 return SDValue(); 7055 } 7056 7057 SDValue DAGCombiner::visitFNEG(SDNode *N) { 7058 SDValue N0 = N->getOperand(0); 7059 EVT VT = N->getValueType(0); 7060 7061 if (VT.isVector()) { 7062 SDValue FoldedVOp = SimplifyVUnaryOp(N); 7063 if (FoldedVOp.getNode()) return FoldedVOp; 7064 } 7065 7066 if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(), 7067 &DAG.getTarget().Options)) 7068 return GetNegatedExpression(N0, DAG, LegalOperations); 7069 7070 // Transform fneg(bitconvert(x)) -> bitconvert(x^sign) to avoid loading 7071 // constant pool values. 7072 if (!TLI.isFNegFree(VT) && N0.getOpcode() == ISD::BITCAST && 7073 !VT.isVector() && 7074 N0.getNode()->hasOneUse() && 7075 N0.getOperand(0).getValueType().isInteger()) { 7076 SDValue Int = N0.getOperand(0); 7077 EVT IntVT = Int.getValueType(); 7078 if (IntVT.isInteger() && !IntVT.isVector()) { 7079 Int = DAG.getNode(ISD::XOR, SDLoc(N0), IntVT, Int, 7080 DAG.getConstant(APInt::getSignBit(IntVT.getSizeInBits()), IntVT)); 7081 AddToWorkList(Int.getNode()); 7082 return DAG.getNode(ISD::BITCAST, SDLoc(N), 7083 VT, Int); 7084 } 7085 } 7086 7087 // (fneg (fmul c, x)) -> (fmul -c, x) 7088 if (N0.getOpcode() == ISD::FMUL) { 7089 ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1)); 7090 if (CFP1) 7091 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, 7092 N0.getOperand(0), 7093 DAG.getNode(ISD::FNEG, SDLoc(N), VT, 7094 N0.getOperand(1))); 7095 } 7096 7097 return SDValue(); 7098 } 7099 7100 SDValue DAGCombiner::visitFCEIL(SDNode *N) { 7101 SDValue N0 = N->getOperand(0); 7102 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 7103 EVT VT = N->getValueType(0); 7104 7105 // fold (fceil c1) -> fceil(c1) 7106 if (N0CFP) 7107 return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0); 7108 7109 return SDValue(); 7110 } 7111 7112 SDValue DAGCombiner::visitFTRUNC(SDNode *N) { 7113 SDValue N0 = N->getOperand(0); 7114 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 7115 EVT VT = N->getValueType(0); 7116 7117 // fold (ftrunc c1) -> ftrunc(c1) 7118 if (N0CFP) 7119 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0); 7120 7121 return SDValue(); 7122 } 7123 7124 SDValue DAGCombiner::visitFFLOOR(SDNode *N) { 7125 SDValue N0 = N->getOperand(0); 7126 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 7127 EVT VT = N->getValueType(0); 7128 7129 // fold (ffloor c1) -> ffloor(c1) 7130 if (N0CFP) 7131 return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0); 7132 7133 return SDValue(); 7134 } 7135 7136 SDValue DAGCombiner::visitFABS(SDNode *N) { 7137 SDValue N0 = N->getOperand(0); 7138 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 7139 EVT VT = N->getValueType(0); 7140 7141 if (VT.isVector()) { 7142 SDValue FoldedVOp = SimplifyVUnaryOp(N); 7143 if (FoldedVOp.getNode()) return FoldedVOp; 7144 } 7145 7146 // fold (fabs c1) -> fabs(c1) 7147 if (N0CFP) 7148 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0); 7149 // fold (fabs (fabs x)) -> (fabs x) 7150 if (N0.getOpcode() == ISD::FABS) 7151 return N->getOperand(0); 7152 // fold (fabs (fneg x)) -> (fabs x) 7153 // fold (fabs (fcopysign x, y)) -> (fabs x) 7154 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN) 7155 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0)); 7156 7157 // Transform fabs(bitconvert(x)) -> bitconvert(x&~sign) to avoid loading 7158 // constant pool values. 7159 if (!TLI.isFAbsFree(VT) && 7160 N0.getOpcode() == ISD::BITCAST && N0.getNode()->hasOneUse() && 7161 N0.getOperand(0).getValueType().isInteger() && 7162 !N0.getOperand(0).getValueType().isVector()) { 7163 SDValue Int = N0.getOperand(0); 7164 EVT IntVT = Int.getValueType(); 7165 if (IntVT.isInteger() && !IntVT.isVector()) { 7166 Int = DAG.getNode(ISD::AND, SDLoc(N0), IntVT, Int, 7167 DAG.getConstant(~APInt::getSignBit(IntVT.getSizeInBits()), IntVT)); 7168 AddToWorkList(Int.getNode()); 7169 return DAG.getNode(ISD::BITCAST, SDLoc(N), 7170 N->getValueType(0), Int); 7171 } 7172 } 7173 7174 return SDValue(); 7175 } 7176 7177 SDValue DAGCombiner::visitBRCOND(SDNode *N) { 7178 SDValue Chain = N->getOperand(0); 7179 SDValue N1 = N->getOperand(1); 7180 SDValue N2 = N->getOperand(2); 7181 7182 // If N is a constant we could fold this into a fallthrough or unconditional 7183 // branch. However that doesn't happen very often in normal code, because 7184 // Instcombine/SimplifyCFG should have handled the available opportunities. 7185 // If we did this folding here, it would be necessary to update the 7186 // MachineBasicBlock CFG, which is awkward. 7187 7188 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal 7189 // on the target. 7190 if (N1.getOpcode() == ISD::SETCC && 7191 TLI.isOperationLegalOrCustom(ISD::BR_CC, 7192 N1.getOperand(0).getValueType())) { 7193 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other, 7194 Chain, N1.getOperand(2), 7195 N1.getOperand(0), N1.getOperand(1), N2); 7196 } 7197 7198 if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) || 7199 ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) && 7200 (N1.getOperand(0).hasOneUse() && 7201 N1.getOperand(0).getOpcode() == ISD::SRL))) { 7202 SDNode *Trunc = 0; 7203 if (N1.getOpcode() == ISD::TRUNCATE) { 7204 // Look pass the truncate. 7205 Trunc = N1.getNode(); 7206 N1 = N1.getOperand(0); 7207 } 7208 7209 // Match this pattern so that we can generate simpler code: 7210 // 7211 // %a = ... 7212 // %b = and i32 %a, 2 7213 // %c = srl i32 %b, 1 7214 // brcond i32 %c ... 7215 // 7216 // into 7217 // 7218 // %a = ... 7219 // %b = and i32 %a, 2 7220 // %c = setcc eq %b, 0 7221 // brcond %c ... 7222 // 7223 // This applies only when the AND constant value has one bit set and the 7224 // SRL constant is equal to the log2 of the AND constant. The back-end is 7225 // smart enough to convert the result into a TEST/JMP sequence. 7226 SDValue Op0 = N1.getOperand(0); 7227 SDValue Op1 = N1.getOperand(1); 7228 7229 if (Op0.getOpcode() == ISD::AND && 7230 Op1.getOpcode() == ISD::Constant) { 7231 SDValue AndOp1 = Op0.getOperand(1); 7232 7233 if (AndOp1.getOpcode() == ISD::Constant) { 7234 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue(); 7235 7236 if (AndConst.isPowerOf2() && 7237 cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) { 7238 SDValue SetCC = 7239 DAG.getSetCC(SDLoc(N), 7240 getSetCCResultType(Op0.getValueType()), 7241 Op0, DAG.getConstant(0, Op0.getValueType()), 7242 ISD::SETNE); 7243 7244 SDValue NewBRCond = DAG.getNode(ISD::BRCOND, SDLoc(N), 7245 MVT::Other, Chain, SetCC, N2); 7246 // Don't add the new BRCond into the worklist or else SimplifySelectCC 7247 // will convert it back to (X & C1) >> C2. 7248 CombineTo(N, NewBRCond, false); 7249 // Truncate is dead. 7250 if (Trunc) { 7251 removeFromWorkList(Trunc); 7252 DAG.DeleteNode(Trunc); 7253 } 7254 // Replace the uses of SRL with SETCC 7255 WorkListRemover DeadNodes(*this); 7256 DAG.ReplaceAllUsesOfValueWith(N1, SetCC); 7257 removeFromWorkList(N1.getNode()); 7258 DAG.DeleteNode(N1.getNode()); 7259 return SDValue(N, 0); // Return N so it doesn't get rechecked! 7260 } 7261 } 7262 } 7263 7264 if (Trunc) 7265 // Restore N1 if the above transformation doesn't match. 7266 N1 = N->getOperand(1); 7267 } 7268 7269 // Transform br(xor(x, y)) -> br(x != y) 7270 // Transform br(xor(xor(x,y), 1)) -> br (x == y) 7271 if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) { 7272 SDNode *TheXor = N1.getNode(); 7273 SDValue Op0 = TheXor->getOperand(0); 7274 SDValue Op1 = TheXor->getOperand(1); 7275 if (Op0.getOpcode() == Op1.getOpcode()) { 7276 // Avoid missing important xor optimizations. 7277 SDValue Tmp = visitXOR(TheXor); 7278 if (Tmp.getNode()) { 7279 if (Tmp.getNode() != TheXor) { 7280 DEBUG(dbgs() << "\nReplacing.8 "; 7281 TheXor->dump(&DAG); 7282 dbgs() << "\nWith: "; 7283 Tmp.getNode()->dump(&DAG); 7284 dbgs() << '\n'); 7285 WorkListRemover DeadNodes(*this); 7286 DAG.ReplaceAllUsesOfValueWith(N1, Tmp); 7287 removeFromWorkList(TheXor); 7288 DAG.DeleteNode(TheXor); 7289 return DAG.getNode(ISD::BRCOND, SDLoc(N), 7290 MVT::Other, Chain, Tmp, N2); 7291 } 7292 7293 // visitXOR has changed XOR's operands or replaced the XOR completely, 7294 // bail out. 7295 return SDValue(N, 0); 7296 } 7297 } 7298 7299 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) { 7300 bool Equal = false; 7301 if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0)) 7302 if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() && 7303 Op0.getOpcode() == ISD::XOR) { 7304 TheXor = Op0.getNode(); 7305 Equal = true; 7306 } 7307 7308 EVT SetCCVT = N1.getValueType(); 7309 if (LegalTypes) 7310 SetCCVT = getSetCCResultType(SetCCVT); 7311 SDValue SetCC = DAG.getSetCC(SDLoc(TheXor), 7312 SetCCVT, 7313 Op0, Op1, 7314 Equal ? ISD::SETEQ : ISD::SETNE); 7315 // Replace the uses of XOR with SETCC 7316 WorkListRemover DeadNodes(*this); 7317 DAG.ReplaceAllUsesOfValueWith(N1, SetCC); 7318 removeFromWorkList(N1.getNode()); 7319 DAG.DeleteNode(N1.getNode()); 7320 return DAG.getNode(ISD::BRCOND, SDLoc(N), 7321 MVT::Other, Chain, SetCC, N2); 7322 } 7323 } 7324 7325 return SDValue(); 7326 } 7327 7328 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB. 7329 // 7330 SDValue DAGCombiner::visitBR_CC(SDNode *N) { 7331 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1)); 7332 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3); 7333 7334 // If N is a constant we could fold this into a fallthrough or unconditional 7335 // branch. However that doesn't happen very often in normal code, because 7336 // Instcombine/SimplifyCFG should have handled the available opportunities. 7337 // If we did this folding here, it would be necessary to update the 7338 // MachineBasicBlock CFG, which is awkward. 7339 7340 // Use SimplifySetCC to simplify SETCC's. 7341 SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()), 7342 CondLHS, CondRHS, CC->get(), SDLoc(N), 7343 false); 7344 if (Simp.getNode()) AddToWorkList(Simp.getNode()); 7345 7346 // fold to a simpler setcc 7347 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC) 7348 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other, 7349 N->getOperand(0), Simp.getOperand(2), 7350 Simp.getOperand(0), Simp.getOperand(1), 7351 N->getOperand(4)); 7352 7353 return SDValue(); 7354 } 7355 7356 /// canFoldInAddressingMode - Return true if 'Use' is a load or a store that 7357 /// uses N as its base pointer and that N may be folded in the load / store 7358 /// addressing mode. 7359 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use, 7360 SelectionDAG &DAG, 7361 const TargetLowering &TLI) { 7362 EVT VT; 7363 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) { 7364 if (LD->isIndexed() || LD->getBasePtr().getNode() != N) 7365 return false; 7366 VT = Use->getValueType(0); 7367 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) { 7368 if (ST->isIndexed() || ST->getBasePtr().getNode() != N) 7369 return false; 7370 VT = ST->getValue().getValueType(); 7371 } else 7372 return false; 7373 7374 TargetLowering::AddrMode AM; 7375 if (N->getOpcode() == ISD::ADD) { 7376 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1)); 7377 if (Offset) 7378 // [reg +/- imm] 7379 AM.BaseOffs = Offset->getSExtValue(); 7380 else 7381 // [reg +/- reg] 7382 AM.Scale = 1; 7383 } else if (N->getOpcode() == ISD::SUB) { 7384 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1)); 7385 if (Offset) 7386 // [reg +/- imm] 7387 AM.BaseOffs = -Offset->getSExtValue(); 7388 else 7389 // [reg +/- reg] 7390 AM.Scale = 1; 7391 } else 7392 return false; 7393 7394 return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext())); 7395 } 7396 7397 /// CombineToPreIndexedLoadStore - Try turning a load / store into a 7398 /// pre-indexed load / store when the base pointer is an add or subtract 7399 /// and it has other uses besides the load / store. After the 7400 /// transformation, the new indexed load / store has effectively folded 7401 /// the add / subtract in and all of its other uses are redirected to the 7402 /// new load / store. 7403 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) { 7404 if (Level < AfterLegalizeDAG) 7405 return false; 7406 7407 bool isLoad = true; 7408 SDValue Ptr; 7409 EVT VT; 7410 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 7411 if (LD->isIndexed()) 7412 return false; 7413 VT = LD->getMemoryVT(); 7414 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) && 7415 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT)) 7416 return false; 7417 Ptr = LD->getBasePtr(); 7418 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 7419 if (ST->isIndexed()) 7420 return false; 7421 VT = ST->getMemoryVT(); 7422 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) && 7423 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT)) 7424 return false; 7425 Ptr = ST->getBasePtr(); 7426 isLoad = false; 7427 } else { 7428 return false; 7429 } 7430 7431 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail 7432 // out. There is no reason to make this a preinc/predec. 7433 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) || 7434 Ptr.getNode()->hasOneUse()) 7435 return false; 7436 7437 // Ask the target to do addressing mode selection. 7438 SDValue BasePtr; 7439 SDValue Offset; 7440 ISD::MemIndexedMode AM = ISD::UNINDEXED; 7441 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG)) 7442 return false; 7443 7444 // Backends without true r+i pre-indexed forms may need to pass a 7445 // constant base with a variable offset so that constant coercion 7446 // will work with the patterns in canonical form. 7447 bool Swapped = false; 7448 if (isa<ConstantSDNode>(BasePtr)) { 7449 std::swap(BasePtr, Offset); 7450 Swapped = true; 7451 } 7452 7453 // Don't create a indexed load / store with zero offset. 7454 if (isa<ConstantSDNode>(Offset) && 7455 cast<ConstantSDNode>(Offset)->isNullValue()) 7456 return false; 7457 7458 // Try turning it into a pre-indexed load / store except when: 7459 // 1) The new base ptr is a frame index. 7460 // 2) If N is a store and the new base ptr is either the same as or is a 7461 // predecessor of the value being stored. 7462 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded 7463 // that would create a cycle. 7464 // 4) All uses are load / store ops that use it as old base ptr. 7465 7466 // Check #1. Preinc'ing a frame index would require copying the stack pointer 7467 // (plus the implicit offset) to a register to preinc anyway. 7468 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr)) 7469 return false; 7470 7471 // Check #2. 7472 if (!isLoad) { 7473 SDValue Val = cast<StoreSDNode>(N)->getValue(); 7474 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode())) 7475 return false; 7476 } 7477 7478 // If the offset is a constant, there may be other adds of constants that 7479 // can be folded with this one. We should do this to avoid having to keep 7480 // a copy of the original base pointer. 7481 SmallVector<SDNode *, 16> OtherUses; 7482 if (isa<ConstantSDNode>(Offset)) 7483 for (SDNode::use_iterator I = BasePtr.getNode()->use_begin(), 7484 E = BasePtr.getNode()->use_end(); I != E; ++I) { 7485 SDNode *Use = *I; 7486 if (Use == Ptr.getNode()) 7487 continue; 7488 7489 if (Use->isPredecessorOf(N)) 7490 continue; 7491 7492 if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) { 7493 OtherUses.clear(); 7494 break; 7495 } 7496 7497 SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1); 7498 if (Op1.getNode() == BasePtr.getNode()) 7499 std::swap(Op0, Op1); 7500 assert(Op0.getNode() == BasePtr.getNode() && 7501 "Use of ADD/SUB but not an operand"); 7502 7503 if (!isa<ConstantSDNode>(Op1)) { 7504 OtherUses.clear(); 7505 break; 7506 } 7507 7508 // FIXME: In some cases, we can be smarter about this. 7509 if (Op1.getValueType() != Offset.getValueType()) { 7510 OtherUses.clear(); 7511 break; 7512 } 7513 7514 OtherUses.push_back(Use); 7515 } 7516 7517 if (Swapped) 7518 std::swap(BasePtr, Offset); 7519 7520 // Now check for #3 and #4. 7521 bool RealUse = false; 7522 7523 // Caches for hasPredecessorHelper 7524 SmallPtrSet<const SDNode *, 32> Visited; 7525 SmallVector<const SDNode *, 16> Worklist; 7526 7527 for (SDNode::use_iterator I = Ptr.getNode()->use_begin(), 7528 E = Ptr.getNode()->use_end(); I != E; ++I) { 7529 SDNode *Use = *I; 7530 if (Use == N) 7531 continue; 7532 if (N->hasPredecessorHelper(Use, Visited, Worklist)) 7533 return false; 7534 7535 // If Ptr may be folded in addressing mode of other use, then it's 7536 // not profitable to do this transformation. 7537 if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI)) 7538 RealUse = true; 7539 } 7540 7541 if (!RealUse) 7542 return false; 7543 7544 SDValue Result; 7545 if (isLoad) 7546 Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N), 7547 BasePtr, Offset, AM); 7548 else 7549 Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N), 7550 BasePtr, Offset, AM); 7551 ++PreIndexedNodes; 7552 ++NodesCombined; 7553 DEBUG(dbgs() << "\nReplacing.4 "; 7554 N->dump(&DAG); 7555 dbgs() << "\nWith: "; 7556 Result.getNode()->dump(&DAG); 7557 dbgs() << '\n'); 7558 WorkListRemover DeadNodes(*this); 7559 if (isLoad) { 7560 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0)); 7561 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2)); 7562 } else { 7563 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1)); 7564 } 7565 7566 // Finally, since the node is now dead, remove it from the graph. 7567 DAG.DeleteNode(N); 7568 7569 if (Swapped) 7570 std::swap(BasePtr, Offset); 7571 7572 // Replace other uses of BasePtr that can be updated to use Ptr 7573 for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) { 7574 unsigned OffsetIdx = 1; 7575 if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode()) 7576 OffsetIdx = 0; 7577 assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() == 7578 BasePtr.getNode() && "Expected BasePtr operand"); 7579 7580 // We need to replace ptr0 in the following expression: 7581 // x0 * offset0 + y0 * ptr0 = t0 7582 // knowing that 7583 // x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store) 7584 // 7585 // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the 7586 // indexed load/store and the expresion that needs to be re-written. 7587 // 7588 // Therefore, we have: 7589 // t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1 7590 7591 ConstantSDNode *CN = 7592 cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx)); 7593 int X0, X1, Y0, Y1; 7594 APInt Offset0 = CN->getAPIntValue(); 7595 APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue(); 7596 7597 X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1; 7598 Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1; 7599 X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1; 7600 Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1; 7601 7602 unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD; 7603 7604 APInt CNV = Offset0; 7605 if (X0 < 0) CNV = -CNV; 7606 if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1; 7607 else CNV = CNV - Offset1; 7608 7609 // We can now generate the new expression. 7610 SDValue NewOp1 = DAG.getConstant(CNV, CN->getValueType(0)); 7611 SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0); 7612 7613 SDValue NewUse = DAG.getNode(Opcode, 7614 SDLoc(OtherUses[i]), 7615 OtherUses[i]->getValueType(0), NewOp1, NewOp2); 7616 DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse); 7617 removeFromWorkList(OtherUses[i]); 7618 DAG.DeleteNode(OtherUses[i]); 7619 } 7620 7621 // Replace the uses of Ptr with uses of the updated base value. 7622 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0)); 7623 removeFromWorkList(Ptr.getNode()); 7624 DAG.DeleteNode(Ptr.getNode()); 7625 7626 return true; 7627 } 7628 7629 /// CombineToPostIndexedLoadStore - Try to combine a load / store with a 7630 /// add / sub of the base pointer node into a post-indexed load / store. 7631 /// The transformation folded the add / subtract into the new indexed 7632 /// load / store effectively and all of its uses are redirected to the 7633 /// new load / store. 7634 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) { 7635 if (Level < AfterLegalizeDAG) 7636 return false; 7637 7638 bool isLoad = true; 7639 SDValue Ptr; 7640 EVT VT; 7641 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 7642 if (LD->isIndexed()) 7643 return false; 7644 VT = LD->getMemoryVT(); 7645 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) && 7646 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT)) 7647 return false; 7648 Ptr = LD->getBasePtr(); 7649 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 7650 if (ST->isIndexed()) 7651 return false; 7652 VT = ST->getMemoryVT(); 7653 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) && 7654 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT)) 7655 return false; 7656 Ptr = ST->getBasePtr(); 7657 isLoad = false; 7658 } else { 7659 return false; 7660 } 7661 7662 if (Ptr.getNode()->hasOneUse()) 7663 return false; 7664 7665 for (SDNode::use_iterator I = Ptr.getNode()->use_begin(), 7666 E = Ptr.getNode()->use_end(); I != E; ++I) { 7667 SDNode *Op = *I; 7668 if (Op == N || 7669 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB)) 7670 continue; 7671 7672 SDValue BasePtr; 7673 SDValue Offset; 7674 ISD::MemIndexedMode AM = ISD::UNINDEXED; 7675 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) { 7676 // Don't create a indexed load / store with zero offset. 7677 if (isa<ConstantSDNode>(Offset) && 7678 cast<ConstantSDNode>(Offset)->isNullValue()) 7679 continue; 7680 7681 // Try turning it into a post-indexed load / store except when 7682 // 1) All uses are load / store ops that use it as base ptr (and 7683 // it may be folded as addressing mmode). 7684 // 2) Op must be independent of N, i.e. Op is neither a predecessor 7685 // nor a successor of N. Otherwise, if Op is folded that would 7686 // create a cycle. 7687 7688 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr)) 7689 continue; 7690 7691 // Check for #1. 7692 bool TryNext = false; 7693 for (SDNode::use_iterator II = BasePtr.getNode()->use_begin(), 7694 EE = BasePtr.getNode()->use_end(); II != EE; ++II) { 7695 SDNode *Use = *II; 7696 if (Use == Ptr.getNode()) 7697 continue; 7698 7699 // If all the uses are load / store addresses, then don't do the 7700 // transformation. 7701 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){ 7702 bool RealUse = false; 7703 for (SDNode::use_iterator III = Use->use_begin(), 7704 EEE = Use->use_end(); III != EEE; ++III) { 7705 SDNode *UseUse = *III; 7706 if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI)) 7707 RealUse = true; 7708 } 7709 7710 if (!RealUse) { 7711 TryNext = true; 7712 break; 7713 } 7714 } 7715 } 7716 7717 if (TryNext) 7718 continue; 7719 7720 // Check for #2 7721 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) { 7722 SDValue Result = isLoad 7723 ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N), 7724 BasePtr, Offset, AM) 7725 : DAG.getIndexedStore(SDValue(N,0), SDLoc(N), 7726 BasePtr, Offset, AM); 7727 ++PostIndexedNodes; 7728 ++NodesCombined; 7729 DEBUG(dbgs() << "\nReplacing.5 "; 7730 N->dump(&DAG); 7731 dbgs() << "\nWith: "; 7732 Result.getNode()->dump(&DAG); 7733 dbgs() << '\n'); 7734 WorkListRemover DeadNodes(*this); 7735 if (isLoad) { 7736 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0)); 7737 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2)); 7738 } else { 7739 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1)); 7740 } 7741 7742 // Finally, since the node is now dead, remove it from the graph. 7743 DAG.DeleteNode(N); 7744 7745 // Replace the uses of Use with uses of the updated base value. 7746 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0), 7747 Result.getValue(isLoad ? 1 : 0)); 7748 removeFromWorkList(Op); 7749 DAG.DeleteNode(Op); 7750 return true; 7751 } 7752 } 7753 } 7754 7755 return false; 7756 } 7757 7758 SDValue DAGCombiner::visitLOAD(SDNode *N) { 7759 LoadSDNode *LD = cast<LoadSDNode>(N); 7760 SDValue Chain = LD->getChain(); 7761 SDValue Ptr = LD->getBasePtr(); 7762 7763 // If load is not volatile and there are no uses of the loaded value (and 7764 // the updated indexed value in case of indexed loads), change uses of the 7765 // chain value into uses of the chain input (i.e. delete the dead load). 7766 if (!LD->isVolatile()) { 7767 if (N->getValueType(1) == MVT::Other) { 7768 // Unindexed loads. 7769 if (!N->hasAnyUseOfValue(0)) { 7770 // It's not safe to use the two value CombineTo variant here. e.g. 7771 // v1, chain2 = load chain1, loc 7772 // v2, chain3 = load chain2, loc 7773 // v3 = add v2, c 7774 // Now we replace use of chain2 with chain1. This makes the second load 7775 // isomorphic to the one we are deleting, and thus makes this load live. 7776 DEBUG(dbgs() << "\nReplacing.6 "; 7777 N->dump(&DAG); 7778 dbgs() << "\nWith chain: "; 7779 Chain.getNode()->dump(&DAG); 7780 dbgs() << "\n"); 7781 WorkListRemover DeadNodes(*this); 7782 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain); 7783 7784 if (N->use_empty()) { 7785 removeFromWorkList(N); 7786 DAG.DeleteNode(N); 7787 } 7788 7789 return SDValue(N, 0); // Return N so it doesn't get rechecked! 7790 } 7791 } else { 7792 // Indexed loads. 7793 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?"); 7794 if (!N->hasAnyUseOfValue(0) && !N->hasAnyUseOfValue(1)) { 7795 SDValue Undef = DAG.getUNDEF(N->getValueType(0)); 7796 DEBUG(dbgs() << "\nReplacing.7 "; 7797 N->dump(&DAG); 7798 dbgs() << "\nWith: "; 7799 Undef.getNode()->dump(&DAG); 7800 dbgs() << " and 2 other values\n"); 7801 WorkListRemover DeadNodes(*this); 7802 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef); 7803 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), 7804 DAG.getUNDEF(N->getValueType(1))); 7805 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain); 7806 removeFromWorkList(N); 7807 DAG.DeleteNode(N); 7808 return SDValue(N, 0); // Return N so it doesn't get rechecked! 7809 } 7810 } 7811 } 7812 7813 // If this load is directly stored, replace the load value with the stored 7814 // value. 7815 // TODO: Handle store large -> read small portion. 7816 // TODO: Handle TRUNCSTORE/LOADEXT 7817 if (ISD::isNormalLoad(N) && !LD->isVolatile()) { 7818 if (ISD::isNON_TRUNCStore(Chain.getNode())) { 7819 StoreSDNode *PrevST = cast<StoreSDNode>(Chain); 7820 if (PrevST->getBasePtr() == Ptr && 7821 PrevST->getValue().getValueType() == N->getValueType(0)) 7822 return CombineTo(N, Chain.getOperand(1), Chain); 7823 } 7824 } 7825 7826 // Try to infer better alignment information than the load already has. 7827 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) { 7828 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) { 7829 if (Align > LD->getMemOperand()->getBaseAlignment()) { 7830 SDValue NewLoad = 7831 DAG.getExtLoad(LD->getExtensionType(), SDLoc(N), 7832 LD->getValueType(0), 7833 Chain, Ptr, LD->getPointerInfo(), 7834 LD->getMemoryVT(), 7835 LD->isVolatile(), LD->isNonTemporal(), Align, 7836 LD->getTBAAInfo()); 7837 return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true); 7838 } 7839 } 7840 } 7841 7842 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA : 7843 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA(); 7844 #ifndef NDEBUG 7845 if (CombinerAAOnlyFunc.getNumOccurrences() && 7846 CombinerAAOnlyFunc != DAG.getMachineFunction().getName()) 7847 UseAA = false; 7848 #endif 7849 if (UseAA && LD->isUnindexed()) { 7850 // Walk up chain skipping non-aliasing memory nodes. 7851 SDValue BetterChain = FindBetterChain(N, Chain); 7852 7853 // If there is a better chain. 7854 if (Chain != BetterChain) { 7855 SDValue ReplLoad; 7856 7857 // Replace the chain to void dependency. 7858 if (LD->getExtensionType() == ISD::NON_EXTLOAD) { 7859 ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD), 7860 BetterChain, Ptr, LD->getMemOperand()); 7861 } else { 7862 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), 7863 LD->getValueType(0), 7864 BetterChain, Ptr, LD->getMemoryVT(), 7865 LD->getMemOperand()); 7866 } 7867 7868 // Create token factor to keep old chain connected. 7869 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N), 7870 MVT::Other, Chain, ReplLoad.getValue(1)); 7871 7872 // Make sure the new and old chains are cleaned up. 7873 AddToWorkList(Token.getNode()); 7874 7875 // Replace uses with load result and token factor. Don't add users 7876 // to work list. 7877 return CombineTo(N, ReplLoad.getValue(0), Token, false); 7878 } 7879 } 7880 7881 // Try transforming N to an indexed load. 7882 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N)) 7883 return SDValue(N, 0); 7884 7885 // Try to slice up N to more direct loads if the slices are mapped to 7886 // different register banks or pairing can take place. 7887 if (SliceUpLoad(N)) 7888 return SDValue(N, 0); 7889 7890 return SDValue(); 7891 } 7892 7893 namespace { 7894 /// \brief Helper structure used to slice a load in smaller loads. 7895 /// Basically a slice is obtained from the following sequence: 7896 /// Origin = load Ty1, Base 7897 /// Shift = srl Ty1 Origin, CstTy Amount 7898 /// Inst = trunc Shift to Ty2 7899 /// 7900 /// Then, it will be rewriten into: 7901 /// Slice = load SliceTy, Base + SliceOffset 7902 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2 7903 /// 7904 /// SliceTy is deduced from the number of bits that are actually used to 7905 /// build Inst. 7906 struct LoadedSlice { 7907 /// \brief Helper structure used to compute the cost of a slice. 7908 struct Cost { 7909 /// Are we optimizing for code size. 7910 bool ForCodeSize; 7911 /// Various cost. 7912 unsigned Loads; 7913 unsigned Truncates; 7914 unsigned CrossRegisterBanksCopies; 7915 unsigned ZExts; 7916 unsigned Shift; 7917 7918 Cost(bool ForCodeSize = false) 7919 : ForCodeSize(ForCodeSize), Loads(0), Truncates(0), 7920 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {} 7921 7922 /// \brief Get the cost of one isolated slice. 7923 Cost(const LoadedSlice &LS, bool ForCodeSize = false) 7924 : ForCodeSize(ForCodeSize), Loads(1), Truncates(0), 7925 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) { 7926 EVT TruncType = LS.Inst->getValueType(0); 7927 EVT LoadedType = LS.getLoadedType(); 7928 if (TruncType != LoadedType && 7929 !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType)) 7930 ZExts = 1; 7931 } 7932 7933 /// \brief Account for slicing gain in the current cost. 7934 /// Slicing provide a few gains like removing a shift or a 7935 /// truncate. This method allows to grow the cost of the original 7936 /// load with the gain from this slice. 7937 void addSliceGain(const LoadedSlice &LS) { 7938 // Each slice saves a truncate. 7939 const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo(); 7940 if (!TLI.isTruncateFree(LS.Inst->getValueType(0), 7941 LS.Inst->getOperand(0).getValueType())) 7942 ++Truncates; 7943 // If there is a shift amount, this slice gets rid of it. 7944 if (LS.Shift) 7945 ++Shift; 7946 // If this slice can merge a cross register bank copy, account for it. 7947 if (LS.canMergeExpensiveCrossRegisterBankCopy()) 7948 ++CrossRegisterBanksCopies; 7949 } 7950 7951 Cost &operator+=(const Cost &RHS) { 7952 Loads += RHS.Loads; 7953 Truncates += RHS.Truncates; 7954 CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies; 7955 ZExts += RHS.ZExts; 7956 Shift += RHS.Shift; 7957 return *this; 7958 } 7959 7960 bool operator==(const Cost &RHS) const { 7961 return Loads == RHS.Loads && Truncates == RHS.Truncates && 7962 CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies && 7963 ZExts == RHS.ZExts && Shift == RHS.Shift; 7964 } 7965 7966 bool operator!=(const Cost &RHS) const { return !(*this == RHS); } 7967 7968 bool operator<(const Cost &RHS) const { 7969 // Assume cross register banks copies are as expensive as loads. 7970 // FIXME: Do we want some more target hooks? 7971 unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies; 7972 unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies; 7973 // Unless we are optimizing for code size, consider the 7974 // expensive operation first. 7975 if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS) 7976 return ExpensiveOpsLHS < ExpensiveOpsRHS; 7977 return (Truncates + ZExts + Shift + ExpensiveOpsLHS) < 7978 (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS); 7979 } 7980 7981 bool operator>(const Cost &RHS) const { return RHS < *this; } 7982 7983 bool operator<=(const Cost &RHS) const { return !(RHS < *this); } 7984 7985 bool operator>=(const Cost &RHS) const { return !(*this < RHS); } 7986 }; 7987 // The last instruction that represent the slice. This should be a 7988 // truncate instruction. 7989 SDNode *Inst; 7990 // The original load instruction. 7991 LoadSDNode *Origin; 7992 // The right shift amount in bits from the original load. 7993 unsigned Shift; 7994 // The DAG from which Origin came from. 7995 // This is used to get some contextual information about legal types, etc. 7996 SelectionDAG *DAG; 7997 7998 LoadedSlice(SDNode *Inst = NULL, LoadSDNode *Origin = NULL, 7999 unsigned Shift = 0, SelectionDAG *DAG = NULL) 8000 : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {} 8001 8002 LoadedSlice(const LoadedSlice &LS) 8003 : Inst(LS.Inst), Origin(LS.Origin), Shift(LS.Shift), DAG(LS.DAG) {} 8004 8005 /// \brief Get the bits used in a chunk of bits \p BitWidth large. 8006 /// \return Result is \p BitWidth and has used bits set to 1 and 8007 /// not used bits set to 0. 8008 APInt getUsedBits() const { 8009 // Reproduce the trunc(lshr) sequence: 8010 // - Start from the truncated value. 8011 // - Zero extend to the desired bit width. 8012 // - Shift left. 8013 assert(Origin && "No original load to compare against."); 8014 unsigned BitWidth = Origin->getValueSizeInBits(0); 8015 assert(Inst && "This slice is not bound to an instruction"); 8016 assert(Inst->getValueSizeInBits(0) <= BitWidth && 8017 "Extracted slice is bigger than the whole type!"); 8018 APInt UsedBits(Inst->getValueSizeInBits(0), 0); 8019 UsedBits.setAllBits(); 8020 UsedBits = UsedBits.zext(BitWidth); 8021 UsedBits <<= Shift; 8022 return UsedBits; 8023 } 8024 8025 /// \brief Get the size of the slice to be loaded in bytes. 8026 unsigned getLoadedSize() const { 8027 unsigned SliceSize = getUsedBits().countPopulation(); 8028 assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte."); 8029 return SliceSize / 8; 8030 } 8031 8032 /// \brief Get the type that will be loaded for this slice. 8033 /// Note: This may not be the final type for the slice. 8034 EVT getLoadedType() const { 8035 assert(DAG && "Missing context"); 8036 LLVMContext &Ctxt = *DAG->getContext(); 8037 return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8); 8038 } 8039 8040 /// \brief Get the alignment of the load used for this slice. 8041 unsigned getAlignment() const { 8042 unsigned Alignment = Origin->getAlignment(); 8043 unsigned Offset = getOffsetFromBase(); 8044 if (Offset != 0) 8045 Alignment = MinAlign(Alignment, Alignment + Offset); 8046 return Alignment; 8047 } 8048 8049 /// \brief Check if this slice can be rewritten with legal operations. 8050 bool isLegal() const { 8051 // An invalid slice is not legal. 8052 if (!Origin || !Inst || !DAG) 8053 return false; 8054 8055 // Offsets are for indexed load only, we do not handle that. 8056 if (Origin->getOffset().getOpcode() != ISD::UNDEF) 8057 return false; 8058 8059 const TargetLowering &TLI = DAG->getTargetLoweringInfo(); 8060 8061 // Check that the type is legal. 8062 EVT SliceType = getLoadedType(); 8063 if (!TLI.isTypeLegal(SliceType)) 8064 return false; 8065 8066 // Check that the load is legal for this type. 8067 if (!TLI.isOperationLegal(ISD::LOAD, SliceType)) 8068 return false; 8069 8070 // Check that the offset can be computed. 8071 // 1. Check its type. 8072 EVT PtrType = Origin->getBasePtr().getValueType(); 8073 if (PtrType == MVT::Untyped || PtrType.isExtended()) 8074 return false; 8075 8076 // 2. Check that it fits in the immediate. 8077 if (!TLI.isLegalAddImmediate(getOffsetFromBase())) 8078 return false; 8079 8080 // 3. Check that the computation is legal. 8081 if (!TLI.isOperationLegal(ISD::ADD, PtrType)) 8082 return false; 8083 8084 // Check that the zext is legal if it needs one. 8085 EVT TruncateType = Inst->getValueType(0); 8086 if (TruncateType != SliceType && 8087 !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType)) 8088 return false; 8089 8090 return true; 8091 } 8092 8093 /// \brief Get the offset in bytes of this slice in the original chunk of 8094 /// bits. 8095 /// \pre DAG != NULL. 8096 uint64_t getOffsetFromBase() const { 8097 assert(DAG && "Missing context."); 8098 bool IsBigEndian = 8099 DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian(); 8100 assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported."); 8101 uint64_t Offset = Shift / 8; 8102 unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8; 8103 assert(!(Origin->getValueSizeInBits(0) & 0x7) && 8104 "The size of the original loaded type is not a multiple of a" 8105 " byte."); 8106 // If Offset is bigger than TySizeInBytes, it means we are loading all 8107 // zeros. This should have been optimized before in the process. 8108 assert(TySizeInBytes > Offset && 8109 "Invalid shift amount for given loaded size"); 8110 if (IsBigEndian) 8111 Offset = TySizeInBytes - Offset - getLoadedSize(); 8112 return Offset; 8113 } 8114 8115 /// \brief Generate the sequence of instructions to load the slice 8116 /// represented by this object and redirect the uses of this slice to 8117 /// this new sequence of instructions. 8118 /// \pre this->Inst && this->Origin are valid Instructions and this 8119 /// object passed the legal check: LoadedSlice::isLegal returned true. 8120 /// \return The last instruction of the sequence used to load the slice. 8121 SDValue loadSlice() const { 8122 assert(Inst && Origin && "Unable to replace a non-existing slice."); 8123 const SDValue &OldBaseAddr = Origin->getBasePtr(); 8124 SDValue BaseAddr = OldBaseAddr; 8125 // Get the offset in that chunk of bytes w.r.t. the endianess. 8126 int64_t Offset = static_cast<int64_t>(getOffsetFromBase()); 8127 assert(Offset >= 0 && "Offset too big to fit in int64_t!"); 8128 if (Offset) { 8129 // BaseAddr = BaseAddr + Offset. 8130 EVT ArithType = BaseAddr.getValueType(); 8131 BaseAddr = DAG->getNode(ISD::ADD, SDLoc(Origin), ArithType, BaseAddr, 8132 DAG->getConstant(Offset, ArithType)); 8133 } 8134 8135 // Create the type of the loaded slice according to its size. 8136 EVT SliceType = getLoadedType(); 8137 8138 // Create the load for the slice. 8139 SDValue LastInst = DAG->getLoad( 8140 SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr, 8141 Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(), 8142 Origin->isNonTemporal(), Origin->isInvariant(), getAlignment()); 8143 // If the final type is not the same as the loaded type, this means that 8144 // we have to pad with zero. Create a zero extend for that. 8145 EVT FinalType = Inst->getValueType(0); 8146 if (SliceType != FinalType) 8147 LastInst = 8148 DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst); 8149 return LastInst; 8150 } 8151 8152 /// \brief Check if this slice can be merged with an expensive cross register 8153 /// bank copy. E.g., 8154 /// i = load i32 8155 /// f = bitcast i32 i to float 8156 bool canMergeExpensiveCrossRegisterBankCopy() const { 8157 if (!Inst || !Inst->hasOneUse()) 8158 return false; 8159 SDNode *Use = *Inst->use_begin(); 8160 if (Use->getOpcode() != ISD::BITCAST) 8161 return false; 8162 assert(DAG && "Missing context"); 8163 const TargetLowering &TLI = DAG->getTargetLoweringInfo(); 8164 EVT ResVT = Use->getValueType(0); 8165 const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT()); 8166 const TargetRegisterClass *ArgRC = 8167 TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT()); 8168 if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT)) 8169 return false; 8170 8171 // At this point, we know that we perform a cross-register-bank copy. 8172 // Check if it is expensive. 8173 const TargetRegisterInfo *TRI = TLI.getTargetMachine().getRegisterInfo(); 8174 // Assume bitcasts are cheap, unless both register classes do not 8175 // explicitly share a common sub class. 8176 if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC)) 8177 return false; 8178 8179 // Check if it will be merged with the load. 8180 // 1. Check the alignment constraint. 8181 unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment( 8182 ResVT.getTypeForEVT(*DAG->getContext())); 8183 8184 if (RequiredAlignment > getAlignment()) 8185 return false; 8186 8187 // 2. Check that the load is a legal operation for that type. 8188 if (!TLI.isOperationLegal(ISD::LOAD, ResVT)) 8189 return false; 8190 8191 // 3. Check that we do not have a zext in the way. 8192 if (Inst->getValueType(0) != getLoadedType()) 8193 return false; 8194 8195 return true; 8196 } 8197 }; 8198 } 8199 8200 /// \brief Sorts LoadedSlice according to their offset. 8201 struct LoadedSliceSorter { 8202 bool operator()(const LoadedSlice &LHS, const LoadedSlice &RHS) { 8203 assert(LHS.Origin == RHS.Origin && "Different bases not implemented."); 8204 return LHS.getOffsetFromBase() < RHS.getOffsetFromBase(); 8205 } 8206 }; 8207 8208 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e., 8209 /// \p UsedBits looks like 0..0 1..1 0..0. 8210 static bool areUsedBitsDense(const APInt &UsedBits) { 8211 // If all the bits are one, this is dense! 8212 if (UsedBits.isAllOnesValue()) 8213 return true; 8214 8215 // Get rid of the unused bits on the right. 8216 APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros()); 8217 // Get rid of the unused bits on the left. 8218 if (NarrowedUsedBits.countLeadingZeros()) 8219 NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits()); 8220 // Check that the chunk of bits is completely used. 8221 return NarrowedUsedBits.isAllOnesValue(); 8222 } 8223 8224 /// \brief Check whether or not \p First and \p Second are next to each other 8225 /// in memory. This means that there is no hole between the bits loaded 8226 /// by \p First and the bits loaded by \p Second. 8227 static bool areSlicesNextToEachOther(const LoadedSlice &First, 8228 const LoadedSlice &Second) { 8229 assert(First.Origin == Second.Origin && First.Origin && 8230 "Unable to match different memory origins."); 8231 APInt UsedBits = First.getUsedBits(); 8232 assert((UsedBits & Second.getUsedBits()) == 0 && 8233 "Slices are not supposed to overlap."); 8234 UsedBits |= Second.getUsedBits(); 8235 return areUsedBitsDense(UsedBits); 8236 } 8237 8238 /// \brief Adjust the \p GlobalLSCost according to the target 8239 /// paring capabilities and the layout of the slices. 8240 /// \pre \p GlobalLSCost should account for at least as many loads as 8241 /// there is in the slices in \p LoadedSlices. 8242 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices, 8243 LoadedSlice::Cost &GlobalLSCost) { 8244 unsigned NumberOfSlices = LoadedSlices.size(); 8245 // If there is less than 2 elements, no pairing is possible. 8246 if (NumberOfSlices < 2) 8247 return; 8248 8249 // Sort the slices so that elements that are likely to be next to each 8250 // other in memory are next to each other in the list. 8251 std::sort(LoadedSlices.begin(), LoadedSlices.end(), LoadedSliceSorter()); 8252 const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo(); 8253 // First (resp. Second) is the first (resp. Second) potentially candidate 8254 // to be placed in a paired load. 8255 const LoadedSlice *First = NULL; 8256 const LoadedSlice *Second = NULL; 8257 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice, 8258 // Set the beginning of the pair. 8259 First = Second) { 8260 8261 Second = &LoadedSlices[CurrSlice]; 8262 8263 // If First is NULL, it means we start a new pair. 8264 // Get to the next slice. 8265 if (!First) 8266 continue; 8267 8268 EVT LoadedType = First->getLoadedType(); 8269 8270 // If the types of the slices are different, we cannot pair them. 8271 if (LoadedType != Second->getLoadedType()) 8272 continue; 8273 8274 // Check if the target supplies paired loads for this type. 8275 unsigned RequiredAlignment = 0; 8276 if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) { 8277 // move to the next pair, this type is hopeless. 8278 Second = NULL; 8279 continue; 8280 } 8281 // Check if we meet the alignment requirement. 8282 if (RequiredAlignment > First->getAlignment()) 8283 continue; 8284 8285 // Check that both loads are next to each other in memory. 8286 if (!areSlicesNextToEachOther(*First, *Second)) 8287 continue; 8288 8289 assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!"); 8290 --GlobalLSCost.Loads; 8291 // Move to the next pair. 8292 Second = NULL; 8293 } 8294 } 8295 8296 /// \brief Check the profitability of all involved LoadedSlice. 8297 /// Currently, it is considered profitable if there is exactly two 8298 /// involved slices (1) which are (2) next to each other in memory, and 8299 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3). 8300 /// 8301 /// Note: The order of the elements in \p LoadedSlices may be modified, but not 8302 /// the elements themselves. 8303 /// 8304 /// FIXME: When the cost model will be mature enough, we can relax 8305 /// constraints (1) and (2). 8306 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices, 8307 const APInt &UsedBits, bool ForCodeSize) { 8308 unsigned NumberOfSlices = LoadedSlices.size(); 8309 if (StressLoadSlicing) 8310 return NumberOfSlices > 1; 8311 8312 // Check (1). 8313 if (NumberOfSlices != 2) 8314 return false; 8315 8316 // Check (2). 8317 if (!areUsedBitsDense(UsedBits)) 8318 return false; 8319 8320 // Check (3). 8321 LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize); 8322 // The original code has one big load. 8323 OrigCost.Loads = 1; 8324 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) { 8325 const LoadedSlice &LS = LoadedSlices[CurrSlice]; 8326 // Accumulate the cost of all the slices. 8327 LoadedSlice::Cost SliceCost(LS, ForCodeSize); 8328 GlobalSlicingCost += SliceCost; 8329 8330 // Account as cost in the original configuration the gain obtained 8331 // with the current slices. 8332 OrigCost.addSliceGain(LS); 8333 } 8334 8335 // If the target supports paired load, adjust the cost accordingly. 8336 adjustCostForPairing(LoadedSlices, GlobalSlicingCost); 8337 return OrigCost > GlobalSlicingCost; 8338 } 8339 8340 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr) 8341 /// operations, split it in the various pieces being extracted. 8342 /// 8343 /// This sort of thing is introduced by SROA. 8344 /// This slicing takes care not to insert overlapping loads. 8345 /// \pre LI is a simple load (i.e., not an atomic or volatile load). 8346 bool DAGCombiner::SliceUpLoad(SDNode *N) { 8347 if (Level < AfterLegalizeDAG) 8348 return false; 8349 8350 LoadSDNode *LD = cast<LoadSDNode>(N); 8351 if (LD->isVolatile() || !ISD::isNormalLoad(LD) || 8352 !LD->getValueType(0).isInteger()) 8353 return false; 8354 8355 // Keep track of already used bits to detect overlapping values. 8356 // In that case, we will just abort the transformation. 8357 APInt UsedBits(LD->getValueSizeInBits(0), 0); 8358 8359 SmallVector<LoadedSlice, 4> LoadedSlices; 8360 8361 // Check if this load is used as several smaller chunks of bits. 8362 // Basically, look for uses in trunc or trunc(lshr) and record a new chain 8363 // of computation for each trunc. 8364 for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end(); 8365 UI != UIEnd; ++UI) { 8366 // Skip the uses of the chain. 8367 if (UI.getUse().getResNo() != 0) 8368 continue; 8369 8370 SDNode *User = *UI; 8371 unsigned Shift = 0; 8372 8373 // Check if this is a trunc(lshr). 8374 if (User->getOpcode() == ISD::SRL && User->hasOneUse() && 8375 isa<ConstantSDNode>(User->getOperand(1))) { 8376 Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue(); 8377 User = *User->use_begin(); 8378 } 8379 8380 // At this point, User is a Truncate, iff we encountered, trunc or 8381 // trunc(lshr). 8382 if (User->getOpcode() != ISD::TRUNCATE) 8383 return false; 8384 8385 // The width of the type must be a power of 2 and greater than 8-bits. 8386 // Otherwise the load cannot be represented in LLVM IR. 8387 // Moreover, if we shifted with a non-8-bits multiple, the slice 8388 // will be across several bytes. We do not support that. 8389 unsigned Width = User->getValueSizeInBits(0); 8390 if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7)) 8391 return 0; 8392 8393 // Build the slice for this chain of computations. 8394 LoadedSlice LS(User, LD, Shift, &DAG); 8395 APInt CurrentUsedBits = LS.getUsedBits(); 8396 8397 // Check if this slice overlaps with another. 8398 if ((CurrentUsedBits & UsedBits) != 0) 8399 return false; 8400 // Update the bits used globally. 8401 UsedBits |= CurrentUsedBits; 8402 8403 // Check if the new slice would be legal. 8404 if (!LS.isLegal()) 8405 return false; 8406 8407 // Record the slice. 8408 LoadedSlices.push_back(LS); 8409 } 8410 8411 // Abort slicing if it does not seem to be profitable. 8412 if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize)) 8413 return false; 8414 8415 ++SlicedLoads; 8416 8417 // Rewrite each chain to use an independent load. 8418 // By construction, each chain can be represented by a unique load. 8419 8420 // Prepare the argument for the new token factor for all the slices. 8421 SmallVector<SDValue, 8> ArgChains; 8422 for (SmallVectorImpl<LoadedSlice>::const_iterator 8423 LSIt = LoadedSlices.begin(), 8424 LSItEnd = LoadedSlices.end(); 8425 LSIt != LSItEnd; ++LSIt) { 8426 SDValue SliceInst = LSIt->loadSlice(); 8427 CombineTo(LSIt->Inst, SliceInst, true); 8428 if (SliceInst.getNode()->getOpcode() != ISD::LOAD) 8429 SliceInst = SliceInst.getOperand(0); 8430 assert(SliceInst->getOpcode() == ISD::LOAD && 8431 "It takes more than a zext to get to the loaded slice!!"); 8432 ArgChains.push_back(SliceInst.getValue(1)); 8433 } 8434 8435 SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other, 8436 &ArgChains[0], ArgChains.size()); 8437 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain); 8438 return true; 8439 } 8440 8441 /// CheckForMaskedLoad - Check to see if V is (and load (ptr), imm), where the 8442 /// load is having specific bytes cleared out. If so, return the byte size 8443 /// being masked out and the shift amount. 8444 static std::pair<unsigned, unsigned> 8445 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) { 8446 std::pair<unsigned, unsigned> Result(0, 0); 8447 8448 // Check for the structure we're looking for. 8449 if (V->getOpcode() != ISD::AND || 8450 !isa<ConstantSDNode>(V->getOperand(1)) || 8451 !ISD::isNormalLoad(V->getOperand(0).getNode())) 8452 return Result; 8453 8454 // Check the chain and pointer. 8455 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0)); 8456 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer. 8457 8458 // The store should be chained directly to the load or be an operand of a 8459 // tokenfactor. 8460 if (LD == Chain.getNode()) 8461 ; // ok. 8462 else if (Chain->getOpcode() != ISD::TokenFactor) 8463 return Result; // Fail. 8464 else { 8465 bool isOk = false; 8466 for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i) 8467 if (Chain->getOperand(i).getNode() == LD) { 8468 isOk = true; 8469 break; 8470 } 8471 if (!isOk) return Result; 8472 } 8473 8474 // This only handles simple types. 8475 if (V.getValueType() != MVT::i16 && 8476 V.getValueType() != MVT::i32 && 8477 V.getValueType() != MVT::i64) 8478 return Result; 8479 8480 // Check the constant mask. Invert it so that the bits being masked out are 8481 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits 8482 // follow the sign bit for uniformity. 8483 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue(); 8484 unsigned NotMaskLZ = countLeadingZeros(NotMask); 8485 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte. 8486 unsigned NotMaskTZ = countTrailingZeros(NotMask); 8487 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte. 8488 if (NotMaskLZ == 64) return Result; // All zero mask. 8489 8490 // See if we have a continuous run of bits. If so, we have 0*1+0* 8491 if (CountTrailingOnes_64(NotMask >> NotMaskTZ)+NotMaskTZ+NotMaskLZ != 64) 8492 return Result; 8493 8494 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64. 8495 if (V.getValueType() != MVT::i64 && NotMaskLZ) 8496 NotMaskLZ -= 64-V.getValueSizeInBits(); 8497 8498 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8; 8499 switch (MaskedBytes) { 8500 case 1: 8501 case 2: 8502 case 4: break; 8503 default: return Result; // All one mask, or 5-byte mask. 8504 } 8505 8506 // Verify that the first bit starts at a multiple of mask so that the access 8507 // is aligned the same as the access width. 8508 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result; 8509 8510 Result.first = MaskedBytes; 8511 Result.second = NotMaskTZ/8; 8512 return Result; 8513 } 8514 8515 8516 /// ShrinkLoadReplaceStoreWithStore - Check to see if IVal is something that 8517 /// provides a value as specified by MaskInfo. If so, replace the specified 8518 /// store with a narrower store of truncated IVal. 8519 static SDNode * 8520 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo, 8521 SDValue IVal, StoreSDNode *St, 8522 DAGCombiner *DC) { 8523 unsigned NumBytes = MaskInfo.first; 8524 unsigned ByteShift = MaskInfo.second; 8525 SelectionDAG &DAG = DC->getDAG(); 8526 8527 // Check to see if IVal is all zeros in the part being masked in by the 'or' 8528 // that uses this. If not, this is not a replacement. 8529 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(), 8530 ByteShift*8, (ByteShift+NumBytes)*8); 8531 if (!DAG.MaskedValueIsZero(IVal, Mask)) return 0; 8532 8533 // Check that it is legal on the target to do this. It is legal if the new 8534 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type 8535 // legalization. 8536 MVT VT = MVT::getIntegerVT(NumBytes*8); 8537 if (!DC->isTypeLegal(VT)) 8538 return 0; 8539 8540 // Okay, we can do this! Replace the 'St' store with a store of IVal that is 8541 // shifted by ByteShift and truncated down to NumBytes. 8542 if (ByteShift) 8543 IVal = DAG.getNode(ISD::SRL, SDLoc(IVal), IVal.getValueType(), IVal, 8544 DAG.getConstant(ByteShift*8, 8545 DC->getShiftAmountTy(IVal.getValueType()))); 8546 8547 // Figure out the offset for the store and the alignment of the access. 8548 unsigned StOffset; 8549 unsigned NewAlign = St->getAlignment(); 8550 8551 if (DAG.getTargetLoweringInfo().isLittleEndian()) 8552 StOffset = ByteShift; 8553 else 8554 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes; 8555 8556 SDValue Ptr = St->getBasePtr(); 8557 if (StOffset) { 8558 Ptr = DAG.getNode(ISD::ADD, SDLoc(IVal), Ptr.getValueType(), 8559 Ptr, DAG.getConstant(StOffset, Ptr.getValueType())); 8560 NewAlign = MinAlign(NewAlign, StOffset); 8561 } 8562 8563 // Truncate down to the new size. 8564 IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal); 8565 8566 ++OpsNarrowed; 8567 return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr, 8568 St->getPointerInfo().getWithOffset(StOffset), 8569 false, false, NewAlign).getNode(); 8570 } 8571 8572 8573 /// ReduceLoadOpStoreWidth - Look for sequence of load / op / store where op is 8574 /// one of 'or', 'xor', and 'and' of immediates. If 'op' is only touching some 8575 /// of the loaded bits, try narrowing the load and store if it would end up 8576 /// being a win for performance or code size. 8577 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) { 8578 StoreSDNode *ST = cast<StoreSDNode>(N); 8579 if (ST->isVolatile()) 8580 return SDValue(); 8581 8582 SDValue Chain = ST->getChain(); 8583 SDValue Value = ST->getValue(); 8584 SDValue Ptr = ST->getBasePtr(); 8585 EVT VT = Value.getValueType(); 8586 8587 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse()) 8588 return SDValue(); 8589 8590 unsigned Opc = Value.getOpcode(); 8591 8592 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst 8593 // is a byte mask indicating a consecutive number of bytes, check to see if 8594 // Y is known to provide just those bytes. If so, we try to replace the 8595 // load + replace + store sequence with a single (narrower) store, which makes 8596 // the load dead. 8597 if (Opc == ISD::OR) { 8598 std::pair<unsigned, unsigned> MaskedLoad; 8599 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain); 8600 if (MaskedLoad.first) 8601 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad, 8602 Value.getOperand(1), ST,this)) 8603 return SDValue(NewST, 0); 8604 8605 // Or is commutative, so try swapping X and Y. 8606 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain); 8607 if (MaskedLoad.first) 8608 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad, 8609 Value.getOperand(0), ST,this)) 8610 return SDValue(NewST, 0); 8611 } 8612 8613 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) || 8614 Value.getOperand(1).getOpcode() != ISD::Constant) 8615 return SDValue(); 8616 8617 SDValue N0 = Value.getOperand(0); 8618 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() && 8619 Chain == SDValue(N0.getNode(), 1)) { 8620 LoadSDNode *LD = cast<LoadSDNode>(N0); 8621 if (LD->getBasePtr() != Ptr || 8622 LD->getPointerInfo().getAddrSpace() != 8623 ST->getPointerInfo().getAddrSpace()) 8624 return SDValue(); 8625 8626 // Find the type to narrow it the load / op / store to. 8627 SDValue N1 = Value.getOperand(1); 8628 unsigned BitWidth = N1.getValueSizeInBits(); 8629 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue(); 8630 if (Opc == ISD::AND) 8631 Imm ^= APInt::getAllOnesValue(BitWidth); 8632 if (Imm == 0 || Imm.isAllOnesValue()) 8633 return SDValue(); 8634 unsigned ShAmt = Imm.countTrailingZeros(); 8635 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1; 8636 unsigned NewBW = NextPowerOf2(MSB - ShAmt); 8637 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW); 8638 while (NewBW < BitWidth && 8639 !(TLI.isOperationLegalOrCustom(Opc, NewVT) && 8640 TLI.isNarrowingProfitable(VT, NewVT))) { 8641 NewBW = NextPowerOf2(NewBW); 8642 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW); 8643 } 8644 if (NewBW >= BitWidth) 8645 return SDValue(); 8646 8647 // If the lsb changed does not start at the type bitwidth boundary, 8648 // start at the previous one. 8649 if (ShAmt % NewBW) 8650 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW; 8651 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt, 8652 std::min(BitWidth, ShAmt + NewBW)); 8653 if ((Imm & Mask) == Imm) { 8654 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW); 8655 if (Opc == ISD::AND) 8656 NewImm ^= APInt::getAllOnesValue(NewBW); 8657 uint64_t PtrOff = ShAmt / 8; 8658 // For big endian targets, we need to adjust the offset to the pointer to 8659 // load the correct bytes. 8660 if (TLI.isBigEndian()) 8661 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff; 8662 8663 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff); 8664 Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext()); 8665 if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy)) 8666 return SDValue(); 8667 8668 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD), 8669 Ptr.getValueType(), Ptr, 8670 DAG.getConstant(PtrOff, Ptr.getValueType())); 8671 SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0), 8672 LD->getChain(), NewPtr, 8673 LD->getPointerInfo().getWithOffset(PtrOff), 8674 LD->isVolatile(), LD->isNonTemporal(), 8675 LD->isInvariant(), NewAlign, 8676 LD->getTBAAInfo()); 8677 SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD, 8678 DAG.getConstant(NewImm, NewVT)); 8679 SDValue NewST = DAG.getStore(Chain, SDLoc(N), 8680 NewVal, NewPtr, 8681 ST->getPointerInfo().getWithOffset(PtrOff), 8682 false, false, NewAlign); 8683 8684 AddToWorkList(NewPtr.getNode()); 8685 AddToWorkList(NewLD.getNode()); 8686 AddToWorkList(NewVal.getNode()); 8687 WorkListRemover DeadNodes(*this); 8688 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1)); 8689 ++OpsNarrowed; 8690 return NewST; 8691 } 8692 } 8693 8694 return SDValue(); 8695 } 8696 8697 /// TransformFPLoadStorePair - For a given floating point load / store pair, 8698 /// if the load value isn't used by any other operations, then consider 8699 /// transforming the pair to integer load / store operations if the target 8700 /// deems the transformation profitable. 8701 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) { 8702 StoreSDNode *ST = cast<StoreSDNode>(N); 8703 SDValue Chain = ST->getChain(); 8704 SDValue Value = ST->getValue(); 8705 if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) && 8706 Value.hasOneUse() && 8707 Chain == SDValue(Value.getNode(), 1)) { 8708 LoadSDNode *LD = cast<LoadSDNode>(Value); 8709 EVT VT = LD->getMemoryVT(); 8710 if (!VT.isFloatingPoint() || 8711 VT != ST->getMemoryVT() || 8712 LD->isNonTemporal() || 8713 ST->isNonTemporal() || 8714 LD->getPointerInfo().getAddrSpace() != 0 || 8715 ST->getPointerInfo().getAddrSpace() != 0) 8716 return SDValue(); 8717 8718 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits()); 8719 if (!TLI.isOperationLegal(ISD::LOAD, IntVT) || 8720 !TLI.isOperationLegal(ISD::STORE, IntVT) || 8721 !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) || 8722 !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT)) 8723 return SDValue(); 8724 8725 unsigned LDAlign = LD->getAlignment(); 8726 unsigned STAlign = ST->getAlignment(); 8727 Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext()); 8728 unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy); 8729 if (LDAlign < ABIAlign || STAlign < ABIAlign) 8730 return SDValue(); 8731 8732 SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value), 8733 LD->getChain(), LD->getBasePtr(), 8734 LD->getPointerInfo(), 8735 false, false, false, LDAlign); 8736 8737 SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N), 8738 NewLD, ST->getBasePtr(), 8739 ST->getPointerInfo(), 8740 false, false, STAlign); 8741 8742 AddToWorkList(NewLD.getNode()); 8743 AddToWorkList(NewST.getNode()); 8744 WorkListRemover DeadNodes(*this); 8745 DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1)); 8746 ++LdStFP2Int; 8747 return NewST; 8748 } 8749 8750 return SDValue(); 8751 } 8752 8753 /// Helper struct to parse and store a memory address as base + index + offset. 8754 /// We ignore sign extensions when it is safe to do so. 8755 /// The following two expressions are not equivalent. To differentiate we need 8756 /// to store whether there was a sign extension involved in the index 8757 /// computation. 8758 /// (load (i64 add (i64 copyfromreg %c) 8759 /// (i64 signextend (add (i8 load %index) 8760 /// (i8 1)))) 8761 /// vs 8762 /// 8763 /// (load (i64 add (i64 copyfromreg %c) 8764 /// (i64 signextend (i32 add (i32 signextend (i8 load %index)) 8765 /// (i32 1))))) 8766 struct BaseIndexOffset { 8767 SDValue Base; 8768 SDValue Index; 8769 int64_t Offset; 8770 bool IsIndexSignExt; 8771 8772 BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {} 8773 8774 BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset, 8775 bool IsIndexSignExt) : 8776 Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {} 8777 8778 bool equalBaseIndex(const BaseIndexOffset &Other) { 8779 return Other.Base == Base && Other.Index == Index && 8780 Other.IsIndexSignExt == IsIndexSignExt; 8781 } 8782 8783 /// Parses tree in Ptr for base, index, offset addresses. 8784 static BaseIndexOffset match(SDValue Ptr) { 8785 bool IsIndexSignExt = false; 8786 8787 // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD 8788 // instruction, then it could be just the BASE or everything else we don't 8789 // know how to handle. Just use Ptr as BASE and give up. 8790 if (Ptr->getOpcode() != ISD::ADD) 8791 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt); 8792 8793 // We know that we have at least an ADD instruction. Try to pattern match 8794 // the simple case of BASE + OFFSET. 8795 if (isa<ConstantSDNode>(Ptr->getOperand(1))) { 8796 int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue(); 8797 return BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset, 8798 IsIndexSignExt); 8799 } 8800 8801 // Inside a loop the current BASE pointer is calculated using an ADD and a 8802 // MUL instruction. In this case Ptr is the actual BASE pointer. 8803 // (i64 add (i64 %array_ptr) 8804 // (i64 mul (i64 %induction_var) 8805 // (i64 %element_size))) 8806 if (Ptr->getOperand(1)->getOpcode() == ISD::MUL) 8807 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt); 8808 8809 // Look at Base + Index + Offset cases. 8810 SDValue Base = Ptr->getOperand(0); 8811 SDValue IndexOffset = Ptr->getOperand(1); 8812 8813 // Skip signextends. 8814 if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) { 8815 IndexOffset = IndexOffset->getOperand(0); 8816 IsIndexSignExt = true; 8817 } 8818 8819 // Either the case of Base + Index (no offset) or something else. 8820 if (IndexOffset->getOpcode() != ISD::ADD) 8821 return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt); 8822 8823 // Now we have the case of Base + Index + offset. 8824 SDValue Index = IndexOffset->getOperand(0); 8825 SDValue Offset = IndexOffset->getOperand(1); 8826 8827 if (!isa<ConstantSDNode>(Offset)) 8828 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt); 8829 8830 // Ignore signextends. 8831 if (Index->getOpcode() == ISD::SIGN_EXTEND) { 8832 Index = Index->getOperand(0); 8833 IsIndexSignExt = true; 8834 } else IsIndexSignExt = false; 8835 8836 int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue(); 8837 return BaseIndexOffset(Base, Index, Off, IsIndexSignExt); 8838 } 8839 }; 8840 8841 /// Holds a pointer to an LSBaseSDNode as well as information on where it 8842 /// is located in a sequence of memory operations connected by a chain. 8843 struct MemOpLink { 8844 MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq): 8845 MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { } 8846 // Ptr to the mem node. 8847 LSBaseSDNode *MemNode; 8848 // Offset from the base ptr. 8849 int64_t OffsetFromBase; 8850 // What is the sequence number of this mem node. 8851 // Lowest mem operand in the DAG starts at zero. 8852 unsigned SequenceNum; 8853 }; 8854 8855 /// Sorts store nodes in a link according to their offset from a shared 8856 // base ptr. 8857 struct ConsecutiveMemoryChainSorter { 8858 bool operator()(MemOpLink LHS, MemOpLink RHS) { 8859 return 8860 LHS.OffsetFromBase < RHS.OffsetFromBase || 8861 (LHS.OffsetFromBase == RHS.OffsetFromBase && 8862 LHS.SequenceNum > RHS.SequenceNum); 8863 } 8864 }; 8865 8866 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) { 8867 EVT MemVT = St->getMemoryVT(); 8868 int64_t ElementSizeBytes = MemVT.getSizeInBits()/8; 8869 bool NoVectors = DAG.getMachineFunction().getFunction()->getAttributes(). 8870 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat); 8871 8872 // Don't merge vectors into wider inputs. 8873 if (MemVT.isVector() || !MemVT.isSimple()) 8874 return false; 8875 8876 // Perform an early exit check. Do not bother looking at stored values that 8877 // are not constants or loads. 8878 SDValue StoredVal = St->getValue(); 8879 bool IsLoadSrc = isa<LoadSDNode>(StoredVal); 8880 if (!isa<ConstantSDNode>(StoredVal) && !isa<ConstantFPSDNode>(StoredVal) && 8881 !IsLoadSrc) 8882 return false; 8883 8884 // Only look at ends of store sequences. 8885 SDValue Chain = SDValue(St, 1); 8886 if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE) 8887 return false; 8888 8889 // This holds the base pointer, index, and the offset in bytes from the base 8890 // pointer. 8891 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr()); 8892 8893 // We must have a base and an offset. 8894 if (!BasePtr.Base.getNode()) 8895 return false; 8896 8897 // Do not handle stores to undef base pointers. 8898 if (BasePtr.Base.getOpcode() == ISD::UNDEF) 8899 return false; 8900 8901 // Save the LoadSDNodes that we find in the chain. 8902 // We need to make sure that these nodes do not interfere with 8903 // any of the store nodes. 8904 SmallVector<LSBaseSDNode*, 8> AliasLoadNodes; 8905 8906 // Save the StoreSDNodes that we find in the chain. 8907 SmallVector<MemOpLink, 8> StoreNodes; 8908 8909 // Walk up the chain and look for nodes with offsets from the same 8910 // base pointer. Stop when reaching an instruction with a different kind 8911 // or instruction which has a different base pointer. 8912 unsigned Seq = 0; 8913 StoreSDNode *Index = St; 8914 while (Index) { 8915 // If the chain has more than one use, then we can't reorder the mem ops. 8916 if (Index != St && !SDValue(Index, 1)->hasOneUse()) 8917 break; 8918 8919 // Find the base pointer and offset for this memory node. 8920 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr()); 8921 8922 // Check that the base pointer is the same as the original one. 8923 if (!Ptr.equalBaseIndex(BasePtr)) 8924 break; 8925 8926 // Check that the alignment is the same. 8927 if (Index->getAlignment() != St->getAlignment()) 8928 break; 8929 8930 // The memory operands must not be volatile. 8931 if (Index->isVolatile() || Index->isIndexed()) 8932 break; 8933 8934 // No truncation. 8935 if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index)) 8936 if (St->isTruncatingStore()) 8937 break; 8938 8939 // The stored memory type must be the same. 8940 if (Index->getMemoryVT() != MemVT) 8941 break; 8942 8943 // We do not allow unaligned stores because we want to prevent overriding 8944 // stores. 8945 if (Index->getAlignment()*8 != MemVT.getSizeInBits()) 8946 break; 8947 8948 // We found a potential memory operand to merge. 8949 StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++)); 8950 8951 // Find the next memory operand in the chain. If the next operand in the 8952 // chain is a store then move up and continue the scan with the next 8953 // memory operand. If the next operand is a load save it and use alias 8954 // information to check if it interferes with anything. 8955 SDNode *NextInChain = Index->getChain().getNode(); 8956 while (1) { 8957 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) { 8958 // We found a store node. Use it for the next iteration. 8959 Index = STn; 8960 break; 8961 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) { 8962 if (Ldn->isVolatile()) { 8963 Index = NULL; 8964 break; 8965 } 8966 8967 // Save the load node for later. Continue the scan. 8968 AliasLoadNodes.push_back(Ldn); 8969 NextInChain = Ldn->getChain().getNode(); 8970 continue; 8971 } else { 8972 Index = NULL; 8973 break; 8974 } 8975 } 8976 } 8977 8978 // Check if there is anything to merge. 8979 if (StoreNodes.size() < 2) 8980 return false; 8981 8982 // Sort the memory operands according to their distance from the base pointer. 8983 std::sort(StoreNodes.begin(), StoreNodes.end(), 8984 ConsecutiveMemoryChainSorter()); 8985 8986 // Scan the memory operations on the chain and find the first non-consecutive 8987 // store memory address. 8988 unsigned LastConsecutiveStore = 0; 8989 int64_t StartAddress = StoreNodes[0].OffsetFromBase; 8990 for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) { 8991 8992 // Check that the addresses are consecutive starting from the second 8993 // element in the list of stores. 8994 if (i > 0) { 8995 int64_t CurrAddress = StoreNodes[i].OffsetFromBase; 8996 if (CurrAddress - StartAddress != (ElementSizeBytes * i)) 8997 break; 8998 } 8999 9000 bool Alias = false; 9001 // Check if this store interferes with any of the loads that we found. 9002 for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld) 9003 if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) { 9004 Alias = true; 9005 break; 9006 } 9007 // We found a load that alias with this store. Stop the sequence. 9008 if (Alias) 9009 break; 9010 9011 // Mark this node as useful. 9012 LastConsecutiveStore = i; 9013 } 9014 9015 // The node with the lowest store address. 9016 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode; 9017 9018 // Store the constants into memory as one consecutive store. 9019 if (!IsLoadSrc) { 9020 unsigned LastLegalType = 0; 9021 unsigned LastLegalVectorType = 0; 9022 bool NonZero = false; 9023 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) { 9024 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 9025 SDValue StoredVal = St->getValue(); 9026 9027 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) { 9028 NonZero |= !C->isNullValue(); 9029 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) { 9030 NonZero |= !C->getConstantFPValue()->isNullValue(); 9031 } else { 9032 // Non-constant. 9033 break; 9034 } 9035 9036 // Find a legal type for the constant store. 9037 unsigned StoreBW = (i+1) * ElementSizeBytes * 8; 9038 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW); 9039 if (TLI.isTypeLegal(StoreTy)) 9040 LastLegalType = i+1; 9041 // Or check whether a truncstore is legal. 9042 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) == 9043 TargetLowering::TypePromoteInteger) { 9044 EVT LegalizedStoredValueTy = 9045 TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType()); 9046 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy)) 9047 LastLegalType = i+1; 9048 } 9049 9050 // Find a legal type for the vector store. 9051 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1); 9052 if (TLI.isTypeLegal(Ty)) 9053 LastLegalVectorType = i + 1; 9054 } 9055 9056 // We only use vectors if the constant is known to be zero and the 9057 // function is not marked with the noimplicitfloat attribute. 9058 if (NonZero || NoVectors) 9059 LastLegalVectorType = 0; 9060 9061 // Check if we found a legal integer type to store. 9062 if (LastLegalType == 0 && LastLegalVectorType == 0) 9063 return false; 9064 9065 bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors; 9066 unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType; 9067 9068 // Make sure we have something to merge. 9069 if (NumElem < 2) 9070 return false; 9071 9072 unsigned EarliestNodeUsed = 0; 9073 for (unsigned i=0; i < NumElem; ++i) { 9074 // Find a chain for the new wide-store operand. Notice that some 9075 // of the store nodes that we found may not be selected for inclusion 9076 // in the wide store. The chain we use needs to be the chain of the 9077 // earliest store node which is *used* and replaced by the wide store. 9078 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum) 9079 EarliestNodeUsed = i; 9080 } 9081 9082 // The earliest Node in the DAG. 9083 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode; 9084 SDLoc DL(StoreNodes[0].MemNode); 9085 9086 SDValue StoredVal; 9087 if (UseVector) { 9088 // Find a legal type for the vector store. 9089 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem); 9090 assert(TLI.isTypeLegal(Ty) && "Illegal vector store"); 9091 StoredVal = DAG.getConstant(0, Ty); 9092 } else { 9093 unsigned StoreBW = NumElem * ElementSizeBytes * 8; 9094 APInt StoreInt(StoreBW, 0); 9095 9096 // Construct a single integer constant which is made of the smaller 9097 // constant inputs. 9098 bool IsLE = TLI.isLittleEndian(); 9099 for (unsigned i = 0; i < NumElem ; ++i) { 9100 unsigned Idx = IsLE ?(NumElem - 1 - i) : i; 9101 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[Idx].MemNode); 9102 SDValue Val = St->getValue(); 9103 StoreInt<<=ElementSizeBytes*8; 9104 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) { 9105 StoreInt|=C->getAPIntValue().zext(StoreBW); 9106 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) { 9107 StoreInt|= C->getValueAPF().bitcastToAPInt().zext(StoreBW); 9108 } else { 9109 assert(false && "Invalid constant element type"); 9110 } 9111 } 9112 9113 // Create the new Load and Store operations. 9114 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW); 9115 StoredVal = DAG.getConstant(StoreInt, StoreTy); 9116 } 9117 9118 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), DL, StoredVal, 9119 FirstInChain->getBasePtr(), 9120 FirstInChain->getPointerInfo(), 9121 false, false, 9122 FirstInChain->getAlignment()); 9123 9124 // Replace the first store with the new store 9125 CombineTo(EarliestOp, NewStore); 9126 // Erase all other stores. 9127 for (unsigned i = 0; i < NumElem ; ++i) { 9128 if (StoreNodes[i].MemNode == EarliestOp) 9129 continue; 9130 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 9131 // ReplaceAllUsesWith will replace all uses that existed when it was 9132 // called, but graph optimizations may cause new ones to appear. For 9133 // example, the case in pr14333 looks like 9134 // 9135 // St's chain -> St -> another store -> X 9136 // 9137 // And the only difference from St to the other store is the chain. 9138 // When we change it's chain to be St's chain they become identical, 9139 // get CSEed and the net result is that X is now a use of St. 9140 // Since we know that St is redundant, just iterate. 9141 while (!St->use_empty()) 9142 DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain()); 9143 removeFromWorkList(St); 9144 DAG.DeleteNode(St); 9145 } 9146 9147 return true; 9148 } 9149 9150 // Below we handle the case of multiple consecutive stores that 9151 // come from multiple consecutive loads. We merge them into a single 9152 // wide load and a single wide store. 9153 9154 // Look for load nodes which are used by the stored values. 9155 SmallVector<MemOpLink, 8> LoadNodes; 9156 9157 // Find acceptable loads. Loads need to have the same chain (token factor), 9158 // must not be zext, volatile, indexed, and they must be consecutive. 9159 BaseIndexOffset LdBasePtr; 9160 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) { 9161 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 9162 LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue()); 9163 if (!Ld) break; 9164 9165 // Loads must only have one use. 9166 if (!Ld->hasNUsesOfValue(1, 0)) 9167 break; 9168 9169 // Check that the alignment is the same as the stores. 9170 if (Ld->getAlignment() != St->getAlignment()) 9171 break; 9172 9173 // The memory operands must not be volatile. 9174 if (Ld->isVolatile() || Ld->isIndexed()) 9175 break; 9176 9177 // We do not accept ext loads. 9178 if (Ld->getExtensionType() != ISD::NON_EXTLOAD) 9179 break; 9180 9181 // The stored memory type must be the same. 9182 if (Ld->getMemoryVT() != MemVT) 9183 break; 9184 9185 BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr()); 9186 // If this is not the first ptr that we check. 9187 if (LdBasePtr.Base.getNode()) { 9188 // The base ptr must be the same. 9189 if (!LdPtr.equalBaseIndex(LdBasePtr)) 9190 break; 9191 } else { 9192 // Check that all other base pointers are the same as this one. 9193 LdBasePtr = LdPtr; 9194 } 9195 9196 // We found a potential memory operand to merge. 9197 LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0)); 9198 } 9199 9200 if (LoadNodes.size() < 2) 9201 return false; 9202 9203 // Scan the memory operations on the chain and find the first non-consecutive 9204 // load memory address. These variables hold the index in the store node 9205 // array. 9206 unsigned LastConsecutiveLoad = 0; 9207 // This variable refers to the size and not index in the array. 9208 unsigned LastLegalVectorType = 0; 9209 unsigned LastLegalIntegerType = 0; 9210 StartAddress = LoadNodes[0].OffsetFromBase; 9211 SDValue FirstChain = LoadNodes[0].MemNode->getChain(); 9212 for (unsigned i = 1; i < LoadNodes.size(); ++i) { 9213 // All loads much share the same chain. 9214 if (LoadNodes[i].MemNode->getChain() != FirstChain) 9215 break; 9216 9217 int64_t CurrAddress = LoadNodes[i].OffsetFromBase; 9218 if (CurrAddress - StartAddress != (ElementSizeBytes * i)) 9219 break; 9220 LastConsecutiveLoad = i; 9221 9222 // Find a legal type for the vector store. 9223 EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1); 9224 if (TLI.isTypeLegal(StoreTy)) 9225 LastLegalVectorType = i + 1; 9226 9227 // Find a legal type for the integer store. 9228 unsigned StoreBW = (i+1) * ElementSizeBytes * 8; 9229 StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW); 9230 if (TLI.isTypeLegal(StoreTy)) 9231 LastLegalIntegerType = i + 1; 9232 // Or check whether a truncstore and extload is legal. 9233 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) == 9234 TargetLowering::TypePromoteInteger) { 9235 EVT LegalizedStoredValueTy = 9236 TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy); 9237 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) && 9238 TLI.isLoadExtLegal(ISD::ZEXTLOAD, StoreTy) && 9239 TLI.isLoadExtLegal(ISD::SEXTLOAD, StoreTy) && 9240 TLI.isLoadExtLegal(ISD::EXTLOAD, StoreTy)) 9241 LastLegalIntegerType = i+1; 9242 } 9243 } 9244 9245 // Only use vector types if the vector type is larger than the integer type. 9246 // If they are the same, use integers. 9247 bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors; 9248 unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType); 9249 9250 // We add +1 here because the LastXXX variables refer to location while 9251 // the NumElem refers to array/index size. 9252 unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1; 9253 NumElem = std::min(LastLegalType, NumElem); 9254 9255 if (NumElem < 2) 9256 return false; 9257 9258 // The earliest Node in the DAG. 9259 unsigned EarliestNodeUsed = 0; 9260 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode; 9261 for (unsigned i=1; i<NumElem; ++i) { 9262 // Find a chain for the new wide-store operand. Notice that some 9263 // of the store nodes that we found may not be selected for inclusion 9264 // in the wide store. The chain we use needs to be the chain of the 9265 // earliest store node which is *used* and replaced by the wide store. 9266 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum) 9267 EarliestNodeUsed = i; 9268 } 9269 9270 // Find if it is better to use vectors or integers to load and store 9271 // to memory. 9272 EVT JointMemOpVT; 9273 if (UseVectorTy) { 9274 JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem); 9275 } else { 9276 unsigned StoreBW = NumElem * ElementSizeBytes * 8; 9277 JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW); 9278 } 9279 9280 SDLoc LoadDL(LoadNodes[0].MemNode); 9281 SDLoc StoreDL(StoreNodes[0].MemNode); 9282 9283 LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode); 9284 SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL, 9285 FirstLoad->getChain(), 9286 FirstLoad->getBasePtr(), 9287 FirstLoad->getPointerInfo(), 9288 false, false, false, 9289 FirstLoad->getAlignment()); 9290 9291 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), StoreDL, NewLoad, 9292 FirstInChain->getBasePtr(), 9293 FirstInChain->getPointerInfo(), false, false, 9294 FirstInChain->getAlignment()); 9295 9296 // Replace one of the loads with the new load. 9297 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode); 9298 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), 9299 SDValue(NewLoad.getNode(), 1)); 9300 9301 // Remove the rest of the load chains. 9302 for (unsigned i = 1; i < NumElem ; ++i) { 9303 // Replace all chain users of the old load nodes with the chain of the new 9304 // load node. 9305 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode); 9306 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain()); 9307 } 9308 9309 // Replace the first store with the new store. 9310 CombineTo(EarliestOp, NewStore); 9311 // Erase all other stores. 9312 for (unsigned i = 0; i < NumElem ; ++i) { 9313 // Remove all Store nodes. 9314 if (StoreNodes[i].MemNode == EarliestOp) 9315 continue; 9316 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 9317 DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain()); 9318 removeFromWorkList(St); 9319 DAG.DeleteNode(St); 9320 } 9321 9322 return true; 9323 } 9324 9325 SDValue DAGCombiner::visitSTORE(SDNode *N) { 9326 StoreSDNode *ST = cast<StoreSDNode>(N); 9327 SDValue Chain = ST->getChain(); 9328 SDValue Value = ST->getValue(); 9329 SDValue Ptr = ST->getBasePtr(); 9330 9331 // If this is a store of a bit convert, store the input value if the 9332 // resultant store does not need a higher alignment than the original. 9333 if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() && 9334 ST->isUnindexed()) { 9335 unsigned OrigAlign = ST->getAlignment(); 9336 EVT SVT = Value.getOperand(0).getValueType(); 9337 unsigned Align = TLI.getDataLayout()-> 9338 getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext())); 9339 if (Align <= OrigAlign && 9340 ((!LegalOperations && !ST->isVolatile()) || 9341 TLI.isOperationLegalOrCustom(ISD::STORE, SVT))) 9342 return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0), 9343 Ptr, ST->getPointerInfo(), ST->isVolatile(), 9344 ST->isNonTemporal(), OrigAlign, 9345 ST->getTBAAInfo()); 9346 } 9347 9348 // Turn 'store undef, Ptr' -> nothing. 9349 if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed()) 9350 return Chain; 9351 9352 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr' 9353 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) { 9354 // NOTE: If the original store is volatile, this transform must not increase 9355 // the number of stores. For example, on x86-32 an f64 can be stored in one 9356 // processor operation but an i64 (which is not legal) requires two. So the 9357 // transform should not be done in this case. 9358 if (Value.getOpcode() != ISD::TargetConstantFP) { 9359 SDValue Tmp; 9360 switch (CFP->getSimpleValueType(0).SimpleTy) { 9361 default: llvm_unreachable("Unknown FP type"); 9362 case MVT::f16: // We don't do this for these yet. 9363 case MVT::f80: 9364 case MVT::f128: 9365 case MVT::ppcf128: 9366 break; 9367 case MVT::f32: 9368 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) || 9369 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) { 9370 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF(). 9371 bitcastToAPInt().getZExtValue(), MVT::i32); 9372 return DAG.getStore(Chain, SDLoc(N), Tmp, 9373 Ptr, ST->getMemOperand()); 9374 } 9375 break; 9376 case MVT::f64: 9377 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations && 9378 !ST->isVolatile()) || 9379 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) { 9380 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt(). 9381 getZExtValue(), MVT::i64); 9382 return DAG.getStore(Chain, SDLoc(N), Tmp, 9383 Ptr, ST->getMemOperand()); 9384 } 9385 9386 if (!ST->isVolatile() && 9387 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) { 9388 // Many FP stores are not made apparent until after legalize, e.g. for 9389 // argument passing. Since this is so common, custom legalize the 9390 // 64-bit integer store into two 32-bit stores. 9391 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue(); 9392 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32); 9393 SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32); 9394 if (TLI.isBigEndian()) std::swap(Lo, Hi); 9395 9396 unsigned Alignment = ST->getAlignment(); 9397 bool isVolatile = ST->isVolatile(); 9398 bool isNonTemporal = ST->isNonTemporal(); 9399 const MDNode *TBAAInfo = ST->getTBAAInfo(); 9400 9401 SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo, 9402 Ptr, ST->getPointerInfo(), 9403 isVolatile, isNonTemporal, 9404 ST->getAlignment(), TBAAInfo); 9405 Ptr = DAG.getNode(ISD::ADD, SDLoc(N), Ptr.getValueType(), Ptr, 9406 DAG.getConstant(4, Ptr.getValueType())); 9407 Alignment = MinAlign(Alignment, 4U); 9408 SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi, 9409 Ptr, ST->getPointerInfo().getWithOffset(4), 9410 isVolatile, isNonTemporal, 9411 Alignment, TBAAInfo); 9412 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, 9413 St0, St1); 9414 } 9415 9416 break; 9417 } 9418 } 9419 } 9420 9421 // Try to infer better alignment information than the store already has. 9422 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) { 9423 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) { 9424 if (Align > ST->getAlignment()) 9425 return DAG.getTruncStore(Chain, SDLoc(N), Value, 9426 Ptr, ST->getPointerInfo(), ST->getMemoryVT(), 9427 ST->isVolatile(), ST->isNonTemporal(), Align, 9428 ST->getTBAAInfo()); 9429 } 9430 } 9431 9432 // Try transforming a pair floating point load / store ops to integer 9433 // load / store ops. 9434 SDValue NewST = TransformFPLoadStorePair(N); 9435 if (NewST.getNode()) 9436 return NewST; 9437 9438 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA : 9439 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA(); 9440 #ifndef NDEBUG 9441 if (CombinerAAOnlyFunc.getNumOccurrences() && 9442 CombinerAAOnlyFunc != DAG.getMachineFunction().getName()) 9443 UseAA = false; 9444 #endif 9445 if (UseAA && ST->isUnindexed()) { 9446 // Walk up chain skipping non-aliasing memory nodes. 9447 SDValue BetterChain = FindBetterChain(N, Chain); 9448 9449 // If there is a better chain. 9450 if (Chain != BetterChain) { 9451 SDValue ReplStore; 9452 9453 // Replace the chain to avoid dependency. 9454 if (ST->isTruncatingStore()) { 9455 ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr, 9456 ST->getMemoryVT(), ST->getMemOperand()); 9457 } else { 9458 ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr, 9459 ST->getMemOperand()); 9460 } 9461 9462 // Create token to keep both nodes around. 9463 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N), 9464 MVT::Other, Chain, ReplStore); 9465 9466 // Make sure the new and old chains are cleaned up. 9467 AddToWorkList(Token.getNode()); 9468 9469 // Don't add users to work list. 9470 return CombineTo(N, Token, false); 9471 } 9472 } 9473 9474 // Try transforming N to an indexed store. 9475 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N)) 9476 return SDValue(N, 0); 9477 9478 // FIXME: is there such a thing as a truncating indexed store? 9479 if (ST->isTruncatingStore() && ST->isUnindexed() && 9480 Value.getValueType().isInteger()) { 9481 // See if we can simplify the input to this truncstore with knowledge that 9482 // only the low bits are being used. For example: 9483 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8" 9484 SDValue Shorter = 9485 GetDemandedBits(Value, 9486 APInt::getLowBitsSet( 9487 Value.getValueType().getScalarType().getSizeInBits(), 9488 ST->getMemoryVT().getScalarType().getSizeInBits())); 9489 AddToWorkList(Value.getNode()); 9490 if (Shorter.getNode()) 9491 return DAG.getTruncStore(Chain, SDLoc(N), Shorter, 9492 Ptr, ST->getMemoryVT(), ST->getMemOperand()); 9493 9494 // Otherwise, see if we can simplify the operation with 9495 // SimplifyDemandedBits, which only works if the value has a single use. 9496 if (SimplifyDemandedBits(Value, 9497 APInt::getLowBitsSet( 9498 Value.getValueType().getScalarType().getSizeInBits(), 9499 ST->getMemoryVT().getScalarType().getSizeInBits()))) 9500 return SDValue(N, 0); 9501 } 9502 9503 // If this is a load followed by a store to the same location, then the store 9504 // is dead/noop. 9505 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) { 9506 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() && 9507 ST->isUnindexed() && !ST->isVolatile() && 9508 // There can't be any side effects between the load and store, such as 9509 // a call or store. 9510 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) { 9511 // The store is dead, remove it. 9512 return Chain; 9513 } 9514 } 9515 9516 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a 9517 // truncating store. We can do this even if this is already a truncstore. 9518 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE) 9519 && Value.getNode()->hasOneUse() && ST->isUnindexed() && 9520 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(), 9521 ST->getMemoryVT())) { 9522 return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0), 9523 Ptr, ST->getMemoryVT(), ST->getMemOperand()); 9524 } 9525 9526 // Only perform this optimization before the types are legal, because we 9527 // don't want to perform this optimization on every DAGCombine invocation. 9528 if (!LegalTypes) { 9529 bool EverChanged = false; 9530 9531 do { 9532 // There can be multiple store sequences on the same chain. 9533 // Keep trying to merge store sequences until we are unable to do so 9534 // or until we merge the last store on the chain. 9535 bool Changed = MergeConsecutiveStores(ST); 9536 EverChanged |= Changed; 9537 if (!Changed) break; 9538 } while (ST->getOpcode() != ISD::DELETED_NODE); 9539 9540 if (EverChanged) 9541 return SDValue(N, 0); 9542 } 9543 9544 return ReduceLoadOpStoreWidth(N); 9545 } 9546 9547 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) { 9548 SDValue InVec = N->getOperand(0); 9549 SDValue InVal = N->getOperand(1); 9550 SDValue EltNo = N->getOperand(2); 9551 SDLoc dl(N); 9552 9553 // If the inserted element is an UNDEF, just use the input vector. 9554 if (InVal.getOpcode() == ISD::UNDEF) 9555 return InVec; 9556 9557 EVT VT = InVec.getValueType(); 9558 9559 // If we can't generate a legal BUILD_VECTOR, exit 9560 if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT)) 9561 return SDValue(); 9562 9563 // Check that we know which element is being inserted 9564 if (!isa<ConstantSDNode>(EltNo)) 9565 return SDValue(); 9566 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue(); 9567 9568 // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially 9569 // be converted to a BUILD_VECTOR). Fill in the Ops vector with the 9570 // vector elements. 9571 SmallVector<SDValue, 8> Ops; 9572 // Do not combine these two vectors if the output vector will not replace 9573 // the input vector. 9574 if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) { 9575 Ops.append(InVec.getNode()->op_begin(), 9576 InVec.getNode()->op_end()); 9577 } else if (InVec.getOpcode() == ISD::UNDEF) { 9578 unsigned NElts = VT.getVectorNumElements(); 9579 Ops.append(NElts, DAG.getUNDEF(InVal.getValueType())); 9580 } else { 9581 return SDValue(); 9582 } 9583 9584 // Insert the element 9585 if (Elt < Ops.size()) { 9586 // All the operands of BUILD_VECTOR must have the same type; 9587 // we enforce that here. 9588 EVT OpVT = Ops[0].getValueType(); 9589 if (InVal.getValueType() != OpVT) 9590 InVal = OpVT.bitsGT(InVal.getValueType()) ? 9591 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) : 9592 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal); 9593 Ops[Elt] = InVal; 9594 } 9595 9596 // Return the new vector 9597 return DAG.getNode(ISD::BUILD_VECTOR, dl, 9598 VT, &Ops[0], Ops.size()); 9599 } 9600 9601 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) { 9602 // (vextract (scalar_to_vector val, 0) -> val 9603 SDValue InVec = N->getOperand(0); 9604 EVT VT = InVec.getValueType(); 9605 EVT NVT = N->getValueType(0); 9606 9607 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) { 9608 // Check if the result type doesn't match the inserted element type. A 9609 // SCALAR_TO_VECTOR may truncate the inserted element and the 9610 // EXTRACT_VECTOR_ELT may widen the extracted vector. 9611 SDValue InOp = InVec.getOperand(0); 9612 if (InOp.getValueType() != NVT) { 9613 assert(InOp.getValueType().isInteger() && NVT.isInteger()); 9614 return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT); 9615 } 9616 return InOp; 9617 } 9618 9619 SDValue EltNo = N->getOperand(1); 9620 bool ConstEltNo = isa<ConstantSDNode>(EltNo); 9621 9622 // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT. 9623 // We only perform this optimization before the op legalization phase because 9624 // we may introduce new vector instructions which are not backed by TD 9625 // patterns. For example on AVX, extracting elements from a wide vector 9626 // without using extract_subvector. 9627 if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE 9628 && ConstEltNo && !LegalOperations) { 9629 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue(); 9630 int NumElem = VT.getVectorNumElements(); 9631 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec); 9632 // Find the new index to extract from. 9633 int OrigElt = SVOp->getMaskElt(Elt); 9634 9635 // Extracting an undef index is undef. 9636 if (OrigElt == -1) 9637 return DAG.getUNDEF(NVT); 9638 9639 // Select the right vector half to extract from. 9640 if (OrigElt < NumElem) { 9641 InVec = InVec->getOperand(0); 9642 } else { 9643 InVec = InVec->getOperand(1); 9644 OrigElt -= NumElem; 9645 } 9646 9647 EVT IndexTy = TLI.getVectorIdxTy(); 9648 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT, 9649 InVec, DAG.getConstant(OrigElt, IndexTy)); 9650 } 9651 9652 // Perform only after legalization to ensure build_vector / vector_shuffle 9653 // optimizations have already been done. 9654 if (!LegalOperations) return SDValue(); 9655 9656 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size) 9657 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size) 9658 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr) 9659 9660 if (ConstEltNo) { 9661 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue(); 9662 bool NewLoad = false; 9663 bool BCNumEltsChanged = false; 9664 EVT ExtVT = VT.getVectorElementType(); 9665 EVT LVT = ExtVT; 9666 9667 // If the result of load has to be truncated, then it's not necessarily 9668 // profitable. 9669 if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT)) 9670 return SDValue(); 9671 9672 if (InVec.getOpcode() == ISD::BITCAST) { 9673 // Don't duplicate a load with other uses. 9674 if (!InVec.hasOneUse()) 9675 return SDValue(); 9676 9677 EVT BCVT = InVec.getOperand(0).getValueType(); 9678 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType())) 9679 return SDValue(); 9680 if (VT.getVectorNumElements() != BCVT.getVectorNumElements()) 9681 BCNumEltsChanged = true; 9682 InVec = InVec.getOperand(0); 9683 ExtVT = BCVT.getVectorElementType(); 9684 NewLoad = true; 9685 } 9686 9687 LoadSDNode *LN0 = NULL; 9688 const ShuffleVectorSDNode *SVN = NULL; 9689 if (ISD::isNormalLoad(InVec.getNode())) { 9690 LN0 = cast<LoadSDNode>(InVec); 9691 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR && 9692 InVec.getOperand(0).getValueType() == ExtVT && 9693 ISD::isNormalLoad(InVec.getOperand(0).getNode())) { 9694 // Don't duplicate a load with other uses. 9695 if (!InVec.hasOneUse()) 9696 return SDValue(); 9697 9698 LN0 = cast<LoadSDNode>(InVec.getOperand(0)); 9699 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) { 9700 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1) 9701 // => 9702 // (load $addr+1*size) 9703 9704 // Don't duplicate a load with other uses. 9705 if (!InVec.hasOneUse()) 9706 return SDValue(); 9707 9708 // If the bit convert changed the number of elements, it is unsafe 9709 // to examine the mask. 9710 if (BCNumEltsChanged) 9711 return SDValue(); 9712 9713 // Select the input vector, guarding against out of range extract vector. 9714 unsigned NumElems = VT.getVectorNumElements(); 9715 int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt); 9716 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1); 9717 9718 if (InVec.getOpcode() == ISD::BITCAST) { 9719 // Don't duplicate a load with other uses. 9720 if (!InVec.hasOneUse()) 9721 return SDValue(); 9722 9723 InVec = InVec.getOperand(0); 9724 } 9725 if (ISD::isNormalLoad(InVec.getNode())) { 9726 LN0 = cast<LoadSDNode>(InVec); 9727 Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems; 9728 } 9729 } 9730 9731 // Make sure we found a non-volatile load and the extractelement is 9732 // the only use. 9733 if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile()) 9734 return SDValue(); 9735 9736 // If Idx was -1 above, Elt is going to be -1, so just return undef. 9737 if (Elt == -1) 9738 return DAG.getUNDEF(LVT); 9739 9740 unsigned Align = LN0->getAlignment(); 9741 if (NewLoad) { 9742 // Check the resultant load doesn't need a higher alignment than the 9743 // original load. 9744 unsigned NewAlign = 9745 TLI.getDataLayout() 9746 ->getABITypeAlignment(LVT.getTypeForEVT(*DAG.getContext())); 9747 9748 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, LVT)) 9749 return SDValue(); 9750 9751 Align = NewAlign; 9752 } 9753 9754 SDValue NewPtr = LN0->getBasePtr(); 9755 unsigned PtrOff = 0; 9756 9757 if (Elt) { 9758 PtrOff = LVT.getSizeInBits() * Elt / 8; 9759 EVT PtrType = NewPtr.getValueType(); 9760 if (TLI.isBigEndian()) 9761 PtrOff = VT.getSizeInBits() / 8 - PtrOff; 9762 NewPtr = DAG.getNode(ISD::ADD, SDLoc(N), PtrType, NewPtr, 9763 DAG.getConstant(PtrOff, PtrType)); 9764 } 9765 9766 // The replacement we need to do here is a little tricky: we need to 9767 // replace an extractelement of a load with a load. 9768 // Use ReplaceAllUsesOfValuesWith to do the replacement. 9769 // Note that this replacement assumes that the extractvalue is the only 9770 // use of the load; that's okay because we don't want to perform this 9771 // transformation in other cases anyway. 9772 SDValue Load; 9773 SDValue Chain; 9774 if (NVT.bitsGT(LVT)) { 9775 // If the result type of vextract is wider than the load, then issue an 9776 // extending load instead. 9777 ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, LVT) 9778 ? ISD::ZEXTLOAD : ISD::EXTLOAD; 9779 Load = DAG.getExtLoad(ExtType, SDLoc(N), NVT, LN0->getChain(), 9780 NewPtr, LN0->getPointerInfo().getWithOffset(PtrOff), 9781 LVT, LN0->isVolatile(), LN0->isNonTemporal(), 9782 Align, LN0->getTBAAInfo()); 9783 Chain = Load.getValue(1); 9784 } else { 9785 Load = DAG.getLoad(LVT, SDLoc(N), LN0->getChain(), NewPtr, 9786 LN0->getPointerInfo().getWithOffset(PtrOff), 9787 LN0->isVolatile(), LN0->isNonTemporal(), 9788 LN0->isInvariant(), Align, LN0->getTBAAInfo()); 9789 Chain = Load.getValue(1); 9790 if (NVT.bitsLT(LVT)) 9791 Load = DAG.getNode(ISD::TRUNCATE, SDLoc(N), NVT, Load); 9792 else 9793 Load = DAG.getNode(ISD::BITCAST, SDLoc(N), NVT, Load); 9794 } 9795 WorkListRemover DeadNodes(*this); 9796 SDValue From[] = { SDValue(N, 0), SDValue(LN0,1) }; 9797 SDValue To[] = { Load, Chain }; 9798 DAG.ReplaceAllUsesOfValuesWith(From, To, 2); 9799 // Since we're explcitly calling ReplaceAllUses, add the new node to the 9800 // worklist explicitly as well. 9801 AddToWorkList(Load.getNode()); 9802 AddUsersToWorkList(Load.getNode()); // Add users too 9803 // Make sure to revisit this node to clean it up; it will usually be dead. 9804 AddToWorkList(N); 9805 return SDValue(N, 0); 9806 } 9807 9808 return SDValue(); 9809 } 9810 9811 // Simplify (build_vec (ext )) to (bitcast (build_vec )) 9812 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) { 9813 // We perform this optimization post type-legalization because 9814 // the type-legalizer often scalarizes integer-promoted vectors. 9815 // Performing this optimization before may create bit-casts which 9816 // will be type-legalized to complex code sequences. 9817 // We perform this optimization only before the operation legalizer because we 9818 // may introduce illegal operations. 9819 if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes) 9820 return SDValue(); 9821 9822 unsigned NumInScalars = N->getNumOperands(); 9823 SDLoc dl(N); 9824 EVT VT = N->getValueType(0); 9825 9826 // Check to see if this is a BUILD_VECTOR of a bunch of values 9827 // which come from any_extend or zero_extend nodes. If so, we can create 9828 // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR 9829 // optimizations. We do not handle sign-extend because we can't fill the sign 9830 // using shuffles. 9831 EVT SourceType = MVT::Other; 9832 bool AllAnyExt = true; 9833 9834 for (unsigned i = 0; i != NumInScalars; ++i) { 9835 SDValue In = N->getOperand(i); 9836 // Ignore undef inputs. 9837 if (In.getOpcode() == ISD::UNDEF) continue; 9838 9839 bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND; 9840 bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND; 9841 9842 // Abort if the element is not an extension. 9843 if (!ZeroExt && !AnyExt) { 9844 SourceType = MVT::Other; 9845 break; 9846 } 9847 9848 // The input is a ZeroExt or AnyExt. Check the original type. 9849 EVT InTy = In.getOperand(0).getValueType(); 9850 9851 // Check that all of the widened source types are the same. 9852 if (SourceType == MVT::Other) 9853 // First time. 9854 SourceType = InTy; 9855 else if (InTy != SourceType) { 9856 // Multiple income types. Abort. 9857 SourceType = MVT::Other; 9858 break; 9859 } 9860 9861 // Check if all of the extends are ANY_EXTENDs. 9862 AllAnyExt &= AnyExt; 9863 } 9864 9865 // In order to have valid types, all of the inputs must be extended from the 9866 // same source type and all of the inputs must be any or zero extend. 9867 // Scalar sizes must be a power of two. 9868 EVT OutScalarTy = VT.getScalarType(); 9869 bool ValidTypes = SourceType != MVT::Other && 9870 isPowerOf2_32(OutScalarTy.getSizeInBits()) && 9871 isPowerOf2_32(SourceType.getSizeInBits()); 9872 9873 // Create a new simpler BUILD_VECTOR sequence which other optimizations can 9874 // turn into a single shuffle instruction. 9875 if (!ValidTypes) 9876 return SDValue(); 9877 9878 bool isLE = TLI.isLittleEndian(); 9879 unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits(); 9880 assert(ElemRatio > 1 && "Invalid element size ratio"); 9881 SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType): 9882 DAG.getConstant(0, SourceType); 9883 9884 unsigned NewBVElems = ElemRatio * VT.getVectorNumElements(); 9885 SmallVector<SDValue, 8> Ops(NewBVElems, Filler); 9886 9887 // Populate the new build_vector 9888 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 9889 SDValue Cast = N->getOperand(i); 9890 assert((Cast.getOpcode() == ISD::ANY_EXTEND || 9891 Cast.getOpcode() == ISD::ZERO_EXTEND || 9892 Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode"); 9893 SDValue In; 9894 if (Cast.getOpcode() == ISD::UNDEF) 9895 In = DAG.getUNDEF(SourceType); 9896 else 9897 In = Cast->getOperand(0); 9898 unsigned Index = isLE ? (i * ElemRatio) : 9899 (i * ElemRatio + (ElemRatio - 1)); 9900 9901 assert(Index < Ops.size() && "Invalid index"); 9902 Ops[Index] = In; 9903 } 9904 9905 // The type of the new BUILD_VECTOR node. 9906 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems); 9907 assert(VecVT.getSizeInBits() == VT.getSizeInBits() && 9908 "Invalid vector size"); 9909 // Check if the new vector type is legal. 9910 if (!isTypeLegal(VecVT)) return SDValue(); 9911 9912 // Make the new BUILD_VECTOR. 9913 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, &Ops[0], Ops.size()); 9914 9915 // The new BUILD_VECTOR node has the potential to be further optimized. 9916 AddToWorkList(BV.getNode()); 9917 // Bitcast to the desired type. 9918 return DAG.getNode(ISD::BITCAST, dl, VT, BV); 9919 } 9920 9921 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) { 9922 EVT VT = N->getValueType(0); 9923 9924 unsigned NumInScalars = N->getNumOperands(); 9925 SDLoc dl(N); 9926 9927 EVT SrcVT = MVT::Other; 9928 unsigned Opcode = ISD::DELETED_NODE; 9929 unsigned NumDefs = 0; 9930 9931 for (unsigned i = 0; i != NumInScalars; ++i) { 9932 SDValue In = N->getOperand(i); 9933 unsigned Opc = In.getOpcode(); 9934 9935 if (Opc == ISD::UNDEF) 9936 continue; 9937 9938 // If all scalar values are floats and converted from integers. 9939 if (Opcode == ISD::DELETED_NODE && 9940 (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) { 9941 Opcode = Opc; 9942 } 9943 9944 if (Opc != Opcode) 9945 return SDValue(); 9946 9947 EVT InVT = In.getOperand(0).getValueType(); 9948 9949 // If all scalar values are typed differently, bail out. It's chosen to 9950 // simplify BUILD_VECTOR of integer types. 9951 if (SrcVT == MVT::Other) 9952 SrcVT = InVT; 9953 if (SrcVT != InVT) 9954 return SDValue(); 9955 NumDefs++; 9956 } 9957 9958 // If the vector has just one element defined, it's not worth to fold it into 9959 // a vectorized one. 9960 if (NumDefs < 2) 9961 return SDValue(); 9962 9963 assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP) 9964 && "Should only handle conversion from integer to float."); 9965 assert(SrcVT != MVT::Other && "Cannot determine source type!"); 9966 9967 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars); 9968 9969 if (!TLI.isOperationLegalOrCustom(Opcode, NVT)) 9970 return SDValue(); 9971 9972 SmallVector<SDValue, 8> Opnds; 9973 for (unsigned i = 0; i != NumInScalars; ++i) { 9974 SDValue In = N->getOperand(i); 9975 9976 if (In.getOpcode() == ISD::UNDEF) 9977 Opnds.push_back(DAG.getUNDEF(SrcVT)); 9978 else 9979 Opnds.push_back(In.getOperand(0)); 9980 } 9981 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, 9982 &Opnds[0], Opnds.size()); 9983 AddToWorkList(BV.getNode()); 9984 9985 return DAG.getNode(Opcode, dl, VT, BV); 9986 } 9987 9988 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) { 9989 unsigned NumInScalars = N->getNumOperands(); 9990 SDLoc dl(N); 9991 EVT VT = N->getValueType(0); 9992 9993 // A vector built entirely of undefs is undef. 9994 if (ISD::allOperandsUndef(N)) 9995 return DAG.getUNDEF(VT); 9996 9997 SDValue V = reduceBuildVecExtToExtBuildVec(N); 9998 if (V.getNode()) 9999 return V; 10000 10001 V = reduceBuildVecConvertToConvertBuildVec(N); 10002 if (V.getNode()) 10003 return V; 10004 10005 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT 10006 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from 10007 // at most two distinct vectors, turn this into a shuffle node. 10008 10009 // May only combine to shuffle after legalize if shuffle is legal. 10010 if (LegalOperations && 10011 !TLI.isOperationLegalOrCustom(ISD::VECTOR_SHUFFLE, VT)) 10012 return SDValue(); 10013 10014 SDValue VecIn1, VecIn2; 10015 for (unsigned i = 0; i != NumInScalars; ++i) { 10016 // Ignore undef inputs. 10017 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue; 10018 10019 // If this input is something other than a EXTRACT_VECTOR_ELT with a 10020 // constant index, bail out. 10021 if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT || 10022 !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) { 10023 VecIn1 = VecIn2 = SDValue(0, 0); 10024 break; 10025 } 10026 10027 // We allow up to two distinct input vectors. 10028 SDValue ExtractedFromVec = N->getOperand(i).getOperand(0); 10029 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2) 10030 continue; 10031 10032 if (VecIn1.getNode() == 0) { 10033 VecIn1 = ExtractedFromVec; 10034 } else if (VecIn2.getNode() == 0) { 10035 VecIn2 = ExtractedFromVec; 10036 } else { 10037 // Too many inputs. 10038 VecIn1 = VecIn2 = SDValue(0, 0); 10039 break; 10040 } 10041 } 10042 10043 // If everything is good, we can make a shuffle operation. 10044 if (VecIn1.getNode()) { 10045 SmallVector<int, 8> Mask; 10046 for (unsigned i = 0; i != NumInScalars; ++i) { 10047 if (N->getOperand(i).getOpcode() == ISD::UNDEF) { 10048 Mask.push_back(-1); 10049 continue; 10050 } 10051 10052 // If extracting from the first vector, just use the index directly. 10053 SDValue Extract = N->getOperand(i); 10054 SDValue ExtVal = Extract.getOperand(1); 10055 if (Extract.getOperand(0) == VecIn1) { 10056 unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue(); 10057 if (ExtIndex > VT.getVectorNumElements()) 10058 return SDValue(); 10059 10060 Mask.push_back(ExtIndex); 10061 continue; 10062 } 10063 10064 // Otherwise, use InIdx + VecSize 10065 unsigned Idx = cast<ConstantSDNode>(ExtVal)->getZExtValue(); 10066 Mask.push_back(Idx+NumInScalars); 10067 } 10068 10069 // We can't generate a shuffle node with mismatched input and output types. 10070 // Attempt to transform a single input vector to the correct type. 10071 if ((VT != VecIn1.getValueType())) { 10072 // We don't support shuffeling between TWO values of different types. 10073 if (VecIn2.getNode() != 0) 10074 return SDValue(); 10075 10076 // We only support widening of vectors which are half the size of the 10077 // output registers. For example XMM->YMM widening on X86 with AVX. 10078 if (VecIn1.getValueType().getSizeInBits()*2 != VT.getSizeInBits()) 10079 return SDValue(); 10080 10081 // If the input vector type has a different base type to the output 10082 // vector type, bail out. 10083 if (VecIn1.getValueType().getVectorElementType() != 10084 VT.getVectorElementType()) 10085 return SDValue(); 10086 10087 // Widen the input vector by adding undef values. 10088 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, 10089 VecIn1, DAG.getUNDEF(VecIn1.getValueType())); 10090 } 10091 10092 // If VecIn2 is unused then change it to undef. 10093 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT); 10094 10095 // Check that we were able to transform all incoming values to the same 10096 // type. 10097 if (VecIn2.getValueType() != VecIn1.getValueType() || 10098 VecIn1.getValueType() != VT) 10099 return SDValue(); 10100 10101 // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes. 10102 if (!isTypeLegal(VT)) 10103 return SDValue(); 10104 10105 // Return the new VECTOR_SHUFFLE node. 10106 SDValue Ops[2]; 10107 Ops[0] = VecIn1; 10108 Ops[1] = VecIn2; 10109 return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]); 10110 } 10111 10112 return SDValue(); 10113 } 10114 10115 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) { 10116 // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of 10117 // EXTRACT_SUBVECTOR operations. If so, and if the EXTRACT_SUBVECTOR vector 10118 // inputs come from at most two distinct vectors, turn this into a shuffle 10119 // node. 10120 10121 // If we only have one input vector, we don't need to do any concatenation. 10122 if (N->getNumOperands() == 1) 10123 return N->getOperand(0); 10124 10125 // Check if all of the operands are undefs. 10126 EVT VT = N->getValueType(0); 10127 if (ISD::allOperandsUndef(N)) 10128 return DAG.getUNDEF(VT); 10129 10130 // Optimize concat_vectors where one of the vectors is undef. 10131 if (N->getNumOperands() == 2 && 10132 N->getOperand(1)->getOpcode() == ISD::UNDEF) { 10133 SDValue In = N->getOperand(0); 10134 assert(In.getValueType().isVector() && "Must concat vectors"); 10135 10136 // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr). 10137 if (In->getOpcode() == ISD::BITCAST && 10138 !In->getOperand(0)->getValueType(0).isVector()) { 10139 SDValue Scalar = In->getOperand(0); 10140 EVT SclTy = Scalar->getValueType(0); 10141 10142 if (!SclTy.isFloatingPoint() && !SclTy.isInteger()) 10143 return SDValue(); 10144 10145 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy, 10146 VT.getSizeInBits() / SclTy.getSizeInBits()); 10147 if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType())) 10148 return SDValue(); 10149 10150 SDLoc dl = SDLoc(N); 10151 SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar); 10152 return DAG.getNode(ISD::BITCAST, dl, VT, Res); 10153 } 10154 } 10155 10156 // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...)) 10157 // -> (BUILD_VECTOR A, B, ..., C, D, ...) 10158 if (N->getNumOperands() == 2 && 10159 N->getOperand(0).getOpcode() == ISD::BUILD_VECTOR && 10160 N->getOperand(1).getOpcode() == ISD::BUILD_VECTOR) { 10161 EVT VT = N->getValueType(0); 10162 SDValue N0 = N->getOperand(0); 10163 SDValue N1 = N->getOperand(1); 10164 SmallVector<SDValue, 8> Opnds; 10165 unsigned BuildVecNumElts = N0.getNumOperands(); 10166 10167 for (unsigned i = 0; i != BuildVecNumElts; ++i) 10168 Opnds.push_back(N0.getOperand(i)); 10169 for (unsigned i = 0; i != BuildVecNumElts; ++i) 10170 Opnds.push_back(N1.getOperand(i)); 10171 10172 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, &Opnds[0], 10173 Opnds.size()); 10174 } 10175 10176 // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR 10177 // nodes often generate nop CONCAT_VECTOR nodes. 10178 // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that 10179 // place the incoming vectors at the exact same location. 10180 SDValue SingleSource = SDValue(); 10181 unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements(); 10182 10183 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 10184 SDValue Op = N->getOperand(i); 10185 10186 if (Op.getOpcode() == ISD::UNDEF) 10187 continue; 10188 10189 // Check if this is the identity extract: 10190 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR) 10191 return SDValue(); 10192 10193 // Find the single incoming vector for the extract_subvector. 10194 if (SingleSource.getNode()) { 10195 if (Op.getOperand(0) != SingleSource) 10196 return SDValue(); 10197 } else { 10198 SingleSource = Op.getOperand(0); 10199 10200 // Check the source type is the same as the type of the result. 10201 // If not, this concat may extend the vector, so we can not 10202 // optimize it away. 10203 if (SingleSource.getValueType() != N->getValueType(0)) 10204 return SDValue(); 10205 } 10206 10207 unsigned IdentityIndex = i * PartNumElem; 10208 ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 10209 // The extract index must be constant. 10210 if (!CS) 10211 return SDValue(); 10212 10213 // Check that we are reading from the identity index. 10214 if (CS->getZExtValue() != IdentityIndex) 10215 return SDValue(); 10216 } 10217 10218 if (SingleSource.getNode()) 10219 return SingleSource; 10220 10221 return SDValue(); 10222 } 10223 10224 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) { 10225 EVT NVT = N->getValueType(0); 10226 SDValue V = N->getOperand(0); 10227 10228 if (V->getOpcode() == ISD::CONCAT_VECTORS) { 10229 // Combine: 10230 // (extract_subvec (concat V1, V2, ...), i) 10231 // Into: 10232 // Vi if possible 10233 // Only operand 0 is checked as 'concat' assumes all inputs of the same 10234 // type. 10235 if (V->getOperand(0).getValueType() != NVT) 10236 return SDValue(); 10237 unsigned Idx = dyn_cast<ConstantSDNode>(N->getOperand(1))->getZExtValue(); 10238 unsigned NumElems = NVT.getVectorNumElements(); 10239 assert((Idx % NumElems) == 0 && 10240 "IDX in concat is not a multiple of the result vector length."); 10241 return V->getOperand(Idx / NumElems); 10242 } 10243 10244 // Skip bitcasting 10245 if (V->getOpcode() == ISD::BITCAST) 10246 V = V.getOperand(0); 10247 10248 if (V->getOpcode() == ISD::INSERT_SUBVECTOR) { 10249 SDLoc dl(N); 10250 // Handle only simple case where vector being inserted and vector 10251 // being extracted are of same type, and are half size of larger vectors. 10252 EVT BigVT = V->getOperand(0).getValueType(); 10253 EVT SmallVT = V->getOperand(1).getValueType(); 10254 if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits()) 10255 return SDValue(); 10256 10257 // Only handle cases where both indexes are constants with the same type. 10258 ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1)); 10259 ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2)); 10260 10261 if (InsIdx && ExtIdx && 10262 InsIdx->getValueType(0).getSizeInBits() <= 64 && 10263 ExtIdx->getValueType(0).getSizeInBits() <= 64) { 10264 // Combine: 10265 // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx) 10266 // Into: 10267 // indices are equal or bit offsets are equal => V1 10268 // otherwise => (extract_subvec V1, ExtIdx) 10269 if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() == 10270 ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits()) 10271 return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1)); 10272 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT, 10273 DAG.getNode(ISD::BITCAST, dl, 10274 N->getOperand(0).getValueType(), 10275 V->getOperand(0)), N->getOperand(1)); 10276 } 10277 } 10278 10279 return SDValue(); 10280 } 10281 10282 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat. 10283 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) { 10284 EVT VT = N->getValueType(0); 10285 unsigned NumElts = VT.getVectorNumElements(); 10286 10287 SDValue N0 = N->getOperand(0); 10288 SDValue N1 = N->getOperand(1); 10289 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N); 10290 10291 SmallVector<SDValue, 4> Ops; 10292 EVT ConcatVT = N0.getOperand(0).getValueType(); 10293 unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements(); 10294 unsigned NumConcats = NumElts / NumElemsPerConcat; 10295 10296 // Look at every vector that's inserted. We're looking for exact 10297 // subvector-sized copies from a concatenated vector 10298 for (unsigned I = 0; I != NumConcats; ++I) { 10299 // Make sure we're dealing with a copy. 10300 unsigned Begin = I * NumElemsPerConcat; 10301 bool AllUndef = true, NoUndef = true; 10302 for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) { 10303 if (SVN->getMaskElt(J) >= 0) 10304 AllUndef = false; 10305 else 10306 NoUndef = false; 10307 } 10308 10309 if (NoUndef) { 10310 if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0) 10311 return SDValue(); 10312 10313 for (unsigned J = 1; J != NumElemsPerConcat; ++J) 10314 if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J)) 10315 return SDValue(); 10316 10317 unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat; 10318 if (FirstElt < N0.getNumOperands()) 10319 Ops.push_back(N0.getOperand(FirstElt)); 10320 else 10321 Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands())); 10322 10323 } else if (AllUndef) { 10324 Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType())); 10325 } else { // Mixed with general masks and undefs, can't do optimization. 10326 return SDValue(); 10327 } 10328 } 10329 10330 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops.data(), 10331 Ops.size()); 10332 } 10333 10334 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) { 10335 EVT VT = N->getValueType(0); 10336 unsigned NumElts = VT.getVectorNumElements(); 10337 10338 SDValue N0 = N->getOperand(0); 10339 SDValue N1 = N->getOperand(1); 10340 10341 assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG"); 10342 10343 // Canonicalize shuffle undef, undef -> undef 10344 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF) 10345 return DAG.getUNDEF(VT); 10346 10347 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N); 10348 10349 // Canonicalize shuffle v, v -> v, undef 10350 if (N0 == N1) { 10351 SmallVector<int, 8> NewMask; 10352 for (unsigned i = 0; i != NumElts; ++i) { 10353 int Idx = SVN->getMaskElt(i); 10354 if (Idx >= (int)NumElts) Idx -= NumElts; 10355 NewMask.push_back(Idx); 10356 } 10357 return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT), 10358 &NewMask[0]); 10359 } 10360 10361 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask. 10362 if (N0.getOpcode() == ISD::UNDEF) { 10363 SmallVector<int, 8> NewMask; 10364 for (unsigned i = 0; i != NumElts; ++i) { 10365 int Idx = SVN->getMaskElt(i); 10366 if (Idx >= 0) { 10367 if (Idx >= (int)NumElts) 10368 Idx -= NumElts; 10369 else 10370 Idx = -1; // remove reference to lhs 10371 } 10372 NewMask.push_back(Idx); 10373 } 10374 return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT), 10375 &NewMask[0]); 10376 } 10377 10378 // Remove references to rhs if it is undef 10379 if (N1.getOpcode() == ISD::UNDEF) { 10380 bool Changed = false; 10381 SmallVector<int, 8> NewMask; 10382 for (unsigned i = 0; i != NumElts; ++i) { 10383 int Idx = SVN->getMaskElt(i); 10384 if (Idx >= (int)NumElts) { 10385 Idx = -1; 10386 Changed = true; 10387 } 10388 NewMask.push_back(Idx); 10389 } 10390 if (Changed) 10391 return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]); 10392 } 10393 10394 // If it is a splat, check if the argument vector is another splat or a 10395 // build_vector with all scalar elements the same. 10396 if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) { 10397 SDNode *V = N0.getNode(); 10398 10399 // If this is a bit convert that changes the element type of the vector but 10400 // not the number of vector elements, look through it. Be careful not to 10401 // look though conversions that change things like v4f32 to v2f64. 10402 if (V->getOpcode() == ISD::BITCAST) { 10403 SDValue ConvInput = V->getOperand(0); 10404 if (ConvInput.getValueType().isVector() && 10405 ConvInput.getValueType().getVectorNumElements() == NumElts) 10406 V = ConvInput.getNode(); 10407 } 10408 10409 if (V->getOpcode() == ISD::BUILD_VECTOR) { 10410 assert(V->getNumOperands() == NumElts && 10411 "BUILD_VECTOR has wrong number of operands"); 10412 SDValue Base; 10413 bool AllSame = true; 10414 for (unsigned i = 0; i != NumElts; ++i) { 10415 if (V->getOperand(i).getOpcode() != ISD::UNDEF) { 10416 Base = V->getOperand(i); 10417 break; 10418 } 10419 } 10420 // Splat of <u, u, u, u>, return <u, u, u, u> 10421 if (!Base.getNode()) 10422 return N0; 10423 for (unsigned i = 0; i != NumElts; ++i) { 10424 if (V->getOperand(i) != Base) { 10425 AllSame = false; 10426 break; 10427 } 10428 } 10429 // Splat of <x, x, x, x>, return <x, x, x, x> 10430 if (AllSame) 10431 return N0; 10432 } 10433 } 10434 10435 if (N0.getOpcode() == ISD::CONCAT_VECTORS && 10436 Level < AfterLegalizeVectorOps && 10437 (N1.getOpcode() == ISD::UNDEF || 10438 (N1.getOpcode() == ISD::CONCAT_VECTORS && 10439 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) { 10440 SDValue V = partitionShuffleOfConcats(N, DAG); 10441 10442 if (V.getNode()) 10443 return V; 10444 } 10445 10446 // If this shuffle node is simply a swizzle of another shuffle node, 10447 // and it reverses the swizzle of the previous shuffle then we can 10448 // optimize shuffle(shuffle(x, undef), undef) -> x. 10449 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG && 10450 N1.getOpcode() == ISD::UNDEF) { 10451 10452 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0); 10453 10454 // Shuffle nodes can only reverse shuffles with a single non-undef value. 10455 if (N0.getOperand(1).getOpcode() != ISD::UNDEF) 10456 return SDValue(); 10457 10458 // The incoming shuffle must be of the same type as the result of the 10459 // current shuffle. 10460 assert(OtherSV->getOperand(0).getValueType() == VT && 10461 "Shuffle types don't match"); 10462 10463 for (unsigned i = 0; i != NumElts; ++i) { 10464 int Idx = SVN->getMaskElt(i); 10465 assert(Idx < (int)NumElts && "Index references undef operand"); 10466 // Next, this index comes from the first value, which is the incoming 10467 // shuffle. Adopt the incoming index. 10468 if (Idx >= 0) 10469 Idx = OtherSV->getMaskElt(Idx); 10470 10471 // The combined shuffle must map each index to itself. 10472 if (Idx >= 0 && (unsigned)Idx != i) 10473 return SDValue(); 10474 } 10475 10476 return OtherSV->getOperand(0); 10477 } 10478 10479 return SDValue(); 10480 } 10481 10482 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) { 10483 SDValue N0 = N->getOperand(0); 10484 SDValue N2 = N->getOperand(2); 10485 10486 // If the input vector is a concatenation, and the insert replaces 10487 // one of the halves, we can optimize into a single concat_vectors. 10488 if (N0.getOpcode() == ISD::CONCAT_VECTORS && 10489 N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) { 10490 APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue(); 10491 EVT VT = N->getValueType(0); 10492 10493 // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) -> 10494 // (concat_vectors Z, Y) 10495 if (InsIdx == 0) 10496 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, 10497 N->getOperand(1), N0.getOperand(1)); 10498 10499 // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) -> 10500 // (concat_vectors X, Z) 10501 if (InsIdx == VT.getVectorNumElements()/2) 10502 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, 10503 N0.getOperand(0), N->getOperand(1)); 10504 } 10505 10506 return SDValue(); 10507 } 10508 10509 /// XformToShuffleWithZero - Returns a vector_shuffle if it able to transform 10510 /// an AND to a vector_shuffle with the destination vector and a zero vector. 10511 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==> 10512 /// vector_shuffle V, Zero, <0, 4, 2, 4> 10513 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) { 10514 EVT VT = N->getValueType(0); 10515 SDLoc dl(N); 10516 SDValue LHS = N->getOperand(0); 10517 SDValue RHS = N->getOperand(1); 10518 if (N->getOpcode() == ISD::AND) { 10519 if (RHS.getOpcode() == ISD::BITCAST) 10520 RHS = RHS.getOperand(0); 10521 if (RHS.getOpcode() == ISD::BUILD_VECTOR) { 10522 SmallVector<int, 8> Indices; 10523 unsigned NumElts = RHS.getNumOperands(); 10524 for (unsigned i = 0; i != NumElts; ++i) { 10525 SDValue Elt = RHS.getOperand(i); 10526 if (!isa<ConstantSDNode>(Elt)) 10527 return SDValue(); 10528 10529 if (cast<ConstantSDNode>(Elt)->isAllOnesValue()) 10530 Indices.push_back(i); 10531 else if (cast<ConstantSDNode>(Elt)->isNullValue()) 10532 Indices.push_back(NumElts); 10533 else 10534 return SDValue(); 10535 } 10536 10537 // Let's see if the target supports this vector_shuffle. 10538 EVT RVT = RHS.getValueType(); 10539 if (!TLI.isVectorClearMaskLegal(Indices, RVT)) 10540 return SDValue(); 10541 10542 // Return the new VECTOR_SHUFFLE node. 10543 EVT EltVT = RVT.getVectorElementType(); 10544 SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(), 10545 DAG.getConstant(0, EltVT)); 10546 SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), 10547 RVT, &ZeroOps[0], ZeroOps.size()); 10548 LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS); 10549 SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]); 10550 return DAG.getNode(ISD::BITCAST, dl, VT, Shuf); 10551 } 10552 } 10553 10554 return SDValue(); 10555 } 10556 10557 /// SimplifyVBinOp - Visit a binary vector operation, like ADD. 10558 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) { 10559 assert(N->getValueType(0).isVector() && 10560 "SimplifyVBinOp only works on vectors!"); 10561 10562 SDValue LHS = N->getOperand(0); 10563 SDValue RHS = N->getOperand(1); 10564 SDValue Shuffle = XformToShuffleWithZero(N); 10565 if (Shuffle.getNode()) return Shuffle; 10566 10567 // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold 10568 // this operation. 10569 if (LHS.getOpcode() == ISD::BUILD_VECTOR && 10570 RHS.getOpcode() == ISD::BUILD_VECTOR) { 10571 // Check if both vectors are constants. If not bail out. 10572 if (!(cast<BuildVectorSDNode>(LHS)->isConstant() && 10573 cast<BuildVectorSDNode>(RHS)->isConstant())) 10574 return SDValue(); 10575 10576 SmallVector<SDValue, 8> Ops; 10577 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) { 10578 SDValue LHSOp = LHS.getOperand(i); 10579 SDValue RHSOp = RHS.getOperand(i); 10580 10581 // Can't fold divide by zero. 10582 if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV || 10583 N->getOpcode() == ISD::FDIV) { 10584 if ((RHSOp.getOpcode() == ISD::Constant && 10585 cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) || 10586 (RHSOp.getOpcode() == ISD::ConstantFP && 10587 cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero())) 10588 break; 10589 } 10590 10591 EVT VT = LHSOp.getValueType(); 10592 EVT RVT = RHSOp.getValueType(); 10593 if (RVT != VT) { 10594 // Integer BUILD_VECTOR operands may have types larger than the element 10595 // size (e.g., when the element type is not legal). Prior to type 10596 // legalization, the types may not match between the two BUILD_VECTORS. 10597 // Truncate one of the operands to make them match. 10598 if (RVT.getSizeInBits() > VT.getSizeInBits()) { 10599 RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp); 10600 } else { 10601 LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp); 10602 VT = RVT; 10603 } 10604 } 10605 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT, 10606 LHSOp, RHSOp); 10607 if (FoldOp.getOpcode() != ISD::UNDEF && 10608 FoldOp.getOpcode() != ISD::Constant && 10609 FoldOp.getOpcode() != ISD::ConstantFP) 10610 break; 10611 Ops.push_back(FoldOp); 10612 AddToWorkList(FoldOp.getNode()); 10613 } 10614 10615 if (Ops.size() == LHS.getNumOperands()) 10616 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), 10617 LHS.getValueType(), &Ops[0], Ops.size()); 10618 } 10619 10620 return SDValue(); 10621 } 10622 10623 /// SimplifyVUnaryOp - Visit a binary vector operation, like FABS/FNEG. 10624 SDValue DAGCombiner::SimplifyVUnaryOp(SDNode *N) { 10625 assert(N->getValueType(0).isVector() && 10626 "SimplifyVUnaryOp only works on vectors!"); 10627 10628 SDValue N0 = N->getOperand(0); 10629 10630 if (N0.getOpcode() != ISD::BUILD_VECTOR) 10631 return SDValue(); 10632 10633 // Operand is a BUILD_VECTOR node, see if we can constant fold it. 10634 SmallVector<SDValue, 8> Ops; 10635 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) { 10636 SDValue Op = N0.getOperand(i); 10637 if (Op.getOpcode() != ISD::UNDEF && 10638 Op.getOpcode() != ISD::ConstantFP) 10639 break; 10640 EVT EltVT = Op.getValueType(); 10641 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(N0), EltVT, Op); 10642 if (FoldOp.getOpcode() != ISD::UNDEF && 10643 FoldOp.getOpcode() != ISD::ConstantFP) 10644 break; 10645 Ops.push_back(FoldOp); 10646 AddToWorkList(FoldOp.getNode()); 10647 } 10648 10649 if (Ops.size() != N0.getNumOperands()) 10650 return SDValue(); 10651 10652 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), 10653 N0.getValueType(), &Ops[0], Ops.size()); 10654 } 10655 10656 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0, 10657 SDValue N1, SDValue N2){ 10658 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!"); 10659 10660 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2, 10661 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 10662 10663 // If we got a simplified select_cc node back from SimplifySelectCC, then 10664 // break it down into a new SETCC node, and a new SELECT node, and then return 10665 // the SELECT node, since we were called with a SELECT node. 10666 if (SCC.getNode()) { 10667 // Check to see if we got a select_cc back (to turn into setcc/select). 10668 // Otherwise, just return whatever node we got back, like fabs. 10669 if (SCC.getOpcode() == ISD::SELECT_CC) { 10670 SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0), 10671 N0.getValueType(), 10672 SCC.getOperand(0), SCC.getOperand(1), 10673 SCC.getOperand(4)); 10674 AddToWorkList(SETCC.getNode()); 10675 return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), 10676 SCC.getOperand(2), SCC.getOperand(3), SETCC); 10677 } 10678 10679 return SCC; 10680 } 10681 return SDValue(); 10682 } 10683 10684 /// SimplifySelectOps - Given a SELECT or a SELECT_CC node, where LHS and RHS 10685 /// are the two values being selected between, see if we can simplify the 10686 /// select. Callers of this should assume that TheSelect is deleted if this 10687 /// returns true. As such, they should return the appropriate thing (e.g. the 10688 /// node) back to the top-level of the DAG combiner loop to avoid it being 10689 /// looked at. 10690 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS, 10691 SDValue RHS) { 10692 10693 // Cannot simplify select with vector condition 10694 if (TheSelect->getOperand(0).getValueType().isVector()) return false; 10695 10696 // If this is a select from two identical things, try to pull the operation 10697 // through the select. 10698 if (LHS.getOpcode() != RHS.getOpcode() || 10699 !LHS.hasOneUse() || !RHS.hasOneUse()) 10700 return false; 10701 10702 // If this is a load and the token chain is identical, replace the select 10703 // of two loads with a load through a select of the address to load from. 10704 // This triggers in things like "select bool X, 10.0, 123.0" after the FP 10705 // constants have been dropped into the constant pool. 10706 if (LHS.getOpcode() == ISD::LOAD) { 10707 LoadSDNode *LLD = cast<LoadSDNode>(LHS); 10708 LoadSDNode *RLD = cast<LoadSDNode>(RHS); 10709 10710 // Token chains must be identical. 10711 if (LHS.getOperand(0) != RHS.getOperand(0) || 10712 // Do not let this transformation reduce the number of volatile loads. 10713 LLD->isVolatile() || RLD->isVolatile() || 10714 // If this is an EXTLOAD, the VT's must match. 10715 LLD->getMemoryVT() != RLD->getMemoryVT() || 10716 // If this is an EXTLOAD, the kind of extension must match. 10717 (LLD->getExtensionType() != RLD->getExtensionType() && 10718 // The only exception is if one of the extensions is anyext. 10719 LLD->getExtensionType() != ISD::EXTLOAD && 10720 RLD->getExtensionType() != ISD::EXTLOAD) || 10721 // FIXME: this discards src value information. This is 10722 // over-conservative. It would be beneficial to be able to remember 10723 // both potential memory locations. Since we are discarding 10724 // src value info, don't do the transformation if the memory 10725 // locations are not in the default address space. 10726 LLD->getPointerInfo().getAddrSpace() != 0 || 10727 RLD->getPointerInfo().getAddrSpace() != 0 || 10728 !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(), 10729 LLD->getBasePtr().getValueType())) 10730 return false; 10731 10732 // Check that the select condition doesn't reach either load. If so, 10733 // folding this will induce a cycle into the DAG. If not, this is safe to 10734 // xform, so create a select of the addresses. 10735 SDValue Addr; 10736 if (TheSelect->getOpcode() == ISD::SELECT) { 10737 SDNode *CondNode = TheSelect->getOperand(0).getNode(); 10738 if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) || 10739 (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode))) 10740 return false; 10741 // The loads must not depend on one another. 10742 if (LLD->isPredecessorOf(RLD) || 10743 RLD->isPredecessorOf(LLD)) 10744 return false; 10745 Addr = DAG.getSelect(SDLoc(TheSelect), 10746 LLD->getBasePtr().getValueType(), 10747 TheSelect->getOperand(0), LLD->getBasePtr(), 10748 RLD->getBasePtr()); 10749 } else { // Otherwise SELECT_CC 10750 SDNode *CondLHS = TheSelect->getOperand(0).getNode(); 10751 SDNode *CondRHS = TheSelect->getOperand(1).getNode(); 10752 10753 if ((LLD->hasAnyUseOfValue(1) && 10754 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) || 10755 (RLD->hasAnyUseOfValue(1) && 10756 (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS)))) 10757 return false; 10758 10759 Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect), 10760 LLD->getBasePtr().getValueType(), 10761 TheSelect->getOperand(0), 10762 TheSelect->getOperand(1), 10763 LLD->getBasePtr(), RLD->getBasePtr(), 10764 TheSelect->getOperand(4)); 10765 } 10766 10767 SDValue Load; 10768 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) { 10769 Load = DAG.getLoad(TheSelect->getValueType(0), 10770 SDLoc(TheSelect), 10771 // FIXME: Discards pointer and TBAA info. 10772 LLD->getChain(), Addr, MachinePointerInfo(), 10773 LLD->isVolatile(), LLD->isNonTemporal(), 10774 LLD->isInvariant(), LLD->getAlignment()); 10775 } else { 10776 Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ? 10777 RLD->getExtensionType() : LLD->getExtensionType(), 10778 SDLoc(TheSelect), 10779 TheSelect->getValueType(0), 10780 // FIXME: Discards pointer and TBAA info. 10781 LLD->getChain(), Addr, MachinePointerInfo(), 10782 LLD->getMemoryVT(), LLD->isVolatile(), 10783 LLD->isNonTemporal(), LLD->getAlignment()); 10784 } 10785 10786 // Users of the select now use the result of the load. 10787 CombineTo(TheSelect, Load); 10788 10789 // Users of the old loads now use the new load's chain. We know the 10790 // old-load value is dead now. 10791 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1)); 10792 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1)); 10793 return true; 10794 } 10795 10796 return false; 10797 } 10798 10799 /// SimplifySelectCC - Simplify an expression of the form (N0 cond N1) ? N2 : N3 10800 /// where 'cond' is the comparison specified by CC. 10801 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, 10802 SDValue N2, SDValue N3, 10803 ISD::CondCode CC, bool NotExtCompare) { 10804 // (x ? y : y) -> y. 10805 if (N2 == N3) return N2; 10806 10807 EVT VT = N2.getValueType(); 10808 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode()); 10809 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode()); 10810 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode()); 10811 10812 // Determine if the condition we're dealing with is constant 10813 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()), 10814 N0, N1, CC, DL, false); 10815 if (SCC.getNode()) AddToWorkList(SCC.getNode()); 10816 ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode()); 10817 10818 // fold select_cc true, x, y -> x 10819 if (SCCC && !SCCC->isNullValue()) 10820 return N2; 10821 // fold select_cc false, x, y -> y 10822 if (SCCC && SCCC->isNullValue()) 10823 return N3; 10824 10825 // Check to see if we can simplify the select into an fabs node 10826 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) { 10827 // Allow either -0.0 or 0.0 10828 if (CFP->getValueAPF().isZero()) { 10829 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs 10830 if ((CC == ISD::SETGE || CC == ISD::SETGT) && 10831 N0 == N2 && N3.getOpcode() == ISD::FNEG && 10832 N2 == N3.getOperand(0)) 10833 return DAG.getNode(ISD::FABS, DL, VT, N0); 10834 10835 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs 10836 if ((CC == ISD::SETLT || CC == ISD::SETLE) && 10837 N0 == N3 && N2.getOpcode() == ISD::FNEG && 10838 N2.getOperand(0) == N3) 10839 return DAG.getNode(ISD::FABS, DL, VT, N3); 10840 } 10841 } 10842 10843 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)" 10844 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0 10845 // in it. This is a win when the constant is not otherwise available because 10846 // it replaces two constant pool loads with one. We only do this if the FP 10847 // type is known to be legal, because if it isn't, then we are before legalize 10848 // types an we want the other legalization to happen first (e.g. to avoid 10849 // messing with soft float) and if the ConstantFP is not legal, because if 10850 // it is legal, we may not need to store the FP constant in a constant pool. 10851 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2)) 10852 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) { 10853 if (TLI.isTypeLegal(N2.getValueType()) && 10854 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) != 10855 TargetLowering::Legal) && 10856 // If both constants have multiple uses, then we won't need to do an 10857 // extra load, they are likely around in registers for other users. 10858 (TV->hasOneUse() || FV->hasOneUse())) { 10859 Constant *Elts[] = { 10860 const_cast<ConstantFP*>(FV->getConstantFPValue()), 10861 const_cast<ConstantFP*>(TV->getConstantFPValue()) 10862 }; 10863 Type *FPTy = Elts[0]->getType(); 10864 const DataLayout &TD = *TLI.getDataLayout(); 10865 10866 // Create a ConstantArray of the two constants. 10867 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts); 10868 SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(), 10869 TD.getPrefTypeAlignment(FPTy)); 10870 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment(); 10871 10872 // Get the offsets to the 0 and 1 element of the array so that we can 10873 // select between them. 10874 SDValue Zero = DAG.getIntPtrConstant(0); 10875 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType()); 10876 SDValue One = DAG.getIntPtrConstant(EltSize); 10877 10878 SDValue Cond = DAG.getSetCC(DL, 10879 getSetCCResultType(N0.getValueType()), 10880 N0, N1, CC); 10881 AddToWorkList(Cond.getNode()); 10882 SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(), 10883 Cond, One, Zero); 10884 AddToWorkList(CstOffset.getNode()); 10885 CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx, 10886 CstOffset); 10887 AddToWorkList(CPIdx.getNode()); 10888 return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx, 10889 MachinePointerInfo::getConstantPool(), false, 10890 false, false, Alignment); 10891 10892 } 10893 } 10894 10895 // Check to see if we can perform the "gzip trick", transforming 10896 // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A) 10897 if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT && 10898 (N1C->isNullValue() || // (a < 0) ? b : 0 10899 (N1C->getAPIntValue() == 1 && N0 == N2))) { // (a < 1) ? a : 0 10900 EVT XType = N0.getValueType(); 10901 EVT AType = N2.getValueType(); 10902 if (XType.bitsGE(AType)) { 10903 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a 10904 // single-bit constant. 10905 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) { 10906 unsigned ShCtV = N2C->getAPIntValue().logBase2(); 10907 ShCtV = XType.getSizeInBits()-ShCtV-1; 10908 SDValue ShCt = DAG.getConstant(ShCtV, 10909 getShiftAmountTy(N0.getValueType())); 10910 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), 10911 XType, N0, ShCt); 10912 AddToWorkList(Shift.getNode()); 10913 10914 if (XType.bitsGT(AType)) { 10915 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift); 10916 AddToWorkList(Shift.getNode()); 10917 } 10918 10919 return DAG.getNode(ISD::AND, DL, AType, Shift, N2); 10920 } 10921 10922 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), 10923 XType, N0, 10924 DAG.getConstant(XType.getSizeInBits()-1, 10925 getShiftAmountTy(N0.getValueType()))); 10926 AddToWorkList(Shift.getNode()); 10927 10928 if (XType.bitsGT(AType)) { 10929 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift); 10930 AddToWorkList(Shift.getNode()); 10931 } 10932 10933 return DAG.getNode(ISD::AND, DL, AType, Shift, N2); 10934 } 10935 } 10936 10937 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A) 10938 // where y is has a single bit set. 10939 // A plaintext description would be, we can turn the SELECT_CC into an AND 10940 // when the condition can be materialized as an all-ones register. Any 10941 // single bit-test can be materialized as an all-ones register with 10942 // shift-left and shift-right-arith. 10943 if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND && 10944 N0->getValueType(0) == VT && 10945 N1C && N1C->isNullValue() && 10946 N2C && N2C->isNullValue()) { 10947 SDValue AndLHS = N0->getOperand(0); 10948 ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 10949 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) { 10950 // Shift the tested bit over the sign bit. 10951 APInt AndMask = ConstAndRHS->getAPIntValue(); 10952 SDValue ShlAmt = 10953 DAG.getConstant(AndMask.countLeadingZeros(), 10954 getShiftAmountTy(AndLHS.getValueType())); 10955 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt); 10956 10957 // Now arithmetic right shift it all the way over, so the result is either 10958 // all-ones, or zero. 10959 SDValue ShrAmt = 10960 DAG.getConstant(AndMask.getBitWidth()-1, 10961 getShiftAmountTy(Shl.getValueType())); 10962 SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt); 10963 10964 return DAG.getNode(ISD::AND, DL, VT, Shr, N3); 10965 } 10966 } 10967 10968 // fold select C, 16, 0 -> shl C, 4 10969 if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() && 10970 TLI.getBooleanContents(N0.getValueType().isVector()) == 10971 TargetLowering::ZeroOrOneBooleanContent) { 10972 10973 // If the caller doesn't want us to simplify this into a zext of a compare, 10974 // don't do it. 10975 if (NotExtCompare && N2C->getAPIntValue() == 1) 10976 return SDValue(); 10977 10978 // Get a SetCC of the condition 10979 // NOTE: Don't create a SETCC if it's not legal on this target. 10980 if (!LegalOperations || 10981 TLI.isOperationLegal(ISD::SETCC, 10982 LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) { 10983 SDValue Temp, SCC; 10984 // cast from setcc result type to select result type 10985 if (LegalTypes) { 10986 SCC = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()), 10987 N0, N1, CC); 10988 if (N2.getValueType().bitsLT(SCC.getValueType())) 10989 Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2), 10990 N2.getValueType()); 10991 else 10992 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2), 10993 N2.getValueType(), SCC); 10994 } else { 10995 SCC = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC); 10996 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2), 10997 N2.getValueType(), SCC); 10998 } 10999 11000 AddToWorkList(SCC.getNode()); 11001 AddToWorkList(Temp.getNode()); 11002 11003 if (N2C->getAPIntValue() == 1) 11004 return Temp; 11005 11006 // shl setcc result by log2 n2c 11007 return DAG.getNode( 11008 ISD::SHL, DL, N2.getValueType(), Temp, 11009 DAG.getConstant(N2C->getAPIntValue().logBase2(), 11010 getShiftAmountTy(Temp.getValueType()))); 11011 } 11012 } 11013 11014 // Check to see if this is the equivalent of setcc 11015 // FIXME: Turn all of these into setcc if setcc if setcc is legal 11016 // otherwise, go ahead with the folds. 11017 if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) { 11018 EVT XType = N0.getValueType(); 11019 if (!LegalOperations || 11020 TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) { 11021 SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC); 11022 if (Res.getValueType() != VT) 11023 Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res); 11024 return Res; 11025 } 11026 11027 // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X)))) 11028 if (N1C && N1C->isNullValue() && CC == ISD::SETEQ && 11029 (!LegalOperations || 11030 TLI.isOperationLegal(ISD::CTLZ, XType))) { 11031 SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0); 11032 return DAG.getNode(ISD::SRL, DL, XType, Ctlz, 11033 DAG.getConstant(Log2_32(XType.getSizeInBits()), 11034 getShiftAmountTy(Ctlz.getValueType()))); 11035 } 11036 // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1)) 11037 if (N1C && N1C->isNullValue() && CC == ISD::SETGT) { 11038 SDValue NegN0 = DAG.getNode(ISD::SUB, SDLoc(N0), 11039 XType, DAG.getConstant(0, XType), N0); 11040 SDValue NotN0 = DAG.getNOT(SDLoc(N0), N0, XType); 11041 return DAG.getNode(ISD::SRL, DL, XType, 11042 DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0), 11043 DAG.getConstant(XType.getSizeInBits()-1, 11044 getShiftAmountTy(XType))); 11045 } 11046 // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1)) 11047 if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) { 11048 SDValue Sign = DAG.getNode(ISD::SRL, SDLoc(N0), XType, N0, 11049 DAG.getConstant(XType.getSizeInBits()-1, 11050 getShiftAmountTy(N0.getValueType()))); 11051 return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType)); 11052 } 11053 } 11054 11055 // Check to see if this is an integer abs. 11056 // select_cc setg[te] X, 0, X, -X -> 11057 // select_cc setgt X, -1, X, -X -> 11058 // select_cc setl[te] X, 0, -X, X -> 11059 // select_cc setlt X, 1, -X, X -> 11060 // Y = sra (X, size(X)-1); xor (add (X, Y), Y) 11061 if (N1C) { 11062 ConstantSDNode *SubC = NULL; 11063 if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) || 11064 (N1C->isAllOnesValue() && CC == ISD::SETGT)) && 11065 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1)) 11066 SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0)); 11067 else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) || 11068 (N1C->isOne() && CC == ISD::SETLT)) && 11069 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1)) 11070 SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0)); 11071 11072 EVT XType = N0.getValueType(); 11073 if (SubC && SubC->isNullValue() && XType.isInteger()) { 11074 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), XType, 11075 N0, 11076 DAG.getConstant(XType.getSizeInBits()-1, 11077 getShiftAmountTy(N0.getValueType()))); 11078 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0), 11079 XType, N0, Shift); 11080 AddToWorkList(Shift.getNode()); 11081 AddToWorkList(Add.getNode()); 11082 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift); 11083 } 11084 } 11085 11086 return SDValue(); 11087 } 11088 11089 /// SimplifySetCC - This is a stub for TargetLowering::SimplifySetCC. 11090 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0, 11091 SDValue N1, ISD::CondCode Cond, 11092 SDLoc DL, bool foldBooleans) { 11093 TargetLowering::DAGCombinerInfo 11094 DagCombineInfo(DAG, Level, false, this); 11095 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL); 11096 } 11097 11098 /// BuildSDIVSequence - Given an ISD::SDIV node expressing a divide by constant, 11099 /// return a DAG expression to select that will generate the same value by 11100 /// multiplying by a magic number. See: 11101 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html> 11102 SDValue DAGCombiner::BuildSDIV(SDNode *N) { 11103 std::vector<SDNode*> Built; 11104 SDValue S = TLI.BuildSDIV(N, DAG, LegalOperations, &Built); 11105 11106 for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end(); 11107 ii != ee; ++ii) 11108 AddToWorkList(*ii); 11109 return S; 11110 } 11111 11112 /// BuildUDIVSequence - Given an ISD::UDIV node expressing a divide by constant, 11113 /// return a DAG expression to select that will generate the same value by 11114 /// multiplying by a magic number. See: 11115 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html> 11116 SDValue DAGCombiner::BuildUDIV(SDNode *N) { 11117 std::vector<SDNode*> Built; 11118 SDValue S = TLI.BuildUDIV(N, DAG, LegalOperations, &Built); 11119 11120 for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end(); 11121 ii != ee; ++ii) 11122 AddToWorkList(*ii); 11123 return S; 11124 } 11125 11126 /// FindBaseOffset - Return true if base is a frame index, which is known not 11127 // to alias with anything but itself. Provides base object and offset as 11128 // results. 11129 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset, 11130 const GlobalValue *&GV, const void *&CV) { 11131 // Assume it is a primitive operation. 11132 Base = Ptr; Offset = 0; GV = 0; CV = 0; 11133 11134 // If it's an adding a simple constant then integrate the offset. 11135 if (Base.getOpcode() == ISD::ADD) { 11136 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) { 11137 Base = Base.getOperand(0); 11138 Offset += C->getZExtValue(); 11139 } 11140 } 11141 11142 // Return the underlying GlobalValue, and update the Offset. Return false 11143 // for GlobalAddressSDNode since the same GlobalAddress may be represented 11144 // by multiple nodes with different offsets. 11145 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) { 11146 GV = G->getGlobal(); 11147 Offset += G->getOffset(); 11148 return false; 11149 } 11150 11151 // Return the underlying Constant value, and update the Offset. Return false 11152 // for ConstantSDNodes since the same constant pool entry may be represented 11153 // by multiple nodes with different offsets. 11154 if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) { 11155 CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal() 11156 : (const void *)C->getConstVal(); 11157 Offset += C->getOffset(); 11158 return false; 11159 } 11160 // If it's any of the following then it can't alias with anything but itself. 11161 return isa<FrameIndexSDNode>(Base); 11162 } 11163 11164 /// isAlias - Return true if there is any possibility that the two addresses 11165 /// overlap. 11166 bool DAGCombiner::isAlias(SDValue Ptr1, int64_t Size1, bool IsVolatile1, 11167 const Value *SrcValue1, int SrcValueOffset1, 11168 unsigned SrcValueAlign1, 11169 const MDNode *TBAAInfo1, 11170 SDValue Ptr2, int64_t Size2, bool IsVolatile2, 11171 const Value *SrcValue2, int SrcValueOffset2, 11172 unsigned SrcValueAlign2, 11173 const MDNode *TBAAInfo2) const { 11174 // If they are the same then they must be aliases. 11175 if (Ptr1 == Ptr2) return true; 11176 11177 // If they are both volatile then they cannot be reordered. 11178 if (IsVolatile1 && IsVolatile2) return true; 11179 11180 // Gather base node and offset information. 11181 SDValue Base1, Base2; 11182 int64_t Offset1, Offset2; 11183 const GlobalValue *GV1, *GV2; 11184 const void *CV1, *CV2; 11185 bool isFrameIndex1 = FindBaseOffset(Ptr1, Base1, Offset1, GV1, CV1); 11186 bool isFrameIndex2 = FindBaseOffset(Ptr2, Base2, Offset2, GV2, CV2); 11187 11188 // If they have a same base address then check to see if they overlap. 11189 if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2))) 11190 return !((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1); 11191 11192 // It is possible for different frame indices to alias each other, mostly 11193 // when tail call optimization reuses return address slots for arguments. 11194 // To catch this case, look up the actual index of frame indices to compute 11195 // the real alias relationship. 11196 if (isFrameIndex1 && isFrameIndex2) { 11197 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo(); 11198 Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex()); 11199 Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex()); 11200 return !((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1); 11201 } 11202 11203 // Otherwise, if we know what the bases are, and they aren't identical, then 11204 // we know they cannot alias. 11205 if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2)) 11206 return false; 11207 11208 // If we know required SrcValue1 and SrcValue2 have relatively large alignment 11209 // compared to the size and offset of the access, we may be able to prove they 11210 // do not alias. This check is conservative for now to catch cases created by 11211 // splitting vector types. 11212 if ((SrcValueAlign1 == SrcValueAlign2) && 11213 (SrcValueOffset1 != SrcValueOffset2) && 11214 (Size1 == Size2) && (SrcValueAlign1 > Size1)) { 11215 int64_t OffAlign1 = SrcValueOffset1 % SrcValueAlign1; 11216 int64_t OffAlign2 = SrcValueOffset2 % SrcValueAlign1; 11217 11218 // There is no overlap between these relatively aligned accesses of similar 11219 // size, return no alias. 11220 if ((OffAlign1 + Size1) <= OffAlign2 || (OffAlign2 + Size2) <= OffAlign1) 11221 return false; 11222 } 11223 11224 bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0 ? CombinerGlobalAA : 11225 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA(); 11226 #ifndef NDEBUG 11227 if (CombinerAAOnlyFunc.getNumOccurrences() && 11228 CombinerAAOnlyFunc != DAG.getMachineFunction().getName()) 11229 UseAA = false; 11230 #endif 11231 if (UseAA && SrcValue1 && SrcValue2) { 11232 // Use alias analysis information. 11233 int64_t MinOffset = std::min(SrcValueOffset1, SrcValueOffset2); 11234 int64_t Overlap1 = Size1 + SrcValueOffset1 - MinOffset; 11235 int64_t Overlap2 = Size2 + SrcValueOffset2 - MinOffset; 11236 AliasAnalysis::AliasResult AAResult = 11237 AA.alias(AliasAnalysis::Location(SrcValue1, Overlap1, 11238 UseTBAA ? TBAAInfo1 : 0), 11239 AliasAnalysis::Location(SrcValue2, Overlap2, 11240 UseTBAA ? TBAAInfo2 : 0)); 11241 if (AAResult == AliasAnalysis::NoAlias) 11242 return false; 11243 } 11244 11245 // Otherwise we have to assume they alias. 11246 return true; 11247 } 11248 11249 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) { 11250 SDValue Ptr0, Ptr1; 11251 int64_t Size0, Size1; 11252 bool IsVolatile0, IsVolatile1; 11253 const Value *SrcValue0, *SrcValue1; 11254 int SrcValueOffset0, SrcValueOffset1; 11255 unsigned SrcValueAlign0, SrcValueAlign1; 11256 const MDNode *SrcTBAAInfo0, *SrcTBAAInfo1; 11257 FindAliasInfo(Op0, Ptr0, Size0, IsVolatile0, SrcValue0, SrcValueOffset0, 11258 SrcValueAlign0, SrcTBAAInfo0); 11259 FindAliasInfo(Op1, Ptr1, Size1, IsVolatile1, SrcValue1, SrcValueOffset1, 11260 SrcValueAlign1, SrcTBAAInfo1); 11261 return isAlias(Ptr0, Size0, IsVolatile0, SrcValue0, SrcValueOffset0, 11262 SrcValueAlign0, SrcTBAAInfo0, 11263 Ptr1, Size1, IsVolatile1, SrcValue1, SrcValueOffset1, 11264 SrcValueAlign1, SrcTBAAInfo1); 11265 } 11266 11267 /// FindAliasInfo - Extracts the relevant alias information from the memory 11268 /// node. Returns true if the operand was a nonvolatile load. 11269 bool DAGCombiner::FindAliasInfo(SDNode *N, 11270 SDValue &Ptr, int64_t &Size, bool &IsVolatile, 11271 const Value *&SrcValue, 11272 int &SrcValueOffset, 11273 unsigned &SrcValueAlign, 11274 const MDNode *&TBAAInfo) const { 11275 LSBaseSDNode *LS = cast<LSBaseSDNode>(N); 11276 11277 Ptr = LS->getBasePtr(); 11278 Size = LS->getMemoryVT().getSizeInBits() >> 3; 11279 IsVolatile = LS->isVolatile(); 11280 SrcValue = LS->getSrcValue(); 11281 SrcValueOffset = LS->getSrcValueOffset(); 11282 SrcValueAlign = LS->getOriginalAlignment(); 11283 TBAAInfo = LS->getTBAAInfo(); 11284 return isa<LoadSDNode>(LS) && !IsVolatile; 11285 } 11286 11287 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes, 11288 /// looking for aliasing nodes and adding them to the Aliases vector. 11289 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain, 11290 SmallVectorImpl<SDValue> &Aliases) { 11291 SmallVector<SDValue, 8> Chains; // List of chains to visit. 11292 SmallPtrSet<SDNode *, 16> Visited; // Visited node set. 11293 11294 // Get alias information for node. 11295 SDValue Ptr; 11296 int64_t Size; 11297 bool IsVolatile; 11298 const Value *SrcValue; 11299 int SrcValueOffset; 11300 unsigned SrcValueAlign; 11301 const MDNode *SrcTBAAInfo; 11302 bool IsLoad = FindAliasInfo(N, Ptr, Size, IsVolatile, SrcValue, 11303 SrcValueOffset, SrcValueAlign, SrcTBAAInfo); 11304 11305 // Starting off. 11306 Chains.push_back(OriginalChain); 11307 unsigned Depth = 0; 11308 11309 // Look at each chain and determine if it is an alias. If so, add it to the 11310 // aliases list. If not, then continue up the chain looking for the next 11311 // candidate. 11312 while (!Chains.empty()) { 11313 SDValue Chain = Chains.back(); 11314 Chains.pop_back(); 11315 11316 // For TokenFactor nodes, look at each operand and only continue up the 11317 // chain until we find two aliases. If we've seen two aliases, assume we'll 11318 // find more and revert to original chain since the xform is unlikely to be 11319 // profitable. 11320 // 11321 // FIXME: The depth check could be made to return the last non-aliasing 11322 // chain we found before we hit a tokenfactor rather than the original 11323 // chain. 11324 if (Depth > 6 || Aliases.size() == 2) { 11325 Aliases.clear(); 11326 Aliases.push_back(OriginalChain); 11327 return; 11328 } 11329 11330 // Don't bother if we've been before. 11331 if (!Visited.insert(Chain.getNode())) 11332 continue; 11333 11334 switch (Chain.getOpcode()) { 11335 case ISD::EntryToken: 11336 // Entry token is ideal chain operand, but handled in FindBetterChain. 11337 break; 11338 11339 case ISD::LOAD: 11340 case ISD::STORE: { 11341 // Get alias information for Chain. 11342 SDValue OpPtr; 11343 int64_t OpSize; 11344 bool OpIsVolatile; 11345 const Value *OpSrcValue; 11346 int OpSrcValueOffset; 11347 unsigned OpSrcValueAlign; 11348 const MDNode *OpSrcTBAAInfo; 11349 bool IsOpLoad = FindAliasInfo(Chain.getNode(), OpPtr, OpSize, 11350 OpIsVolatile, OpSrcValue, OpSrcValueOffset, 11351 OpSrcValueAlign, 11352 OpSrcTBAAInfo); 11353 11354 // If chain is alias then stop here. 11355 if (!(IsLoad && IsOpLoad) && 11356 isAlias(Ptr, Size, IsVolatile, SrcValue, SrcValueOffset, 11357 SrcValueAlign, SrcTBAAInfo, 11358 OpPtr, OpSize, OpIsVolatile, OpSrcValue, OpSrcValueOffset, 11359 OpSrcValueAlign, OpSrcTBAAInfo)) { 11360 Aliases.push_back(Chain); 11361 } else { 11362 // Look further up the chain. 11363 Chains.push_back(Chain.getOperand(0)); 11364 ++Depth; 11365 } 11366 break; 11367 } 11368 11369 case ISD::TokenFactor: 11370 // We have to check each of the operands of the token factor for "small" 11371 // token factors, so we queue them up. Adding the operands to the queue 11372 // (stack) in reverse order maintains the original order and increases the 11373 // likelihood that getNode will find a matching token factor (CSE.) 11374 if (Chain.getNumOperands() > 16) { 11375 Aliases.push_back(Chain); 11376 break; 11377 } 11378 for (unsigned n = Chain.getNumOperands(); n;) 11379 Chains.push_back(Chain.getOperand(--n)); 11380 ++Depth; 11381 break; 11382 11383 default: 11384 // For all other instructions we will just have to take what we can get. 11385 Aliases.push_back(Chain); 11386 break; 11387 } 11388 } 11389 11390 // We need to be careful here to also search for aliases through the 11391 // value operand of a store, etc. Consider the following situation: 11392 // Token1 = ... 11393 // L1 = load Token1, %52 11394 // S1 = store Token1, L1, %51 11395 // L2 = load Token1, %52+8 11396 // S2 = store Token1, L2, %51+8 11397 // Token2 = Token(S1, S2) 11398 // L3 = load Token2, %53 11399 // S3 = store Token2, L3, %52 11400 // L4 = load Token2, %53+8 11401 // S4 = store Token2, L4, %52+8 11402 // If we search for aliases of S3 (which loads address %52), and we look 11403 // only through the chain, then we'll miss the trivial dependence on L1 11404 // (which also loads from %52). We then might change all loads and 11405 // stores to use Token1 as their chain operand, which could result in 11406 // copying %53 into %52 before copying %52 into %51 (which should 11407 // happen first). 11408 // 11409 // The problem is, however, that searching for such data dependencies 11410 // can become expensive, and the cost is not directly related to the 11411 // chain depth. Instead, we'll rule out such configurations here by 11412 // insisting that we've visited all chain users (except for users 11413 // of the original chain, which is not necessary). When doing this, 11414 // we need to look through nodes we don't care about (otherwise, things 11415 // like register copies will interfere with trivial cases). 11416 11417 SmallVector<const SDNode *, 16> Worklist; 11418 for (SmallPtrSet<SDNode *, 16>::iterator I = Visited.begin(), 11419 IE = Visited.end(); I != IE; ++I) 11420 if (*I != OriginalChain.getNode()) 11421 Worklist.push_back(*I); 11422 11423 while (!Worklist.empty()) { 11424 const SDNode *M = Worklist.pop_back_val(); 11425 11426 // We have already visited M, and want to make sure we've visited any uses 11427 // of M that we care about. For uses that we've not visisted, and don't 11428 // care about, queue them to the worklist. 11429 11430 for (SDNode::use_iterator UI = M->use_begin(), 11431 UIE = M->use_end(); UI != UIE; ++UI) 11432 if (UI.getUse().getValueType() == MVT::Other && Visited.insert(*UI)) { 11433 if (isa<MemIntrinsicSDNode>(*UI) || isa<MemSDNode>(*UI)) { 11434 // We've not visited this use, and we care about it (it could have an 11435 // ordering dependency with the original node). 11436 Aliases.clear(); 11437 Aliases.push_back(OriginalChain); 11438 return; 11439 } 11440 11441 // We've not visited this use, but we don't care about it. Mark it as 11442 // visited and enqueue it to the worklist. 11443 Worklist.push_back(*UI); 11444 } 11445 } 11446 } 11447 11448 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes, looking 11449 /// for a better chain (aliasing node.) 11450 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) { 11451 SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor. 11452 11453 // Accumulate all the aliases to this node. 11454 GatherAllAliases(N, OldChain, Aliases); 11455 11456 // If no operands then chain to entry token. 11457 if (Aliases.size() == 0) 11458 return DAG.getEntryNode(); 11459 11460 // If a single operand then chain to it. We don't need to revisit it. 11461 if (Aliases.size() == 1) 11462 return Aliases[0]; 11463 11464 // Construct a custom tailored token factor. 11465 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, 11466 &Aliases[0], Aliases.size()); 11467 } 11468 11469 // SelectionDAG::Combine - This is the entry point for the file. 11470 // 11471 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA, 11472 CodeGenOpt::Level OptLevel) { 11473 /// run - This is the main entry point to this class. 11474 /// 11475 DAGCombiner(*this, AA, OptLevel).Run(Level); 11476 } 11477