LLVM API Documentation

DAGCombiner.cpp

Go to the documentation of this file.
00001 //===-- DAGCombiner.cpp - Implement a DAG node combiner -------------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This pass combines dag nodes to form fewer, simpler DAG nodes.  It can be run
00011 // both before and after the DAG is legalized.
00012 //
00013 // This pass is not a substitute for the LLVM IR instcombine pass. This pass is
00014 // primarily intended to handle simplification opportunities that are implicit
00015 // in the LLVM IR and exposed by the various codegen lowering phases.
00016 //
00017 //===----------------------------------------------------------------------===//
00018 
00019 #define DEBUG_TYPE "dagcombine"
00020 #include "llvm/CodeGen/SelectionDAG.h"
00021 #include "llvm/DerivedTypes.h"
00022 #include "llvm/LLVMContext.h"
00023 #include "llvm/CodeGen/MachineFunction.h"
00024 #include "llvm/CodeGen/MachineFrameInfo.h"
00025 #include "llvm/CodeGen/PseudoSourceValue.h"
00026 #include "llvm/Analysis/AliasAnalysis.h"
00027 #include "llvm/Target/TargetData.h"
00028 #include "llvm/Target/TargetFrameInfo.h"
00029 #include "llvm/Target/TargetLowering.h"
00030 #include "llvm/Target/TargetMachine.h"
00031 #include "llvm/Target/TargetOptions.h"
00032 #include "llvm/ADT/SmallPtrSet.h"
00033 #include "llvm/ADT/Statistic.h"
00034 #include "llvm/Support/Compiler.h"
00035 #include "llvm/Support/CommandLine.h"
00036 #include "llvm/Support/Debug.h"
00037 #include "llvm/Support/ErrorHandling.h"
00038 #include "llvm/Support/MathExtras.h"
00039 #include <algorithm>
00040 #include <set>
00041 using namespace llvm;
00042 
00043 STATISTIC(NodesCombined   , "Number of dag nodes combined");
00044 STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created");
00045 STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created");
00046 STATISTIC(OpsNarrowed     , "Number of load/op/store narrowed");
00047 
00048 namespace {
00049   static cl::opt<bool>
00050     CombinerAA("combiner-alias-analysis", cl::Hidden,
00051                cl::desc("Turn on alias analysis during testing"));
00052 
00053   static cl::opt<bool>
00054     CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
00055                cl::desc("Include global information in alias analysis"));
00056 
00057 //------------------------------ DAGCombiner ---------------------------------//
00058 
00059   class VISIBILITY_HIDDEN DAGCombiner {
00060     SelectionDAG &DAG;
00061     const TargetLowering &TLI;
00062     CombineLevel Level;
00063     CodeGenOpt::Level OptLevel;
00064     bool LegalOperations;
00065     bool LegalTypes;
00066 
00067     // Worklist of all of the nodes that need to be simplified.
00068     std::vector<SDNode*> WorkList;
00069 
00070     // AA - Used for DAG load/store alias analysis.
00071     AliasAnalysis &AA;
00072 
00073     /// AddUsersToWorkList - When an instruction is simplified, add all users of
00074     /// the instruction to the work lists because they might get more simplified
00075     /// now.
00076     ///
00077     void AddUsersToWorkList(SDNode *N) {
00078       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
00079            UI != UE; ++UI)
00080         AddToWorkList(*UI);
00081     }
00082 
00083     /// visit - call the node-specific routine that knows how to fold each
00084     /// particular type of node.
00085     SDValue visit(SDNode *N);
00086 
00087   public:
00088     /// AddToWorkList - Add to the work list making sure it's instance is at the
00089     /// the back (next to be processed.)
00090     void AddToWorkList(SDNode *N) {
00091       removeFromWorkList(N);
00092       WorkList.push_back(N);
00093     }
00094 
00095     /// removeFromWorkList - remove all instances of N from the worklist.
00096     ///
00097     void removeFromWorkList(SDNode *N) {
00098       WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), N),
00099                      WorkList.end());
00100     }
00101 
00102     SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
00103                       bool AddTo = true);
00104 
00105     SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
00106       return CombineTo(N, &Res, 1, AddTo);
00107     }
00108 
00109     SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
00110                       bool AddTo = true) {
00111       SDValue To[] = { Res0, Res1 };
00112       return CombineTo(N, To, 2, AddTo);
00113     }
00114 
00115     void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
00116 
00117   private:
00118 
00119     /// SimplifyDemandedBits - Check the specified integer node value to see if
00120     /// it can be simplified or if things it uses can be simplified by bit
00121     /// propagation.  If so, return true.
00122     bool SimplifyDemandedBits(SDValue Op) {
00123       APInt Demanded = APInt::getAllOnesValue(Op.getValueSizeInBits());
00124       return SimplifyDemandedBits(Op, Demanded);
00125     }
00126 
00127     bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded);
00128 
00129     bool CombineToPreIndexedLoadStore(SDNode *N);
00130     bool CombineToPostIndexedLoadStore(SDNode *N);
00131 
00132 
00133     /// combine - call the node-specific routine that knows how to fold each
00134     /// particular type of node. If that doesn't do anything, try the
00135     /// target-specific DAG combines.
00136     SDValue combine(SDNode *N);
00137 
00138     // Visitation implementation - Implement dag node combining for different
00139     // node types.  The semantics are as follows:
00140     // Return Value:
00141     //   SDValue.getNode() == 0 - No change was made
00142     //   SDValue.getNode() == N - N was replaced, is dead and has been handled.
00143     //   otherwise              - N should be replaced by the returned Operand.
00144     //
00145     SDValue visitTokenFactor(SDNode *N);
00146     SDValue visitMERGE_VALUES(SDNode *N);
00147     SDValue visitADD(SDNode *N);
00148     SDValue visitSUB(SDNode *N);
00149     SDValue visitADDC(SDNode *N);
00150     SDValue visitADDE(SDNode *N);
00151     SDValue visitMUL(SDNode *N);
00152     SDValue visitSDIV(SDNode *N);
00153     SDValue visitUDIV(SDNode *N);
00154     SDValue visitSREM(SDNode *N);
00155     SDValue visitUREM(SDNode *N);
00156     SDValue visitMULHU(SDNode *N);
00157     SDValue visitMULHS(SDNode *N);
00158     SDValue visitSMUL_LOHI(SDNode *N);
00159     SDValue visitUMUL_LOHI(SDNode *N);
00160     SDValue visitSDIVREM(SDNode *N);
00161     SDValue visitUDIVREM(SDNode *N);
00162     SDValue visitAND(SDNode *N);
00163     SDValue visitOR(SDNode *N);
00164     SDValue visitXOR(SDNode *N);
00165     SDValue SimplifyVBinOp(SDNode *N);
00166     SDValue visitSHL(SDNode *N);
00167     SDValue visitSRA(SDNode *N);
00168     SDValue visitSRL(SDNode *N);
00169     SDValue visitCTLZ(SDNode *N);
00170     SDValue visitCTTZ(SDNode *N);
00171     SDValue visitCTPOP(SDNode *N);
00172     SDValue visitSELECT(SDNode *N);
00173     SDValue visitSELECT_CC(SDNode *N);
00174     SDValue visitSETCC(SDNode *N);
00175     SDValue visitSIGN_EXTEND(SDNode *N);
00176     SDValue visitZERO_EXTEND(SDNode *N);
00177     SDValue visitANY_EXTEND(SDNode *N);
00178     SDValue visitSIGN_EXTEND_INREG(SDNode *N);
00179     SDValue visitTRUNCATE(SDNode *N);
00180     SDValue visitBIT_CONVERT(SDNode *N);
00181     SDValue visitBUILD_PAIR(SDNode *N);
00182     SDValue visitFADD(SDNode *N);
00183     SDValue visitFSUB(SDNode *N);
00184     SDValue visitFMUL(SDNode *N);
00185     SDValue visitFDIV(SDNode *N);
00186     SDValue visitFREM(SDNode *N);
00187     SDValue visitFCOPYSIGN(SDNode *N);
00188     SDValue visitSINT_TO_FP(SDNode *N);
00189     SDValue visitUINT_TO_FP(SDNode *N);
00190     SDValue visitFP_TO_SINT(SDNode *N);
00191     SDValue visitFP_TO_UINT(SDNode *N);
00192     SDValue visitFP_ROUND(SDNode *N);
00193     SDValue visitFP_ROUND_INREG(SDNode *N);
00194     SDValue visitFP_EXTEND(SDNode *N);
00195     SDValue visitFNEG(SDNode *N);
00196     SDValue visitFABS(SDNode *N);
00197     SDValue visitBRCOND(SDNode *N);
00198     SDValue visitBR_CC(SDNode *N);
00199     SDValue visitLOAD(SDNode *N);
00200     SDValue visitSTORE(SDNode *N);
00201     SDValue visitINSERT_VECTOR_ELT(SDNode *N);
00202     SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
00203     SDValue visitBUILD_VECTOR(SDNode *N);
00204     SDValue visitCONCAT_VECTORS(SDNode *N);
00205     SDValue visitVECTOR_SHUFFLE(SDNode *N);
00206 
00207     SDValue XformToShuffleWithZero(SDNode *N);
00208     SDValue ReassociateOps(unsigned Opc, DebugLoc DL, SDValue LHS, SDValue RHS);
00209 
00210     SDValue visitShiftByConstant(SDNode *N, unsigned Amt);
00211 
00212     bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
00213     SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
00214     SDValue SimplifySelect(DebugLoc DL, SDValue N0, SDValue N1, SDValue N2);
00215     SDValue SimplifySelectCC(DebugLoc DL, SDValue N0, SDValue N1, SDValue N2,
00216                              SDValue N3, ISD::CondCode CC,
00217                              bool NotExtCompare = false);
00218     SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
00219                           DebugLoc DL, bool foldBooleans = true);
00220     SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
00221                                          unsigned HiOp);
00222     SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
00223     SDValue ConstantFoldBIT_CONVERTofBUILD_VECTOR(SDNode *, EVT);
00224     SDValue BuildSDIV(SDNode *N);
00225     SDValue BuildUDIV(SDNode *N);
00226     SDNode *MatchRotate(SDValue LHS, SDValue RHS, DebugLoc DL);
00227     SDValue ReduceLoadWidth(SDNode *N);
00228     SDValue ReduceLoadOpStoreWidth(SDNode *N);
00229 
00230     SDValue GetDemandedBits(SDValue V, const APInt &Mask);
00231 
00232     /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
00233     /// looking for aliasing nodes and adding them to the Aliases vector.
00234     void GatherAllAliases(SDNode *N, SDValue OriginalChain,
00235                           SmallVector<SDValue, 8> &Aliases);
00236 
00237     /// isAlias - Return true if there is any possibility that the two addresses
00238     /// overlap.
00239     bool isAlias(SDValue Ptr1, int64_t Size1,
00240                  const Value *SrcValue1, int SrcValueOffset1,
00241                  SDValue Ptr2, int64_t Size2,
00242                  const Value *SrcValue2, int SrcValueOffset2) const;
00243 
00244     /// FindAliasInfo - Extracts the relevant alias information from the memory
00245     /// node.  Returns true if the operand was a load.
00246     bool FindAliasInfo(SDNode *N,
00247                        SDValue &Ptr, int64_t &Size,
00248                        const Value *&SrcValue, int &SrcValueOffset) const;
00249 
00250     /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes,
00251     /// looking for a better chain (aliasing node.)
00252     SDValue FindBetterChain(SDNode *N, SDValue Chain);
00253 
00254     /// getShiftAmountTy - Returns a type large enough to hold any valid
00255     /// shift amount - before type legalization these can be huge.
00256     EVT getShiftAmountTy() {
00257       return LegalTypes ?  TLI.getShiftAmountTy() : TLI.getPointerTy();
00258     }
00259 
00260 public:
00261     DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
00262       : DAG(D),
00263         TLI(D.getTargetLoweringInfo()),
00264         Level(Unrestricted),
00265         OptLevel(OL),
00266         LegalOperations(false),
00267         LegalTypes(false),
00268         AA(A) {}
00269 
00270     /// Run - runs the dag combiner on all nodes in the work list
00271     void Run(CombineLevel AtLevel);
00272   };
00273 }
00274 
00275 
00276 namespace {
00277 /// WorkListRemover - This class is a DAGUpdateListener that removes any deleted
00278 /// nodes from the worklist.
00279 class VISIBILITY_HIDDEN WorkListRemover :
00280   public SelectionDAG::DAGUpdateListener {
00281   DAGCombiner &DC;
00282 public:
00283   explicit WorkListRemover(DAGCombiner &dc) : DC(dc) {}
00284 
00285   virtual void NodeDeleted(SDNode *N, SDNode *E) {
00286     DC.removeFromWorkList(N);
00287   }
00288 
00289   virtual void NodeUpdated(SDNode *N) {
00290     // Ignore updates.
00291   }
00292 };
00293 }
00294 
00295 //===----------------------------------------------------------------------===//
00296 //  TargetLowering::DAGCombinerInfo implementation
00297 //===----------------------------------------------------------------------===//
00298 
00299 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
00300   ((DAGCombiner*)DC)->AddToWorkList(N);
00301 }
00302 
00303 SDValue TargetLowering::DAGCombinerInfo::
00304 CombineTo(SDNode *N, const std::vector<SDValue> &To, bool AddTo) {
00305   return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
00306 }
00307 
00308 SDValue TargetLowering::DAGCombinerInfo::
00309 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
00310   return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
00311 }
00312 
00313 
00314 SDValue TargetLowering::DAGCombinerInfo::
00315 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
00316   return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
00317 }
00318 
00319 void TargetLowering::DAGCombinerInfo::
00320 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
00321   return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
00322 }
00323 
00324 //===----------------------------------------------------------------------===//
00325 // Helper Functions
00326 //===----------------------------------------------------------------------===//
00327 
00328 /// isNegatibleForFree - Return 1 if we can compute the negated form of the
00329 /// specified expression for the same cost as the expression itself, or 2 if we
00330 /// can compute the negated form more cheaply than the expression itself.
00331 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
00332                                unsigned Depth = 0) {
00333   // No compile time optimizations on this type.
00334   if (Op.getValueType() == MVT::ppcf128)
00335     return 0;
00336 
00337   // fneg is removable even if it has multiple uses.
00338   if (Op.getOpcode() == ISD::FNEG) return 2;
00339 
00340   // Don't allow anything with multiple uses.
00341   if (!Op.hasOneUse()) return 0;
00342 
00343   // Don't recurse exponentially.
00344   if (Depth > 6) return 0;
00345 
00346   switch (Op.getOpcode()) {
00347   default: return false;
00348   case ISD::ConstantFP:
00349     // Don't invert constant FP values after legalize.  The negated constant
00350     // isn't necessarily legal.
00351     return LegalOperations ? 0 : 1;
00352   case ISD::FADD:
00353     // FIXME: determine better conditions for this xform.
00354     if (!UnsafeFPMath) return 0;
00355 
00356     // fold (fsub (fadd A, B)) -> (fsub (fneg A), B)
00357     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, Depth+1))
00358       return V;
00359     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
00360     return isNegatibleForFree(Op.getOperand(1), LegalOperations, Depth+1);
00361   case ISD::FSUB:
00362     // We can't turn -(A-B) into B-A when we honor signed zeros.
00363     if (!UnsafeFPMath) return 0;
00364 
00365     // fold (fneg (fsub A, B)) -> (fsub B, A)
00366     return 1;
00367 
00368   case ISD::FMUL:
00369   case ISD::FDIV:
00370     if (HonorSignDependentRoundingFPMath()) return 0;
00371 
00372     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
00373     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, Depth+1))
00374       return V;
00375 
00376     return isNegatibleForFree(Op.getOperand(1), LegalOperations, Depth+1);
00377 
00378   case ISD::FP_EXTEND:
00379   case ISD::FP_ROUND:
00380   case ISD::FSIN:
00381     return isNegatibleForFree(Op.getOperand(0), LegalOperations, Depth+1);
00382   }
00383 }
00384 
00385 /// GetNegatedExpression - If isNegatibleForFree returns true, this function
00386 /// returns the newly negated expression.
00387 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
00388                                     bool LegalOperations, unsigned Depth = 0) {
00389   // fneg is removable even if it has multiple uses.
00390   if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
00391 
00392   // Don't allow anything with multiple uses.
00393   assert(Op.hasOneUse() && "Unknown reuse!");
00394 
00395   assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
00396   switch (Op.getOpcode()) {
00397   default: llvm_unreachable("Unknown code");
00398   case ISD::ConstantFP: {
00399     APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
00400     V.changeSign();
00401     return DAG.getConstantFP(V, Op.getValueType());
00402   }
00403   case ISD::FADD:
00404     // FIXME: determine better conditions for this xform.
00405     assert(UnsafeFPMath);
00406 
00407     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
00408     if (isNegatibleForFree(Op.getOperand(0), LegalOperations, Depth+1))
00409       return DAG.getNode(ISD::FSUB, Op.getDebugLoc(), Op.getValueType(),
00410                          GetNegatedExpression(Op.getOperand(0), DAG,
00411                                               LegalOperations, Depth+1),
00412                          Op.getOperand(1));
00413     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
00414     return DAG.getNode(ISD::FSUB, Op.getDebugLoc(), Op.getValueType(),
00415                        GetNegatedExpression(Op.getOperand(1), DAG,
00416                                             LegalOperations, Depth+1),
00417                        Op.getOperand(0));
00418   case ISD::FSUB:
00419     // We can't turn -(A-B) into B-A when we honor signed zeros.
00420     assert(UnsafeFPMath);
00421 
00422     // fold (fneg (fsub 0, B)) -> B
00423     if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
00424       if (N0CFP->getValueAPF().isZero())
00425         return Op.getOperand(1);
00426 
00427     // fold (fneg (fsub A, B)) -> (fsub B, A)
00428     return DAG.getNode(ISD::FSUB, Op.getDebugLoc(), Op.getValueType(),
00429                        Op.getOperand(1), Op.getOperand(0));
00430 
00431   case ISD::FMUL:
00432   case ISD::FDIV:
00433     assert(!HonorSignDependentRoundingFPMath());
00434 
00435     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
00436     if (isNegatibleForFree(Op.getOperand(0), LegalOperations, Depth+1))
00437       return DAG.getNode(Op.getOpcode(), Op.getDebugLoc(), Op.getValueType(),
00438                          GetNegatedExpression(Op.getOperand(0), DAG,
00439                                               LegalOperations, Depth+1),
00440                          Op.getOperand(1));
00441 
00442     // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
00443     return DAG.getNode(Op.getOpcode(), Op.getDebugLoc(), Op.getValueType(),
00444                        Op.getOperand(0),
00445                        GetNegatedExpression(Op.getOperand(1), DAG,
00446                                             LegalOperations, Depth+1));
00447 
00448   case ISD::FP_EXTEND:
00449   case ISD::FSIN:
00450     return DAG.getNode(Op.getOpcode(), Op.getDebugLoc(), Op.getValueType(),
00451                        GetNegatedExpression(Op.getOperand(0), DAG,
00452                                             LegalOperations, Depth+1));
00453   case ISD::FP_ROUND:
00454       return DAG.getNode(ISD::FP_ROUND, Op.getDebugLoc(), Op.getValueType(),
00455                          GetNegatedExpression(Op.getOperand(0), DAG,
00456                                               LegalOperations, Depth+1),
00457                          Op.getOperand(1));
00458   }
00459 }
00460 
00461 
00462 // isSetCCEquivalent - Return true if this node is a setcc, or is a select_cc
00463 // that selects between the values 1 and 0, making it equivalent to a setcc.
00464 // Also, set the incoming LHS, RHS, and CC references to the appropriate
00465 // nodes based on the type of node we are checking.  This simplifies life a
00466 // bit for the callers.
00467 static bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
00468                               SDValue &CC) {
00469   if (N.getOpcode() == ISD::SETCC) {
00470     LHS = N.getOperand(0);
00471     RHS = N.getOperand(1);
00472     CC  = N.getOperand(2);
00473     return true;
00474   }
00475   if (N.getOpcode() == ISD::SELECT_CC &&
00476       N.getOperand(2).getOpcode() == ISD::Constant &&
00477       N.getOperand(3).getOpcode() == ISD::Constant &&
00478       cast<ConstantSDNode>(N.getOperand(2))->getAPIntValue() == 1 &&
00479       cast<ConstantSDNode>(N.getOperand(3))->isNullValue()) {
00480     LHS = N.getOperand(0);
00481     RHS = N.getOperand(1);
00482     CC  = N.getOperand(4);
00483     return true;
00484   }
00485   return false;
00486 }
00487 
00488 // isOneUseSetCC - Return true if this is a SetCC-equivalent operation with only
00489 // one use.  If this is true, it allows the users to invert the operation for
00490 // free when it is profitable to do so.
00491 static bool isOneUseSetCC(SDValue N) {
00492   SDValue N0, N1, N2;
00493   if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
00494     return true;
00495   return false;
00496 }
00497 
00498 SDValue DAGCombiner::ReassociateOps(unsigned Opc, DebugLoc DL,
00499                                     SDValue N0, SDValue N1) {
00500   EVT VT = N0.getValueType();
00501   if (N0.getOpcode() == Opc && isa<ConstantSDNode>(N0.getOperand(1))) {
00502     if (isa<ConstantSDNode>(N1)) {
00503       // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
00504       SDValue OpNode =
00505         DAG.FoldConstantArithmetic(Opc, VT,
00506                                    cast<ConstantSDNode>(N0.getOperand(1)),
00507                                    cast<ConstantSDNode>(N1));
00508       return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
00509     } else if (N0.hasOneUse()) {
00510       // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one use
00511       SDValue OpNode = DAG.getNode(Opc, N0.getDebugLoc(), VT,
00512                                    N0.getOperand(0), N1);
00513       AddToWorkList(OpNode.getNode());
00514       return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
00515     }
00516   }
00517 
00518   if (N1.getOpcode() == Opc && isa<ConstantSDNode>(N1.getOperand(1))) {
00519     if (isa<ConstantSDNode>(N0)) {
00520       // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
00521       SDValue OpNode =
00522         DAG.FoldConstantArithmetic(Opc, VT,
00523                                    cast<ConstantSDNode>(N1.getOperand(1)),
00524                                    cast<ConstantSDNode>(N0));
00525       return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
00526     } else if (N1.hasOneUse()) {
00527       // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one use
00528       SDValue OpNode = DAG.getNode(Opc, N0.getDebugLoc(), VT,
00529                                    N1.getOperand(0), N0);
00530       AddToWorkList(OpNode.getNode());
00531       return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
00532     }
00533   }
00534 
00535   return SDValue();
00536 }
00537 
00538 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
00539                                bool AddTo) {
00540   assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
00541   ++NodesCombined;
00542   DOUT << "\nReplacing.1 "; DEBUG(N->dump(&DAG));
00543   DOUT << "\nWith: "; DEBUG(To[0].getNode()->dump(&DAG));
00544   DOUT << " and " << NumTo-1 << " other values\n";
00545   DEBUG(for (unsigned i = 0, e = NumTo; i != e; ++i)
00546           assert(N->getValueType(i) == To[i].getValueType() &&
00547                  "Cannot combine value to value of different type!"));
00548   WorkListRemover DeadNodes(*this);
00549   DAG.ReplaceAllUsesWith(N, To, &DeadNodes);
00550 
00551   if (AddTo) {
00552     // Push the new nodes and any users onto the worklist
00553     for (unsigned i = 0, e = NumTo; i != e; ++i) {
00554       if (To[i].getNode()) {
00555         AddToWorkList(To[i].getNode());
00556         AddUsersToWorkList(To[i].getNode());
00557       }
00558     }
00559   }
00560 
00561   // Finally, if the node is now dead, remove it from the graph.  The node
00562   // may not be dead if the replacement process recursively simplified to
00563   // something else needing this node.
00564   if (N->use_empty()) {
00565     // Nodes can be reintroduced into the worklist.  Make sure we do not
00566     // process a node that has been replaced.
00567     removeFromWorkList(N);
00568 
00569     // Finally, since the node is now dead, remove it from the graph.
00570     DAG.DeleteNode(N);
00571   }
00572   return SDValue(N, 0);
00573 }
00574 
00575 void
00576 DAGCombiner::CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &
00577                                                                           TLO) {
00578   // Replace all uses.  If any nodes become isomorphic to other nodes and
00579   // are deleted, make sure to remove them from our worklist.
00580   WorkListRemover DeadNodes(*this);
00581   DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New, &DeadNodes);
00582 
00583   // Push the new node and any (possibly new) users onto the worklist.
00584   AddToWorkList(TLO.New.getNode());
00585   AddUsersToWorkList(TLO.New.getNode());
00586 
00587   // Finally, if the node is now dead, remove it from the graph.  The node
00588   // may not be dead if the replacement process recursively simplified to
00589   // something else needing this node.
00590   if (TLO.Old.getNode()->use_empty()) {
00591     removeFromWorkList(TLO.Old.getNode());
00592 
00593     // If the operands of this node are only used by the node, they will now
00594     // be dead.  Make sure to visit them first to delete dead nodes early.
00595     for (unsigned i = 0, e = TLO.Old.getNode()->getNumOperands(); i != e; ++i)
00596       if (TLO.Old.getNode()->getOperand(i).getNode()->hasOneUse())
00597         AddToWorkList(TLO.Old.getNode()->getOperand(i).getNode());
00598 
00599     DAG.DeleteNode(TLO.Old.getNode());
00600   }
00601 }
00602 
00603 /// SimplifyDemandedBits - Check the specified integer node value to see if
00604 /// it can be simplified or if things it uses can be simplified by bit
00605 /// propagation.  If so, return true.
00606 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
00607   TargetLowering::TargetLoweringOpt TLO(DAG);
00608   APInt KnownZero, KnownOne;
00609   if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
00610     return false;
00611 
00612   // Revisit the node.
00613   AddToWorkList(Op.getNode());
00614 
00615   // Replace the old value with the new one.
00616   ++NodesCombined;
00617   DOUT << "\nReplacing.2 "; DEBUG(TLO.Old.getNode()->dump(&DAG));
00618   DOUT << "\nWith: "; DEBUG(TLO.New.getNode()->dump(&DAG));
00619   DOUT << '\n';
00620 
00621   CommitTargetLoweringOpt(TLO);
00622   return true;
00623 }
00624 
00625 //===----------------------------------------------------------------------===//
00626 //  Main DAG Combiner implementation
00627 //===----------------------------------------------------------------------===//
00628 
00629 void DAGCombiner::Run(CombineLevel AtLevel) {
00630   // set the instance variables, so that the various visit routines may use it.
00631   Level = AtLevel;
00632   LegalOperations = Level >= NoIllegalOperations;
00633   LegalTypes = Level >= NoIllegalTypes;
00634 
00635   // Add all the dag nodes to the worklist.
00636   WorkList.reserve(DAG.allnodes_size());
00637   for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
00638        E = DAG.allnodes_end(); I != E; ++I)
00639     WorkList.push_back(I);
00640 
00641   // Create a dummy node (which is not added to allnodes), that adds a reference
00642   // to the root node, preventing it from being deleted, and tracking any
00643   // changes of the root.
00644   HandleSDNode Dummy(DAG.getRoot());
00645 
00646   // The root of the dag may dangle to deleted nodes until the dag combiner is
00647   // done.  Set it to null to avoid confusion.
00648   DAG.setRoot(SDValue());
00649 
00650   // while the worklist isn't empty, inspect the node on the end of it and
00651   // try and combine it.
00652   while (!WorkList.empty()) {
00653     SDNode *N = WorkList.back();
00654     WorkList.pop_back();
00655 
00656     // If N has no uses, it is dead.  Make sure to revisit all N's operands once
00657     // N is deleted from the DAG, since they too may now be dead or may have a
00658     // reduced number of uses, allowing other xforms.
00659     if (N->use_empty() && N != &Dummy) {
00660       for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
00661         AddToWorkList(N->getOperand(i).getNode());
00662 
00663       DAG.DeleteNode(N);
00664       continue;
00665     }
00666 
00667     SDValue RV = combine(N);
00668 
00669     if (RV.getNode() == 0)
00670       continue;
00671 
00672     ++NodesCombined;
00673 
00674     // If we get back the same node we passed in, rather than a new node or
00675     // zero, we know that the node must have defined multiple values and
00676     // CombineTo was used.  Since CombineTo takes care of the worklist
00677     // mechanics for us, we have no work to do in this case.
00678     if (RV.getNode() == N)
00679       continue;
00680 
00681     assert(N->getOpcode() != ISD::DELETED_NODE &&
00682            RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
00683            "Node was deleted but visit returned new node!");
00684 
00685     DOUT << "\nReplacing.3 "; DEBUG(N->dump(&DAG));
00686     DOUT << "\nWith: "; DEBUG(RV.getNode()->dump(&DAG));
00687     DOUT << '\n';
00688     WorkListRemover DeadNodes(*this);
00689     if (N->getNumValues() == RV.getNode()->getNumValues())
00690       DAG.ReplaceAllUsesWith(N, RV.getNode(), &DeadNodes);
00691     else {
00692       assert(N->getValueType(0) == RV.getValueType() &&
00693              N->getNumValues() == 1 && "Type mismatch");
00694       SDValue OpV = RV;
00695       DAG.ReplaceAllUsesWith(N, &OpV, &DeadNodes);
00696     }
00697 
00698     // Push the new node and any users onto the worklist
00699     AddToWorkList(RV.getNode());
00700     AddUsersToWorkList(RV.getNode());
00701 
00702     // Add any uses of the old node to the worklist in case this node is the
00703     // last one that uses them.  They may become dead after this node is
00704     // deleted.
00705     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
00706       AddToWorkList(N->getOperand(i).getNode());
00707 
00708     // Finally, if the node is now dead, remove it from the graph.  The node
00709     // may not be dead if the replacement process recursively simplified to
00710     // something else needing this node.
00711     if (N->use_empty()) {
00712       // Nodes can be reintroduced into the worklist.  Make sure we do not
00713       // process a node that has been replaced.
00714       removeFromWorkList(N);
00715 
00716       // Finally, since the node is now dead, remove it from the graph.
00717       DAG.DeleteNode(N);
00718     }
00719   }
00720 
00721   // If the root changed (e.g. it was a dead load, update the root).
00722   DAG.setRoot(Dummy.getValue());
00723 }
00724 
00725 SDValue DAGCombiner::visit(SDNode *N) {
00726   switch(N->getOpcode()) {
00727   default: break;
00728   case ISD::TokenFactor:        return visitTokenFactor(N);
00729   case ISD::MERGE_VALUES:       return visitMERGE_VALUES(N);
00730   case ISD::ADD:                return visitADD(N);
00731   case ISD::SUB:                return visitSUB(N);
00732   case ISD::ADDC:               return visitADDC(N);
00733   case ISD::ADDE:               return visitADDE(N);
00734   case ISD::MUL:                return visitMUL(N);
00735   case ISD::SDIV:               return visitSDIV(N);
00736   case ISD::UDIV:               return visitUDIV(N);
00737   case ISD::SREM:               return visitSREM(N);
00738   case ISD::UREM:               return visitUREM(N);
00739   case ISD::MULHU:              return visitMULHU(N);
00740   case ISD::MULHS:              return visitMULHS(N);
00741   case ISD::SMUL_LOHI:          return visitSMUL_LOHI(N);
00742   case ISD::UMUL_LOHI:          return visitUMUL_LOHI(N);
00743   case ISD::SDIVREM:            return visitSDIVREM(N);
00744   case ISD::UDIVREM:            return visitUDIVREM(N);
00745   case ISD::AND:                return visitAND(N);
00746   case ISD::OR:                 return visitOR(N);
00747   case ISD::XOR:                return visitXOR(N);
00748   case ISD::SHL:                return visitSHL(N);
00749   case ISD::SRA:                return visitSRA(N);
00750   case ISD::SRL:                return visitSRL(N);
00751   case ISD::CTLZ:               return visitCTLZ(N);
00752   case ISD::CTTZ:               return visitCTTZ(N);
00753   case ISD::CTPOP:              return visitCTPOP(N);
00754   case ISD::SELECT:             return visitSELECT(N);
00755   case ISD::SELECT_CC:          return visitSELECT_CC(N);
00756   case ISD::SETCC:              return visitSETCC(N);
00757   case ISD::SIGN_EXTEND:        return visitSIGN_EXTEND(N);
00758   case ISD::ZERO_EXTEND:        return visitZERO_EXTEND(N);
00759   case ISD::ANY_EXTEND:         return visitANY_EXTEND(N);
00760   case ISD::SIGN_EXTEND_INREG:  return visitSIGN_EXTEND_INREG(N);
00761   case ISD::TRUNCATE:           return visitTRUNCATE(N);
00762   case ISD::BIT_CONVERT:        return visitBIT_CONVERT(N);
00763   case ISD::BUILD_PAIR:         return visitBUILD_PAIR(N);
00764   case ISD::FADD:               return visitFADD(N);
00765   case ISD::FSUB:               return visitFSUB(N);
00766   case ISD::FMUL:               return visitFMUL(N);
00767   case ISD::FDIV:               return visitFDIV(N);
00768   case ISD::FREM:               return visitFREM(N);
00769   case ISD::FCOPYSIGN:          return visitFCOPYSIGN(N);
00770   case ISD::SINT_TO_FP:         return visitSINT_TO_FP(N);
00771   case ISD::UINT_TO_FP:         return visitUINT_TO_FP(N);
00772   case ISD::FP_TO_SINT:         return visitFP_TO_SINT(N);
00773   case ISD::FP_TO_UINT:         return visitFP_TO_UINT(N);
00774   case ISD::FP_ROUND:           return visitFP_ROUND(N);
00775   case ISD::FP_ROUND_INREG:     return visitFP_ROUND_INREG(N);
00776   case ISD::FP_EXTEND:          return visitFP_EXTEND(N);
00777   case ISD::FNEG:               return visitFNEG(N);
00778   case ISD::FABS:               return visitFABS(N);
00779   case ISD::BRCOND:             return visitBRCOND(N);
00780   case ISD::BR_CC:              return visitBR_CC(N);
00781   case ISD::LOAD:               return visitLOAD(N);
00782   case ISD::STORE:              return visitSTORE(N);
00783   case ISD::INSERT_VECTOR_ELT:  return visitINSERT_VECTOR_ELT(N);
00784   case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
00785   case ISD::BUILD_VECTOR:       return visitBUILD_VECTOR(N);
00786   case ISD::CONCAT_VECTORS:     return visitCONCAT_VECTORS(N);
00787   case ISD::VECTOR_SHUFFLE:     return visitVECTOR_SHUFFLE(N);
00788   }
00789   return SDValue();
00790 }
00791 
00792 SDValue DAGCombiner::combine(SDNode *N) {
00793   SDValue RV = visit(N);
00794 
00795   // If nothing happened, try a target-specific DAG combine.
00796   if (RV.getNode() == 0) {
00797     assert(N->getOpcode() != ISD::DELETED_NODE &&
00798            "Node was deleted but visit returned NULL!");
00799 
00800     if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
00801         TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
00802 
00803       // Expose the DAG combiner to the target combiner impls.
00804       TargetLowering::DAGCombinerInfo
00805         DagCombineInfo(DAG, !LegalTypes, !LegalOperations, false, this);
00806 
00807       RV = TLI.PerformDAGCombine(N, DagCombineInfo);
00808     }
00809   }
00810 
00811   // If N is a commutative binary node, try commuting it to enable more
00812   // sdisel CSE.
00813   if (RV.getNode() == 0 &&
00814       SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
00815       N->getNumValues() == 1) {
00816     SDValue N0 = N->getOperand(0);
00817     SDValue N1 = N->getOperand(1);
00818 
00819     // Constant operands are canonicalized to RHS.
00820     if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
00821       SDValue Ops[] = { N1, N0 };
00822       SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(),
00823                                             Ops, 2);
00824       if (CSENode)
00825         return SDValue(CSENode, 0);
00826     }
00827   }
00828 
00829   return RV;
00830 }
00831 
00832 /// getInputChainForNode - Given a node, return its input chain if it has one,
00833 /// otherwise return a null sd operand.
00834 static SDValue getInputChainForNode(SDNode *N) {
00835   if (unsigned NumOps = N->getNumOperands()) {
00836     if (N->getOperand(0).getValueType() == MVT::Other)
00837       return N->getOperand(0);
00838     else if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
00839       return N->getOperand(NumOps-1);
00840     for (unsigned i = 1; i < NumOps-1; ++i)
00841       if (N->getOperand(i).getValueType() == MVT::Other)
00842         return N->getOperand(i);
00843   }
00844   return SDValue();
00845 }
00846 
00847 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
00848   // If N has two operands, where one has an input chain equal to the other,
00849   // the 'other' chain is redundant.
00850   if (N->getNumOperands() == 2) {
00851     if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
00852       return N->getOperand(0);
00853     if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
00854       return N->getOperand(1);
00855   }
00856 
00857   SmallVector<SDNode *, 8> TFs;     // List of token factors to visit.
00858   SmallVector<SDValue, 8> Ops;    // Ops for replacing token factor.
00859   SmallPtrSet<SDNode*, 16> SeenOps;
00860   bool Changed = false;             // If we should replace this token factor.
00861 
00862   // Start out with this token factor.
00863   TFs.push_back(N);
00864 
00865   // Iterate through token factors.  The TFs grows when new token factors are
00866   // encountered.
00867   for (unsigned i = 0; i < TFs.size(); ++i) {
00868     SDNode *TF = TFs[i];
00869 
00870     // Check each of the operands.
00871     for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
00872       SDValue Op = TF->getOperand(i);
00873 
00874       switch (Op.getOpcode()) {
00875       case ISD::EntryToken:
00876         // Entry tokens don't need to be added to the list. They are
00877         // rededundant.
00878         Changed = true;
00879         break;
00880 
00881       case ISD::TokenFactor:
00882         if ((CombinerAA || Op.hasOneUse()) &&
00883             std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
00884           // Queue up for processing.
00885           TFs.push_back(Op.getNode());
00886           // Clean up in case the token factor is removed.
00887           AddToWorkList(Op.getNode());
00888           Changed = true;
00889           break;
00890         }
00891         // Fall thru
00892 
00893       default:
00894         // Only add if it isn't already in the list.
00895         if (SeenOps.insert(Op.getNode()))
00896           Ops.push_back(Op);
00897         else
00898           Changed = true;
00899         break;
00900       }
00901     }
00902   }
00903 
00904   SDValue Result;
00905 
00906   // If we've change things around then replace token factor.
00907   if (Changed) {
00908     if (Ops.empty()) {
00909       // The entry token is the only possible outcome.
00910       Result = DAG.getEntryNode();
00911     } else {
00912       // New and improved token factor.
00913       Result = DAG.getNode(ISD::TokenFactor, N->getDebugLoc(),
00914                            MVT::Other, &Ops[0], Ops.size());
00915     }
00916 
00917     // Don't add users to work list.
00918     return CombineTo(N, Result, false);
00919   }
00920 
00921   return Result;
00922 }
00923 
00924 /// MERGE_VALUES can always be eliminated.
00925 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
00926   WorkListRemover DeadNodes(*this);
00927   // Replacing results may cause a different MERGE_VALUES to suddenly
00928   // be CSE'd with N, and carry its uses with it. Iterate until no
00929   // uses remain, to ensure that the node can be safely deleted.
00930   do {
00931     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
00932       DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i),
00933                                     &DeadNodes);
00934   } while (!N->use_empty());
00935   removeFromWorkList(N);
00936   DAG.DeleteNode(N);
00937   return SDValue(N, 0);   // Return N so it doesn't get rechecked!
00938 }
00939 
00940 static
00941 SDValue combineShlAddConstant(DebugLoc DL, SDValue N0, SDValue N1,
00942                               SelectionDAG &DAG) {
00943   EVT VT = N0.getValueType();
00944   SDValue N00 = N0.getOperand(0);
00945   SDValue N01 = N0.getOperand(1);
00946   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N01);
00947 
00948   if (N01C && N00.getOpcode() == ISD::ADD && N00.getNode()->hasOneUse() &&
00949       isa<ConstantSDNode>(N00.getOperand(1))) {
00950     // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
00951     N0 = DAG.getNode(ISD::ADD, N0.getDebugLoc(), VT,
00952                      DAG.getNode(ISD::SHL, N00.getDebugLoc(), VT,
00953                                  N00.getOperand(0), N01),
00954                      DAG.getNode(ISD::SHL, N01.getDebugLoc(), VT,
00955                                  N00.getOperand(1), N01));
00956     return DAG.getNode(ISD::ADD, DL, VT, N0, N1);
00957   }
00958 
00959   return SDValue();
00960 }
00961 
00962 SDValue DAGCombiner::visitADD(SDNode *N) {
00963   SDValue N0 = N->getOperand(0);
00964   SDValue N1 = N->getOperand(1);
00965   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
00966   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
00967   EVT VT = N0.getValueType();
00968 
00969   // fold vector ops
00970   if (VT.isVector()) {
00971     SDValue FoldedVOp = SimplifyVBinOp(N);
00972     if (FoldedVOp.getNode()) return FoldedVOp;
00973   }
00974 
00975   // fold (add x, undef) -> undef
00976   if (N0.getOpcode() == ISD::UNDEF)
00977     return N0;
00978   if (N1.getOpcode() == ISD::UNDEF)
00979     return N1;
00980   // fold (add c1, c2) -> c1+c2
00981   if (N0C && N1C)
00982     return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C);
00983   // canonicalize constant to RHS
00984   if (N0C && !N1C)
00985     return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N1, N0);
00986   // fold (add x, 0) -> x
00987   if (N1C && N1C->isNullValue())
00988     return N0;
00989   // fold (add Sym, c) -> Sym+c
00990   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
00991     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
00992         GA->getOpcode() == ISD::GlobalAddress)
00993       return DAG.getGlobalAddress(GA->getGlobal(), VT,
00994                                   GA->getOffset() +
00995                                     (uint64_t)N1C->getSExtValue());
00996   // fold ((c1-A)+c2) -> (c1+c2)-A
00997   if (N1C && N0.getOpcode() == ISD::SUB)
00998     if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
00999       return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
01000                          DAG.getConstant(N1C->getAPIntValue()+
01001                                          N0C->getAPIntValue(), VT),
01002                          N0.getOperand(1));
01003   // reassociate add
01004   SDValue RADD = ReassociateOps(ISD::ADD, N->getDebugLoc(), N0, N1);
01005   if (RADD.getNode() != 0)
01006     return RADD;
01007   // fold ((0-A) + B) -> B-A
01008   if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
01009       cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
01010     return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N1, N0.getOperand(1));
01011   // fold (A + (0-B)) -> A-B
01012   if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
01013       cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
01014     return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N0, N1.getOperand(1));
01015   // fold (A+(B-A)) -> B
01016   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
01017     return N1.getOperand(0);
01018   // fold ((B-A)+A) -> B
01019   if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
01020     return N0.getOperand(0);
01021   // fold (A+(B-(A+C))) to (B-C)
01022   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
01023       N0 == N1.getOperand(1).getOperand(0))
01024     return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N1.getOperand(0),
01025                        N1.getOperand(1).getOperand(1));
01026   // fold (A+(B-(C+A))) to (B-C)
01027   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
01028       N0 == N1.getOperand(1).getOperand(1))
01029     return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N1.getOperand(0),
01030                        N1.getOperand(1).getOperand(0));
01031   // fold (A+((B-A)+or-C)) to (B+or-C)
01032   if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
01033       N1.getOperand(0).getOpcode() == ISD::SUB &&
01034       N0 == N1.getOperand(0).getOperand(1))
01035     return DAG.getNode(N1.getOpcode(), N->getDebugLoc(), VT,
01036                        N1.getOperand(0).getOperand(0), N1.getOperand(1));
01037 
01038   // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
01039   if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
01040     SDValue N00 = N0.getOperand(0);
01041     SDValue N01 = N0.getOperand(1);
01042     SDValue N10 = N1.getOperand(0);
01043     SDValue N11 = N1.getOperand(1);
01044 
01045     if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
01046       return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
01047                          DAG.getNode(ISD::ADD, N0.getDebugLoc(), VT, N00, N10),
01048                          DAG.getNode(ISD::ADD, N1.getDebugLoc(), VT, N01, N11));
01049   }
01050 
01051   if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
01052     return SDValue(N, 0);
01053 
01054   // fold (a+b) -> (a|b) iff a and b share no bits.
01055   if (VT.isInteger() && !VT.isVector()) {
01056     APInt LHSZero, LHSOne;
01057     APInt RHSZero, RHSOne;
01058     APInt Mask = APInt::getAllOnesValue(VT.getSizeInBits());
01059     DAG.ComputeMaskedBits(N0, Mask, LHSZero, LHSOne);
01060 
01061     if (LHSZero.getBoolValue()) {
01062       DAG.ComputeMaskedBits(N1, Mask, RHSZero, RHSOne);
01063 
01064       // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
01065       // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
01066       if ((RHSZero & (~LHSZero & Mask)) == (~LHSZero & Mask) ||
01067           (LHSZero & (~RHSZero & Mask)) == (~RHSZero & Mask))
01068         return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, N0, N1);
01069     }
01070   }
01071 
01072   // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
01073   if (N0.getOpcode() == ISD::SHL && N0.getNode()->hasOneUse()) {
01074     SDValue Result = combineShlAddConstant(N->getDebugLoc(), N0, N1, DAG);
01075     if (Result.getNode()) return Result;
01076   }
01077   if (N1.getOpcode() == ISD::SHL && N1.getNode()->hasOneUse()) {
01078     SDValue Result = combineShlAddConstant(N->getDebugLoc(), N1, N0, DAG);
01079     if (Result.getNode()) return Result;
01080   }
01081 
01082   return SDValue();
01083 }
01084 
01085 SDValue DAGCombiner::visitADDC(SDNode *N) {
01086   SDValue N0 = N->getOperand(0);
01087   SDValue N1 = N->getOperand(1);
01088   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
01089   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
01090   EVT VT = N0.getValueType();
01091 
01092   // If the flag result is dead, turn this into an ADD.
01093   if (N->hasNUsesOfValue(0, 1))
01094     return CombineTo(N, DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N1, N0),
01095                      DAG.getNode(ISD::CARRY_FALSE,
01096                                  N->getDebugLoc(), MVT::Flag));
01097 
01098   // canonicalize constant to RHS.
01099   if (N0C && !N1C)
01100     return DAG.getNode(ISD::ADDC, N->getDebugLoc(), N->getVTList(), N1, N0);
01101 
01102   // fold (addc x, 0) -> x + no carry out
01103   if (N1C && N1C->isNullValue())
01104     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
01105                                         N->getDebugLoc(), MVT::Flag));
01106 
01107   // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
01108   APInt LHSZero, LHSOne;
01109   APInt RHSZero, RHSOne;
01110   APInt Mask = APInt::getAllOnesValue(VT.getSizeInBits());
01111   DAG.ComputeMaskedBits(N0, Mask, LHSZero, LHSOne);
01112 
01113   if (LHSZero.getBoolValue()) {
01114     DAG.ComputeMaskedBits(N1, Mask, RHSZero, RHSOne);
01115 
01116     // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
01117     // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
01118     if ((RHSZero & (~LHSZero & Mask)) == (~LHSZero & Mask) ||
01119         (LHSZero & (~RHSZero & Mask)) == (~RHSZero & Mask))
01120       return CombineTo(N, DAG.getNode(ISD::OR, N->getDebugLoc(), VT, N0, N1),
01121                        DAG.getNode(ISD::CARRY_FALSE,
01122                                    N->getDebugLoc(), MVT::Flag));
01123   }
01124 
01125   return SDValue();
01126 }
01127 
01128 SDValue DAGCombiner::visitADDE(SDNode *N) {
01129   SDValue N0 = N->getOperand(0);
01130   SDValue N1 = N->getOperand(1);
01131   SDValue CarryIn = N->getOperand(2);
01132   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
01133   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
01134 
01135   // canonicalize constant to RHS
01136   if (N0C && !N1C)
01137     return DAG.getNode(ISD::ADDE, N->getDebugLoc(), N->getVTList(),
01138                        N1, N0, CarryIn);
01139 
01140   // fold (adde x, y, false) -> (addc x, y)
01141   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
01142     return DAG.getNode(ISD::ADDC, N->getDebugLoc(), N->getVTList(), N1, N0);
01143 
01144   return SDValue();
01145 }
01146 
01147 SDValue DAGCombiner::visitSUB(SDNode *N) {
01148   SDValue N0 = N->getOperand(0);
01149   SDValue N1 = N->getOperand(1);
01150   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
01151   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
01152   EVT VT = N0.getValueType();
01153 
01154   // fold vector ops
01155   if (VT.isVector()) {
01156     SDValue FoldedVOp = SimplifyVBinOp(N);
01157     if (FoldedVOp.getNode()) return FoldedVOp;
01158   }
01159 
01160   // fold (sub x, x) -> 0
01161   if (N0 == N1)
01162     return DAG.getConstant(0, N->getValueType(0));
01163   // fold (sub c1, c2) -> c1-c2
01164   if (N0C && N1C)
01165     return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C);
01166   // fold (sub x, c) -> (add x, -c)
01167   if (N1C)
01168     return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0,
01169                        DAG.getConstant(-N1C->getAPIntValue(), VT));
01170   // fold (A+B)-A -> B
01171   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
01172     return N0.getOperand(1);
01173   // fold (A+B)-B -> A
01174   if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
01175     return N0.getOperand(0);
01176   // fold ((A+(B+or-C))-B) -> A+or-C
01177   if (N0.getOpcode() == ISD::ADD &&
01178       (N0.getOperand(1).getOpcode() == ISD::SUB ||
01179        N0.getOperand(1).getOpcode() == ISD::ADD) &&
01180       N0.getOperand(1).getOperand(0) == N1)
01181     return DAG.getNode(N0.getOperand(1).getOpcode(), N->getDebugLoc(), VT,
01182                        N0.getOperand(0), N0.getOperand(1).getOperand(1));
01183   // fold ((A+(C+B))-B) -> A+C
01184   if (N0.getOpcode() == ISD::ADD &&
01185       N0.getOperand(1).getOpcode() == ISD::ADD &&
01186       N0.getOperand(1).getOperand(1) == N1)
01187     return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT,
01188                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
01189   // fold ((A-(B-C))-C) -> A-B
01190   if (N0.getOpcode() == ISD::SUB &&
01191       N0.getOperand(1).getOpcode() == ISD::SUB &&
01192       N0.getOperand(1).getOperand(1) == N1)
01193     return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
01194                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
01195 
01196   // If either operand of a sub is undef, the result is undef
01197   if (N0.getOpcode() == ISD::UNDEF)
01198     return N0;
01199   if (N1.getOpcode() == ISD::UNDEF)
01200     return N1;
01201 
01202   // If the relocation model supports it, consider symbol offsets.
01203   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
01204     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
01205       // fold (sub Sym, c) -> Sym-c
01206       if (N1C && GA->getOpcode() == ISD::GlobalAddress)
01207         return DAG.getGlobalAddress(GA->getGlobal(), VT,
01208                                     GA->getOffset() -
01209                                       (uint64_t)N1C->getSExtValue());
01210       // fold (sub Sym+c1, Sym+c2) -> c1-c2
01211       if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
01212         if (GA->getGlobal() == GB->getGlobal())
01213           return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
01214                                  VT);
01215     }
01216 
01217   return SDValue();
01218 }
01219 
01220 SDValue DAGCombiner::visitMUL(SDNode *N) {
01221   SDValue N0 = N->getOperand(0);
01222   SDValue N1 = N->getOperand(1);
01223   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
01224   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
01225   EVT VT = N0.getValueType();
01226 
01227   // fold vector ops
01228   if (VT.isVector()) {
01229     SDValue FoldedVOp = SimplifyVBinOp(N);
01230     if (FoldedVOp.getNode()) return FoldedVOp;
01231   }
01232 
01233   // fold (mul x, undef) -> 0
01234   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
01235     return DAG.getConstant(0, VT);
01236   // fold (mul c1, c2) -> c1*c2
01237   if (N0C && N1C)
01238     return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0C, N1C);
01239   // canonicalize constant to RHS
01240   if (N0C && !N1C)
01241     return DAG.getNode(ISD::MUL, N->getDebugLoc(), VT, N1, N0);
01242   // fold (mul x, 0) -> 0
01243   if (N1C && N1C->isNullValue())
01244     return N1;
01245   // fold (mul x, -1) -> 0-x
01246   if (N1C && N1C->isAllOnesValue())
01247     return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
01248                        DAG.getConstant(0, VT), N0);
01249   // fold (mul x, (1 << c)) -> x << c
01250   if (N1C && N1C->getAPIntValue().isPowerOf2())
01251     return DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, N0,
01252                        DAG.getConstant(N1C->getAPIntValue().logBase2(),
01253                                        getShiftAmountTy()));
01254   // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
01255   if (N1C && (-N1C->getAPIntValue()).isPowerOf2()) {
01256     unsigned Log2Val = (-N1C->getAPIntValue()).logBase2();
01257     // FIXME: If the input is something that is easily negated (e.g. a
01258     // single-use add), we should put the negate there.
01259     return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
01260                        DAG.getConstant(0, VT),
01261                        DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, N0,
01262                             DAG.getConstant(Log2Val, getShiftAmountTy())));
01263   }
01264   // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
01265   if (N1C && N0.getOpcode() == ISD::SHL &&
01266       isa<ConstantSDNode>(N0.getOperand(1))) {
01267     SDValue C3 = DAG.getNode(ISD::SHL, N->getDebugLoc(), VT,
01268                              N1, N0.getOperand(1));
01269     AddToWorkList(C3.getNode());
01270     return DAG.getNode(ISD::MUL, N->getDebugLoc(), VT,
01271                        N0.getOperand(0), C3);
01272   }
01273 
01274   // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
01275   // use.
01276   {
01277     SDValue Sh(0,0), Y(0,0);
01278     // Check for both (mul (shl X, C), Y)  and  (mul Y, (shl X, C)).
01279     if (N0.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N0.getOperand(1)) &&
01280         N0.getNode()->hasOneUse()) {
01281       Sh = N0; Y = N1;
01282     } else if (N1.getOpcode() == ISD::SHL &&
01283                isa<ConstantSDNode>(N1.getOperand(1)) &&
01284                N1.getNode()->hasOneUse()) {
01285       Sh = N1; Y = N0;
01286     }
01287 
01288     if (Sh.getNode()) {
01289       SDValue Mul = DAG.getNode(ISD::MUL, N->getDebugLoc(), VT,
01290                                 Sh.getOperand(0), Y);
01291       return DAG.getNode(ISD::SHL, N->getDebugLoc(), VT,
01292                          Mul, Sh.getOperand(1));
01293     }
01294   }
01295 
01296   // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
01297   if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
01298       isa<ConstantSDNode>(N0.getOperand(1)))
01299     return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT,
01300                        DAG.getNode(ISD::MUL, N0.getDebugLoc(), VT,
01301                                    N0.getOperand(0), N1),
01302                        DAG.getNode(ISD::MUL, N1.getDebugLoc(), VT,
01303                                    N0.getOperand(1), N1));
01304 
01305   // reassociate mul
01306   SDValue RMUL = ReassociateOps(ISD::MUL, N->getDebugLoc(), N0, N1);
01307   if (RMUL.getNode() != 0)
01308     return RMUL;
01309 
01310   return SDValue();
01311 }
01312 
01313 SDValue DAGCombiner::visitSDIV(SDNode *N) {
01314   SDValue N0 = N->getOperand(0);
01315   SDValue N1 = N->getOperand(1);
01316   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
01317   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
01318   EVT VT = N->getValueType(0);
01319 
01320   // fold vector ops
01321   if (VT.isVector()) {
01322     SDValue FoldedVOp = SimplifyVBinOp(N);
01323     if (FoldedVOp.getNode()) return FoldedVOp;
01324   }
01325 
01326   // fold (sdiv c1, c2) -> c1/c2
01327   if (N0C && N1C && !N1C->isNullValue())
01328     return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C);
01329   // fold (sdiv X, 1) -> X
01330   if (N1C && N1C->getSExtValue() == 1LL)
01331     return N0;
01332   // fold (sdiv X, -1) -> 0-X
01333   if (N1C && N1C->isAllOnesValue())
01334     return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
01335                        DAG.getConstant(0, VT), N0);
01336   // If we know the sign bits of both operands are zero, strength reduce to a
01337   // udiv instead.  Handles (X&15) /s 4 -> X&15 >> 2
01338   if (!VT.isVector()) {
01339     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
01340       return DAG.getNode(ISD::UDIV, N->getDebugLoc(), N1.getValueType(),
01341                          N0, N1);
01342   }
01343   // fold (sdiv X, pow2) -> simple ops after legalize
01344   if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap() &&
01345       (isPowerOf2_64(N1C->getSExtValue()) ||
01346        isPowerOf2_64(-N1C->getSExtValue()))) {
01347     // If dividing by powers of two is cheap, then don't perform the following
01348     // fold.
01349     if (TLI.isPow2DivCheap())
01350       return SDValue();
01351 
01352     int64_t pow2 = N1C->getSExtValue();
01353     int64_t abs2 = pow2 > 0 ? pow2 : -pow2;
01354     unsigned lg2 = Log2_64(abs2);
01355 
01356     // Splat the sign bit into the register
01357     SDValue SGN = DAG.getNode(ISD::SRA, N->getDebugLoc(), VT, N0,
01358                               DAG.getConstant(VT.getSizeInBits()-1,
01359                                               getShiftAmountTy()));
01360     AddToWorkList(SGN.getNode());
01361 
01362     // Add (N0 < 0) ? abs2 - 1 : 0;
01363     SDValue SRL = DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, SGN,
01364                               DAG.getConstant(VT.getSizeInBits() - lg2,
01365                                               getShiftAmountTy()));
01366     SDValue ADD = DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0, SRL);
01367     AddToWorkList(SRL.getNode());
01368     AddToWorkList(ADD.getNode());    // Divide by pow2
01369     SDValue SRA = DAG.getNode(ISD::SRA, N->getDebugLoc(), VT, ADD,
01370                               DAG.getConstant(lg2, getShiftAmountTy()));
01371 
01372     // If we're dividing by a positive value, we're done.  Otherwise, we must
01373     // negate the result.
01374     if (pow2 > 0)
01375       return SRA;
01376 
01377     AddToWorkList(SRA.getNode());
01378     return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
01379                        DAG.getConstant(0, VT), SRA);
01380   }
01381 
01382   // if integer divide is expensive and we satisfy the requirements, emit an
01383   // alternate sequence.
01384   if (N1C && (N1C->getSExtValue() < -1 || N1C->getSExtValue() > 1) &&
01385       !TLI.isIntDivCheap()) {
01386     SDValue Op = BuildSDIV(N);
01387     if (Op.getNode()) return Op;
01388   }
01389 
01390   // undef / X -> 0
01391   if (N0.getOpcode() == ISD::UNDEF)
01392     return DAG.getConstant(0, VT);
01393   // X / undef -> undef
01394   if (N1.getOpcode() == ISD::UNDEF)
01395     return N1;
01396 
01397   return SDValue();
01398 }
01399 
01400 SDValue DAGCombiner::visitUDIV(SDNode *N) {
01401   SDValue N0 = N->getOperand(0);
01402   SDValue N1 = N->getOperand(1);
01403   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
01404   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
01405   EVT VT = N->getValueType(0);
01406 
01407   // fold vector ops
01408   if (VT.isVector()) {
01409     SDValue FoldedVOp = SimplifyVBinOp(N);
01410     if (FoldedVOp.getNode()) return FoldedVOp;
01411   }
01412 
01413   // fold (udiv c1, c2) -> c1/c2
01414   if (N0C && N1C && !N1C->isNullValue())
01415     return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C);
01416   // fold (udiv x, (1 << c)) -> x >>u c
01417   if (N1C && N1C->getAPIntValue().isPowerOf2())
01418     return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0,
01419                        DAG.getConstant(N1C->getAPIntValue().logBase2(),
01420                                        getShiftAmountTy()));
01421   // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
01422   if (N1.getOpcode() == ISD::SHL) {
01423     if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
01424       if (SHC->getAPIntValue().isPowerOf2()) {
01425         EVT ADDVT = N1.getOperand(1).getValueType();
01426         SDValue Add = DAG.getNode(ISD::ADD, N->getDebugLoc(), ADDVT,
01427                                   N1.getOperand(1),
01428                                   DAG.getConstant(SHC->getAPIntValue()
01429                                                                   .logBase2(),
01430                                                   ADDVT));
01431         AddToWorkList(Add.getNode());
01432         return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0, Add);
01433       }
01434     }
01435   }
01436   // fold (udiv x, c) -> alternate
01437   if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap()) {
01438     SDValue Op = BuildUDIV(N);
01439     if (Op.getNode()) return Op;
01440   }
01441 
01442   // undef / X -> 0
01443   if (N0.getOpcode() == ISD::UNDEF)
01444     return DAG.getConstant(0, VT);
01445   // X / undef -> undef
01446   if (N1.getOpcode() == ISD::UNDEF)
01447     return N1;
01448 
01449   return SDValue();
01450 }
01451 
01452 SDValue DAGCombiner::visitSREM(SDNode *N) {
01453   SDValue N0 = N->getOperand(0);
01454   SDValue N1 = N->getOperand(1);
01455   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
01456   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
01457   EVT VT = N->getValueType(0);
01458 
01459   // fold (srem c1, c2) -> c1%c2
01460   if (N0C && N1C && !N1C->isNullValue())
01461     return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C);
01462   // If we know the sign bits of both operands are zero, strength reduce to a
01463   // urem instead.  Handles (X & 0x0FFFFFFF) %s 16 -> X&15
01464   if (!VT.isVector()) {
01465     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
01466       return DAG.getNode(ISD::UREM, N->getDebugLoc(), VT, N0, N1);
01467   }
01468 
01469   // If X/C can be simplified by the division-by-constant logic, lower
01470   // X%C to the equivalent of X-X/C*C.
01471   if (N1C && !N1C->isNullValue()) {
01472     SDValue Div = DAG.getNode(ISD::SDIV, N->getDebugLoc(), VT, N0, N1);
01473     AddToWorkList(Div.getNode());
01474     SDValue OptimizedDiv = combine(Div.getNode());
01475     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
01476       SDValue Mul = DAG.getNode(ISD::MUL, N->getDebugLoc(), VT,
01477                                 OptimizedDiv, N1);
01478       SDValue Sub = DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N0, Mul);
01479       AddToWorkList(Mul.getNode());
01480       return Sub;
01481     }
01482   }
01483 
01484   // undef % X -> 0
01485   if (N0.getOpcode() == ISD::UNDEF)
01486     return DAG.getConstant(0, VT);
01487   // X % undef -> undef
01488   if (N1.getOpcode() == ISD::UNDEF)
01489     return N1;
01490 
01491   return SDValue();
01492 }
01493 
01494 SDValue DAGCombiner::visitUREM(SDNode *N) {
01495   SDValue N0 = N->getOperand(0);
01496   SDValue N1 = N->getOperand(1);
01497   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
01498   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
01499   EVT VT = N->getValueType(0);
01500 
01501   // fold (urem c1, c2) -> c1%c2
01502   if (N0C && N1C && !N1C->isNullValue())
01503     return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C);
01504   // fold (urem x, pow2) -> (and x, pow2-1)
01505   if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
01506     return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0,
01507                        DAG.getConstant(N1C->getAPIntValue()-1,VT));
01508   // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
01509   if (N1.getOpcode() == ISD::SHL) {
01510     if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
01511       if (SHC->getAPIntValue().isPowerOf2()) {
01512         SDValue Add =
01513           DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N1,
01514                  DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
01515                                  VT));
01516         AddToWorkList(Add.getNode());
01517         return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0, Add);
01518       }
01519     }
01520   }
01521 
01522   // If X/C can be simplified by the division-by-constant logic, lower
01523   // X%C to the equivalent of X-X/C*C.
01524   if (N1C && !N1C->isNullValue()) {
01525     SDValue Div = DAG.getNode(ISD::UDIV, N->getDebugLoc(), VT, N0, N1);
01526     AddToWorkList(Div.getNode());
01527     SDValue OptimizedDiv = combine(Div.getNode());
01528     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
01529       SDValue Mul = DAG.getNode(ISD::MUL, N->getDebugLoc(), VT,
01530                                 OptimizedDiv, N1);
01531       SDValue Sub = DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N0, Mul);
01532       AddToWorkList(Mul.getNode());
01533       return Sub;
01534     }
01535   }
01536 
01537   // undef % X -> 0
01538   if (N0.getOpcode() == ISD::UNDEF)
01539     return DAG.getConstant(0, VT);
01540   // X % undef -> undef
01541   if (N1.getOpcode() == ISD::UNDEF)
01542     return N1;
01543 
01544   return SDValue();
01545 }
01546 
01547 SDValue DAGCombiner::visitMULHS(SDNode *N) {
01548   SDValue N0 = N->getOperand(0);
01549   SDValue N1 = N->getOperand(1);
01550   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
01551   EVT VT = N->getValueType(0);
01552 
01553   // fold (mulhs x, 0) -> 0
01554   if (N1C && N1C->isNullValue())
01555     return N1;
01556   // fold (mulhs x, 1) -> (sra x, size(x)-1)
01557   if (N1C && N1C->getAPIntValue() == 1)
01558     return DAG.getNode(ISD::SRA, N->getDebugLoc(), N0.getValueType(), N0,
01559                        DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
01560                                        getShiftAmountTy()));
01561   // fold (mulhs x, undef) -> 0
01562   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
01563     return DAG.getConstant(0, VT);
01564 
01565   return SDValue();
01566 }
01567 
01568 SDValue DAGCombiner::visitMULHU(SDNode *N) {
01569   SDValue N0 = N->getOperand(0);
01570   SDValue N1 = N->getOperand(1);
01571   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
01572   EVT VT = N->getValueType(0);
01573 
01574   // fold (mulhu x, 0) -> 0
01575   if (N1C && N1C->isNullValue())
01576     return N1;
01577   // fold (mulhu x, 1) -> 0
01578   if (N1C && N1C->getAPIntValue() == 1)
01579     return DAG.getConstant(0, N0.getValueType());
01580   // fold (mulhu x, undef) -> 0
01581   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
01582     return DAG.getConstant(0, VT);
01583 
01584   return SDValue();
01585 }
01586 
01587 /// SimplifyNodeWithTwoResults - Perform optimizations common to nodes that
01588 /// compute two values. LoOp and HiOp give the opcodes for the two computations
01589 /// that are being performed. Return true if a simplification was made.
01590 ///
01591 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
01592                                                 unsigned HiOp) {
01593   // If the high half is not needed, just compute the low half.
01594   bool HiExists = N->hasAnyUseOfValue(1);
01595   if (!HiExists &&
01596       (!LegalOperations ||
01597        TLI.isOperationLegal(LoOp, N->getValueType(0)))) {
01598     SDValue Res = DAG.getNode(LoOp, N->getDebugLoc(), N->getValueType(0),
01599                               N->op_begin(), N->getNumOperands());
01600     return CombineTo(N, Res, Res);
01601   }
01602 
01603   // If the low half is not needed, just compute the high half.
01604   bool LoExists = N->hasAnyUseOfValue(0);
01605   if (!LoExists &&
01606       (!LegalOperations ||
01607        TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
01608     SDValue Res = DAG.getNode(HiOp, N->getDebugLoc(), N->getValueType(1),
01609                               N->op_begin(), N->getNumOperands());
01610     return CombineTo(N, Res, Res);
01611   }
01612 
01613   // If both halves are used, return as it is.
01614   if (LoExists && HiExists)
01615     return SDValue();
01616 
01617   // If the two computed results can be simplified separately, separate them.
01618   if (LoExists) {
01619     SDValue Lo = DAG.getNode(LoOp, N->getDebugLoc(), N->getValueType(0),
01620                              N->op_begin(), N->getNumOperands());
01621     AddToWorkList(Lo.getNode());
01622     SDValue LoOpt = combine(Lo.getNode());
01623     if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
01624         (!LegalOperations ||
01625          TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
01626       return CombineTo(N, LoOpt, LoOpt);
01627   }
01628 
01629   if (HiExists) {
01630     SDValue Hi = DAG.getNode(HiOp, N->getDebugLoc(), N->getValueType(1),
01631                              N->op_begin(), N->getNumOperands());
01632     AddToWorkList(Hi.getNode());
01633     SDValue HiOpt = combine(Hi.getNode());
01634     if (HiOpt.getNode() && HiOpt != Hi &&
01635         (!LegalOperations ||
01636          TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
01637       return CombineTo(N, HiOpt, HiOpt);
01638   }
01639 
01640   return SDValue();
01641 }
01642 
01643 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
01644   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
01645   if (Res.getNode()) return Res;
01646 
01647   return SDValue();
01648 }
01649 
01650 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
01651   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
01652   if (Res.getNode()) return Res;
01653 
01654   return SDValue();
01655 }
01656 
01657 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
01658   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
01659   if (Res.getNode()) return Res;
01660 
01661   return SDValue();
01662 }
01663 
01664 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
01665   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
01666   if (Res.getNode()) return Res;
01667 
01668   return SDValue();
01669 }
01670 
01671 /// SimplifyBinOpWithSameOpcodeHands - If this is a binary operator with
01672 /// two operands of the same opcode, try to simplify it.
01673 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
01674   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
01675   EVT VT = N0.getValueType();
01676   assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
01677 
01678   // For each of OP in AND/OR/XOR:
01679   // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
01680   // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
01681   // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
01682   // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
01683   if ((N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND||
01684        N0.getOpcode() == ISD::SIGN_EXTEND ||
01685        (N0.getOpcode() == ISD::TRUNCATE &&
01686         !TLI.isTruncateFree(N0.getOperand(0).getValueType(), VT))) &&
01687       N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
01688       (!LegalOperations ||
01689        TLI.isOperationLegal(N->getOpcode(), N0.getOperand(0).getValueType()))) {
01690     SDValue ORNode = DAG.getNode(N->getOpcode(), N0.getDebugLoc(),
01691                                  N0.getOperand(0).getValueType(),
01692                                  N0.getOperand(0), N1.getOperand(0));
01693     AddToWorkList(ORNode.getNode());
01694     return DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT, ORNode);
01695   }
01696 
01697   // For each of OP in SHL/SRL/SRA/AND...
01698   //   fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
01699   //   fold (or  (OP x, z), (OP y, z)) -> (OP (or  x, y), z)
01700   //   fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
01701   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
01702        N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
01703       N0.getOperand(1) == N1.getOperand(1)) {
01704     SDValue ORNode = DAG.getNode(N->getOpcode(), N0.getDebugLoc(),
01705                                  N0.getOperand(0).getValueType(),
01706                                  N0.getOperand(0), N1.getOperand(0));
01707     AddToWorkList(ORNode.getNode());
01708     return DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT,
01709                        ORNode, N0.getOperand(1));
01710   }
01711 
01712   return SDValue();
01713 }
01714 
01715 SDValue DAGCombiner::visitAND(SDNode *N) {
01716   SDValue N0 = N->getOperand(0);
01717   SDValue N1 = N->getOperand(1);
01718   SDValue LL, LR, RL, RR, CC0, CC1;
01719   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
01720   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
01721   EVT VT = N1.getValueType();
01722   unsigned BitWidth = VT.getSizeInBits();
01723 
01724   // fold vector ops
01725   if (VT.isVector()) {
01726     SDValue FoldedVOp = SimplifyVBinOp(N);
01727     if (FoldedVOp.getNode()) return FoldedVOp;
01728   }
01729 
01730   // fold (and x, undef) -> 0
01731   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
01732     return DAG.getConstant(0, VT);
01733   // fold (and c1, c2) -> c1&c2
01734   if (N0C && N1C)
01735     return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C);
01736   // canonicalize constant to RHS
01737   if (N0C && !N1C)
01738     return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N1, N0);
01739   // fold (and x, -1) -> x
01740   if (N1C && N1C->isAllOnesValue())
01741     return N0;
01742   // if (and x, c) is known to be zero, return 0
01743   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
01744                                    APInt::getAllOnesValue(BitWidth)))
01745     return DAG.getConstant(0, VT);
01746   // reassociate and
01747   SDValue RAND = ReassociateOps(ISD::AND, N->getDebugLoc(), N0, N1);
01748   if (RAND.getNode() != 0)
01749     return RAND;
01750   // fold (and (or x, 0xFFFF), 0xFF) -> 0xFF
01751   if (N1C && N0.getOpcode() == ISD::OR)
01752     if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
01753       if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
01754         return N1;
01755   // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
01756   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
01757     SDValue N0Op0 = N0.getOperand(0);
01758     APInt Mask = ~N1C->getAPIntValue();
01759     Mask.trunc(N0Op0.getValueSizeInBits());
01760     if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
01761       SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(),
01762                                  N0.getValueType(), N0Op0);
01763 
01764       // Replace uses of the AND with uses of the Zero extend node.
01765       CombineTo(N, Zext);
01766 
01767       // We actually want to replace all uses of the any_extend with the
01768       // zero_extend, to avoid duplicating things.  This will later cause this
01769       // AND to be folded.
01770       CombineTo(N0.getNode(), Zext);
01771       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
01772     }
01773   }
01774   // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
01775   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
01776     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
01777     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
01778 
01779     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
01780         LL.getValueType().isInteger()) {
01781       // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
01782       if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
01783         SDValue ORNode = DAG.getNode(ISD::OR, N0.getDebugLoc(),
01784                                      LR.getValueType(), LL, RL);
01785         AddToWorkList(ORNode.getNode());
01786         return DAG.getSetCC(N->getDebugLoc(), VT, ORNode, LR, Op1);
01787       }
01788       // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
01789       if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
01790         SDValue ANDNode = DAG.getNode(ISD::AND, N0.getDebugLoc(),
01791                                       LR.getValueType(), LL, RL);
01792         AddToWorkList(ANDNode.getNode());
01793         return DAG.getSetCC(N->getDebugLoc(), VT, ANDNode, LR, Op1);
01794       }
01795       // fold (and (setgt X,  -1), (setgt Y,  -1)) -> (setgt (or X, Y), -1)
01796       if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
01797         SDValue ORNode = DAG.getNode(ISD::OR, N0.getDebugLoc(),
01798                                      LR.getValueType(), LL, RL);
01799         AddToWorkList(ORNode.getNode());
01800         return DAG.getSetCC(N->getDebugLoc(), VT, ORNode, LR, Op1);
01801       }
01802     }
01803     // canonicalize equivalent to ll == rl
01804     if (LL == RR && LR == RL) {
01805       Op1 = ISD::getSetCCSwappedOperands(Op1);
01806       std::swap(RL, RR);
01807     }
01808     if (LL == RL && LR == RR) {
01809       bool isInteger = LL.getValueType().isInteger();
01810       ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
01811       if (Result != ISD::SETCC_INVALID &&
01812           (!LegalOperations || TLI.isCondCodeLegal(Result, LL.getValueType())))
01813         return DAG.getSetCC(N->getDebugLoc(), N0.getValueType(),
01814                             LL, LR, Result);
01815     }
01816   }
01817 
01818   // Simplify: (and (op x...), (op y...))  -> (op (and x, y))
01819   if (N0.getOpcode() == N1.getOpcode()) {
01820     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
01821     if (Tmp.getNode()) return Tmp;
01822   }
01823 
01824   // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
01825   // fold (and (sra)) -> (and (srl)) when possible.
01826   if (!VT.isVector() &&
01827       SimplifyDemandedBits(SDValue(N, 0)))
01828     return SDValue(N, 0);
01829   // fold (zext_inreg (extload x)) -> (zextload x)
01830   if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
01831     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
01832     EVT EVT = LN0->getMemoryVT();
01833     // If we zero all the possible extended bits, then we can turn this into
01834     // a zextload if we are running before legalize or the operation is legal.
01835     unsigned BitWidth = N1.getValueSizeInBits();
01836     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
01837                                      BitWidth - EVT.getSizeInBits())) &&
01838         ((!LegalOperations && !LN0->isVolatile()) ||
01839          TLI.isLoadExtLegal(ISD::ZEXTLOAD, EVT))) {
01840       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, N0.getDebugLoc(), VT,
01841                                        LN0->getChain(), LN0->getBasePtr(),
01842                                        LN0->getSrcValue(),
01843                                        LN0->getSrcValueOffset(), EVT,
01844                                        LN0->isVolatile(), LN0->getAlignment());
01845       AddToWorkList(N);
01846       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
01847       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
01848     }
01849   }
01850   // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
01851   if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
01852       N0.hasOneUse()) {
01853     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
01854     EVT EVT = LN0->getMemoryVT();
01855     // If we zero all the possible extended bits, then we can turn this into
01856     // a zextload if we are running before legalize or the operation is legal.
01857     unsigned BitWidth = N1.getValueSizeInBits();
01858     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
01859                                      BitWidth - EVT.getSizeInBits())) &&
01860         ((!LegalOperations && !LN0->isVolatile()) ||
01861          TLI.isLoadExtLegal(ISD::ZEXTLOAD, EVT))) {
01862       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, N0.getDebugLoc(), VT,
01863                                        LN0->getChain(),
01864                                        LN0->getBasePtr(), LN0->getSrcValue(),
01865                                        LN0->getSrcValueOffset(), EVT,
01866                                        LN0->isVolatile(), LN0->getAlignment());
01867       AddToWorkList(N);
01868       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
01869       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
01870     }
01871   }
01872 
01873   // fold (and (load x), 255) -> (zextload x, i8)
01874   // fold (and (extload x, i16), 255) -> (zextload x, i8)
01875   if (N1C && N0.getOpcode() == ISD::LOAD) {
01876     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
01877     if (LN0->getExtensionType() != ISD::SEXTLOAD &&
01878         LN0->isUnindexed() && N0.hasOneUse() &&
01879         // Do not change the width of a volatile load.
01880         !LN0->isVolatile()) {
01881       EVT ExtVT = MVT::Other;
01882       uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
01883       if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue()))
01884         ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
01885 
01886       EVT LoadedVT = LN0->getMemoryVT();
01887 
01888       // Do not generate loads of non-round integer types since these can
01889       // be expensive (and would be wrong if the type is not byte sized).
01890       if (ExtVT != MVT::Other && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
01891           (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
01892         EVT PtrType = N0.getOperand(1).getValueType();
01893 
01894         // For big endian targets, we need to add an offset to the pointer to
01895         // load the correct bytes.  For little endian systems, we merely need to
01896         // read fewer bytes from the same pointer.
01897         unsigned LVTStoreBytes = LoadedVT.getStoreSizeInBits()/8;
01898         unsigned EVTStoreBytes = ExtVT.getStoreSizeInBits()/8;
01899         unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
01900         unsigned Alignment = LN0->getAlignment();
01901         SDValue NewPtr = LN0->getBasePtr();
01902 
01903         if (TLI.isBigEndian()) {
01904           NewPtr = DAG.getNode(ISD::ADD, LN0->getDebugLoc(), PtrType,
01905                                NewPtr, DAG.getConstant(PtrOff, PtrType));
01906           Alignment = MinAlign(Alignment, PtrOff);
01907         }
01908 
01909         AddToWorkList(NewPtr.getNode());
01910         SDValue Load =
01911           DAG.getExtLoad(ISD::ZEXTLOAD, LN0->getDebugLoc(), VT, LN0->getChain(),
01912                          NewPtr, LN0->getSrcValue(), LN0->getSrcValueOffset(),
01913                          ExtVT, LN0->isVolatile(), Alignment);
01914         AddToWorkList(N);
01915         CombineTo(N0.getNode(), Load, Load.getValue(1));
01916         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
01917       }
01918     }
01919   }
01920 
01921   return SDValue();
01922 }
01923 
01924 SDValue DAGCombiner::visitOR(SDNode *N) {
01925   SDValue N0 = N->getOperand(0);
01926   SDValue N1 = N->getOperand(1);
01927   SDValue LL, LR, RL, RR, CC0, CC1;
01928   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
01929   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
01930   EVT VT = N1.getValueType();
01931 
01932   // fold vector ops
01933   if (VT.isVector()) {
01934     SDValue FoldedVOp = SimplifyVBinOp(N);
01935     if (FoldedVOp.getNode()) return FoldedVOp;
01936   }
01937 
01938   // fold (or x, undef) -> -1
01939   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
01940     return DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), VT);
01941   // fold (or c1, c2) -> c1|c2
01942   if (N0C && N1C)
01943     return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C);
01944   // canonicalize constant to RHS
01945   if (N0C && !N1C)
01946     return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, N1, N0);
01947   // fold (or x, 0) -> x
01948   if (N1C && N1C->isNullValue())
01949     return N0;
01950   // fold (or x, -1) -> -1
01951   if (N1C && N1C->isAllOnesValue())
01952     return N1;
01953   // fold (or x, c) -> c iff (x & ~c) == 0
01954   if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
01955     return N1;
01956   // reassociate or
01957   SDValue ROR = ReassociateOps(ISD::OR, N->getDebugLoc(), N0, N1);
01958   if (ROR.getNode() != 0)
01959     return ROR;
01960   // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
01961   if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
01962              isa<ConstantSDNode>(N0.getOperand(1))) {
01963     ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
01964     return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
01965                        DAG.getNode(ISD::OR, N0.getDebugLoc(), VT,
01966                                    N0.getOperand(0), N1),
01967                        DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1));
01968   }
01969   // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
01970   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
01971     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
01972     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
01973 
01974     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
01975         LL.getValueType().isInteger()) {
01976       // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
01977       // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
01978       if (cast<ConstantSDNode>(LR)->isNullValue() &&
01979           (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
01980         SDValue ORNode = DAG.getNode(ISD::OR, LR.getDebugLoc(),
01981                                      LR.getValueType(), LL, RL);
01982         AddToWorkList(ORNode.getNode());
01983         return DAG.getSetCC(N->getDebugLoc(), VT, ORNode, LR, Op1);
01984       }
01985       // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
01986       // fold (or (setgt X, -1), (setgt Y  -1)) -> (setgt (and X, Y), -1)
01987       if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
01988           (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
01989         SDValue ANDNode = DAG.getNode(ISD::AND, LR.getDebugLoc(),
01990                                       LR.getValueType(), LL, RL);
01991         AddToWorkList(ANDNode.getNode());
01992         return DAG.getSetCC(N->getDebugLoc(), VT, ANDNode, LR, Op1);
01993       }
01994     }
01995     // canonicalize equivalent to ll == rl
01996     if (LL == RR && LR == RL) {
01997       Op1 = ISD::getSetCCSwappedOperands(Op1);
01998       std::swap(RL, RR);
01999     }
02000     if (LL == RL && LR == RR) {
02001       bool isInteger = LL.getValueType().isInteger();
02002       ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
02003       if (Result != ISD::SETCC_INVALID &&
02004           (!LegalOperations || TLI.isCondCodeLegal(Result, LL.getValueType())))
02005         return DAG.getSetCC(N->getDebugLoc(), N0.getValueType(),
02006                             LL, LR, Result);
02007     }
02008   }
02009 
02010   // Simplify: (or (op x...), (op y...))  -> (op (or x, y))
02011   if (N0.getOpcode() == N1.getOpcode()) {
02012     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
02013     if (Tmp.getNode()) return Tmp;
02014   }
02015 
02016   // (or (and X, C1), (and Y, C2))  -> (and (or X, Y), C3) if possible.
02017   if (N0.getOpcode() == ISD::AND &&
02018       N1.getOpcode() == ISD::AND &&
02019       N0.getOperand(1).getOpcode() == ISD::Constant &&
02020       N1.getOperand(1).getOpcode() == ISD::Constant &&
02021       // Don't increase # computations.
02022       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
02023     // We can only do this xform if we know that bits from X that are set in C2
02024     // but not in C1 are already zero.  Likewise for Y.
02025     const APInt &LHSMask =
02026       cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
02027     const APInt &RHSMask =
02028       cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
02029 
02030     if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
02031         DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
02032       SDValue X = DAG.getNode(ISD::OR, N0.getDebugLoc(), VT,
02033                               N0.getOperand(0), N1.getOperand(0));
02034       return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, X,
02035                          DAG.getConstant(LHSMask | RHSMask, VT));
02036     }
02037   }
02038 
02039   // See if this is some rotate idiom.
02040   if (SDNode *Rot = MatchRotate(N0, N1, N->getDebugLoc()))
02041     return SDValue(Rot, 0);
02042 
02043   return SDValue();
02044 }
02045 
02046 /// MatchRotateHalf - Match "(X shl/srl V1) & V2" where V2 may not be present.
02047 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
02048   if (Op.getOpcode() == ISD::AND) {
02049     if (isa<ConstantSDNode>(Op.getOperand(1))) {
02050       Mask = Op.getOperand(1);
02051       Op = Op.getOperand(0);
02052     } else {
02053       return false;
02054     }
02055   }
02056 
02057   if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
02058     Shift = Op;
02059     return true;
02060   }
02061 
02062   return false;
02063 }
02064 
02065 // MatchRotate - Handle an 'or' of two operands.  If this is one of the many
02066 // idioms for rotate, and if the target supports rotation instructions, generate
02067 // a rot[lr].
02068 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, DebugLoc DL) {
02069   // Must be a legal type.  Expanded 'n promoted things won't work with rotates.
02070   EVT VT = LHS.getValueType();
02071   if (!TLI.isTypeLegal(VT)) return 0;
02072 
02073   // The target must have at least one rotate flavor.
02074   bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
02075   bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
02076   if (!HasROTL && !HasROTR) return 0;
02077 
02078   // Match "(X shl/srl V1) & V2" where V2 may not be present.
02079   SDValue LHSShift;   // The shift.
02080   SDValue LHSMask;    // AND value if any.
02081   if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
02082     return 0; // Not part of a rotate.
02083 
02084   SDValue RHSShift;   // The shift.
02085   SDValue RHSMask;    // AND value if any.
02086   if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
02087     return 0; // Not part of a rotate.
02088 
02089   if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
02090     return 0;   // Not shifting the same value.
02091 
02092   if (LHSShift.getOpcode() == RHSShift.getOpcode())
02093     return 0;   // Shifts must disagree.
02094 
02095   // Canonicalize shl to left side in a shl/srl pair.
02096   if (RHSShift.getOpcode() == ISD::SHL) {
02097     std::swap(LHS, RHS);
02098     std::swap(LHSShift, RHSShift);
02099     std::swap(LHSMask , RHSMask );
02100   }
02101 
02102   unsigned OpSizeInBits = VT.getSizeInBits();
02103   SDValue LHSShiftArg = LHSShift.getOperand(0);
02104   SDValue LHSShiftAmt = LHSShift.getOperand(1);
02105   SDValue RHSShiftAmt = RHSShift.getOperand(1);
02106 
02107   // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
02108   // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
02109   if (LHSShiftAmt.getOpcode() == ISD::Constant &&
02110       RHSShiftAmt.getOpcode() == ISD::Constant) {
02111     uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
02112     uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
02113     if ((LShVal + RShVal) != OpSizeInBits)
02114       return 0;
02115 
02116     SDValue Rot;
02117     if (HasROTL)
02118       Rot = DAG.getNode(ISD::ROTL, DL, VT, LHSShiftArg, LHSShiftAmt);
02119     else
02120       Rot = DAG.getNode(ISD::ROTR, DL, VT, LHSShiftArg, RHSShiftAmt);
02121 
02122     // If there is an AND of either shifted operand, apply it to the result.
02123     if (LHSMask.getNode() || RHSMask.getNode()) {
02124       APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
02125 
02126       if (LHSMask.getNode()) {
02127         APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
02128         Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
02129       }
02130       if (RHSMask.getNode()) {
02131         APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
02132         Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
02133       }
02134 
02135       Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT));
02136     }
02137 
02138     return Rot.getNode();
02139   }
02140 
02141   // If there is a mask here, and we have a variable shift, we can't be sure
02142   // that we're masking out the right stuff.
02143   if (LHSMask.getNode() || RHSMask.getNode())
02144     return 0;
02145 
02146   // fold (or (shl x, y), (srl x, (sub 32, y))) -> (rotl x, y)
02147   // fold (or (shl x, y), (srl x, (sub 32, y))) -> (rotr x, (sub 32, y))
02148   if (RHSShiftAmt.getOpcode() == ISD::SUB &&
02149       LHSShiftAmt == RHSShiftAmt.getOperand(1)) {
02150     if (ConstantSDNode *SUBC =
02151           dyn_cast<ConstantSDNode>(RHSShiftAmt.getOperand(0))) {
02152       if (SUBC->getAPIntValue() == OpSizeInBits) {
02153         if (HasROTL)
02154           return DAG.getNode(ISD::ROTL, DL, VT,
02155                              LHSShiftArg, LHSShiftAmt).getNode();
02156         else
02157           return DAG.getNode(ISD::ROTR, DL, VT,
02158                              LHSShiftArg, RHSShiftAmt).getNode();
02159       }
02160     }
02161   }
02162 
02163   // fold (or (shl x, (sub 32, y)), (srl x, r)) -> (rotr x, y)
02164   // fold (or (shl x, (sub 32, y)), (srl x, r)) -> (rotl x, (sub 32, y))
02165   if (LHSShiftAmt.getOpcode() == ISD::SUB &&
02166       RHSShiftAmt == LHSShiftAmt.getOperand(1)) {
02167     if (ConstantSDNode *SUBC =
02168           dyn_cast<ConstantSDNode>(LHSShiftAmt.getOperand(0))) {
02169       if (SUBC->getAPIntValue() == OpSizeInBits) {
02170         if (HasROTR)
02171           return DAG.getNode(ISD::ROTR, DL, VT,
02172                              LHSShiftArg, RHSShiftAmt).getNode();
02173         else
02174           return DAG.getNode(ISD::ROTL, DL, VT,
02175                              LHSShiftArg, LHSShiftAmt).getNode();
02176       }
02177     }
02178   }
02179 
02180   // Look for sign/zext/any-extended or truncate cases:
02181   if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND
02182        || LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND
02183        || LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND
02184        || LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
02185       (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND
02186        || RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND
02187        || RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND
02188        || RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
02189     SDValue LExtOp0 = LHSShiftAmt.getOperand(0);
02190     SDValue RExtOp0 = RHSShiftAmt.getOperand(0);
02191     if (RExtOp0.getOpcode() == ISD::SUB &&
02192         RExtOp0.getOperand(1) == LExtOp0) {
02193       // fold (or (shl x, (*ext y)), (srl x, (*ext (sub 32, y)))) ->
02194       //   (rotl x, y)
02195       // fold (or (shl x, (*ext y)), (srl x, (*ext (sub 32, y)))) ->
02196       //   (rotr x, (sub 32, y))
02197       if (ConstantSDNode *SUBC =
02198             dyn_cast<ConstantSDNode>(RExtOp0.getOperand(0))) {
02199         if (SUBC->getAPIntValue() == OpSizeInBits) {
02200           return DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
02201                              LHSShiftArg,
02202                              HasROTL ? LHSShiftAmt : RHSShiftAmt).getNode();
02203         }
02204       }
02205     } else if (LExtOp0.getOpcode() == ISD::SUB &&
02206                RExtOp0 == LExtOp0.getOperand(1)) {
02207       // fold (or (shl x, (*ext (sub 32, y))), (srl x, (*ext y))) ->
02208       //   (rotr x, y)
02209       // fold (or (shl x, (*ext (sub 32, y))), (srl x, (*ext y))) ->
02210       //   (rotl x, (sub 32, y))
02211       if (ConstantSDNode *SUBC =
02212             dyn_cast<ConstantSDNode>(LExtOp0.getOperand(0))) {
02213         if (SUBC->getAPIntValue() == OpSizeInBits) {
02214           return DAG.getNode(HasROTR ? ISD::ROTR : ISD::ROTL, DL, VT,
02215                              LHSShiftArg,
02216                              HasROTR ? RHSShiftAmt : LHSShiftAmt).getNode();
02217         }
02218       }
02219     }
02220   }
02221 
02222   return 0;
02223 }
02224 
02225 SDValue DAGCombiner::visitXOR(SDNode *N) {
02226   SDValue N0 = N->getOperand(0);
02227   SDValue N1 = N->getOperand(1);
02228   SDValue LHS, RHS, CC;
02229   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
02230   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
02231   EVT VT = N0.getValueType();
02232 
02233   // fold vector ops
02234   if (VT.isVector()) {
02235     SDValue FoldedVOp = SimplifyVBinOp(N);
02236     if (FoldedVOp.getNode()) return FoldedVOp;
02237   }
02238 
02239   // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
02240   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
02241     return DAG.getConstant(0, VT);
02242   // fold (xor x, undef) -> undef
02243   if (N0.getOpcode() == ISD::UNDEF)
02244     return N0;
02245   if (N1.getOpcode() == ISD::UNDEF)
02246     return N1;
02247   // fold (xor c1, c2) -> c1^c2
02248   if (N0C && N1C)
02249     return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
02250   // canonicalize constant to RHS
02251   if (N0C && !N1C)
02252     return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT, N1, N0);
02253   // fold (xor x, 0) -> x
02254   if (N1C && N1C->isNullValue())
02255     return N0;
02256   // reassociate xor
02257   SDValue RXOR = ReassociateOps(ISD::XOR, N->getDebugLoc(), N0, N1);
02258   if (RXOR.getNode() != 0)
02259     return RXOR;
02260 
02261   // fold !(x cc y) -> (x !cc y)
02262   if (N1C && N1C->getAPIntValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) {
02263     bool isInt = LHS.getValueType().isInteger();
02264     ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
02265                                                isInt);
02266 
02267     if (!LegalOperations || TLI.isCondCodeLegal(NotCC, LHS.getValueType())) {
02268       switch (N0.getOpcode()) {
02269       default:
02270         llvm_unreachable("Unhandled SetCC Equivalent!");
02271       case ISD::SETCC:
02272         return DAG.getSetCC(N->getDebugLoc(), VT, LHS, RHS, NotCC);
02273       case ISD::SELECT_CC:
02274         return DAG.getSelectCC(N->getDebugLoc(), LHS, RHS, N0.getOperand(2),
02275                                N0.getOperand(3), NotCC);
02276       }
02277     }
02278   }
02279 
02280   // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
02281   if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
02282       N0.getNode()->hasOneUse() &&
02283       isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
02284     SDValue V = N0.getOperand(0);
02285     V = DAG.getNode(ISD::XOR, N0.getDebugLoc(), V.getValueType(), V,
02286                     DAG.getConstant(1, V.getValueType()));
02287     AddToWorkList(V.getNode());
02288     return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT, V);
02289   }
02290 
02291   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
02292   if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
02293       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
02294     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
02295     if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
02296       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
02297       LHS = DAG.getNode(ISD::XOR, LHS.getDebugLoc(), VT, LHS, N1); // LHS = ~LHS
02298       RHS = DAG.getNode(ISD::XOR, RHS.getDebugLoc(), VT, RHS, N1); // RHS = ~RHS
02299       AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
02300       return DAG.getNode(NewOpcode, N->getDebugLoc(), VT, LHS, RHS);
02301     }
02302   }
02303   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
02304   if (N1C && N1C->isAllOnesValue() &&
02305       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
02306     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
02307     if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
02308       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
02309       LHS = DAG.getNode(ISD::XOR, LHS.getDebugLoc(), VT, LHS, N1); // LHS = ~LHS
02310       RHS = DAG.getNode(ISD::XOR, RHS.getDebugLoc(), VT, RHS, N1); // RHS = ~RHS
02311       AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
02312       return DAG.getNode(NewOpcode, N->getDebugLoc(), VT, LHS, RHS);
02313     }
02314   }
02315   // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
02316   if (N1C && N0.getOpcode() == ISD::XOR) {
02317     ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
02318     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
02319     if (N00C)
02320       return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT, N0.getOperand(1),
02321                          DAG.getConstant(N1C->getAPIntValue() ^
02322                                          N00C->getAPIntValue(), VT));
02323     if (N01C)
02324       return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT, N0.getOperand(0),
02325                          DAG.getConstant(N1C->getAPIntValue() ^
02326                                          N01C->getAPIntValue(), VT));
02327   }
02328   // fold (xor x, x) -> 0
02329   if (N0 == N1) {
02330     if (!VT.isVector()) {
02331       return DAG.getConstant(0, VT);
02332     } else if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT)){
02333       // Produce a vector of zeros.
02334       SDValue El = DAG.getConstant(0, VT.getVectorElementType());
02335       std::vector<SDValue> Ops(VT.getVectorNumElements(), El);
02336       return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(), VT,
02337                          &Ops[0], Ops.size());
02338     }
02339   }
02340 
02341   // Simplify: xor (op x...), (op y...)  -> (op (xor x, y))
02342   if (N0.getOpcode() == N1.getOpcode()) {
02343     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
02344     if (Tmp.getNode()) return Tmp;
02345   }
02346 
02347   // Simplify the expression using non-local knowledge.
02348   if (!VT.isVector() &&
02349       SimplifyDemandedBits(SDValue(N, 0)))
02350     return SDValue(N, 0);
02351 
02352   return SDValue();
02353 }
02354 
02355 /// visitShiftByConstant - Handle transforms common to the three shifts, when
02356 /// the shift amount is a constant.
02357 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, unsigned Amt) {
02358   SDNode *LHS = N->getOperand(0).getNode();
02359   if (!LHS->hasOneUse()) return SDValue();
02360 
02361   // We want to pull some binops through shifts, so that we have (and (shift))
02362   // instead of (shift (and)), likewise for add, or, xor, etc.  This sort of
02363   // thing happens with address calculations, so it's important to canonicalize
02364   // it.
02365   bool HighBitSet = false;  // Can we transform this if the high bit is set?
02366 
02367   switch (LHS->getOpcode()) {
02368   default: return SDValue();
02369   case ISD::OR:
02370   case ISD::XOR:
02371     HighBitSet = false; // We can only transform sra if the high bit is clear.
02372     break;
02373   case ISD::AND:
02374     HighBitSet = true;  // We can only transform sra if the high bit is set.
02375     break;
02376   case ISD::ADD:
02377     if (N->getOpcode() != ISD::SHL)
02378       return SDValue(); // only shl(add) not sr[al](add).
02379     HighBitSet = false; // We can only transform sra if the high bit is clear.
02380     break;
02381   }
02382 
02383   // We require the RHS of the binop to be a constant as well.
02384   ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
02385   if (!BinOpCst) return SDValue();
02386 
02387   // FIXME: disable this unless the input to the binop is a shift by a constant.
02388   // If it is not a shift, it pessimizes some common cases like:
02389   //
02390   //    void foo(int *X, int i) { X[i & 1235] = 1; }
02391   //    int bar(int *X, int i) { return X[i & 255]; }
02392   SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
02393   if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
02394        BinOpLHSVal->getOpcode() != ISD::SRA &&
02395        BinOpLHSVal->getOpcode() != ISD::SRL) ||
02396       !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
02397     return SDValue();
02398 
02399   EVT VT = N->getValueType(0);
02400 
02401   // If this is a signed shift right, and the high bit is modified by the
02402   // logical operation, do not perform the transformation. The highBitSet
02403   // boolean indicates the value of the high bit of the constant which would
02404   // cause it to be modified for this operation.
02405   if (N->getOpcode() == ISD::SRA) {
02406     bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
02407     if (BinOpRHSSignSet != HighBitSet)
02408       return SDValue();
02409   }
02410 
02411   // Fold the constants, shifting the binop RHS by the shift amount.
02412   SDValue NewRHS = DAG.getNode(N->getOpcode(), LHS->getOperand(1).getDebugLoc(),
02413                                N->getValueType(0),
02414                                LHS->getOperand(1), N->getOperand(1));
02415 
02416   // Create the new shift.
02417   SDValue NewShift = DAG.getNode(N->getOpcode(), LHS->getOperand(0).getDebugLoc(),
02418                                  VT, LHS->getOperand(0), N->getOperand(1));
02419 
02420   // Create the new binop.
02421   return DAG.getNode(LHS->getOpcode(), N->getDebugLoc(), VT, NewShift, NewRHS);
02422 }
02423 
02424 SDValue DAGCombiner::visitSHL(SDNode *N) {
02425   SDValue N0 = N->getOperand(0);
02426   SDValue N1 = N->getOperand(1);
02427   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
02428   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
02429   EVT VT = N0.getValueType();
02430   unsigned OpSizeInBits = VT.getSizeInBits();
02431 
02432   // fold (shl c1, c2) -> c1<<c2
02433   if (N0C && N1C)
02434     return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
02435   // fold (shl 0, x) -> 0
02436   if (N0C && N0C->isNullValue())
02437     return N0;
02438   // fold (shl x, c >= size(x)) -> undef
02439   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
02440     return DAG.getUNDEF(VT);
02441   // fold (shl x, 0) -> x
02442   if (N1C && N1C->isNullValue())
02443     return N0;
02444   // if (shl x, c) is known to be zero, return 0
02445   if (DAG.MaskedValueIsZero(SDValue(N, 0),
02446                             APInt::getAllOnesValue(VT.getSizeInBits())))
02447     return DAG.getConstant(0, VT);
02448   // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
02449   if (N1.getOpcode() == ISD::TRUNCATE &&
02450       N1.getOperand(0).getOpcode() == ISD::AND &&
02451       N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
02452     SDValue N101 = N1.getOperand(0).getOperand(1);
02453     if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
02454       EVT TruncVT = N1.getValueType();
02455       SDValue N100 = N1.getOperand(0).getOperand(0);
02456       APInt TruncC = N101C->getAPIntValue();
02457       TruncC.trunc(TruncVT.getSizeInBits());
02458       return DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, N0,
02459                          DAG.getNode(ISD::AND, N->getDebugLoc(), TruncVT,
02460                                      DAG.getNode(ISD::TRUNCATE,
02461                                                  N->getDebugLoc(),
02462                                                  TruncVT, N100),
02463                                      DAG.getConstant(TruncC, TruncVT)));
02464     }
02465   }
02466 
02467   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
02468     return SDValue(N, 0);
02469 
02470   // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
02471   if (N1C && N0.getOpcode() == ISD::SHL &&
02472       N0.getOperand(1).getOpcode() == ISD::Constant) {
02473     uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
02474     uint64_t c2 = N1C->getZExtValue();
02475     if (c1 + c2 > OpSizeInBits)
02476       return DAG.getConstant(0, VT);
02477     return DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, N0.getOperand(0),
02478                        DAG.getConstant(c1 + c2, N1.getValueType()));
02479   }
02480   // fold (shl (srl x, c1), c2) -> (shl (and x, (shl -1, c1)), (sub c2, c1)) or
02481   //                               (srl (and x, (shl -1, c1)), (sub c1, c2))
02482   if (N1C && N0.getOpcode() == ISD::SRL &&
02483       N0.getOperand(1).getOpcode() == ISD::Constant) {
02484     uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
02485     if (c1 < VT.getSizeInBits()) {
02486       uint64_t c2 = N1C->getZExtValue();
02487       SDValue HiBitsMask =
02488         DAG.getConstant(APInt::getHighBitsSet(VT.getSizeInBits(),
02489                                               VT.getSizeInBits() - c1),
02490                         VT);
02491       SDValue Mask = DAG.getNode(ISD::AND, N0.getDebugLoc(), VT,
02492                                  N0.getOperand(0),
02493                                  HiBitsMask);
02494       if (c2 > c1)
02495         return DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, Mask,
02496                            DAG.getConstant(c2-c1, N1.getValueType()));
02497       else
02498         return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, Mask,
02499                            DAG.getConstant(c1-c2, N1.getValueType()));
02500     }
02501   }
02502   // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
02503   if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
02504     SDValue HiBitsMask =
02505       DAG.getConstant(APInt::getHighBitsSet(VT.getSizeInBits(),
02506                                             VT.getSizeInBits() -
02507                                               N1C->getZExtValue()),
02508                       VT);
02509     return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0.getOperand(0),
02510                        HiBitsMask);
02511   }
02512 
02513   return N1C ? visitShiftByConstant(N, N1C->getZExtValue()) : SDValue();
02514 }
02515 
02516 SDValue DAGCombiner::visitSRA(SDNode *N) {
02517   SDValue N0 = N->getOperand(0);
02518   SDValue N1 = N->getOperand(1);
02519   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
02520   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
02521   EVT VT = N0.getValueType();
02522 
02523   // fold (sra c1, c2) -> (sra c1, c2)
02524   if (N0C && N1C)
02525     return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
02526   // fold (sra 0, x) -> 0
02527   if (N0C && N0C->isNullValue())
02528     return N0;
02529   // fold (sra -1, x) -> -1
02530   if (N0C && N0C->isAllOnesValue())
02531     return N0;
02532   // fold (sra x, (setge c, size(x))) -> undef
02533   if (N1C && N1C->getZExtValue() >= VT.getSizeInBits())
02534     return DAG.getUNDEF(VT);
02535   // fold (sra x, 0) -> x
02536   if (N1C && N1C->isNullValue())
02537     return N0;
02538   // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
02539   // sext_inreg.
02540   if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
02541     unsigned LowBits = VT.getSizeInBits() - (unsigned)N1C->getZExtValue();
02542     EVT EVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
02543     if ((!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, EVT)))
02544       return DAG.getNode(ISD::SIGN_EXTEND_INREG, N->getDebugLoc(), VT,
02545                          N0.getOperand(0), DAG.getValueType(EVT));
02546   }
02547 
02548   // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
02549   if (N1C && N0.getOpcode() == ISD::SRA) {
02550     if (ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
02551       unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
02552       if (Sum >= VT.getSizeInBits()) Sum = VT.getSizeInBits()-1;
02553       return DAG.getNode(ISD::SRA, N->getDebugLoc(), VT, N0.getOperand(0),
02554                          DAG.getConstant(Sum, N1C->getValueType(0)));
02555     }
02556   }
02557 
02558   // fold (sra (shl X, m), (sub result_size, n))
02559   // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
02560   // result_size - n != m.
02561   // If truncate is free for the target sext(shl) is likely to result in better
02562   // code.
02563   if (N0.getOpcode() == ISD::SHL) {
02564     // Get the two constanst of the shifts, CN0 = m, CN = n.
02565     const ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
02566     if (N01C && N1C) {
02567       // Determine what the truncate's result bitsize and type would be.
02568       unsigned VTValSize = VT.getSizeInBits();
02569       EVT TruncVT =
02570         EVT::getIntegerVT(*DAG.getContext(), VTValSize - N1C->getZExtValue());
02571       // Determine the residual right-shift amount.
02572       signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
02573 
02574       // If the shift is not a no-op (in which case this should be just a sign
02575       // extend already), the truncated to type is legal, sign_extend is legal
02576       // on that type, and the the truncate to that type is both legal and free,
02577       // perform the transform.
02578       if ((ShiftAmt > 0) &&
02579           TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
02580           TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
02581           TLI.isTruncateFree(VT, TruncVT)) {
02582 
02583           SDValue Amt = DAG.getConstant(ShiftAmt, getShiftAmountTy());
02584           SDValue Shift = DAG.getNode(ISD::SRL, N0.getDebugLoc(), VT,
02585                                       N0.getOperand(0), Amt);
02586           SDValue Trunc = DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(), TruncVT,
02587                                       Shift);
02588           return DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(),
02589                              N->getValueType(0), Trunc);
02590       }
02591     }
02592   }
02593 
02594   // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
02595   if (N1.getOpcode() == ISD::TRUNCATE &&
02596       N1.getOperand(0).getOpcode() == ISD::AND &&
02597       N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
02598     SDValue N101 = N1.getOperand(0).getOperand(1);
02599     if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
02600       EVT TruncVT = N1.getValueType();
02601       SDValue N100 = N1.getOperand(0).getOperand(0);
02602       APInt TruncC = N101C->getAPIntValue();
02603       TruncC.trunc(TruncVT.getSizeInBits());
02604       return DAG.getNode(ISD::SRA, N->getDebugLoc(), VT, N0,
02605                          DAG.getNode(ISD::AND, N->getDebugLoc(),
02606                                      TruncVT,
02607                                      DAG.getNode(ISD::TRUNCATE,
02608                                                  N->getDebugLoc(),
02609                                                  TruncVT, N100),
02610                                      DAG.getConstant(TruncC, TruncVT)));
02611     }
02612   }
02613 
02614   // Simplify, based on bits shifted out of the LHS.
02615   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
02616     return SDValue(N, 0);
02617 
02618 
02619   // If the sign bit is known to be zero, switch this to a SRL.
02620   if (DAG.SignBitIsZero(N0))
02621     return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0, N1);
02622 
02623   return N1C ? visitShiftByConstant(N, N1C->getZExtValue()) : SDValue();
02624 }
02625 
02626 SDValue DAGCombiner::visitSRL(SDNode *N) {
02627   SDValue N0 = N->getOperand(0);
02628   SDValue N1 = N->getOperand(1);
02629   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
02630   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
02631   EVT VT = N0.getValueType();
02632   unsigned OpSizeInBits = VT.getSizeInBits();
02633 
02634   // fold (srl c1, c2) -> c1 >>u c2
02635   if (N0C && N1C)
02636     return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C);
02637   // fold (srl 0, x) -> 0
02638   if (N0C && N0C->isNullValue())
02639     return N0;
02640   // fold (srl x, c >= size(x)) -> undef
02641   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
02642     return DAG.getUNDEF(VT);
02643   // fold (srl x, 0) -> x
02644   if (N1C && N1C->isNullValue())
02645     return N0;
02646   // if (srl x, c) is known to be zero, return 0
02647   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
02648                                    APInt::getAllOnesValue(OpSizeInBits)))
02649     return DAG.getConstant(0, VT);
02650 
02651   // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
02652   if (N1C && N0.getOpcode() == ISD::SRL &&
02653       N0.getOperand(1).getOpcode() == ISD::Constant) {
02654     uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
02655     uint64_t c2 = N1C->getZExtValue();
02656     if (c1 + c2 > OpSizeInBits)
02657       return DAG.getConstant(0, VT);
02658     return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0.getOperand(0),
02659                        DAG.getConstant(c1 + c2, N1.getValueType()));
02660   }
02661 
02662   // fold (srl (anyextend x), c) -> (anyextend (srl x, c))
02663   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
02664     // Shifting in all undef bits?
02665     EVT SmallVT = N0.getOperand(0).getValueType();
02666     if (N1C->getZExtValue() >= SmallVT.getSizeInBits())
02667       return DAG.getUNDEF(VT);
02668 
02669     SDValue SmallShift = DAG.getNode(ISD::SRL, N0.getDebugLoc(), SmallVT,
02670                                      N0.getOperand(0), N1);
02671     AddToWorkList(SmallShift.getNode());
02672     return DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, SmallShift);
02673   }
02674 
02675   // fold (srl (sra X, Y), 31) -> (srl X, 31).  This srl only looks at the sign
02676   // bit, which is unmodified by sra.
02677   if (N1C && N1C->getZExtValue() + 1 == VT.getSizeInBits()) {
02678     if (N0.getOpcode() == ISD::SRA)
02679       return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0.getOperand(0), N1);
02680   }
02681 
02682   // fold (srl (ctlz x), "5") -> x  iff x has one bit set (the low bit).
02683   if (N1C && N0.getOpcode() == ISD::CTLZ &&
02684       N1C->getAPIntValue() == Log2_32(VT.getSizeInBits())) {
02685     APInt KnownZero, KnownOne;
02686     APInt Mask = APInt::getAllOnesValue(VT.getSizeInBits());
02687     DAG.ComputeMaskedBits(N0.getOperand(0), Mask, KnownZero, KnownOne);
02688 
02689     // If any of the input bits are KnownOne, then the input couldn't be all
02690     // zeros, thus the result of the srl will always be zero.
02691     if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
02692 
02693     // If all of the bits input the to ctlz node are known to be zero, then
02694     // the result of the ctlz is "32" and the result of the shift is one.
02695     APInt UnknownBits = ~KnownZero & Mask;
02696     if (UnknownBits == 0) return DAG.getConstant(1, VT);
02697 
02698     // Otherwise, check to see if there is exactly one bit input to the ctlz.
02699     if ((UnknownBits & (UnknownBits - 1)) == 0) {
02700       // Okay, we know that only that the single bit specified by UnknownBits
02701       // could be set on input to the CTLZ node. If this bit is set, the SRL
02702       // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
02703       // to an SRL/XOR pair, which is likely to simplify more.
02704       unsigned ShAmt = UnknownBits.countTrailingZeros();
02705       SDValue Op = N0.getOperand(0);
02706 
02707       if (ShAmt) {
02708         Op = DAG.getNode(ISD::SRL, N0.getDebugLoc(), VT, Op,
02709                          DAG.getConstant(ShAmt, getShiftAmountTy()));
02710         AddToWorkList(Op.getNode());
02711       }
02712 
02713       return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT,
02714                          Op, DAG.getConstant(1, VT));
02715     }
02716   }
02717 
02718   // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
02719   if (N1.getOpcode() == ISD::TRUNCATE &&
02720       N1.getOperand(0).getOpcode() == ISD::AND &&
02721       N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
02722     SDValue N101 = N1.getOperand(0).getOperand(1);
02723     if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
02724       EVT TruncVT = N1.getValueType();
02725       SDValue N100 = N1.getOperand(0).getOperand(0);
02726       APInt TruncC = N101C->getAPIntValue();
02727       TruncC.trunc(TruncVT.getSizeInBits());
02728       return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0,
02729                          DAG.getNode(ISD::AND, N->getDebugLoc(),
02730                                      TruncVT,
02731                                      DAG.getNode(ISD::TRUNCATE,
02732                                                  N->getDebugLoc(),
02733                                                  TruncVT, N100),
02734                                      DAG.getConstant(TruncC, TruncVT)));
02735     }
02736   }
02737 
02738   // fold operands of srl based on knowledge that the low bits are not
02739   // demanded.
02740   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
02741     return SDValue(N, 0);
02742 
02743   return N1C ? visitShiftByConstant(N, N1C->getZExtValue()) : SDValue();
02744 }
02745 
02746 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
02747   SDValue N0 = N->getOperand(0);
02748   EVT VT = N->getValueType(0);
02749 
02750   // fold (ctlz c1) -> c2
02751   if (isa<ConstantSDNode>(N0))
02752     return DAG.getNode(ISD::CTLZ, N->getDebugLoc(), VT, N0);
02753   return SDValue();
02754 }
02755 
02756 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
02757   SDValue N0 = N->getOperand(0);
02758   EVT VT = N->getValueType(0);
02759 
02760   // fold (cttz c1) -> c2
02761   if (isa<ConstantSDNode>(N0))
02762     return DAG.getNode(ISD::CTTZ, N->getDebugLoc(), VT, N0);
02763   return SDValue();
02764 }
02765 
02766 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
02767   SDValue N0 = N->getOperand(0);
02768   EVT VT = N->getValueType(0);
02769 
02770   // fold (ctpop c1) -> c2
02771   if (isa<ConstantSDNode>(N0))
02772     return DAG.getNode(ISD::CTPOP, N->getDebugLoc(), VT, N0);
02773   return SDValue();
02774 }
02775 
02776 SDValue DAGCombiner::visitSELECT(SDNode *N) {
02777   SDValue N0 = N->getOperand(0);
02778   SDValue N1 = N->getOperand(1);
02779   SDValue N2 = N->getOperand(2);
02780   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
02781   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
02782   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
02783   EVT VT = N->getValueType(0);
02784   EVT VT0 = N0.getValueType();
02785 
02786   // fold (select C, X, X) -> X
02787   if (N1 == N2)
02788     return N1;
02789   // fold (select true, X, Y) -> X
02790   if (N0C && !N0C->isNullValue())
02791     return N1;
02792   // fold (select false, X, Y) -> Y
02793   if (N0C && N0C->isNullValue())
02794     return N2;
02795   // fold (select C, 1, X) -> (or C, X)
02796   if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
02797     return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, N0, N2);
02798   // fold (select C, 0, 1) -> (xor C, 1)
02799   if (VT.isInteger() &&
02800       (VT0 == MVT::i1 ||
02801        (VT0.isInteger() &&
02802         TLI.getBooleanContents() == TargetLowering::ZeroOrOneBooleanContent)) &&
02803       N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
02804     SDValue XORNode;
02805     if (VT == VT0)
02806       return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT0,
02807                          N0, DAG.getConstant(1, VT0));
02808     XORNode = DAG.getNode(ISD::XOR, N0.getDebugLoc(), VT0,
02809                           N0, DAG.getConstant(1, VT0));
02810     AddToWorkList(XORNode.getNode());
02811     if (VT.bitsGT(VT0))
02812       return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT, XORNode);
02813     return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, XORNode);
02814   }
02815   // fold (select C, 0, X) -> (and (not C), X)
02816   if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
02817     SDValue NOTNode = DAG.getNOT(N0.getDebugLoc(), N0, VT);
02818     AddToWorkList(NOTNode.getNode());
02819     return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, NOTNode, N2);
02820   }
02821   // fold (select C, X, 1) -> (or (not C), X)
02822   if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
02823     SDValue NOTNode = DAG.getNOT(N0.getDebugLoc(), N0, VT);
02824     AddToWorkList(NOTNode.getNode());
02825     return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, NOTNode, N1);
02826   }
02827   // fold (select C, X, 0) -> (and C, X)
02828   if (VT == MVT::i1 && N2C && N2C->isNullValue())
02829     return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0, N1);
02830   // fold (select X, X, Y) -> (or X, Y)
02831   // fold (select X, 1, Y) -> (or X, Y)
02832   if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
02833     return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, N0, N2);
02834   // fold (select X, Y, X) -> (and X, Y)
02835   // fold (select X, Y, 0) -> (and X, Y)
02836   if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
02837     return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0, N1);
02838 
02839   // If we can fold this based on the true/false value, do so.
02840   if (SimplifySelectOps(N, N1, N2))
02841     return SDValue(N, 0);  // Don't revisit N.
02842 
02843   // fold selects based on a setcc into other things, such as min/max/abs
02844   if (N0.getOpcode() == ISD::SETCC) {
02845     // FIXME:
02846     // Check against MVT::Other for SELECT_CC, which is a workaround for targets
02847     // having to say they don't support SELECT_CC on every type the DAG knows
02848     // about, since there is no way to mark an opcode illegal at all value types
02849     if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other) &&
02850         TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT))
02851       return DAG.getNode(ISD::SELECT_CC, N->getDebugLoc(), VT,
02852                          N0.getOperand(0), N0.getOperand(1),
02853                          N1, N2, N0.getOperand(2));
02854     return SimplifySelect(N->getDebugLoc(), N0, N1, N2);
02855   }
02856 
02857   return SDValue();
02858 }
02859 
02860 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
02861   SDValue N0 = N->getOperand(0);
02862   SDValue N1 = N->getOperand(1);
02863   SDValue N2 = N->getOperand(2);
02864   SDValue N3 = N->getOperand(3);
02865   SDValue N4 = N->getOperand(4);
02866   ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
02867 
02868   // fold select_cc lhs, rhs, x, x, cc -> x
02869   if (N2 == N3)
02870     return N2;
02871 
02872   // Determine if the condition we're dealing with is constant
02873   SDValue SCC = SimplifySetCC(TLI.getSetCCResultType(N0.getValueType()),
02874                               N0, N1, CC, N->getDebugLoc(), false);
02875   if (SCC.getNode()) AddToWorkList(SCC.getNode());
02876 
02877   if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode())) {
02878     if (!SCCC->isNullValue())
02879       return N2;    // cond always true -> true val
02880     else
02881       return N3;    // cond always false -> false val
02882   }
02883 
02884   // Fold to a simpler select_cc
02885   if (SCC.getNode() && SCC.getOpcode() == ISD::SETCC)
02886     return DAG.getNode(ISD::SELECT_CC, N->getDebugLoc(), N2.getValueType(),
02887                        SCC.getOperand(0), SCC.getOperand(1), N2, N3,
02888                        SCC.getOperand(2));
02889 
02890   // If we can fold this based on the true/false value, do so.
02891   if (SimplifySelectOps(N, N2, N3))
02892     return SDValue(N, 0);  // Don't revisit N.
02893 
02894   // fold select_cc into other things, such as min/max/abs
02895   return SimplifySelectCC(N->getDebugLoc(), N0, N1, N2, N3, CC);
02896 }
02897 
02898 SDValue DAGCombiner::visitSETCC(SDNode *N) {
02899   return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
02900                        cast<CondCodeSDNode>(N->getOperand(2))->get(),
02901                        N->getDebugLoc());
02902 }
02903 
02904 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
02905 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
02906 // transformation. Returns true if extension are possible and the above
02907 // mentioned transformation is profitable.
02908 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
02909                                     unsigned ExtOpc,
02910                                     SmallVector<SDNode*, 4> &ExtendNodes,
02911                                     const TargetLowering &TLI) {
02912   bool HasCopyToRegUses = false;
02913   bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
02914   for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
02915                             UE = N0.getNode()->use_end();
02916        UI != UE; ++UI) {
02917     SDNode *User = *UI;
02918     if (User == N)
02919       continue;
02920     if (UI.getUse().getResNo() != N0.getResNo())
02921       continue;
02922     // FIXME: Only extend SETCC N, N and SETCC N, c for now.
02923     if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
02924       ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
02925       if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
02926         // Sign bits will be lost after a zext.
02927         return false;
02928       bool Add = false;
02929       for (unsigned i = 0; i != 2; ++i) {
02930         SDValue UseOp = User->getOperand(i);
02931         if (UseOp == N0)
02932           continue;
02933         if (!isa<ConstantSDNode>(UseOp))
02934           return false;
02935         Add = true;
02936       }
02937       if (Add)
02938         ExtendNodes.push_back(User);
02939       continue;
02940     }
02941     // If truncates aren't free and there are users we can't
02942     // extend, it isn't worthwhile.
02943     if (!isTruncFree)
02944       return false;
02945     // Remember if this value is live-out.
02946     if (User->getOpcode() == ISD::CopyToReg)
02947       HasCopyToRegUses = true;
02948   }
02949 
02950   if (HasCopyToRegUses) {
02951     bool BothLiveOut = false;
02952     for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
02953          UI != UE; ++UI) {
02954       SDUse &Use = UI.getUse();
02955       if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
02956         BothLiveOut = true;
02957         break;
02958       }
02959     }
02960     if (BothLiveOut)
02961       // Both unextended and extended values are live out. There had better be
02962       // good a reason for the transformation.
02963       return ExtendNodes.size();
02964   }
02965   return true;
02966 }
02967 
02968 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
02969   SDValue N0 = N->getOperand(0);
02970   EVT VT = N->getValueType(0);
02971 
02972   // fold (sext c1) -> c1
02973   if (isa<ConstantSDNode>(N0))
02974     return DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), VT, N0);
02975 
02976   // fold (sext (sext x)) -> (sext x)
02977   // fold (sext (aext x)) -> (sext x)
02978   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
02979     return DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), VT,
02980                        N0.getOperand(0));
02981 
02982   if (N0.getOpcode() == ISD::TRUNCATE) {
02983     // fold (sext (truncate (load x))) -> (sext (smaller load x))
02984     // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
02985     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
02986     if (NarrowLoad.getNode()) {
02987       if (NarrowLoad.getNode() != N0.getNode())
02988         CombineTo(N0.getNode(), NarrowLoad);
02989       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
02990     }
02991 
02992     // See if the value being truncated is already sign extended.  If so, just
02993     // eliminate the trunc/sext pair.
02994     SDValue Op = N0.getOperand(0);
02995     unsigned OpBits   = Op.getValueType().getSizeInBits();
02996     unsigned MidBits  = N0.getValueType().getSizeInBits();
02997     unsigned DestBits = VT.getSizeInBits();
02998     unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
02999 
03000     if (OpBits == DestBits) {
03001       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
03002       // bits, it is already ready.
03003       if (NumSignBits > DestBits-MidBits)
03004         return Op;
03005     } else if (OpBits < DestBits) {
03006       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
03007       // bits, just sext from i32.
03008       if (NumSignBits > OpBits-MidBits)
03009         return DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), VT, Op);
03010     } else {
03011       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
03012       // bits, just truncate to i32.
03013       if (NumSignBits > OpBits-MidBits)
03014         return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, Op);
03015     }
03016 
03017     // fold (sext (truncate x)) -> (sextinreg x).
03018     if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
03019                                                  N0.getValueType())) {
03020       if (Op.getValueType().bitsLT(VT))
03021         Op = DAG.getNode(ISD::ANY_EXTEND, N0.getDebugLoc(), VT, Op);
03022       else if (Op.getValueType().bitsGT(VT))
03023         Op = DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(), VT, Op);
03024       return DAG.getNode(ISD::SIGN_EXTEND_INREG, N->getDebugLoc(), VT, Op,
03025                          DAG.getValueType(N0.getValueType()));
03026     }
03027   }
03028 
03029   // fold (sext (load x)) -> (sext (truncate (sextload x)))
03030   if (ISD::isNON_EXTLoad(N0.getNode()) &&
03031       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
03032        TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()))) {
03033     bool DoXform = true;
03034     SmallVector<SDNode*, 4> SetCCs;
03035     if (!N0.hasOneUse())
03036       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
03037     if (DoXform) {
03038       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
03039       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, N->getDebugLoc(), VT,
03040                                        LN0->getChain(),
03041                                        LN0->getBasePtr(), LN0->getSrcValue(),
03042                                        LN0->getSrcValueOffset(),
03043                                        N0.getValueType(),
03044                                        LN0->isVolatile(), LN0->getAlignment());
03045       CombineTo(N, ExtLoad);
03046       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(),
03047                                   N0.getValueType(), ExtLoad);
03048       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
03049 
03050       // Extend SetCC uses if necessary.
03051       for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
03052         SDNode *SetCC = SetCCs[i];
03053         SmallVector<SDValue, 4> Ops;
03054 
03055         for (unsigned j = 0; j != 2; ++j) {
03056           SDValue SOp = SetCC->getOperand(j);
03057           if (SOp == Trunc)
03058             Ops.push_back(ExtLoad);
03059           else
03060             Ops.push_back(DAG.getNode(ISD::SIGN_EXTEND,
03061                                       N->getDebugLoc(), VT, SOp));
03062         }
03063 
03064         Ops.push_back(SetCC->getOperand(2));
03065         CombineTo(SetCC, DAG.getNode(ISD::SETCC, N->getDebugLoc(),
03066                                      SetCC->getValueType(0),
03067                                      &Ops[0], Ops.size()));
03068       }
03069 
03070       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
03071     }
03072   }
03073 
03074   // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
03075   // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
03076   if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
03077       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
03078     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
03079     EVT EVT = LN0->getMemoryVT();
03080     if ((!LegalOperations && !LN0->isVolatile()) ||
03081         TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT)) {
03082       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, N->getDebugLoc(), VT,
03083                                        LN0->getChain(),
03084                                        LN0->getBasePtr(), LN0->getSrcValue(),
03085                                        LN0->getSrcValueOffset(), EVT,
03086                                        LN0->isVolatile(), LN0->getAlignment());
03087       CombineTo(N, ExtLoad);
03088       CombineTo(N0.getNode(),
03089                 DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(),
03090                             N0.getValueType(), ExtLoad),
03091                 ExtLoad.getValue(1));
03092       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
03093     }
03094   }
03095 
03096   if (N0.getOpcode() == ISD::SETCC) {
03097     // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
03098     if (VT.isVector() &&
03099         // We know that the # elements of the results is the same as the
03100         // # elements of the compare (and the # elements of the compare result
03101         // for that matter).  Check to see that they are the same size.  If so,
03102         // we know that the element size of the sext'd result matches the
03103         // element size of the compare operands.
03104         VT.getSizeInBits() == N0.getOperand(0).getValueType().getSizeInBits() &&
03105       
03106         // Only do this before legalize for now.
03107         !LegalOperations) {
03108       return DAG.getVSetCC(N->getDebugLoc(), VT, N0.getOperand(0),
03109                            N0.getOperand(1),
03110                            cast<CondCodeSDNode>(N0.getOperand(2))->get());
03111     }
03112     
03113     // sext(setcc x, y, cc) -> (select_cc x, y, -1, 0, cc)
03114     SDValue NegOne =
03115       DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), VT);
03116     SDValue SCC =
03117       SimplifySelectCC(N->getDebugLoc(), N0.getOperand(0), N0.getOperand(1),
03118                        NegOne, DAG.getConstant(0, VT),
03119                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
03120     if (SCC.getNode()) return SCC;
03121   }
03122   
03123   
03124 
03125   // fold (sext x) -> (zext x) if the sign bit is known zero.
03126   if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
03127       DAG.SignBitIsZero(N0))
03128     return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT, N0);
03129 
03130   return SDValue();
03131 }
03132 
03133 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
03134   SDValue N0 = N->getOperand(0);
03135   EVT VT = N->getValueType(0);
03136 
03137   // fold (zext c1) -> c1
03138   if (isa<ConstantSDNode>(N0))
03139     return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT, N0);
03140   // fold (zext (zext x)) -> (zext x)
03141   // fold (zext (aext x)) -> (zext x)
03142   if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
03143     return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT,
03144                        N0.getOperand(0));
03145 
03146   // fold (zext (truncate (load x))) -> (zext (smaller load x))
03147   // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
03148   if (N0.getOpcode() == ISD::TRUNCATE) {
03149     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
03150     if (NarrowLoad.getNode()) {
03151       if (NarrowLoad.getNode() != N0.getNode())
03152         CombineTo(N0.getNode(), NarrowLoad);
03153       return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT, NarrowLoad);
03154     }
03155   }
03156 
03157   // fold (zext (truncate x)) -> (and x, mask)
03158   if (N0.getOpcode() == ISD::TRUNCATE &&
03159       (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
03160     SDValue Op = N0.getOperand(0);
03161     if (Op.getValueType().bitsLT(VT)) {
03162       Op = DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, Op);
03163     } else if (Op.getValueType().bitsGT(VT)) {
03164       Op = DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, Op);
03165     }
03166     return DAG.getZeroExtendInReg(Op, N->getDebugLoc(), N0.getValueType());
03167   }
03168 
03169   // Fold (zext (and (trunc x), cst)) -> (and x, cst),
03170   // if either of the casts is not free.
03171   if (N0.getOpcode() == ISD::AND &&
03172       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
03173       N0.getOperand(1).getOpcode() == ISD::Constant &&
03174       (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
03175                            N0.getValueType()) ||
03176        !TLI.isZExtFree(N0.getValueType(), VT))) {
03177     SDValue X = N0.getOperand(0).getOperand(0);
03178     if (X.getValueType().bitsLT(VT)) {
03179       X = DAG.getNode(ISD::ANY_EXTEND, X.getDebugLoc(), VT, X);
03180     } else if (X.getValueType().bitsGT(VT)) {
03181       X = DAG.getNode(ISD::TRUNCATE, X.getDebugLoc(), VT, X);
03182     }
03183     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
03184     Mask.zext(VT.getSizeInBits());
03185     return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
03186                        X, DAG.getConstant(Mask, VT));
03187   }
03188 
03189   // fold (zext (load x)) -> (zext (truncate (zextload x)))
03190   if (ISD::isNON_EXTLoad(N0.getNode()) &&
03191       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
03192        TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()))) {
03193     bool DoXform = true;
03194     SmallVector<SDNode*, 4> SetCCs;
03195     if (!N0.hasOneUse())
03196       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
03197     if (DoXform) {
03198       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
03199       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, N->getDebugLoc(), VT,
03200                                        LN0->getChain(),
03201                                        LN0->getBasePtr(), LN0->getSrcValue(),
03202                                        LN0->getSrcValueOffset(),
03203                                        N0.getValueType(),
03204                                        LN0->isVolatile(), LN0->getAlignment());
03205       CombineTo(N, ExtLoad);
03206       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(),
03207                                   N0.getValueType(), ExtLoad);
03208       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
03209 
03210       // Extend SetCC uses if necessary.
03211       for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
03212         SDNode *SetCC = SetCCs[i];
03213         SmallVector<SDValue, 4> Ops;
03214 
03215         for (unsigned j = 0; j != 2; ++j) {
03216           SDValue SOp = SetCC->getOperand(j);
03217           if (SOp == Trunc)
03218             Ops.push_back(ExtLoad);
03219           else
03220             Ops.push_back(DAG.getNode(ISD::ZERO_EXTEND,
03221                                       N->getDebugLoc(), VT, SOp));
03222         }
03223 
03224         Ops.push_back(SetCC->getOperand(2));
03225         CombineTo(SetCC, DAG.getNode(ISD::SETCC, N->getDebugLoc(),
03226                                      SetCC->getValueType(0),
03227                                      &Ops[0], Ops.size()));
03228       }
03229 
03230       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
03231     }
03232   }
03233 
03234   // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
03235   // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
03236   if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
03237       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
03238     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
03239     EVT EVT = LN0->getMemoryVT();
03240     if ((!LegalOperations && !LN0->isVolatile()) ||
03241         TLI.isLoadExtLegal(ISD::ZEXTLOAD, EVT)) {
03242       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, N->getDebugLoc(), VT,
03243                                        LN0->getChain(),
03244                                        LN0->getBasePtr(), LN0->getSrcValue(),
03245                                        LN0->getSrcValueOffset(), EVT,
03246                                        LN0->isVolatile(), LN0->getAlignment());
03247       CombineTo(N, ExtLoad);
03248       CombineTo(N0.getNode(),
03249                 DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(), N0.getValueType(),
03250                             ExtLoad),
03251                 ExtLoad.getValue(1));
03252       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
03253     }
03254   }
03255 
03256   // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
03257   if (N0.getOpcode() == ISD::SETCC) {
03258     SDValue SCC =
03259       SimplifySelectCC(N->getDebugLoc(), N0.getOperand(0), N0.getOperand(1),
03260                        DAG.getConstant(1, VT), DAG.getConstant(0, VT),
03261                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
03262     if (SCC.getNode()) return SCC;
03263   }
03264 
03265   return SDValue();
03266 }
03267 
03268 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
03269   SDValue N0 = N->getOperand(0);
03270   EVT VT = N->getValueType(0);
03271 
03272   // fold (aext c1) -> c1
03273   if (isa<ConstantSDNode>(N0))
03274     return DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, N0);
03275   // fold (aext (aext x)) -> (aext x)
03276   // fold (aext (zext x)) -> (zext x)
03277   // fold (aext (sext x)) -> (sext x)
03278   if (N0.getOpcode() == ISD::ANY_EXTEND  ||
03279       N0.getOpcode() == ISD::ZERO_EXTEND ||
03280       N0.getOpcode() == ISD::SIGN_EXTEND)
03281     return DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT, N0.getOperand(0));
03282 
03283   // fold (aext (truncate (load x))) -> (aext (smaller load x))
03284   // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
03285   if (N0.getOpcode() == ISD::TRUNCATE) {
03286     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
03287     if (NarrowLoad.getNode()) {
03288       if (NarrowLoad.getNode() != N0.getNode())
03289         CombineTo(N0.getNode(), NarrowLoad);
03290       return DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, NarrowLoad);
03291     }
03292   }
03293 
03294   // fold (aext (truncate x))
03295   if (N0.getOpcode() == ISD::TRUNCATE) {
03296     SDValue TruncOp = N0.getOperand(0);
03297     if (TruncOp.getValueType() == VT)
03298       return TruncOp; // x iff x size == zext size.
03299     if (TruncOp.getValueType().bitsGT(VT))
03300       return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, TruncOp);
03301     return DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, TruncOp);
03302   }
03303 
03304   // Fold (aext (and (trunc x), cst)) -> (and x, cst)
03305   // if the trunc is not free.
03306   if (N0.getOpcode() == ISD::AND &&
03307       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
03308       N0.getOperand(1).getOpcode() == ISD::Constant &&
03309       !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
03310                           N0.getValueType())) {
03311     SDValue X = N0.getOperand(0).getOperand(0);
03312     if (X.getValueType().bitsLT(VT)) {
03313       X = DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, X);
03314     } else if (X.getValueType().bitsGT(VT)) {
03315       X = DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, X);
03316     }
03317     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
03318     Mask.zext(VT.getSizeInBits());
03319     return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
03320                        X, DAG.getConstant(Mask, VT));
03321   }
03322 
03323   // fold (aext (load x)) -> (aext (truncate (extload x)))
03324   if (ISD::isNON_EXTLoad(N0.getNode()) &&
03325       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
03326        TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
03327     bool DoXform = true;
03328     SmallVector<SDNode*, 4> SetCCs;
03329     if (!N0.hasOneUse())
03330       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
03331     if (DoXform) {
03332       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
03333       SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, N->getDebugLoc(), VT,
03334                                        LN0->getChain(),
03335                                        LN0->getBasePtr(), LN0->getSrcValue(),
03336                                        LN0->getSrcValueOffset(),
03337                                        N0.getValueType(),
03338                                        LN0->isVolatile(), LN0->getAlignment());
03339       CombineTo(N, ExtLoad);
03340       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(),
03341                                   N0.getValueType(), ExtLoad);
03342       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
03343 
03344       // Extend SetCC uses if necessary.
03345       for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
03346         SDNode *SetCC = SetCCs[i];
03347         SmallVector<SDValue, 4> Ops;
03348 
03349         for (unsigned j = 0; j != 2; ++j) {
03350           SDValue SOp = SetCC->getOperand(j);
03351           if (SOp == Trunc)
03352             Ops.push_back(ExtLoad);
03353           else
03354             Ops.push_back(DAG.getNode(ISD::ANY_EXTEND,
03355                                       N->getDebugLoc(), VT, SOp));
03356         }
03357 
03358         Ops.push_back(SetCC->getOperand(2));
03359         CombineTo(SetCC, DAG.getNode(ISD::SETCC, N->getDebugLoc(),
03360                                      SetCC->getValueType(0),
03361                                      &Ops[0], Ops.size()));
03362       }
03363 
03364       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
03365     }
03366   }
03367 
03368   // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
03369   // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
03370   // fold (aext ( extload x)) -> (aext (truncate (extload  x)))
03371   if (N0.getOpcode() == ISD::LOAD &&
03372       !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
03373       N0.hasOneUse()) {
03374     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
03375     EVT EVT = LN0->getMemoryVT();
03376     SDValue ExtLoad = DAG.getExtLoad(LN0->getExtensionType(), N->getDebugLoc(),
03377                                      VT, LN0->getChain(), LN0->getBasePtr(),
03378                                      LN0->getSrcValue(),
03379                                      LN0->getSrcValueOffset(), EVT,
03380                                      LN0->isVolatile(), LN0->getAlignment());
03381     CombineTo(N, ExtLoad);
03382     CombineTo(N0.getNode(),
03383               DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(),
03384                           N0.getValueType(), ExtLoad),
03385               ExtLoad.getValue(1));
03386     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
03387   }
03388 
03389   // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
03390   if (N0.getOpcode() == ISD::SETCC) {
03391     SDValue SCC =
03392       SimplifySelectCC(N->getDebugLoc(), N0.getOperand(0), N0.getOperand(1),
03393                        DAG.getConstant(1, VT), DAG.getConstant(0, VT),
03394                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
03395     if (SCC.getNode())
03396       return SCC;
03397   }
03398 
03399   return SDValue();
03400 }
03401 
03402 /// GetDemandedBits - See if the specified operand can be simplified with the
03403 /// knowledge that only the bits specified by Mask are used.  If so, return the
03404 /// simpler operand, otherwise return a null SDValue.
03405 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
03406   switch (V.getOpcode()) {
03407   default: break;
03408   case ISD::OR:
03409   case ISD::XOR:
03410     // If the LHS or RHS don't contribute bits to the or, drop them.
03411     if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
03412       return V.getOperand(1);
03413     if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
03414       return V.getOperand(0);
03415     break;
03416   case ISD::SRL:
03417     // Only look at single-use SRLs.
03418     if (!V.getNode()->hasOneUse())
03419       break;
03420     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
03421       // See if we can recursively simplify the LHS.
03422       unsigned Amt = RHSC->getZExtValue();
03423 
03424       // Watch out for shift count overflow though.
03425       if (Amt >= Mask.getBitWidth()) break;
03426       APInt NewMask = Mask << Amt;
03427       SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
03428       if (SimplifyLHS.getNode())
03429         return DAG.getNode(ISD::SRL, V.getDebugLoc(), V.getValueType(),
03430                            SimplifyLHS, V.getOperand(1));
03431     }
03432   }
03433   return SDValue();
03434 }
03435 
03436 /// ReduceLoadWidth - If the result of a wider load is shifted to right of N
03437 /// bits and then truncated to a narrower type and where N is a multiple
03438 /// of number of bits of the narrower type, transform it to a narrower load
03439 /// from address + N / num of bits of new type. If the result is to be
03440 /// extended, also fold the extension to form a extending load.
03441 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
03442   unsigned Opc = N->getOpcode();
03443   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
03444   SDValue N0 = N->getOperand(0);
03445   EVT VT = N->getValueType(0);
03446   EVT ExtVT = VT;
03447 
03448   // This transformation isn't valid for vector loads.
03449   if (VT.isVector())
03450     return SDValue();
03451 
03452   // Special case: SIGN_EXTEND_INREG is basically truncating to EVT then
03453   // extended to VT.
03454   if (Opc == ISD::SIGN_EXTEND_INREG) {
03455     ExtType = ISD::SEXTLOAD;
03456     ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
03457     if (LegalOperations && !TLI.isLoadExtLegal(ISD::SEXTLOAD, ExtVT))
03458       return SDValue();
03459   }
03460 
03461   unsigned EVTBits = ExtVT.getSizeInBits();
03462   unsigned ShAmt = 0;
03463   if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
03464     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
03465       ShAmt = N01->getZExtValue();
03466       // Is the shift amount a multiple of size of VT?
03467       if ((ShAmt & (EVTBits-1)) == 0) {
03468         N0 = N0.getOperand(0);
03469         // Is the load width a multiple of size of VT?
03470         if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
03471           return SDValue();
03472       }
03473     }
03474   }
03475 
03476   // Do not generate loads of non-round integer types since these can
03477   // be expensive (and would be wrong if the type is not byte sized).
03478   if (isa<LoadSDNode>(N0) && N0.hasOneUse() && ExtVT.isRound() &&
03479       cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits() > EVTBits &&
03480       // Do not change the width of a volatile load.
03481       !cast<LoadSDNode>(N0)->isVolatile()) {
03482     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
03483     EVT PtrType = N0.getOperand(1).getValueType();
03484 
03485     // For big endian targets, we need to adjust the offset to the pointer to
03486     // load the correct bytes.
03487     if (TLI.isBigEndian()) {
03488       unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
03489       unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
03490       ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
03491     }
03492 
03493     uint64_t PtrOff =  ShAmt / 8;
03494     unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
03495     SDValue NewPtr = DAG.getNode(ISD::ADD, LN0->getDebugLoc(),
03496                                  PtrType, LN0->getBasePtr(),
03497                                  DAG.getConstant(PtrOff, PtrType));
03498     AddToWorkList(NewPtr.getNode());
03499 
03500     SDValue Load = (ExtType == ISD::NON_EXTLOAD)
03501       ? DAG.getLoad(VT, N0.getDebugLoc(), LN0->getChain(), NewPtr,
03502                     LN0->getSrcValue(), LN0->getSrcValueOffset() + PtrOff,
03503                     LN0->isVolatile(), NewAlign)
03504       : DAG.getExtLoad(ExtType, N0.getDebugLoc(), VT, LN0->getChain(), NewPtr,
03505                        LN0->getSrcValue(), LN0->getSrcValueOffset() + PtrOff,
03506                        ExtVT, LN0->isVolatile(), NewAlign);
03507 
03508     // Replace the old load's chain with the new load's chain.
03509     WorkListRemover DeadNodes(*this);
03510     DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1),
03511                                   &DeadNodes);
03512 
03513     // Return the new loaded value.
03514     return Load;
03515   }
03516 
03517   return SDValue();
03518 }
03519 
03520 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
03521   SDValue N0 = N->getOperand(0);
03522   SDValue N1 = N->getOperand(1);
03523   EVT VT = N->getValueType(0);
03524   EVT EVT = cast<VTSDNode>(N1)->getVT();
03525   unsigned VTBits = VT.getSizeInBits();
03526   unsigned EVTBits = EVT.getSizeInBits();
03527 
03528   // fold (sext_in_reg c1) -> c1
03529   if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
03530     return DAG.getNode(ISD::SIGN_EXTEND_INREG, N->getDebugLoc(), VT, N0, N1);
03531 
03532   // If the input is already sign extended, just drop the extension.
03533   if (DAG.ComputeNumSignBits(N0) >= VT.getSizeInBits()-EVTBits+1)
03534     return N0;
03535 
03536   // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
03537   if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
03538       EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT())) {
03539     return DAG.getNode(ISD::SIGN_EXTEND_INREG, N->getDebugLoc(), VT,
03540                        N0.getOperand(0), N1);
03541   }
03542 
03543   // fold (sext_in_reg (sext x)) -> (sext x)
03544   // fold (sext_in_reg (aext x)) -> (sext x)
03545   // if x is small enough.
03546   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
03547     SDValue N00 = N0.getOperand(0);
03548     if (N00.getValueType().getSizeInBits() < EVTBits)
03549       return DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), VT, N00, N1);
03550   }
03551 
03552   // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
03553   if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
03554     return DAG.getZeroExtendInReg(N0, N->getDebugLoc(), EVT);
03555 
03556   // fold operands of sext_in_reg based on knowledge that the top bits are not
03557   // demanded.
03558   if (SimplifyDemandedBits(SDValue(N, 0)))
03559     return SDValue(N, 0);
03560 
03561   // fold (sext_in_reg (load x)) -> (smaller sextload x)
03562   // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
03563   SDValue NarrowLoad = ReduceLoadWidth(N);
03564   if (NarrowLoad.getNode())
03565     return NarrowLoad;
03566 
03567   // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
03568   // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
03569   // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
03570   if (N0.getOpcode() == ISD::SRL) {
03571     if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
03572       if (ShAmt->getZExtValue()+EVTBits <= VT.getSizeInBits()) {
03573         // We can turn this into an SRA iff the input to the SRL is already sign
03574         // extended enough.
03575         unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
03576         if (VT.getSizeInBits()-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
03577           return DAG.getNode(ISD::SRA, N->getDebugLoc(), VT,
03578                              N0.getOperand(0), N0.getOperand(1));
03579       }
03580   }
03581 
03582   // fold (sext_inreg (extload x)) -> (sextload x)
03583   if (ISD::isEXTLoad(N0.getNode()) &&
03584       ISD::isUNINDEXEDLoad(N0.getNode()) &&
03585       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
03586       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
03587        TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
03588     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
03589     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, N->getDebugLoc(), VT,
03590                                      LN0->getChain(),
03591                                      LN0->getBasePtr(), LN0->getSrcValue(),
03592                                      LN0->getSrcValueOffset(), EVT,
03593                                      LN0->isVolatile(), LN0->getAlignment());
03594     CombineTo(N, ExtLoad);
03595     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
03596     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
03597   }
03598   // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
03599   if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
03600       N0.hasOneUse() &&
03601       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
03602       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
03603        TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
03604     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
03605     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, N->getDebugLoc(), VT,
03606                                      LN0->getChain(),
03607                                      LN0->getBasePtr(), LN0->getSrcValue(),
03608                                      LN0->getSrcValueOffset(), EVT,
03609                                      LN0->isVolatile(), LN0->getAlignment());
03610     CombineTo(N, ExtLoad);
03611     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
03612     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
03613   }
03614   return SDValue();
03615 }
03616 
03617 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
03618   SDValue N0 = N->getOperand(0);
03619   EVT VT = N->getValueType(0);
03620 
03621   // noop truncate
03622   if (N0.getValueType() == N->getValueType(0))
03623     return N0;
03624   // fold (truncate c1) -> c1
03625   if (isa<ConstantSDNode>(N0))
03626     return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, N0);
03627   // fold (truncate (truncate x)) -> (truncate x)
03628   if (N0.getOpcode() == ISD::TRUNCATE)
03629     return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, N0.getOperand(0));
03630   // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
03631   if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::SIGN_EXTEND||
03632       N0.getOpcode() == ISD::ANY_EXTEND) {
03633     if (N0.getOperand(0).getValueType().bitsLT(VT))
03634       // if the source is smaller than the dest, we still need an extend
03635       return DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT,
03636                          N0.getOperand(0));
03637     else if (N0.getOperand(0).getValueType().bitsGT(VT))
03638       // if the source is larger than the dest, than we just need the truncate
03639       return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, N0.getOperand(0));
03640     else
03641       // if the source and dest are the same type, we can drop both the extend
03642       // and the truncate
03643       return N0.getOperand(0);
03644   }
03645 
03646   // See if we can simplify the input to this truncate through knowledge that
03647   // only the low bits are being used.  For example "trunc (or (shl x, 8), y)"
03648   // -> trunc y
03649   SDValue Shorter =
03650     GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
03651                                              VT.getSizeInBits()));
03652   if (Shorter.getNode())
03653     return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, Shorter);
03654 
03655   // fold (truncate (load x)) -> (smaller load x)
03656   // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
03657   return ReduceLoadWidth(N);
03658 }
03659 
03660 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
03661   SDValue Elt = N->getOperand(i);
03662   if (Elt.getOpcode() != ISD::MERGE_VALUES)
03663     return Elt.getNode();
03664   return Elt.getOperand(Elt.getResNo()).getNode();
03665 }
03666 
03667 /// CombineConsecutiveLoads - build_pair (load, load) -> load
03668 /// if load locations are consecutive.
03669 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
03670   assert(N->getOpcode() == ISD::BUILD_PAIR);
03671 
03672   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
03673   LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
03674   if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse())
03675     return SDValue();
03676   EVT LD1VT = LD1->getValueType(0);
03677   const MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
03678 
03679   if (ISD::isNON_EXTLoad(LD2) &&
03680       LD2->hasOneUse() &&
03681       // If both are volatile this would reduce the number of volatile loads.
03682       // If one is volatile it might be ok, but play conservative and bail out.
03683       !LD1->isVolatile() &&
03684       !LD2->isVolatile() &&
03685       TLI.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1, MFI)) {
03686     unsigned Align = LD1->getAlignment();
03687     unsigned NewAlign = TLI.getTargetData()->
03688       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
03689 
03690     if (NewAlign <= Align &&
03691         (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
03692       return DAG.getLoad(VT, N->getDebugLoc(), LD1->getChain(),
03693                          LD1->getBasePtr(), LD1->getSrcValue(),
03694                          LD1->getSrcValueOffset(), false, Align);
03695   }
03696 
03697   return SDValue();
03698 }
03699 
03700 SDValue DAGCombiner::visitBIT_CONVERT(SDNode *N) {
03701   SDValue N0 = N->getOperand(0);
03702   EVT VT = N->getValueType(0);
03703 
03704   // If the input is a BUILD_VECTOR with all constant elements, fold this now.
03705   // Only do this before legalize, since afterward the target may be depending
03706   // on the bitconvert.
03707   // First check to see if this is all constant.
03708   if (!LegalTypes &&
03709       N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
03710       VT.isVector()) {
03711     bool isSimple = true;
03712     for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i)
03713       if (N0.getOperand(i).getOpcode() != ISD::UNDEF &&
03714           N0.getOperand(i).getOpcode() != ISD::Constant &&
03715           N0.getOperand(i).getOpcode() != ISD::ConstantFP) {
03716         isSimple = false;
03717         break;
03718       }
03719 
03720     EVT DestEltVT = N->getValueType(0).getVectorElementType();
03721     assert(!DestEltVT.isVector() &&
03722            "Element type of vector ValueType must not be vector!");
03723     if (isSimple)
03724       return ConstantFoldBIT_CONVERTofBUILD_VECTOR(N0.getNode(), DestEltVT);
03725   }
03726 
03727   // If the input is a constant, let getNode fold it.
03728   if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
03729     SDValue Res = DAG.getNode(ISD::BIT_CONVERT, N->getDebugLoc(), VT, N0);
03730     if (Res.getNode() != N) {
03731       if (!LegalOperations ||
03732           TLI.isOperationLegal(Res.getNode()->getOpcode(), VT))
03733         return Res;
03734 
03735       // Folding it resulted in an illegal node, and it's too late to
03736       // do that. Clean up the old node and forego the transformation.
03737       // Ideally this won't happen very often, because instcombine
03738       // and the earlier dagcombine runs (where illegal nodes are
03739       // permitted) should have folded most of them already.
03740       DAG.DeleteNode(Res.getNode());
03741     }
03742   }
03743 
03744   // (conv (conv x, t1), t2) -> (conv x, t2)
03745   if (N0.getOpcode() == ISD::BIT_CONVERT)
03746     return DAG.getNode(ISD::BIT_CONVERT, N->getDebugLoc(), VT,
03747                        N0.getOperand(0));
03748 
03749   // fold (conv (load x)) -> (load (conv*)x)
03750   // If the resultant load doesn't need a higher alignment than the original!
03751   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
03752       // Do not change the width of a volatile load.
03753       !cast<LoadSDNode>(N0)->isVolatile() &&
03754       (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT))) {
03755     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
03756     unsigned Align = TLI.getTargetData()->
03757       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
03758     unsigned OrigAlign = LN0->getAlignment();
03759 
03760     if (Align <= OrigAlign) {
03761       SDValue Load = DAG.getLoad(VT, N->getDebugLoc(), LN0->getChain(),
03762                                  LN0->getBasePtr(),
03763                                  LN0->getSrcValue(), LN0->getSrcValueOffset(),
03764                                  LN0->isVolatile(), OrigAlign);
03765       AddToWorkList(N);
03766       CombineTo(N0.getNode(),
03767                 DAG.getNode(ISD::BIT_CONVERT, N0.getDebugLoc(),
03768                             N0.getValueType(), Load),
03769                 Load.getValue(1));
03770       return Load;
03771     }
03772   }
03773 
03774   // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
03775   // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
03776   // This often reduces constant pool loads.
03777   if ((N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FABS) &&
03778       N0.getNode()->hasOneUse() && VT.isInteger() && !VT.isVector()) {
03779     SDValue NewConv = DAG.getNode(ISD::BIT_CONVERT, N0.getDebugLoc(), VT,
03780                                   N0.getOperand(0));
03781     AddToWorkList(NewConv.getNode());
03782 
03783     APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
03784     if (N0.getOpcode() == ISD::FNEG)
03785       return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT,
03786                          NewConv, DAG.getConstant(SignBit, VT));
03787     assert(N0.getOpcode() == ISD::FABS);
03788     return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
03789                        NewConv, DAG.getConstant(~SignBit, VT));
03790   }
03791 
03792   // fold (bitconvert (fcopysign cst, x)) ->
03793   //         (or (and (bitconvert x), sign), (and cst, (not sign)))
03794   // Note that we don't handle (copysign x, cst) because this can always be
03795   // folded to an fneg or fabs.
03796   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
03797       isa<ConstantFPSDNode>(N0.getOperand(0)) &&
03798       VT.isInteger() && !VT.isVector()) {
03799     unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
03800     EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
03801     if (TLI.isTypeLegal(IntXVT) || !LegalTypes) {
03802       SDValue X = DAG.getNode(ISD::BIT_CONVERT, N0.getDebugLoc(),
03803                               IntXVT, N0.getOperand(1));
03804       AddToWorkList(X.getNode());
03805 
03806       // If X has a different width than the result/lhs, sext it or truncate it.
03807       unsigned VTWidth = VT.getSizeInBits();
03808       if (OrigXWidth < VTWidth) {
03809         X = DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), VT, X);
03810         AddToWorkList(X.getNode());
03811       } else if (OrigXWidth > VTWidth) {
03812         // To get the sign bit in the right place, we have to shift it right
03813         // before truncating.
03814         X = DAG.getNode(ISD::SRL, X.getDebugLoc(),
03815                         X.getValueType(), X,
03816                         DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
03817         AddToWorkList(X.getNode());
03818         X = DAG.getNode(ISD::TRUNCATE, X.getDebugLoc(), VT, X);
03819         AddToWorkList(X.getNode());
03820       }
03821 
03822       APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
03823       X = DAG.getNode(ISD::AND, X.getDebugLoc(), VT,
03824                       X, DAG.getConstant(SignBit, VT));
03825       AddToWorkList(X.getNode());
03826 
03827       SDValue Cst = DAG.getNode(ISD::BIT_CONVERT, N0.getDebugLoc(),
03828                                 VT, N0.getOperand(0));
03829       Cst = DAG.getNode(ISD::AND, Cst.getDebugLoc(), VT,
03830                         Cst, DAG.getConstant(~SignBit, VT));
03831       AddToWorkList(Cst.getNode());
03832 
03833       return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, X, Cst);
03834     }
03835   }
03836 
03837   // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
03838   if (N0.getOpcode() == ISD::BUILD_PAIR) {
03839     SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
03840     if (CombineLD.getNode())
03841       return CombineLD;
03842   }
03843 
03844   return SDValue();
03845 }
03846 
03847 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
03848   EVT VT = N->getValueType(0);
03849   return CombineConsecutiveLoads(N, VT);
03850 }
03851 
03852 /// ConstantFoldBIT_CONVERTofBUILD_VECTOR - We know that BV is a build_vector
03853 /// node with Constant, ConstantFP or Undef operands.  DstEltVT indicates the
03854 /// destination element value type.
03855 SDValue DAGCombiner::
03856 ConstantFoldBIT_CONVERTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
03857   EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
03858 
03859   // If this is already the right type, we're done.
03860   if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
03861 
03862   unsigned SrcBitSize = SrcEltVT.getSizeInBits();
03863   unsigned DstBitSize = DstEltVT.getSizeInBits();
03864 
03865   // If this is a conversion of N elements of one type to N elements of another
03866   // type, convert each element.  This handles FP<->INT cases.
03867   if (SrcBitSize == DstBitSize) {
03868     SmallVector<SDValue, 8> Ops;
03869     for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
03870       SDValue Op = BV->getOperand(i);
03871       // If the vector element type is not legal, the BUILD_VECTOR operands
03872       // are promoted and implicitly truncated.  Make that explicit here.
03873       if (Op.getValueType() != SrcEltVT)
03874         Op = DAG.getNode(ISD::TRUNCATE, BV->getDebugLoc(), SrcEltVT, Op);
03875       Ops.push_back(DAG.getNode(ISD::BIT_CONVERT, BV->getDebugLoc(),
03876                                 DstEltVT, Op));
03877       AddToWorkList(Ops.back().getNode());
03878     }
03879     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
03880                               BV->getValueType(0).getVectorNumElements());
03881     return DAG.getNode(ISD::BUILD_VECTOR, BV->getDebugLoc(), VT,
03882                        &Ops[0], Ops.size());
03883   }
03884 
03885   // Otherwise, we're growing or shrinking the elements.  To avoid having to
03886   // handle annoying details of growing/shrinking FP values, we convert them to
03887   // int first.
03888   if (SrcEltVT.isFloatingPoint()) {
03889     // Convert the input float vector to a int vector where the elements are the
03890     // same sizes.
03891     assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!");
03892     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
03893     BV = ConstantFoldBIT_CONVERTofBUILD_VECTOR(BV, IntVT).getNode();
03894     SrcEltVT = IntVT;
03895   }
03896 
03897   // Now we know the input is an integer vector.  If the output is a FP type,
03898   // convert to integer first, then to FP of the right size.
03899   if (DstEltVT.isFloatingPoint()) {
03900     assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!");
03901     EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
03902     SDNode *Tmp = ConstantFoldBIT_CONVERTofBUILD_VECTOR(BV, TmpVT).getNode();
03903 
03904     // Next, convert to FP elements of the same size.
03905     return ConstantFoldBIT_CONVERTofBUILD_VECTOR(Tmp, DstEltVT);
03906   }
03907 
03908   // Okay, we know the src/dst types are both integers of differing types.
03909   // Handling growing first.
03910   assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
03911   if (SrcBitSize < DstBitSize) {
03912     unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
03913 
03914     SmallVector<SDValue, 8> Ops;
03915     for (unsigned i = 0, e = BV->getNumOperands(); i != e;
03916          i += NumInputsPerOutput) {
03917       bool isLE = TLI.isLittleEndian();
03918       APInt NewBits = APInt(DstBitSize, 0);
03919       bool EltIsUndef = true;
03920       for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
03921         // Shift the previously computed bits over.
03922         NewBits <<= SrcBitSize;
03923         SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
03924         if (Op.getOpcode() == ISD::UNDEF) continue;
03925         EltIsUndef = false;
03926 
03927         NewBits |= (APInt(cast<ConstantSDNode>(Op)->getAPIntValue()).
03928                     zextOrTrunc(SrcBitSize).zext(DstBitSize));
03929       }
03930 
03931       if (EltIsUndef)
03932         Ops.push_back(DAG.getUNDEF(DstEltVT));
03933       else
03934         Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
03935     }
03936 
03937     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
03938     return DAG.getNode(ISD::BUILD_VECTOR, BV->getDebugLoc(), VT,
03939                        &Ops[0], Ops.size());
03940   }
03941 
03942   // Finally, this must be the case where we are shrinking elements: each input
03943   // turns into multiple outputs.
03944   bool isS2V = ISD::isScalarToVector(BV);
03945   unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
03946   EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
03947                             NumOutputsPerInput*BV->getNumOperands());
03948   SmallVector<SDValue, 8> Ops;
03949 
03950   for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
03951     if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
03952       for (unsigned j = 0; j != NumOutputsPerInput; ++j)
03953         Ops.push_back(DAG.getUNDEF(DstEltVT));
03954       continue;
03955     }
03956 
03957     APInt OpVal = APInt(cast<ConstantSDNode>(BV->getOperand(i))->
03958                         getAPIntValue()).zextOrTrunc(SrcBitSize);
03959 
03960     for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
03961       APInt ThisVal = APInt(OpVal).trunc(DstBitSize);
03962       Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
03963       if (isS2V && i == 0 && j == 0 && APInt(ThisVal).zext(SrcBitSize) == OpVal)
03964         // Simply turn this into a SCALAR_TO_VECTOR of the new type.
03965         return DAG.getNode(ISD::SCALAR_TO_VECTOR, BV->getDebugLoc(), VT,
03966                            Ops[0]);
03967       OpVal = OpVal.lshr(DstBitSize);
03968     }
03969 
03970     // For big endian targets, swap the order of the pieces of each element.
03971     if (TLI.isBigEndian())
03972       std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
03973   }
03974 
03975   return DAG.getNode(ISD::BUILD_VECTOR, BV->getDebugLoc(), VT,
03976                      &Ops[0], Ops.size());
03977 }
03978 
03979 SDValue DAGCombiner::visitFADD(SDNode *N) {
03980   SDValue N0 = N->getOperand(0);
03981   SDValue N1 = N->getOperand(1);
03982   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
03983   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
03984   EVT VT = N->getValueType(0);
03985 
03986   // fold vector ops
03987   if (VT.isVector()) {
03988     SDValue FoldedVOp = SimplifyVBinOp(N);
03989     if (FoldedVOp.getNode()) return FoldedVOp;
03990   }
03991 
03992   // fold (fadd c1, c2) -> (fadd c1, c2)
03993   if (N0CFP && N1CFP && VT != MVT::ppcf128)
03994     return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N0, N1);
03995   // canonicalize constant to RHS
03996   if (N0CFP && !N1CFP)
03997     return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N1, N0);
03998   // fold (fadd A, 0) -> A
03999   if (UnsafeFPMath && N1CFP && N1CFP->getValueAPF().isZero())
04000     return N0;
04001   // fold (fadd A, (fneg B)) -> (fsub A, B)
04002   if (isNegatibleForFree(N1, LegalOperations) == 2)
04003     return DAG.getNode(ISD::FSUB, N->getDebugLoc(), VT, N0,
04004                        GetNegatedExpression(N1, DAG, LegalOperations));
04005   // fold (fadd (fneg A), B) -> (fsub B, A)
04006   if (isNegatibleForFree(N0, LegalOperations) == 2)
04007     return DAG.getNode(ISD::FSUB, N->getDebugLoc(), VT, N1,
04008                        GetNegatedExpression(N0, DAG, LegalOperations));
04009 
04010   // If allowed, fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
04011   if (UnsafeFPMath && N1CFP && N0.getOpcode() == ISD::FADD &&
04012       N0.getNode()->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
04013     return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N0.getOperand(0),
04014                        DAG.getNode(ISD::FADD, N->getDebugLoc(), VT,
04015                                    N0.getOperand(1), N1));
04016 
04017   return SDValue();
04018 }
04019 
04020 SDValue DAGCombiner::visitFSUB(SDNode *N) {
04021   SDValue N0 = N->getOperand(0);
04022   SDValue N1 = N->getOperand(1);
04023   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
04024   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
04025   EVT VT = N->getValueType(0);
04026 
04027   // fold vector ops
04028   if (VT.isVector()) {
04029     SDValue FoldedVOp = SimplifyVBinOp(N);
04030     if (FoldedVOp.getNode()) return FoldedVOp;
04031   }
04032 
04033   // fold (fsub c1, c2) -> c1-c2
04034   if (N0CFP && N1CFP && VT != MVT::ppcf128)
04035     return DAG.getNode(ISD::FSUB, N->getDebugLoc(), VT, N0, N1);
04036   // fold (fsub A, 0) -> A
04037   if (UnsafeFPMath && N1CFP && N1CFP->getValueAPF().isZero())
04038     return N0;
04039   // fold (fsub 0, B) -> -B
04040   if (UnsafeFPMath && N0CFP && N0CFP->getValueAPF().isZero()) {
04041     if (isNegatibleForFree(N1, LegalOperations))
04042       return GetNegatedExpression(N1, DAG, LegalOperations);
04043     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
04044       return DAG.getNode(ISD::FNEG, N->getDebugLoc(), VT, N1);
04045   }
04046   // fold (fsub A, (fneg B)) -> (fadd A, B)
04047   if (isNegatibleForFree(N1, LegalOperations))
04048     return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N0,
04049                        GetNegatedExpression(N1, DAG, LegalOperations));
04050 
04051   return SDValue();
04052 }
04053 
04054 SDValue DAGCombiner::visitFMUL(SDNode *N) {
04055   SDValue N0 = N->getOperand(0);
04056   SDValue N1 = N->getOperand(1);
04057   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
04058   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
04059   EVT VT = N->getValueType(0);
04060 
04061   // fold vector ops
04062   if (VT.isVector()) {
04063     SDValue FoldedVOp = SimplifyVBinOp(N);
04064     if (FoldedVOp.getNode()) return FoldedVOp;
04065   }
04066 
04067   // fold (fmul c1, c2) -> c1*c2
04068   if (N0CFP && N1CFP && VT != MVT::ppcf128)
04069     return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT, N0, N1);
04070   // canonicalize constant to RHS
04071   if (N0CFP && !N1CFP)
04072     return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT, N1, N0);
04073   // fold (fmul A, 0) -> 0
04074   if (UnsafeFPMath && N1CFP && N1CFP->getValueAPF().isZero())
04075     return N1;
04076   // fold (fmul A, 0) -> 0, vector edition.
04077   if (UnsafeFPMath && ISD::isBuildVectorAllZeros(N1.getNode()))
04078     return N1;
04079   // fold (fmul X, 2.0) -> (fadd X, X)
04080   if (N1CFP && N1CFP->isExactlyValue(+2.0))
04081     return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N0, N0);
04082   // fold (fmul X, -1.0) -> (fneg X)
04083   if (N1CFP && N1CFP->isExactlyValue(-1.0))
04084     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
04085       return DAG.getNode(ISD::FNEG, N->getDebugLoc(), VT, N0);
04086 
04087   // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
04088   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations)) {
04089     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations)) {
04090       // Both can be negated for free, check to see if at least one is cheaper
04091       // negated.
04092       if (LHSNeg == 2 || RHSNeg == 2)
04093         return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT,
04094                            GetNegatedExpression(N0, DAG, LegalOperations),
04095                            GetNegatedExpression(N1, DAG, LegalOperations));
04096     }
04097   }
04098 
04099   // If allowed, fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
04100   if (UnsafeFPMath && N1CFP && N0.getOpcode() == ISD::FMUL &&
04101       N0.getNode()->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
04102     return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT, N0.getOperand(0),
04103                        DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT,
04104                                    N0.getOperand(1), N1));
04105 
04106   return SDValue();
04107 }
04108 
04109 SDValue DAGCombiner::visitFDIV(SDNode *N) {
04110   SDValue N0 = N->getOperand(0);
04111   SDValue N1 = N->getOperand(1);
04112   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
04113   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
04114   EVT VT = N->getValueType(0);
04115 
04116   // fold vector ops
04117   if (VT.isVector()) {
04118     SDValue FoldedVOp = SimplifyVBinOp(N);
04119     if (FoldedVOp.getNode()) return FoldedVOp;
04120   }
04121 
04122   // fold (fdiv c1, c2) -> c1/c2
04123   if (N0CFP && N1CFP && VT != MVT::ppcf128)
04124     return DAG.getNode(ISD::FDIV, N->getDebugLoc(), VT, N0, N1);
04125 
04126 
04127   // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
04128   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations)) {
04129     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations)) {
04130       // Both can be negated for free, check to see if at least one is cheaper
04131       // negated.
04132       if (LHSNeg == 2 || RHSNeg == 2)
04133         return DAG.getNode(ISD::FDIV, N->getDebugLoc(), VT,
04134                            GetNegatedExpression(N0, DAG, LegalOperations),
04135                            GetNegatedExpression(N1, DAG, LegalOperations));
04136     }
04137   }
04138 
04139   return SDValue();
04140 }
04141 
04142 SDValue DAGCombiner::visitFREM(SDNode *N) {
04143   SDValue N0 = N->getOperand(0);
04144   SDValue N1 = N->getOperand(1);
04145   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
04146   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
04147   EVT VT = N->getValueType(0);
04148 
04149   // fold (frem c1, c2) -> fmod(c1,c2)
04150   if (N0CFP && N1CFP && VT != MVT::ppcf128)
04151     return DAG.getNode(ISD::FREM, N->getDebugLoc(), VT, N0, N1);
04152 
04153   return SDValue();
04154 }
04155 
04156 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
04157   SDValue N0 = N->getOperand(0);
04158   SDValue N1 = N->getOperand(1);
04159   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
04160   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
04161   EVT VT = N->getValueType(0);
04162 
04163   if (N0CFP && N1CFP && VT != MVT::ppcf128)  // Constant fold
04164     return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT, N0, N1);
04165 
04166   if (N1CFP) {
04167     const APFloat& V = N1CFP->getValueAPF();
04168     // copysign(x, c1) -> fabs(x)       iff ispos(c1)
04169     // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
04170     if (!V.isNegative()) {
04171       if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
04172         return DAG.getNode(ISD::FABS, N->getDebugLoc(), VT, N0);
04173     } else {
04174       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
04175         return DAG.getNode(ISD::FNEG, N->getDebugLoc(), VT,
04176                            DAG.getNode(ISD::FABS, N0.getDebugLoc(), VT, N0));
04177     }
04178   }
04179 
04180   // copysign(fabs(x), y) -> copysign(x, y)
04181   // copysign(fneg(x), y) -> copysign(x, y)
04182   // copysign(copysign(x,z), y) -> copysign(x, y)
04183   if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
04184       N0.getOpcode() == ISD::FCOPYSIGN)
04185     return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT,
04186                        N0.getOperand(0), N1);
04187 
04188   // copysign(x, abs(y)) -> abs(x)
04189   if (N1.getOpcode() == ISD::FABS)
04190     return DAG.getNode(ISD::FABS, N->getDebugLoc(), VT, N0);
04191 
04192   // copysign(x, copysign(y,z)) -> copysign(x, z)
04193   if (N1.getOpcode() == ISD::FCOPYSIGN)
04194     return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT,
04195                        N0, N1.getOperand(1));
04196 
04197   // copysign(x, fp_extend(y)) -> copysign(x, y)
04198   // copysign(x, fp_round(y)) -> copysign(x, y)
04199   if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
04200     return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT,
04201                        N0, N1.getOperand(0));
04202 
04203   return SDValue();
04204 }
04205 
04206 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
04207   SDValue N0 = N->getOperand(0);
04208   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
04209   EVT VT = N->getValueType(0);
04210   EVT OpVT = N0.getValueType();
04211 
04212   // fold (sint_to_fp c1) -> c1fp
04213   if (N0C && OpVT != MVT::ppcf128)
04214     return DAG.getNode(ISD::SINT_TO_FP, N->getDebugLoc(), VT, N0);
04215 
04216   // If the input is a legal type, and SINT_TO_FP is not legal on this target,
04217   // but UINT_TO_FP is legal on this target, try to convert.
04218   if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
04219       TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
04220     // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
04221     if (DAG.SignBitIsZero(N0))
04222       return DAG.getNode(ISD::UINT_TO_FP, N->getDebugLoc(), VT, N0);
04223   }
04224 
04225   return SDValue();
04226 }
04227 
04228 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
04229   SDValue N0 = N->getOperand(0);
04230   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
04231   EVT VT = N->getValueType(0);
04232   EVT OpVT = N0.getValueType();
04233 
04234   // fold (uint_to_fp c1) -> c1fp
04235   if (N0C && OpVT != MVT::ppcf128)
04236     return DAG.getNode(ISD::UINT_TO_FP, N->getDebugLoc(), VT, N0);
04237 
04238   // If the input is a legal type, and UINT_TO_FP is not legal on this target,
04239   // but SINT_TO_FP is legal on this target, try to convert.
04240   if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
04241       TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
04242     // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
04243     if (DAG.SignBitIsZero(N0))
04244       return DAG.getNode(ISD::SINT_TO_FP, N->getDebugLoc(), VT, N0);
04245   }
04246 
04247   return SDValue();
04248 }
04249 
04250 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
04251   SDValue N0 = N->getOperand(0);
04252   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
04253   EVT VT = N->getValueType(0);
04254 
04255   // fold (fp_to_sint c1fp) -> c1
04256   if (N0CFP)
04257     return DAG.getNode(ISD::FP_TO_SINT, N->getDebugLoc(), VT, N0);
04258 
04259   return SDValue();
04260 }
04261 
04262 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
04263   SDValue N0 = N->getOperand(0);
04264   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
04265   EVT VT = N->getValueType(0);
04266 
04267   // fold (fp_to_uint c1fp) -> c1
04268   if (N0CFP && VT != MVT::ppcf128)
04269     return DAG.getNode(ISD::FP_TO_UINT, N->getDebugLoc(), VT, N0);
04270 
04271   return SDValue();
04272 }
04273 
04274 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
04275   SDValue N0 = N->getOperand(0);
04276   SDValue N1 = N->getOperand(1);
04277   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
04278   EVT VT = N->getValueType(0);
04279 
04280   // fold (fp_round c1fp) -> c1fp
04281   if (N0CFP && N0.getValueType() != MVT::ppcf128)
04282     return DAG.getNode(ISD::FP_ROUND, N->getDebugLoc(), VT, N0, N1);
04283 
04284   // fold (fp_round (fp_extend x)) -> x
04285   if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
04286     return N0.getOperand(0);
04287 
04288   // fold (fp_round (fp_round x)) -> (fp_round x)
04289   if (N0.getOpcode() == ISD::FP_ROUND) {
04290     // This is a value preserving truncation if both round's are.
04291     bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
04292                    N0.getNode()->getConstantOperandVal(1) == 1;
04293     return DAG.getNode(ISD::FP_ROUND, N->getDebugLoc(), VT, N0.getOperand(0),
04294                        DAG.getIntPtrConstant(IsTrunc));
04295   }
04296 
04297   // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
04298   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
04299     SDValue Tmp = DAG.getNode(ISD::FP_ROUND, N0.getDebugLoc(), VT,
04300                               N0.getOperand(0), N1);
04301     AddToWorkList(Tmp.getNode());
04302     return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT,
04303                        Tmp, N0.getOperand(1));
04304   }
04305 
04306   return SDValue();
04307 }
04308 
04309 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
04310   SDValue N0 = N->getOperand(0);
04311   EVT VT = N->getValueType(0);
04312   EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
04313   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
04314 
04315   // fold (fp_round_inreg c1fp) -> c1fp
04316   if (N0CFP && (TLI.isTypeLegal(EVT) || !LegalTypes)) {
04317     SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
04318     return DAG.getNode(ISD::FP_EXTEND, N->getDebugLoc(), VT, Round);
04319   }
04320 
04321   return SDValue();
04322 }
04323 
04324 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
04325   SDValue N0 = N->getOperand(0);
04326   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
04327   EVT VT = N->getValueType(0);
04328 
04329   // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
04330   if (N->hasOneUse() &&
04331       N->use_begin()->getOpcode() == ISD::FP_ROUND)
04332     return SDValue();
04333 
04334   // fold (fp_extend c1fp) -> c1fp
04335   if (N0CFP && VT != MVT::ppcf128)
04336     return DAG.getNode(ISD::FP_EXTEND, N->getDebugLoc(), VT, N0);
04337 
04338   // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
04339   // value of X.
04340   if (N0.getOpcode() == ISD::FP_ROUND
04341       && N0.getNode()->getConstantOperandVal(1) == 1) {
04342     SDValue In = N0.getOperand(0);
04343     if (In.getValueType() == VT) return In;
04344     if (VT.bitsLT(In.getValueType()))
04345       return DAG.getNode(ISD::FP_ROUND, N->getDebugLoc(), VT,
04346                          In, N0.getOperand(1));
04347     return DAG.getNode(ISD::FP_EXTEND, N->getDebugLoc(), VT, In);
04348   }
04349 
04350   // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
04351   if (ISD::isNON_EXTLoad(N0.getNode()) && N0.hasOneUse() &&
04352       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
04353        TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
04354     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
04355     SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, N->getDebugLoc(), VT,
04356                                      LN0->getChain(),
04357                                      LN0->getBasePtr(), LN0->getSrcValue(),
04358                                      LN0->getSrcValueOffset(),
04359                                      N0.getValueType(),
04360                                      LN0->isVolatile(), LN0->getAlignment());
04361     CombineTo(N, ExtLoad);
04362     CombineTo(N0.getNode(),
04363               DAG.getNode(ISD::FP_ROUND, N0.getDebugLoc(),
04364                           N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
04365               ExtLoad.getValue(1));
04366     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
04367   }
04368 
04369   return SDValue();
04370 }
04371 
04372 SDValue DAGCombiner::visitFNEG(SDNode *N) {
04373   SDValue N0 = N->getOperand(0);
04374 
04375   if (isNegatibleForFree(N0, LegalOperations))
04376     return GetNegatedExpression(N0, DAG, LegalOperations);
04377 
04378   // Transform fneg(bitconvert(x)) -> bitconvert(x^sign) to avoid loading
04379   // constant pool values.
04380   if (N0.getOpcode() == ISD::BIT_CONVERT && N0.getNode()->hasOneUse() &&
04381       N0.getOperand(0).getValueType().isInteger() &&
04382       !N0.getOperand(0).getValueType().isVector()) {
04383     SDValue Int = N0.getOperand(0);
04384     EVT IntVT = Int.getValueType();
04385     if (IntVT.isInteger() && !IntVT.isVector()) {
04386       Int = DAG.getNode(ISD::XOR, N0.getDebugLoc(), IntVT, Int,
04387               DAG.getConstant(APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
04388       AddToWorkList(Int.getNode());
04389       return DAG.getNode(ISD::BIT_CONVERT, N->getDebugLoc(),
04390                          N->getValueType(0), Int);
04391     }
04392   }
04393 
04394   return SDValue();
04395 }
04396 
04397 SDValue DAGCombiner::visitFABS(SDNode *N) {
04398   SDValue N0 = N->getOperand(0);
04399   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
04400   EVT VT = N->getValueType(0);
04401 
04402   // fold (fabs c1) -> fabs(c1)
04403   if (N0CFP && VT != MVT::ppcf128)
04404     return DAG.getNode(ISD::FABS, N->getDebugLoc(), VT, N0);
04405   // fold (fabs (fabs x)) -> (fabs x)
04406   if (N0.getOpcode() == ISD::FABS)
04407     return N->getOperand(0);
04408   // fold (fabs (fneg x)) -> (fabs x)
04409   // fold (fabs (fcopysign x, y)) -> (fabs x)
04410   if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
04411     return DAG.getNode(ISD::FABS, N->getDebugLoc(), VT, N0.getOperand(0));
04412 
04413   // Transform fabs(bitconvert(x)) -> bitconvert(x&~sign) to avoid loading
04414   // constant pool values.
04415   if (N0.getOpcode() == ISD::BIT_CONVERT && N0.getNode()->hasOneUse() &&
04416       N0.getOperand(0).getValueType().isInteger() &&
04417       !N0.getOperand(0).getValueType().isVector()) {
04418     SDValue Int = N0.getOperand(0);
04419     EVT IntVT = Int.getValueType();
04420     if (IntVT.isInteger() && !IntVT.isVector()) {
04421       Int = DAG.getNode(ISD::AND, N0.getDebugLoc(), IntVT, Int,
04422              DAG.getConstant(~APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
04423       AddToWorkList(Int.getNode());
04424       return DAG.getNode(ISD::BIT_CONVERT, N->getDebugLoc(),
04425                          N->getValueType(0), Int);
04426     }
04427   }
04428 
04429   return SDValue();
04430 }
04431 
04432 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
04433   SDValue Chain = N->getOperand(0);
04434   SDValue N1 = N->getOperand(1);
04435   SDValue N2 = N->getOperand(2);
04436   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
04437 
04438   // never taken branch, fold to chain
04439   if (N1C && N1C->isNullValue())
04440     return Chain;
04441   // unconditional branch
04442   if (N1C && N1C->getAPIntValue() == 1)
04443     return DAG.getNode(ISD::BR, N->getDebugLoc(), MVT::Other, Chain, N2);
04444   // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
04445   // on the target.
04446   if (N1.getOpcode() == ISD::SETCC &&
04447       TLI.isOperationLegalOrCustom(ISD::BR_CC, MVT::Other)) {
04448     return DAG.getNode(ISD::BR_CC, N->getDebugLoc(), MVT::Other,
04449                        Chain, N1.getOperand(2),
04450                        N1.getOperand(0), N1.getOperand(1), N2);
04451   }
04452 
04453   if (N1.hasOneUse() && N1.getOpcode() == ISD::SRL) {
04454     // Match this pattern so that we can generate simpler code:
04455     //
04456     //   %a = ...
04457     //   %b = and i32 %a, 2
04458     //   %c = srl i32 %b, 1
04459     //   brcond i32 %c ...
04460     //
04461     // into
04462     // 
04463     //   %a = ...
04464     //   %b = and %a, 2
04465     //   %c = setcc eq %b, 0
04466     //   brcond %c ...
04467     //
04468     // This applies only when the AND constant value has one bit set and the
04469     // SRL constant is equal to the log2 of the AND constant. The back-end is
04470     // smart enough to convert the result into a TEST/JMP sequence.
04471     SDValue Op0 = N1.getOperand(0);
04472     SDValue Op1 = N1.getOperand(1);
04473 
04474     if (Op0.getOpcode() == ISD::AND &&
04475         Op0.hasOneUse() &&
04476         Op1.getOpcode() == ISD::Constant) {
04477       SDValue AndOp0 = Op0.getOperand(0);
04478       SDValue AndOp1 = Op0.getOperand(1);
04479 
04480       if (AndOp1.getOpcode() == ISD::Constant) {
04481         const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
04482 
04483         if (AndConst.isPowerOf2() &&
04484             cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
04485           SDValue SetCC =
04486             DAG.getSetCC(N->getDebugLoc(),
04487                          TLI.getSetCCResultType(Op0.getValueType()),
04488                          Op0, DAG.getConstant(0, Op0.getValueType()),
04489                          ISD::SETNE);
04490 
04491           // Replace the uses of SRL with SETCC
04492           DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
04493           removeFromWorkList(N1.getNode());
04494           DAG.DeleteNode(N1.getNode());
04495           return DAG.getNode(ISD::BRCOND, N->getDebugLoc(),
04496                              MVT::Other, Chain, SetCC, N2);
04497         }
04498       }
04499     }
04500   }
04501 
04502   return SDValue();
04503 }
04504 
04505 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
04506 //
04507 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
04508   CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
04509   SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
04510 
04511   // Use SimplifySetCC to simplify SETCC's.
04512   SDValue Simp = SimplifySetCC(TLI.getSetCCResultType(CondLHS.getValueType()),
04513                                CondLHS, CondRHS, CC->get(), N->getDebugLoc(),
04514                                false);
04515   if (Simp.getNode()) AddToWorkList(Simp.getNode());
04516 
04517   ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(Simp.getNode());
04518 
04519   // fold br_cc true, dest -> br dest (unconditional branch)
04520   if (SCCC && !SCCC->isNullValue())
04521     return DAG.getNode(ISD::BR, N->getDebugLoc(), MVT::Other,
04522                        N->getOperand(0), N->getOperand(4));
04523   // fold br_cc false, dest -> unconditional fall through
04524   if (SCCC && SCCC->isNullValue())
04525     return N->getOperand(0);
04526 
04527   // fold to a simpler setcc
04528   if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
04529     return DAG.getNode(ISD::BR_CC, N->getDebugLoc(), MVT::Other,
04530                        N->getOperand(0), Simp.getOperand(2),
04531                        Simp.getOperand(0), Simp.getOperand(1),
04532                        N->getOperand(4));
04533 
04534   return SDValue();
04535 }
04536 
04537 /// CombineToPreIndexedLoadStore - Try turning a load / store into a
04538 /// pre-indexed load / store when the base pointer is an add or subtract
04539 /// and it has other uses besides the load / store. After the
04540 /// transformation, the new indexed load / store has effectively folded
04541 /// the add / subtract in and all of its other uses are redirected to the
04542 /// new load / store.
04543 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
04544   if (!LegalOperations)
04545     return false;
04546 
04547   bool isLoad = true;
04548   SDValue Ptr;
04549   EVT VT;
04550   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
04551     if (LD->isIndexed())
04552       return false;
04553     VT = LD->getMemoryVT();
04554     if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
04555         !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
04556       return false;
04557     Ptr = LD->getBasePtr();
04558   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
04559     if (ST->isIndexed())
04560       return false;
04561     VT = ST->getMemoryVT();
04562     if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
04563         !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
04564       return false;
04565     Ptr = ST->getBasePtr();
04566     isLoad = false;
04567   } else {
04568     return false;
04569   }
04570 
04571   // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
04572   // out.  There is no reason to make this a preinc/predec.
04573   if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
04574       Ptr.getNode()->hasOneUse())
04575     return false;
04576 
04577   // Ask the target to do addressing mode selection.
04578   SDValue BasePtr;
04579   SDValue Offset;
04580   ISD::MemIndexedMode AM = ISD::UNINDEXED;
04581   if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
04582     return false;
04583   // Don't create a indexed load / store with zero offset.
04584   if (isa<ConstantSDNode>(Offset) &&
04585       cast<ConstantSDNode>(Offset)->isNullValue())
04586     return false;
04587 
04588   // Try turning it into a pre-indexed load / store except when:
04589   // 1) The new base ptr is a frame index.
04590   // 2) If N is a store and the new base ptr is either the same as or is a
04591   //    predecessor of the value being stored.
04592   // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
04593   //    that would create a cycle.
04594   // 4) All uses are load / store ops that use it as old base ptr.
04595 
04596   // Check #1.  Preinc'ing a frame index would require copying the stack pointer
04597   // (plus the implicit offset) to a register to preinc anyway.
04598   if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
04599     return false;
04600 
04601   // Check #2.
04602   if (!isLoad) {
04603     SDValue Val = cast<StoreSDNode>(N)->getValue();
04604     if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
04605       return false;
04606   }
04607 
04608   // Now check for #3 and #4.
04609   bool RealUse = false;
04610   for (SDNode::use_iterator I = Ptr.getNode()->use_begin(),
04611          E = Ptr.getNode()->use_end(); I != E; ++I) {
04612     SDNode *Use = *I;
04613     if (Use == N)
04614       continue;
04615     if (Use->isPredecessorOf(N))
04616       return false;
04617 
04618     if (!((Use->getOpcode() == ISD::LOAD &&
04619            cast<LoadSDNode>(Use)->getBasePtr() == Ptr) ||
04620           (Use->getOpcode() == ISD::STORE &&
04621            cast<StoreSDNode>(Use)->getBasePtr() == Ptr)))
04622       RealUse = true;
04623   }
04624 
04625   if (!RealUse)
04626     return false;
04627 
04628   SDValue Result;
04629   if (isLoad)
04630     Result = DAG.getIndexedLoad(SDValue(N,0), N->getDebugLoc(),
04631                                 BasePtr, Offset, AM);
04632   else
04633     Result = DAG.getIndexedStore(SDValue(N,0), N->getDebugLoc(),
04634                                  BasePtr, Offset, AM);
04635   ++PreIndexedNodes;
04636   ++NodesCombined;
04637   DOUT << "\nReplacing.4 "; DEBUG(N->dump(&DAG));
04638   DOUT << "\nWith: "; DEBUG(Result.getNode()->dump(&DAG));
04639   DOUT << '\n';
04640   WorkListRemover DeadNodes(*this);
04641   if (isLoad) {
04642     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0),
04643                                   &DeadNodes);
04644     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2),
04645                                   &DeadNodes);
04646   } else {
04647     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1),
04648                                   &DeadNodes);
04649   }
04650 
04651   // Finally, since the node is now dead, remove it from the graph.
04652   DAG.DeleteNode(N);
04653 
04654   // Replace the uses of Ptr with uses of the updated base value.
04655   DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0),
04656                                 &DeadNodes);
04657   removeFromWorkList(Ptr.getNode());
04658   DAG.DeleteNode(Ptr.getNode());
04659 
04660   return true;
04661 }
04662 
04663 /// CombineToPostIndexedLoadStore - Try to combine a load / store with a
04664 /// add / sub of the base pointer node into a post-indexed load / store.
04665 /// The transformation folded the add / subtract into the new indexed
04666 /// load / store effectively and all of its uses are redirected to the
04667 /// new load / store.
04668 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
04669   if (!LegalOperations)
04670     return false;
04671 
04672   bool isLoad = true;
04673   SDValue Ptr;
04674   EVT VT;
04675   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
04676     if (LD->isIndexed())
04677       return false;
04678     VT = LD->getMemoryVT();
04679     if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
04680         !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
04681       return false;
04682     Ptr = LD->getBasePtr();
04683   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
04684     if (ST->isIndexed())
04685       return false;
04686     VT = ST->getMemoryVT();
04687     if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
04688         !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
04689       return false;
04690     Ptr = ST->getBasePtr();
04691     isLoad = false;
04692   } else {
04693     return false;
04694   }
04695 
04696   if (Ptr.getNode()->hasOneUse())
04697     return false;
04698 
04699   for (SDNode::use_iterator I = Ptr.getNode()->use_begin(),
04700          E = Ptr.getNode()->use_end(); I != E; ++I) {
04701     SDNode *Op = *I;
04702     if (Op == N ||
04703         (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
04704       continue;
04705 
04706     SDValue BasePtr;
04707     SDValue Offset;
04708     ISD::MemIndexedMode AM = ISD::UNINDEXED;
04709     if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
04710       if (Ptr == Offset)
04711         std::swap(BasePtr, Offset);
04712       if (Ptr != BasePtr)
04713         continue;
04714       // Don't create a indexed load / store with zero offset.
04715       if (isa<ConstantSDNode>(Offset) &&
04716           cast<ConstantSDNode>(Offset)->isNullValue())
04717         continue;
04718 
04719       // Try turning it into a post-indexed load / store except when
04720       // 1) All uses are load / store ops that use it as base ptr.
04721       // 2) Op must be independent of N, i.e. Op is neither a predecessor
04722       //    nor a successor of N. Otherwise, if Op is folded that would
04723       //    create a cycle.
04724 
04725       if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
04726         continue;
04727 
04728       // Check for #1.
04729       bool TryNext = false;
04730       for (SDNode::use_iterator II = BasePtr.getNode()->use_begin(),
04731              EE = BasePtr.getNode()->use_end(); II != EE; ++II) {
04732         SDNode *Use = *II;
04733         if (Use == Ptr.getNode())
04734           continue;
04735 
04736         // If all the uses are load / store addresses, then don't do the
04737         // transformation.
04738         if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
04739           bool RealUse = false;
04740           for (SDNode::use_iterator III = Use->use_begin(),
04741                  EEE = Use->use_end(); III != EEE; ++III) {
04742             SDNode *UseUse = *III;
04743             if (!((UseUse->getOpcode() == ISD::LOAD &&
04744                    cast<LoadSDNode>(UseUse)->getBasePtr().getNode() == Use) ||
04745                   (UseUse->getOpcode() == ISD::STORE &&
04746                    cast<StoreSDNode>(UseUse)->getBasePtr().getNode() == Use)))
04747               RealUse = true;
04748           }
04749 
04750           if (!RealUse) {
04751             TryNext = true;
04752             break;
04753           }
04754         }
04755       }
04756 
04757       if (TryNext)
04758         continue;
04759 
04760       // Check for #2
04761       if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
04762         SDValue Result = isLoad
04763           ? DAG.getIndexedLoad(SDValue(N,0), N->getDebugLoc(),
04764                                BasePtr, Offset, AM)
04765           : DAG.getIndexedStore(SDValue(N,0), N->getDebugLoc(),
04766                                 BasePtr, Offset, AM);
04767         ++PostIndexedNodes;
04768         ++NodesCombined;
04769         DOUT << "\nReplacing.5 "; DEBUG(N->dump(&DAG));
04770         DOUT << "\nWith: "; DEBUG(Result.getNode()->dump(&DAG));
04771         DOUT << '\n';
04772         WorkListRemover DeadNodes(*this);
04773         if (isLoad) {
04774           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0),
04775                                         &DeadNodes);
04776           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2),
04777                                         &DeadNodes);
04778         } else {
04779           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1),
04780                                         &DeadNodes);
04781         }
04782 
04783         // Finally, since the node is now dead, remove it from the graph.
04784         DAG.DeleteNode(N);
04785 
04786         // Replace the uses of Use with uses of the updated base value.
04787         DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
04788                                       Result.getValue(isLoad ? 1 : 0),
04789                                       &DeadNodes);
04790         removeFromWorkList(Op);
04791         DAG.DeleteNode(Op);
04792         return true;
04793       }
04794     }
04795   }
04796 
04797   return false;
04798 }
04799 
04800 /// InferAlignment - If we can infer some alignment information from this
04801 /// pointer, return it.
04802 static unsigned InferAlignment(SDValue Ptr, SelectionDAG &DAG) {
04803   // If this is a direct reference to a stack slot, use information about the
04804   // stack slot's alignment.
04805   int FrameIdx = 1 << 31;
04806   int64_t FrameOffset = 0;
04807   if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr)) {
04808     FrameIdx = FI->getIndex();
04809   } else if (Ptr.getOpcode() == ISD::ADD &&
04810              isa<ConstantSDNode>(Ptr.getOperand(1)) &&
04811              isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
04812     FrameIdx = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
04813     FrameOffset = Ptr.getConstantOperandVal(1);
04814   }
04815 
04816   if (FrameIdx != (1 << 31)) {
04817     // FIXME: Handle FI+CST.
04818     const MachineFrameInfo &MFI = *DAG.getMachineFunction().getFrameInfo();
04819     if (MFI.isFixedObjectIndex(FrameIdx)) {
04820       int64_t ObjectOffset = MFI.getObjectOffset(FrameIdx) + FrameOffset;
04821 
04822       // The alignment of the frame index can be determined from its offset from
04823       // the incoming frame position.  If the frame object is at offset 32 and
04824       // the stack is guaranteed to be 16-byte aligned, then we know that the
04825       // object is 16-byte aligned.
04826       unsigned StackAlign = DAG.getTarget().getFrameInfo()->getStackAlignment();
04827       unsigned Align = MinAlign(ObjectOffset, StackAlign);
04828 
04829       // Finally, the frame object itself may have a known alignment.  Factor
04830       // the alignment + offset into a new alignment.  For example, if we know
04831       // the  FI is 8 byte aligned, but the pointer is 4 off, we really have a
04832       // 4-byte alignment of the resultant pointer.  Likewise align 4 + 4-byte
04833       // offset = 4-byte alignment, align 4 + 1-byte offset = align 1, etc.
04834       unsigned FIInfoAlign = MinAlign(MFI.getObjectAlignment(FrameIdx),
04835                                       FrameOffset);
04836       return std::max(Align, FIInfoAlign);
04837     }
04838   }
04839 
04840   return 0;
04841 }
04842 
04843 SDValue DAGCombiner::visitLOAD(SDNode *N) {
04844   LoadSDNode *LD  = cast<LoadSDNode>(N);
04845   SDValue Chain = LD->getChain();
04846   SDValue Ptr   = LD->getBasePtr();
04847 
04848   // Try to infer better alignment information than the load already has.
04849   if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
04850     if (unsigned Align = InferAlignment(Ptr, DAG)) {
04851       if (Align > LD->getAlignment())
04852         return DAG.getExtLoad(LD->getExtensionType(), N->getDebugLoc(),
04853                               LD->getValueType(0),
04854                               Chain, Ptr, LD->getSrcValue(),
04855                               LD->getSrcValueOffset(), LD->getMemoryVT(),
04856                               LD->isVolatile(), Align);
04857     }
04858   }
04859 
04860   // If load is not volatile and there are no uses of the loaded value (and
04861   // the updated indexed value in case of indexed loads), change uses of the
04862   // chain value into uses of the chain input (i.e. delete the dead load).
04863   if (!LD->isVolatile()) {
04864     if (N->getValueType(1) == MVT::Other) {
04865       // Unindexed loads.
04866       if (N->hasNUsesOfValue(0, 0)) {
04867         // It's not safe to use the two value CombineTo variant here. e.g.
04868         // v1, chain2 = load chain1, loc
04869         // v2, chain3 = load chain2, loc
04870         // v3         = add v2, c
04871         // Now we replace use of chain2 with chain1.  This makes the second load
04872         // isomorphic to the one we are deleting, and thus makes this load live.
04873         DOUT << "\nReplacing.6 "; DEBUG(N->dump(&DAG));
04874         DOUT << "\nWith chain: "; DEBUG(Chain.getNode()->dump(&DAG));
04875         DOUT << "\n";
04876         WorkListRemover DeadNodes(*this);
04877         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain, &DeadNodes);
04878 
04879         if (N->use_empty()) {
04880           removeFromWorkList(N);
04881           DAG.DeleteNode(N);
04882         }
04883 
04884         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
04885       }
04886     } else {
04887       // Indexed loads.
04888       assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
04889       if (N->hasNUsesOfValue(0, 0) && N->hasNUsesOfValue(0, 1)) {
04890         SDValue Undef = DAG.getUNDEF(N->getValueType(0));
04891         DOUT << "\nReplacing.6 "; DEBUG(N->dump(&DAG));
04892         DOUT << "\nWith: "; DEBUG(Undef.getNode()->dump(&DAG));
04893         DOUT << " and 2 other values\n";
04894         WorkListRemover DeadNodes(*this);
04895         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef, &DeadNodes);
04896         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1),
04897                                       DAG.getUNDEF(N->getValueType(1)),
04898                                       &DeadNodes);
04899         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain, &DeadNodes);
04900         removeFromWorkList(N);
04901         DAG.DeleteNode(N);
04902         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
04903       }
04904     }
04905   }
04906 
04907   // If this load is directly stored, replace the load value with the stored
04908   // value.
04909   // TODO: Handle store large -> read small portion.
04910   // TODO: Handle TRUNCSTORE/LOADEXT
04911   if (LD->getExtensionType() == ISD::NON_EXTLOAD &&
04912       !LD->isVolatile()) {
04913     if (ISD::isNON_TRUNCStore(Chain.getNode())) {
04914       StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
04915       if (PrevST->getBasePtr() == Ptr &&
04916           PrevST->getValue().getValueType() == N->getValueType(0))
04917       return CombineTo(N, Chain.getOperand(1), Chain);
04918     }
04919   }
04920 
04921   if (CombinerAA) {
04922     // Walk up chain skipping non-aliasing memory nodes.
04923     SDValue BetterChain = FindBetterChain(N, Chain);
04924 
04925     // If there is a better chain.
04926     if (Chain != BetterChain) {
04927       SDValue ReplLoad;
04928 
04929       // Replace the chain to void dependency.
04930       if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
04931         ReplLoad = DAG.getLoad(N->getValueType(0), LD->getDebugLoc(),
04932                                BetterChain, Ptr,
04933                                LD->getSrcValue(), LD->getSrcValueOffset(),
04934                                LD->isVolatile(), LD->getAlignment());
04935       } else {
04936         ReplLoad = DAG.getExtLoad(LD->getExtensionType(), LD->getDebugLoc(),
04937                                   LD->getValueType(0),
04938                                   BetterChain, Ptr, LD->getSrcValue(),
04939                                   LD->getSrcValueOffset(),
04940                                   LD->getMemoryVT(),
04941                                   LD->isVolatile(),
04942                                   LD->getAlignment());
04943       }
04944 
04945       // Create token factor to keep old chain connected.
04946       SDValue Token = DAG.getNode(ISD::TokenFactor, N->getDebugLoc(),
04947                                   MVT::Other, Chain, ReplLoad.getValue(1));
04948 
04949       // Replace uses with load result and token factor. Don't add users
04950       // to work list.
04951       return CombineTo(N, ReplLoad.getValue(0), Token, false);
04952     }
04953   }
04954 
04955   // Try transforming N to an indexed load.
04956   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
04957     return SDValue(N, 0);
04958 
04959   return SDValue();
04960 }
04961 
04962 
04963 /// ReduceLoadOpStoreWidth - Look for sequence of load / op / store where op is
04964 /// one of 'or', 'xor', and 'and' of immediates. If 'op' is only touching some
04965 /// of the loaded bits, try narrowing the load and store if it would end up
04966 /// being a win for performance or code size.
04967 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
04968   StoreSDNode *ST  = cast<StoreSDNode>(N);
04969   if (ST->isVolatile())
04970     return SDValue();
04971 
04972   SDValue Chain = ST->getChain();
04973   SDValue Value = ST->getValue();
04974   SDValue Ptr   = ST->getBasePtr();
04975   EVT VT = Value.getValueType();
04976 
04977   if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
04978     return SDValue();
04979 
04980   unsigned Opc = Value.getOpcode();
04981   if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
04982       Value.getOperand(1).getOpcode() != ISD::Constant)
04983     return SDValue();
04984 
04985   SDValue N0 = Value.getOperand(0);
04986   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse()) {
04987     LoadSDNode *LD = cast<LoadSDNode>(N0);
04988     if (LD->getBasePtr() != Ptr)
04989       return SDValue();
04990 
04991     // Find the type to narrow it the load / op / store to.
04992     SDValue N1 = Value.getOperand(1);
04993     unsigned BitWidth = N1.getValueSizeInBits();
04994     APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
04995     if (Opc == ISD::AND)
04996       Imm ^= APInt::getAllOnesValue(BitWidth);
04997     if (Imm == 0 || Imm.isAllOnesValue())
04998       return SDValue();
04999     unsigned ShAmt = Imm.countTrailingZeros();
05000     unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
05001     unsigned NewBW = NextPowerOf2(MSB - ShAmt);
05002     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
05003     while (NewBW < BitWidth &&
05004            !(TLI.isOperationLegalOrCustom(Opc, NewVT) &&
05005              TLI.isNarrowingProfitable(VT, NewVT))) {
05006       NewBW = NextPowerOf2(NewBW);
05007       NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
05008     }
05009     if (NewBW >= BitWidth)
05010       return SDValue();
05011 
05012     // If the lsb changed does not start at the type bitwidth boundary,
05013     // start at the previous one.
05014     if (ShAmt % NewBW)
05015       ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
05016     APInt Mask = APInt::getBitsSet(BitWidth, ShAmt, ShAmt + NewBW);
05017     if ((Imm & Mask) == Imm) {
05018       APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
05019       if (Opc == ISD::AND)
05020         NewImm ^= APInt::getAllOnesValue(NewBW);
05021       uint64_t PtrOff = ShAmt / 8;
05022       // For big endian targets, we need to adjust the offset to the pointer to
05023       // load the correct bytes.
05024       if (TLI.isBigEndian())
05025         PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
05026 
05027       unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
05028       if (NewAlign <
05029           TLI.getTargetData()->getABITypeAlignment(NewVT.getTypeForEVT(*DAG.getContext())))
05030         return SDValue();
05031 
05032       SDValue NewPtr = DAG.getNode(ISD::ADD, LD->getDebugLoc(),
05033                                    Ptr.getValueType(), Ptr,
05034                                    DAG.getConstant(PtrOff, Ptr.getValueType()));
05035       SDValue NewLD = DAG.getLoad(NewVT, N0.getDebugLoc(),
05036                                   LD->getChain(), NewPtr,
05037                                   LD->getSrcValue(), LD->getSrcValueOffset(),
05038                                   LD->isVolatile(), NewAlign);
05039       SDValue NewVal = DAG.getNode(Opc, Value.getDebugLoc(), NewVT, NewLD,
05040                                    DAG.getConstant(NewImm, NewVT));
05041       SDValue NewST = DAG.getStore(Chain, N->getDebugLoc(),
05042                                    NewVal, NewPtr,
05043                                    ST->getSrcValue(), ST->getSrcValueOffset(),
05044                                    false, NewAlign);
05045 
05046       AddToWorkList(NewPtr.getNode());
05047       AddToWorkList(NewLD.getNode());
05048       AddToWorkList(NewVal.getNode());
05049       WorkListRemover DeadNodes(*this);
05050       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1),
05051                                     &DeadNodes);
05052       ++OpsNarrowed;
05053       return NewST;
05054     }
05055   }
05056 
05057   return SDValue();
05058 }
05059 
05060 SDValue DAGCombiner::visitSTORE(SDNode *N) {
05061   StoreSDNode *ST  = cast<StoreSDNode>(N);
05062   SDValue Chain = ST->getChain();
05063   SDValue Value = ST->getValue();
05064   SDValue Ptr   = ST->getBasePtr();
05065 
05066   // Try to infer better alignment information than the store already has.
05067   if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
05068     if (unsigned Align = InferAlignment(Ptr, DAG)) {
05069       if (Align > ST->getAlignment())
05070         return DAG.getTruncStore(Chain, N->getDebugLoc(), Value,
05071                                  Ptr, ST->getSrcValue(),
05072                                  ST->getSrcValueOffset(), ST->getMemoryVT(),
05073                                  ST->isVolatile(), Align);
05074     }
05075   }
05076 
05077   // If this is a store of a bit convert, store the input value if the
05078   // resultant store does not need a higher alignment than the original.
05079   if (Value.getOpcode() == ISD::BIT_CONVERT && !ST->isTruncatingStore() &&
05080       ST->isUnindexed()) {
05081     unsigned OrigAlign = ST->getAlignment();
05082     EVT SVT = Value.getOperand(0).getValueType();
05083     unsigned Align = TLI.getTargetData()->
05084       getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
05085     if (Align <= OrigAlign &&
05086         ((!LegalOperations && !ST->isVolatile()) ||
05087          TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
05088       return DAG.getStore(Chain, N->getDebugLoc(), Value.getOperand(0),
05089                           Ptr, ST->getSrcValue(),
05090                           ST->getSrcValueOffset(), ST->isVolatile(), OrigAlign);
05091   }
05092 
05093   // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
05094   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
05095     // NOTE: If the original store is volatile, this transform must not increase
05096     // the number of stores.  For example, on x86-32 an f64 can be stored in one
05097     // processor operation but an i64 (which is not legal) requires two.  So the
05098     // transform should not be done in this case.
05099     if (Value.getOpcode() != ISD::TargetConstantFP) {
05100       SDValue Tmp;
05101       switch (CFP->getValueType(0).getSimpleVT().SimpleTy) {
05102       default: llvm_unreachable("Unknown FP type");
05103       case MVT::f80:    // We don't do this for these yet.
05104       case MVT::f128:
05105       case MVT::ppcf128:
05106         break;
05107       case MVT::f32:
05108         if (((TLI.isTypeLegal(MVT::i32) || !LegalTypes) && !LegalOperations &&
05109              !ST->isVolatile()) ||
05110             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
05111           Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
05112                               bitcastToAPInt().getZExtValue(), MVT::i32);
05113           return DAG.getStore(Chain, N->getDebugLoc(), Tmp,
05114                               Ptr, ST->getSrcValue(),
05115                               ST->getSrcValueOffset(), ST->isVolatile(),
05116                               ST->getAlignment());
05117         }
05118         break;
05119       case MVT::f64:
05120         if (((TLI.isTypeLegal(MVT::i64) || !LegalTypes) && !LegalOperations &&
05121              !ST->isVolatile()) ||
05122             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
05123           Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
05124                                 getZExtValue(), MVT::i64);
05125           return DAG.getStore(Chain, N->getDebugLoc(), Tmp,
05126                               Ptr, ST->getSrcValue(),
05127                               ST->getSrcValueOffset(), ST->isVolatile(),
05128                               ST->getAlignment());
05129         } else if (!ST->isVolatile() &&
05130                    TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
05131           // Many FP stores are not made apparent until after legalize, e.g. for
05132           // argument passing.  Since this is so common, custom legalize the
05133           // 64-bit integer store into two 32-bit stores.
05134           uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
05135           SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
05136           SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
05137           if (TLI.isBigEndian()) std::swap(Lo, Hi);
05138 
05139           int SVOffset = ST->getSrcValueOffset();
05140           unsigned Alignment = ST->getAlignment();
05141           bool isVolatile = ST->isVolatile();
05142 
05143           SDValue St0 = DAG.getStore(Chain, ST->getDebugLoc(), Lo,
05144                                      Ptr, ST->getSrcValue(),
05145                                      ST->getSrcValueOffset(),
05146                                      isVolatile, ST->getAlignment());
05147           Ptr = DAG.getNode(ISD::ADD, N->getDebugLoc(), Ptr.getValueType(), Ptr,
05148                             DAG.getConstant(4, Ptr.getValueType()));
05149           SVOffset += 4;
05150           Alignment = MinAlign(Alignment, 4U);
05151           SDValue St1 = DAG.getStore(Chain, ST->getDebugLoc(), Hi,
05152                                      Ptr, ST->getSrcValue(),
05153                                      SVOffset, isVolatile, Alignment);
05154           return DAG.getNode(ISD::TokenFactor, N->getDebugLoc(), MVT::Other,
05155                              St0, St1);
05156         }
05157 
05158         break;
05159       }
05160     }
05161   }
05162 
05163   if (CombinerAA) {
05164     // Walk up chain skipping non-aliasing memory nodes.
05165     SDValue BetterChain = FindBetterChain(N, Chain);
05166 
05167     // If there is a better chain.
05168     if (Chain != BetterChain) {
05169       // Replace the chain to avoid dependency.
05170       SDValue ReplStore;
05171       if (ST->isTruncatingStore()) {
05172         ReplStore = DAG.getTruncStore(BetterChain, N->getDebugLoc(), Value, Ptr,
05173                                       ST->getSrcValue(),ST->getSrcValueOffset(),
05174                                       ST->getMemoryVT(),
05175                                       ST->isVolatile(), ST->getAlignment());
05176       } else {
05177         ReplStore = DAG.getStore(BetterChain, N->getDebugLoc(), Value, Ptr,
05178                                  ST->getSrcValue(), ST->getSrcValueOffset(),
05179                                  ST->isVolatile(), ST->getAlignment());
05180       }
05181 
05182       // Create token to keep both nodes around.
05183       SDValue Token = DAG.getNode(ISD::TokenFactor, N->getDebugLoc(),
05184                                   MVT::Other, Chain, ReplStore);
05185 
05186       // Don't add users to work list.
05187       return CombineTo(N, Token, false);
05188     }
05189   }
05190 
05191   // Try transforming N to an indexed store.
05192   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
05193     return SDValue(N, 0);
05194 
05195   // FIXME: is there such a thing as a truncating indexed store?
05196   if (ST->isTruncatingStore() && ST->isUnindexed() &&
05197       Value.getValueType().isInteger()) {
05198     // See if we can simplify the input to this truncstore with knowledge that
05199     // only the low bits are being used.  For example:
05200     // "truncstore (or (shl x, 8), y), i8"  -> "truncstore y, i8"
05201     SDValue Shorter =
05202       GetDemandedBits(Value,
05203                       APInt::getLowBitsSet(Value.getValueSizeInBits(),
05204                                            ST->getMemoryVT().getSizeInBits()));
05205     AddToWorkList(Value.getNode());
05206     if (Shorter.getNode())
05207       return DAG.getTruncStore(Chain, N->getDebugLoc(), Shorter,
05208                                Ptr, ST->getSrcValue(),
05209                                ST->getSrcValueOffset(), ST->getMemoryVT(),
05210                                ST->isVolatile(), ST->getAlignment());
05211 
05212     // Otherwise, see if we can simplify the operation with
05213     // SimplifyDemandedBits, which only works if the value has a single use.
05214     if (SimplifyDemandedBits(Value,
05215                              APInt::getLowBitsSet(
05216                                Value.getValueSizeInBits(),
05217                                ST->getMemoryVT().getSizeInBits())))
05218       return SDValue(N, 0);
05219   }
05220 
05221   // If this is a load followed by a store to the same location, then the store
05222   // is dead/noop.
05223   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
05224     if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
05225         ST->isUnindexed() && !ST->isVolatile() &&
05226         // There can't be any side effects between the load and store, such as
05227         // a call or store.
05228         Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
05229       // The store is dead, remove it.
05230       return Chain;
05231     }
05232   }
05233 
05234   // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
05235   // truncating store.  We can do this even if this is already a truncstore.
05236   if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
05237       && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
05238       TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
05239                             ST->getMemoryVT())) {
05240     return DAG.getTruncStore(Chain, N->getDebugLoc(), Value.getOperand(0),
05241                              Ptr, ST->getSrcValue(),
05242                              ST->getSrcValueOffset(), ST->getMemoryVT(),
05243                              ST->isVolatile(), ST->getAlignment());
05244   }
05245 
05246   return ReduceLoadOpStoreWidth(N);
05247 }
05248 
05249 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
05250   SDValue InVec = N->getOperand(0);
05251   SDValue InVal = N->getOperand(1);
05252   SDValue EltNo = N->getOperand(2);
05253 
05254   // If the invec is a BUILD_VECTOR and if EltNo is a constant, build a new
05255   // vector with the inserted element.
05256   if (InVec.getOpcode() == ISD::BUILD_VECTOR && isa<ConstantSDNode>(EltNo)) {
05257     unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
05258     SmallVector<SDValue, 8> Ops(InVec.getNode()->op_begin(),
05259                                 InVec.getNode()->op_end());
05260     if (Elt < Ops.size())
05261       Ops[Elt] = InVal;
05262     return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(),
05263                        InVec.getValueType(), &Ops[0], Ops.size());
05264   }
05265   // If the invec is an UNDEF and if EltNo is a constant, create a new 
05266   // BUILD_VECTOR with undef elements and the inserted element.
05267   if (!LegalOperations && InVec.getOpcode() == ISD::UNDEF && 
05268       isa<ConstantSDNode>(EltNo)) {
05269     EVT VT = InVec.getValueType();
05270     EVT EVT = VT.getVectorElementType();
05271     unsigned NElts = VT.getVectorNumElements();
05272     SmallVector<SDValue, 8> Ops(NElts, DAG.getUNDEF(EVT));
05273 
05274     unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
05275     if (Elt < Ops.size())
05276       Ops[Elt] = InVal;
05277     return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(),
05278                        InVec.getValueType(), &Ops[0], Ops.size());
05279   }
05280   return SDValue();
05281 }
05282 
05283 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
05284   // (vextract (scalar_to_vector val, 0) -> val
05285   SDValue InVec = N->getOperand(0);
05286 
05287  if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
05288    // If the operand is wider than the vector element type then it is implicitly
05289    // truncated.  Make that explicit here.
05290    EVT EltVT = InVec.getValueType().getVectorElementType();
05291    SDValue InOp = InVec.getOperand(0);
05292    if (InOp.getValueType() != EltVT)
05293      return DAG.getNode(ISD::TRUNCATE, InVec.getDebugLoc(), EltVT, InOp);
05294    return InOp;
05295  }
05296 
05297   // Perform only after legalization to ensure build_vector / vector_shuffle
05298   // optimizations have already been done.
05299   if (!LegalOperations) return SDValue();
05300 
05301   // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
05302   // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
05303   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
05304   SDValue EltNo = N->getOperand(1);
05305 
05306   if (isa<ConstantSDNode>(EltNo)) {
05307     unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
05308     bool NewLoad = false;
05309     bool BCNumEltsChanged = false;
05310     EVT VT = InVec.getValueType();
05311     EVT ExtVT = VT.getVectorElementType();
05312     EVT LVT = ExtVT;
05313 
05314     if (InVec.getOpcode() == ISD::BIT_CONVERT) {
05315       EVT BCVT = InVec.getOperand(0).getValueType();
05316       if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
05317         return SDValue();
05318       if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
05319         BCNumEltsChanged = true;
05320       InVec = InVec.getOperand(0);
05321       ExtVT = BCVT.getVectorElementType();
05322       NewLoad = true;
05323     }
05324 
05325     LoadSDNode *LN0 = NULL;
05326     const ShuffleVectorSDNode *SVN = NULL;
05327     if (ISD::isNormalLoad(InVec.getNode())) {
05328       LN0 = cast<LoadSDNode>(InVec);
05329     } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
05330                InVec.getOperand(0).getValueType() == ExtVT &&
05331                ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
05332       LN0 = cast<LoadSDNode>(InVec.getOperand(0));
05333     } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
05334       // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
05335       // =>
05336       // (load $addr+1*size)
05337 
05338       // If the bit convert changed the number of elements, it is unsafe
05339       // to examine the mask.
05340       if (BCNumEltsChanged)
05341         return SDValue();
05342 
05343       // Select the input vector, guarding against out of range extract vector.
05344       unsigned NumElems = VT.getVectorNumElements();
05345       int Idx = (Elt > NumElems) ? -1 : SVN->getMaskElt(Elt);
05346       InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
05347 
05348       if (InVec.getOpcode() == ISD::BIT_CONVERT)
05349         InVec = InVec.getOperand(0);
05350       if (ISD::isNormalLoad(InVec.getNode())) {
05351         LN0 = cast<LoadSDNode>(InVec);
05352         Elt = (Idx < (int)NumElems) ? Idx : Idx - NumElems;
05353       }
05354     }
05355 
05356     if (!LN0 || !LN0->hasOneUse() || LN0->isVolatile())
05357       return SDValue();
05358 
05359     unsigned Align = LN0->getAlignment();
05360     if (NewLoad) {
05361       // Check the resultant load doesn't need a higher alignment than the
05362       // original load.
05363       unsigned NewAlign =
05364         TLI.getTargetData()->getABITypeAlignment(LVT.getTypeForEVT(*DAG.getContext()));
05365 
05366       if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, LVT))
05367         return SDValue();
05368 
05369       Align = NewAlign;
05370     }
05371 
05372     SDValue NewPtr = LN0->getBasePtr();
05373     if (Elt) {
05374       unsigned PtrOff = LVT.getSizeInBits() * Elt / 8;
05375       EVT PtrType = NewPtr.getValueType();
05376       if (TLI.isBigEndian())
05377         PtrOff = VT.getSizeInBits() / 8 - PtrOff;
05378       NewPtr = DAG.getNode(ISD::ADD, N->getDebugLoc(), PtrType, NewPtr,
05379                            DAG.getConstant(PtrOff, PtrType));
05380     }
05381 
05382     return DAG.getLoad(LVT, N->getDebugLoc(), LN0->getChain(), NewPtr,
05383                        LN0->getSrcValue(), LN0->getSrcValueOffset(),
05384                        LN0->isVolatile(), Align);
05385   }
05386 
05387   return SDValue();
05388 }
05389 
05390 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
05391   unsigned NumInScalars = N->getNumOperands();
05392   EVT VT = N->getValueType(0);
05393   EVT EltType = VT.getVectorElementType();
05394 
05395   // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
05396   // operations.  If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
05397   // at most two distinct vectors, turn this into a shuffle node.
05398   SDValue VecIn1, VecIn2;
05399   for (unsigned i = 0; i != NumInScalars; ++i) {
05400     // Ignore undef inputs.
05401     if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
05402 
05403     // If this input is something other than a EXTRACT_VECTOR_ELT with a
05404     // constant index, bail out.
05405     if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
05406         !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) {
05407       VecIn1 = VecIn2 = SDValue(0, 0);
05408       break;
05409     }
05410 
05411     // If the input vector type disagrees with the result of the build_vector,
05412     // we can't make a shuffle.
05413     SDValue ExtractedFromVec = N->getOperand(i).getOperand(0);
05414     if (ExtractedFromVec.getValueType() != VT) {
05415       VecIn1 = VecIn2 = SDValue(0, 0);
05416       break;
05417     }
05418 
05419     // Otherwise, remember this.  We allow up to two distinct input vectors.
05420     if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
05421       continue;
05422 
05423     if (VecIn1.getNode() == 0) {
05424       VecIn1 = ExtractedFromVec;
05425     } else if (VecIn2.getNode() == 0) {
05426       VecIn2 = ExtractedFromVec;
05427     } else {
05428       // Too many inputs.
05429       VecIn1 = VecIn2 = SDValue(0, 0);
05430       break;
05431     }
05432   }
05433 
05434   // If everything is good, we can make a shuffle operation.
05435   if (VecIn1.getNode()) {
05436     SmallVector<int, 8> Mask;
05437     for (unsigned i = 0; i != NumInScalars; ++i) {
05438       if (N->getOperand(i).getOpcode() == ISD::UNDEF) {
05439         Mask.push_back(-1);
05440         continue;
05441       }
05442 
05443       // If extracting from the first vector, just use the index directly.
05444       SDValue Extract = N->getOperand(i);
05445       SDValue ExtVal = Extract.getOperand(1);
05446       if (Extract.getOperand(0) == VecIn1) {
05447         unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
05448         if (ExtIndex > VT.getVectorNumElements())
05449           return SDValue();
05450         
05451         Mask.push_back(ExtIndex);
05452         continue;
05453       }
05454 
05455       // Otherwise, use InIdx + VecSize
05456       unsigned Idx = cast<ConstantSDNode>(ExtVal)->getZExtValue();
05457       Mask.push_back(Idx+NumInScalars);
05458     }
05459 
05460     // Add count and size info.
05461     if (!TLI.isTypeLegal(VT) && LegalTypes)
05462       return SDValue();
05463 
05464     // Return the new VECTOR_SHUFFLE node.
05465     SDValue Ops[2];
05466     Ops[0] = VecIn1;
05467     Ops[1] = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
05468     return DAG.getVectorShuffle(VT, N->getDebugLoc(), Ops[0], Ops[1], &Mask[0]);
05469   }
05470 
05471   return SDValue();
05472 }
05473 
05474 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
05475   // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
05476   // EXTRACT_SUBVECTOR operations.  If so, and if the EXTRACT_SUBVECTOR vector
05477   // inputs come from at most two distinct vectors, turn this into a shuffle
05478   // node.
05479 
05480   // If we only have one input vector, we don't need to do any concatenation.
05481   if (N->getNumOperands() == 1)
05482     return N->getOperand(0);
05483 
05484   return SDValue();
05485 }
05486 
05487 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
05488   return SDValue();
05489   
05490   EVT VT = N->getValueType(0);
05491   unsigned NumElts = VT.getVectorNumElements();
05492 
05493   SDValue N0 = N->getOperand(0);
05494   SDValue N1 = N->getOperand(1);
05495 
05496   assert(N0.getValueType().getVectorNumElements() == NumElts &&
05497         "Vector shuffle must be normalized in DAG");
05498 
05499   // FIXME: implement canonicalizations from DAG.getVectorShuffle()
05500 
05501   // If it is a splat, check if the argument vector is a build_vector with
05502   // all scalar elements the same.
05503   if (cast<ShuffleVectorSDNode>(N)->isSplat()) {
05504     SDNode *V = N0.getNode();
05505     
05506 
05507     // If this is a bit convert that changes the element type of the vector but
05508     // not the number of vector elements, look through it.  Be careful not to
05509     // look though conversions that change things like v4f32 to v2f64.
05510     if (V->getOpcode() == ISD::BIT_CONVERT) {
05511       SDValue ConvInput = V->getOperand(0);
05512       if (ConvInput.getValueType().isVector() &&
05513           ConvInput.getValueType().getVectorNumElements() == NumElts)
05514         V = ConvInput.getNode();
05515     }
05516 
05517     if (V->getOpcode() == ISD::BUILD_VECTOR) {
05518       unsigned NumElems = V->getNumOperands();
05519       unsigned BaseIdx = cast<ShuffleVectorSDNode>(N)->getSplatIndex();
05520       if (NumElems > BaseIdx) {
05521         SDValue Base;
05522         bool AllSame = true;
05523         for (unsigned i = 0; i != NumElems; ++i) {
05524           if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
05525             Base = V->getOperand(i);
05526             break;
05527           }
05528         }
05529         // Splat of <u, u, u, u>, return <u, u, u, u>
05530         if (!Base.getNode())
05531           return N0;
05532         for (unsigned i = 0; i != NumElems; ++i) {
05533           if (V->getOperand(i) != Base) {
05534             AllSame = false;
05535             break;
05536           }
05537         }
05538         // Splat of <x, x, x, x>, return <x, x, x, x>
05539         if (AllSame)
05540           return N0;
05541       }
05542     }
05543   }
05544   return SDValue();
05545 }
05546 
05547 /// XformToShuffleWithZero - Returns a vector_shuffle if it able to transform
05548 /// an AND to a vector_shuffle with the destination vector and a zero vector.
05549 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
05550 ///      vector_shuffle V, Zero, <0, 4, 2, 4>
05551 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
05552   EVT VT = N->getValueType(0);
05553   DebugLoc dl = N->getDebugLoc();
05554   SDValue LHS = N->getOperand(0);
05555   SDValue RHS = N->getOperand(1);
05556   if (N->getOpcode() == ISD::AND) {
05557     if (RHS.getOpcode() == ISD::BIT_CONVERT)
05558       RHS = RHS.getOperand(0);
05559     if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
05560       SmallVector<int, 8> Indices;
05561       unsigned NumElts = RHS.getNumOperands();
05562       for (unsigned i = 0; i != NumElts; ++i) {
05563         SDValue Elt = RHS.getOperand(i);
05564         if (!isa<ConstantSDNode>(Elt))
05565           return SDValue();
05566         else if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
05567           Indices.push_back(i);
05568         else if (cast<ConstantSDNode>(Elt)->isNullValue())
05569           Indices.push_back(NumElts);
05570         else
05571           return SDValue();
05572       }
05573 
05574       // Let's see if the target supports this vector_shuffle.
05575       EVT RVT = RHS.getValueType();
05576       if (!TLI.isVectorClearMaskLegal(Indices, RVT))
05577         return SDValue();
05578 
05579       // Return the new VECTOR_SHUFFLE node.
05580       EVT EVT = RVT.getVectorElementType();
05581       SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
05582                                      DAG.getConstant(0, EVT));
05583       SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(),
05584                                  RVT, &ZeroOps[0], ZeroOps.size());
05585       LHS = DAG.getNode(ISD::BIT_CONVERT, dl, RVT, LHS);
05586       SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
05587       return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Shuf);
05588     }
05589   }
05590 
05591   return SDValue();
05592 }
05593 
05594 /// SimplifyVBinOp - Visit a binary vector operation, like ADD.
05595 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
05596   // After legalize, the target may be depending on adds and other
05597   // binary ops to provide legal ways to construct constants or other
05598   // things. Simplifying them may result in a loss of legality.
05599   if (LegalOperations) return SDValue();
05600 
05601   EVT VT = N->getValueType(0);
05602   assert(VT.isVector() && "SimplifyVBinOp only works on vectors!");
05603 
05604   EVT EltType = VT.getVectorElementType();
05605   SDValue LHS = N->getOperand(0);
05606   SDValue RHS = N->getOperand(1);
05607   SDValue Shuffle = XformToShuffleWithZero(N);
05608   if (Shuffle.getNode()) return Shuffle;
05609 
05610   // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
05611   // this operation.
05612   if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
05613       RHS.getOpcode() == ISD::BUILD_VECTOR) {
05614     SmallVector<SDValue, 8> Ops;
05615     for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
05616       SDValue LHSOp = LHS.getOperand(i);
05617       SDValue RHSOp = RHS.getOperand(i);
05618       // If these two elements can't be folded, bail out.
05619       if ((LHSOp.getOpcode() != ISD::UNDEF &&
05620            LHSOp.getOpcode() != ISD::Constant &&
05621            LHSOp.getOpcode() != ISD::ConstantFP) ||
05622           (RHSOp.getOpcode() != ISD::UNDEF &&
05623            RHSOp.getOpcode() != ISD::Constant &&
05624            RHSOp.getOpcode() != ISD::ConstantFP))
05625         break;
05626 
05627       // Can't fold divide by zero.
05628       if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
05629           N->getOpcode() == ISD::FDIV) {
05630         if ((RHSOp.getOpcode() == ISD::Constant &&
05631              cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
05632             (RHSOp.getOpcode() == ISD::ConstantFP &&
05633              cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
05634           break;
05635       }
05636 
05637       Ops.push_back(DAG.getNode(N->getOpcode(), LHS.getDebugLoc(),
05638                                 EltType, LHSOp, RHSOp));
05639       AddToWorkList(Ops.back().getNode());
05640       assert((Ops.back().getOpcode() == ISD::UNDEF ||
05641               Ops.back().getOpcode() == ISD::Constant ||
05642               Ops.back().getOpcode() == ISD::ConstantFP) &&
05643              "Scalar binop didn't fold!");
05644     }
05645 
05646     if (Ops.size() == LHS.getNumOperands()) {
05647       EVT VT = LHS.getValueType();
05648       return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(), VT,
05649                          &Ops[0], Ops.size());
05650     }
05651   }
05652 
05653   return SDValue();
05654 }
05655 
05656 SDValue DAGCombiner::SimplifySelect(DebugLoc DL, SDValue N0,
05657                                     SDValue N1, SDValue N2){
05658   assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
05659 
05660   SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
05661                                  cast<CondCodeSDNode>(N0.getOperand(2))->get());
05662 
05663   // If we got a simplified select_cc node back from SimplifySelectCC, then
05664   // break it down into a new SETCC node, and a new SELECT node, and then return
05665   // the SELECT node, since we were called with a SELECT node.
05666   if (SCC.getNode()) {
05667     // Check to see if we got a select_cc back (to turn into setcc/select).
05668     // Otherwise, just return whatever node we got back, like fabs.
05669     if (SCC.getOpcode() == ISD::SELECT_CC) {
05670       SDValue SETCC = DAG.getNode(ISD::SETCC, N0.getDebugLoc(),
05671                                   N0.getValueType(),
05672                                   SCC.getOperand(0), SCC.getOperand(1),
05673                                   SCC.getOperand(4));
05674       AddToWorkList(SETCC.getNode());
05675       return DAG.getNode(ISD::SELECT, SCC.getDebugLoc(), SCC.getValueType(),
05676                          SCC.getOperand(2), SCC.getOperand(3), SETCC);
05677     }
05678 
05679     return SCC;
05680   }
05681   return SDValue();
05682 }
05683 
05684 /// SimplifySelectOps - Given a SELECT or a SELECT_CC node, where LHS and RHS
05685 /// are the two values being selected between, see if we can simplify the
05686 /// select.  Callers of this should assume that TheSelect is deleted if this
05687 /// returns true.  As such, they should return the appropriate thing (e.g. the
05688 /// node) back to the top-level of the DAG combiner loop to avoid it being
05689 /// looked at.
05690 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
05691                                     SDValue RHS) {
05692 
05693   // If this is a select from two identical things, try to pull the operation
05694   // through the select.
05695   if (LHS.getOpcode() == RHS.getOpcode() && LHS.hasOneUse() && RHS.hasOneUse()){
05696     // If this is a load and the token chain is identical, replace the select
05697     // of two loads with a load through a select of the address to load from.
05698     // This triggers in things like "select bool X, 10.0, 123.0" after the FP
05699     // constants have been dropped into the constant pool.
05700     if (LHS.getOpcode() == ISD::LOAD &&
05701         // Do not let this transformation reduce the number of volatile loads.
05702         !cast<LoadSDNode>(LHS)->isVolatile() &&
05703         !cast<LoadSDNode>(RHS)->isVolatile() &&
05704         // Token chains must be identical.
05705         LHS.getOperand(0) == RHS.getOperand(0)) {
05706       LoadSDNode *LLD = cast<LoadSDNode>(LHS);
05707       LoadSDNode *RLD = cast<LoadSDNode>(RHS);
05708 
05709       // If this is an EXTLOAD, the VT's must match.
05710       if (LLD->getMemoryVT() == RLD->getMemoryVT()) {
05711         // FIXME: this conflates two src values, discarding one.  This is not
05712         // the right thing to do, but nothing uses srcvalues now.  When they do,
05713         // turn SrcValue into a list of locations.
05714         SDValue Addr;
05715         if (TheSelect->getOpcode() == ISD::SELECT) {
05716           // Check that the condition doesn't reach either load.  If so, folding
05717           // this will induce a cycle into the DAG.
05718           if (!LLD->isPredecessorOf(TheSelect->getOperand(0).getNode()) &&
05719               !RLD->isPredecessorOf(TheSelect->getOperand(0).getNode())) {
05720             Addr = DAG.getNode(ISD::SELECT, TheSelect->getDebugLoc(),
05721                                LLD->getBasePtr().getValueType(),
05722                                TheSelect->getOperand(0), LLD->getBasePtr(),
05723                                RLD->getBasePtr());
05724           }
05725         } else {
05726           // Check that the condition doesn't reach either load.  If so, folding
05727           // this will induce a cycle into the DAG.
05728           if (!LLD->isPredecessorOf(TheSelect->getOperand(0).getNode()) &&
05729               !RLD->isPredecessorOf(TheSelect->getOperand(0).getNode()) &&
05730               !LLD->isPredecessorOf(TheSelect->getOperand(1).getNode()) &&
05731               !RLD->isPredecessorOf(TheSelect->getOperand(1).getNode())) {
05732             Addr = DAG.getNode(ISD::SELECT_CC, TheSelect->getDebugLoc(),
05733                                LLD->getBasePtr().getValueType(),
05734                                TheSelect->getOperand(0),
05735                                TheSelect->getOperand(1),
05736                                LLD->getBasePtr(), RLD->getBasePtr(),
05737                                TheSelect->getOperand(4));
05738           }
05739         }
05740 
05741         if (Addr.getNode()) {
05742           SDValue Load;
05743           if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
05744             Load = DAG.getLoad(TheSelect->getValueType(0),
05745                                TheSelect->getDebugLoc(),
05746                                LLD->getChain(),
05747                                Addr,LLD->getSrcValue(),
05748                                LLD->getSrcValueOffset(),
05749                                LLD->isVolatile(),
05750                                LLD->getAlignment());
05751           } else {
05752             Load = DAG.getExtLoad(LLD->getExtensionType(),
05753                                   TheSelect->getDebugLoc(),
05754                                   TheSelect->getValueType(0),
05755                                   LLD->getChain(), Addr, LLD->getSrcValue(),
05756                                   LLD->getSrcValueOffset(),
05757                                   LLD->getMemoryVT(),
05758                                   LLD->isVolatile(),
05759                                   LLD->getAlignment());
05760           }
05761 
05762           // Users of the select now use the result of the load.
05763           CombineTo(TheSelect, Load);
05764 
05765           // Users of the old loads now use the new load's chain.  We know the
05766           // old-load value is dead now.
05767           CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
05768           CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
05769           return true;
05770         }
05771       }
05772     }
05773   }
05774 
05775   return false;
05776 }
05777 
05778 /// SimplifySelectCC - Simplify an expression of the form (N0 cond N1) ? N2 : N3
05779 /// where 'cond' is the comparison specified by CC.
05780 SDValue DAGCombiner::SimplifySelectCC(DebugLoc DL, SDValue N0, SDValue N1,
05781                                       SDValue N2, SDValue N3,
05782                                       ISD::CondCode CC, bool NotExtCompare) {
05783   // (x ? y : y) -> y.
05784   if (N2 == N3) return N2;
05785   
05786   EVT VT = N2.getValueType();
05787   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
05788   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
05789   ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
05790 
05791   // Determine if the condition we're dealing with is constant
05792   SDValue SCC = SimplifySetCC(TLI.getSetCCResultType(N0.getValueType()),
05793                               N0, N1, CC, DL, false);
05794   if (SCC.getNode()) AddToWorkList(SCC.getNode());
05795   ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
05796 
05797   // fold select_cc true, x, y -> x
05798   if (SCCC && !SCCC->isNullValue())
05799     return N2;
05800   // fold select_cc false, x, y -> y
05801   if (SCCC && SCCC->isNullValue())
05802     return N3;
05803 
05804   // Check to see if we can simplify the select into an fabs node
05805   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
05806     // Allow either -0.0 or 0.0
05807     if (CFP->getValueAPF().isZero()) {
05808       // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
05809       if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
05810           N0 == N2 && N3.getOpcode() == ISD::FNEG &&
05811           N2 == N3.getOperand(0))
05812         return DAG.getNode(ISD::FABS, DL, VT, N0);
05813 
05814       // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
05815       if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
05816           N0 == N3 && N2.getOpcode() == ISD::FNEG &&
05817           N2.getOperand(0) == N3)
05818         return DAG.getNode(ISD::FABS, DL, VT, N3);
05819     }
05820   }
05821   
05822   // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
05823   // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
05824   // in it.  This is a win when the constant is not otherwise available because
05825   // it replaces two constant pool loads with one.  We only do this if the FP
05826   // type is known to be legal, because if it isn't, then we are before legalize
05827   // types an we want the other legalization to happen first (e.g. to avoid
05828   // messing with soft float) and if the ConstantFP is not legal, because if
05829   // it is legal, we may not need to store the FP constant in a constant pool.
05830   if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
05831     if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
05832       if (TLI.isTypeLegal(N2.getValueType()) &&
05833           (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
05834            TargetLowering::Legal) &&
05835           // If both constants have multiple uses, then we won't need to do an
05836           // extra load, they are likely around in registers for other users.
05837           (TV->hasOneUse() || FV->hasOneUse())) {
05838         Constant *Elts[] = {
05839           const_cast<ConstantFP*>(FV->getConstantFPValue()),
05840           const_cast<ConstantFP*>(TV->getConstantFPValue())
05841         };
05842         const Type *FPTy = Elts[0]->getType();
05843         const TargetData &TD = *TLI.getTargetData();
05844         
05845         // Create a ConstantArray of the two constants.
05846         Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts, 2);
05847         SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
05848                                             TD.getPrefTypeAlignment(FPTy));
05849         unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
05850 
05851         // Get the offsets to the 0 and 1 element of the array so that we can
05852         // select between them.
05853         SDValue Zero = DAG.getIntPtrConstant(0);
05854         unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
05855         SDValue One = DAG.getIntPtrConstant(EltSize);
05856         
05857         SDValue Cond = DAG.getSetCC(DL,
05858                                     TLI.getSetCCResultType(N0.getValueType()),
05859                                     N0, N1, CC);
05860         SDValue CstOffset = DAG.getNode(ISD::SELECT, DL, Zero.getValueType(),
05861                                         Cond, One, Zero);
05862         CPIdx = DAG.getNode(ISD::ADD, DL, TLI.getPointerTy(), CPIdx,
05863                             CstOffset);
05864         return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
05865                            PseudoSourceValue::getConstantPool(), 0, false,
05866                            Alignment);
05867 
05868       }
05869     }  
05870 
05871   // Check to see if we can perform the "gzip trick", transforming
05872   // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
05873   if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
05874       N0.getValueType().isInteger() &&
05875       N2.getValueType().isInteger() &&
05876       (N1C->isNullValue() ||                         // (a < 0) ? b : 0
05877        (N1C->getAPIntValue() == 1 && N0 == N2))) {   // (a < 1) ? a : 0
05878     EVT XType = N0.getValueType();
05879     EVT AType = N2.getValueType();
05880     if (XType.bitsGE(AType)) {
05881       // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
05882       // single-bit constant.
05883       if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
05884         unsigned ShCtV = N2C->getAPIntValue().logBase2();
05885         ShCtV = XType.getSizeInBits()-ShCtV-1;
05886         SDValue ShCt = DAG.getConstant(ShCtV, getShiftAmountTy());
05887         SDValue Shift = DAG.getNode(ISD::SRL, N0.getDebugLoc(),
05888                                     XType, N0, ShCt);
05889         AddToWorkList(Shift.getNode());
05890 
05891         if (XType.bitsGT(AType)) {
05892           Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
05893           AddToWorkList(Shift.getNode());
05894         }
05895 
05896         return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
05897       }
05898 
05899       SDValue Shift = DAG.getNode(ISD::SRA, N0.getDebugLoc(),
05900                                   XType, N0,
05901                                   DAG.getConstant(XType.getSizeInBits()-1,
05902                                                   getShiftAmountTy()));
05903       AddToWorkList(Shift.getNode());
05904 
05905       if (XType.bitsGT(AType)) {
05906         Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
05907         AddToWorkList(Shift.getNode());
05908       }
05909 
05910       return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
05911     }
05912   }
05913 
05914   // fold select C, 16, 0 -> shl C, 4
05915   if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
05916       TLI.getBooleanContents() == TargetLowering::ZeroOrOneBooleanContent) {
05917 
05918     // If the caller doesn't want us to simplify this into a zext of a compare,
05919     // don't do it.
05920     if (NotExtCompare && N2C->getAPIntValue() == 1)
05921       return SDValue();
05922 
05923     // Get a SetCC of the condition
05924     // FIXME: Should probably make sure that setcc is legal if we ever have a
05925     // target where it isn't.
05926     SDValue Temp, SCC;
05927     // cast from setcc result type to select result type
05928     if (LegalTypes) {
05929       SCC  = DAG.getSetCC(DL, TLI.getSetCCResultType(N0.getValueType()),
05930                           N0, N1, CC);
05931       if (N2.getValueType().bitsLT(SCC.getValueType()))
05932         Temp = DAG.getZeroExtendInReg(SCC, N2.getDebugLoc(), N2.getValueType());
05933       else
05934         Temp = DAG.getNode(ISD::ZERO_EXTEND, N2.getDebugLoc(),
05935                            N2.getValueType(), SCC);
05936     } else {
05937       SCC  = DAG.getSetCC(N0.getDebugLoc(), MVT::i1, N0, N1, CC);
05938       Temp = DAG.getNode(ISD::ZERO_EXTEND, N2.getDebugLoc(),
05939                          N2.getValueType(), SCC);
05940     }
05941 
05942     AddToWorkList(SCC.getNode());
05943     AddToWorkList(Temp.getNode());
05944 
05945     if (N2C->getAPIntValue() == 1)
05946       return Temp;
05947 
05948     // shl setcc result by log2 n2c
05949     return DAG.getNode(ISD::SHL, DL, N2.getValueType(), Temp,
05950                        DAG.getConstant(N2C->getAPIntValue().logBase2(),
05951                                        getShiftAmountTy()));
05952   }
05953 
05954   // Check to see if this is the equivalent of setcc
05955   // FIXME: Turn all of these into setcc if setcc if setcc is legal
05956   // otherwise, go ahead with the folds.
05957   if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
05958     EVT XType = N0.getValueType();
05959     if (!LegalOperations ||
05960         TLI.isOperationLegal(ISD::SETCC, TLI.getSetCCResultType(XType))) {
05961       SDValue Res = DAG.getSetCC(DL, TLI.getSetCCResultType(XType), N0, N1, CC);
05962       if (Res.getValueType() != VT)
05963         Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
05964       return Res;
05965     }
05966 
05967     // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
05968     if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
05969         (!LegalOperations ||
05970          TLI.isOperationLegal(ISD::CTLZ, XType))) {
05971       SDValue Ctlz = DAG.getNode(ISD::CTLZ, N0.getDebugLoc(), XType, N0);
05972       return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
05973                          DAG.getConstant(Log2_32(XType.getSizeInBits()),
05974                                          getShiftAmountTy()));
05975     }
05976     // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
05977     if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
05978       SDValue NegN0 = DAG.getNode(ISD::SUB, N0.getDebugLoc(),
05979                                   XType, DAG.getConstant(0, XType), N0);
05980       SDValue NotN0 = DAG.getNOT(N0.getDebugLoc(), N0, XType);
05981       return DAG.getNode(ISD::SRL, DL, XType,
05982                          DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
05983                          DAG.getConstant(XType.getSizeInBits()-1,
05984                                          getShiftAmountTy()));
05985     }
05986     // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
05987     if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
05988       SDValue Sign = DAG.getNode(ISD::SRL, N0.getDebugLoc(), XType, N0,
05989                                  DAG.getConstant(XType.getSizeInBits()-1,
05990                                                  getShiftAmountTy()));
05991       return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
05992     }
05993   }
05994 
05995   // Check to see if this is an integer abs. select_cc setl[te] X, 0, -X, X ->
05996   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
05997   if (N1C && N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE) &&
05998       N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1) &&
05999       N2.getOperand(0) == N1 && N0.getValueType().isInteger()) {
06000     EVT XType = N0.getValueType();
06001     SDValue Shift = DAG.getNode(ISD::SRA, N0.getDebugLoc(), XType, N0,
06002                                 DAG.getConstant(XType.getSizeInBits()-1,
06003                                                 getShiftAmountTy()));
06004     SDValue Add = DAG.getNode(ISD::ADD, N0.getDebugLoc(), XType,
06005                               N0, Shift);
06006     AddToWorkList(Shift.getNode());
06007     AddToWorkList(Add.getNode());
06008     return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
06009   }
06010   // Check to see if this is an integer abs. select_cc setgt X, -1, X, -X ->
06011   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
06012   if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT &&
06013       N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1)) {
06014     if (ConstantSDNode *SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0))) {
06015       EVT XType = N0.getValueType();
06016       if (SubC->isNullValue() && XType.isInteger()) {
06017         SDValue Shift = DAG.getNode(ISD::SRA, N0.getDebugLoc(), XType,
06018                                     N0,
06019                                     DAG.getConstant(XType.getSizeInBits()-1,
06020                                                     getShiftAmountTy()));
06021         SDValue Add = DAG.getNode(ISD::ADD, N0.getDebugLoc(),
06022                                   XType, N0, Shift);
06023         AddToWorkList(Shift.getNode());
06024         AddToWorkList(Add.getNode());
06025         return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
06026       }
06027     }
06028   }
06029 
06030   return SDValue();
06031 }
06032 
06033 /// SimplifySetCC - This is a stub for TargetLowering::SimplifySetCC.
06034 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
06035                                    SDValue N1, ISD::CondCode Cond,
06036                                    DebugLoc DL, bool foldBooleans) {
06037   TargetLowering::DAGCombinerInfo
06038     DagCombineInfo(DAG, !LegalTypes, !LegalOperations, false, this);
06039   return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
06040 }
06041 
06042 /// BuildSDIVSequence - Given an ISD::SDIV node expressing a divide by constant,
06043 /// return a DAG expression to select that will generate the same value by
06044 /// multiplying by a magic number.  See:
06045 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
06046 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
06047   std::vector<SDNode*> Built;
06048   SDValue S = TLI.BuildSDIV(N, DAG, &Built);
06049 
06050   for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
06051        ii != ee; ++ii)
06052     AddToWorkList(*ii);
06053   return S;
06054 }
06055 
06056 /// BuildUDIVSequence - Given an ISD::UDIV node expressing a divide by constant,
06057 /// return a DAG expression to select that will generate the same value by
06058 /// multiplying by a magic number.  See:
06059 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
06060 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
06061   std::vector<SDNode*> Built;
06062   SDValue S = TLI.BuildUDIV(N, DAG, &Built);
06063 
06064   for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
06065        ii != ee; ++ii)
06066     AddToWorkList(*ii);
06067   return S;
06068 }
06069 
06070 /// FindBaseOffset - Return true if base is known not to alias with anything
06071 /// but itself.  Provides base object and offset as results.
06072 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset) {
06073   // Assume it is a primitive operation.
06074   Base = Ptr; Offset = 0;
06075 
06076   // If it's an adding a simple constant then integrate the offset.
06077   if (Base.getOpcode() == ISD::ADD) {
06078     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
06079       Base = Base.getOperand(0);
06080       Offset += C->getZExtValue();
06081     }
06082   }
06083 
06084   // If it's any of the following then it can't alias with anything but itself.
06085   return isa<FrameIndexSDNode>(Base) ||
06086          isa<ConstantPoolSDNode>(Base) ||
06087          isa<GlobalAddressSDNode>(Base);
06088 }
06089 
06090 /// isAlias - Return true if there is any possibility that the two addresses
06091 /// overlap.
06092 bool DAGCombiner::isAlias(SDValue Ptr1, int64_t Size1,
06093                           const Value *SrcValue1, int SrcValueOffset1,
06094                           SDValue Ptr2, int64_t Size2,
06095                           const Value *SrcValue2, int SrcValueOffset2) const {
06096   // If they are the same then they must be aliases.
06097   if (Ptr1 == Ptr2) return true;
06098 
06099   // Gather base node and offset information.
06100   SDValue Base1, Base2;
06101   int64_t Offset1, Offset2;
06102   bool KnownBase1 = FindBaseOffset(Ptr1, Base1, Offset1);
06103   bool KnownBase2 = FindBaseOffset(Ptr2, Base2, Offset2);
06104 
06105   // If they have a same base address then...
06106   if (Base1 == Base2)
06107     // Check to see if the addresses overlap.
06108     return !((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1);
06109 
06110   // If we know both bases then they can't alias.
06111   if (KnownBase1 && KnownBase2) return false;
06112 
06113   if (CombinerGlobalAA) {
06114     // Use alias analysis information.
06115     int64_t MinOffset = std::min(SrcValueOffset1, SrcValueOffset2);
06116     int64_t Overlap1 = Size1 + SrcValueOffset1 - MinOffset;
06117     int64_t Overlap2 = Size2 + SrcValueOffset2 - MinOffset;
06118     AliasAnalysis::AliasResult AAResult =
06119                              AA.alias(SrcValue1, Overlap1, SrcValue2, Overlap2);
06120     if (AAResult == AliasAnalysis::NoAlias)
06121       return false;
06122   }
06123 
06124   // Otherwise we have to assume they alias.
06125   return true;
06126 }
06127 
06128 /// FindAliasInfo - Extracts the relevant alias information from the memory
06129 /// node.  Returns true if the operand was a load.
06130 bool DAGCombiner::FindAliasInfo(SDNode *N,
06131                         SDValue &Ptr, int64_t &Size,
06132                         const Value *&SrcValue, int &SrcValueOffset) const {
06133   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
06134     Ptr = LD->getBasePtr();
06135     Size = LD->getMemoryVT().getSizeInBits() >> 3;
06136     SrcValue = LD->getSrcValue();
06137     SrcValueOffset = LD->getSrcValueOffset();
06138     return true;
06139   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
06140     Ptr = ST->getBasePtr();
06141     Size = ST->getMemoryVT().getSizeInBits() >> 3;
06142     SrcValue = ST->getSrcValue();
06143     SrcValueOffset = ST->getSrcValueOffset();
06144   } else {
06145     llvm_unreachable("FindAliasInfo expected a memory operand");
06146   }
06147 
06148   return false;
06149 }
06150 
06151 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
06152 /// looking for aliasing nodes and adding them to the Aliases vector.
06153 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
06154                                    SmallVector<SDValue, 8> &Aliases) {
06155   SmallVector<SDValue, 8> Chains;     // List of chains to visit.
06156   std::set<SDNode *> Visited;           // Visited node set.
06157 
06158   // Get alias information for node.
06159   SDValue Ptr;
06160   int64_t Size = 0;
06161   const Value *SrcValue = 0;
06162   int SrcValueOffset = 0;
06163   bool IsLoad = FindAliasInfo(N, Ptr, Size, SrcValue, SrcValueOffset);
06164 
06165   // Starting off.
06166   Chains.push_back(OriginalChain);
06167 
06168   // Look at each chain and determine if it is an alias.  If so, add it to the
06169   // aliases list.  If not, then continue up the chain looking for the next
06170   // candidate.
06171   while (!Chains.empty()) {
06172     SDValue Chain = Chains.back();
06173     Chains.pop_back();
06174 
06175      // Don't bother if we've been before.
06176     if (Visited.find(Chain.getNode()) != Visited.end()) continue;
06177     Visited.insert(Chain.getNode());
06178 
06179     switch (Chain.getOpcode()) {
06180     case ISD::EntryToken:
06181       // Entry token is ideal chain operand, but handled in FindBetterChain.
06182       break;
06183 
06184     case ISD::LOAD:
06185     case ISD::STORE: {
06186       // Get alias information for Chain.
06187       SDValue OpPtr;
06188       int64_t OpSize = 0;
06189       const Value *OpSrcValue = 0;
06190       int OpSrcValueOffset = 0;
06191       bool IsOpLoad = FindAliasInfo(Chain.getNode(), OpPtr, OpSize,
06192                                     OpSrcValue, OpSrcValueOffset);
06193 
06194       // If chain is alias then stop here.
06195       if (!(IsLoad && IsOpLoad) &&
06196           isAlias(Ptr, Size, SrcValue, SrcValueOffset,
06197                   OpPtr, OpSize, OpSrcValue, OpSrcValueOffset)) {
06198         Aliases.push_back(Chain);
06199       } else {
06200         // Look further up the chain.
06201         Chains.push_back(Chain.getOperand(0));
06202         // Clean up old chain.
06203         AddToWorkList(Chain.getNode());
06204       }
06205       break;
06206     }
06207 
06208     case ISD::TokenFactor:
06209       // We have to check each of the operands of the token factor, so we queue
06210       // then up.  Adding the  operands to the queue (stack) in reverse order
06211       // maintains the original order and increases the likelihood that getNode
06212       // will find a matching token factor (CSE.)
06213       for (unsigned n = Chain.getNumOperands(); n;)
06214         Chains.push_back(Chain.getOperand(--n));
06215       // Eliminate the token factor if we can.
06216       AddToWorkList(Chain.getNode());
06217       break;
06218 
06219     default:
06220       // For all other instructions we will just have to take what we can get.
06221       Aliases.push_back(Chain);
06222       break;
06223     }
06224   }
06225 }
06226 
06227 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes, looking
06228 /// for a better chain (aliasing node.)
06229 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
06230   SmallVector<SDValue, 8> Aliases;  // Ops for replacing token factor.
06231 
06232   // Accumulate all the aliases to this node.
06233   GatherAllAliases(N, OldChain, Aliases);
06234 
06235   if (Aliases.size() == 0) {
06236     // If no operands then chain to entry token.
06237     return DAG.getEntryNode();
06238   } else if (Aliases.size() == 1) {
06239     // If a single operand then chain to it.  We don't need to revisit it.
06240     return Aliases[0];
06241   }
06242 
06243   // Construct a custom tailored token factor.
06244   SDValue NewChain = DAG.getNode(ISD::TokenFactor, N->getDebugLoc(), MVT::Other,
06245                                  &Aliases[0], Aliases.size());
06246 
06247   // Make sure the old chain gets cleaned up.
06248   if (NewChain != OldChain) AddToWorkList(OldChain.getNode());
06249 
06250   return NewChain;
06251 }
06252 
06253 // SelectionDAG::Combine - This is the entry point for the file.
06254 //
06255 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
06256                            CodeGenOpt::Level OptLevel) {
06257   /// run - This is the main entry point to this class.
06258   ///
06259   DAGCombiner(*this, AA, OptLevel).Run(Level);
06260 }