Home | History | Annotate | Download | only in SelectionDAG
      1 //===-- DAGCombiner.cpp - Implement a DAG node combiner -------------------===//
      2 //
      3 //                     The LLVM Compiler Infrastructure
      4 //
      5 // This file is distributed under the University of Illinois Open Source
      6 // License. See LICENSE.TXT for details.
      7 //
      8 //===----------------------------------------------------------------------===//
      9 //
     10 // This pass combines dag nodes to form fewer, simpler DAG nodes.  It can be run
     11 // both before and after the DAG is legalized.
     12 //
     13 // This pass is not a substitute for the LLVM IR instcombine pass. This pass is
     14 // primarily intended to handle simplification opportunities that are implicit
     15 // in the LLVM IR and exposed by the various codegen lowering phases.
     16 //
     17 //===----------------------------------------------------------------------===//
     18 
     19 #include "llvm/CodeGen/SelectionDAG.h"
     20 #include "llvm/ADT/SetVector.h"
     21 #include "llvm/ADT/SmallBitVector.h"
     22 #include "llvm/ADT/SmallPtrSet.h"
     23 #include "llvm/ADT/Statistic.h"
     24 #include "llvm/Analysis/AliasAnalysis.h"
     25 #include "llvm/CodeGen/MachineFrameInfo.h"
     26 #include "llvm/CodeGen/MachineFunction.h"
     27 #include "llvm/IR/DataLayout.h"
     28 #include "llvm/IR/DerivedTypes.h"
     29 #include "llvm/IR/Function.h"
     30 #include "llvm/IR/LLVMContext.h"
     31 #include "llvm/Support/CommandLine.h"
     32 #include "llvm/Support/Debug.h"
     33 #include "llvm/Support/ErrorHandling.h"
     34 #include "llvm/Support/MathExtras.h"
     35 #include "llvm/Support/raw_ostream.h"
     36 #include "llvm/Target/TargetLowering.h"
     37 #include "llvm/Target/TargetOptions.h"
     38 #include "llvm/Target/TargetRegisterInfo.h"
     39 #include "llvm/Target/TargetSubtargetInfo.h"
     40 #include <algorithm>
     41 using namespace llvm;
     42 
     43 #define DEBUG_TYPE "dagcombine"
     44 
     45 STATISTIC(NodesCombined   , "Number of dag nodes combined");
     46 STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created");
     47 STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created");
     48 STATISTIC(OpsNarrowed     , "Number of load/op/store narrowed");
     49 STATISTIC(LdStFP2Int      , "Number of fp load/store pairs transformed to int");
     50 STATISTIC(SlicedLoads, "Number of load sliced");
     51 
     52 namespace {
     53   static cl::opt<bool>
     54     CombinerAA("combiner-alias-analysis", cl::Hidden,
     55                cl::desc("Enable DAG combiner alias-analysis heuristics"));
     56 
     57   static cl::opt<bool>
     58     CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
     59                cl::desc("Enable DAG combiner's use of IR alias analysis"));
     60 
     61   static cl::opt<bool>
     62     UseTBAA("combiner-use-tbaa", cl::Hidden, cl::init(true),
     63                cl::desc("Enable DAG combiner's use of TBAA"));
     64 
     65 #ifndef NDEBUG
     66   static cl::opt<std::string>
     67     CombinerAAOnlyFunc("combiner-aa-only-func", cl::Hidden,
     68                cl::desc("Only use DAG-combiner alias analysis in this"
     69                         " function"));
     70 #endif
     71 
     72   /// Hidden option to stress test load slicing, i.e., when this option
     73   /// is enabled, load slicing bypasses most of its profitability guards.
     74   static cl::opt<bool>
     75   StressLoadSlicing("combiner-stress-load-slicing", cl::Hidden,
     76                     cl::desc("Bypass the profitability model of load "
     77                              "slicing"),
     78                     cl::init(false));
     79 
     80   static cl::opt<bool>
     81     MaySplitLoadIndex("combiner-split-load-index", cl::Hidden, cl::init(true),
     82                       cl::desc("DAG combiner may split indexing from loads"));
     83 
     84 //------------------------------ DAGCombiner ---------------------------------//
     85 
     86   class DAGCombiner {
     87     SelectionDAG &DAG;
     88     const TargetLowering &TLI;
     89     CombineLevel Level;
     90     CodeGenOpt::Level OptLevel;
     91     bool LegalOperations;
     92     bool LegalTypes;
     93     bool ForCodeSize;
     94 
     95     /// \brief Worklist of all of the nodes that need to be simplified.
     96     ///
     97     /// This must behave as a stack -- new nodes to process are pushed onto the
     98     /// back and when processing we pop off of the back.
     99     ///
    100     /// The worklist will not contain duplicates but may contain null entries
    101     /// due to nodes being deleted from the underlying DAG.
    102     SmallVector<SDNode *, 64> Worklist;
    103 
    104     /// \brief Mapping from an SDNode to its position on the worklist.
    105     ///
    106     /// This is used to find and remove nodes from the worklist (by nulling
    107     /// them) when they are deleted from the underlying DAG. It relies on
    108     /// stable indices of nodes within the worklist.
    109     DenseMap<SDNode *, unsigned> WorklistMap;
    110 
    111     /// \brief Set of nodes which have been combined (at least once).
    112     ///
    113     /// This is used to allow us to reliably add any operands of a DAG node
    114     /// which have not yet been combined to the worklist.
    115     SmallPtrSet<SDNode *, 64> CombinedNodes;
    116 
    117     // AA - Used for DAG load/store alias analysis.
    118     AliasAnalysis &AA;
    119 
    120     /// When an instruction is simplified, add all users of the instruction to
    121     /// the work lists because they might get more simplified now.
    122     void AddUsersToWorklist(SDNode *N) {
    123       for (SDNode *Node : N->uses())
    124         AddToWorklist(Node);
    125     }
    126 
    127     /// Call the node-specific routine that folds each particular type of node.
    128     SDValue visit(SDNode *N);
    129 
    130   public:
    131     /// Add to the worklist making sure its instance is at the back (next to be
    132     /// processed.)
    133     void AddToWorklist(SDNode *N) {
    134       // Skip handle nodes as they can't usefully be combined and confuse the
    135       // zero-use deletion strategy.
    136       if (N->getOpcode() == ISD::HANDLENODE)
    137         return;
    138 
    139       if (WorklistMap.insert(std::make_pair(N, Worklist.size())).second)
    140         Worklist.push_back(N);
    141     }
    142 
    143     /// Remove all instances of N from the worklist.
    144     void removeFromWorklist(SDNode *N) {
    145       CombinedNodes.erase(N);
    146 
    147       auto It = WorklistMap.find(N);
    148       if (It == WorklistMap.end())
    149         return; // Not in the worklist.
    150 
    151       // Null out the entry rather than erasing it to avoid a linear operation.
    152       Worklist[It->second] = nullptr;
    153       WorklistMap.erase(It);
    154     }
    155 
    156     void deleteAndRecombine(SDNode *N);
    157     bool recursivelyDeleteUnusedNodes(SDNode *N);
    158 
    159     SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
    160                       bool AddTo = true);
    161 
    162     SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
    163       return CombineTo(N, &Res, 1, AddTo);
    164     }
    165 
    166     SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
    167                       bool AddTo = true) {
    168       SDValue To[] = { Res0, Res1 };
    169       return CombineTo(N, To, 2, AddTo);
    170     }
    171 
    172     void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
    173 
    174   private:
    175 
    176     /// Check the specified integer node value to see if it can be simplified or
    177     /// if things it uses can be simplified by bit propagation.
    178     /// If so, return true.
    179     bool SimplifyDemandedBits(SDValue Op) {
    180       unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits();
    181       APInt Demanded = APInt::getAllOnesValue(BitWidth);
    182       return SimplifyDemandedBits(Op, Demanded);
    183     }
    184 
    185     bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded);
    186 
    187     bool CombineToPreIndexedLoadStore(SDNode *N);
    188     bool CombineToPostIndexedLoadStore(SDNode *N);
    189     SDValue SplitIndexingFromLoad(LoadSDNode *LD);
    190     bool SliceUpLoad(SDNode *N);
    191 
    192     /// \brief Replace an ISD::EXTRACT_VECTOR_ELT of a load with a narrowed
    193     ///   load.
    194     ///
    195     /// \param EVE ISD::EXTRACT_VECTOR_ELT to be replaced.
    196     /// \param InVecVT type of the input vector to EVE with bitcasts resolved.
    197     /// \param EltNo index of the vector element to load.
    198     /// \param OriginalLoad load that EVE came from to be replaced.
    199     /// \returns EVE on success SDValue() on failure.
    200     SDValue ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
    201         SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad);
    202     void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
    203     SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
    204     SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
    205     SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
    206     SDValue PromoteIntBinOp(SDValue Op);
    207     SDValue PromoteIntShiftOp(SDValue Op);
    208     SDValue PromoteExtend(SDValue Op);
    209     bool PromoteLoad(SDValue Op);
    210 
    211     void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
    212                          SDValue Trunc, SDValue ExtLoad, SDLoc DL,
    213                          ISD::NodeType ExtType);
    214 
    215     /// Call the node-specific routine that knows how to fold each
    216     /// particular type of node. If that doesn't do anything, try the
    217     /// target-specific DAG combines.
    218     SDValue combine(SDNode *N);
    219 
    220     // Visitation implementation - Implement dag node combining for different
    221     // node types.  The semantics are as follows:
    222     // Return Value:
    223     //   SDValue.getNode() == 0 - No change was made
    224     //   SDValue.getNode() == N - N was replaced, is dead and has been handled.
    225     //   otherwise              - N should be replaced by the returned Operand.
    226     //
    227     SDValue visitTokenFactor(SDNode *N);
    228     SDValue visitMERGE_VALUES(SDNode *N);
    229     SDValue visitADD(SDNode *N);
    230     SDValue visitSUB(SDNode *N);
    231     SDValue visitADDC(SDNode *N);
    232     SDValue visitSUBC(SDNode *N);
    233     SDValue visitADDE(SDNode *N);
    234     SDValue visitSUBE(SDNode *N);
    235     SDValue visitMUL(SDNode *N);
    236     SDValue visitSDIV(SDNode *N);
    237     SDValue visitUDIV(SDNode *N);
    238     SDValue visitSREM(SDNode *N);
    239     SDValue visitUREM(SDNode *N);
    240     SDValue visitMULHU(SDNode *N);
    241     SDValue visitMULHS(SDNode *N);
    242     SDValue visitSMUL_LOHI(SDNode *N);
    243     SDValue visitUMUL_LOHI(SDNode *N);
    244     SDValue visitSMULO(SDNode *N);
    245     SDValue visitUMULO(SDNode *N);
    246     SDValue visitSDIVREM(SDNode *N);
    247     SDValue visitUDIVREM(SDNode *N);
    248     SDValue visitAND(SDNode *N);
    249     SDValue visitANDLike(SDValue N0, SDValue N1, SDNode *LocReference);
    250     SDValue visitOR(SDNode *N);
    251     SDValue visitORLike(SDValue N0, SDValue N1, SDNode *LocReference);
    252     SDValue visitXOR(SDNode *N);
    253     SDValue SimplifyVBinOp(SDNode *N);
    254     SDValue visitSHL(SDNode *N);
    255     SDValue visitSRA(SDNode *N);
    256     SDValue visitSRL(SDNode *N);
    257     SDValue visitRotate(SDNode *N);
    258     SDValue visitCTLZ(SDNode *N);
    259     SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
    260     SDValue visitCTTZ(SDNode *N);
    261     SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
    262     SDValue visitCTPOP(SDNode *N);
    263     SDValue visitSELECT(SDNode *N);
    264     SDValue visitVSELECT(SDNode *N);
    265     SDValue visitSELECT_CC(SDNode *N);
    266     SDValue visitSETCC(SDNode *N);
    267     SDValue visitSIGN_EXTEND(SDNode *N);
    268     SDValue visitZERO_EXTEND(SDNode *N);
    269     SDValue visitANY_EXTEND(SDNode *N);
    270     SDValue visitSIGN_EXTEND_INREG(SDNode *N);
    271     SDValue visitTRUNCATE(SDNode *N);
    272     SDValue visitBITCAST(SDNode *N);
    273     SDValue visitBUILD_PAIR(SDNode *N);
    274     SDValue visitFADD(SDNode *N);
    275     SDValue visitFSUB(SDNode *N);
    276     SDValue visitFMUL(SDNode *N);
    277     SDValue visitFMA(SDNode *N);
    278     SDValue visitFDIV(SDNode *N);
    279     SDValue visitFREM(SDNode *N);
    280     SDValue visitFSQRT(SDNode *N);
    281     SDValue visitFCOPYSIGN(SDNode *N);
    282     SDValue visitSINT_TO_FP(SDNode *N);
    283     SDValue visitUINT_TO_FP(SDNode *N);
    284     SDValue visitFP_TO_SINT(SDNode *N);
    285     SDValue visitFP_TO_UINT(SDNode *N);
    286     SDValue visitFP_ROUND(SDNode *N);
    287     SDValue visitFP_ROUND_INREG(SDNode *N);
    288     SDValue visitFP_EXTEND(SDNode *N);
    289     SDValue visitFNEG(SDNode *N);
    290     SDValue visitFABS(SDNode *N);
    291     SDValue visitFCEIL(SDNode *N);
    292     SDValue visitFTRUNC(SDNode *N);
    293     SDValue visitFFLOOR(SDNode *N);
    294     SDValue visitFMINNUM(SDNode *N);
    295     SDValue visitFMAXNUM(SDNode *N);
    296     SDValue visitBRCOND(SDNode *N);
    297     SDValue visitBR_CC(SDNode *N);
    298     SDValue visitLOAD(SDNode *N);
    299     SDValue visitSTORE(SDNode *N);
    300     SDValue visitINSERT_VECTOR_ELT(SDNode *N);
    301     SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
    302     SDValue visitBUILD_VECTOR(SDNode *N);
    303     SDValue visitCONCAT_VECTORS(SDNode *N);
    304     SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
    305     SDValue visitVECTOR_SHUFFLE(SDNode *N);
    306     SDValue visitSCALAR_TO_VECTOR(SDNode *N);
    307     SDValue visitINSERT_SUBVECTOR(SDNode *N);
    308     SDValue visitMLOAD(SDNode *N);
    309     SDValue visitMSTORE(SDNode *N);
    310     SDValue visitFP_TO_FP16(SDNode *N);
    311 
    312     SDValue XformToShuffleWithZero(SDNode *N);
    313     SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS);
    314 
    315     SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt);
    316 
    317     bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
    318     SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
    319     SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2);
    320     SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2,
    321                              SDValue N3, ISD::CondCode CC,
    322                              bool NotExtCompare = false);
    323     SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
    324                           SDLoc DL, bool foldBooleans = true);
    325 
    326     bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
    327                            SDValue &CC) const;
    328     bool isOneUseSetCC(SDValue N) const;
    329 
    330     SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
    331                                          unsigned HiOp);
    332     SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
    333     SDValue CombineExtLoad(SDNode *N);
    334     SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
    335     SDValue BuildSDIV(SDNode *N);
    336     SDValue BuildSDIVPow2(SDNode *N);
    337     SDValue BuildUDIV(SDNode *N);
    338     SDValue BuildReciprocalEstimate(SDValue Op);
    339     SDValue BuildRsqrtEstimate(SDValue Op);
    340     SDValue BuildRsqrtNROneConst(SDValue Op, SDValue Est, unsigned Iterations);
    341     SDValue BuildRsqrtNRTwoConst(SDValue Op, SDValue Est, unsigned Iterations);
    342     SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
    343                                bool DemandHighBits = true);
    344     SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
    345     SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
    346                               SDValue InnerPos, SDValue InnerNeg,
    347                               unsigned PosOpcode, unsigned NegOpcode,
    348                               SDLoc DL);
    349     SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL);
    350     SDValue ReduceLoadWidth(SDNode *N);
    351     SDValue ReduceLoadOpStoreWidth(SDNode *N);
    352     SDValue TransformFPLoadStorePair(SDNode *N);
    353     SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
    354     SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
    355 
    356     SDValue GetDemandedBits(SDValue V, const APInt &Mask);
    357 
    358     /// Walk up chain skipping non-aliasing memory nodes,
    359     /// looking for aliasing nodes and adding them to the Aliases vector.
    360     void GatherAllAliases(SDNode *N, SDValue OriginalChain,
    361                           SmallVectorImpl<SDValue> &Aliases);
    362 
    363     /// Return true if there is any possibility that the two addresses overlap.
    364     bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const;
    365 
    366     /// Walk up chain skipping non-aliasing memory nodes, looking for a better
    367     /// chain (aliasing node.)
    368     SDValue FindBetterChain(SDNode *N, SDValue Chain);
    369 
    370     /// Holds a pointer to an LSBaseSDNode as well as information on where it
    371     /// is located in a sequence of memory operations connected by a chain.
    372     struct MemOpLink {
    373       MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
    374       MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
    375       // Ptr to the mem node.
    376       LSBaseSDNode *MemNode;
    377       // Offset from the base ptr.
    378       int64_t OffsetFromBase;
    379       // What is the sequence number of this mem node.
    380       // Lowest mem operand in the DAG starts at zero.
    381       unsigned SequenceNum;
    382     };
    383 
    384     /// This is a helper function for MergeConsecutiveStores. When the source
    385     /// elements of the consecutive stores are all constants or all extracted
    386     /// vector elements, try to merge them into one larger store.
    387     /// \return True if a merged store was created.
    388     bool MergeStoresOfConstantsOrVecElts(SmallVectorImpl<MemOpLink> &StoreNodes,
    389                                          EVT MemVT, unsigned NumElem,
    390                                          bool IsConstantSrc, bool UseVector);
    391 
    392     /// Merge consecutive store operations into a wide store.
    393     /// This optimization uses wide integers or vectors when possible.
    394     /// \return True if some memory operations were changed.
    395     bool MergeConsecutiveStores(StoreSDNode *N);
    396 
    397     /// \brief Try to transform a truncation where C is a constant:
    398     ///     (trunc (and X, C)) -> (and (trunc X), (trunc C))
    399     ///
    400     /// \p N needs to be a truncation and its first operand an AND. Other
    401     /// requirements are checked by the function (e.g. that trunc is
    402     /// single-use) and if missed an empty SDValue is returned.
    403     SDValue distributeTruncateThroughAnd(SDNode *N);
    404 
    405   public:
    406     DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
    407         : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
    408           OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
    409       auto *F = DAG.getMachineFunction().getFunction();
    410       ForCodeSize = F->hasFnAttribute(Attribute::OptimizeForSize) ||
    411                     F->hasFnAttribute(Attribute::MinSize);
    412     }
    413 
    414     /// Runs the dag combiner on all nodes in the work list
    415     void Run(CombineLevel AtLevel);
    416 
    417     SelectionDAG &getDAG() const { return DAG; }
    418 
    419     /// Returns a type large enough to hold any valid shift amount - before type
    420     /// legalization these can be huge.
    421     EVT getShiftAmountTy(EVT LHSTy) {
    422       assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
    423       if (LHSTy.isVector())
    424         return LHSTy;
    425       return LegalTypes ? TLI.getScalarShiftAmountTy(LHSTy)
    426                         : TLI.getPointerTy();
    427     }
    428 
    429     /// This method returns true if we are running before type legalization or
    430     /// if the specified VT is legal.
    431     bool isTypeLegal(const EVT &VT) {
    432       if (!LegalTypes) return true;
    433       return TLI.isTypeLegal(VT);
    434     }
    435 
    436     /// Convenience wrapper around TargetLowering::getSetCCResultType
    437     EVT getSetCCResultType(EVT VT) const {
    438       return TLI.getSetCCResultType(*DAG.getContext(), VT);
    439     }
    440   };
    441 }
    442 
    443 
    444 namespace {
    445 /// This class is a DAGUpdateListener that removes any deleted
    446 /// nodes from the worklist.
    447 class WorklistRemover : public SelectionDAG::DAGUpdateListener {
    448   DAGCombiner &DC;
    449 public:
    450   explicit WorklistRemover(DAGCombiner &dc)
    451     : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
    452 
    453   void NodeDeleted(SDNode *N, SDNode *E) override {
    454     DC.removeFromWorklist(N);
    455   }
    456 };
    457 }
    458 
    459 //===----------------------------------------------------------------------===//
    460 //  TargetLowering::DAGCombinerInfo implementation
    461 //===----------------------------------------------------------------------===//
    462 
    463 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
    464   ((DAGCombiner*)DC)->AddToWorklist(N);
    465 }
    466 
    467 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
    468   ((DAGCombiner*)DC)->removeFromWorklist(N);
    469 }
    470 
    471 SDValue TargetLowering::DAGCombinerInfo::
    472 CombineTo(SDNode *N, ArrayRef<SDValue> To, bool AddTo) {
    473   return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
    474 }
    475 
    476 SDValue TargetLowering::DAGCombinerInfo::
    477 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
    478   return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
    479 }
    480 
    481 
    482 SDValue TargetLowering::DAGCombinerInfo::
    483 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
    484   return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
    485 }
    486 
    487 void TargetLowering::DAGCombinerInfo::
    488 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
    489   return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
    490 }
    491 
    492 //===----------------------------------------------------------------------===//
    493 // Helper Functions
    494 //===----------------------------------------------------------------------===//
    495 
    496 void DAGCombiner::deleteAndRecombine(SDNode *N) {
    497   removeFromWorklist(N);
    498 
    499   // If the operands of this node are only used by the node, they will now be
    500   // dead. Make sure to re-visit them and recursively delete dead nodes.
    501   for (const SDValue &Op : N->ops())
    502     // For an operand generating multiple values, one of the values may
    503     // become dead allowing further simplification (e.g. split index
    504     // arithmetic from an indexed load).
    505     if (Op->hasOneUse() || Op->getNumValues() > 1)
    506       AddToWorklist(Op.getNode());
    507 
    508   DAG.DeleteNode(N);
    509 }
    510 
    511 /// Return 1 if we can compute the negated form of the specified expression for
    512 /// the same cost as the expression itself, or 2 if we can compute the negated
    513 /// form more cheaply than the expression itself.
    514 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
    515                                const TargetLowering &TLI,
    516                                const TargetOptions *Options,
    517                                unsigned Depth = 0) {
    518   // fneg is removable even if it has multiple uses.
    519   if (Op.getOpcode() == ISD::FNEG) return 2;
    520 
    521   // Don't allow anything with multiple uses.
    522   if (!Op.hasOneUse()) return 0;
    523 
    524   // Don't recurse exponentially.
    525   if (Depth > 6) return 0;
    526 
    527   switch (Op.getOpcode()) {
    528   default: return false;
    529   case ISD::ConstantFP:
    530     // Don't invert constant FP values after legalize.  The negated constant
    531     // isn't necessarily legal.
    532     return LegalOperations ? 0 : 1;
    533   case ISD::FADD:
    534     // FIXME: determine better conditions for this xform.
    535     if (!Options->UnsafeFPMath) return 0;
    536 
    537     // After operation legalization, it might not be legal to create new FSUBs.
    538     if (LegalOperations &&
    539         !TLI.isOperationLegalOrCustom(ISD::FSUB,  Op.getValueType()))
    540       return 0;
    541 
    542     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
    543     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
    544                                     Options, Depth + 1))
    545       return V;
    546     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
    547     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
    548                               Depth + 1);
    549   case ISD::FSUB:
    550     // We can't turn -(A-B) into B-A when we honor signed zeros.
    551     if (!Options->UnsafeFPMath) return 0;
    552 
    553     // fold (fneg (fsub A, B)) -> (fsub B, A)
    554     return 1;
    555 
    556   case ISD::FMUL:
    557   case ISD::FDIV:
    558     if (Options->HonorSignDependentRoundingFPMath()) return 0;
    559 
    560     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
    561     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
    562                                     Options, Depth + 1))
    563       return V;
    564 
    565     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
    566                               Depth + 1);
    567 
    568   case ISD::FP_EXTEND:
    569   case ISD::FP_ROUND:
    570   case ISD::FSIN:
    571     return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
    572                               Depth + 1);
    573   }
    574 }
    575 
    576 /// If isNegatibleForFree returns true, return the newly negated expression.
    577 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
    578                                     bool LegalOperations, unsigned Depth = 0) {
    579   const TargetOptions &Options = DAG.getTarget().Options;
    580   // fneg is removable even if it has multiple uses.
    581   if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
    582 
    583   // Don't allow anything with multiple uses.
    584   assert(Op.hasOneUse() && "Unknown reuse!");
    585 
    586   assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
    587   switch (Op.getOpcode()) {
    588   default: llvm_unreachable("Unknown code");
    589   case ISD::ConstantFP: {
    590     APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
    591     V.changeSign();
    592     return DAG.getConstantFP(V, Op.getValueType());
    593   }
    594   case ISD::FADD:
    595     // FIXME: determine better conditions for this xform.
    596     assert(Options.UnsafeFPMath);
    597 
    598     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
    599     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
    600                            DAG.getTargetLoweringInfo(), &Options, Depth+1))
    601       return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
    602                          GetNegatedExpression(Op.getOperand(0), DAG,
    603                                               LegalOperations, Depth+1),
    604                          Op.getOperand(1));
    605     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
    606     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
    607                        GetNegatedExpression(Op.getOperand(1), DAG,
    608                                             LegalOperations, Depth+1),
    609                        Op.getOperand(0));
    610   case ISD::FSUB:
    611     // We can't turn -(A-B) into B-A when we honor signed zeros.
    612     assert(Options.UnsafeFPMath);
    613 
    614     // fold (fneg (fsub 0, B)) -> B
    615     if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
    616       if (N0CFP->getValueAPF().isZero())
    617         return Op.getOperand(1);
    618 
    619     // fold (fneg (fsub A, B)) -> (fsub B, A)
    620     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
    621                        Op.getOperand(1), Op.getOperand(0));
    622 
    623   case ISD::FMUL:
    624   case ISD::FDIV:
    625     assert(!Options.HonorSignDependentRoundingFPMath());
    626 
    627     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
    628     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
    629                            DAG.getTargetLoweringInfo(), &Options, Depth+1))
    630       return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
    631                          GetNegatedExpression(Op.getOperand(0), DAG,
    632                                               LegalOperations, Depth+1),
    633                          Op.getOperand(1));
    634 
    635     // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
    636     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
    637                        Op.getOperand(0),
    638                        GetNegatedExpression(Op.getOperand(1), DAG,
    639                                             LegalOperations, Depth+1));
    640 
    641   case ISD::FP_EXTEND:
    642   case ISD::FSIN:
    643     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
    644                        GetNegatedExpression(Op.getOperand(0), DAG,
    645                                             LegalOperations, Depth+1));
    646   case ISD::FP_ROUND:
    647       return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
    648                          GetNegatedExpression(Op.getOperand(0), DAG,
    649                                               LegalOperations, Depth+1),
    650                          Op.getOperand(1));
    651   }
    652 }
    653 
    654 // Return true if this node is a setcc, or is a select_cc
    655 // that selects between the target values used for true and false, making it
    656 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
    657 // the appropriate nodes based on the type of node we are checking. This
    658 // simplifies life a bit for the callers.
    659 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
    660                                     SDValue &CC) const {
    661   if (N.getOpcode() == ISD::SETCC) {
    662     LHS = N.getOperand(0);
    663     RHS = N.getOperand(1);
    664     CC  = N.getOperand(2);
    665     return true;
    666   }
    667 
    668   if (N.getOpcode() != ISD::SELECT_CC ||
    669       !TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
    670       !TLI.isConstFalseVal(N.getOperand(3).getNode()))
    671     return false;
    672 
    673   if (TLI.getBooleanContents(N.getValueType()) ==
    674       TargetLowering::UndefinedBooleanContent)
    675     return false;
    676 
    677   LHS = N.getOperand(0);
    678   RHS = N.getOperand(1);
    679   CC  = N.getOperand(4);
    680   return true;
    681 }
    682 
    683 /// Return true if this is a SetCC-equivalent operation with only one use.
    684 /// If this is true, it allows the users to invert the operation for free when
    685 /// it is profitable to do so.
    686 bool DAGCombiner::isOneUseSetCC(SDValue N) const {
    687   SDValue N0, N1, N2;
    688   if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
    689     return true;
    690   return false;
    691 }
    692 
    693 /// Returns true if N is a BUILD_VECTOR node whose
    694 /// elements are all the same constant or undefined.
    695 static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
    696   BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
    697   if (!C)
    698     return false;
    699 
    700   APInt SplatUndef;
    701   unsigned SplatBitSize;
    702   bool HasAnyUndefs;
    703   EVT EltVT = N->getValueType(0).getVectorElementType();
    704   return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
    705                              HasAnyUndefs) &&
    706           EltVT.getSizeInBits() >= SplatBitSize);
    707 }
    708 
    709 // \brief Returns the SDNode if it is a constant integer BuildVector
    710 // or constant integer.
    711 static SDNode *isConstantIntBuildVectorOrConstantInt(SDValue N) {
    712   if (isa<ConstantSDNode>(N))
    713     return N.getNode();
    714   if (ISD::isBuildVectorOfConstantSDNodes(N.getNode()))
    715     return N.getNode();
    716   return nullptr;
    717 }
    718 
    719 // \brief Returns the SDNode if it is a constant float BuildVector
    720 // or constant float.
    721 static SDNode *isConstantFPBuildVectorOrConstantFP(SDValue N) {
    722   if (isa<ConstantFPSDNode>(N))
    723     return N.getNode();
    724   if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode()))
    725     return N.getNode();
    726   return nullptr;
    727 }
    728 
    729 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
    730 // int.
    731 static ConstantSDNode *isConstOrConstSplat(SDValue N) {
    732   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
    733     return CN;
    734 
    735   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
    736     BitVector UndefElements;
    737     ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
    738 
    739     // BuildVectors can truncate their operands. Ignore that case here.
    740     // FIXME: We blindly ignore splats which include undef which is overly
    741     // pessimistic.
    742     if (CN && UndefElements.none() &&
    743         CN->getValueType(0) == N.getValueType().getScalarType())
    744       return CN;
    745   }
    746 
    747   return nullptr;
    748 }
    749 
    750 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
    751 // float.
    752 static ConstantFPSDNode *isConstOrConstSplatFP(SDValue N) {
    753   if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
    754     return CN;
    755 
    756   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
    757     BitVector UndefElements;
    758     ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements);
    759 
    760     if (CN && UndefElements.none())
    761       return CN;
    762   }
    763 
    764   return nullptr;
    765 }
    766 
    767 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
    768                                     SDValue N0, SDValue N1) {
    769   EVT VT = N0.getValueType();
    770   if (N0.getOpcode() == Opc) {
    771     if (SDNode *L = isConstantIntBuildVectorOrConstantInt(N0.getOperand(1))) {
    772       if (SDNode *R = isConstantIntBuildVectorOrConstantInt(N1)) {
    773         // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
    774         if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, L, R))
    775           return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
    776         return SDValue();
    777       }
    778       if (N0.hasOneUse()) {
    779         // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
    780         // use
    781         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
    782         if (!OpNode.getNode())
    783           return SDValue();
    784         AddToWorklist(OpNode.getNode());
    785         return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
    786       }
    787     }
    788   }
    789 
    790   if (N1.getOpcode() == Opc) {
    791     if (SDNode *R = isConstantIntBuildVectorOrConstantInt(N1.getOperand(1))) {
    792       if (SDNode *L = isConstantIntBuildVectorOrConstantInt(N0)) {
    793         // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
    794         if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, R, L))
    795           return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
    796         return SDValue();
    797       }
    798       if (N1.hasOneUse()) {
    799         // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one
    800         // use
    801         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0);
    802         if (!OpNode.getNode())
    803           return SDValue();
    804         AddToWorklist(OpNode.getNode());
    805         return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
    806       }
    807     }
    808   }
    809 
    810   return SDValue();
    811 }
    812 
    813 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
    814                                bool AddTo) {
    815   assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
    816   ++NodesCombined;
    817   DEBUG(dbgs() << "\nReplacing.1 ";
    818         N->dump(&DAG);
    819         dbgs() << "\nWith: ";
    820         To[0].getNode()->dump(&DAG);
    821         dbgs() << " and " << NumTo-1 << " other values\n");
    822   for (unsigned i = 0, e = NumTo; i != e; ++i)
    823     assert((!To[i].getNode() ||
    824             N->getValueType(i) == To[i].getValueType()) &&
    825            "Cannot combine value to value of different type!");
    826 
    827   WorklistRemover DeadNodes(*this);
    828   DAG.ReplaceAllUsesWith(N, To);
    829   if (AddTo) {
    830     // Push the new nodes and any users onto the worklist
    831     for (unsigned i = 0, e = NumTo; i != e; ++i) {
    832       if (To[i].getNode()) {
    833         AddToWorklist(To[i].getNode());
    834         AddUsersToWorklist(To[i].getNode());
    835       }
    836     }
    837   }
    838 
    839   // Finally, if the node is now dead, remove it from the graph.  The node
    840   // may not be dead if the replacement process recursively simplified to
    841   // something else needing this node.
    842   if (N->use_empty())
    843     deleteAndRecombine(N);
    844   return SDValue(N, 0);
    845 }
    846 
    847 void DAGCombiner::
    848 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
    849   // Replace all uses.  If any nodes become isomorphic to other nodes and
    850   // are deleted, make sure to remove them from our worklist.
    851   WorklistRemover DeadNodes(*this);
    852   DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
    853 
    854   // Push the new node and any (possibly new) users onto the worklist.
    855   AddToWorklist(TLO.New.getNode());
    856   AddUsersToWorklist(TLO.New.getNode());
    857 
    858   // Finally, if the node is now dead, remove it from the graph.  The node
    859   // may not be dead if the replacement process recursively simplified to
    860   // something else needing this node.
    861   if (TLO.Old.getNode()->use_empty())
    862     deleteAndRecombine(TLO.Old.getNode());
    863 }
    864 
    865 /// Check the specified integer node value to see if it can be simplified or if
    866 /// things it uses can be simplified by bit propagation. If so, return true.
    867 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
    868   TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
    869   APInt KnownZero, KnownOne;
    870   if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
    871     return false;
    872 
    873   // Revisit the node.
    874   AddToWorklist(Op.getNode());
    875 
    876   // Replace the old value with the new one.
    877   ++NodesCombined;
    878   DEBUG(dbgs() << "\nReplacing.2 ";
    879         TLO.Old.getNode()->dump(&DAG);
    880         dbgs() << "\nWith: ";
    881         TLO.New.getNode()->dump(&DAG);
    882         dbgs() << '\n');
    883 
    884   CommitTargetLoweringOpt(TLO);
    885   return true;
    886 }
    887 
    888 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
    889   SDLoc dl(Load);
    890   EVT VT = Load->getValueType(0);
    891   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
    892 
    893   DEBUG(dbgs() << "\nReplacing.9 ";
    894         Load->dump(&DAG);
    895         dbgs() << "\nWith: ";
    896         Trunc.getNode()->dump(&DAG);
    897         dbgs() << '\n');
    898   WorklistRemover DeadNodes(*this);
    899   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
    900   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
    901   deleteAndRecombine(Load);
    902   AddToWorklist(Trunc.getNode());
    903 }
    904 
    905 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
    906   Replace = false;
    907   SDLoc dl(Op);
    908   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
    909     EVT MemVT = LD->getMemoryVT();
    910     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
    911       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
    912                                                        : ISD::EXTLOAD)
    913       : LD->getExtensionType();
    914     Replace = true;
    915     return DAG.getExtLoad(ExtType, dl, PVT,
    916                           LD->getChain(), LD->getBasePtr(),
    917                           MemVT, LD->getMemOperand());
    918   }
    919 
    920   unsigned Opc = Op.getOpcode();
    921   switch (Opc) {
    922   default: break;
    923   case ISD::AssertSext:
    924     return DAG.getNode(ISD::AssertSext, dl, PVT,
    925                        SExtPromoteOperand(Op.getOperand(0), PVT),
    926                        Op.getOperand(1));
    927   case ISD::AssertZext:
    928     return DAG.getNode(ISD::AssertZext, dl, PVT,
    929                        ZExtPromoteOperand(Op.getOperand(0), PVT),
    930                        Op.getOperand(1));
    931   case ISD::Constant: {
    932     unsigned ExtOpc =
    933       Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
    934     return DAG.getNode(ExtOpc, dl, PVT, Op);
    935   }
    936   }
    937 
    938   if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
    939     return SDValue();
    940   return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
    941 }
    942 
    943 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
    944   if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
    945     return SDValue();
    946   EVT OldVT = Op.getValueType();
    947   SDLoc dl(Op);
    948   bool Replace = false;
    949   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
    950   if (!NewOp.getNode())
    951     return SDValue();
    952   AddToWorklist(NewOp.getNode());
    953 
    954   if (Replace)
    955     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
    956   return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
    957                      DAG.getValueType(OldVT));
    958 }
    959 
    960 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
    961   EVT OldVT = Op.getValueType();
    962   SDLoc dl(Op);
    963   bool Replace = false;
    964   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
    965   if (!NewOp.getNode())
    966     return SDValue();
    967   AddToWorklist(NewOp.getNode());
    968 
    969   if (Replace)
    970     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
    971   return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
    972 }
    973 
    974 /// Promote the specified integer binary operation if the target indicates it is
    975 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
    976 /// i32 since i16 instructions are longer.
    977 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
    978   if (!LegalOperations)
    979     return SDValue();
    980 
    981   EVT VT = Op.getValueType();
    982   if (VT.isVector() || !VT.isInteger())
    983     return SDValue();
    984 
    985   // If operation type is 'undesirable', e.g. i16 on x86, consider
    986   // promoting it.
    987   unsigned Opc = Op.getOpcode();
    988   if (TLI.isTypeDesirableForOp(Opc, VT))
    989     return SDValue();
    990 
    991   EVT PVT = VT;
    992   // Consult target whether it is a good idea to promote this operation and
    993   // what's the right type to promote it to.
    994   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
    995     assert(PVT != VT && "Don't know what type to promote to!");
    996 
    997     bool Replace0 = false;
    998     SDValue N0 = Op.getOperand(0);
    999     SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
   1000     if (!NN0.getNode())
   1001       return SDValue();
   1002 
   1003     bool Replace1 = false;
   1004     SDValue N1 = Op.getOperand(1);
   1005     SDValue NN1;
   1006     if (N0 == N1)
   1007       NN1 = NN0;
   1008     else {
   1009       NN1 = PromoteOperand(N1, PVT, Replace1);
   1010       if (!NN1.getNode())
   1011         return SDValue();
   1012     }
   1013 
   1014     AddToWorklist(NN0.getNode());
   1015     if (NN1.getNode())
   1016       AddToWorklist(NN1.getNode());
   1017 
   1018     if (Replace0)
   1019       ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
   1020     if (Replace1)
   1021       ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
   1022 
   1023     DEBUG(dbgs() << "\nPromoting ";
   1024           Op.getNode()->dump(&DAG));
   1025     SDLoc dl(Op);
   1026     return DAG.getNode(ISD::TRUNCATE, dl, VT,
   1027                        DAG.getNode(Opc, dl, PVT, NN0, NN1));
   1028   }
   1029   return SDValue();
   1030 }
   1031 
   1032 /// Promote the specified integer shift operation if the target indicates it is
   1033 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
   1034 /// i32 since i16 instructions are longer.
   1035 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
   1036   if (!LegalOperations)
   1037     return SDValue();
   1038 
   1039   EVT VT = Op.getValueType();
   1040   if (VT.isVector() || !VT.isInteger())
   1041     return SDValue();
   1042 
   1043   // If operation type is 'undesirable', e.g. i16 on x86, consider
   1044   // promoting it.
   1045   unsigned Opc = Op.getOpcode();
   1046   if (TLI.isTypeDesirableForOp(Opc, VT))
   1047     return SDValue();
   1048 
   1049   EVT PVT = VT;
   1050   // Consult target whether it is a good idea to promote this operation and
   1051   // what's the right type to promote it to.
   1052   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
   1053     assert(PVT != VT && "Don't know what type to promote to!");
   1054 
   1055     bool Replace = false;
   1056     SDValue N0 = Op.getOperand(0);
   1057     if (Opc == ISD::SRA)
   1058       N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
   1059     else if (Opc == ISD::SRL)
   1060       N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
   1061     else
   1062       N0 = PromoteOperand(N0, PVT, Replace);
   1063     if (!N0.getNode())
   1064       return SDValue();
   1065 
   1066     AddToWorklist(N0.getNode());
   1067     if (Replace)
   1068       ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
   1069 
   1070     DEBUG(dbgs() << "\nPromoting ";
   1071           Op.getNode()->dump(&DAG));
   1072     SDLoc dl(Op);
   1073     return DAG.getNode(ISD::TRUNCATE, dl, VT,
   1074                        DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
   1075   }
   1076   return SDValue();
   1077 }
   1078 
   1079 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
   1080   if (!LegalOperations)
   1081     return SDValue();
   1082 
   1083   EVT VT = Op.getValueType();
   1084   if (VT.isVector() || !VT.isInteger())
   1085     return SDValue();
   1086 
   1087   // If operation type is 'undesirable', e.g. i16 on x86, consider
   1088   // promoting it.
   1089   unsigned Opc = Op.getOpcode();
   1090   if (TLI.isTypeDesirableForOp(Opc, VT))
   1091     return SDValue();
   1092 
   1093   EVT PVT = VT;
   1094   // Consult target whether it is a good idea to promote this operation and
   1095   // what's the right type to promote it to.
   1096   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
   1097     assert(PVT != VT && "Don't know what type to promote to!");
   1098     // fold (aext (aext x)) -> (aext x)
   1099     // fold (aext (zext x)) -> (zext x)
   1100     // fold (aext (sext x)) -> (sext x)
   1101     DEBUG(dbgs() << "\nPromoting ";
   1102           Op.getNode()->dump(&DAG));
   1103     return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
   1104   }
   1105   return SDValue();
   1106 }
   1107 
   1108 bool DAGCombiner::PromoteLoad(SDValue Op) {
   1109   if (!LegalOperations)
   1110     return false;
   1111 
   1112   EVT VT = Op.getValueType();
   1113   if (VT.isVector() || !VT.isInteger())
   1114     return false;
   1115 
   1116   // If operation type is 'undesirable', e.g. i16 on x86, consider
   1117   // promoting it.
   1118   unsigned Opc = Op.getOpcode();
   1119   if (TLI.isTypeDesirableForOp(Opc, VT))
   1120     return false;
   1121 
   1122   EVT PVT = VT;
   1123   // Consult target whether it is a good idea to promote this operation and
   1124   // what's the right type to promote it to.
   1125   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
   1126     assert(PVT != VT && "Don't know what type to promote to!");
   1127 
   1128     SDLoc dl(Op);
   1129     SDNode *N = Op.getNode();
   1130     LoadSDNode *LD = cast<LoadSDNode>(N);
   1131     EVT MemVT = LD->getMemoryVT();
   1132     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
   1133       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
   1134                                                        : ISD::EXTLOAD)
   1135       : LD->getExtensionType();
   1136     SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
   1137                                    LD->getChain(), LD->getBasePtr(),
   1138                                    MemVT, LD->getMemOperand());
   1139     SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
   1140 
   1141     DEBUG(dbgs() << "\nPromoting ";
   1142           N->dump(&DAG);
   1143           dbgs() << "\nTo: ";
   1144           Result.getNode()->dump(&DAG);
   1145           dbgs() << '\n');
   1146     WorklistRemover DeadNodes(*this);
   1147     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
   1148     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
   1149     deleteAndRecombine(N);
   1150     AddToWorklist(Result.getNode());
   1151     return true;
   1152   }
   1153   return false;
   1154 }
   1155 
   1156 /// \brief Recursively delete a node which has no uses and any operands for
   1157 /// which it is the only use.
   1158 ///
   1159 /// Note that this both deletes the nodes and removes them from the worklist.
   1160 /// It also adds any nodes who have had a user deleted to the worklist as they
   1161 /// may now have only one use and subject to other combines.
   1162 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) {
   1163   if (!N->use_empty())
   1164     return false;
   1165 
   1166   SmallSetVector<SDNode *, 16> Nodes;
   1167   Nodes.insert(N);
   1168   do {
   1169     N = Nodes.pop_back_val();
   1170     if (!N)
   1171       continue;
   1172 
   1173     if (N->use_empty()) {
   1174       for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
   1175         Nodes.insert(N->getOperand(i).getNode());
   1176 
   1177       removeFromWorklist(N);
   1178       DAG.DeleteNode(N);
   1179     } else {
   1180       AddToWorklist(N);
   1181     }
   1182   } while (!Nodes.empty());
   1183   return true;
   1184 }
   1185 
   1186 //===----------------------------------------------------------------------===//
   1187 //  Main DAG Combiner implementation
   1188 //===----------------------------------------------------------------------===//
   1189 
   1190 void DAGCombiner::Run(CombineLevel AtLevel) {
   1191   // set the instance variables, so that the various visit routines may use it.
   1192   Level = AtLevel;
   1193   LegalOperations = Level >= AfterLegalizeVectorOps;
   1194   LegalTypes = Level >= AfterLegalizeTypes;
   1195 
   1196   // Add all the dag nodes to the worklist.
   1197   for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
   1198        E = DAG.allnodes_end(); I != E; ++I)
   1199     AddToWorklist(I);
   1200 
   1201   // Create a dummy node (which is not added to allnodes), that adds a reference
   1202   // to the root node, preventing it from being deleted, and tracking any
   1203   // changes of the root.
   1204   HandleSDNode Dummy(DAG.getRoot());
   1205 
   1206   // while the worklist isn't empty, find a node and
   1207   // try and combine it.
   1208   while (!WorklistMap.empty()) {
   1209     SDNode *N;
   1210     // The Worklist holds the SDNodes in order, but it may contain null entries.
   1211     do {
   1212       N = Worklist.pop_back_val();
   1213     } while (!N);
   1214 
   1215     bool GoodWorklistEntry = WorklistMap.erase(N);
   1216     (void)GoodWorklistEntry;
   1217     assert(GoodWorklistEntry &&
   1218            "Found a worklist entry without a corresponding map entry!");
   1219 
   1220     // If N has no uses, it is dead.  Make sure to revisit all N's operands once
   1221     // N is deleted from the DAG, since they too may now be dead or may have a
   1222     // reduced number of uses, allowing other xforms.
   1223     if (recursivelyDeleteUnusedNodes(N))
   1224       continue;
   1225 
   1226     WorklistRemover DeadNodes(*this);
   1227 
   1228     // If this combine is running after legalizing the DAG, re-legalize any
   1229     // nodes pulled off the worklist.
   1230     if (Level == AfterLegalizeDAG) {
   1231       SmallSetVector<SDNode *, 16> UpdatedNodes;
   1232       bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes);
   1233 
   1234       for (SDNode *LN : UpdatedNodes) {
   1235         AddToWorklist(LN);
   1236         AddUsersToWorklist(LN);
   1237       }
   1238       if (!NIsValid)
   1239         continue;
   1240     }
   1241 
   1242     DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG));
   1243 
   1244     // Add any operands of the new node which have not yet been combined to the
   1245     // worklist as well. Because the worklist uniques things already, this
   1246     // won't repeatedly process the same operand.
   1247     CombinedNodes.insert(N);
   1248     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
   1249       if (!CombinedNodes.count(N->getOperand(i).getNode()))
   1250         AddToWorklist(N->getOperand(i).getNode());
   1251 
   1252     SDValue RV = combine(N);
   1253 
   1254     if (!RV.getNode())
   1255       continue;
   1256 
   1257     ++NodesCombined;
   1258 
   1259     // If we get back the same node we passed in, rather than a new node or
   1260     // zero, we know that the node must have defined multiple values and
   1261     // CombineTo was used.  Since CombineTo takes care of the worklist
   1262     // mechanics for us, we have no work to do in this case.
   1263     if (RV.getNode() == N)
   1264       continue;
   1265 
   1266     assert(N->getOpcode() != ISD::DELETED_NODE &&
   1267            RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
   1268            "Node was deleted but visit returned new node!");
   1269 
   1270     DEBUG(dbgs() << " ... into: ";
   1271           RV.getNode()->dump(&DAG));
   1272 
   1273     // Transfer debug value.
   1274     DAG.TransferDbgValues(SDValue(N, 0), RV);
   1275     if (N->getNumValues() == RV.getNode()->getNumValues())
   1276       DAG.ReplaceAllUsesWith(N, RV.getNode());
   1277     else {
   1278       assert(N->getValueType(0) == RV.getValueType() &&
   1279              N->getNumValues() == 1 && "Type mismatch");
   1280       SDValue OpV = RV;
   1281       DAG.ReplaceAllUsesWith(N, &OpV);
   1282     }
   1283 
   1284     // Push the new node and any users onto the worklist
   1285     AddToWorklist(RV.getNode());
   1286     AddUsersToWorklist(RV.getNode());
   1287 
   1288     // Finally, if the node is now dead, remove it from the graph.  The node
   1289     // may not be dead if the replacement process recursively simplified to
   1290     // something else needing this node. This will also take care of adding any
   1291     // operands which have lost a user to the worklist.
   1292     recursivelyDeleteUnusedNodes(N);
   1293   }
   1294 
   1295   // If the root changed (e.g. it was a dead load, update the root).
   1296   DAG.setRoot(Dummy.getValue());
   1297   DAG.RemoveDeadNodes();
   1298 }
   1299 
   1300 SDValue DAGCombiner::visit(SDNode *N) {
   1301   switch (N->getOpcode()) {
   1302   default: break;
   1303   case ISD::TokenFactor:        return visitTokenFactor(N);
   1304   case ISD::MERGE_VALUES:       return visitMERGE_VALUES(N);
   1305   case ISD::ADD:                return visitADD(N);
   1306   case ISD::SUB:                return visitSUB(N);
   1307   case ISD::ADDC:               return visitADDC(N);
   1308   case ISD::SUBC:               return visitSUBC(N);
   1309   case ISD::ADDE:               return visitADDE(N);
   1310   case ISD::SUBE:               return visitSUBE(N);
   1311   case ISD::MUL:                return visitMUL(N);
   1312   case ISD::SDIV:               return visitSDIV(N);
   1313   case ISD::UDIV:               return visitUDIV(N);
   1314   case ISD::SREM:               return visitSREM(N);
   1315   case ISD::UREM:               return visitUREM(N);
   1316   case ISD::MULHU:              return visitMULHU(N);
   1317   case ISD::MULHS:              return visitMULHS(N);
   1318   case ISD::SMUL_LOHI:          return visitSMUL_LOHI(N);
   1319   case ISD::UMUL_LOHI:          return visitUMUL_LOHI(N);
   1320   case ISD::SMULO:              return visitSMULO(N);
   1321   case ISD::UMULO:              return visitUMULO(N);
   1322   case ISD::SDIVREM:            return visitSDIVREM(N);
   1323   case ISD::UDIVREM:            return visitUDIVREM(N);
   1324   case ISD::AND:                return visitAND(N);
   1325   case ISD::OR:                 return visitOR(N);
   1326   case ISD::XOR:                return visitXOR(N);
   1327   case ISD::SHL:                return visitSHL(N);
   1328   case ISD::SRA:                return visitSRA(N);
   1329   case ISD::SRL:                return visitSRL(N);
   1330   case ISD::ROTR:
   1331   case ISD::ROTL:               return visitRotate(N);
   1332   case ISD::CTLZ:               return visitCTLZ(N);
   1333   case ISD::CTLZ_ZERO_UNDEF:    return visitCTLZ_ZERO_UNDEF(N);
   1334   case ISD::CTTZ:               return visitCTTZ(N);
   1335   case ISD::CTTZ_ZERO_UNDEF:    return visitCTTZ_ZERO_UNDEF(N);
   1336   case ISD::CTPOP:              return visitCTPOP(N);
   1337   case ISD::SELECT:             return visitSELECT(N);
   1338   case ISD::VSELECT:            return visitVSELECT(N);
   1339   case ISD::SELECT_CC:          return visitSELECT_CC(N);
   1340   case ISD::SETCC:              return visitSETCC(N);
   1341   case ISD::SIGN_EXTEND:        return visitSIGN_EXTEND(N);
   1342   case ISD::ZERO_EXTEND:        return visitZERO_EXTEND(N);
   1343   case ISD::ANY_EXTEND:         return visitANY_EXTEND(N);
   1344   case ISD::SIGN_EXTEND_INREG:  return visitSIGN_EXTEND_INREG(N);
   1345   case ISD::TRUNCATE:           return visitTRUNCATE(N);
   1346   case ISD::BITCAST:            return visitBITCAST(N);
   1347   case ISD::BUILD_PAIR:         return visitBUILD_PAIR(N);
   1348   case ISD::FADD:               return visitFADD(N);
   1349   case ISD::FSUB:               return visitFSUB(N);
   1350   case ISD::FMUL:               return visitFMUL(N);
   1351   case ISD::FMA:                return visitFMA(N);
   1352   case ISD::FDIV:               return visitFDIV(N);
   1353   case ISD::FREM:               return visitFREM(N);
   1354   case ISD::FSQRT:              return visitFSQRT(N);
   1355   case ISD::FCOPYSIGN:          return visitFCOPYSIGN(N);
   1356   case ISD::SINT_TO_FP:         return visitSINT_TO_FP(N);
   1357   case ISD::UINT_TO_FP:         return visitUINT_TO_FP(N);
   1358   case ISD::FP_TO_SINT:         return visitFP_TO_SINT(N);
   1359   case ISD::FP_TO_UINT:         return visitFP_TO_UINT(N);
   1360   case ISD::FP_ROUND:           return visitFP_ROUND(N);
   1361   case ISD::FP_ROUND_INREG:     return visitFP_ROUND_INREG(N);
   1362   case ISD::FP_EXTEND:          return visitFP_EXTEND(N);
   1363   case ISD::FNEG:               return visitFNEG(N);
   1364   case ISD::FABS:               return visitFABS(N);
   1365   case ISD::FFLOOR:             return visitFFLOOR(N);
   1366   case ISD::FMINNUM:            return visitFMINNUM(N);
   1367   case ISD::FMAXNUM:            return visitFMAXNUM(N);
   1368   case ISD::FCEIL:              return visitFCEIL(N);
   1369   case ISD::FTRUNC:             return visitFTRUNC(N);
   1370   case ISD::BRCOND:             return visitBRCOND(N);
   1371   case ISD::BR_CC:              return visitBR_CC(N);
   1372   case ISD::LOAD:               return visitLOAD(N);
   1373   case ISD::STORE:              return visitSTORE(N);
   1374   case ISD::INSERT_VECTOR_ELT:  return visitINSERT_VECTOR_ELT(N);
   1375   case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
   1376   case ISD::BUILD_VECTOR:       return visitBUILD_VECTOR(N);
   1377   case ISD::CONCAT_VECTORS:     return visitCONCAT_VECTORS(N);
   1378   case ISD::EXTRACT_SUBVECTOR:  return visitEXTRACT_SUBVECTOR(N);
   1379   case ISD::VECTOR_SHUFFLE:     return visitVECTOR_SHUFFLE(N);
   1380   case ISD::SCALAR_TO_VECTOR:   return visitSCALAR_TO_VECTOR(N);
   1381   case ISD::INSERT_SUBVECTOR:   return visitINSERT_SUBVECTOR(N);
   1382   case ISD::MLOAD:              return visitMLOAD(N);
   1383   case ISD::MSTORE:             return visitMSTORE(N);
   1384   case ISD::FP_TO_FP16:         return visitFP_TO_FP16(N);
   1385   }
   1386   return SDValue();
   1387 }
   1388 
   1389 SDValue DAGCombiner::combine(SDNode *N) {
   1390   SDValue RV = visit(N);
   1391 
   1392   // If nothing happened, try a target-specific DAG combine.
   1393   if (!RV.getNode()) {
   1394     assert(N->getOpcode() != ISD::DELETED_NODE &&
   1395            "Node was deleted but visit returned NULL!");
   1396 
   1397     if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
   1398         TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
   1399 
   1400       // Expose the DAG combiner to the target combiner impls.
   1401       TargetLowering::DAGCombinerInfo
   1402         DagCombineInfo(DAG, Level, false, this);
   1403 
   1404       RV = TLI.PerformDAGCombine(N, DagCombineInfo);
   1405     }
   1406   }
   1407 
   1408   // If nothing happened still, try promoting the operation.
   1409   if (!RV.getNode()) {
   1410     switch (N->getOpcode()) {
   1411     default: break;
   1412     case ISD::ADD:
   1413     case ISD::SUB:
   1414     case ISD::MUL:
   1415     case ISD::AND:
   1416     case ISD::OR:
   1417     case ISD::XOR:
   1418       RV = PromoteIntBinOp(SDValue(N, 0));
   1419       break;
   1420     case ISD::SHL:
   1421     case ISD::SRA:
   1422     case ISD::SRL:
   1423       RV = PromoteIntShiftOp(SDValue(N, 0));
   1424       break;
   1425     case ISD::SIGN_EXTEND:
   1426     case ISD::ZERO_EXTEND:
   1427     case ISD::ANY_EXTEND:
   1428       RV = PromoteExtend(SDValue(N, 0));
   1429       break;
   1430     case ISD::LOAD:
   1431       if (PromoteLoad(SDValue(N, 0)))
   1432         RV = SDValue(N, 0);
   1433       break;
   1434     }
   1435   }
   1436 
   1437   // If N is a commutative binary node, try commuting it to enable more
   1438   // sdisel CSE.
   1439   if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
   1440       N->getNumValues() == 1) {
   1441     SDValue N0 = N->getOperand(0);
   1442     SDValue N1 = N->getOperand(1);
   1443 
   1444     // Constant operands are canonicalized to RHS.
   1445     if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
   1446       SDValue Ops[] = {N1, N0};
   1447       SDNode *CSENode;
   1448       if (const BinaryWithFlagsSDNode *BinNode =
   1449               dyn_cast<BinaryWithFlagsSDNode>(N)) {
   1450         CSENode = DAG.getNodeIfExists(
   1451             N->getOpcode(), N->getVTList(), Ops, BinNode->hasNoUnsignedWrap(),
   1452             BinNode->hasNoSignedWrap(), BinNode->isExact());
   1453       } else {
   1454         CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops);
   1455       }
   1456       if (CSENode)
   1457         return SDValue(CSENode, 0);
   1458     }
   1459   }
   1460 
   1461   return RV;
   1462 }
   1463 
   1464 /// Given a node, return its input chain if it has one, otherwise return a null
   1465 /// sd operand.
   1466 static SDValue getInputChainForNode(SDNode *N) {
   1467   if (unsigned NumOps = N->getNumOperands()) {
   1468     if (N->getOperand(0).getValueType() == MVT::Other)
   1469       return N->getOperand(0);
   1470     if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
   1471       return N->getOperand(NumOps-1);
   1472     for (unsigned i = 1; i < NumOps-1; ++i)
   1473       if (N->getOperand(i).getValueType() == MVT::Other)
   1474         return N->getOperand(i);
   1475   }
   1476   return SDValue();
   1477 }
   1478 
   1479 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
   1480   // If N has two operands, where one has an input chain equal to the other,
   1481   // the 'other' chain is redundant.
   1482   if (N->getNumOperands() == 2) {
   1483     if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
   1484       return N->getOperand(0);
   1485     if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
   1486       return N->getOperand(1);
   1487   }
   1488 
   1489   SmallVector<SDNode *, 8> TFs;     // List of token factors to visit.
   1490   SmallVector<SDValue, 8> Ops;    // Ops for replacing token factor.
   1491   SmallPtrSet<SDNode*, 16> SeenOps;
   1492   bool Changed = false;             // If we should replace this token factor.
   1493 
   1494   // Start out with this token factor.
   1495   TFs.push_back(N);
   1496 
   1497   // Iterate through token factors.  The TFs grows when new token factors are
   1498   // encountered.
   1499   for (unsigned i = 0; i < TFs.size(); ++i) {
   1500     SDNode *TF = TFs[i];
   1501 
   1502     // Check each of the operands.
   1503     for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
   1504       SDValue Op = TF->getOperand(i);
   1505 
   1506       switch (Op.getOpcode()) {
   1507       case ISD::EntryToken:
   1508         // Entry tokens don't need to be added to the list. They are
   1509         // redundant.
   1510         Changed = true;
   1511         break;
   1512 
   1513       case ISD::TokenFactor:
   1514         if (Op.hasOneUse() &&
   1515             std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
   1516           // Queue up for processing.
   1517           TFs.push_back(Op.getNode());
   1518           // Clean up in case the token factor is removed.
   1519           AddToWorklist(Op.getNode());
   1520           Changed = true;
   1521           break;
   1522         }
   1523         // Fall thru
   1524 
   1525       default:
   1526         // Only add if it isn't already in the list.
   1527         if (SeenOps.insert(Op.getNode()).second)
   1528           Ops.push_back(Op);
   1529         else
   1530           Changed = true;
   1531         break;
   1532       }
   1533     }
   1534   }
   1535 
   1536   SDValue Result;
   1537 
   1538   // If we've changed things around then replace token factor.
   1539   if (Changed) {
   1540     if (Ops.empty()) {
   1541       // The entry token is the only possible outcome.
   1542       Result = DAG.getEntryNode();
   1543     } else {
   1544       // New and improved token factor.
   1545       Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
   1546     }
   1547 
   1548     // Add users to worklist if AA is enabled, since it may introduce
   1549     // a lot of new chained token factors while removing memory deps.
   1550     bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
   1551       : DAG.getSubtarget().useAA();
   1552     return CombineTo(N, Result, UseAA /*add to worklist*/);
   1553   }
   1554 
   1555   return Result;
   1556 }
   1557 
   1558 /// MERGE_VALUES can always be eliminated.
   1559 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
   1560   WorklistRemover DeadNodes(*this);
   1561   // Replacing results may cause a different MERGE_VALUES to suddenly
   1562   // be CSE'd with N, and carry its uses with it. Iterate until no
   1563   // uses remain, to ensure that the node can be safely deleted.
   1564   // First add the users of this node to the work list so that they
   1565   // can be tried again once they have new operands.
   1566   AddUsersToWorklist(N);
   1567   do {
   1568     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
   1569       DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
   1570   } while (!N->use_empty());
   1571   deleteAndRecombine(N);
   1572   return SDValue(N, 0);   // Return N so it doesn't get rechecked!
   1573 }
   1574 
   1575 SDValue DAGCombiner::visitADD(SDNode *N) {
   1576   SDValue N0 = N->getOperand(0);
   1577   SDValue N1 = N->getOperand(1);
   1578   EVT VT = N0.getValueType();
   1579 
   1580   // fold vector ops
   1581   if (VT.isVector()) {
   1582     if (SDValue FoldedVOp = SimplifyVBinOp(N))
   1583       return FoldedVOp;
   1584 
   1585     // fold (add x, 0) -> x, vector edition
   1586     if (ISD::isBuildVectorAllZeros(N1.getNode()))
   1587       return N0;
   1588     if (ISD::isBuildVectorAllZeros(N0.getNode()))
   1589       return N1;
   1590   }
   1591 
   1592   // fold (add x, undef) -> undef
   1593   if (N0.getOpcode() == ISD::UNDEF)
   1594     return N0;
   1595   if (N1.getOpcode() == ISD::UNDEF)
   1596     return N1;
   1597   // fold (add c1, c2) -> c1+c2
   1598   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
   1599   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
   1600   if (N0C && N1C)
   1601     return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C);
   1602   // canonicalize constant to RHS
   1603   if (isConstantIntBuildVectorOrConstantInt(N0) &&
   1604      !isConstantIntBuildVectorOrConstantInt(N1))
   1605     return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
   1606   // fold (add x, 0) -> x
   1607   if (N1C && N1C->isNullValue())
   1608     return N0;
   1609   // fold (add Sym, c) -> Sym+c
   1610   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
   1611     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
   1612         GA->getOpcode() == ISD::GlobalAddress)
   1613       return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
   1614                                   GA->getOffset() +
   1615                                     (uint64_t)N1C->getSExtValue());
   1616   // fold ((c1-A)+c2) -> (c1+c2)-A
   1617   if (N1C && N0.getOpcode() == ISD::SUB)
   1618     if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
   1619       return DAG.getNode(ISD::SUB, SDLoc(N), VT,
   1620                          DAG.getConstant(N1C->getAPIntValue()+
   1621                                          N0C->getAPIntValue(), VT),
   1622                          N0.getOperand(1));
   1623   // reassociate add
   1624   if (SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1))
   1625     return RADD;
   1626   // fold ((0-A) + B) -> B-A
   1627   if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
   1628       cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
   1629     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
   1630   // fold (A + (0-B)) -> A-B
   1631   if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
   1632       cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
   1633     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
   1634   // fold (A+(B-A)) -> B
   1635   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
   1636     return N1.getOperand(0);
   1637   // fold ((B-A)+A) -> B
   1638   if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
   1639     return N0.getOperand(0);
   1640   // fold (A+(B-(A+C))) to (B-C)
   1641   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
   1642       N0 == N1.getOperand(1).getOperand(0))
   1643     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
   1644                        N1.getOperand(1).getOperand(1));
   1645   // fold (A+(B-(C+A))) to (B-C)
   1646   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
   1647       N0 == N1.getOperand(1).getOperand(1))
   1648     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
   1649                        N1.getOperand(1).getOperand(0));
   1650   // fold (A+((B-A)+or-C)) to (B+or-C)
   1651   if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
   1652       N1.getOperand(0).getOpcode() == ISD::SUB &&
   1653       N0 == N1.getOperand(0).getOperand(1))
   1654     return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
   1655                        N1.getOperand(0).getOperand(0), N1.getOperand(1));
   1656 
   1657   // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
   1658   if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
   1659     SDValue N00 = N0.getOperand(0);
   1660     SDValue N01 = N0.getOperand(1);
   1661     SDValue N10 = N1.getOperand(0);
   1662     SDValue N11 = N1.getOperand(1);
   1663 
   1664     if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
   1665       return DAG.getNode(ISD::SUB, SDLoc(N), VT,
   1666                          DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
   1667                          DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
   1668   }
   1669 
   1670   if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
   1671     return SDValue(N, 0);
   1672 
   1673   // fold (a+b) -> (a|b) iff a and b share no bits.
   1674   if (VT.isInteger() && !VT.isVector()) {
   1675     APInt LHSZero, LHSOne;
   1676     APInt RHSZero, RHSOne;
   1677     DAG.computeKnownBits(N0, LHSZero, LHSOne);
   1678 
   1679     if (LHSZero.getBoolValue()) {
   1680       DAG.computeKnownBits(N1, RHSZero, RHSOne);
   1681 
   1682       // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
   1683       // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
   1684       if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){
   1685         if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT))
   1686           return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
   1687       }
   1688     }
   1689   }
   1690 
   1691   // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
   1692   if (N1.getOpcode() == ISD::SHL &&
   1693       N1.getOperand(0).getOpcode() == ISD::SUB)
   1694     if (ConstantSDNode *C =
   1695           dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
   1696       if (C->getAPIntValue() == 0)
   1697         return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
   1698                            DAG.getNode(ISD::SHL, SDLoc(N), VT,
   1699                                        N1.getOperand(0).getOperand(1),
   1700                                        N1.getOperand(1)));
   1701   if (N0.getOpcode() == ISD::SHL &&
   1702       N0.getOperand(0).getOpcode() == ISD::SUB)
   1703     if (ConstantSDNode *C =
   1704           dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
   1705       if (C->getAPIntValue() == 0)
   1706         return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
   1707                            DAG.getNode(ISD::SHL, SDLoc(N), VT,
   1708                                        N0.getOperand(0).getOperand(1),
   1709                                        N0.getOperand(1)));
   1710 
   1711   if (N1.getOpcode() == ISD::AND) {
   1712     SDValue AndOp0 = N1.getOperand(0);
   1713     ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1));
   1714     unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
   1715     unsigned DestBits = VT.getScalarType().getSizeInBits();
   1716 
   1717     // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
   1718     // and similar xforms where the inner op is either ~0 or 0.
   1719     if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) {
   1720       SDLoc DL(N);
   1721       return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
   1722     }
   1723   }
   1724 
   1725   // add (sext i1), X -> sub X, (zext i1)
   1726   if (N0.getOpcode() == ISD::SIGN_EXTEND &&
   1727       N0.getOperand(0).getValueType() == MVT::i1 &&
   1728       !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
   1729     SDLoc DL(N);
   1730     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
   1731     return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
   1732   }
   1733 
   1734   // add X, (sextinreg Y i1) -> sub X, (and Y 1)
   1735   if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
   1736     VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
   1737     if (TN->getVT() == MVT::i1) {
   1738       SDLoc DL(N);
   1739       SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
   1740                                  DAG.getConstant(1, VT));
   1741       return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt);
   1742     }
   1743   }
   1744 
   1745   return SDValue();
   1746 }
   1747 
   1748 SDValue DAGCombiner::visitADDC(SDNode *N) {
   1749   SDValue N0 = N->getOperand(0);
   1750   SDValue N1 = N->getOperand(1);
   1751   EVT VT = N0.getValueType();
   1752 
   1753   // If the flag result is dead, turn this into an ADD.
   1754   if (!N->hasAnyUseOfValue(1))
   1755     return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
   1756                      DAG.getNode(ISD::CARRY_FALSE,
   1757                                  SDLoc(N), MVT::Glue));
   1758 
   1759   // canonicalize constant to RHS.
   1760   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
   1761   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
   1762   if (N0C && !N1C)
   1763     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
   1764 
   1765   // fold (addc x, 0) -> x + no carry out
   1766   if (N1C && N1C->isNullValue())
   1767     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
   1768                                         SDLoc(N), MVT::Glue));
   1769 
   1770   // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
   1771   APInt LHSZero, LHSOne;
   1772   APInt RHSZero, RHSOne;
   1773   DAG.computeKnownBits(N0, LHSZero, LHSOne);
   1774 
   1775   if (LHSZero.getBoolValue()) {
   1776     DAG.computeKnownBits(N1, RHSZero, RHSOne);
   1777 
   1778     // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
   1779     // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
   1780     if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
   1781       return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
   1782                        DAG.getNode(ISD::CARRY_FALSE,
   1783                                    SDLoc(N), MVT::Glue));
   1784   }
   1785 
   1786   return SDValue();
   1787 }
   1788 
   1789 SDValue DAGCombiner::visitADDE(SDNode *N) {
   1790   SDValue N0 = N->getOperand(0);
   1791   SDValue N1 = N->getOperand(1);
   1792   SDValue CarryIn = N->getOperand(2);
   1793 
   1794   // canonicalize constant to RHS
   1795   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
   1796   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
   1797   if (N0C && !N1C)
   1798     return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
   1799                        N1, N0, CarryIn);
   1800 
   1801   // fold (adde x, y, false) -> (addc x, y)
   1802   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
   1803     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
   1804 
   1805   return SDValue();
   1806 }
   1807 
   1808 // Since it may not be valid to emit a fold to zero for vector initializers
   1809 // check if we can before folding.
   1810 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
   1811                              SelectionDAG &DAG,
   1812                              bool LegalOperations, bool LegalTypes) {
   1813   if (!VT.isVector())
   1814     return DAG.getConstant(0, VT);
   1815   if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
   1816     return DAG.getConstant(0, VT);
   1817   return SDValue();
   1818 }
   1819 
   1820 SDValue DAGCombiner::visitSUB(SDNode *N) {
   1821   SDValue N0 = N->getOperand(0);
   1822   SDValue N1 = N->getOperand(1);
   1823   EVT VT = N0.getValueType();
   1824 
   1825   // fold vector ops
   1826   if (VT.isVector()) {
   1827     if (SDValue FoldedVOp = SimplifyVBinOp(N))
   1828       return FoldedVOp;
   1829 
   1830     // fold (sub x, 0) -> x, vector edition
   1831     if (ISD::isBuildVectorAllZeros(N1.getNode()))
   1832       return N0;
   1833   }
   1834 
   1835   // fold (sub x, x) -> 0
   1836   // FIXME: Refactor this and xor and other similar operations together.
   1837   if (N0 == N1)
   1838     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
   1839   // fold (sub c1, c2) -> c1-c2
   1840   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
   1841   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
   1842   if (N0C && N1C)
   1843     return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C);
   1844   // fold (sub x, c) -> (add x, -c)
   1845   if (N1C)
   1846     return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0,
   1847                        DAG.getConstant(-N1C->getAPIntValue(), VT));
   1848   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
   1849   if (N0C && N0C->isAllOnesValue())
   1850     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
   1851   // fold A-(A-B) -> B
   1852   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
   1853     return N1.getOperand(1);
   1854   // fold (A+B)-A -> B
   1855   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
   1856     return N0.getOperand(1);
   1857   // fold (A+B)-B -> A
   1858   if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
   1859     return N0.getOperand(0);
   1860   // fold C2-(A+C1) -> (C2-C1)-A
   1861   ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr :
   1862     dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
   1863   if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
   1864     SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
   1865                                    VT);
   1866     return DAG.getNode(ISD::SUB, SDLoc(N), VT, NewC,
   1867                        N1.getOperand(0));
   1868   }
   1869   // fold ((A+(B+or-C))-B) -> A+or-C
   1870   if (N0.getOpcode() == ISD::ADD &&
   1871       (N0.getOperand(1).getOpcode() == ISD::SUB ||
   1872        N0.getOperand(1).getOpcode() == ISD::ADD) &&
   1873       N0.getOperand(1).getOperand(0) == N1)
   1874     return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
   1875                        N0.getOperand(0), N0.getOperand(1).getOperand(1));
   1876   // fold ((A+(C+B))-B) -> A+C
   1877   if (N0.getOpcode() == ISD::ADD &&
   1878       N0.getOperand(1).getOpcode() == ISD::ADD &&
   1879       N0.getOperand(1).getOperand(1) == N1)
   1880     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
   1881                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
   1882   // fold ((A-(B-C))-C) -> A-B
   1883   if (N0.getOpcode() == ISD::SUB &&
   1884       N0.getOperand(1).getOpcode() == ISD::SUB &&
   1885       N0.getOperand(1).getOperand(1) == N1)
   1886     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
   1887                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
   1888 
   1889   // If either operand of a sub is undef, the result is undef
   1890   if (N0.getOpcode() == ISD::UNDEF)
   1891     return N0;
   1892   if (N1.getOpcode() == ISD::UNDEF)
   1893     return N1;
   1894 
   1895   // If the relocation model supports it, consider symbol offsets.
   1896   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
   1897     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
   1898       // fold (sub Sym, c) -> Sym-c
   1899       if (N1C && GA->getOpcode() == ISD::GlobalAddress)
   1900         return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
   1901                                     GA->getOffset() -
   1902                                       (uint64_t)N1C->getSExtValue());
   1903       // fold (sub Sym+c1, Sym+c2) -> c1-c2
   1904       if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
   1905         if (GA->getGlobal() == GB->getGlobal())
   1906           return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
   1907                                  VT);
   1908     }
   1909 
   1910   // sub X, (sextinreg Y i1) -> add X, (and Y 1)
   1911   if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
   1912     VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
   1913     if (TN->getVT() == MVT::i1) {
   1914       SDLoc DL(N);
   1915       SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
   1916                                  DAG.getConstant(1, VT));
   1917       return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt);
   1918     }
   1919   }
   1920 
   1921   return SDValue();
   1922 }
   1923 
   1924 SDValue DAGCombiner::visitSUBC(SDNode *N) {
   1925   SDValue N0 = N->getOperand(0);
   1926   SDValue N1 = N->getOperand(1);
   1927   EVT VT = N0.getValueType();
   1928 
   1929   // If the flag result is dead, turn this into an SUB.
   1930   if (!N->hasAnyUseOfValue(1))
   1931     return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
   1932                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
   1933                                  MVT::Glue));
   1934 
   1935   // fold (subc x, x) -> 0 + no borrow
   1936   if (N0 == N1)
   1937     return CombineTo(N, DAG.getConstant(0, VT),
   1938                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
   1939                                  MVT::Glue));
   1940 
   1941   // fold (subc x, 0) -> x + no borrow
   1942   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
   1943   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
   1944   if (N1C && N1C->isNullValue())
   1945     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
   1946                                         MVT::Glue));
   1947 
   1948   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
   1949   if (N0C && N0C->isAllOnesValue())
   1950     return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
   1951                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
   1952                                  MVT::Glue));
   1953 
   1954   return SDValue();
   1955 }
   1956 
   1957 SDValue DAGCombiner::visitSUBE(SDNode *N) {
   1958   SDValue N0 = N->getOperand(0);
   1959   SDValue N1 = N->getOperand(1);
   1960   SDValue CarryIn = N->getOperand(2);
   1961 
   1962   // fold (sube x, y, false) -> (subc x, y)
   1963   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
   1964     return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
   1965 
   1966   return SDValue();
   1967 }
   1968 
   1969 SDValue DAGCombiner::visitMUL(SDNode *N) {
   1970   SDValue N0 = N->getOperand(0);
   1971   SDValue N1 = N->getOperand(1);
   1972   EVT VT = N0.getValueType();
   1973 
   1974   // fold (mul x, undef) -> 0
   1975   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
   1976     return DAG.getConstant(0, VT);
   1977 
   1978   bool N0IsConst = false;
   1979   bool N1IsConst = false;
   1980   APInt ConstValue0, ConstValue1;
   1981   // fold vector ops
   1982   if (VT.isVector()) {
   1983     if (SDValue FoldedVOp = SimplifyVBinOp(N))
   1984       return FoldedVOp;
   1985 
   1986     N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
   1987     N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
   1988   } else {
   1989     N0IsConst = isa<ConstantSDNode>(N0);
   1990     if (N0IsConst)
   1991       ConstValue0 = cast<ConstantSDNode>(N0)->getAPIntValue();
   1992     N1IsConst = isa<ConstantSDNode>(N1);
   1993     if (N1IsConst)
   1994       ConstValue1 = cast<ConstantSDNode>(N1)->getAPIntValue();
   1995   }
   1996 
   1997   // fold (mul c1, c2) -> c1*c2
   1998   if (N0IsConst && N1IsConst)
   1999     return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0.getNode(), N1.getNode());
   2000 
   2001   // canonicalize constant to RHS (vector doesn't have to splat)
   2002   if (isConstantIntBuildVectorOrConstantInt(N0) &&
   2003      !isConstantIntBuildVectorOrConstantInt(N1))
   2004     return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
   2005   // fold (mul x, 0) -> 0
   2006   if (N1IsConst && ConstValue1 == 0)
   2007     return N1;
   2008   // We require a splat of the entire scalar bit width for non-contiguous
   2009   // bit patterns.
   2010   bool IsFullSplat =
   2011     ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
   2012   // fold (mul x, 1) -> x
   2013   if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
   2014     return N0;
   2015   // fold (mul x, -1) -> 0-x
   2016   if (N1IsConst && ConstValue1.isAllOnesValue())
   2017     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
   2018                        DAG.getConstant(0, VT), N0);
   2019   // fold (mul x, (1 << c)) -> x << c
   2020   if (N1IsConst && ConstValue1.isPowerOf2() && IsFullSplat)
   2021     return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
   2022                        DAG.getConstant(ConstValue1.logBase2(),
   2023                                        getShiftAmountTy(N0.getValueType())));
   2024   // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
   2025   if (N1IsConst && (-ConstValue1).isPowerOf2() && IsFullSplat) {
   2026     unsigned Log2Val = (-ConstValue1).logBase2();
   2027     // FIXME: If the input is something that is easily negated (e.g. a
   2028     // single-use add), we should put the negate there.
   2029     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
   2030                        DAG.getConstant(0, VT),
   2031                        DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
   2032                             DAG.getConstant(Log2Val,
   2033                                       getShiftAmountTy(N0.getValueType()))));
   2034   }
   2035 
   2036   APInt Val;
   2037   // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
   2038   if (N1IsConst && N0.getOpcode() == ISD::SHL &&
   2039       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
   2040                      isa<ConstantSDNode>(N0.getOperand(1)))) {
   2041     SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
   2042                              N1, N0.getOperand(1));
   2043     AddToWorklist(C3.getNode());
   2044     return DAG.getNode(ISD::MUL, SDLoc(N), VT,
   2045                        N0.getOperand(0), C3);
   2046   }
   2047 
   2048   // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
   2049   // use.
   2050   {
   2051     SDValue Sh(nullptr,0), Y(nullptr,0);
   2052     // Check for both (mul (shl X, C), Y)  and  (mul Y, (shl X, C)).
   2053     if (N0.getOpcode() == ISD::SHL &&
   2054         (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
   2055                        isa<ConstantSDNode>(N0.getOperand(1))) &&
   2056         N0.getNode()->hasOneUse()) {
   2057       Sh = N0; Y = N1;
   2058     } else if (N1.getOpcode() == ISD::SHL &&
   2059                isa<ConstantSDNode>(N1.getOperand(1)) &&
   2060                N1.getNode()->hasOneUse()) {
   2061       Sh = N1; Y = N0;
   2062     }
   2063 
   2064     if (Sh.getNode()) {
   2065       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
   2066                                 Sh.getOperand(0), Y);
   2067       return DAG.getNode(ISD::SHL, SDLoc(N), VT,
   2068                          Mul, Sh.getOperand(1));
   2069     }
   2070   }
   2071 
   2072   // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
   2073   if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
   2074       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
   2075                      isa<ConstantSDNode>(N0.getOperand(1))))
   2076     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
   2077                        DAG.getNode(ISD::MUL, SDLoc(N0), VT,
   2078                                    N0.getOperand(0), N1),
   2079                        DAG.getNode(ISD::MUL, SDLoc(N1), VT,
   2080                                    N0.getOperand(1), N1));
   2081 
   2082   // reassociate mul
   2083   if (SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1))
   2084     return RMUL;
   2085 
   2086   return SDValue();
   2087 }
   2088 
   2089 SDValue DAGCombiner::visitSDIV(SDNode *N) {
   2090   SDValue N0 = N->getOperand(0);
   2091   SDValue N1 = N->getOperand(1);
   2092   EVT VT = N->getValueType(0);
   2093 
   2094   // fold vector ops
   2095   if (VT.isVector())
   2096     if (SDValue FoldedVOp = SimplifyVBinOp(N))
   2097       return FoldedVOp;
   2098 
   2099   // fold (sdiv c1, c2) -> c1/c2
   2100   ConstantSDNode *N0C = isConstOrConstSplat(N0);
   2101   ConstantSDNode *N1C = isConstOrConstSplat(N1);
   2102   if (N0C && N1C && !N1C->isNullValue())
   2103     return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C);
   2104   // fold (sdiv X, 1) -> X
   2105   if (N1C && N1C->getAPIntValue() == 1LL)
   2106     return N0;
   2107   // fold (sdiv X, -1) -> 0-X
   2108   if (N1C && N1C->isAllOnesValue())
   2109     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
   2110                        DAG.getConstant(0, VT), N0);
   2111   // If we know the sign bits of both operands are zero, strength reduce to a
   2112   // udiv instead.  Handles (X&15) /s 4 -> X&15 >> 2
   2113   if (!VT.isVector()) {
   2114     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
   2115       return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
   2116                          N0, N1);
   2117   }
   2118 
   2119   // fold (sdiv X, pow2) -> simple ops after legalize
   2120   if (N1C && !N1C->isNullValue() && (N1C->getAPIntValue().isPowerOf2() ||
   2121                                      (-N1C->getAPIntValue()).isPowerOf2())) {
   2122     // If dividing by powers of two is cheap, then don't perform the following
   2123     // fold.
   2124     if (TLI.isPow2SDivCheap())
   2125       return SDValue();
   2126 
   2127     // Target-specific implementation of sdiv x, pow2.
   2128     SDValue Res = BuildSDIVPow2(N);
   2129     if (Res.getNode())
   2130       return Res;
   2131 
   2132     unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
   2133 
   2134     // Splat the sign bit into the register
   2135     SDValue SGN =
   2136         DAG.getNode(ISD::SRA, SDLoc(N), VT, N0,
   2137                     DAG.getConstant(VT.getScalarSizeInBits() - 1,
   2138                                     getShiftAmountTy(N0.getValueType())));
   2139     AddToWorklist(SGN.getNode());
   2140 
   2141     // Add (N0 < 0) ? abs2 - 1 : 0;
   2142     SDValue SRL =
   2143         DAG.getNode(ISD::SRL, SDLoc(N), VT, SGN,
   2144                     DAG.getConstant(VT.getScalarSizeInBits() - lg2,
   2145                                     getShiftAmountTy(SGN.getValueType())));
   2146     SDValue ADD = DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, SRL);
   2147     AddToWorklist(SRL.getNode());
   2148     AddToWorklist(ADD.getNode());    // Divide by pow2
   2149     SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), VT, ADD,
   2150                   DAG.getConstant(lg2, getShiftAmountTy(ADD.getValueType())));
   2151 
   2152     // If we're dividing by a positive value, we're done.  Otherwise, we must
   2153     // negate the result.
   2154     if (N1C->getAPIntValue().isNonNegative())
   2155       return SRA;
   2156 
   2157     AddToWorklist(SRA.getNode());
   2158     return DAG.getNode(ISD::SUB, SDLoc(N), VT, DAG.getConstant(0, VT), SRA);
   2159   }
   2160 
   2161   // If integer divide is expensive and we satisfy the requirements, emit an
   2162   // alternate sequence.
   2163   if (N1C && !TLI.isIntDivCheap()) {
   2164     SDValue Op = BuildSDIV(N);
   2165     if (Op.getNode()) return Op;
   2166   }
   2167 
   2168   // undef / X -> 0
   2169   if (N0.getOpcode() == ISD::UNDEF)
   2170     return DAG.getConstant(0, VT);
   2171   // X / undef -> undef
   2172   if (N1.getOpcode() == ISD::UNDEF)
   2173     return N1;
   2174 
   2175   return SDValue();
   2176 }
   2177 
   2178 SDValue DAGCombiner::visitUDIV(SDNode *N) {
   2179   SDValue N0 = N->getOperand(0);
   2180   SDValue N1 = N->getOperand(1);
   2181   EVT VT = N->getValueType(0);
   2182 
   2183   // fold vector ops
   2184   if (VT.isVector())
   2185     if (SDValue FoldedVOp = SimplifyVBinOp(N))
   2186       return FoldedVOp;
   2187 
   2188   // fold (udiv c1, c2) -> c1/c2
   2189   ConstantSDNode *N0C = isConstOrConstSplat(N0);
   2190   ConstantSDNode *N1C = isConstOrConstSplat(N1);
   2191   if (N0C && N1C && !N1C->isNullValue())
   2192     return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C);
   2193   // fold (udiv x, (1 << c)) -> x >>u c
   2194   if (N1C && N1C->getAPIntValue().isPowerOf2())
   2195     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0,
   2196                        DAG.getConstant(N1C->getAPIntValue().logBase2(),
   2197                                        getShiftAmountTy(N0.getValueType())));
   2198   // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
   2199   if (N1.getOpcode() == ISD::SHL) {
   2200     if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
   2201       if (SHC->getAPIntValue().isPowerOf2()) {
   2202         EVT ADDVT = N1.getOperand(1).getValueType();
   2203         SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N), ADDVT,
   2204                                   N1.getOperand(1),
   2205                                   DAG.getConstant(SHC->getAPIntValue()
   2206                                                                   .logBase2(),
   2207                                                   ADDVT));
   2208         AddToWorklist(Add.getNode());
   2209         return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, Add);
   2210       }
   2211     }
   2212   }
   2213   // fold (udiv x, c) -> alternate
   2214   if (N1C && !TLI.isIntDivCheap()) {
   2215     SDValue Op = BuildUDIV(N);
   2216     if (Op.getNode()) return Op;
   2217   }
   2218 
   2219   // undef / X -> 0
   2220   if (N0.getOpcode() == ISD::UNDEF)
   2221     return DAG.getConstant(0, VT);
   2222   // X / undef -> undef
   2223   if (N1.getOpcode() == ISD::UNDEF)
   2224     return N1;
   2225 
   2226   return SDValue();
   2227 }
   2228 
   2229 SDValue DAGCombiner::visitSREM(SDNode *N) {
   2230   SDValue N0 = N->getOperand(0);
   2231   SDValue N1 = N->getOperand(1);
   2232   EVT VT = N->getValueType(0);
   2233 
   2234   // fold (srem c1, c2) -> c1%c2
   2235   ConstantSDNode *N0C = isConstOrConstSplat(N0);
   2236   ConstantSDNode *N1C = isConstOrConstSplat(N1);
   2237   if (N0C && N1C && !N1C->isNullValue())
   2238     return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C);
   2239   // If we know the sign bits of both operands are zero, strength reduce to a
   2240   // urem instead.  Handles (X & 0x0FFFFFFF) %s 16 -> X&15
   2241   if (!VT.isVector()) {
   2242     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
   2243       return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
   2244   }
   2245 
   2246   // If X/C can be simplified by the division-by-constant logic, lower
   2247   // X%C to the equivalent of X-X/C*C.
   2248   if (N1C && !N1C->isNullValue()) {
   2249     SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
   2250     AddToWorklist(Div.getNode());
   2251     SDValue OptimizedDiv = combine(Div.getNode());
   2252     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
   2253       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
   2254                                 OptimizedDiv, N1);
   2255       SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
   2256       AddToWorklist(Mul.getNode());
   2257       return Sub;
   2258     }
   2259   }
   2260 
   2261   // undef % X -> 0
   2262   if (N0.getOpcode() == ISD::UNDEF)
   2263     return DAG.getConstant(0, VT);
   2264   // X % undef -> undef
   2265   if (N1.getOpcode() == ISD::UNDEF)
   2266     return N1;
   2267 
   2268   return SDValue();
   2269 }
   2270 
   2271 SDValue DAGCombiner::visitUREM(SDNode *N) {
   2272   SDValue N0 = N->getOperand(0);
   2273   SDValue N1 = N->getOperand(1);
   2274   EVT VT = N->getValueType(0);
   2275 
   2276   // fold (urem c1, c2) -> c1%c2
   2277   ConstantSDNode *N0C = isConstOrConstSplat(N0);
   2278   ConstantSDNode *N1C = isConstOrConstSplat(N1);
   2279   if (N0C && N1C && !N1C->isNullValue())
   2280     return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C);
   2281   // fold (urem x, pow2) -> (and x, pow2-1)
   2282   if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
   2283     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0,
   2284                        DAG.getConstant(N1C->getAPIntValue()-1,VT));
   2285   // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
   2286   if (N1.getOpcode() == ISD::SHL) {
   2287     if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
   2288       if (SHC->getAPIntValue().isPowerOf2()) {
   2289         SDValue Add =
   2290           DAG.getNode(ISD::ADD, SDLoc(N), VT, N1,
   2291                  DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
   2292                                  VT));
   2293         AddToWorklist(Add.getNode());
   2294         return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, Add);
   2295       }
   2296     }
   2297   }
   2298 
   2299   // If X/C can be simplified by the division-by-constant logic, lower
   2300   // X%C to the equivalent of X-X/C*C.
   2301   if (N1C && !N1C->isNullValue()) {
   2302     SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
   2303     AddToWorklist(Div.getNode());
   2304     SDValue OptimizedDiv = combine(Div.getNode());
   2305     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
   2306       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
   2307                                 OptimizedDiv, N1);
   2308       SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
   2309       AddToWorklist(Mul.getNode());
   2310       return Sub;
   2311     }
   2312   }
   2313 
   2314   // undef % X -> 0
   2315   if (N0.getOpcode() == ISD::UNDEF)
   2316     return DAG.getConstant(0, VT);
   2317   // X % undef -> undef
   2318   if (N1.getOpcode() == ISD::UNDEF)
   2319     return N1;
   2320 
   2321   return SDValue();
   2322 }
   2323 
   2324 SDValue DAGCombiner::visitMULHS(SDNode *N) {
   2325   SDValue N0 = N->getOperand(0);
   2326   SDValue N1 = N->getOperand(1);
   2327   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
   2328   EVT VT = N->getValueType(0);
   2329   SDLoc DL(N);
   2330 
   2331   // fold (mulhs x, 0) -> 0
   2332   if (N1C && N1C->isNullValue())
   2333     return N1;
   2334   // fold (mulhs x, 1) -> (sra x, size(x)-1)
   2335   if (N1C && N1C->getAPIntValue() == 1)
   2336     return DAG.getNode(ISD::SRA, SDLoc(N), N0.getValueType(), N0,
   2337                        DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
   2338                                        getShiftAmountTy(N0.getValueType())));
   2339   // fold (mulhs x, undef) -> 0
   2340   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
   2341     return DAG.getConstant(0, VT);
   2342 
   2343   // If the type twice as wide is legal, transform the mulhs to a wider multiply
   2344   // plus a shift.
   2345   if (VT.isSimple() && !VT.isVector()) {
   2346     MVT Simple = VT.getSimpleVT();
   2347     unsigned SimpleSize = Simple.getSizeInBits();
   2348     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
   2349     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
   2350       N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
   2351       N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
   2352       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
   2353       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
   2354             DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
   2355       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
   2356     }
   2357   }
   2358 
   2359   return SDValue();
   2360 }
   2361 
   2362 SDValue DAGCombiner::visitMULHU(SDNode *N) {
   2363   SDValue N0 = N->getOperand(0);
   2364   SDValue N1 = N->getOperand(1);
   2365   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
   2366   EVT VT = N->getValueType(0);
   2367   SDLoc DL(N);
   2368 
   2369   // fold (mulhu x, 0) -> 0
   2370   if (N1C && N1C->isNullValue())
   2371     return N1;
   2372   // fold (mulhu x, 1) -> 0
   2373   if (N1C && N1C->getAPIntValue() == 1)
   2374     return DAG.getConstant(0, N0.getValueType());
   2375   // fold (mulhu x, undef) -> 0
   2376   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
   2377     return DAG.getConstant(0, VT);
   2378 
   2379   // If the type twice as wide is legal, transform the mulhu to a wider multiply
   2380   // plus a shift.
   2381   if (VT.isSimple() && !VT.isVector()) {
   2382     MVT Simple = VT.getSimpleVT();
   2383     unsigned SimpleSize = Simple.getSizeInBits();
   2384     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
   2385     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
   2386       N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
   2387       N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
   2388       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
   2389       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
   2390             DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
   2391       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
   2392     }
   2393   }
   2394 
   2395   return SDValue();
   2396 }
   2397 
   2398 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp
   2399 /// give the opcodes for the two computations that are being performed. Return
   2400 /// true if a simplification was made.
   2401 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
   2402                                                 unsigned HiOp) {
   2403   // If the high half is not needed, just compute the low half.
   2404   bool HiExists = N->hasAnyUseOfValue(1);
   2405   if (!HiExists &&
   2406       (!LegalOperations ||
   2407        TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
   2408     SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
   2409     return CombineTo(N, Res, Res);
   2410   }
   2411 
   2412   // If the low half is not needed, just compute the high half.
   2413   bool LoExists = N->hasAnyUseOfValue(0);
   2414   if (!LoExists &&
   2415       (!LegalOperations ||
   2416        TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
   2417     SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
   2418     return CombineTo(N, Res, Res);
   2419   }
   2420 
   2421   // If both halves are used, return as it is.
   2422   if (LoExists && HiExists)
   2423     return SDValue();
   2424 
   2425   // If the two computed results can be simplified separately, separate them.
   2426   if (LoExists) {
   2427     SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
   2428     AddToWorklist(Lo.getNode());
   2429     SDValue LoOpt = combine(Lo.getNode());
   2430     if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
   2431         (!LegalOperations ||
   2432          TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
   2433       return CombineTo(N, LoOpt, LoOpt);
   2434   }
   2435 
   2436   if (HiExists) {
   2437     SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
   2438     AddToWorklist(Hi.getNode());
   2439     SDValue HiOpt = combine(Hi.getNode());
   2440     if (HiOpt.getNode() && HiOpt != Hi &&
   2441         (!LegalOperations ||
   2442          TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
   2443       return CombineTo(N, HiOpt, HiOpt);
   2444   }
   2445 
   2446   return SDValue();
   2447 }
   2448 
   2449 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
   2450   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
   2451   if (Res.getNode()) return Res;
   2452 
   2453   EVT VT = N->getValueType(0);
   2454   SDLoc DL(N);
   2455 
   2456   // If the type is twice as wide is legal, transform the mulhu to a wider
   2457   // multiply plus a shift.
   2458   if (VT.isSimple() && !VT.isVector()) {
   2459     MVT Simple = VT.getSimpleVT();
   2460     unsigned SimpleSize = Simple.getSizeInBits();
   2461     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
   2462     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
   2463       SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
   2464       SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
   2465       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
   2466       // Compute the high part as N1.
   2467       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
   2468             DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
   2469       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
   2470       // Compute the low part as N0.
   2471       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
   2472       return CombineTo(N, Lo, Hi);
   2473     }
   2474   }
   2475 
   2476   return SDValue();
   2477 }
   2478 
   2479 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
   2480   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
   2481   if (Res.getNode()) return Res;
   2482 
   2483   EVT VT = N->getValueType(0);
   2484   SDLoc DL(N);
   2485 
   2486   // If the type is twice as wide is legal, transform the mulhu to a wider
   2487   // multiply plus a shift.
   2488   if (VT.isSimple() && !VT.isVector()) {
   2489     MVT Simple = VT.getSimpleVT();
   2490     unsigned SimpleSize = Simple.getSizeInBits();
   2491     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
   2492     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
   2493       SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
   2494       SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
   2495       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
   2496       // Compute the high part as N1.
   2497       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
   2498             DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
   2499       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
   2500       // Compute the low part as N0.
   2501       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
   2502       return CombineTo(N, Lo, Hi);
   2503     }
   2504   }
   2505 
   2506   return SDValue();
   2507 }
   2508 
   2509 SDValue DAGCombiner::visitSMULO(SDNode *N) {
   2510   // (smulo x, 2) -> (saddo x, x)
   2511   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
   2512     if (C2->getAPIntValue() == 2)
   2513       return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
   2514                          N->getOperand(0), N->getOperand(0));
   2515 
   2516   return SDValue();
   2517 }
   2518 
   2519 SDValue DAGCombiner::visitUMULO(SDNode *N) {
   2520   // (umulo x, 2) -> (uaddo x, x)
   2521   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
   2522     if (C2->getAPIntValue() == 2)
   2523       return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
   2524                          N->getOperand(0), N->getOperand(0));
   2525 
   2526   return SDValue();
   2527 }
   2528 
   2529 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
   2530   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
   2531   if (Res.getNode()) return Res;
   2532 
   2533   return SDValue();
   2534 }
   2535 
   2536 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
   2537   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
   2538   if (Res.getNode()) return Res;
   2539 
   2540   return SDValue();
   2541 }
   2542 
   2543 /// If this is a binary operator with two operands of the same opcode, try to
   2544 /// simplify it.
   2545 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
   2546   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
   2547   EVT VT = N0.getValueType();
   2548   assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
   2549 
   2550   // Bail early if none of these transforms apply.
   2551   if (N0.getNode()->getNumOperands() == 0) return SDValue();
   2552 
   2553   // For each of OP in AND/OR/XOR:
   2554   // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
   2555   // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
   2556   // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
   2557   // fold (OP (bswap x), (bswap y)) -> (bswap (OP x, y))
   2558   // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
   2559   //
   2560   // do not sink logical op inside of a vector extend, since it may combine
   2561   // into a vsetcc.
   2562   EVT Op0VT = N0.getOperand(0).getValueType();
   2563   if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
   2564        N0.getOpcode() == ISD::SIGN_EXTEND ||
   2565        N0.getOpcode() == ISD::BSWAP ||
   2566        // Avoid infinite looping with PromoteIntBinOp.
   2567        (N0.getOpcode() == ISD::ANY_EXTEND &&
   2568         (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
   2569        (N0.getOpcode() == ISD::TRUNCATE &&
   2570         (!TLI.isZExtFree(VT, Op0VT) ||
   2571          !TLI.isTruncateFree(Op0VT, VT)) &&
   2572         TLI.isTypeLegal(Op0VT))) &&
   2573       !VT.isVector() &&
   2574       Op0VT == N1.getOperand(0).getValueType() &&
   2575       (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
   2576     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
   2577                                  N0.getOperand(0).getValueType(),
   2578                                  N0.getOperand(0), N1.getOperand(0));
   2579     AddToWorklist(ORNode.getNode());
   2580     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
   2581   }
   2582 
   2583   // For each of OP in SHL/SRL/SRA/AND...
   2584   //   fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
   2585   //   fold (or  (OP x, z), (OP y, z)) -> (OP (or  x, y), z)
   2586   //   fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
   2587   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
   2588        N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
   2589       N0.getOperand(1) == N1.getOperand(1)) {
   2590     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
   2591                                  N0.getOperand(0).getValueType(),
   2592                                  N0.getOperand(0), N1.getOperand(0));
   2593     AddToWorklist(ORNode.getNode());
   2594     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
   2595                        ORNode, N0.getOperand(1));
   2596   }
   2597 
   2598   // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
   2599   // Only perform this optimization after type legalization and before
   2600   // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
   2601   // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
   2602   // we don't want to undo this promotion.
   2603   // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
   2604   // on scalars.
   2605   if ((N0.getOpcode() == ISD::BITCAST ||
   2606        N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
   2607       Level == AfterLegalizeTypes) {
   2608     SDValue In0 = N0.getOperand(0);
   2609     SDValue In1 = N1.getOperand(0);
   2610     EVT In0Ty = In0.getValueType();
   2611     EVT In1Ty = In1.getValueType();
   2612     SDLoc DL(N);
   2613     // If both incoming values are integers, and the original types are the
   2614     // same.
   2615     if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
   2616       SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
   2617       SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
   2618       AddToWorklist(Op.getNode());
   2619       return BC;
   2620     }
   2621   }
   2622 
   2623   // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
   2624   // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
   2625   // If both shuffles use the same mask, and both shuffle within a single
   2626   // vector, then it is worthwhile to move the swizzle after the operation.
   2627   // The type-legalizer generates this pattern when loading illegal
   2628   // vector types from memory. In many cases this allows additional shuffle
   2629   // optimizations.
   2630   // There are other cases where moving the shuffle after the xor/and/or
   2631   // is profitable even if shuffles don't perform a swizzle.
   2632   // If both shuffles use the same mask, and both shuffles have the same first
   2633   // or second operand, then it might still be profitable to move the shuffle
   2634   // after the xor/and/or operation.
   2635   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
   2636     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
   2637     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
   2638 
   2639     assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
   2640            "Inputs to shuffles are not the same type");
   2641 
   2642     // Check that both shuffles use the same mask. The masks are known to be of
   2643     // the same length because the result vector type is the same.
   2644     // Check also that shuffles have only one use to avoid introducing extra
   2645     // instructions.
   2646     if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
   2647         SVN0->getMask().equals(SVN1->getMask())) {
   2648       SDValue ShOp = N0->getOperand(1);
   2649 
   2650       // Don't try to fold this node if it requires introducing a
   2651       // build vector of all zeros that might be illegal at this stage.
   2652       if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
   2653         if (!LegalTypes)
   2654           ShOp = DAG.getConstant(0, VT);
   2655         else
   2656           ShOp = SDValue();
   2657       }
   2658 
   2659       // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
   2660       // (OR  (shuf (A, C), shuf (B, C)) -> shuf (OR  (A, B), C)
   2661       // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
   2662       if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
   2663         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
   2664                                       N0->getOperand(0), N1->getOperand(0));
   2665         AddToWorklist(NewNode.getNode());
   2666         return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
   2667                                     &SVN0->getMask()[0]);
   2668       }
   2669 
   2670       // Don't try to fold this node if it requires introducing a
   2671       // build vector of all zeros that might be illegal at this stage.
   2672       ShOp = N0->getOperand(0);
   2673       if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
   2674         if (!LegalTypes)
   2675           ShOp = DAG.getConstant(0, VT);
   2676         else
   2677           ShOp = SDValue();
   2678       }
   2679 
   2680       // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
   2681       // (OR  (shuf (C, A), shuf (C, B)) -> shuf (C, OR  (A, B))
   2682       // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
   2683       if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
   2684         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
   2685                                       N0->getOperand(1), N1->getOperand(1));
   2686         AddToWorklist(NewNode.getNode());
   2687         return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
   2688                                     &SVN0->getMask()[0]);
   2689       }
   2690     }
   2691   }
   2692 
   2693   return SDValue();
   2694 }
   2695 
   2696 /// This contains all DAGCombine rules which reduce two values combined by
   2697 /// an And operation to a single value. This makes them reusable in the context
   2698 /// of visitSELECT(). Rules involving constants are not included as
   2699 /// visitSELECT() already handles those cases.
   2700 SDValue DAGCombiner::visitANDLike(SDValue N0, SDValue N1,
   2701                                   SDNode *LocReference) {
   2702   EVT VT = N1.getValueType();
   2703 
   2704   // fold (and x, undef) -> 0
   2705   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
   2706     return DAG.getConstant(0, VT);
   2707   // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
   2708   SDValue LL, LR, RL, RR, CC0, CC1;
   2709   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
   2710     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
   2711     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
   2712 
   2713     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
   2714         LL.getValueType().isInteger()) {
   2715       // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
   2716       if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
   2717         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
   2718                                      LR.getValueType(), LL, RL);
   2719         AddToWorklist(ORNode.getNode());
   2720         return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
   2721       }
   2722       // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
   2723       if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
   2724         SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
   2725                                       LR.getValueType(), LL, RL);
   2726         AddToWorklist(ANDNode.getNode());
   2727         return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
   2728       }
   2729       // fold (and (setgt X,  -1), (setgt Y,  -1)) -> (setgt (or X, Y), -1)
   2730       if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
   2731         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
   2732                                      LR.getValueType(), LL, RL);
   2733         AddToWorklist(ORNode.getNode());
   2734         return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
   2735       }
   2736     }
   2737     // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
   2738     if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
   2739         Op0 == Op1 && LL.getValueType().isInteger() &&
   2740       Op0 == ISD::SETNE && ((cast<ConstantSDNode>(LR)->isNullValue() &&
   2741                                  cast<ConstantSDNode>(RR)->isAllOnesValue()) ||
   2742                                 (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
   2743                                  cast<ConstantSDNode>(RR)->isNullValue()))) {
   2744       SDValue ADDNode = DAG.getNode(ISD::ADD, SDLoc(N0), LL.getValueType(),
   2745                                     LL, DAG.getConstant(1, LL.getValueType()));
   2746       AddToWorklist(ADDNode.getNode());
   2747       return DAG.getSetCC(SDLoc(LocReference), VT, ADDNode,
   2748                           DAG.getConstant(2, LL.getValueType()), ISD::SETUGE);
   2749     }
   2750     // canonicalize equivalent to ll == rl
   2751     if (LL == RR && LR == RL) {
   2752       Op1 = ISD::getSetCCSwappedOperands(Op1);
   2753       std::swap(RL, RR);
   2754     }
   2755     if (LL == RL && LR == RR) {
   2756       bool isInteger = LL.getValueType().isInteger();
   2757       ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
   2758       if (Result != ISD::SETCC_INVALID &&
   2759           (!LegalOperations ||
   2760            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
   2761             TLI.isOperationLegal(ISD::SETCC,
   2762                             getSetCCResultType(N0.getSimpleValueType())))))
   2763         return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
   2764                             LL, LR, Result);
   2765     }
   2766   }
   2767 
   2768   if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
   2769       VT.getSizeInBits() <= 64) {
   2770     if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
   2771       APInt ADDC = ADDI->getAPIntValue();
   2772       if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
   2773         // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
   2774         // immediate for an add, but it is legal if its top c2 bits are set,
   2775         // transform the ADD so the immediate doesn't need to be materialized
   2776         // in a register.
   2777         if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
   2778           APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
   2779                                              SRLI->getZExtValue());
   2780           if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
   2781             ADDC |= Mask;
   2782             if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
   2783               SDValue NewAdd =
   2784                 DAG.getNode(ISD::ADD, SDLoc(N0), VT,
   2785                             N0.getOperand(0), DAG.getConstant(ADDC, VT));
   2786               CombineTo(N0.getNode(), NewAdd);
   2787               // Return N so it doesn't get rechecked!
   2788               return SDValue(LocReference, 0);
   2789             }
   2790           }
   2791         }
   2792       }
   2793     }
   2794   }
   2795 
   2796   return SDValue();
   2797 }
   2798 
   2799 SDValue DAGCombiner::visitAND(SDNode *N) {
   2800   SDValue N0 = N->getOperand(0);
   2801   SDValue N1 = N->getOperand(1);
   2802   EVT VT = N1.getValueType();
   2803 
   2804   // fold vector ops
   2805   if (VT.isVector()) {
   2806     if (SDValue FoldedVOp = SimplifyVBinOp(N))
   2807       return FoldedVOp;
   2808 
   2809     // fold (and x, 0) -> 0, vector edition
   2810     if (ISD::isBuildVectorAllZeros(N0.getNode()))
   2811       // do not return N0, because undef node may exist in N0
   2812       return DAG.getConstant(
   2813           APInt::getNullValue(
   2814               N0.getValueType().getScalarType().getSizeInBits()),
   2815           N0.getValueType());
   2816     if (ISD::isBuildVectorAllZeros(N1.getNode()))
   2817       // do not return N1, because undef node may exist in N1
   2818       return DAG.getConstant(
   2819           APInt::getNullValue(
   2820               N1.getValueType().getScalarType().getSizeInBits()),
   2821           N1.getValueType());
   2822 
   2823     // fold (and x, -1) -> x, vector edition
   2824     if (ISD::isBuildVectorAllOnes(N0.getNode()))
   2825       return N1;
   2826     if (ISD::isBuildVectorAllOnes(N1.getNode()))
   2827       return N0;
   2828   }
   2829 
   2830   // fold (and c1, c2) -> c1&c2
   2831   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
   2832   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
   2833   if (N0C && N1C)
   2834     return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C);
   2835   // canonicalize constant to RHS
   2836   if (isConstantIntBuildVectorOrConstantInt(N0) &&
   2837      !isConstantIntBuildVectorOrConstantInt(N1))
   2838     return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
   2839   // fold (and x, -1) -> x
   2840   if (N1C && N1C->isAllOnesValue())
   2841     return N0;
   2842   // if (and x, c) is known to be zero, return 0
   2843   unsigned BitWidth = VT.getScalarType().getSizeInBits();
   2844   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
   2845                                    APInt::getAllOnesValue(BitWidth)))
   2846     return DAG.getConstant(0, VT);
   2847   // reassociate and
   2848   if (SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1))
   2849     return RAND;
   2850   // fold (and (or x, C), D) -> D if (C & D) == D
   2851   if (N1C && N0.getOpcode() == ISD::OR)
   2852     if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
   2853       if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
   2854         return N1;
   2855   // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
   2856   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
   2857     SDValue N0Op0 = N0.getOperand(0);
   2858     APInt Mask = ~N1C->getAPIntValue();
   2859     Mask = Mask.trunc(N0Op0.getValueSizeInBits());
   2860     if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
   2861       SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
   2862                                  N0.getValueType(), N0Op0);
   2863 
   2864       // Replace uses of the AND with uses of the Zero extend node.
   2865       CombineTo(N, Zext);
   2866 
   2867       // We actually want to replace all uses of the any_extend with the
   2868       // zero_extend, to avoid duplicating things.  This will later cause this
   2869       // AND to be folded.
   2870       CombineTo(N0.getNode(), Zext);
   2871       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
   2872     }
   2873   }
   2874   // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
   2875   // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
   2876   // already be zero by virtue of the width of the base type of the load.
   2877   //
   2878   // the 'X' node here can either be nothing or an extract_vector_elt to catch
   2879   // more cases.
   2880   if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
   2881        N0.getOperand(0).getOpcode() == ISD::LOAD) ||
   2882       N0.getOpcode() == ISD::LOAD) {
   2883     LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
   2884                                          N0 : N0.getOperand(0) );
   2885 
   2886     // Get the constant (if applicable) the zero'th operand is being ANDed with.
   2887     // This can be a pure constant or a vector splat, in which case we treat the
   2888     // vector as a scalar and use the splat value.
   2889     APInt Constant = APInt::getNullValue(1);
   2890     if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
   2891       Constant = C->getAPIntValue();
   2892     } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
   2893       APInt SplatValue, SplatUndef;
   2894       unsigned SplatBitSize;
   2895       bool HasAnyUndefs;
   2896       bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
   2897                                              SplatBitSize, HasAnyUndefs);
   2898       if (IsSplat) {
   2899         // Undef bits can contribute to a possible optimisation if set, so
   2900         // set them.
   2901         SplatValue |= SplatUndef;
   2902 
   2903         // The splat value may be something like "0x00FFFFFF", which means 0 for
   2904         // the first vector value and FF for the rest, repeating. We need a mask
   2905         // that will apply equally to all members of the vector, so AND all the
   2906         // lanes of the constant together.
   2907         EVT VT = Vector->getValueType(0);
   2908         unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
   2909 
   2910         // If the splat value has been compressed to a bitlength lower
   2911         // than the size of the vector lane, we need to re-expand it to
   2912         // the lane size.
   2913         if (BitWidth > SplatBitSize)
   2914           for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
   2915                SplatBitSize < BitWidth;
   2916                SplatBitSize = SplatBitSize * 2)
   2917             SplatValue |= SplatValue.shl(SplatBitSize);
   2918 
   2919         // Make sure that variable 'Constant' is only set if 'SplatBitSize' is a
   2920         // multiple of 'BitWidth'. Otherwise, we could propagate a wrong value.
   2921         if (SplatBitSize % BitWidth == 0) {
   2922           Constant = APInt::getAllOnesValue(BitWidth);
   2923           for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
   2924             Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
   2925         }
   2926       }
   2927     }
   2928 
   2929     // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
   2930     // actually legal and isn't going to get expanded, else this is a false
   2931     // optimisation.
   2932     bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
   2933                                                     Load->getValueType(0),
   2934                                                     Load->getMemoryVT());
   2935 
   2936     // Resize the constant to the same size as the original memory access before
   2937     // extension. If it is still the AllOnesValue then this AND is completely
   2938     // unneeded.
   2939     Constant =
   2940       Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
   2941 
   2942     bool B;
   2943     switch (Load->getExtensionType()) {
   2944     default: B = false; break;
   2945     case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
   2946     case ISD::ZEXTLOAD:
   2947     case ISD::NON_EXTLOAD: B = true; break;
   2948     }
   2949 
   2950     if (B && Constant.isAllOnesValue()) {
   2951       // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
   2952       // preserve semantics once we get rid of the AND.
   2953       SDValue NewLoad(Load, 0);
   2954       if (Load->getExtensionType() == ISD::EXTLOAD) {
   2955         NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
   2956                               Load->getValueType(0), SDLoc(Load),
   2957                               Load->getChain(), Load->getBasePtr(),
   2958                               Load->getOffset(), Load->getMemoryVT(),
   2959                               Load->getMemOperand());
   2960         // Replace uses of the EXTLOAD with the new ZEXTLOAD.
   2961         if (Load->getNumValues() == 3) {
   2962           // PRE/POST_INC loads have 3 values.
   2963           SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
   2964                            NewLoad.getValue(2) };
   2965           CombineTo(Load, To, 3, true);
   2966         } else {
   2967           CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
   2968         }
   2969       }
   2970 
   2971       // Fold the AND away, taking care not to fold to the old load node if we
   2972       // replaced it.
   2973       CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
   2974 
   2975       return SDValue(N, 0); // Return N so it doesn't get rechecked!
   2976     }
   2977   }
   2978 
   2979   // fold (and (load x), 255) -> (zextload x, i8)
   2980   // fold (and (extload x, i16), 255) -> (zextload x, i8)
   2981   // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
   2982   if (N1C && (N0.getOpcode() == ISD::LOAD ||
   2983               (N0.getOpcode() == ISD::ANY_EXTEND &&
   2984                N0.getOperand(0).getOpcode() == ISD::LOAD))) {
   2985     bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
   2986     LoadSDNode *LN0 = HasAnyExt
   2987       ? cast<LoadSDNode>(N0.getOperand(0))
   2988       : cast<LoadSDNode>(N0);
   2989     if (LN0->getExtensionType() != ISD::SEXTLOAD &&
   2990         LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
   2991       uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
   2992       if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
   2993         EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
   2994         EVT LoadedVT = LN0->getMemoryVT();
   2995         EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
   2996 
   2997         if (ExtVT == LoadedVT &&
   2998             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy,
   2999                                                     ExtVT))) {
   3000 
   3001           SDValue NewLoad =
   3002             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
   3003                            LN0->getChain(), LN0->getBasePtr(), ExtVT,
   3004                            LN0->getMemOperand());
   3005           AddToWorklist(N);
   3006           CombineTo(LN0, NewLoad, NewLoad.getValue(1));
   3007           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
   3008         }
   3009 
   3010         // Do not change the width of a volatile load.
   3011         // Do not generate loads of non-round integer types since these can
   3012         // be expensive (and would be wrong if the type is not byte sized).
   3013         if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
   3014             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy,
   3015                                                     ExtVT))) {
   3016           EVT PtrType = LN0->getOperand(1).getValueType();
   3017 
   3018           unsigned Alignment = LN0->getAlignment();
   3019           SDValue NewPtr = LN0->getBasePtr();
   3020 
   3021           // For big endian targets, we need to add an offset to the pointer
   3022           // to load the correct bytes.  For little endian systems, we merely
   3023           // need to read fewer bytes from the same pointer.
   3024           if (TLI.isBigEndian()) {
   3025             unsigned LVTStoreBytes = LoadedVT.getStoreSize();
   3026             unsigned EVTStoreBytes = ExtVT.getStoreSize();
   3027             unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
   3028             NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0), PtrType,
   3029                                  NewPtr, DAG.getConstant(PtrOff, PtrType));
   3030             Alignment = MinAlign(Alignment, PtrOff);
   3031           }
   3032 
   3033           AddToWorklist(NewPtr.getNode());
   3034 
   3035           SDValue Load =
   3036             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
   3037                            LN0->getChain(), NewPtr,
   3038                            LN0->getPointerInfo(),
   3039                            ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
   3040                            LN0->isInvariant(), Alignment, LN0->getAAInfo());
   3041           AddToWorklist(N);
   3042           CombineTo(LN0, Load, Load.getValue(1));
   3043           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
   3044         }
   3045       }
   3046     }
   3047   }
   3048 
   3049   if (SDValue Combined = visitANDLike(N0, N1, N))
   3050     return Combined;
   3051 
   3052   // Simplify: (and (op x...), (op y...))  -> (op (and x, y))
   3053   if (N0.getOpcode() == N1.getOpcode()) {
   3054     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
   3055     if (Tmp.getNode()) return Tmp;
   3056   }
   3057 
   3058   // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
   3059   // fold (and (sra)) -> (and (srl)) when possible.
   3060   if (!VT.isVector() &&
   3061       SimplifyDemandedBits(SDValue(N, 0)))
   3062     return SDValue(N, 0);
   3063 
   3064   // fold (zext_inreg (extload x)) -> (zextload x)
   3065   if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
   3066     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
   3067     EVT MemVT = LN0->getMemoryVT();
   3068     // If we zero all the possible extended bits, then we can turn this into
   3069     // a zextload if we are running before legalize or the operation is legal.
   3070     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
   3071     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
   3072                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
   3073         ((!LegalOperations && !LN0->isVolatile()) ||
   3074          TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
   3075       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
   3076                                        LN0->getChain(), LN0->getBasePtr(),
   3077                                        MemVT, LN0->getMemOperand());
   3078       AddToWorklist(N);
   3079       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
   3080       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
   3081     }
   3082   }
   3083   // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
   3084   if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
   3085       N0.hasOneUse()) {
   3086     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
   3087     EVT MemVT = LN0->getMemoryVT();
   3088     // If we zero all the possible extended bits, then we can turn this into
   3089     // a zextload if we are running before legalize or the operation is legal.
   3090     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
   3091     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
   3092                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
   3093         ((!LegalOperations && !LN0->isVolatile()) ||
   3094          TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
   3095       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
   3096                                        LN0->getChain(), LN0->getBasePtr(),
   3097                                        MemVT, LN0->getMemOperand());
   3098       AddToWorklist(N);
   3099       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
   3100       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
   3101     }
   3102   }
   3103   // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
   3104   if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
   3105     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
   3106                                        N0.getOperand(1), false);
   3107     if (BSwap.getNode())
   3108       return BSwap;
   3109   }
   3110 
   3111   return SDValue();
   3112 }
   3113 
   3114 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16.
   3115 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
   3116                                         bool DemandHighBits) {
   3117   if (!LegalOperations)
   3118     return SDValue();
   3119 
   3120   EVT VT = N->getValueType(0);
   3121   if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
   3122     return SDValue();
   3123   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
   3124     return SDValue();
   3125 
   3126   // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
   3127   bool LookPassAnd0 = false;
   3128   bool LookPassAnd1 = false;
   3129   if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
   3130       std::swap(N0, N1);
   3131   if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
   3132       std::swap(N0, N1);
   3133   if (N0.getOpcode() == ISD::AND) {
   3134     if (!N0.getNode()->hasOneUse())
   3135       return SDValue();
   3136     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
   3137     if (!N01C || N01C->getZExtValue() != 0xFF00)
   3138       return SDValue();
   3139     N0 = N0.getOperand(0);
   3140     LookPassAnd0 = true;
   3141   }
   3142 
   3143   if (N1.getOpcode() == ISD::AND) {
   3144     if (!N1.getNode()->hasOneUse())
   3145       return SDValue();
   3146     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
   3147     if (!N11C || N11C->getZExtValue() != 0xFF)
   3148       return SDValue();
   3149     N1 = N1.getOperand(0);
   3150     LookPassAnd1 = true;
   3151   }
   3152 
   3153   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
   3154     std::swap(N0, N1);
   3155   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
   3156     return SDValue();
   3157   if (!N0.getNode()->hasOneUse() ||
   3158       !N1.getNode()->hasOneUse())
   3159     return SDValue();
   3160 
   3161   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
   3162   ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
   3163   if (!N01C || !N11C)
   3164     return SDValue();
   3165   if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
   3166     return SDValue();
   3167 
   3168   // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
   3169   SDValue N00 = N0->getOperand(0);
   3170   if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
   3171     if (!N00.getNode()->hasOneUse())
   3172       return SDValue();
   3173     ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
   3174     if (!N001C || N001C->getZExtValue() != 0xFF)
   3175       return SDValue();
   3176     N00 = N00.getOperand(0);
   3177     LookPassAnd0 = true;
   3178   }
   3179 
   3180   SDValue N10 = N1->getOperand(0);
   3181   if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
   3182     if (!N10.getNode()->hasOneUse())
   3183       return SDValue();
   3184     ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
   3185     if (!N101C || N101C->getZExtValue() != 0xFF00)
   3186       return SDValue();
   3187     N10 = N10.getOperand(0);
   3188     LookPassAnd1 = true;
   3189   }
   3190 
   3191   if (N00 != N10)
   3192     return SDValue();
   3193 
   3194   // Make sure everything beyond the low halfword gets set to zero since the SRL
   3195   // 16 will clear the top bits.
   3196   unsigned OpSizeInBits = VT.getSizeInBits();
   3197   if (DemandHighBits && OpSizeInBits > 16) {
   3198     // If the left-shift isn't masked out then the only way this is a bswap is
   3199     // if all bits beyond the low 8 are 0. In that case the entire pattern
   3200     // reduces to a left shift anyway: leave it for other parts of the combiner.
   3201     if (!LookPassAnd0)
   3202       return SDValue();
   3203 
   3204     // However, if the right shift isn't masked out then it might be because
   3205     // it's not needed. See if we can spot that too.
   3206     if (!LookPassAnd1 &&
   3207         !DAG.MaskedValueIsZero(
   3208             N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
   3209       return SDValue();
   3210   }
   3211 
   3212   SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
   3213   if (OpSizeInBits > 16)
   3214     Res = DAG.getNode(ISD::SRL, SDLoc(N), VT, Res,
   3215                       DAG.getConstant(OpSizeInBits-16, getShiftAmountTy(VT)));
   3216   return Res;
   3217 }
   3218 
   3219 /// Return true if the specified node is an element that makes up a 32-bit
   3220 /// packed halfword byteswap.
   3221 /// ((x & 0x000000ff) << 8) |
   3222 /// ((x & 0x0000ff00) >> 8) |
   3223 /// ((x & 0x00ff0000) << 8) |
   3224 /// ((x & 0xff000000) >> 8)
   3225 static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) {
   3226   if (!N.getNode()->hasOneUse())
   3227     return false;
   3228 
   3229   unsigned Opc = N.getOpcode();
   3230   if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
   3231     return false;
   3232 
   3233   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
   3234   if (!N1C)
   3235     return false;
   3236 
   3237   unsigned Num;
   3238   switch (N1C->getZExtValue()) {
   3239   default:
   3240     return false;
   3241   case 0xFF:       Num = 0; break;
   3242   case 0xFF00:     Num = 1; break;
   3243   case 0xFF0000:   Num = 2; break;
   3244   case 0xFF000000: Num = 3; break;
   3245   }
   3246 
   3247   // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
   3248   SDValue N0 = N.getOperand(0);
   3249   if (Opc == ISD::AND) {
   3250     if (Num == 0 || Num == 2) {
   3251       // (x >> 8) & 0xff
   3252       // (x >> 8) & 0xff0000
   3253       if (N0.getOpcode() != ISD::SRL)
   3254         return false;
   3255       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
   3256       if (!C || C->getZExtValue() != 8)
   3257         return false;
   3258     } else {
   3259       // (x << 8) & 0xff00
   3260       // (x << 8) & 0xff000000
   3261       if (N0.getOpcode() != ISD::SHL)
   3262         return false;
   3263       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
   3264       if (!C || C->getZExtValue() != 8)
   3265         return false;
   3266     }
   3267   } else if (Opc == ISD::SHL) {
   3268     // (x & 0xff) << 8
   3269     // (x & 0xff0000) << 8
   3270     if (Num != 0 && Num != 2)
   3271       return false;
   3272     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
   3273     if (!C || C->getZExtValue() != 8)
   3274       return false;
   3275   } else { // Opc == ISD::SRL
   3276     // (x & 0xff00) >> 8
   3277     // (x & 0xff000000) >> 8
   3278     if (Num != 1 && Num != 3)
   3279       return false;
   3280     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
   3281     if (!C || C->getZExtValue() != 8)
   3282       return false;
   3283   }
   3284 
   3285   if (Parts[Num])
   3286     return false;
   3287 
   3288   Parts[Num] = N0.getOperand(0).getNode();
   3289   return true;
   3290 }
   3291 
   3292 /// Match a 32-bit packed halfword bswap. That is
   3293 /// ((x & 0x000000ff) << 8) |
   3294 /// ((x & 0x0000ff00) >> 8) |
   3295 /// ((x & 0x00ff0000) << 8) |
   3296 /// ((x & 0xff000000) >> 8)
   3297 /// => (rotl (bswap x), 16)
   3298 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
   3299   if (!LegalOperations)
   3300     return SDValue();
   3301 
   3302   EVT VT = N->getValueType(0);
   3303   if (VT != MVT::i32)
   3304     return SDValue();
   3305   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
   3306     return SDValue();
   3307 
   3308   // Look for either
   3309   // (or (or (and), (and)), (or (and), (and)))
   3310   // (or (or (or (and), (and)), (and)), (and))
   3311   if (N0.getOpcode() != ISD::OR)
   3312     return SDValue();
   3313   SDValue N00 = N0.getOperand(0);
   3314   SDValue N01 = N0.getOperand(1);
   3315   SDNode *Parts[4] = {};
   3316 
   3317   if (N1.getOpcode() == ISD::OR &&
   3318       N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
   3319     // (or (or (and), (and)), (or (and), (and)))
   3320     SDValue N000 = N00.getOperand(0);
   3321     if (!isBSwapHWordElement(N000, Parts))
   3322       return SDValue();
   3323 
   3324     SDValue N001 = N00.getOperand(1);
   3325     if (!isBSwapHWordElement(N001, Parts))
   3326       return SDValue();
   3327     SDValue N010 = N01.getOperand(0);
   3328     if (!isBSwapHWordElement(N010, Parts))
   3329       return SDValue();
   3330     SDValue N011 = N01.getOperand(1);
   3331     if (!isBSwapHWordElement(N011, Parts))
   3332       return SDValue();
   3333   } else {
   3334     // (or (or (or (and), (and)), (and)), (and))
   3335     if (!isBSwapHWordElement(N1, Parts))
   3336       return SDValue();
   3337     if (!isBSwapHWordElement(N01, Parts))
   3338       return SDValue();
   3339     if (N00.getOpcode() != ISD::OR)
   3340       return SDValue();
   3341     SDValue N000 = N00.getOperand(0);
   3342     if (!isBSwapHWordElement(N000, Parts))
   3343       return SDValue();
   3344     SDValue N001 = N00.getOperand(1);
   3345     if (!isBSwapHWordElement(N001, Parts))
   3346       return SDValue();
   3347   }
   3348 
   3349   // Make sure the parts are all coming from the same node.
   3350   if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
   3351     return SDValue();
   3352 
   3353   SDValue BSwap = DAG.getNode(ISD::BSWAP, SDLoc(N), VT,
   3354                               SDValue(Parts[0],0));
   3355 
   3356   // Result of the bswap should be rotated by 16. If it's not legal, then
   3357   // do  (x << 16) | (x >> 16).
   3358   SDValue ShAmt = DAG.getConstant(16, getShiftAmountTy(VT));
   3359   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
   3360     return DAG.getNode(ISD::ROTL, SDLoc(N), VT, BSwap, ShAmt);
   3361   if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
   3362     return DAG.getNode(ISD::ROTR, SDLoc(N), VT, BSwap, ShAmt);
   3363   return DAG.getNode(ISD::OR, SDLoc(N), VT,
   3364                      DAG.getNode(ISD::SHL, SDLoc(N), VT, BSwap, ShAmt),
   3365                      DAG.getNode(ISD::SRL, SDLoc(N), VT, BSwap, ShAmt));
   3366 }
   3367 
   3368 /// This contains all DAGCombine rules which reduce two values combined by
   3369 /// an Or operation to a single value \see visitANDLike().
   3370 SDValue DAGCombiner::visitORLike(SDValue N0, SDValue N1, SDNode *LocReference) {
   3371   EVT VT = N1.getValueType();
   3372   // fold (or x, undef) -> -1
   3373   if (!LegalOperations &&
   3374       (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
   3375     EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
   3376     return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
   3377   }
   3378   // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
   3379   SDValue LL, LR, RL, RR, CC0, CC1;
   3380   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
   3381     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
   3382     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
   3383 
   3384     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
   3385         LL.getValueType().isInteger()) {
   3386       // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
   3387       // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
   3388       if (cast<ConstantSDNode>(LR)->isNullValue() &&
   3389           (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
   3390         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
   3391                                      LR.getValueType(), LL, RL);
   3392         AddToWorklist(ORNode.getNode());
   3393         return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
   3394       }
   3395       // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
   3396       // fold (or (setgt X, -1), (setgt Y  -1)) -> (setgt (and X, Y), -1)
   3397       if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
   3398           (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
   3399         SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
   3400                                       LR.getValueType(), LL, RL);
   3401         AddToWorklist(ANDNode.getNode());
   3402         return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
   3403       }
   3404     }
   3405     // canonicalize equivalent to ll == rl
   3406     if (LL == RR && LR == RL) {
   3407       Op1 = ISD::getSetCCSwappedOperands(Op1);
   3408       std::swap(RL, RR);
   3409     }
   3410     if (LL == RL && LR == RR) {
   3411       bool isInteger = LL.getValueType().isInteger();
   3412       ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
   3413       if (Result != ISD::SETCC_INVALID &&
   3414           (!LegalOperations ||
   3415            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
   3416             TLI.isOperationLegal(ISD::SETCC,
   3417               getSetCCResultType(N0.getValueType())))))
   3418         return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
   3419                             LL, LR, Result);
   3420     }
   3421   }
   3422 
   3423   // (or (and X, C1), (and Y, C2))  -> (and (or X, Y), C3) if possible.
   3424   if (N0.getOpcode() == ISD::AND &&
   3425       N1.getOpcode() == ISD::AND &&
   3426       N0.getOperand(1).getOpcode() == ISD::Constant &&
   3427       N1.getOperand(1).getOpcode() == ISD::Constant &&
   3428       // Don't increase # computations.
   3429       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
   3430     // We can only do this xform if we know that bits from X that are set in C2
   3431     // but not in C1 are already zero.  Likewise for Y.
   3432     const APInt &LHSMask =
   3433       cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
   3434     const APInt &RHSMask =
   3435       cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
   3436 
   3437     if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
   3438         DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
   3439       SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
   3440                               N0.getOperand(0), N1.getOperand(0));
   3441       return DAG.getNode(ISD::AND, SDLoc(LocReference), VT, X,
   3442                          DAG.getConstant(LHSMask | RHSMask, VT));
   3443     }
   3444   }
   3445 
   3446   // (or (and X, M), (and X, N)) -> (and X, (or M, N))
   3447   if (N0.getOpcode() == ISD::AND &&
   3448       N1.getOpcode() == ISD::AND &&
   3449       N0.getOperand(0) == N1.getOperand(0) &&
   3450       // Don't increase # computations.
   3451       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
   3452     SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
   3453                             N0.getOperand(1), N1.getOperand(1));
   3454     return DAG.getNode(ISD::AND, SDLoc(LocReference), VT, N0.getOperand(0), X);
   3455   }
   3456 
   3457   return SDValue();
   3458 }
   3459 
   3460 SDValue DAGCombiner::visitOR(SDNode *N) {
   3461   SDValue N0 = N->getOperand(0);
   3462   SDValue N1 = N->getOperand(1);
   3463   EVT VT = N1.getValueType();
   3464 
   3465   // fold vector ops
   3466   if (VT.isVector()) {
   3467     if (SDValue FoldedVOp = SimplifyVBinOp(N))
   3468       return FoldedVOp;
   3469 
   3470     // fold (or x, 0) -> x, vector edition
   3471     if (ISD::isBuildVectorAllZeros(N0.getNode()))
   3472       return N1;
   3473     if (ISD::isBuildVectorAllZeros(N1.getNode()))
   3474       return N0;
   3475 
   3476     // fold (or x, -1) -> -1, vector edition
   3477     if (ISD::isBuildVectorAllOnes(N0.getNode()))
   3478       // do not return N0, because undef node may exist in N0
   3479       return DAG.getConstant(
   3480           APInt::getAllOnesValue(
   3481               N0.getValueType().getScalarType().getSizeInBits()),
   3482           N0.getValueType());
   3483     if (ISD::isBuildVectorAllOnes(N1.getNode()))
   3484       // do not return N1, because undef node may exist in N1
   3485       return DAG.getConstant(
   3486           APInt::getAllOnesValue(
   3487               N1.getValueType().getScalarType().getSizeInBits()),
   3488           N1.getValueType());
   3489 
   3490     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
   3491     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
   3492     // Do this only if the resulting shuffle is legal.
   3493     if (isa<ShuffleVectorSDNode>(N0) &&
   3494         isa<ShuffleVectorSDNode>(N1) &&
   3495         // Avoid folding a node with illegal type.
   3496         TLI.isTypeLegal(VT) &&
   3497         N0->getOperand(1) == N1->getOperand(1) &&
   3498         ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
   3499       bool CanFold = true;
   3500       unsigned NumElts = VT.getVectorNumElements();
   3501       const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
   3502       const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
   3503       // We construct two shuffle masks:
   3504       // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
   3505       // and N1 as the second operand.
   3506       // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
   3507       // and N0 as the second operand.
   3508       // We do this because OR is commutable and therefore there might be
   3509       // two ways to fold this node into a shuffle.
   3510       SmallVector<int,4> Mask1;
   3511       SmallVector<int,4> Mask2;
   3512 
   3513       for (unsigned i = 0; i != NumElts && CanFold; ++i) {
   3514         int M0 = SV0->getMaskElt(i);
   3515         int M1 = SV1->getMaskElt(i);
   3516 
   3517         // Both shuffle indexes are undef. Propagate Undef.
   3518         if (M0 < 0 && M1 < 0) {
   3519           Mask1.push_back(M0);
   3520           Mask2.push_back(M0);
   3521           continue;
   3522         }
   3523 
   3524         if (M0 < 0 || M1 < 0 ||
   3525             (M0 < (int)NumElts && M1 < (int)NumElts) ||
   3526             (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
   3527           CanFold = false;
   3528           break;
   3529         }
   3530 
   3531         Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
   3532         Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
   3533       }
   3534 
   3535       if (CanFold) {
   3536         // Fold this sequence only if the resulting shuffle is 'legal'.
   3537         if (TLI.isShuffleMaskLegal(Mask1, VT))
   3538           return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
   3539                                       N1->getOperand(0), &Mask1[0]);
   3540         if (TLI.isShuffleMaskLegal(Mask2, VT))
   3541           return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
   3542                                       N0->getOperand(0), &Mask2[0]);
   3543       }
   3544     }
   3545   }
   3546 
   3547   // fold (or c1, c2) -> c1|c2
   3548   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
   3549   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
   3550   if (N0C && N1C)
   3551     return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C);
   3552   // canonicalize constant to RHS
   3553   if (isConstantIntBuildVectorOrConstantInt(N0) &&
   3554      !isConstantIntBuildVectorOrConstantInt(N1))
   3555     return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
   3556   // fold (or x, 0) -> x
   3557   if (N1C && N1C->isNullValue())
   3558     return N0;
   3559   // fold (or x, -1) -> -1
   3560   if (N1C && N1C->isAllOnesValue())
   3561     return N1;
   3562   // fold (or x, c) -> c iff (x & ~c) == 0
   3563   if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
   3564     return N1;
   3565 
   3566   if (SDValue Combined = visitORLike(N0, N1, N))
   3567     return Combined;
   3568 
   3569   // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
   3570   SDValue BSwap = MatchBSwapHWord(N, N0, N1);
   3571   if (BSwap.getNode())
   3572     return BSwap;
   3573   BSwap = MatchBSwapHWordLow(N, N0, N1);
   3574   if (BSwap.getNode())
   3575     return BSwap;
   3576 
   3577   // reassociate or
   3578   if (SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1))
   3579     return ROR;
   3580   // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
   3581   // iff (c1 & c2) == 0.
   3582   if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
   3583              isa<ConstantSDNode>(N0.getOperand(1))) {
   3584     ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
   3585     if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
   3586       if (SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1))
   3587         return DAG.getNode(
   3588             ISD::AND, SDLoc(N), VT,
   3589             DAG.getNode(ISD::OR, SDLoc(N0), VT, N0.getOperand(0), N1), COR);
   3590       return SDValue();
   3591     }
   3592   }
   3593   // Simplify: (or (op x...), (op y...))  -> (op (or x, y))
   3594   if (N0.getOpcode() == N1.getOpcode()) {
   3595     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
   3596     if (Tmp.getNode()) return Tmp;
   3597   }
   3598 
   3599   // See if this is some rotate idiom.
   3600   if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
   3601     return SDValue(Rot, 0);
   3602 
   3603   // Simplify the operands using demanded-bits information.
   3604   if (!VT.isVector() &&
   3605       SimplifyDemandedBits(SDValue(N, 0)))
   3606     return SDValue(N, 0);
   3607 
   3608   return SDValue();
   3609 }
   3610 
   3611 /// Match "(X shl/srl V1) & V2" where V2 may not be present.
   3612 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
   3613   if (Op.getOpcode() == ISD::AND) {
   3614     if (isa<ConstantSDNode>(Op.getOperand(1))) {
   3615       Mask = Op.getOperand(1);
   3616       Op = Op.getOperand(0);
   3617     } else {
   3618       return false;
   3619     }
   3620   }
   3621 
   3622   if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
   3623     Shift = Op;
   3624     return true;
   3625   }
   3626 
   3627   return false;
   3628 }
   3629 
   3630 // Return true if we can prove that, whenever Neg and Pos are both in the
   3631 // range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos).  This means that
   3632 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
   3633 //
   3634 //     (or (shift1 X, Neg), (shift2 X, Pos))
   3635 //
   3636 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
   3637 // in direction shift1 by Neg.  The range [0, OpSize) means that we only need
   3638 // to consider shift amounts with defined behavior.
   3639 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) {
   3640   // If OpSize is a power of 2 then:
   3641   //
   3642   //  (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1)
   3643   //  (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize).
   3644   //
   3645   // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check
   3646   // for the stronger condition:
   3647   //
   3648   //     Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1)    [A]
   3649   //
   3650   // for all Neg and Pos.  Since Neg & (OpSize - 1) == Neg' & (OpSize - 1)
   3651   // we can just replace Neg with Neg' for the rest of the function.
   3652   //
   3653   // In other cases we check for the even stronger condition:
   3654   //
   3655   //     Neg == OpSize - Pos                                    [B]
   3656   //
   3657   // for all Neg and Pos.  Note that the (or ...) then invokes undefined
   3658   // behavior if Pos == 0 (and consequently Neg == OpSize).
   3659   //
   3660   // We could actually use [A] whenever OpSize is a power of 2, but the
   3661   // only extra cases that it would match are those uninteresting ones
   3662   // where Neg and Pos are never in range at the same time.  E.g. for
   3663   // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
   3664   // as well as (sub 32, Pos), but:
   3665   //
   3666   //     (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
   3667   //
   3668   // always invokes undefined behavior for 32-bit X.
   3669   //
   3670   // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise.
   3671   unsigned MaskLoBits = 0;
   3672   if (Neg.getOpcode() == ISD::AND &&
   3673       isPowerOf2_64(OpSize) &&
   3674       Neg.getOperand(1).getOpcode() == ISD::Constant &&
   3675       cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) {
   3676     Neg = Neg.getOperand(0);
   3677     MaskLoBits = Log2_64(OpSize);
   3678   }
   3679 
   3680   // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
   3681   if (Neg.getOpcode() != ISD::SUB)
   3682     return 0;
   3683   ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0));
   3684   if (!NegC)
   3685     return 0;
   3686   SDValue NegOp1 = Neg.getOperand(1);
   3687 
   3688   // On the RHS of [A], if Pos is Pos' & (OpSize - 1), just replace Pos with
   3689   // Pos'.  The truncation is redundant for the purpose of the equality.
   3690   if (MaskLoBits &&
   3691       Pos.getOpcode() == ISD::AND &&
   3692       Pos.getOperand(1).getOpcode() == ISD::Constant &&
   3693       cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() == OpSize - 1)
   3694     Pos = Pos.getOperand(0);
   3695 
   3696   // The condition we need is now:
   3697   //
   3698   //     (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask
   3699   //
   3700   // If NegOp1 == Pos then we need:
   3701   //
   3702   //              OpSize & Mask == NegC & Mask
   3703   //
   3704   // (because "x & Mask" is a truncation and distributes through subtraction).
   3705   APInt Width;
   3706   if (Pos == NegOp1)
   3707     Width = NegC->getAPIntValue();
   3708   // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
   3709   // Then the condition we want to prove becomes:
   3710   //
   3711   //     (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask
   3712   //
   3713   // which, again because "x & Mask" is a truncation, becomes:
   3714   //
   3715   //                NegC & Mask == (OpSize - PosC) & Mask
   3716   //              OpSize & Mask == (NegC + PosC) & Mask
   3717   else if (Pos.getOpcode() == ISD::ADD &&
   3718            Pos.getOperand(0) == NegOp1 &&
   3719            Pos.getOperand(1).getOpcode() == ISD::Constant)
   3720     Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() +
   3721              NegC->getAPIntValue());
   3722   else
   3723     return false;
   3724 
   3725   // Now we just need to check that OpSize & Mask == Width & Mask.
   3726   if (MaskLoBits)
   3727     // Opsize & Mask is 0 since Mask is Opsize - 1.
   3728     return Width.getLoBits(MaskLoBits) == 0;
   3729   return Width == OpSize;
   3730 }
   3731 
   3732 // A subroutine of MatchRotate used once we have found an OR of two opposite
   3733 // shifts of Shifted.  If Neg == <operand size> - Pos then the OR reduces
   3734 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
   3735 // former being preferred if supported.  InnerPos and InnerNeg are Pos and
   3736 // Neg with outer conversions stripped away.
   3737 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
   3738                                        SDValue Neg, SDValue InnerPos,
   3739                                        SDValue InnerNeg, unsigned PosOpcode,
   3740                                        unsigned NegOpcode, SDLoc DL) {
   3741   // fold (or (shl x, (*ext y)),
   3742   //          (srl x, (*ext (sub 32, y)))) ->
   3743   //   (rotl x, y) or (rotr x, (sub 32, y))
   3744   //
   3745   // fold (or (shl x, (*ext (sub 32, y))),
   3746   //          (srl x, (*ext y))) ->
   3747   //   (rotr x, y) or (rotl x, (sub 32, y))
   3748   EVT VT = Shifted.getValueType();
   3749   if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) {
   3750     bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
   3751     return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
   3752                        HasPos ? Pos : Neg).getNode();
   3753   }
   3754 
   3755   return nullptr;
   3756 }
   3757 
   3758 // MatchRotate - Handle an 'or' of two operands.  If this is one of the many
   3759 // idioms for rotate, and if the target supports rotation instructions, generate
   3760 // a rot[lr].
   3761 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
   3762   // Must be a legal type.  Expanded 'n promoted things won't work with rotates.
   3763   EVT VT = LHS.getValueType();
   3764   if (!TLI.isTypeLegal(VT)) return nullptr;
   3765 
   3766   // The target must have at least one rotate flavor.
   3767   bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
   3768   bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
   3769   if (!HasROTL && !HasROTR) return nullptr;
   3770 
   3771   // Match "(X shl/srl V1) & V2" where V2 may not be present.
   3772   SDValue LHSShift;   // The shift.
   3773   SDValue LHSMask;    // AND value if any.
   3774   if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
   3775     return nullptr; // Not part of a rotate.
   3776 
   3777   SDValue RHSShift;   // The shift.
   3778   SDValue RHSMask;    // AND value if any.
   3779   if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
   3780     return nullptr; // Not part of a rotate.
   3781 
   3782   if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
   3783     return nullptr;   // Not shifting the same value.
   3784 
   3785   if (LHSShift.getOpcode() == RHSShift.getOpcode())
   3786     return nullptr;   // Shifts must disagree.
   3787 
   3788   // Canonicalize shl to left side in a shl/srl pair.
   3789   if (RHSShift.getOpcode() == ISD::SHL) {
   3790     std::swap(LHS, RHS);
   3791     std::swap(LHSShift, RHSShift);
   3792     std::swap(LHSMask , RHSMask );
   3793   }
   3794 
   3795   unsigned OpSizeInBits = VT.getSizeInBits();
   3796   SDValue LHSShiftArg = LHSShift.getOperand(0);
   3797   SDValue LHSShiftAmt = LHSShift.getOperand(1);
   3798   SDValue RHSShiftArg = RHSShift.getOperand(0);
   3799   SDValue RHSShiftAmt = RHSShift.getOperand(1);
   3800 
   3801   // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
   3802   // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
   3803   if (LHSShiftAmt.getOpcode() == ISD::Constant &&
   3804       RHSShiftAmt.getOpcode() == ISD::Constant) {
   3805     uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
   3806     uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
   3807     if ((LShVal + RShVal) != OpSizeInBits)
   3808       return nullptr;
   3809 
   3810     SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
   3811                               LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
   3812 
   3813     // If there is an AND of either shifted operand, apply it to the result.
   3814     if (LHSMask.getNode() || RHSMask.getNode()) {
   3815       APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
   3816 
   3817       if (LHSMask.getNode()) {
   3818         APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
   3819         Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
   3820       }
   3821       if (RHSMask.getNode()) {
   3822         APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
   3823         Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
   3824       }
   3825 
   3826       Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT));
   3827     }
   3828 
   3829     return Rot.getNode();
   3830   }
   3831 
   3832   // If there is a mask here, and we have a variable shift, we can't be sure
   3833   // that we're masking out the right stuff.
   3834   if (LHSMask.getNode() || RHSMask.getNode())
   3835     return nullptr;
   3836 
   3837   // If the shift amount is sign/zext/any-extended just peel it off.
   3838   SDValue LExtOp0 = LHSShiftAmt;
   3839   SDValue RExtOp0 = RHSShiftAmt;
   3840   if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
   3841        LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
   3842        LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
   3843        LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
   3844       (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
   3845        RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
   3846        RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
   3847        RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
   3848     LExtOp0 = LHSShiftAmt.getOperand(0);
   3849     RExtOp0 = RHSShiftAmt.getOperand(0);
   3850   }
   3851 
   3852   SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
   3853                                    LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
   3854   if (TryL)
   3855     return TryL;
   3856 
   3857   SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
   3858                                    RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
   3859   if (TryR)
   3860     return TryR;
   3861 
   3862   return nullptr;
   3863 }
   3864 
   3865 SDValue DAGCombiner::visitXOR(SDNode *N) {
   3866   SDValue N0 = N->getOperand(0);
   3867   SDValue N1 = N->getOperand(1);
   3868   EVT VT = N0.getValueType();
   3869 
   3870   // fold vector ops
   3871   if (VT.isVector()) {
   3872     if (SDValue FoldedVOp = SimplifyVBinOp(N))
   3873       return FoldedVOp;
   3874 
   3875     // fold (xor x, 0) -> x, vector edition
   3876     if (ISD::isBuildVectorAllZeros(N0.getNode()))
   3877       return N1;
   3878     if (ISD::isBuildVectorAllZeros(N1.getNode()))
   3879       return N0;
   3880   }
   3881 
   3882   // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
   3883   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
   3884     return DAG.getConstant(0, VT);
   3885   // fold (xor x, undef) -> undef
   3886   if (N0.getOpcode() == ISD::UNDEF)
   3887     return N0;
   3888   if (N1.getOpcode() == ISD::UNDEF)
   3889     return N1;
   3890   // fold (xor c1, c2) -> c1^c2
   3891   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
   3892   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
   3893   if (N0C && N1C)
   3894     return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
   3895   // canonicalize constant to RHS
   3896   if (isConstantIntBuildVectorOrConstantInt(N0) &&
   3897      !isConstantIntBuildVectorOrConstantInt(N1))
   3898     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
   3899   // fold (xor x, 0) -> x
   3900   if (N1C && N1C->isNullValue())
   3901     return N0;
   3902   // reassociate xor
   3903   if (SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1))
   3904     return RXOR;
   3905 
   3906   // fold !(x cc y) -> (x !cc y)
   3907   SDValue LHS, RHS, CC;
   3908   if (TLI.isConstTrueVal(N1.getNode()) && isSetCCEquivalent(N0, LHS, RHS, CC)) {
   3909     bool isInt = LHS.getValueType().isInteger();
   3910     ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
   3911                                                isInt);
   3912 
   3913     if (!LegalOperations ||
   3914         TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
   3915       switch (N0.getOpcode()) {
   3916       default:
   3917         llvm_unreachable("Unhandled SetCC Equivalent!");
   3918       case ISD::SETCC:
   3919         return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
   3920       case ISD::SELECT_CC:
   3921         return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
   3922                                N0.getOperand(3), NotCC);
   3923       }
   3924     }
   3925   }
   3926 
   3927   // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
   3928   if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
   3929       N0.getNode()->hasOneUse() &&
   3930       isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
   3931     SDValue V = N0.getOperand(0);
   3932     V = DAG.getNode(ISD::XOR, SDLoc(N0), V.getValueType(), V,
   3933                     DAG.getConstant(1, V.getValueType()));
   3934     AddToWorklist(V.getNode());
   3935     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
   3936   }
   3937 
   3938   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
   3939   if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
   3940       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
   3941     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
   3942     if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
   3943       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
   3944       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
   3945       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
   3946       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
   3947       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
   3948     }
   3949   }
   3950   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
   3951   if (N1C && N1C->isAllOnesValue() &&
   3952       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
   3953     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
   3954     if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
   3955       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
   3956       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
   3957       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
   3958       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
   3959       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
   3960     }
   3961   }
   3962   // fold (xor (and x, y), y) -> (and (not x), y)
   3963   if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
   3964       N0->getOperand(1) == N1) {
   3965     SDValue X = N0->getOperand(0);
   3966     SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
   3967     AddToWorklist(NotX.getNode());
   3968     return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
   3969   }
   3970   // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
   3971   if (N1C && N0.getOpcode() == ISD::XOR) {
   3972     ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
   3973     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
   3974     if (N00C)
   3975       return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(1),
   3976                          DAG.getConstant(N1C->getAPIntValue() ^
   3977                                          N00C->getAPIntValue(), VT));
   3978     if (N01C)
   3979       return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(0),
   3980                          DAG.getConstant(N1C->getAPIntValue() ^
   3981                                          N01C->getAPIntValue(), VT));
   3982   }
   3983   // fold (xor x, x) -> 0
   3984   if (N0 == N1)
   3985     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
   3986 
   3987   // fold (xor (shl 1, x), -1) -> (rotl ~1, x)
   3988   // Here is a concrete example of this equivalence:
   3989   // i16   x ==  14
   3990   // i16 shl ==   1 << 14  == 16384 == 0b0100000000000000
   3991   // i16 xor == ~(1 << 14) == 49151 == 0b1011111111111111
   3992   //
   3993   // =>
   3994   //
   3995   // i16     ~1      == 0b1111111111111110
   3996   // i16 rol(~1, 14) == 0b1011111111111111
   3997   //
   3998   // Some additional tips to help conceptualize this transform:
   3999   // - Try to see the operation as placing a single zero in a value of all ones.
   4000   // - There exists no value for x which would allow the result to contain zero.
   4001   // - Values of x larger than the bitwidth are undefined and do not require a
   4002   //   consistent result.
   4003   // - Pushing the zero left requires shifting one bits in from the right.
   4004   // A rotate left of ~1 is a nice way of achieving the desired result.
   4005   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
   4006     if (auto *N1C = dyn_cast<ConstantSDNode>(N1.getNode()))
   4007       if (N0.getOpcode() == ISD::SHL)
   4008         if (auto *ShlLHS = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
   4009           if (N1C->isAllOnesValue() && ShlLHS->isOne())
   4010             return DAG.getNode(ISD::ROTL, SDLoc(N), VT, DAG.getConstant(~1, VT),
   4011                                N0.getOperand(1));
   4012 
   4013   // Simplify: xor (op x...), (op y...)  -> (op (xor x, y))
   4014   if (N0.getOpcode() == N1.getOpcode()) {
   4015     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
   4016     if (Tmp.getNode()) return Tmp;
   4017   }
   4018 
   4019   // Simplify the expression using non-local knowledge.
   4020   if (!VT.isVector() &&
   4021       SimplifyDemandedBits(SDValue(N, 0)))
   4022     return SDValue(N, 0);
   4023 
   4024   return SDValue();
   4025 }
   4026 
   4027 /// Handle transforms common to the three shifts, when the shift amount is a
   4028 /// constant.
   4029 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
   4030   // We can't and shouldn't fold opaque constants.
   4031   if (Amt->isOpaque())
   4032     return SDValue();
   4033 
   4034   SDNode *LHS = N->getOperand(0).getNode();
   4035   if (!LHS->hasOneUse()) return SDValue();
   4036 
   4037   // We want to pull some binops through shifts, so that we have (and (shift))
   4038   // instead of (shift (and)), likewise for add, or, xor, etc.  This sort of
   4039   // thing happens with address calculations, so it's important to canonicalize
   4040   // it.
   4041   bool HighBitSet = false;  // Can we transform this if the high bit is set?
   4042 
   4043   switch (LHS->getOpcode()) {
   4044   default: return SDValue();
   4045   case ISD::OR:
   4046   case ISD::XOR:
   4047     HighBitSet = false; // We can only transform sra if the high bit is clear.
   4048     break;
   4049   case ISD::AND:
   4050     HighBitSet = true;  // We can only transform sra if the high bit is set.
   4051     break;
   4052   case ISD::ADD:
   4053     if (N->getOpcode() != ISD::SHL)
   4054       return SDValue(); // only shl(add) not sr[al](add).
   4055     HighBitSet = false; // We can only transform sra if the high bit is clear.
   4056     break;
   4057   }
   4058 
   4059   // We require the RHS of the binop to be a constant and not opaque as well.
   4060   ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
   4061   if (!BinOpCst || BinOpCst->isOpaque()) return SDValue();
   4062 
   4063   // FIXME: disable this unless the input to the binop is a shift by a constant.
   4064   // If it is not a shift, it pessimizes some common cases like:
   4065   //
   4066   //    void foo(int *X, int i) { X[i & 1235] = 1; }
   4067   //    int bar(int *X, int i) { return X[i & 255]; }
   4068   SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
   4069   if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
   4070        BinOpLHSVal->getOpcode() != ISD::SRA &&
   4071        BinOpLHSVal->getOpcode() != ISD::SRL) ||
   4072       !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
   4073     return SDValue();
   4074 
   4075   EVT VT = N->getValueType(0);
   4076 
   4077   // If this is a signed shift right, and the high bit is modified by the
   4078   // logical operation, do not perform the transformation. The highBitSet
   4079   // boolean indicates the value of the high bit of the constant which would
   4080   // cause it to be modified for this operation.
   4081   if (N->getOpcode() == ISD::SRA) {
   4082     bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
   4083     if (BinOpRHSSignSet != HighBitSet)
   4084       return SDValue();
   4085   }
   4086 
   4087   if (!TLI.isDesirableToCommuteWithShift(LHS))
   4088     return SDValue();
   4089 
   4090   // Fold the constants, shifting the binop RHS by the shift amount.
   4091   SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
   4092                                N->getValueType(0),
   4093                                LHS->getOperand(1), N->getOperand(1));
   4094   assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
   4095 
   4096   // Create the new shift.
   4097   SDValue NewShift = DAG.getNode(N->getOpcode(),
   4098                                  SDLoc(LHS->getOperand(0)),
   4099                                  VT, LHS->getOperand(0), N->getOperand(1));
   4100 
   4101   // Create the new binop.
   4102   return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
   4103 }
   4104 
   4105 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
   4106   assert(N->getOpcode() == ISD::TRUNCATE);
   4107   assert(N->getOperand(0).getOpcode() == ISD::AND);
   4108 
   4109   // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
   4110   if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
   4111     SDValue N01 = N->getOperand(0).getOperand(1);
   4112 
   4113     if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
   4114       EVT TruncVT = N->getValueType(0);
   4115       SDValue N00 = N->getOperand(0).getOperand(0);
   4116       APInt TruncC = N01C->getAPIntValue();
   4117       TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
   4118 
   4119       return DAG.getNode(ISD::AND, SDLoc(N), TruncVT,
   4120                          DAG.getNode(ISD::TRUNCATE, SDLoc(N), TruncVT, N00),
   4121                          DAG.getConstant(TruncC, TruncVT));
   4122     }
   4123   }
   4124 
   4125   return SDValue();
   4126 }
   4127 
   4128 SDValue DAGCombiner::visitRotate(SDNode *N) {
   4129   // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
   4130   if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
   4131       N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
   4132     SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode());
   4133     if (NewOp1.getNode())
   4134       return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
   4135                          N->getOperand(0), NewOp1);
   4136   }
   4137   return SDValue();
   4138 }
   4139 
   4140 SDValue DAGCombiner::visitSHL(SDNode *N) {
   4141   SDValue N0 = N->getOperand(0);
   4142   SDValue N1 = N->getOperand(1);
   4143   EVT VT = N0.getValueType();
   4144   unsigned OpSizeInBits = VT.getScalarSizeInBits();
   4145 
   4146   // fold vector ops
   4147   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
   4148   if (VT.isVector()) {
   4149     if (SDValue FoldedVOp = SimplifyVBinOp(N))
   4150       return FoldedVOp;
   4151 
   4152     BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
   4153     // If setcc produces all-one true value then:
   4154     // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
   4155     if (N1CV && N1CV->isConstant()) {
   4156       if (N0.getOpcode() == ISD::AND) {
   4157         SDValue N00 = N0->getOperand(0);
   4158         SDValue N01 = N0->getOperand(1);
   4159         BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
   4160 
   4161         if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
   4162             TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
   4163                 TargetLowering::ZeroOrNegativeOneBooleanContent) {
   4164           if (SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, VT, N01CV, N1CV))
   4165             return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
   4166         }
   4167       } else {
   4168         N1C = isConstOrConstSplat(N1);
   4169       }
   4170     }
   4171   }
   4172 
   4173   // fold (shl c1, c2) -> c1<<c2
   4174   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
   4175   if (N0C && N1C)
   4176     return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
   4177   // fold (shl 0, x) -> 0
   4178   if (N0C && N0C->isNullValue())
   4179     return N0;
   4180   // fold (shl x, c >= size(x)) -> undef
   4181   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
   4182     return DAG.getUNDEF(VT);
   4183   // fold (shl x, 0) -> x
   4184   if (N1C && N1C->isNullValue())
   4185     return N0;
   4186   // fold (shl undef, x) -> 0
   4187   if (N0.getOpcode() == ISD::UNDEF)
   4188     return DAG.getConstant(0, VT);
   4189   // if (shl x, c) is known to be zero, return 0
   4190   if (DAG.MaskedValueIsZero(SDValue(N, 0),
   4191                             APInt::getAllOnesValue(OpSizeInBits)))
   4192     return DAG.getConstant(0, VT);
   4193   // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
   4194   if (N1.getOpcode() == ISD::TRUNCATE &&
   4195       N1.getOperand(0).getOpcode() == ISD::AND) {
   4196     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
   4197     if (NewOp1.getNode())
   4198       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
   4199   }
   4200 
   4201   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
   4202     return SDValue(N, 0);
   4203 
   4204   // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
   4205   if (N1C && N0.getOpcode() == ISD::SHL) {
   4206     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
   4207       uint64_t c1 = N0C1->getZExtValue();
   4208       uint64_t c2 = N1C->getZExtValue();
   4209       if (c1 + c2 >= OpSizeInBits)
   4210         return DAG.getConstant(0, VT);
   4211       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
   4212                          DAG.getConstant(c1 + c2, N1.getValueType()));
   4213     }
   4214   }
   4215 
   4216   // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
   4217   // For this to be valid, the second form must not preserve any of the bits
   4218   // that are shifted out by the inner shift in the first form.  This means
   4219   // the outer shift size must be >= the number of bits added by the ext.
   4220   // As a corollary, we don't care what kind of ext it is.
   4221   if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
   4222               N0.getOpcode() == ISD::ANY_EXTEND ||
   4223               N0.getOpcode() == ISD::SIGN_EXTEND) &&
   4224       N0.getOperand(0).getOpcode() == ISD::SHL) {
   4225     SDValue N0Op0 = N0.getOperand(0);
   4226     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
   4227       uint64_t c1 = N0Op0C1->getZExtValue();
   4228       uint64_t c2 = N1C->getZExtValue();
   4229       EVT InnerShiftVT = N0Op0.getValueType();
   4230       uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
   4231       if (c2 >= OpSizeInBits - InnerShiftSize) {
   4232         if (c1 + c2 >= OpSizeInBits)
   4233           return DAG.getConstant(0, VT);
   4234         return DAG.getNode(ISD::SHL, SDLoc(N0), VT,
   4235                            DAG.getNode(N0.getOpcode(), SDLoc(N0), VT,
   4236                                        N0Op0->getOperand(0)),
   4237                            DAG.getConstant(c1 + c2, N1.getValueType()));
   4238       }
   4239     }
   4240   }
   4241 
   4242   // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
   4243   // Only fold this if the inner zext has no other uses to avoid increasing
   4244   // the total number of instructions.
   4245   if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
   4246       N0.getOperand(0).getOpcode() == ISD::SRL) {
   4247     SDValue N0Op0 = N0.getOperand(0);
   4248     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
   4249       uint64_t c1 = N0Op0C1->getZExtValue();
   4250       if (c1 < VT.getScalarSizeInBits()) {
   4251         uint64_t c2 = N1C->getZExtValue();
   4252         if (c1 == c2) {
   4253           SDValue NewOp0 = N0.getOperand(0);
   4254           EVT CountVT = NewOp0.getOperand(1).getValueType();
   4255           SDValue NewSHL = DAG.getNode(ISD::SHL, SDLoc(N), NewOp0.getValueType(),
   4256                                        NewOp0, DAG.getConstant(c2, CountVT));
   4257           AddToWorklist(NewSHL.getNode());
   4258           return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
   4259         }
   4260       }
   4261     }
   4262   }
   4263 
   4264   // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
   4265   //                               (and (srl x, (sub c1, c2), MASK)
   4266   // Only fold this if the inner shift has no other uses -- if it does, folding
   4267   // this will increase the total number of instructions.
   4268   if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
   4269     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
   4270       uint64_t c1 = N0C1->getZExtValue();
   4271       if (c1 < OpSizeInBits) {
   4272         uint64_t c2 = N1C->getZExtValue();
   4273         APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
   4274         SDValue Shift;
   4275         if (c2 > c1) {
   4276           Mask = Mask.shl(c2 - c1);
   4277           Shift = DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
   4278                               DAG.getConstant(c2 - c1, N1.getValueType()));
   4279         } else {
   4280           Mask = Mask.lshr(c1 - c2);
   4281           Shift = DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
   4282                               DAG.getConstant(c1 - c2, N1.getValueType()));
   4283         }
   4284         return DAG.getNode(ISD::AND, SDLoc(N0), VT, Shift,
   4285                            DAG.getConstant(Mask, VT));
   4286       }
   4287     }
   4288   }
   4289   // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
   4290   if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
   4291     unsigned BitSize = VT.getScalarSizeInBits();
   4292     SDValue HiBitsMask =
   4293       DAG.getConstant(APInt::getHighBitsSet(BitSize,
   4294                                             BitSize - N1C->getZExtValue()), VT);
   4295     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
   4296                        HiBitsMask);
   4297   }
   4298 
   4299   // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
   4300   // Variant of version done on multiply, except mul by a power of 2 is turned
   4301   // into a shift.
   4302   APInt Val;
   4303   if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
   4304       (isa<ConstantSDNode>(N0.getOperand(1)) ||
   4305        isConstantSplatVector(N0.getOperand(1).getNode(), Val))) {
   4306     SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1);
   4307     SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
   4308     return DAG.getNode(ISD::ADD, SDLoc(N), VT, Shl0, Shl1);
   4309   }
   4310 
   4311   if (N1C) {
   4312     SDValue NewSHL = visitShiftByConstant(N, N1C);
   4313     if (NewSHL.getNode())
   4314       return NewSHL;
   4315   }
   4316 
   4317   return SDValue();
   4318 }
   4319 
   4320 SDValue DAGCombiner::visitSRA(SDNode *N) {
   4321   SDValue N0 = N->getOperand(0);
   4322   SDValue N1 = N->getOperand(1);
   4323   EVT VT = N0.getValueType();
   4324   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
   4325 
   4326   // fold vector ops
   4327   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
   4328   if (VT.isVector()) {
   4329     if (SDValue FoldedVOp = SimplifyVBinOp(N))
   4330       return FoldedVOp;
   4331 
   4332     N1C = isConstOrConstSplat(N1);
   4333   }
   4334 
   4335   // fold (sra c1, c2) -> (sra c1, c2)
   4336   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
   4337   if (N0C && N1C)
   4338     return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
   4339   // fold (sra 0, x) -> 0
   4340   if (N0C && N0C->isNullValue())
   4341     return N0;
   4342   // fold (sra -1, x) -> -1
   4343   if (N0C && N0C->isAllOnesValue())
   4344     return N0;
   4345   // fold (sra x, (setge c, size(x))) -> undef
   4346   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
   4347     return DAG.getUNDEF(VT);
   4348   // fold (sra x, 0) -> x
   4349   if (N1C && N1C->isNullValue())
   4350     return N0;
   4351   // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
   4352   // sext_inreg.
   4353   if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
   4354     unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
   4355     EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
   4356     if (VT.isVector())
   4357       ExtVT = EVT::getVectorVT(*DAG.getContext(),
   4358                                ExtVT, VT.getVectorNumElements());
   4359     if ((!LegalOperations ||
   4360          TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
   4361       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
   4362                          N0.getOperand(0), DAG.getValueType(ExtVT));
   4363   }
   4364 
   4365   // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
   4366   if (N1C && N0.getOpcode() == ISD::SRA) {
   4367     if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
   4368       unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
   4369       if (Sum >= OpSizeInBits)
   4370         Sum = OpSizeInBits - 1;
   4371       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0.getOperand(0),
   4372                          DAG.getConstant(Sum, N1.getValueType()));
   4373     }
   4374   }
   4375 
   4376   // fold (sra (shl X, m), (sub result_size, n))
   4377   // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
   4378   // result_size - n != m.
   4379   // If truncate is free for the target sext(shl) is likely to result in better
   4380   // code.
   4381   if (N0.getOpcode() == ISD::SHL && N1C) {
   4382     // Get the two constanst of the shifts, CN0 = m, CN = n.
   4383     const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
   4384     if (N01C) {
   4385       LLVMContext &Ctx = *DAG.getContext();
   4386       // Determine what the truncate's result bitsize and type would be.
   4387       EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
   4388 
   4389       if (VT.isVector())
   4390         TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
   4391 
   4392       // Determine the residual right-shift amount.
   4393       signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
   4394 
   4395       // If the shift is not a no-op (in which case this should be just a sign
   4396       // extend already), the truncated to type is legal, sign_extend is legal
   4397       // on that type, and the truncate to that type is both legal and free,
   4398       // perform the transform.
   4399       if ((ShiftAmt > 0) &&
   4400           TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
   4401           TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
   4402           TLI.isTruncateFree(VT, TruncVT)) {
   4403 
   4404           SDValue Amt = DAG.getConstant(ShiftAmt,
   4405               getShiftAmountTy(N0.getOperand(0).getValueType()));
   4406           SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), VT,
   4407                                       N0.getOperand(0), Amt);
   4408           SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), TruncVT,
   4409                                       Shift);
   4410           return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N),
   4411                              N->getValueType(0), Trunc);
   4412       }
   4413     }
   4414   }
   4415 
   4416   // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
   4417   if (N1.getOpcode() == ISD::TRUNCATE &&
   4418       N1.getOperand(0).getOpcode() == ISD::AND) {
   4419     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
   4420     if (NewOp1.getNode())
   4421       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
   4422   }
   4423 
   4424   // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
   4425   //      if c1 is equal to the number of bits the trunc removes
   4426   if (N0.getOpcode() == ISD::TRUNCATE &&
   4427       (N0.getOperand(0).getOpcode() == ISD::SRL ||
   4428        N0.getOperand(0).getOpcode() == ISD::SRA) &&
   4429       N0.getOperand(0).hasOneUse() &&
   4430       N0.getOperand(0).getOperand(1).hasOneUse() &&
   4431       N1C) {
   4432     SDValue N0Op0 = N0.getOperand(0);
   4433     if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
   4434       unsigned LargeShiftVal = LargeShift->getZExtValue();
   4435       EVT LargeVT = N0Op0.getValueType();
   4436 
   4437       if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
   4438         SDValue Amt =
   4439           DAG.getConstant(LargeShiftVal + N1C->getZExtValue(),
   4440                           getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
   4441         SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), LargeVT,
   4442                                   N0Op0.getOperand(0), Amt);
   4443         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, SRA);
   4444       }
   4445     }
   4446   }
   4447 
   4448   // Simplify, based on bits shifted out of the LHS.
   4449   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
   4450     return SDValue(N, 0);
   4451 
   4452 
   4453   // If the sign bit is known to be zero, switch this to a SRL.
   4454   if (DAG.SignBitIsZero(N0))
   4455     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
   4456 
   4457   if (N1C) {
   4458     SDValue NewSRA = visitShiftByConstant(N, N1C);
   4459     if (NewSRA.getNode())
   4460       return NewSRA;
   4461   }
   4462 
   4463   return SDValue();
   4464 }
   4465 
   4466 SDValue DAGCombiner::visitSRL(SDNode *N) {
   4467   SDValue N0 = N->getOperand(0);
   4468   SDValue N1 = N->getOperand(1);
   4469   EVT VT = N0.getValueType();
   4470   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
   4471 
   4472   // fold vector ops
   4473   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
   4474   if (VT.isVector()) {
   4475     if (SDValue FoldedVOp = SimplifyVBinOp(N))
   4476       return FoldedVOp;
   4477 
   4478     N1C = isConstOrConstSplat(N1);
   4479   }
   4480 
   4481   // fold (srl c1, c2) -> c1 >>u c2
   4482   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
   4483   if (N0C && N1C)
   4484     return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C);
   4485   // fold (srl 0, x) -> 0
   4486   if (N0C && N0C->isNullValue())
   4487     return N0;
   4488   // fold (srl x, c >= size(x)) -> undef
   4489   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
   4490     return DAG.getUNDEF(VT);
   4491   // fold (srl x, 0) -> x
   4492   if (N1C && N1C->isNullValue())
   4493     return N0;
   4494   // if (srl x, c) is known to be zero, return 0
   4495   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
   4496                                    APInt::getAllOnesValue(OpSizeInBits)))
   4497     return DAG.getConstant(0, VT);
   4498 
   4499   // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
   4500   if (N1C && N0.getOpcode() == ISD::SRL) {
   4501     if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
   4502       uint64_t c1 = N01C->getZExtValue();
   4503       uint64_t c2 = N1C->getZExtValue();
   4504       if (c1 + c2 >= OpSizeInBits)
   4505         return DAG.getConstant(0, VT);
   4506       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
   4507                          DAG.getConstant(c1 + c2, N1.getValueType()));
   4508     }
   4509   }
   4510 
   4511   // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
   4512   if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
   4513       N0.getOperand(0).getOpcode() == ISD::SRL &&
   4514       isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
   4515     uint64_t c1 =
   4516       cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
   4517     uint64_t c2 = N1C->getZExtValue();
   4518     EVT InnerShiftVT = N0.getOperand(0).getValueType();
   4519     EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
   4520     uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
   4521     // This is only valid if the OpSizeInBits + c1 = size of inner shift.
   4522     if (c1 + OpSizeInBits == InnerShiftSize) {
   4523       if (c1 + c2 >= InnerShiftSize)
   4524         return DAG.getConstant(0, VT);
   4525       return DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT,
   4526                          DAG.getNode(ISD::SRL, SDLoc(N0), InnerShiftVT,
   4527                                      N0.getOperand(0)->getOperand(0),
   4528                                      DAG.getConstant(c1 + c2, ShiftCountVT)));
   4529     }
   4530   }
   4531 
   4532   // fold (srl (shl x, c), c) -> (and x, cst2)
   4533   if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
   4534     unsigned BitSize = N0.getScalarValueSizeInBits();
   4535     if (BitSize <= 64) {
   4536       uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
   4537       return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
   4538                          DAG.getConstant(~0ULL >> ShAmt, VT));
   4539     }
   4540   }
   4541 
   4542   // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
   4543   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
   4544     // Shifting in all undef bits?
   4545     EVT SmallVT = N0.getOperand(0).getValueType();
   4546     unsigned BitSize = SmallVT.getScalarSizeInBits();
   4547     if (N1C->getZExtValue() >= BitSize)
   4548       return DAG.getUNDEF(VT);
   4549 
   4550     if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
   4551       uint64_t ShiftAmt = N1C->getZExtValue();
   4552       SDValue SmallShift = DAG.getNode(ISD::SRL, SDLoc(N0), SmallVT,
   4553                                        N0.getOperand(0),
   4554                           DAG.getConstant(ShiftAmt, getShiftAmountTy(SmallVT)));
   4555       AddToWorklist(SmallShift.getNode());
   4556       APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
   4557       return DAG.getNode(ISD::AND, SDLoc(N), VT,
   4558                          DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, SmallShift),
   4559                          DAG.getConstant(Mask, VT));
   4560     }
   4561   }
   4562 
   4563   // fold (srl (sra X, Y), 31) -> (srl X, 31).  This srl only looks at the sign
   4564   // bit, which is unmodified by sra.
   4565   if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
   4566     if (N0.getOpcode() == ISD::SRA)
   4567       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
   4568   }
   4569 
   4570   // fold (srl (ctlz x), "5") -> x  iff x has one bit set (the low bit).
   4571   if (N1C && N0.getOpcode() == ISD::CTLZ &&
   4572       N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
   4573     APInt KnownZero, KnownOne;
   4574     DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne);
   4575 
   4576     // If any of the input bits are KnownOne, then the input couldn't be all
   4577     // zeros, thus the result of the srl will always be zero.
   4578     if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
   4579 
   4580     // If all of the bits input the to ctlz node are known to be zero, then
   4581     // the result of the ctlz is "32" and the result of the shift is one.
   4582     APInt UnknownBits = ~KnownZero;
   4583     if (UnknownBits == 0) return DAG.getConstant(1, VT);
   4584 
   4585     // Otherwise, check to see if there is exactly one bit input to the ctlz.
   4586     if ((UnknownBits & (UnknownBits - 1)) == 0) {
   4587       // Okay, we know that only that the single bit specified by UnknownBits
   4588       // could be set on input to the CTLZ node. If this bit is set, the SRL
   4589       // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
   4590       // to an SRL/XOR pair, which is likely to simplify more.
   4591       unsigned ShAmt = UnknownBits.countTrailingZeros();
   4592       SDValue Op = N0.getOperand(0);
   4593 
   4594       if (ShAmt) {
   4595         Op = DAG.getNode(ISD::SRL, SDLoc(N0), VT, Op,
   4596                   DAG.getConstant(ShAmt, getShiftAmountTy(Op.getValueType())));
   4597         AddToWorklist(Op.getNode());
   4598       }
   4599 
   4600       return DAG.getNode(ISD::XOR, SDLoc(N), VT,
   4601                          Op, DAG.getConstant(1, VT));
   4602     }
   4603   }
   4604 
   4605   // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
   4606   if (N1.getOpcode() == ISD::TRUNCATE &&
   4607       N1.getOperand(0).getOpcode() == ISD::AND) {
   4608     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
   4609     if (NewOp1.getNode())
   4610       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
   4611   }
   4612 
   4613   // fold operands of srl based on knowledge that the low bits are not
   4614   // demanded.
   4615   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
   4616     return SDValue(N, 0);
   4617 
   4618   if (N1C) {
   4619     SDValue NewSRL = visitShiftByConstant(N, N1C);
   4620     if (NewSRL.getNode())
   4621       return NewSRL;
   4622   }
   4623 
   4624   // Attempt to convert a srl of a load into a narrower zero-extending load.
   4625   SDValue NarrowLoad = ReduceLoadWidth(N);
   4626   if (NarrowLoad.getNode())
   4627     return NarrowLoad;
   4628 
   4629   // Here is a common situation. We want to optimize:
   4630   //
   4631   //   %a = ...
   4632   //   %b = and i32 %a, 2
   4633   //   %c = srl i32 %b, 1
   4634   //   brcond i32 %c ...
   4635   //
   4636   // into
   4637   //
   4638   //   %a = ...
   4639   //   %b = and %a, 2
   4640   //   %c = setcc eq %b, 0
   4641   //   brcond %c ...
   4642   //
   4643   // However when after the source operand of SRL is optimized into AND, the SRL
   4644   // itself may not be optimized further. Look for it and add the BRCOND into
   4645   // the worklist.
   4646   if (N->hasOneUse()) {
   4647     SDNode *Use = *N->use_begin();
   4648     if (Use->getOpcode() == ISD::BRCOND)
   4649       AddToWorklist(Use);
   4650     else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
   4651       // Also look pass the truncate.
   4652       Use = *Use->use_begin();
   4653       if (Use->getOpcode() == ISD::BRCOND)
   4654         AddToWorklist(Use);
   4655     }
   4656   }
   4657 
   4658   return SDValue();
   4659 }
   4660 
   4661 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
   4662   SDValue N0 = N->getOperand(0);
   4663   EVT VT = N->getValueType(0);
   4664 
   4665   // fold (ctlz c1) -> c2
   4666   if (isa<ConstantSDNode>(N0))
   4667     return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
   4668   return SDValue();
   4669 }
   4670 
   4671 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
   4672   SDValue N0 = N->getOperand(0);
   4673   EVT VT = N->getValueType(0);
   4674 
   4675   // fold (ctlz_zero_undef c1) -> c2
   4676   if (isa<ConstantSDNode>(N0))
   4677     return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
   4678   return SDValue();
   4679 }
   4680 
   4681 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
   4682   SDValue N0 = N->getOperand(0);
   4683   EVT VT = N->getValueType(0);
   4684 
   4685   // fold (cttz c1) -> c2
   4686   if (isa<ConstantSDNode>(N0))
   4687     return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
   4688   return SDValue();
   4689 }
   4690 
   4691 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
   4692   SDValue N0 = N->getOperand(0);
   4693   EVT VT = N->getValueType(0);
   4694 
   4695   // fold (cttz_zero_undef c1) -> c2
   4696   if (isa<ConstantSDNode>(N0))
   4697     return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
   4698   return SDValue();
   4699 }
   4700 
   4701 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
   4702   SDValue N0 = N->getOperand(0);
   4703   EVT VT = N->getValueType(0);
   4704 
   4705   // fold (ctpop c1) -> c2
   4706   if (isa<ConstantSDNode>(N0))
   4707     return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
   4708   return SDValue();
   4709 }
   4710 
   4711 
   4712 /// \brief Generate Min/Max node
   4713 static SDValue combineMinNumMaxNum(SDLoc DL, EVT VT, SDValue LHS, SDValue RHS,
   4714                                    SDValue True, SDValue False,
   4715                                    ISD::CondCode CC, const TargetLowering &TLI,
   4716                                    SelectionDAG &DAG) {
   4717   if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True))
   4718     return SDValue();
   4719 
   4720   switch (CC) {
   4721   case ISD::SETOLT:
   4722   case ISD::SETOLE:
   4723   case ISD::SETLT:
   4724   case ISD::SETLE:
   4725   case ISD::SETULT:
   4726   case ISD::SETULE: {
   4727     unsigned Opcode = (LHS == True) ? ISD::FMINNUM : ISD::FMAXNUM;
   4728     if (TLI.isOperationLegal(Opcode, VT))
   4729       return DAG.getNode(Opcode, DL, VT, LHS, RHS);
   4730     return SDValue();
   4731   }
   4732   case ISD::SETOGT:
   4733   case ISD::SETOGE:
   4734   case ISD::SETGT:
   4735   case ISD::SETGE:
   4736   case ISD::SETUGT:
   4737   case ISD::SETUGE: {
   4738     unsigned Opcode = (LHS == True) ? ISD::FMAXNUM : ISD::FMINNUM;
   4739     if (TLI.isOperationLegal(Opcode, VT))
   4740       return DAG.getNode(Opcode, DL, VT, LHS, RHS);
   4741     return SDValue();
   4742   }
   4743   default:
   4744     return SDValue();
   4745   }
   4746 }
   4747 
   4748 SDValue DAGCombiner::visitSELECT(SDNode *N) {
   4749   SDValue N0 = N->getOperand(0);
   4750   SDValue N1 = N->getOperand(1);
   4751   SDValue N2 = N->getOperand(2);
   4752   EVT VT = N->getValueType(0);
   4753   EVT VT0 = N0.getValueType();
   4754 
   4755   // fold (select C, X, X) -> X
   4756   if (N1 == N2)
   4757     return N1;
   4758   // fold (select true, X, Y) -> X
   4759   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
   4760   if (N0C && !N0C->isNullValue())
   4761     return N1;
   4762   // fold (select false, X, Y) -> Y
   4763   if (N0C && N0C->isNullValue())
   4764     return N2;
   4765   // fold (select C, 1, X) -> (or C, X)
   4766   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
   4767   if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
   4768     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
   4769   // fold (select C, 0, 1) -> (xor C, 1)
   4770   // We can't do this reliably if integer based booleans have different contents
   4771   // to floating point based booleans. This is because we can't tell whether we
   4772   // have an integer-based boolean or a floating-point-based boolean unless we
   4773   // can find the SETCC that produced it and inspect its operands. This is
   4774   // fairly easy if C is the SETCC node, but it can potentially be
   4775   // undiscoverable (or not reasonably discoverable). For example, it could be
   4776   // in another basic block or it could require searching a complicated
   4777   // expression.
   4778   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
   4779   if (VT.isInteger() &&
   4780       (VT0 == MVT::i1 || (VT0.isInteger() &&
   4781                           TLI.getBooleanContents(false, false) ==
   4782                               TLI.getBooleanContents(false, true) &&
   4783                           TLI.getBooleanContents(false, false) ==
   4784                               TargetLowering::ZeroOrOneBooleanContent)) &&
   4785       N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
   4786     SDValue XORNode;
   4787     if (VT == VT0)
   4788       return DAG.getNode(ISD::XOR, SDLoc(N), VT0,
   4789                          N0, DAG.getConstant(1, VT0));
   4790     XORNode = DAG.getNode(ISD::XOR, SDLoc(N0), VT0,
   4791                           N0, DAG.getConstant(1, VT0));
   4792     AddToWorklist(XORNode.getNode());
   4793     if (VT.bitsGT(VT0))
   4794       return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
   4795     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
   4796   }
   4797   // fold (select C, 0, X) -> (and (not C), X)
   4798   if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
   4799     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
   4800     AddToWorklist(NOTNode.getNode());
   4801     return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
   4802   }
   4803   // fold (select C, X, 1) -> (or (not C), X)
   4804   if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
   4805     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
   4806     AddToWorklist(NOTNode.getNode());
   4807     return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
   4808   }
   4809   // fold (select C, X, 0) -> (and C, X)
   4810   if (VT == MVT::i1 && N2C && N2C->isNullValue())
   4811     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
   4812   // fold (select X, X, Y) -> (or X, Y)
   4813   // fold (select X, 1, Y) -> (or X, Y)
   4814   if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
   4815     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
   4816   // fold (select X, Y, X) -> (and X, Y)
   4817   // fold (select X, Y, 0) -> (and X, Y)
   4818   if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
   4819     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
   4820 
   4821   // If we can fold this based on the true/false value, do so.
   4822   if (SimplifySelectOps(N, N1, N2))
   4823     return SDValue(N, 0);  // Don't revisit N.
   4824 
   4825   // fold selects based on a setcc into other things, such as min/max/abs
   4826   if (N0.getOpcode() == ISD::SETCC) {
   4827     // select x, y (fcmp lt x, y) -> fminnum x, y
   4828     // select x, y (fcmp gt x, y) -> fmaxnum x, y
   4829     //
   4830     // This is OK if we don't care about what happens if either operand is a
   4831     // NaN.
   4832     //
   4833 
   4834     // FIXME: Instead of testing for UnsafeFPMath, this should be checking for
   4835     // no signed zeros as well as no nans.
   4836     const TargetOptions &Options = DAG.getTarget().Options;
   4837     if (Options.UnsafeFPMath &&
   4838         VT.isFloatingPoint() && N0.hasOneUse() &&
   4839         DAG.isKnownNeverNaN(N1) && DAG.isKnownNeverNaN(N2)) {
   4840       ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
   4841 
   4842       SDValue FMinMax =
   4843           combineMinNumMaxNum(SDLoc(N), VT, N0.getOperand(0), N0.getOperand(1),
   4844                               N1, N2, CC, TLI, DAG);
   4845       if (FMinMax)
   4846         return FMinMax;
   4847     }
   4848 
   4849     if ((!LegalOperations &&
   4850          TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
   4851         TLI.isOperationLegal(ISD::SELECT_CC, VT))
   4852       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
   4853                          N0.getOperand(0), N0.getOperand(1),
   4854                          N1, N2, N0.getOperand(2));
   4855     return SimplifySelect(SDLoc(N), N0, N1, N2);
   4856   }
   4857 
   4858   if (VT0 == MVT::i1) {
   4859     if (TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT)) {
   4860       // select (and Cond0, Cond1), X, Y
   4861       //   -> select Cond0, (select Cond1, X, Y), Y
   4862       if (N0->getOpcode() == ISD::AND && N0->hasOneUse()) {
   4863         SDValue Cond0 = N0->getOperand(0);
   4864         SDValue Cond1 = N0->getOperand(1);
   4865         SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
   4866                                           N1.getValueType(), Cond1, N1, N2);
   4867         return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0,
   4868                            InnerSelect, N2);
   4869       }
   4870       // select (or Cond0, Cond1), X, Y -> select Cond0, X, (select Cond1, X, Y)
   4871       if (N0->getOpcode() == ISD::OR && N0->hasOneUse()) {
   4872         SDValue Cond0 = N0->getOperand(0);
   4873         SDValue Cond1 = N0->getOperand(1);
   4874         SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
   4875                                           N1.getValueType(), Cond1, N1, N2);
   4876         return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0, N1,
   4877                            InnerSelect);
   4878       }
   4879     }
   4880 
   4881     // select Cond0, (select Cond1, X, Y), Y -> select (and Cond0, Cond1), X, Y
   4882     if (N1->getOpcode() == ISD::SELECT) {
   4883       SDValue N1_0 = N1->getOperand(0);
   4884       SDValue N1_1 = N1->getOperand(1);
   4885       SDValue N1_2 = N1->getOperand(2);
   4886       if (N1_2 == N2 && N0.getValueType() == N1_0.getValueType()) {
   4887         // Create the actual and node if we can generate good code for it.
   4888         if (!TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT)) {
   4889           SDValue And = DAG.getNode(ISD::AND, SDLoc(N), N0.getValueType(),
   4890                                     N0, N1_0);
   4891           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), And,
   4892                              N1_1, N2);
   4893         }
   4894         // Otherwise see if we can optimize the "and" to a better pattern.
   4895         if (SDValue Combined = visitANDLike(N0, N1_0, N))
   4896           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
   4897                              N1_1, N2);
   4898       }
   4899     }
   4900     // select Cond0, X, (select Cond1, X, Y) -> select (or Cond0, Cond1), X, Y
   4901     if (N2->getOpcode() == ISD::SELECT) {
   4902       SDValue N2_0 = N2->getOperand(0);
   4903       SDValue N2_1 = N2->getOperand(1);
   4904       SDValue N2_2 = N2->getOperand(2);
   4905       if (N2_1 == N1 && N0.getValueType() == N2_0.getValueType()) {
   4906         // Create the actual or node if we can generate good code for it.
   4907         if (!TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT)) {
   4908           SDValue Or = DAG.getNode(ISD::OR, SDLoc(N), N0.getValueType(),
   4909                                    N0, N2_0);
   4910           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Or,
   4911                              N1, N2_2);
   4912         }
   4913         // Otherwise see if we can optimize to a better pattern.
   4914         if (SDValue Combined = visitORLike(N0, N2_0, N))
   4915           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
   4916                              N1, N2_2);
   4917       }
   4918     }
   4919   }
   4920 
   4921   return SDValue();
   4922 }
   4923 
   4924 static
   4925 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
   4926   SDLoc DL(N);
   4927   EVT LoVT, HiVT;
   4928   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
   4929 
   4930   // Split the inputs.
   4931   SDValue Lo, Hi, LL, LH, RL, RH;
   4932   std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
   4933   std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
   4934 
   4935   Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
   4936   Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
   4937 
   4938   return std::make_pair(Lo, Hi);
   4939 }
   4940 
   4941 // This function assumes all the vselect's arguments are CONCAT_VECTOR
   4942 // nodes and that the condition is a BV of ConstantSDNodes (or undefs).
   4943 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
   4944   SDLoc dl(N);
   4945   SDValue Cond = N->getOperand(0);
   4946   SDValue LHS = N->getOperand(1);
   4947   SDValue RHS = N->getOperand(2);
   4948   EVT VT = N->getValueType(0);
   4949   int NumElems = VT.getVectorNumElements();
   4950   assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
   4951          RHS.getOpcode() == ISD::CONCAT_VECTORS &&
   4952          Cond.getOpcode() == ISD::BUILD_VECTOR);
   4953 
   4954   // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about
   4955   // binary ones here.
   4956   if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2)
   4957     return SDValue();
   4958 
   4959   // We're sure we have an even number of elements due to the
   4960   // concat_vectors we have as arguments to vselect.
   4961   // Skip BV elements until we find one that's not an UNDEF
   4962   // After we find an UNDEF element, keep looping until we get to half the
   4963   // length of the BV and see if all the non-undef nodes are the same.
   4964   ConstantSDNode *BottomHalf = nullptr;
   4965   for (int i = 0; i < NumElems / 2; ++i) {
   4966     if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
   4967       continue;
   4968 
   4969     if (BottomHalf == nullptr)
   4970       BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
   4971     else if (Cond->getOperand(i).getNode() != BottomHalf)
   4972       return SDValue();
   4973   }
   4974 
   4975   // Do the same for the second half of the BuildVector
   4976   ConstantSDNode *TopHalf = nullptr;
   4977   for (int i = NumElems / 2; i < NumElems; ++i) {
   4978     if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
   4979       continue;
   4980 
   4981     if (TopHalf == nullptr)
   4982       TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
   4983     else if (Cond->getOperand(i).getNode() != TopHalf)
   4984       return SDValue();
   4985   }
   4986 
   4987   assert(TopHalf && BottomHalf &&
   4988          "One half of the selector was all UNDEFs and the other was all the "
   4989          "same value. This should have been addressed before this function.");
   4990   return DAG.getNode(
   4991       ISD::CONCAT_VECTORS, dl, VT,
   4992       BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
   4993       TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
   4994 }
   4995 
   4996 SDValue DAGCombiner::visitMSTORE(SDNode *N) {
   4997 
   4998   if (Level >= AfterLegalizeTypes)
   4999     return SDValue();
   5000 
   5001   MaskedStoreSDNode *MST = dyn_cast<MaskedStoreSDNode>(N);
   5002   SDValue Mask = MST->getMask();
   5003   SDValue Data  = MST->getValue();
   5004   SDLoc DL(N);
   5005 
   5006   // If the MSTORE data type requires splitting and the mask is provided by a
   5007   // SETCC, then split both nodes and its operands before legalization. This
   5008   // prevents the type legalizer from unrolling SETCC into scalar comparisons
   5009   // and enables future optimizations (e.g. min/max pattern matching on X86).
   5010   if (Mask.getOpcode() == ISD::SETCC) {
   5011 
   5012     // Check if any splitting is required.
   5013     if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
   5014         TargetLowering::TypeSplitVector)
   5015       return SDValue();
   5016 
   5017     SDValue MaskLo, MaskHi, Lo, Hi;
   5018     std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
   5019 
   5020     EVT LoVT, HiVT;
   5021     std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MST->getValueType(0));
   5022 
   5023     SDValue Chain = MST->getChain();
   5024     SDValue Ptr   = MST->getBasePtr();
   5025 
   5026     EVT MemoryVT = MST->getMemoryVT();
   5027     unsigned Alignment = MST->getOriginalAlignment();
   5028 
   5029     // if Alignment is equal to the vector size,
   5030     // take the half of it for the second part
   5031     unsigned SecondHalfAlignment =
   5032       (Alignment == Data->getValueType(0).getSizeInBits()/8) ?
   5033          Alignment/2 : Alignment;
   5034 
   5035     EVT LoMemVT, HiMemVT;
   5036     std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
   5037 
   5038     SDValue DataLo, DataHi;
   5039     std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
   5040 
   5041     MachineMemOperand *MMO = DAG.getMachineFunction().
   5042       getMachineMemOperand(MST->getPointerInfo(),
   5043                            MachineMemOperand::MOStore,  LoMemVT.getStoreSize(),
   5044                            Alignment, MST->getAAInfo(), MST->getRanges());
   5045 
   5046     Lo = DAG.getMaskedStore(Chain, DL, DataLo, Ptr, MaskLo, LoMemVT, MMO,
   5047                             MST->isTruncatingStore());
   5048 
   5049     unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
   5050     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
   5051                       DAG.getConstant(IncrementSize, Ptr.getValueType()));
   5052 
   5053     MMO = DAG.getMachineFunction().
   5054       getMachineMemOperand(MST->getPointerInfo(),
   5055                            MachineMemOperand::MOStore,  HiMemVT.getStoreSize(),
   5056                            SecondHalfAlignment, MST->getAAInfo(),
   5057                            MST->getRanges());
   5058 
   5059     Hi = DAG.getMaskedStore(Chain, DL, DataHi, Ptr, MaskHi, HiMemVT, MMO,
   5060                             MST->isTruncatingStore());
   5061 
   5062     AddToWorklist(Lo.getNode());
   5063     AddToWorklist(Hi.getNode());
   5064 
   5065     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
   5066   }
   5067   return SDValue();
   5068 }
   5069 
   5070 SDValue DAGCombiner::visitMLOAD(SDNode *N) {
   5071 
   5072   if (Level >= AfterLegalizeTypes)
   5073     return SDValue();
   5074 
   5075   MaskedLoadSDNode *MLD = dyn_cast<MaskedLoadSDNode>(N);
   5076   SDValue Mask = MLD->getMask();
   5077   SDLoc DL(N);
   5078 
   5079   // If the MLOAD result requires splitting and the mask is provided by a
   5080   // SETCC, then split both nodes and its operands before legalization. This
   5081   // prevents the type legalizer from unrolling SETCC into scalar comparisons
   5082   // and enables future optimizations (e.g. min/max pattern matching on X86).
   5083 
   5084   if (Mask.getOpcode() == ISD::SETCC) {
   5085     EVT VT = N->getValueType(0);
   5086 
   5087     // Check if any splitting is required.
   5088     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
   5089         TargetLowering::TypeSplitVector)
   5090       return SDValue();
   5091 
   5092     SDValue MaskLo, MaskHi, Lo, Hi;
   5093     std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
   5094 
   5095     SDValue Src0 = MLD->getSrc0();
   5096     SDValue Src0Lo, Src0Hi;
   5097     std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
   5098 
   5099     EVT LoVT, HiVT;
   5100     std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MLD->getValueType(0));
   5101 
   5102     SDValue Chain = MLD->getChain();
   5103     SDValue Ptr   = MLD->getBasePtr();
   5104     EVT MemoryVT = MLD->getMemoryVT();
   5105     unsigned Alignment = MLD->getOriginalAlignment();
   5106 
   5107     // if Alignment is equal to the vector size,
   5108     // take the half of it for the second part
   5109     unsigned SecondHalfAlignment =
   5110       (Alignment == MLD->getValueType(0).getSizeInBits()/8) ?
   5111          Alignment/2 : Alignment;
   5112 
   5113     EVT LoMemVT, HiMemVT;
   5114     std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
   5115 
   5116     MachineMemOperand *MMO = DAG.getMachineFunction().
   5117     getMachineMemOperand(MLD->getPointerInfo(),
   5118                          MachineMemOperand::MOLoad,  LoMemVT.getStoreSize(),
   5119                          Alignment, MLD->getAAInfo(), MLD->getRanges());
   5120 
   5121     Lo = DAG.getMaskedLoad(LoVT, DL, Chain, Ptr, MaskLo, Src0Lo, LoMemVT, MMO,
   5122                            ISD::NON_EXTLOAD);
   5123 
   5124     unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
   5125     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
   5126                       DAG.getConstant(IncrementSize, Ptr.getValueType()));
   5127 
   5128     MMO = DAG.getMachineFunction().
   5129     getMachineMemOperand(MLD->getPointerInfo(),
   5130                          MachineMemOperand::MOLoad,  HiMemVT.getStoreSize(),
   5131                          SecondHalfAlignment, MLD->getAAInfo(), MLD->getRanges());
   5132 
   5133     Hi = DAG.getMaskedLoad(HiVT, DL, Chain, Ptr, MaskHi, Src0Hi, HiMemVT, MMO,
   5134                            ISD::NON_EXTLOAD);
   5135 
   5136     AddToWorklist(Lo.getNode());
   5137     AddToWorklist(Hi.getNode());
   5138 
   5139     // Build a factor node to remember that this load is independent of the
   5140     // other one.
   5141     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
   5142                         Hi.getValue(1));
   5143 
   5144     // Legalized the chain result - switch anything that used the old chain to
   5145     // use the new one.
   5146     DAG.ReplaceAllUsesOfValueWith(SDValue(MLD, 1), Chain);
   5147 
   5148     SDValue LoadRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
   5149 
   5150     SDValue RetOps[] = { LoadRes, Chain };
   5151     return DAG.getMergeValues(RetOps, DL);
   5152   }
   5153   return SDValue();
   5154 }
   5155 
   5156 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
   5157   SDValue N0 = N->getOperand(0);
   5158   SDValue N1 = N->getOperand(1);
   5159   SDValue N2 = N->getOperand(2);
   5160   SDLoc DL(N);
   5161 
   5162   // Canonicalize integer abs.
   5163   // vselect (setg[te] X,  0),  X, -X ->
   5164   // vselect (setgt    X, -1),  X, -X ->
   5165   // vselect (setl[te] X,  0), -X,  X ->
   5166   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
   5167   if (N0.getOpcode() == ISD::SETCC) {
   5168     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
   5169     ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
   5170     bool isAbs = false;
   5171     bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
   5172 
   5173     if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
   5174          (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
   5175         N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
   5176       isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
   5177     else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
   5178              N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
   5179       isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
   5180 
   5181     if (isAbs) {
   5182       EVT VT = LHS.getValueType();
   5183       SDValue Shift = DAG.getNode(
   5184           ISD::SRA, DL, VT, LHS,
   5185           DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, VT));
   5186       SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
   5187       AddToWorklist(Shift.getNode());
   5188       AddToWorklist(Add.getNode());
   5189       return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
   5190     }
   5191   }
   5192 
   5193   // If the VSELECT result requires splitting and the mask is provided by a
   5194   // SETCC, then split both nodes and its operands before legalization. This
   5195   // prevents the type legalizer from unrolling SETCC into scalar comparisons
   5196   // and enables future optimizations (e.g. min/max pattern matching on X86).
   5197   if (N0.getOpcode() == ISD::SETCC) {
   5198     EVT VT = N->getValueType(0);
   5199 
   5200     // Check if any splitting is required.
   5201     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
   5202         TargetLowering::TypeSplitVector)
   5203       return SDValue();
   5204 
   5205     SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
   5206     std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
   5207     std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
   5208     std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
   5209 
   5210     Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
   5211     Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
   5212 
   5213     // Add the new VSELECT nodes to the work list in case they need to be split
   5214     // again.
   5215     AddToWorklist(Lo.getNode());
   5216     AddToWorklist(Hi.getNode());
   5217 
   5218     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
   5219   }
   5220 
   5221   // Fold (vselect (build_vector all_ones), N1, N2) -> N1
   5222   if (ISD::isBuildVectorAllOnes(N0.getNode()))
   5223     return N1;
   5224   // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
   5225   if (ISD::isBuildVectorAllZeros(N0.getNode()))
   5226     return N2;
   5227 
   5228   // The ConvertSelectToConcatVector function is assuming both the above
   5229   // checks for (vselect (build_vector all{ones,zeros) ...) have been made
   5230   // and addressed.
   5231   if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
   5232       N2.getOpcode() == ISD::CONCAT_VECTORS &&
   5233       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
   5234     SDValue CV = ConvertSelectToConcatVector(N, DAG);
   5235     if (CV.getNode())
   5236       return CV;
   5237   }
   5238 
   5239   return SDValue();
   5240 }
   5241 
   5242 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
   5243   SDValue N0 = N->getOperand(0);
   5244   SDValue N1 = N->getOperand(1);
   5245   SDValue N2 = N->getOperand(2);
   5246   SDValue N3 = N->getOperand(3);
   5247   SDValue N4 = N->getOperand(4);
   5248   ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
   5249 
   5250   // fold select_cc lhs, rhs, x, x, cc -> x
   5251   if (N2 == N3)
   5252     return N2;
   5253 
   5254   // Determine if the condition we're dealing with is constant
   5255   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
   5256                               N0, N1, CC, SDLoc(N), false);
   5257   if (SCC.getNode()) {
   5258     AddToWorklist(SCC.getNode());
   5259 
   5260     if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
   5261       if (!SCCC->isNullValue())
   5262         return N2;    // cond always true -> true val
   5263       else
   5264         return N3;    // cond always false -> false val
   5265     } else if (SCC->getOpcode() == ISD::UNDEF) {
   5266       // When the condition is UNDEF, just return the first operand. This is
   5267       // coherent the DAG creation, no setcc node is created in this case
   5268       return N2;
   5269     } else if (SCC.getOpcode() == ISD::SETCC) {
   5270       // Fold to a simpler select_cc
   5271       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
   5272                          SCC.getOperand(0), SCC.getOperand(1), N2, N3,
   5273                          SCC.getOperand(2));
   5274     }
   5275   }
   5276 
   5277   // If we can fold this based on the true/false value, do so.
   5278   if (SimplifySelectOps(N, N2, N3))
   5279     return SDValue(N, 0);  // Don't revisit N.
   5280 
   5281   // fold select_cc into other things, such as min/max/abs
   5282   return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
   5283 }
   5284 
   5285 SDValue DAGCombiner::visitSETCC(SDNode *N) {
   5286   return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
   5287                        cast<CondCodeSDNode>(N->getOperand(2))->get(),
   5288                        SDLoc(N));
   5289 }
   5290 
   5291 // tryToFoldExtendOfConstant - Try to fold a sext/zext/aext
   5292 // dag node into a ConstantSDNode or a build_vector of constants.
   5293 // This function is called by the DAGCombiner when visiting sext/zext/aext
   5294 // dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
   5295 // Vector extends are not folded if operations are legal; this is to
   5296 // avoid introducing illegal build_vector dag nodes.
   5297 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
   5298                                          SelectionDAG &DAG, bool LegalTypes,
   5299                                          bool LegalOperations) {
   5300   unsigned Opcode = N->getOpcode();
   5301   SDValue N0 = N->getOperand(0);
   5302   EVT VT = N->getValueType(0);
   5303 
   5304   assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
   5305          Opcode == ISD::ANY_EXTEND) && "Expected EXTEND dag node in input!");
   5306 
   5307   // fold (sext c1) -> c1
   5308   // fold (zext c1) -> c1
   5309   // fold (aext c1) -> c1
   5310   if (isa<ConstantSDNode>(N0))
   5311     return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
   5312 
   5313   // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
   5314   // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
   5315   // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
   5316   EVT SVT = VT.getScalarType();
   5317   if (!(VT.isVector() &&
   5318       (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
   5319       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
   5320     return nullptr;
   5321 
   5322   // We can fold this node into a build_vector.
   5323   unsigned VTBits = SVT.getSizeInBits();
   5324   unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
   5325   unsigned ShAmt = VTBits - EVTBits;
   5326   SmallVector<SDValue, 8> Elts;
   5327   unsigned NumElts = N0->getNumOperands();
   5328   SDLoc DL(N);
   5329 
   5330   for (unsigned i=0; i != NumElts; ++i) {
   5331     SDValue Op = N0->getOperand(i);
   5332     if (Op->getOpcode() == ISD::UNDEF) {
   5333       Elts.push_back(DAG.getUNDEF(SVT));
   5334       continue;
   5335     }
   5336 
   5337     ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
   5338     const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
   5339     if (Opcode == ISD::SIGN_EXTEND)
   5340       Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
   5341                                      SVT));
   5342     else
   5343       Elts.push_back(DAG.getConstant(C.shl(ShAmt).lshr(ShAmt).getZExtValue(),
   5344                                      SVT));
   5345   }
   5346 
   5347   return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts).getNode();
   5348 }
   5349 
   5350 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
   5351 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
   5352 // transformation. Returns true if extension are possible and the above
   5353 // mentioned transformation is profitable.
   5354 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
   5355                                     unsigned ExtOpc,
   5356                                     SmallVectorImpl<SDNode *> &ExtendNodes,
   5357                                     const TargetLowering &TLI) {
   5358   bool HasCopyToRegUses = false;
   5359   bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
   5360   for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
   5361                             UE = N0.getNode()->use_end();
   5362        UI != UE; ++UI) {
   5363     SDNode *User = *UI;
   5364     if (User == N)
   5365       continue;
   5366     if (UI.getUse().getResNo() != N0.getResNo())
   5367       continue;
   5368     // FIXME: Only extend SETCC N, N and SETCC N, c for now.
   5369     if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
   5370       ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
   5371       if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
   5372         // Sign bits will be lost after a zext.
   5373         return false;
   5374       bool Add = false;
   5375       for (unsigned i = 0; i != 2; ++i) {
   5376         SDValue UseOp = User->getOperand(i);
   5377         if (UseOp == N0)
   5378           continue;
   5379         if (!isa<ConstantSDNode>(UseOp))
   5380           return false;
   5381         Add = true;
   5382       }
   5383       if (Add)
   5384         ExtendNodes.push_back(User);
   5385       continue;
   5386     }
   5387     // If truncates aren't free and there are users we can't
   5388     // extend, it isn't worthwhile.
   5389     if (!isTruncFree)
   5390       return false;
   5391     // Remember if this value is live-out.
   5392     if (User->getOpcode() == ISD::CopyToReg)
   5393       HasCopyToRegUses = true;
   5394   }
   5395 
   5396   if (HasCopyToRegUses) {
   5397     bool BothLiveOut = false;
   5398     for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
   5399          UI != UE; ++UI) {
   5400       SDUse &Use = UI.getUse();
   5401       if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
   5402         BothLiveOut = true;
   5403         break;
   5404       }
   5405     }
   5406     if (BothLiveOut)
   5407       // Both unextended and extended values are live out. There had better be
   5408       // a good reason for the transformation.
   5409       return ExtendNodes.size();
   5410   }
   5411   return true;
   5412 }
   5413 
   5414 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
   5415                                   SDValue Trunc, SDValue ExtLoad, SDLoc DL,
   5416                                   ISD::NodeType ExtType) {
   5417   // Extend SetCC uses if necessary.
   5418   for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
   5419     SDNode *SetCC = SetCCs[i];
   5420     SmallVector<SDValue, 4> Ops;
   5421 
   5422     for (unsigned j = 0; j != 2; ++j) {
   5423       SDValue SOp = SetCC->getOperand(j);
   5424       if (SOp == Trunc)
   5425         Ops.push_back(ExtLoad);
   5426       else
   5427         Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
   5428     }
   5429 
   5430     Ops.push_back(SetCC->getOperand(2));
   5431     CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
   5432   }
   5433 }
   5434 
   5435 // FIXME: Bring more similar combines here, common to sext/zext (maybe aext?).
   5436 SDValue DAGCombiner::CombineExtLoad(SDNode *N) {
   5437   SDValue N0 = N->getOperand(0);
   5438   EVT DstVT = N->getValueType(0);
   5439   EVT SrcVT = N0.getValueType();
   5440 
   5441   assert((N->getOpcode() == ISD::SIGN_EXTEND ||
   5442           N->getOpcode() == ISD::ZERO_EXTEND) &&
   5443          "Unexpected node type (not an extend)!");
   5444 
   5445   // fold (sext (load x)) to multiple smaller sextloads; same for zext.
   5446   // For example, on a target with legal v4i32, but illegal v8i32, turn:
   5447   //   (v8i32 (sext (v8i16 (load x))))
   5448   // into:
   5449   //   (v8i32 (concat_vectors (v4i32 (sextload x)),
   5450   //                          (v4i32 (sextload (x + 16)))))
   5451   // Where uses of the original load, i.e.:
   5452   //   (v8i16 (load x))
   5453   // are replaced with:
   5454   //   (v8i16 (truncate
   5455   //     (v8i32 (concat_vectors (v4i32 (sextload x)),
   5456   //                            (v4i32 (sextload (x + 16)))))))
   5457   //
   5458   // This combine is only applicable to illegal, but splittable, vectors.
   5459   // All legal types, and illegal non-vector types, are handled elsewhere.
   5460   // This combine is controlled by TargetLowering::isVectorLoadExtDesirable.
   5461   //
   5462   if (N0->getOpcode() != ISD::LOAD)
   5463     return SDValue();
   5464 
   5465   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
   5466 
   5467   if (!ISD::isNON_EXTLoad(LN0) || !ISD::isUNINDEXEDLoad(LN0) ||
   5468       !N0.hasOneUse() || LN0->isVolatile() || !DstVT.isVector() ||
   5469       !DstVT.isPow2VectorType() || !TLI.isVectorLoadExtDesirable(SDValue(N, 0)))
   5470     return SDValue();
   5471 
   5472   SmallVector<SDNode *, 4> SetCCs;
   5473   if (!ExtendUsesToFormExtLoad(N, N0, N->getOpcode(), SetCCs, TLI))
   5474     return SDValue();
   5475 
   5476   ISD::LoadExtType ExtType =
   5477       N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
   5478 
   5479   // Try to split the vector types to get down to legal types.
   5480   EVT SplitSrcVT = SrcVT;
   5481   EVT SplitDstVT = DstVT;
   5482   while (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT) &&
   5483          SplitSrcVT.getVectorNumElements() > 1) {
   5484     SplitDstVT = DAG.GetSplitDestVTs(SplitDstVT).first;
   5485     SplitSrcVT = DAG.GetSplitDestVTs(SplitSrcVT).first;
   5486   }
   5487 
   5488   if (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT))
   5489     return SDValue();
   5490 
   5491   SDLoc DL(N);
   5492   const unsigned NumSplits =
   5493       DstVT.getVectorNumElements() / SplitDstVT.getVectorNumElements();
   5494   const unsigned Stride = SplitSrcVT.getStoreSize();
   5495   SmallVector<SDValue, 4> Loads;
   5496   SmallVector<SDValue, 4> Chains;
   5497 
   5498   SDValue BasePtr = LN0->getBasePtr();
   5499   for (unsigned Idx = 0; Idx < NumSplits; Idx++) {
   5500     const unsigned Offset = Idx * Stride;
   5501     const unsigned Align = MinAlign(LN0->getAlignment(), Offset);
   5502 
   5503     SDValue SplitLoad = DAG.getExtLoad(
   5504         ExtType, DL, SplitDstVT, LN0->getChain(), BasePtr,
   5505         LN0->getPointerInfo().getWithOffset(Offset), SplitSrcVT,
   5506         LN0->isVolatile(), LN0->isNonTemporal(), LN0->isInvariant(),
   5507         Align, LN0->getAAInfo());
   5508 
   5509     BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
   5510                           DAG.getConstant(Stride, BasePtr.getValueType()));
   5511 
   5512     Loads.push_back(SplitLoad.getValue(0));
   5513     Chains.push_back(SplitLoad.getValue(1));
   5514   }
   5515 
   5516   SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
   5517   SDValue NewValue = DAG.getNode(ISD::CONCAT_VECTORS, DL, DstVT, Loads);
   5518 
   5519   CombineTo(N, NewValue);
   5520 
   5521   // Replace uses of the original load (before extension)
   5522   // with a truncate of the concatenated sextloaded vectors.
   5523   SDValue Trunc =
   5524       DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), NewValue);
   5525   CombineTo(N0.getNode(), Trunc, NewChain);
   5526   ExtendSetCCUses(SetCCs, Trunc, NewValue, DL,
   5527                   (ISD::NodeType)N->getOpcode());
   5528   return SDValue(N, 0); // Return N so it doesn't get rechecked!
   5529 }
   5530 
   5531 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
   5532   SDValue N0 = N->getOperand(0);
   5533   EVT VT = N->getValueType(0);
   5534 
   5535   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
   5536                                               LegalOperations))
   5537     return SDValue(Res, 0);
   5538 
   5539   // fold (sext (sext x)) -> (sext x)
   5540   // fold (sext (aext x)) -> (sext x)
   5541   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
   5542     return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
   5543                        N0.getOperand(0));
   5544 
   5545   if (N0.getOpcode() == ISD::TRUNCATE) {
   5546     // fold (sext (truncate (load x))) -> (sext (smaller load x))
   5547     // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
   5548     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
   5549     if (NarrowLoad.getNode()) {
   5550       SDNode* oye = N0.getNode()->getOperand(0).getNode();
   5551       if (NarrowLoad.getNode() != N0.getNode()) {
   5552         CombineTo(N0.getNode(), NarrowLoad);
   5553         // CombineTo deleted the truncate, if needed, but not what's under it.
   5554         AddToWorklist(oye);
   5555       }
   5556       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
   5557     }
   5558 
   5559     // See if the value being truncated is already sign extended.  If so, just
   5560     // eliminate the trunc/sext pair.
   5561     SDValue Op = N0.getOperand(0);
   5562     unsigned OpBits   = Op.getValueType().getScalarType().getSizeInBits();
   5563     unsigned MidBits  = N0.getValueType().getScalarType().getSizeInBits();
   5564     unsigned DestBits = VT.getScalarType().getSizeInBits();
   5565     unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
   5566 
   5567     if (OpBits == DestBits) {
   5568       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
   5569       // bits, it is already ready.
   5570       if (NumSignBits > DestBits-MidBits)
   5571         return Op;
   5572     } else if (OpBits < DestBits) {
   5573       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
   5574       // bits, just sext from i32.
   5575       if (NumSignBits > OpBits-MidBits)
   5576         return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
   5577     } else {
   5578       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
   5579       // bits, just truncate to i32.
   5580       if (NumSignBits > OpBits-MidBits)
   5581         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
   5582     }
   5583 
   5584     // fold (sext (truncate x)) -> (sextinreg x).
   5585     if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
   5586                                                  N0.getValueType())) {
   5587       if (OpBits < DestBits)
   5588         Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
   5589       else if (OpBits > DestBits)
   5590         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
   5591       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
   5592                          DAG.getValueType(N0.getValueType()));
   5593     }
   5594   }
   5595 
   5596   // fold (sext (load x)) -> (sext (truncate (sextload x)))
   5597   // Only generate vector extloads when 1) they're legal, and 2) they are
   5598   // deemed desirable by the target.
   5599   if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
   5600       ((!LegalOperations && !VT.isVector() &&
   5601         !cast<LoadSDNode>(N0)->isVolatile()) ||
   5602        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()))) {
   5603     bool DoXform = true;
   5604     SmallVector<SDNode*, 4> SetCCs;
   5605     if (!N0.hasOneUse())
   5606       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
   5607     if (VT.isVector())
   5608       DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
   5609     if (DoXform) {
   5610       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
   5611       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
   5612                                        LN0->getChain(),
   5613                                        LN0->getBasePtr(), N0.getValueType(),
   5614                                        LN0->getMemOperand());
   5615       CombineTo(N, ExtLoad);
   5616       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
   5617                                   N0.getValueType(), ExtLoad);
   5618       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
   5619       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
   5620                       ISD::SIGN_EXTEND);
   5621       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
   5622     }
   5623   }
   5624 
   5625   // fold (sext (load x)) to multiple smaller sextloads.
   5626   // Only on illegal but splittable vectors.
   5627   if (SDValue ExtLoad = CombineExtLoad(N))
   5628     return ExtLoad;
   5629 
   5630   // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
   5631   // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
   5632   if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
   5633       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
   5634     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
   5635     EVT MemVT = LN0->getMemoryVT();
   5636     if ((!LegalOperations && !LN0->isVolatile()) ||
   5637         TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, MemVT)) {
   5638       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
   5639                                        LN0->getChain(),
   5640                                        LN0->getBasePtr(), MemVT,
   5641                                        LN0->getMemOperand());
   5642       CombineTo(N, ExtLoad);
   5643       CombineTo(N0.getNode(),
   5644                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
   5645                             N0.getValueType(), ExtLoad),
   5646                 ExtLoad.getValue(1));
   5647       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
   5648     }
   5649   }
   5650 
   5651   // fold (sext (and/or/xor (load x), cst)) ->
   5652   //      (and/or/xor (sextload x), (sext cst))
   5653   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
   5654        N0.getOpcode() == ISD::XOR) &&
   5655       isa<LoadSDNode>(N0.getOperand(0)) &&
   5656       N0.getOperand(1).getOpcode() == ISD::Constant &&
   5657       TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()) &&
   5658       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
   5659     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
   5660     if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
   5661       bool DoXform = true;
   5662       SmallVector<SDNode*, 4> SetCCs;
   5663       if (!N0.hasOneUse())
   5664         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
   5665                                           SetCCs, TLI);
   5666       if (DoXform) {
   5667         SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
   5668                                          LN0->getChain(), LN0->getBasePtr(),
   5669                                          LN0->getMemoryVT(),
   5670                                          LN0->getMemOperand());
   5671         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
   5672         Mask = Mask.sext(VT.getSizeInBits());
   5673         SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
   5674                                   ExtLoad, DAG.getConstant(Mask, VT));
   5675         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
   5676                                     SDLoc(N0.getOperand(0)),
   5677                                     N0.getOperand(0).getValueType(), ExtLoad);
   5678         CombineTo(N, And);
   5679         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
   5680         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
   5681                         ISD::SIGN_EXTEND);
   5682         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
   5683       }
   5684     }
   5685   }
   5686 
   5687   if (N0.getOpcode() == ISD::SETCC) {
   5688     EVT N0VT = N0.getOperand(0).getValueType();
   5689     // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
   5690     // Only do this before legalize for now.
   5691     if (VT.isVector() && !LegalOperations &&
   5692         TLI.getBooleanContents(N0VT) ==
   5693             TargetLowering::ZeroOrNegativeOneBooleanContent) {
   5694       // On some architectures (such as SSE/NEON/etc) the SETCC result type is
   5695       // of the same size as the compared operands. Only optimize sext(setcc())
   5696       // if this is the case.
   5697       EVT SVT = getSetCCResultType(N0VT);
   5698 
   5699       // We know that the # elements of the results is the same as the
   5700       // # elements of the compare (and the # elements of the compare result
   5701       // for that matter).  Check to see that they are the same size.  If so,
   5702       // we know that the element size of the sext'd result matches the
   5703       // element size of the compare operands.
   5704       if (VT.getSizeInBits() == SVT.getSizeInBits())
   5705         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
   5706                              N0.getOperand(1),
   5707                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
   5708 
   5709       // If the desired elements are smaller or larger than the source
   5710       // elements we can use a matching integer vector type and then
   5711       // truncate/sign extend
   5712       EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
   5713       if (SVT == MatchingVectorType) {
   5714         SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
   5715                                N0.getOperand(0), N0.getOperand(1),
   5716                                cast<CondCodeSDNode>(N0.getOperand(2))->get());
   5717         return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
   5718       }
   5719     }
   5720 
   5721     // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
   5722     unsigned ElementWidth = VT.getScalarType().getSizeInBits();
   5723     SDValue NegOne =
   5724       DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT);
   5725     SDValue SCC =
   5726       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
   5727                        NegOne, DAG.getConstant(0, VT),
   5728                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
   5729     if (SCC.getNode()) return SCC;
   5730 
   5731     if (!VT.isVector()) {
   5732       EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
   5733       if (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, SetCCVT)) {
   5734         SDLoc DL(N);
   5735         ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
   5736         SDValue SetCC = DAG.getSetCC(DL, SetCCVT,
   5737                                      N0.getOperand(0), N0.getOperand(1), CC);
   5738         return DAG.getSelect(DL, VT, SetCC,
   5739                              NegOne, DAG.getConstant(0, VT));
   5740       }
   5741     }
   5742   }
   5743 
   5744   // fold (sext x) -> (zext x) if the sign bit is known zero.
   5745   if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
   5746       DAG.SignBitIsZero(N0))
   5747     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
   5748 
   5749   return SDValue();
   5750 }
   5751 
   5752 // isTruncateOf - If N is a truncate of some other value, return true, record
   5753 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
   5754 // This function computes KnownZero to avoid a duplicated call to
   5755 // computeKnownBits in the caller.
   5756 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
   5757                          APInt &KnownZero) {
   5758   APInt KnownOne;
   5759   if (N->getOpcode() == ISD::TRUNCATE) {
   5760     Op = N->getOperand(0);
   5761     DAG.computeKnownBits(Op, KnownZero, KnownOne);
   5762     return true;
   5763   }
   5764 
   5765   if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
   5766       cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
   5767     return false;
   5768 
   5769   SDValue Op0 = N->getOperand(0);
   5770   SDValue Op1 = N->getOperand(1);
   5771   assert(Op0.getValueType() == Op1.getValueType());
   5772 
   5773   ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0);
   5774   ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
   5775   if (COp0 && COp0->isNullValue())
   5776     Op = Op1;
   5777   else if (COp1 && COp1->isNullValue())
   5778     Op = Op0;
   5779   else
   5780     return false;
   5781 
   5782   DAG.computeKnownBits(Op, KnownZero, KnownOne);
   5783 
   5784   if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
   5785     return false;
   5786 
   5787   return true;
   5788 }
   5789 
   5790 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
   5791   SDValue N0 = N->getOperand(0);
   5792   EVT VT = N->getValueType(0);
   5793 
   5794   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
   5795                                               LegalOperations))
   5796     return SDValue(Res, 0);
   5797 
   5798   // fold (zext (zext x)) -> (zext x)
   5799   // fold (zext (aext x)) -> (zext x)
   5800   if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
   5801     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
   5802                        N0.getOperand(0));
   5803 
   5804   // fold (zext (truncate x)) -> (zext x) or
   5805   //      (zext (truncate x)) -> (truncate x)
   5806   // This is valid when the truncated bits of x are already zero.
   5807   // FIXME: We should extend this to work for vectors too.
   5808   SDValue Op;
   5809   APInt KnownZero;
   5810   if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
   5811     APInt TruncatedBits =
   5812       (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
   5813       APInt(Op.getValueSizeInBits(), 0) :
   5814       APInt::getBitsSet(Op.getValueSizeInBits(),
   5815                         N0.getValueSizeInBits(),
   5816                         std::min(Op.getValueSizeInBits(),
   5817                                  VT.getSizeInBits()));
   5818     if (TruncatedBits == (KnownZero & TruncatedBits)) {
   5819       if (VT.bitsGT(Op.getValueType()))
   5820         return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
   5821       if (VT.bitsLT(Op.getValueType()))
   5822         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
   5823 
   5824       return Op;
   5825     }
   5826   }
   5827 
   5828   // fold (zext (truncate (load x))) -> (zext (smaller load x))
   5829   // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
   5830   if (N0.getOpcode() == ISD::TRUNCATE) {
   5831     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
   5832     if (NarrowLoad.getNode()) {
   5833       SDNode* oye = N0.getNode()->getOperand(0).getNode();
   5834       if (NarrowLoad.getNode() != N0.getNode()) {
   5835         CombineTo(N0.getNode(), NarrowLoad);
   5836         // CombineTo deleted the truncate, if needed, but not what's under it.
   5837         AddToWorklist(oye);
   5838       }
   5839       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
   5840     }
   5841   }
   5842 
   5843   // fold (zext (truncate x)) -> (and x, mask)
   5844   if (N0.getOpcode() == ISD::TRUNCATE &&
   5845       (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
   5846 
   5847     // fold (zext (truncate (load x))) -> (zext (smaller load x))
   5848     // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
   5849     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
   5850     if (NarrowLoad.getNode()) {
   5851       SDNode* oye = N0.getNode()->getOperand(0).getNode();
   5852       if (NarrowLoad.getNode() != N0.getNode()) {
   5853         CombineTo(N0.getNode(), NarrowLoad);
   5854         // CombineTo deleted the truncate, if needed, but not what's under it.
   5855         AddToWorklist(oye);
   5856       }
   5857       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
   5858     }
   5859 
   5860     SDValue Op = N0.getOperand(0);
   5861     if (Op.getValueType().bitsLT(VT)) {
   5862       Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
   5863       AddToWorklist(Op.getNode());
   5864     } else if (Op.getValueType().bitsGT(VT)) {
   5865       Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
   5866       AddToWorklist(Op.getNode());
   5867     }
   5868     return DAG.getZeroExtendInReg(Op, SDLoc(N),
   5869                                   N0.getValueType().getScalarType());
   5870   }
   5871 
   5872   // Fold (zext (and (trunc x), cst)) -> (and x, cst),
   5873   // if either of the casts is not free.
   5874   if (N0.getOpcode() == ISD::AND &&
   5875       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
   5876       N0.getOperand(1).getOpcode() == ISD::Constant &&
   5877       (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
   5878                            N0.getValueType()) ||
   5879        !TLI.isZExtFree(N0.getValueType(), VT))) {
   5880     SDValue X = N0.getOperand(0).getOperand(0);
   5881     if (X.getValueType().bitsLT(VT)) {
   5882       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
   5883     } else if (X.getValueType().bitsGT(VT)) {
   5884       X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
   5885     }
   5886     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
   5887     Mask = Mask.zext(VT.getSizeInBits());
   5888     return DAG.getNode(ISD::AND, SDLoc(N), VT,
   5889                        X, DAG.getConstant(Mask, VT));
   5890   }
   5891 
   5892   // fold (zext (load x)) -> (zext (truncate (zextload x)))
   5893   // Only generate vector extloads when 1) they're legal, and 2) they are
   5894   // deemed desirable by the target.
   5895   if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
   5896       ((!LegalOperations && !VT.isVector() &&
   5897         !cast<LoadSDNode>(N0)->isVolatile()) ||
   5898        TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()))) {
   5899     bool DoXform = true;
   5900     SmallVector<SDNode*, 4> SetCCs;
   5901     if (!N0.hasOneUse())
   5902       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
   5903     if (VT.isVector())
   5904       DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
   5905     if (DoXform) {
   5906       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
   5907       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
   5908                                        LN0->getChain(),
   5909                                        LN0->getBasePtr(), N0.getValueType(),
   5910                                        LN0->getMemOperand());
   5911       CombineTo(N, ExtLoad);
   5912       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
   5913                                   N0.getValueType(), ExtLoad);
   5914       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
   5915 
   5916       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
   5917                       ISD::ZERO_EXTEND);
   5918       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
   5919     }
   5920   }
   5921 
   5922   // fold (zext (load x)) to multiple smaller zextloads.
   5923   // Only on illegal but splittable vectors.
   5924   if (SDValue ExtLoad = CombineExtLoad(N))
   5925     return ExtLoad;
   5926 
   5927   // fold (zext (and/or/xor (load x), cst)) ->
   5928   //      (and/or/xor (zextload x), (zext cst))
   5929   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
   5930        N0.getOpcode() == ISD::XOR) &&
   5931       isa<LoadSDNode>(N0.getOperand(0)) &&
   5932       N0.getOperand(1).getOpcode() == ISD::Constant &&
   5933       TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()) &&
   5934       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
   5935     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
   5936     if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
   5937       bool DoXform = true;
   5938       SmallVector<SDNode*, 4> SetCCs;
   5939       if (!N0.hasOneUse())
   5940         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
   5941                                           SetCCs, TLI);
   5942       if (DoXform) {
   5943         SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
   5944                                          LN0->getChain(), LN0->getBasePtr(),
   5945                                          LN0->getMemoryVT(),
   5946                                          LN0->getMemOperand());
   5947         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
   5948         Mask = Mask.zext(VT.getSizeInBits());
   5949         SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
   5950                                   ExtLoad, DAG.getConstant(Mask, VT));
   5951         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
   5952                                     SDLoc(N0.getOperand(0)),
   5953                                     N0.getOperand(0).getValueType(), ExtLoad);
   5954         CombineTo(N, And);
   5955         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
   5956         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
   5957                         ISD::ZERO_EXTEND);
   5958         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
   5959       }
   5960     }
   5961   }
   5962 
   5963   // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
   5964   // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
   5965   if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
   5966       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
   5967     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
   5968     EVT MemVT = LN0->getMemoryVT();
   5969     if ((!LegalOperations && !LN0->isVolatile()) ||
   5970         TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT)) {
   5971       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
   5972                                        LN0->getChain(),
   5973                                        LN0->getBasePtr(), MemVT,
   5974                                        LN0->getMemOperand());
   5975       CombineTo(N, ExtLoad);
   5976       CombineTo(N0.getNode(),
   5977                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
   5978                             ExtLoad),
   5979                 ExtLoad.getValue(1));
   5980       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
   5981     }
   5982   }
   5983 
   5984   if (N0.getOpcode() == ISD::SETCC) {
   5985     if (!LegalOperations && VT.isVector() &&
   5986         N0.getValueType().getVectorElementType() == MVT::i1) {
   5987       EVT N0VT = N0.getOperand(0).getValueType();
   5988       if (getSetCCResultType(N0VT) == N0.getValueType())
   5989         return SDValue();
   5990 
   5991       // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
   5992       // Only do this before legalize for now.
   5993       EVT EltVT = VT.getVectorElementType();
   5994       SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
   5995                                     DAG.getConstant(1, EltVT));
   5996       if (VT.getSizeInBits() == N0VT.getSizeInBits())
   5997         // We know that the # elements of the results is the same as the
   5998         // # elements of the compare (and the # elements of the compare result
   5999         // for that matter).  Check to see that they are the same size.  If so,
   6000         // we know that the element size of the sext'd result matches the
   6001         // element size of the compare operands.
   6002         return DAG.getNode(ISD::AND, SDLoc(N), VT,
   6003                            DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
   6004                                          N0.getOperand(1),
   6005                                  cast<CondCodeSDNode>(N0.getOperand(2))->get()),
   6006                            DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
   6007                                        OneOps));
   6008 
   6009       // If the desired elements are smaller or larger than the source
   6010       // elements we can use a matching integer vector type and then
   6011       // truncate/sign extend
   6012       EVT MatchingElementType =
   6013         EVT::getIntegerVT(*DAG.getContext(),
   6014                           N0VT.getScalarType().getSizeInBits());
   6015       EVT MatchingVectorType =
   6016         EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
   6017                          N0VT.getVectorNumElements());
   6018       SDValue VsetCC =
   6019         DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
   6020                       N0.getOperand(1),
   6021                       cast<CondCodeSDNode>(N0.getOperand(2))->get());
   6022       return DAG.getNode(ISD::AND, SDLoc(N), VT,
   6023                          DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT),
   6024                          DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, OneOps));
   6025     }
   6026 
   6027     // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
   6028     SDValue SCC =
   6029       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
   6030                        DAG.getConstant(1, VT), DAG.getConstant(0, VT),
   6031                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
   6032     if (SCC.getNode()) return SCC;
   6033   }
   6034 
   6035   // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
   6036   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
   6037       isa<ConstantSDNode>(N0.getOperand(1)) &&
   6038       N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
   6039       N0.hasOneUse()) {
   6040     SDValue ShAmt = N0.getOperand(1);
   6041     unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
   6042     if (N0.getOpcode() == ISD::SHL) {
   6043       SDValue InnerZExt = N0.getOperand(0);
   6044       // If the original shl may be shifting out bits, do not perform this
   6045       // transformation.
   6046       unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
   6047         InnerZExt.getOperand(0).getValueType().getSizeInBits();
   6048       if (ShAmtVal > KnownZeroBits)
   6049         return SDValue();
   6050     }
   6051 
   6052     SDLoc DL(N);
   6053 
   6054     // Ensure that the shift amount is wide enough for the shifted value.
   6055     if (VT.getSizeInBits() >= 256)
   6056       ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
   6057 
   6058     return DAG.getNode(N0.getOpcode(), DL, VT,
   6059                        DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
   6060                        ShAmt);
   6061   }
   6062 
   6063   return SDValue();
   6064 }
   6065 
   6066 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
   6067   SDValue N0 = N->getOperand(0);
   6068   EVT VT = N->getValueType(0);
   6069 
   6070   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
   6071                                               LegalOperations))
   6072     return SDValue(Res, 0);
   6073 
   6074   // fold (aext (aext x)) -> (aext x)
   6075   // fold (aext (zext x)) -> (zext x)
   6076   // fold (aext (sext x)) -> (sext x)
   6077   if (N0.getOpcode() == ISD::ANY_EXTEND  ||
   6078       N0.getOpcode() == ISD::ZERO_EXTEND ||
   6079       N0.getOpcode() == ISD::SIGN_EXTEND)
   6080     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
   6081 
   6082   // fold (aext (truncate (load x))) -> (aext (smaller load x))
   6083   // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
   6084   if (N0.getOpcode() == ISD::TRUNCATE) {
   6085     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
   6086     if (NarrowLoad.getNode()) {
   6087       SDNode* oye = N0.getNode()->getOperand(0).getNode();
   6088       if (NarrowLoad.getNode() != N0.getNode()) {
   6089         CombineTo(N0.getNode(), NarrowLoad);
   6090         // CombineTo deleted the truncate, if needed, but not what's under it.
   6091         AddToWorklist(oye);
   6092       }
   6093       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
   6094     }
   6095   }
   6096 
   6097   // fold (aext (truncate x))
   6098   if (N0.getOpcode() == ISD::TRUNCATE) {
   6099     SDValue TruncOp = N0.getOperand(0);
   6100     if (TruncOp.getValueType() == VT)
   6101       return TruncOp; // x iff x size == zext size.
   6102     if (TruncOp.getValueType().bitsGT(VT))
   6103       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
   6104     return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
   6105   }
   6106 
   6107   // Fold (aext (and (trunc x), cst)) -> (and x, cst)
   6108   // if the trunc is not free.
   6109   if (N0.getOpcode() == ISD::AND &&
   6110       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
   6111       N0.getOperand(1).getOpcode() == ISD::Constant &&
   6112       !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
   6113                           N0.getValueType())) {
   6114     SDValue X = N0.getOperand(0).getOperand(0);
   6115     if (X.getValueType().bitsLT(VT)) {
   6116       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
   6117     } else if (X.getValueType().bitsGT(VT)) {
   6118       X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
   6119     }
   6120     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
   6121     Mask = Mask.zext(VT.getSizeInBits());
   6122     return DAG.getNode(ISD::AND, SDLoc(N), VT,
   6123                        X, DAG.getConstant(Mask, VT));
   6124   }
   6125 
   6126   // fold (aext (load x)) -> (aext (truncate (extload x)))
   6127   // None of the supported targets knows how to perform load and any_ext
   6128   // on vectors in one instruction.  We only perform this transformation on
   6129   // scalars.
   6130   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
   6131       ISD::isUNINDEXEDLoad(N0.getNode()) &&
   6132       TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
   6133     bool DoXform = true;
   6134     SmallVector<SDNode*, 4> SetCCs;
   6135     if (!N0.hasOneUse())
   6136       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
   6137     if (DoXform) {
   6138       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
   6139       SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
   6140                                        LN0->getChain(),
   6141                                        LN0->getBasePtr(), N0.getValueType(),
   6142                                        LN0->getMemOperand());
   6143       CombineTo(N, ExtLoad);
   6144       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
   6145                                   N0.getValueType(), ExtLoad);
   6146       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
   6147       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
   6148                       ISD::ANY_EXTEND);
   6149       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
   6150     }
   6151   }
   6152 
   6153   // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
   6154   // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
   6155   // fold (aext ( extload x)) -> (aext (truncate (extload  x)))
   6156   if (N0.getOpcode() == ISD::LOAD &&
   6157       !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
   6158       N0.hasOneUse()) {
   6159     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
   6160     ISD::LoadExtType ExtType = LN0->getExtensionType();
   6161     EVT MemVT = LN0->getMemoryVT();
   6162     if (!LegalOperations || TLI.isLoadExtLegal(ExtType, VT, MemVT)) {
   6163       SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
   6164                                        VT, LN0->getChain(), LN0->getBasePtr(),
   6165                                        MemVT, LN0->getMemOperand());
   6166       CombineTo(N, ExtLoad);
   6167       CombineTo(N0.getNode(),
   6168                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
   6169                             N0.getValueType(), ExtLoad),
   6170                 ExtLoad.getValue(1));
   6171       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
   6172     }
   6173   }
   6174 
   6175   if (N0.getOpcode() == ISD::SETCC) {
   6176     // For vectors:
   6177     // aext(setcc) -> vsetcc
   6178     // aext(setcc) -> truncate(vsetcc)
   6179     // aext(setcc) -> aext(vsetcc)
   6180     // Only do this before legalize for now.
   6181     if (VT.isVector() && !LegalOperations) {
   6182       EVT N0VT = N0.getOperand(0).getValueType();
   6183         // We know that the # elements of the results is the same as the
   6184         // # elements of the compare (and the # elements of the compare result
   6185         // for that matter).  Check to see that they are the same size.  If so,
   6186         // we know that the element size of the sext'd result matches the
   6187         // element size of the compare operands.
   6188       if (VT.getSizeInBits() == N0VT.getSizeInBits())
   6189         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
   6190                              N0.getOperand(1),
   6191                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
   6192       // If the desired elements are smaller or larger than the source
   6193       // elements we can use a matching integer vector type and then
   6194       // truncate/any extend
   6195       else {
   6196         EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
   6197         SDValue VsetCC =
   6198           DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
   6199                         N0.getOperand(1),
   6200                         cast<CondCodeSDNode>(N0.getOperand(2))->get());
   6201         return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
   6202       }
   6203     }
   6204 
   6205     // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
   6206     SDValue SCC =
   6207       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
   6208                        DAG.getConstant(1, VT), DAG.getConstant(0, VT),
   6209                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
   6210     if (SCC.getNode())
   6211       return SCC;
   6212   }
   6213 
   6214   return SDValue();
   6215 }
   6216 
   6217 /// See if the specified operand can be simplified with the knowledge that only
   6218 /// the bits specified by Mask are used.  If so, return the simpler operand,
   6219 /// otherwise return a null SDValue.
   6220 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
   6221   switch (V.getOpcode()) {
   6222   default: break;
   6223   case ISD::Constant: {
   6224     const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
   6225     assert(CV && "Const value should be ConstSDNode.");
   6226     const APInt &CVal = CV->getAPIntValue();
   6227     APInt NewVal = CVal & Mask;
   6228     if (NewVal != CVal)
   6229       return DAG.getConstant(NewVal, V.getValueType());
   6230     break;
   6231   }
   6232   case ISD::OR:
   6233   case ISD::XOR:
   6234     // If the LHS or RHS don't contribute bits to the or, drop them.
   6235     if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
   6236       return V.getOperand(1);
   6237     if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
   6238       return V.getOperand(0);
   6239     break;
   6240   case ISD::SRL:
   6241     // Only look at single-use SRLs.
   6242     if (!V.getNode()->hasOneUse())
   6243       break;
   6244     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
   6245       // See if we can recursively simplify the LHS.
   6246       unsigned Amt = RHSC->getZExtValue();
   6247 
   6248       // Watch out for shift count overflow though.
   6249       if (Amt >= Mask.getBitWidth()) break;
   6250       APInt NewMask = Mask << Amt;
   6251       SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
   6252       if (SimplifyLHS.getNode())
   6253         return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
   6254                            SimplifyLHS, V.getOperand(1));
   6255     }
   6256   }
   6257   return SDValue();
   6258 }
   6259 
   6260 /// If the result of a wider load is shifted to right of N  bits and then
   6261 /// truncated to a narrower type and where N is a multiple of number of bits of
   6262 /// the narrower type, transform it to a narrower load from address + N / num of
   6263 /// bits of new type. If the result is to be extended, also fold the extension
   6264 /// to form a extending load.
   6265 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
   6266   unsigned Opc = N->getOpcode();
   6267 
   6268   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
   6269   SDValue N0 = N->getOperand(0);
   6270   EVT VT = N->getValueType(0);
   6271   EVT ExtVT = VT;
   6272 
   6273   // This transformation isn't valid for vector loads.
   6274   if (VT.isVector())
   6275     return SDValue();
   6276 
   6277   // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
   6278   // extended to VT.
   6279   if (Opc == ISD::SIGN_EXTEND_INREG) {
   6280     ExtType = ISD::SEXTLOAD;
   6281     ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
   6282   } else if (Opc == ISD::SRL) {
   6283     // Another special-case: SRL is basically zero-extending a narrower value.
   6284     ExtType = ISD::ZEXTLOAD;
   6285     N0 = SDValue(N, 0);
   6286     ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
   6287     if (!N01) return SDValue();
   6288     ExtVT = EVT::getIntegerVT(*DAG.getContext(),
   6289                               VT.getSizeInBits() - N01->getZExtValue());
   6290   }
   6291   if (LegalOperations && !TLI.isLoadExtLegal(ExtType, VT, ExtVT))
   6292     return SDValue();
   6293 
   6294   unsigned EVTBits = ExtVT.getSizeInBits();
   6295 
   6296   // Do not generate loads of non-round integer types since these can
   6297   // be expensive (and would be wrong if the type is not byte sized).
   6298   if (!ExtVT.isRound())
   6299     return SDValue();
   6300 
   6301   unsigned ShAmt = 0;
   6302   if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
   6303     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
   6304       ShAmt = N01->getZExtValue();
   6305       // Is the shift amount a multiple of size of VT?
   6306       if ((ShAmt & (EVTBits-1)) == 0) {
   6307         N0 = N0.getOperand(0);
   6308         // Is the load width a multiple of size of VT?
   6309         if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
   6310           return SDValue();
   6311       }
   6312 
   6313       // At this point, we must have a load or else we can't do the transform.
   6314       if (!isa<LoadSDNode>(N0)) return SDValue();
   6315 
   6316       // Because a SRL must be assumed to *need* to zero-extend the high bits
   6317       // (as opposed to anyext the high bits), we can't combine the zextload
   6318       // lowering of SRL and an sextload.
   6319       if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
   6320         return SDValue();
   6321 
   6322       // If the shift amount is larger than the input type then we're not
   6323       // accessing any of the loaded bytes.  If the load was a zextload/extload
   6324       // then the result of the shift+trunc is zero/undef (handled elsewhere).
   6325       if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
   6326         return SDValue();
   6327     }
   6328   }
   6329 
   6330   // If the load is shifted left (and the result isn't shifted back right),
   6331   // we can fold the truncate through the shift.
   6332   unsigned ShLeftAmt = 0;
   6333   if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
   6334       ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
   6335     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
   6336       ShLeftAmt = N01->getZExtValue();
   6337       N0 = N0.getOperand(0);
   6338     }
   6339   }
   6340 
   6341   // If we haven't found a load, we can't narrow it.  Don't transform one with
   6342   // multiple uses, this would require adding a new load.
   6343   if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
   6344     return SDValue();
   6345 
   6346   // Don't change the width of a volatile load.
   6347   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
   6348   if (LN0->isVolatile())
   6349     return SDValue();
   6350 
   6351   // Verify that we are actually reducing a load width here.
   6352   if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
   6353     return SDValue();
   6354 
   6355   // For the transform to be legal, the load must produce only two values
   6356   // (the value loaded and the chain).  Don't transform a pre-increment
   6357   // load, for example, which produces an extra value.  Otherwise the
   6358   // transformation is not equivalent, and the downstream logic to replace
   6359   // uses gets things wrong.
   6360   if (LN0->getNumValues() > 2)
   6361     return SDValue();
   6362 
   6363   // If the load that we're shrinking is an extload and we're not just
   6364   // discarding the extension we can't simply shrink the load. Bail.
   6365   // TODO: It would be possible to merge the extensions in some cases.
   6366   if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
   6367       LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
   6368     return SDValue();
   6369 
   6370   if (!TLI.shouldReduceLoadWidth(LN0, ExtType, ExtVT))
   6371     return SDValue();
   6372 
   6373   EVT PtrType = N0.getOperand(1).getValueType();
   6374 
   6375   if (PtrType == MVT::Untyped || PtrType.isExtended())
   6376     // It's not possible to generate a constant of extended or untyped type.
   6377     return SDValue();
   6378 
   6379   // For big endian targets, we need to adjust the offset to the pointer to
   6380   // load the correct bytes.
   6381   if (TLI.isBigEndian()) {
   6382     unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
   6383     unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
   6384     ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
   6385   }
   6386 
   6387   uint64_t PtrOff = ShAmt / 8;
   6388   unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
   6389   SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0),
   6390                                PtrType, LN0->getBasePtr(),
   6391                                DAG.getConstant(PtrOff, PtrType));
   6392   AddToWorklist(NewPtr.getNode());
   6393 
   6394   SDValue Load;
   6395   if (ExtType == ISD::NON_EXTLOAD)
   6396     Load =  DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
   6397                         LN0->getPointerInfo().getWithOffset(PtrOff),
   6398                         LN0->isVolatile(), LN0->isNonTemporal(),
   6399                         LN0->isInvariant(), NewAlign, LN0->getAAInfo());
   6400   else
   6401     Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
   6402                           LN0->getPointerInfo().getWithOffset(PtrOff),
   6403                           ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
   6404                           LN0->isInvariant(), NewAlign, LN0->getAAInfo());
   6405 
   6406   // Replace the old load's chain with the new load's chain.
   6407   WorklistRemover DeadNodes(*this);
   6408   DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
   6409 
   6410   // Shift the result left, if we've swallowed a left shift.
   6411   SDValue Result = Load;
   6412   if (ShLeftAmt != 0) {
   6413     EVT ShImmTy = getShiftAmountTy(Result.getValueType());
   6414     if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
   6415       ShImmTy = VT;
   6416     // If the shift amount is as large as the result size (but, presumably,
   6417     // no larger than the source) then the useful bits of the result are
   6418     // zero; we can't simply return the shortened shift, because the result
   6419     // of that operation is undefined.
   6420     if (ShLeftAmt >= VT.getSizeInBits())
   6421       Result = DAG.getConstant(0, VT);
   6422     else
   6423       Result = DAG.getNode(ISD::SHL, SDLoc(N0), VT,
   6424                           Result, DAG.getConstant(ShLeftAmt, ShImmTy));
   6425   }
   6426 
   6427   // Return the new loaded value.
   6428   return Result;
   6429 }
   6430 
   6431 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
   6432   SDValue N0 = N->getOperand(0);
   6433   SDValue N1 = N->getOperand(1);
   6434   EVT VT = N->getValueType(0);
   6435   EVT EVT = cast<VTSDNode>(N1)->getVT();
   6436   unsigned VTBits = VT.getScalarType().getSizeInBits();
   6437   unsigned EVTBits = EVT.getScalarType().getSizeInBits();
   6438 
   6439   // fold (sext_in_reg c1) -> c1
   6440   if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
   6441     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
   6442 
   6443   // If the input is already sign extended, just drop the extension.
   6444   if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
   6445     return N0;
   6446 
   6447   // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
   6448   if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
   6449       EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
   6450     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
   6451                        N0.getOperand(0), N1);
   6452 
   6453   // fold (sext_in_reg (sext x)) -> (sext x)
   6454   // fold (sext_in_reg (aext x)) -> (sext x)
   6455   // if x is small enough.
   6456   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
   6457     SDValue N00 = N0.getOperand(0);
   6458     if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
   6459         (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
   6460       return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
   6461   }
   6462 
   6463   // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
   6464   if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
   6465     return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
   6466 
   6467   // fold operands of sext_in_reg based on knowledge that the top bits are not
   6468   // demanded.
   6469   if (SimplifyDemandedBits(SDValue(N, 0)))
   6470     return SDValue(N, 0);
   6471 
   6472   // fold (sext_in_reg (load x)) -> (smaller sextload x)
   6473   // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
   6474   SDValue NarrowLoad = ReduceLoadWidth(N);
   6475   if (NarrowLoad.getNode())
   6476     return NarrowLoad;
   6477 
   6478   // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
   6479   // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
   6480   // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
   6481   if (N0.getOpcode() == ISD::SRL) {
   6482     if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
   6483       if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
   6484         // We can turn this into an SRA iff the input to the SRL is already sign
   6485         // extended enough.
   6486         unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
   6487         if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
   6488           return DAG.getNode(ISD::SRA, SDLoc(N), VT,
   6489                              N0.getOperand(0), N0.getOperand(1));
   6490       }
   6491   }
   6492 
   6493   // fold (sext_inreg (extload x)) -> (sextload x)
   6494   if (ISD::isEXTLoad(N0.getNode()) &&
   6495       ISD::isUNINDEXEDLoad(N0.getNode()) &&
   6496       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
   6497       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
   6498        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
   6499     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
   6500     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
   6501                                      LN0->getChain(),
   6502                                      LN0->getBasePtr(), EVT,
   6503                                      LN0->getMemOperand());
   6504     CombineTo(N, ExtLoad);
   6505     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
   6506     AddToWorklist(ExtLoad.getNode());
   6507     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
   6508   }
   6509   // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
   6510   if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
   6511       N0.hasOneUse() &&
   6512       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
   6513       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
   6514        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
   6515     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
   6516     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
   6517                                      LN0->getChain(),
   6518                                      LN0->getBasePtr(), EVT,
   6519                                      LN0->getMemOperand());
   6520     CombineTo(N, ExtLoad);
   6521     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
   6522     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
   6523   }
   6524 
   6525   // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
   6526   if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
   6527     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
   6528                                        N0.getOperand(1), false);
   6529     if (BSwap.getNode())
   6530       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
   6531                          BSwap, N1);
   6532   }
   6533 
   6534   // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs
   6535   // into a build_vector.
   6536   if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
   6537     SmallVector<SDValue, 8> Elts;
   6538     unsigned NumElts = N0->getNumOperands();
   6539     unsigned ShAmt = VTBits - EVTBits;
   6540 
   6541     for (unsigned i = 0; i != NumElts; ++i) {
   6542       SDValue Op = N0->getOperand(i);
   6543       if (Op->getOpcode() == ISD::UNDEF) {
   6544         Elts.push_back(Op);
   6545         continue;
   6546       }
   6547 
   6548       ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
   6549       const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
   6550       Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
   6551                                      Op.getValueType()));
   6552     }
   6553 
   6554     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Elts);
   6555   }
   6556 
   6557   return SDValue();
   6558 }
   6559 
   6560 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
   6561   SDValue N0 = N->getOperand(0);
   6562   EVT VT = N->getValueType(0);
   6563   bool isLE = TLI.isLittleEndian();
   6564 
   6565   // noop truncate
   6566   if (N0.getValueType() == N->getValueType(0))
   6567     return N0;
   6568   // fold (truncate c1) -> c1
   6569   if (isConstantIntBuildVectorOrConstantInt(N0))
   6570     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
   6571   // fold (truncate (truncate x)) -> (truncate x)
   6572   if (N0.getOpcode() == ISD::TRUNCATE)
   6573     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
   6574   // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
   6575   if (N0.getOpcode() == ISD::ZERO_EXTEND ||
   6576       N0.getOpcode() == ISD::SIGN_EXTEND ||
   6577       N0.getOpcode() == ISD::ANY_EXTEND) {
   6578     if (N0.getOperand(0).getValueType().bitsLT(VT))
   6579       // if the source is smaller than the dest, we still need an extend
   6580       return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
   6581                          N0.getOperand(0));
   6582     if (N0.getOperand(0).getValueType().bitsGT(VT))
   6583       // if the source is larger than the dest, than we just need the truncate
   6584       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
   6585     // if the source and dest are the same type, we can drop both the extend
   6586     // and the truncate.
   6587     return N0.getOperand(0);
   6588   }
   6589 
   6590   // Fold extract-and-trunc into a narrow extract. For example:
   6591   //   i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
   6592   //   i32 y = TRUNCATE(i64 x)
   6593   //        -- becomes --
   6594   //   v16i8 b = BITCAST (v2i64 val)
   6595   //   i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
   6596   //
   6597   // Note: We only run this optimization after type legalization (which often
   6598   // creates this pattern) and before operation legalization after which
   6599   // we need to be more careful about the vector instructions that we generate.
   6600   if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
   6601       LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
   6602 
   6603     EVT VecTy = N0.getOperand(0).getValueType();
   6604     EVT ExTy = N0.getValueType();
   6605     EVT TrTy = N->getValueType(0);
   6606 
   6607     unsigned NumElem = VecTy.getVectorNumElements();
   6608     unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
   6609 
   6610     EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
   6611     assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
   6612 
   6613     SDValue EltNo = N0->getOperand(1);
   6614     if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
   6615       int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
   6616       EVT IndexTy = TLI.getVectorIdxTy();
   6617       int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
   6618 
   6619       SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
   6620                               NVT, N0.getOperand(0));
   6621 
   6622       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
   6623                          SDLoc(N), TrTy, V,
   6624                          DAG.getConstant(Index, IndexTy));
   6625     }
   6626   }
   6627 
   6628   // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
   6629   if (N0.getOpcode() == ISD::SELECT) {
   6630     EVT SrcVT = N0.getValueType();
   6631     if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
   6632         TLI.isTruncateFree(SrcVT, VT)) {
   6633       SDLoc SL(N0);
   6634       SDValue Cond = N0.getOperand(0);
   6635       SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
   6636       SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
   6637       return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
   6638     }
   6639   }
   6640 
   6641   // Fold a series of buildvector, bitcast, and truncate if possible.
   6642   // For example fold
   6643   //   (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
   6644   //   (2xi32 (buildvector x, y)).
   6645   if (Level == AfterLegalizeVectorOps && VT.isVector() &&
   6646       N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
   6647       N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
   6648       N0.getOperand(0).hasOneUse()) {
   6649 
   6650     SDValue BuildVect = N0.getOperand(0);
   6651     EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
   6652     EVT TruncVecEltTy = VT.getVectorElementType();
   6653 
   6654     // Check that the element types match.
   6655     if (BuildVectEltTy == TruncVecEltTy) {
   6656       // Now we only need to compute the offset of the truncated elements.
   6657       unsigned BuildVecNumElts =  BuildVect.getNumOperands();
   6658       unsigned TruncVecNumElts = VT.getVectorNumElements();
   6659       unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
   6660 
   6661       assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
   6662              "Invalid number of elements");
   6663 
   6664       SmallVector<SDValue, 8> Opnds;
   6665       for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
   6666         Opnds.push_back(BuildVect.getOperand(i));
   6667 
   6668       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
   6669     }
   6670   }
   6671 
   6672   // See if we can simplify the input to this truncate through knowledge that
   6673   // only the low bits are being used.
   6674   // For example "trunc (or (shl x, 8), y)" // -> trunc y
   6675   // Currently we only perform this optimization on scalars because vectors
   6676   // may have different active low bits.
   6677   if (!VT.isVector()) {
   6678     SDValue Shorter =
   6679       GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
   6680                                                VT.getSizeInBits()));
   6681     if (Shorter.getNode())
   6682       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
   6683   }
   6684   // fold (truncate (load x)) -> (smaller load x)
   6685   // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
   6686   if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
   6687     SDValue Reduced = ReduceLoadWidth(N);
   6688     if (Reduced.getNode())
   6689       return Reduced;
   6690     // Handle the case where the load remains an extending load even
   6691     // after truncation.
   6692     if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
   6693       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
   6694       if (!LN0->isVolatile() &&
   6695           LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
   6696         SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
   6697                                          VT, LN0->getChain(), LN0->getBasePtr(),
   6698                                          LN0->getMemoryVT(),
   6699                                          LN0->getMemOperand());
   6700         DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
   6701         return NewLoad;
   6702       }
   6703     }
   6704   }
   6705   // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
   6706   // where ... are all 'undef'.
   6707   if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
   6708     SmallVector<EVT, 8> VTs;
   6709     SDValue V;
   6710     unsigned Idx = 0;
   6711     unsigned NumDefs = 0;
   6712 
   6713     for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
   6714       SDValue X = N0.getOperand(i);
   6715       if (X.getOpcode() != ISD::UNDEF) {
   6716         V = X;
   6717         Idx = i;
   6718         NumDefs++;
   6719       }
   6720       // Stop if more than one members are non-undef.
   6721       if (NumDefs > 1)
   6722         break;
   6723       VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
   6724                                      VT.getVectorElementType(),
   6725                                      X.getValueType().getVectorNumElements()));
   6726     }
   6727 
   6728     if (NumDefs == 0)
   6729       return DAG.getUNDEF(VT);
   6730 
   6731     if (NumDefs == 1) {
   6732       assert(V.getNode() && "The single defined operand is empty!");
   6733       SmallVector<SDValue, 8> Opnds;
   6734       for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
   6735         if (i != Idx) {
   6736           Opnds.push_back(DAG.getUNDEF(VTs[i]));
   6737           continue;
   6738         }
   6739         SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
   6740         AddToWorklist(NV.getNode());
   6741         Opnds.push_back(NV);
   6742       }
   6743       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
   6744     }
   6745   }
   6746 
   6747   // Simplify the operands using demanded-bits information.
   6748   if (!VT.isVector() &&
   6749       SimplifyDemandedBits(SDValue(N, 0)))
   6750     return SDValue(N, 0);
   6751 
   6752   return SDValue();
   6753 }
   6754 
   6755 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
   6756   SDValue Elt = N->getOperand(i);
   6757   if (Elt.getOpcode() != ISD::MERGE_VALUES)
   6758     return Elt.getNode();
   6759   return Elt.getOperand(Elt.getResNo()).getNode();
   6760 }
   6761 
   6762 /// build_pair (load, load) -> load
   6763 /// if load locations are consecutive.
   6764 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
   6765   assert(N->getOpcode() == ISD::BUILD_PAIR);
   6766 
   6767   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
   6768   LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
   6769   if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
   6770       LD1->getAddressSpace() != LD2->getAddressSpace())
   6771     return SDValue();
   6772   EVT LD1VT = LD1->getValueType(0);
   6773 
   6774   if (ISD::isNON_EXTLoad(LD2) &&
   6775       LD2->hasOneUse() &&
   6776       // If both are volatile this would reduce the number of volatile loads.
   6777       // If one is volatile it might be ok, but play conservative and bail out.
   6778       !LD1->isVolatile() &&
   6779       !LD2->isVolatile() &&
   6780       DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
   6781     unsigned Align = LD1->getAlignment();
   6782     unsigned NewAlign = TLI.getDataLayout()->
   6783       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
   6784 
   6785     if (NewAlign <= Align &&
   6786         (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
   6787       return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
   6788                          LD1->getBasePtr(), LD1->getPointerInfo(),
   6789                          false, false, false, Align);
   6790   }
   6791 
   6792   return SDValue();
   6793 }
   6794 
   6795 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
   6796   SDValue N0 = N->getOperand(0);
   6797   EVT VT = N->getValueType(0);
   6798 
   6799   // If the input is a BUILD_VECTOR with all constant elements, fold this now.
   6800   // Only do this before legalize, since afterward the target may be depending
   6801   // on the bitconvert.
   6802   // First check to see if this is all constant.
   6803   if (!LegalTypes &&
   6804       N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
   6805       VT.isVector()) {
   6806     bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
   6807 
   6808     EVT DestEltVT = N->getValueType(0).getVectorElementType();
   6809     assert(!DestEltVT.isVector() &&
   6810            "Element type of vector ValueType must not be vector!");
   6811     if (isSimple)
   6812       return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
   6813   }
   6814 
   6815   // If the input is a constant, let getNode fold it.
   6816   if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
   6817     // If we can't allow illegal operations, we need to check that this is just
   6818     // a fp -> int or int -> conversion and that the resulting operation will
   6819     // be legal.
   6820     if (!LegalOperations ||
   6821         (isa<ConstantSDNode>(N0) && VT.isFloatingPoint() && !VT.isVector() &&
   6822          TLI.isOperationLegal(ISD::ConstantFP, VT)) ||
   6823         (isa<ConstantFPSDNode>(N0) && VT.isInteger() && !VT.isVector() &&
   6824          TLI.isOperationLegal(ISD::Constant, VT)))
   6825       return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
   6826   }
   6827 
   6828   // (conv (conv x, t1), t2) -> (conv x, t2)
   6829   if (N0.getOpcode() == ISD::BITCAST)
   6830     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
   6831                        N0.getOperand(0));
   6832 
   6833   // fold (conv (load x)) -> (load (conv*)x)
   6834   // If the resultant load doesn't need a higher alignment than the original!
   6835   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
   6836       // Do not change the width of a volatile load.
   6837       !cast<LoadSDNode>(N0)->isVolatile() &&
   6838       // Do not remove the cast if the types differ in endian layout.
   6839       TLI.hasBigEndianPartOrdering(N0.getValueType()) ==
   6840       TLI.hasBigEndianPartOrdering(VT) &&
   6841       (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
   6842       TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
   6843     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
   6844     unsigned Align = TLI.getDataLayout()->
   6845       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
   6846     unsigned OrigAlign = LN0->getAlignment();
   6847 
   6848     if (Align <= OrigAlign) {
   6849       SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
   6850                                  LN0->getBasePtr(), LN0->getPointerInfo(),
   6851                                  LN0->isVolatile(), LN0->isNonTemporal(),
   6852                                  LN0->isInvariant(), OrigAlign,
   6853                                  LN0->getAAInfo());
   6854       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
   6855       return Load;
   6856     }
   6857   }
   6858 
   6859   // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
   6860   // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
   6861   // This often reduces constant pool loads.
   6862   if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
   6863        (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
   6864       N0.getNode()->hasOneUse() && VT.isInteger() &&
   6865       !VT.isVector() && !N0.getValueType().isVector()) {
   6866     SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
   6867                                   N0.getOperand(0));
   6868     AddToWorklist(NewConv.getNode());
   6869 
   6870     APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
   6871     if (N0.getOpcode() == ISD::FNEG)
   6872       return DAG.getNode(ISD::XOR, SDLoc(N), VT,
   6873                          NewConv, DAG.getConstant(SignBit, VT));
   6874     assert(N0.getOpcode() == ISD::FABS);
   6875     return DAG.getNode(ISD::AND, SDLoc(N), VT,
   6876                        NewConv, DAG.getConstant(~SignBit, VT));
   6877   }
   6878 
   6879   // fold (bitconvert (fcopysign cst, x)) ->
   6880   //         (or (and (bitconvert x), sign), (and cst, (not sign)))
   6881   // Note that we don't handle (copysign x, cst) because this can always be
   6882   // folded to an fneg or fabs.
   6883   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
   6884       isa<ConstantFPSDNode>(N0.getOperand(0)) &&
   6885       VT.isInteger() && !VT.isVector()) {
   6886     unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
   6887     EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
   6888     if (isTypeLegal(IntXVT)) {
   6889       SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
   6890                               IntXVT, N0.getOperand(1));
   6891       AddToWorklist(X.getNode());
   6892 
   6893       // If X has a different width than the result/lhs, sext it or truncate it.
   6894       unsigned VTWidth = VT.getSizeInBits();
   6895       if (OrigXWidth < VTWidth) {
   6896         X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
   6897         AddToWorklist(X.getNode());
   6898       } else if (OrigXWidth > VTWidth) {
   6899         // To get the sign bit in the right place, we have to shift it right
   6900         // before truncating.
   6901         X = DAG.getNode(ISD::SRL, SDLoc(X),
   6902                         X.getValueType(), X,
   6903                         DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
   6904         AddToWorklist(X.getNode());
   6905         X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
   6906         AddToWorklist(X.getNode());
   6907       }
   6908 
   6909       APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
   6910       X = DAG.getNode(ISD::AND, SDLoc(X), VT,
   6911                       X, DAG.getConstant(SignBit, VT));
   6912       AddToWorklist(X.getNode());
   6913 
   6914       SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
   6915                                 VT, N0.getOperand(0));
   6916       Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
   6917                         Cst, DAG.getConstant(~SignBit, VT));
   6918       AddToWorklist(Cst.getNode());
   6919 
   6920       return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
   6921     }
   6922   }
   6923 
   6924   // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
   6925   if (N0.getOpcode() == ISD::BUILD_PAIR) {
   6926     SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
   6927     if (CombineLD.getNode())
   6928       return CombineLD;
   6929   }
   6930 
   6931   return SDValue();
   6932 }
   6933 
   6934 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
   6935   EVT VT = N->getValueType(0);
   6936   return CombineConsecutiveLoads(N, VT);
   6937 }
   6938 
   6939 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef
   6940 /// operands. DstEltVT indicates the destination element value type.
   6941 SDValue DAGCombiner::
   6942 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
   6943   EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
   6944 
   6945   // If this is already the right type, we're done.
   6946   if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
   6947 
   6948   unsigned SrcBitSize = SrcEltVT.getSizeInBits();
   6949   unsigned DstBitSize = DstEltVT.getSizeInBits();
   6950 
   6951   // If this is a conversion of N elements of one type to N elements of another
   6952   // type, convert each element.  This handles FP<->INT cases.
   6953   if (SrcBitSize == DstBitSize) {
   6954     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
   6955                               BV->getValueType(0).getVectorNumElements());
   6956 
   6957     // Due to the FP element handling below calling this routine recursively,
   6958     // we can end up with a scalar-to-vector node here.
   6959     if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
   6960       return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
   6961                          DAG.getNode(ISD::BITCAST, SDLoc(BV),
   6962                                      DstEltVT, BV->getOperand(0)));
   6963 
   6964     SmallVector<SDValue, 8> Ops;
   6965     for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
   6966       SDValue Op = BV->getOperand(i);
   6967       // If the vector element type is not legal, the BUILD_VECTOR operands
   6968       // are promoted and implicitly truncated.  Make that explicit here.
   6969       if (Op.getValueType() != SrcEltVT)
   6970         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
   6971       Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
   6972                                 DstEltVT, Op));
   6973       AddToWorklist(Ops.back().getNode());
   6974     }
   6975     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
   6976   }
   6977 
   6978   // Otherwise, we're growing or shrinking the elements.  To avoid having to
   6979   // handle annoying details of growing/shrinking FP values, we convert them to
   6980   // int first.
   6981   if (SrcEltVT.isFloatingPoint()) {
   6982     // Convert the input float vector to a int vector where the elements are the
   6983     // same sizes.
   6984     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
   6985     BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
   6986     SrcEltVT = IntVT;
   6987   }
   6988 
   6989   // Now we know the input is an integer vector.  If the output is a FP type,
   6990   // convert to integer first, then to FP of the right size.
   6991   if (DstEltVT.isFloatingPoint()) {
   6992     EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
   6993     SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
   6994 
   6995     // Next, convert to FP elements of the same size.
   6996     return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
   6997   }
   6998 
   6999   // Okay, we know the src/dst types are both integers of differing types.
   7000   // Handling growing first.
   7001   assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
   7002   if (SrcBitSize < DstBitSize) {
   7003     unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
   7004 
   7005     SmallVector<SDValue, 8> Ops;
   7006     for (unsigned i = 0, e = BV->getNumOperands(); i != e;
   7007          i += NumInputsPerOutput) {
   7008       bool isLE = TLI.isLittleEndian();
   7009       APInt NewBits = APInt(DstBitSize, 0);
   7010       bool EltIsUndef = true;
   7011       for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
   7012         // Shift the previously computed bits over.
   7013         NewBits <<= SrcBitSize;
   7014         SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
   7015         if (Op.getOpcode() == ISD::UNDEF) continue;
   7016         EltIsUndef = false;
   7017 
   7018         NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
   7019                    zextOrTrunc(SrcBitSize).zext(DstBitSize);
   7020       }
   7021 
   7022       if (EltIsUndef)
   7023         Ops.push_back(DAG.getUNDEF(DstEltVT));
   7024       else
   7025         Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
   7026     }
   7027 
   7028     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
   7029     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
   7030   }
   7031 
   7032   // Finally, this must be the case where we are shrinking elements: each input
   7033   // turns into multiple outputs.
   7034   unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
   7035   EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
   7036                             NumOutputsPerInput*BV->getNumOperands());
   7037   SmallVector<SDValue, 8> Ops;
   7038 
   7039   for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
   7040     if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
   7041       Ops.append(NumOutputsPerInput, DAG.getUNDEF(DstEltVT));
   7042       continue;
   7043     }
   7044 
   7045     APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
   7046                   getAPIntValue().zextOrTrunc(SrcBitSize);
   7047 
   7048     for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
   7049       APInt ThisVal = OpVal.trunc(DstBitSize);
   7050       Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
   7051       OpVal = OpVal.lshr(DstBitSize);
   7052     }
   7053 
   7054     // For big endian targets, swap the order of the pieces of each element.
   7055     if (TLI.isBigEndian())
   7056       std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
   7057   }
   7058 
   7059   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
   7060 }
   7061 
   7062 // Attempt different variants of (fadd (fmul a, b), c) -> fma or fmad
   7063 static SDValue performFaddFmulCombines(unsigned FusedOpcode,
   7064                                        bool Aggressive,
   7065                                        SDNode *N,
   7066                                        const TargetLowering &TLI,
   7067                                        SelectionDAG &DAG) {
   7068   SDValue N0 = N->getOperand(0);
   7069   SDValue N1 = N->getOperand(1);
   7070   EVT VT = N->getValueType(0);
   7071 
   7072   // fold (fadd (fmul x, y), z) -> (fma x, y, z)
   7073   if (N0.getOpcode() == ISD::FMUL &&
   7074       (Aggressive || N0->hasOneUse())) {
   7075     return DAG.getNode(FusedOpcode, SDLoc(N), VT,
   7076                        N0.getOperand(0), N0.getOperand(1), N1);
   7077   }
   7078 
   7079   // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
   7080   // Note: Commutes FADD operands.
   7081   if (N1.getOpcode() == ISD::FMUL &&
   7082       (Aggressive || N1->hasOneUse())) {
   7083     return DAG.getNode(FusedOpcode, SDLoc(N), VT,
   7084                        N1.getOperand(0), N1.getOperand(1), N0);
   7085   }
   7086 
   7087   // More folding opportunities when target permits.
   7088   if (Aggressive) {
   7089     // fold (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y (fma u, v, z))
   7090     if (N0.getOpcode() == ISD::FMA &&
   7091         N0.getOperand(2).getOpcode() == ISD::FMUL) {
   7092       return DAG.getNode(FusedOpcode, SDLoc(N), VT,
   7093                          N0.getOperand(0), N0.getOperand(1),
   7094                          DAG.getNode(FusedOpcode, SDLoc(N), VT,
   7095                                      N0.getOperand(2).getOperand(0),
   7096                                      N0.getOperand(2).getOperand(1),
   7097                                      N1));
   7098     }
   7099 
   7100     // fold (fadd x, (fma y, z, (fmul u, v)) -> (fma y, z (fma u, v, x))
   7101     if (N1->getOpcode() == ISD::FMA &&
   7102         N1.getOperand(2).getOpcode() == ISD::FMUL) {
   7103       return DAG.getNode(FusedOpcode, SDLoc(N), VT,
   7104                          N1.getOperand(0), N1.getOperand(1),
   7105                          DAG.getNode(FusedOpcode, SDLoc(N), VT,
   7106                                      N1.getOperand(2).getOperand(0),
   7107                                      N1.getOperand(2).getOperand(1),
   7108                                      N0));
   7109     }
   7110   }
   7111 
   7112   return SDValue();
   7113 }
   7114 
   7115 static SDValue performFsubFmulCombines(unsigned FusedOpcode,
   7116                                        bool Aggressive,
   7117                                        SDNode *N,
   7118                                        const TargetLowering &TLI,
   7119                                        SelectionDAG &DAG) {
   7120   SDValue N0 = N->getOperand(0);
   7121   SDValue N1 = N->getOperand(1);
   7122   EVT VT = N->getValueType(0);
   7123 
   7124   SDLoc SL(N);
   7125 
   7126   // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
   7127   if (N0.getOpcode() == ISD::FMUL &&
   7128       (Aggressive || N0->hasOneUse())) {
   7129     return DAG.getNode(FusedOpcode, SL, VT,
   7130                        N0.getOperand(0), N0.getOperand(1),
   7131                        DAG.getNode(ISD::FNEG, SL, VT, N1));
   7132   }
   7133 
   7134   // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
   7135   // Note: Commutes FSUB operands.
   7136   if (N1.getOpcode() == ISD::FMUL &&
   7137       (Aggressive || N1->hasOneUse()))
   7138     return DAG.getNode(FusedOpcode, SL, VT,
   7139                        DAG.getNode(ISD::FNEG, SL, VT,
   7140                                    N1.getOperand(0)),
   7141                        N1.getOperand(1), N0);
   7142 
   7143   // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
   7144   if (N0.getOpcode() == ISD::FNEG &&
   7145       N0.getOperand(0).getOpcode() == ISD::FMUL &&
   7146       (Aggressive || (N0->hasOneUse() && N0.getOperand(0).hasOneUse()))) {
   7147     SDValue N00 = N0.getOperand(0).getOperand(0);
   7148     SDValue N01 = N0.getOperand(0).getOperand(1);
   7149     return DAG.getNode(FusedOpcode, SL, VT,
   7150                        DAG.getNode(ISD::FNEG, SL, VT, N00), N01,
   7151                        DAG.getNode(ISD::FNEG, SL, VT, N1));
   7152   }
   7153 
   7154   // More folding opportunities when target permits.
   7155   if (Aggressive) {
   7156     // fold (fsub (fma x, y, (fmul u, v)), z)
   7157     //   -> (fma x, y (fma u, v, (fneg z)))
   7158     if (N0.getOpcode() == FusedOpcode &&
   7159         N0.getOperand(2).getOpcode() == ISD::FMUL) {
   7160       return DAG.getNode(FusedOpcode, SDLoc(N), VT,
   7161                          N0.getOperand(0), N0.getOperand(1),
   7162                          DAG.getNode(FusedOpcode, SDLoc(N), VT,
   7163                                      N0.getOperand(2).getOperand(0),
   7164                                      N0.getOperand(2).getOperand(1),
   7165                                      DAG.getNode(ISD::FNEG, SDLoc(N), VT,
   7166                                                  N1)));
   7167     }
   7168 
   7169     // fold (fsub x, (fma y, z, (fmul u, v)))
   7170     //   -> (fma (fneg y), z, (fma (fneg u), v, x))
   7171     if (N1.getOpcode() == FusedOpcode &&
   7172         N1.getOperand(2).getOpcode() == ISD::FMUL) {
   7173       SDValue N20 = N1.getOperand(2).getOperand(0);
   7174       SDValue N21 = N1.getOperand(2).getOperand(1);
   7175       return DAG.getNode(FusedOpcode, SDLoc(N), VT,
   7176                          DAG.getNode(ISD::FNEG, SDLoc(N), VT,
   7177                                      N1.getOperand(0)),
   7178                          N1.getOperand(1),
   7179                          DAG.getNode(FusedOpcode, SDLoc(N), VT,
   7180                                      DAG.getNode(ISD::FNEG, SDLoc(N),  VT,
   7181                                                  N20),
   7182                                      N21, N0));
   7183     }
   7184   }
   7185 
   7186   return SDValue();
   7187 }
   7188 
   7189 SDValue DAGCombiner::visitFADD(SDNode *N) {
   7190   SDValue N0 = N->getOperand(0);
   7191   SDValue N1 = N->getOperand(1);
   7192   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
   7193   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
   7194   EVT VT = N->getValueType(0);
   7195   const TargetOptions &Options = DAG.getTarget().Options;
   7196 
   7197   // fold vector ops
   7198   if (VT.isVector())
   7199     if (SDValue FoldedVOp = SimplifyVBinOp(N))
   7200       return FoldedVOp;
   7201 
   7202   // fold (fadd c1, c2) -> c1 + c2
   7203   if (N0CFP && N1CFP)
   7204     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N1);
   7205 
   7206   // canonicalize constant to RHS
   7207   if (N0CFP && !N1CFP)
   7208     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N0);
   7209 
   7210   // fold (fadd A, (fneg B)) -> (fsub A, B)
   7211   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
   7212       isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2)
   7213     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0,
   7214                        GetNegatedExpression(N1, DAG, LegalOperations));
   7215 
   7216   // fold (fadd (fneg A), B) -> (fsub B, A)
   7217   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
   7218       isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2)
   7219     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N1,
   7220                        GetNegatedExpression(N0, DAG, LegalOperations));
   7221 
   7222   // If 'unsafe math' is enabled, fold lots of things.
   7223   if (Options.UnsafeFPMath) {
   7224     // No FP constant should be created after legalization as Instruction
   7225     // Selection pass has a hard time dealing with FP constants.
   7226     bool AllowNewConst = (Level < AfterLegalizeDAG);
   7227 
   7228     // fold (fadd A, 0) -> A
   7229     if (N1CFP && N1CFP->getValueAPF().isZero())
   7230       return N0;
   7231 
   7232     // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
   7233     if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
   7234         isa<ConstantFPSDNode>(N0.getOperand(1)))
   7235       return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0.getOperand(0),
   7236                          DAG.getNode(ISD::FADD, SDLoc(N), VT,
   7237                                      N0.getOperand(1), N1));
   7238 
   7239     // If allowed, fold (fadd (fneg x), x) -> 0.0
   7240     if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
   7241       return DAG.getConstantFP(0.0, VT);
   7242 
   7243     // If allowed, fold (fadd x, (fneg x)) -> 0.0
   7244     if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
   7245       return DAG.getConstantFP(0.0, VT);
   7246 
   7247     // We can fold chains of FADD's of the same value into multiplications.
   7248     // This transform is not safe in general because we are reducing the number
   7249     // of rounding steps.
   7250     if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) {
   7251       if (N0.getOpcode() == ISD::FMUL) {
   7252         ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
   7253         ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
   7254 
   7255         // (fadd (fmul x, c), x) -> (fmul x, c+1)
   7256         if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
   7257           SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
   7258                                        SDValue(CFP01, 0),
   7259                                        DAG.getConstantFP(1.0, VT));
   7260           return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, NewCFP);
   7261         }
   7262 
   7263         // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
   7264         if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
   7265             N1.getOperand(0) == N1.getOperand(1) &&
   7266             N0.getOperand(0) == N1.getOperand(0)) {
   7267           SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
   7268                                        SDValue(CFP01, 0),
   7269                                        DAG.getConstantFP(2.0, VT));
   7270           return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
   7271                              N0.getOperand(0), NewCFP);
   7272         }
   7273       }
   7274 
   7275       if (N1.getOpcode() == ISD::FMUL) {
   7276         ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
   7277         ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
   7278 
   7279         // (fadd x, (fmul x, c)) -> (fmul x, c+1)
   7280         if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
   7281           SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
   7282                                        SDValue(CFP11, 0),
   7283                                        DAG.getConstantFP(1.0, VT));
   7284           return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, NewCFP);
   7285         }
   7286 
   7287         // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
   7288         if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
   7289             N0.getOperand(0) == N0.getOperand(1) &&
   7290             N1.getOperand(0) == N0.getOperand(0)) {
   7291           SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
   7292                                        SDValue(CFP11, 0),
   7293                                        DAG.getConstantFP(2.0, VT));
   7294           return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1.getOperand(0), NewCFP);
   7295         }
   7296       }
   7297 
   7298       if (N0.getOpcode() == ISD::FADD && AllowNewConst) {
   7299         ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
   7300         // (fadd (fadd x, x), x) -> (fmul x, 3.0)
   7301         if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
   7302             (N0.getOperand(0) == N1))
   7303           return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
   7304                              N1, DAG.getConstantFP(3.0, VT));
   7305       }
   7306 
   7307       if (N1.getOpcode() == ISD::FADD && AllowNewConst) {
   7308         ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
   7309         // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
   7310         if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
   7311             N1.getOperand(0) == N0)
   7312           return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
   7313                              N0, DAG.getConstantFP(3.0, VT));
   7314       }
   7315 
   7316       // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
   7317       if (AllowNewConst &&
   7318           N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
   7319           N0.getOperand(0) == N0.getOperand(1) &&
   7320           N1.getOperand(0) == N1.getOperand(1) &&
   7321           N0.getOperand(0) == N1.getOperand(0))
   7322         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
   7323                            N0.getOperand(0), DAG.getConstantFP(4.0, VT));
   7324     }
   7325   } // enable-unsafe-fp-math
   7326 
   7327   if (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT)) {
   7328     // Assume if there is an fmad instruction that it should be aggressively
   7329     // used.
   7330     if (SDValue Fused = performFaddFmulCombines(ISD::FMAD, true, N, TLI, DAG))
   7331       return Fused;
   7332   }
   7333 
   7334   // FADD -> FMA combines:
   7335   if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath) &&
   7336       TLI.isFMAFasterThanFMulAndFAdd(VT) &&
   7337       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
   7338 
   7339     if (!TLI.isOperationLegal(ISD::FMAD, VT)) {
   7340       // Don't form FMA if we are preferring FMAD.
   7341       if (SDValue Fused
   7342           = performFaddFmulCombines(ISD::FMA,
   7343                                     TLI.enableAggressiveFMAFusion(VT),
   7344                                     N, TLI, DAG)) {
   7345         return Fused;
   7346       }
   7347     }
   7348 
   7349     // When FP_EXTEND nodes are free on the target, and there is an opportunity
   7350     // to combine into FMA, arrange such nodes accordingly.
   7351     if (TLI.isFPExtFree(VT)) {
   7352 
   7353       // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z)
   7354       if (N0.getOpcode() == ISD::FP_EXTEND) {
   7355         SDValue N00 = N0.getOperand(0);
   7356         if (N00.getOpcode() == ISD::FMUL)
   7357           return DAG.getNode(ISD::FMA, SDLoc(N), VT,
   7358                              DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
   7359                                          N00.getOperand(0)),
   7360                              DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
   7361                                          N00.getOperand(1)), N1);
   7362       }
   7363 
   7364       // fold (fadd x, (fpext (fmul y, z)), z) -> (fma (fpext y), (fpext z), x)
   7365       // Note: Commutes FADD operands.
   7366       if (N1.getOpcode() == ISD::FP_EXTEND) {
   7367         SDValue N10 = N1.getOperand(0);
   7368         if (N10.getOpcode() == ISD::FMUL)
   7369           return DAG.getNode(ISD::FMA, SDLoc(N), VT,
   7370                              DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
   7371                                          N10.getOperand(0)),
   7372                              DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
   7373                                          N10.getOperand(1)), N0);
   7374       }
   7375     }
   7376   }
   7377 
   7378   return SDValue();
   7379 }
   7380 
   7381 SDValue DAGCombiner::visitFSUB(SDNode *N) {
   7382   SDValue N0 = N->getOperand(0);
   7383   SDValue N1 = N->getOperand(1);
   7384   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
   7385   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
   7386   EVT VT = N->getValueType(0);
   7387   SDLoc dl(N);
   7388   const TargetOptions &Options = DAG.getTarget().Options;
   7389 
   7390   // fold vector ops
   7391   if (VT.isVector())
   7392     if (SDValue FoldedVOp = SimplifyVBinOp(N))
   7393       return FoldedVOp;
   7394 
   7395   // fold (fsub c1, c2) -> c1-c2
   7396   if (N0CFP && N1CFP)
   7397     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0, N1);
   7398 
   7399   // fold (fsub A, (fneg B)) -> (fadd A, B)
   7400   if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
   7401     return DAG.getNode(ISD::FADD, dl, VT, N0,
   7402                        GetNegatedExpression(N1, DAG, LegalOperations));
   7403 
   7404   // If 'unsafe math' is enabled, fold lots of things.
   7405   if (Options.UnsafeFPMath) {
   7406     // (fsub A, 0) -> A
   7407     if (N1CFP && N1CFP->getValueAPF().isZero())
   7408       return N0;
   7409 
   7410     // (fsub 0, B) -> -B
   7411     if (N0CFP && N0CFP->getValueAPF().isZero()) {
   7412       if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
   7413         return GetNegatedExpression(N1, DAG, LegalOperations);
   7414       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
   7415         return DAG.getNode(ISD::FNEG, dl, VT, N1);
   7416     }
   7417 
   7418     // (fsub x, x) -> 0.0
   7419     if (N0 == N1)
   7420       return DAG.getConstantFP(0.0f, VT);
   7421 
   7422     // (fsub x, (fadd x, y)) -> (fneg y)
   7423     // (fsub x, (fadd y, x)) -> (fneg y)
   7424     if (N1.getOpcode() == ISD::FADD) {
   7425       SDValue N10 = N1->getOperand(0);
   7426       SDValue N11 = N1->getOperand(1);
   7427 
   7428       if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options))
   7429         return GetNegatedExpression(N11, DAG, LegalOperations);
   7430 
   7431       if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options))
   7432         return GetNegatedExpression(N10, DAG, LegalOperations);
   7433     }
   7434   }
   7435 
   7436   if (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT)) {
   7437     // Assume if there is an fmad instruction that it should be aggressively
   7438     // used.
   7439     if (SDValue Fused = performFsubFmulCombines(ISD::FMAD, true, N, TLI, DAG))
   7440       return Fused;
   7441   }
   7442 
   7443   // FSUB -> FMA combines:
   7444   if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath) &&
   7445       TLI.isFMAFasterThanFMulAndFAdd(VT) &&
   7446       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
   7447 
   7448     if (!TLI.isOperationLegal(ISD::FMAD, VT)) {
   7449       // Don't form FMA if we are preferring FMAD.
   7450 
   7451       if (SDValue Fused
   7452           = performFsubFmulCombines(ISD::FMA,
   7453                                     TLI.enableAggressiveFMAFusion(VT),
   7454                                     N, TLI, DAG)) {
   7455         return Fused;
   7456       }
   7457     }
   7458 
   7459     // When FP_EXTEND nodes are free on the target, and there is an opportunity
   7460     // to combine into FMA, arrange such nodes accordingly.
   7461     if (TLI.isFPExtFree(VT)) {
   7462       // fold (fsub (fpext (fmul x, y)), z)
   7463       //   -> (fma (fpext x), (fpext y), (fneg z))
   7464       if (N0.getOpcode() == ISD::FP_EXTEND) {
   7465         SDValue N00 = N0.getOperand(0);
   7466         if (N00.getOpcode() == ISD::FMUL)
   7467           return DAG.getNode(ISD::FMA, SDLoc(N), VT,
   7468                              DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
   7469                                          N00.getOperand(0)),
   7470                              DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
   7471                                          N00.getOperand(1)),
   7472                              DAG.getNode(ISD::FNEG, SDLoc(N), VT, N1));
   7473       }
   7474 
   7475       // fold (fsub x, (fpext (fmul y, z)))
   7476       //   -> (fma (fneg (fpext y)), (fpext z), x)
   7477       // Note: Commutes FSUB operands.
   7478       if (N1.getOpcode() == ISD::FP_EXTEND) {
   7479         SDValue N10 = N1.getOperand(0);
   7480         if (N10.getOpcode() == ISD::FMUL)
   7481           return DAG.getNode(ISD::FMA, SDLoc(N), VT,
   7482                              DAG.getNode(ISD::FNEG, SDLoc(N), VT,
   7483                                          DAG.getNode(ISD::FP_EXTEND, SDLoc(N),
   7484                                                      VT, N10.getOperand(0))),
   7485                              DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
   7486                                          N10.getOperand(1)),
   7487                              N0);
   7488       }
   7489 
   7490       // fold (fsub (fpext (fneg (fmul, x, y))), z)
   7491       //   -> (fma (fneg (fpext x)), (fpext y), (fneg z))
   7492       if (N0.getOpcode() == ISD::FP_EXTEND) {
   7493         SDValue N00 = N0.getOperand(0);
   7494         if (N00.getOpcode() == ISD::FNEG) {
   7495           SDValue N000 = N00.getOperand(0);
   7496           if (N000.getOpcode() == ISD::FMUL) {
   7497             return DAG.getNode(ISD::FMA, dl, VT,
   7498                                DAG.getNode(ISD::FNEG, dl, VT,
   7499                                            DAG.getNode(ISD::FP_EXTEND, SDLoc(N),
   7500                                                        VT, N000.getOperand(0))),
   7501                                DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
   7502                                            N000.getOperand(1)),
   7503                                DAG.getNode(ISD::FNEG, dl, VT, N1));
   7504           }
   7505         }
   7506       }
   7507 
   7508       // fold (fsub (fneg (fpext (fmul, x, y))), z)
   7509       //   -> (fma (fneg (fpext x)), (fpext y), (fneg z))
   7510       if (N0.getOpcode() == ISD::FNEG) {
   7511         SDValue N00 = N0.getOperand(0);
   7512         if (N00.getOpcode() == ISD::FP_EXTEND) {
   7513           SDValue N000 = N00.getOperand(0);
   7514           if (N000.getOpcode() == ISD::FMUL) {
   7515             return DAG.getNode(ISD::FMA, dl, VT,
   7516                                DAG.getNode(ISD::FNEG, dl, VT,
   7517                                            DAG.getNode(ISD::FP_EXTEND, SDLoc(N),
   7518                                            VT, N000.getOperand(0))),
   7519                                DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
   7520                                            N000.getOperand(1)),
   7521                                DAG.getNode(ISD::FNEG, dl, VT, N1));
   7522           }
   7523         }
   7524       }
   7525     }
   7526   }
   7527 
   7528   return SDValue();
   7529 }
   7530 
   7531 SDValue DAGCombiner::visitFMUL(SDNode *N) {
   7532   SDValue N0 = N->getOperand(0);
   7533   SDValue N1 = N->getOperand(1);
   7534   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
   7535   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
   7536   EVT VT = N->getValueType(0);
   7537   const TargetOptions &Options = DAG.getTarget().Options;
   7538 
   7539   // fold vector ops
   7540   if (VT.isVector()) {
   7541     // This just handles C1 * C2 for vectors. Other vector folds are below.
   7542     if (SDValue FoldedVOp = SimplifyVBinOp(N))
   7543       return FoldedVOp;
   7544   }
   7545 
   7546   // fold (fmul c1, c2) -> c1*c2
   7547   if (N0CFP && N1CFP)
   7548     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, N1);
   7549 
   7550   // canonicalize constant to RHS
   7551   if (isConstantFPBuildVectorOrConstantFP(N0) &&
   7552      !isConstantFPBuildVectorOrConstantFP(N1))
   7553     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, N0);
   7554 
   7555   // fold (fmul A, 1.0) -> A
   7556   if (N1CFP && N1CFP->isExactlyValue(1.0))
   7557     return N0;
   7558 
   7559   if (Options.UnsafeFPMath) {
   7560     // fold (fmul A, 0) -> 0
   7561     if (N1CFP && N1CFP->getValueAPF().isZero())
   7562       return N1;
   7563 
   7564     // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
   7565     if (N0.getOpcode() == ISD::FMUL) {
   7566       // Fold scalars or any vector constants (not just splats).
   7567       // This fold is done in general by InstCombine, but extra fmul insts
   7568       // may have been generated during lowering.
   7569       SDValue N00 = N0.getOperand(0);
   7570       SDValue N01 = N0.getOperand(1);
   7571       auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
   7572       auto *BV00 = dyn_cast<BuildVectorSDNode>(N00);
   7573       auto *BV01 = dyn_cast<BuildVectorSDNode>(N01);
   7574 
   7575       // Check 1: Make sure that the first operand of the inner multiply is NOT
   7576       // a constant. Otherwise, we may induce infinite looping.
   7577       if (!(isConstOrConstSplatFP(N00) || (BV00 && BV00->isConstant()))) {
   7578         // Check 2: Make sure that the second operand of the inner multiply and
   7579         // the second operand of the outer multiply are constants.
   7580         if ((N1CFP && isConstOrConstSplatFP(N01)) ||
   7581             (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) {
   7582           SDLoc SL(N);
   7583           SDValue MulConsts = DAG.getNode(ISD::FMUL, SL, VT, N01, N1);
   7584           return DAG.getNode(ISD::FMUL, SL, VT, N00, MulConsts);
   7585         }
   7586       }
   7587     }
   7588 
   7589     // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c))
   7590     // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs
   7591     // during an early run of DAGCombiner can prevent folding with fmuls
   7592     // inserted during lowering.
   7593     if (N0.getOpcode() == ISD::FADD && N0.getOperand(0) == N0.getOperand(1)) {
   7594       SDLoc SL(N);
   7595       const SDValue Two = DAG.getConstantFP(2.0, VT);
   7596       SDValue MulConsts = DAG.getNode(ISD::FMUL, SL, VT, Two, N1);
   7597       return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0), MulConsts);
   7598     }
   7599   }
   7600 
   7601   // fold (fmul X, 2.0) -> (fadd X, X)
   7602   if (N1CFP && N1CFP->isExactlyValue(+2.0))
   7603     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N0);
   7604 
   7605   // fold (fmul X, -1.0) -> (fneg X)
   7606   if (N1CFP && N1CFP->isExactlyValue(-1.0))
   7607     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
   7608       return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
   7609 
   7610   // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
   7611   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
   7612     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
   7613       // Both can be negated for free, check to see if at least one is cheaper
   7614       // negated.
   7615       if (LHSNeg == 2 || RHSNeg == 2)
   7616         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
   7617                            GetNegatedExpression(N0, DAG, LegalOperations),
   7618                            GetNegatedExpression(N1, DAG, LegalOperations));
   7619     }
   7620   }
   7621 
   7622   return SDValue();
   7623 }
   7624 
   7625 SDValue DAGCombiner::visitFMA(SDNode *N) {
   7626   SDValue N0 = N->getOperand(0);
   7627   SDValue N1 = N->getOperand(1);
   7628   SDValue N2 = N->getOperand(2);
   7629   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
   7630   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
   7631   EVT VT = N->getValueType(0);
   7632   SDLoc dl(N);
   7633   const TargetOptions &Options = DAG.getTarget().Options;
   7634 
   7635   // Constant fold FMA.
   7636   if (isa<ConstantFPSDNode>(N0) &&
   7637       isa<ConstantFPSDNode>(N1) &&
   7638       isa<ConstantFPSDNode>(N2)) {
   7639     return DAG.getNode(ISD::FMA, dl, VT, N0, N1, N2);
   7640   }
   7641 
   7642   if (Options.UnsafeFPMath) {
   7643     if (N0CFP && N0CFP->isZero())
   7644       return N2;
   7645     if (N1CFP && N1CFP->isZero())
   7646       return N2;
   7647   }
   7648   if (N0CFP && N0CFP->isExactlyValue(1.0))
   7649     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
   7650   if (N1CFP && N1CFP->isExactlyValue(1.0))
   7651     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
   7652 
   7653   // Canonicalize (fma c, x, y) -> (fma x, c, y)
   7654   if (N0CFP && !N1CFP)
   7655     return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
   7656 
   7657   // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
   7658   if (Options.UnsafeFPMath && N1CFP &&
   7659       N2.getOpcode() == ISD::FMUL &&
   7660       N0 == N2.getOperand(0) &&
   7661       N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
   7662     return DAG.getNode(ISD::FMUL, dl, VT, N0,
   7663                        DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
   7664   }
   7665 
   7666 
   7667   // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
   7668   if (Options.UnsafeFPMath &&
   7669       N0.getOpcode() == ISD::FMUL && N1CFP &&
   7670       N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
   7671     return DAG.getNode(ISD::FMA, dl, VT,
   7672                        N0.getOperand(0),
   7673                        DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
   7674                        N2);
   7675   }
   7676 
   7677   // (fma x, 1, y) -> (fadd x, y)
   7678   // (fma x, -1, y) -> (fadd (fneg x), y)
   7679   if (N1CFP) {
   7680     if (N1CFP->isExactlyValue(1.0))
   7681       return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
   7682 
   7683     if (N1CFP->isExactlyValue(-1.0) &&
   7684         (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
   7685       SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
   7686       AddToWorklist(RHSNeg.getNode());
   7687       return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
   7688     }
   7689   }
   7690 
   7691   // (fma x, c, x) -> (fmul x, (c+1))
   7692   if (Options.UnsafeFPMath && N1CFP && N0 == N2)
   7693     return DAG.getNode(ISD::FMUL, dl, VT, N0,
   7694                        DAG.getNode(ISD::FADD, dl, VT,
   7695                                    N1, DAG.getConstantFP(1.0, VT)));
   7696 
   7697   // (fma x, c, (fneg x)) -> (fmul x, (c-1))
   7698   if (Options.UnsafeFPMath && N1CFP &&
   7699       N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
   7700     return DAG.getNode(ISD::FMUL, dl, VT, N0,
   7701                        DAG.getNode(ISD::FADD, dl, VT,
   7702                                    N1, DAG.getConstantFP(-1.0, VT)));
   7703 
   7704 
   7705   return SDValue();
   7706 }
   7707 
   7708 SDValue DAGCombiner::visitFDIV(SDNode *N) {
   7709   SDValue N0 = N->getOperand(0);
   7710   SDValue N1 = N->getOperand(1);
   7711   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
   7712   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
   7713   EVT VT = N->getValueType(0);
   7714   SDLoc DL(N);
   7715   const TargetOptions &Options = DAG.getTarget().Options;
   7716 
   7717   // fold vector ops
   7718   if (VT.isVector())
   7719     if (SDValue FoldedVOp = SimplifyVBinOp(N))
   7720       return FoldedVOp;
   7721 
   7722   // fold (fdiv c1, c2) -> c1/c2
   7723   if (N0CFP && N1CFP)
   7724     return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
   7725 
   7726   if (Options.UnsafeFPMath) {
   7727     // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
   7728     if (N1CFP) {
   7729       // Compute the reciprocal 1.0 / c2.
   7730       APFloat N1APF = N1CFP->getValueAPF();
   7731       APFloat Recip(N1APF.getSemantics(), 1); // 1.0
   7732       APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
   7733       // Only do the transform if the reciprocal is a legal fp immediate that
   7734       // isn't too nasty (eg NaN, denormal, ...).
   7735       if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
   7736           (!LegalOperations ||
   7737            // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
   7738            // backend)... we should handle this gracefully after Legalize.
   7739            // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
   7740            TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
   7741            TLI.isFPImmLegal(Recip, VT)))
   7742         return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0,
   7743                            DAG.getConstantFP(Recip, VT));
   7744     }
   7745 
   7746     // If this FDIV is part of a reciprocal square root, it may be folded
   7747     // into a target-specific square root estimate instruction.
   7748     if (N1.getOpcode() == ISD::FSQRT) {
   7749       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0))) {
   7750         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
   7751       }
   7752     } else if (N1.getOpcode() == ISD::FP_EXTEND &&
   7753                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
   7754       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) {
   7755         RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV);
   7756         AddToWorklist(RV.getNode());
   7757         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
   7758       }
   7759     } else if (N1.getOpcode() == ISD::FP_ROUND &&
   7760                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
   7761       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) {
   7762         RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1));
   7763         AddToWorklist(RV.getNode());
   7764         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
   7765       }
   7766     } else if (N1.getOpcode() == ISD::FMUL) {
   7767       // Look through an FMUL. Even though this won't remove the FDIV directly,
   7768       // it's still worthwhile to get rid of the FSQRT if possible.
   7769       SDValue SqrtOp;
   7770       SDValue OtherOp;
   7771       if (N1.getOperand(0).getOpcode() == ISD::FSQRT) {
   7772         SqrtOp = N1.getOperand(0);
   7773         OtherOp = N1.getOperand(1);
   7774       } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) {
   7775         SqrtOp = N1.getOperand(1);
   7776         OtherOp = N1.getOperand(0);
   7777       }
   7778       if (SqrtOp.getNode()) {
   7779         // We found a FSQRT, so try to make this fold:
   7780         // x / (y * sqrt(z)) -> x * (rsqrt(z) / y)
   7781         if (SDValue RV = BuildRsqrtEstimate(SqrtOp.getOperand(0))) {
   7782           RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp);
   7783           AddToWorklist(RV.getNode());
   7784           return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
   7785         }
   7786       }
   7787     }
   7788 
   7789     // Fold into a reciprocal estimate and multiply instead of a real divide.
   7790     if (SDValue RV = BuildReciprocalEstimate(N1)) {
   7791       AddToWorklist(RV.getNode());
   7792       return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
   7793     }
   7794   }
   7795 
   7796   // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
   7797   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
   7798     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
   7799       // Both can be negated for free, check to see if at least one is cheaper
   7800       // negated.
   7801       if (LHSNeg == 2 || RHSNeg == 2)
   7802         return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
   7803                            GetNegatedExpression(N0, DAG, LegalOperations),
   7804                            GetNegatedExpression(N1, DAG, LegalOperations));
   7805     }
   7806   }
   7807 
   7808   // Combine multiple FDIVs with the same divisor into multiple FMULs by the
   7809   // reciprocal.
   7810   // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip)
   7811   // Notice that this is not always beneficial. One reason is different target
   7812   // may have different costs for FDIV and FMUL, so sometimes the cost of two
   7813   // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason
   7814   // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL".
   7815   if (Options.UnsafeFPMath) {
   7816     // Skip if current node is a reciprocal.
   7817     if (N0CFP && N0CFP->isExactlyValue(1.0))
   7818       return SDValue();
   7819 
   7820     SmallVector<SDNode *, 4> Users;
   7821     // Find all FDIV users of the same divisor.
   7822     for (SDNode::use_iterator UI = N1.getNode()->use_begin(),
   7823                               UE = N1.getNode()->use_end();
   7824          UI != UE; ++UI) {
   7825       SDNode *User = UI.getUse().getUser();
   7826       if (User->getOpcode() == ISD::FDIV && User->getOperand(1) == N1)
   7827         Users.push_back(User);
   7828     }
   7829 
   7830     if (TLI.combineRepeatedFPDivisors(Users.size())) {
   7831       SDValue FPOne = DAG.getConstantFP(1.0, VT); // floating point 1.0
   7832       SDValue Reciprocal = DAG.getNode(ISD::FDIV, SDLoc(N), VT, FPOne, N1);
   7833 
   7834       // Dividend / Divisor -> Dividend * Reciprocal
   7835       for (auto I = Users.begin(), E = Users.end(); I != E; ++I) {
   7836         if ((*I)->getOperand(0) != FPOne) {
   7837           SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(*I), VT,
   7838                                         (*I)->getOperand(0), Reciprocal);
   7839           DAG.ReplaceAllUsesWith(*I, NewNode.getNode());
   7840         }
   7841       }
   7842       return SDValue();
   7843     }
   7844   }
   7845 
   7846   return SDValue();
   7847 }
   7848 
   7849 SDValue DAGCombiner::visitFREM(SDNode *N) {
   7850   SDValue N0 = N->getOperand(0);
   7851   SDValue N1 = N->getOperand(1);
   7852   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
   7853   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
   7854   EVT VT = N->getValueType(0);
   7855 
   7856   // fold (frem c1, c2) -> fmod(c1,c2)
   7857   if (N0CFP && N1CFP)
   7858     return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
   7859 
   7860   return SDValue();
   7861 }
   7862 
   7863 SDValue DAGCombiner::visitFSQRT(SDNode *N) {
   7864   if (DAG.getTarget().Options.UnsafeFPMath &&
   7865       !TLI.isFsqrtCheap()) {
   7866     // Compute this as X * (1/sqrt(X)) = X * (X ** -0.5)
   7867     if (SDValue RV = BuildRsqrtEstimate(N->getOperand(0))) {
   7868       EVT VT = RV.getValueType();
   7869       RV = DAG.getNode(ISD::FMUL, SDLoc(N), VT, N->getOperand(0), RV);
   7870       AddToWorklist(RV.getNode());
   7871 
   7872       // Unfortunately, RV is now NaN if the input was exactly 0.
   7873       // Select out this case and force the answer to 0.
   7874       SDValue Zero = DAG.getConstantFP(0.0, VT);
   7875       SDValue ZeroCmp =
   7876         DAG.getSetCC(SDLoc(N), TLI.getSetCCResultType(*DAG.getContext(), VT),
   7877                      N->getOperand(0), Zero, ISD::SETEQ);
   7878       AddToWorklist(ZeroCmp.getNode());
   7879       AddToWorklist(RV.getNode());
   7880 
   7881       RV = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT,
   7882                        SDLoc(N), VT, ZeroCmp, Zero, RV);
   7883       return RV;
   7884     }
   7885   }
   7886   return SDValue();
   7887 }
   7888 
   7889 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
   7890   SDValue N0 = N->getOperand(0);
   7891   SDValue N1 = N->getOperand(1);
   7892   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
   7893   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
   7894   EVT VT = N->getValueType(0);
   7895 
   7896   if (N0CFP && N1CFP)  // Constant fold
   7897     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
   7898 
   7899   if (N1CFP) {
   7900     const APFloat& V = N1CFP->getValueAPF();
   7901     // copysign(x, c1) -> fabs(x)       iff ispos(c1)
   7902     // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
   7903     if (!V.isNegative()) {
   7904       if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
   7905         return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
   7906     } else {
   7907       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
   7908         return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
   7909                            DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
   7910     }
   7911   }
   7912 
   7913   // copysign(fabs(x), y) -> copysign(x, y)
   7914   // copysign(fneg(x), y) -> copysign(x, y)
   7915   // copysign(copysign(x,z), y) -> copysign(x, y)
   7916   if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
   7917       N0.getOpcode() == ISD::FCOPYSIGN)
   7918     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
   7919                        N0.getOperand(0), N1);
   7920 
   7921   // copysign(x, abs(y)) -> abs(x)
   7922   if (N1.getOpcode() == ISD::FABS)
   7923     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
   7924 
   7925   // copysign(x, copysign(y,z)) -> copysign(x, z)
   7926   if (N1.getOpcode() == ISD::FCOPYSIGN)
   7927     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
   7928                        N0, N1.getOperand(1));
   7929 
   7930   // copysign(x, fp_extend(y)) -> copysign(x, y)
   7931   // copysign(x, fp_round(y)) -> copysign(x, y)
   7932   if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
   7933     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
   7934                        N0, N1.getOperand(0));
   7935 
   7936   return SDValue();
   7937 }
   7938 
   7939 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
   7940   SDValue N0 = N->getOperand(0);
   7941   EVT VT = N->getValueType(0);
   7942   EVT OpVT = N0.getValueType();
   7943 
   7944   // fold (sint_to_fp c1) -> c1fp
   7945   if (isConstantIntBuildVectorOrConstantInt(N0) &&
   7946       // ...but only if the target supports immediate floating-point values
   7947       (!LegalOperations ||
   7948        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
   7949     return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
   7950 
   7951   // If the input is a legal type, and SINT_TO_FP is not legal on this target,
   7952   // but UINT_TO_FP is legal on this target, try to convert.
   7953   if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
   7954       TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
   7955     // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
   7956     if (DAG.SignBitIsZero(N0))
   7957       return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
   7958   }
   7959 
   7960   // The next optimizations are desirable only if SELECT_CC can be lowered.
   7961   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
   7962     // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
   7963     if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
   7964         !VT.isVector() &&
   7965         (!LegalOperations ||
   7966          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
   7967       SDValue Ops[] =
   7968         { N0.getOperand(0), N0.getOperand(1),
   7969           DAG.getConstantFP(-1.0, VT) , DAG.getConstantFP(0.0, VT),
   7970           N0.getOperand(2) };
   7971       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
   7972     }
   7973 
   7974     // fold (sint_to_fp (zext (setcc x, y, cc))) ->
   7975     //      (select_cc x, y, 1.0, 0.0,, cc)
   7976     if (N0.getOpcode() == ISD::ZERO_EXTEND &&
   7977         N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
   7978         (!LegalOperations ||
   7979          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
   7980       SDValue Ops[] =
   7981         { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
   7982           DAG.getConstantFP(1.0, VT) , DAG.getConstantFP(0.0, VT),
   7983           N0.getOperand(0).getOperand(2) };
   7984       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
   7985     }
   7986   }
   7987 
   7988   return SDValue();
   7989 }
   7990 
   7991 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
   7992   SDValue N0 = N->getOperand(0);
   7993   EVT VT = N->getValueType(0);
   7994   EVT OpVT = N0.getValueType();
   7995 
   7996   // fold (uint_to_fp c1) -> c1fp
   7997   if (isConstantIntBuildVectorOrConstantInt(N0) &&
   7998       // ...but only if the target supports immediate floating-point values
   7999       (!LegalOperations ||
   8000        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
   8001     return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
   8002 
   8003   // If the input is a legal type, and UINT_TO_FP is not legal on this target,
   8004   // but SINT_TO_FP is legal on this target, try to convert.
   8005   if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
   8006       TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
   8007     // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
   8008     if (DAG.SignBitIsZero(N0))
   8009       return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
   8010   }
   8011 
   8012   // The next optimizations are desirable only if SELECT_CC can be lowered.
   8013   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
   8014     // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
   8015 
   8016     if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
   8017         (!LegalOperations ||
   8018          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
   8019       SDValue Ops[] =
   8020         { N0.getOperand(0), N0.getOperand(1),
   8021           DAG.getConstantFP(1.0, VT),  DAG.getConstantFP(0.0, VT),
   8022           N0.getOperand(2) };
   8023       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
   8024     }
   8025   }
   8026 
   8027   return SDValue();
   8028 }
   8029 
   8030 // Fold (fp_to_{s/u}int ({s/u}int_to_fpx)) -> zext x, sext x, trunc x, or x
   8031 static SDValue FoldIntToFPToInt(SDNode *N, SelectionDAG &DAG) {
   8032   SDValue N0 = N->getOperand(0);
   8033   EVT VT = N->getValueType(0);
   8034 
   8035   if (N0.getOpcode() != ISD::UINT_TO_FP && N0.getOpcode() != ISD::SINT_TO_FP)
   8036     return SDValue();
   8037 
   8038   SDValue Src = N0.getOperand(0);
   8039   EVT SrcVT = Src.getValueType();
   8040   bool IsInputSigned = N0.getOpcode() == ISD::SINT_TO_FP;
   8041   bool IsOutputSigned = N->getOpcode() == ISD::FP_TO_SINT;
   8042 
   8043   // We can safely assume the conversion won't overflow the output range,
   8044   // because (for example) (uint8_t)18293.f is undefined behavior.
   8045 
   8046   // Since we can assume the conversion won't overflow, our decision as to
   8047   // whether the input will fit in the float should depend on the minimum
   8048   // of the input range and output range.
   8049 
   8050   // This means this is also safe for a signed input and unsigned output, since
   8051   // a negative input would lead to undefined behavior.
   8052   unsigned InputSize = (int)SrcVT.getScalarSizeInBits() - IsInputSigned;
   8053   unsigned OutputSize = (int)VT.getScalarSizeInBits() - IsOutputSigned;
   8054   unsigned ActualSize = std::min(InputSize, OutputSize);
   8055   const fltSemantics &sem = DAG.EVTToAPFloatSemantics(N0.getValueType());
   8056 
   8057   // We can only fold away the float conversion if the input range can be
   8058   // represented exactly in the float range.
   8059   if (APFloat::semanticsPrecision(sem) >= ActualSize) {
   8060     if (VT.getScalarSizeInBits() > SrcVT.getScalarSizeInBits()) {
   8061       unsigned ExtOp = IsInputSigned && IsOutputSigned ? ISD::SIGN_EXTEND
   8062                                                        : ISD::ZERO_EXTEND;
   8063       return DAG.getNode(ExtOp, SDLoc(N), VT, Src);
   8064     }
   8065     if (VT.getScalarSizeInBits() < SrcVT.getScalarSizeInBits())
   8066       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Src);
   8067     if (SrcVT == VT)
   8068       return Src;
   8069     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Src);
   8070   }
   8071   return SDValue();
   8072 }
   8073 
   8074 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
   8075   SDValue N0 = N->getOperand(0);
   8076   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
   8077   EVT VT = N->getValueType(0);
   8078 
   8079   // fold (fp_to_sint c1fp) -> c1
   8080   if (N0CFP)
   8081     return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
   8082 
   8083   return FoldIntToFPToInt(N, DAG);
   8084 }
   8085 
   8086 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
   8087   SDValue N0 = N->getOperand(0);
   8088   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
   8089   EVT VT = N->getValueType(0);
   8090 
   8091   // fold (fp_to_uint c1fp) -> c1
   8092   if (N0CFP)
   8093     return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
   8094 
   8095   return FoldIntToFPToInt(N, DAG);
   8096 }
   8097 
   8098 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
   8099   SDValue N0 = N->getOperand(0);
   8100   SDValue N1 = N->getOperand(1);
   8101   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
   8102   EVT VT = N->getValueType(0);
   8103 
   8104   // fold (fp_round c1fp) -> c1fp
   8105   if (N0CFP)
   8106     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
   8107 
   8108   // fold (fp_round (fp_extend x)) -> x
   8109   if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
   8110     return N0.getOperand(0);
   8111 
   8112   // fold (fp_round (fp_round x)) -> (fp_round x)
   8113   if (N0.getOpcode() == ISD::FP_ROUND) {
   8114     const bool NIsTrunc = N->getConstantOperandVal(1) == 1;
   8115     const bool N0IsTrunc = N0.getNode()->getConstantOperandVal(1) == 1;
   8116     // If the first fp_round isn't a value preserving truncation, it might
   8117     // introduce a tie in the second fp_round, that wouldn't occur in the
   8118     // single-step fp_round we want to fold to.
   8119     // In other words, double rounding isn't the same as rounding.
   8120     // Also, this is a value preserving truncation iff both fp_round's are.
   8121     if (DAG.getTarget().Options.UnsafeFPMath || N0IsTrunc)
   8122       return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0.getOperand(0),
   8123                          DAG.getIntPtrConstant(NIsTrunc && N0IsTrunc));
   8124   }
   8125 
   8126   // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
   8127   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
   8128     SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
   8129                               N0.getOperand(0), N1);
   8130     AddToWorklist(Tmp.getNode());
   8131     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
   8132                        Tmp, N0.getOperand(1));
   8133   }
   8134 
   8135   return SDValue();
   8136 }
   8137 
   8138 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
   8139   SDValue N0 = N->getOperand(0);
   8140   EVT VT = N->getValueType(0);
   8141   EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
   8142   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
   8143 
   8144   // fold (fp_round_inreg c1fp) -> c1fp
   8145   if (N0CFP && isTypeLegal(EVT)) {
   8146     SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
   8147     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, Round);
   8148   }
   8149 
   8150   return SDValue();
   8151 }
   8152 
   8153 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
   8154   SDValue N0 = N->getOperand(0);
   8155   EVT VT = N->getValueType(0);
   8156 
   8157   // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
   8158   if (N->hasOneUse() &&
   8159       N->use_begin()->getOpcode() == ISD::FP_ROUND)
   8160     return SDValue();
   8161 
   8162   // fold (fp_extend c1fp) -> c1fp
   8163   if (isConstantFPBuildVectorOrConstantFP(N0))
   8164     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
   8165 
   8166   // fold (fp_extend (fp16_to_fp op)) -> (fp16_to_fp op)
   8167   if (N0.getOpcode() == ISD::FP16_TO_FP &&
   8168       TLI.getOperationAction(ISD::FP16_TO_FP, VT) == TargetLowering::Legal)
   8169     return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), VT, N0.getOperand(0));
   8170 
   8171   // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
   8172   // value of X.
   8173   if (N0.getOpcode() == ISD::FP_ROUND
   8174       && N0.getNode()->getConstantOperandVal(1) == 1) {
   8175     SDValue In = N0.getOperand(0);
   8176     if (In.getValueType() == VT) return In;
   8177     if (VT.bitsLT(In.getValueType()))
   8178       return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
   8179                          In, N0.getOperand(1));
   8180     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
   8181   }
   8182 
   8183   // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
   8184   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
   8185        TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
   8186     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
   8187     SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
   8188                                      LN0->getChain(),
   8189                                      LN0->getBasePtr(), N0.getValueType(),
   8190                                      LN0->getMemOperand());
   8191     CombineTo(N, ExtLoad);
   8192     CombineTo(N0.getNode(),
   8193               DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
   8194                           N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
   8195               ExtLoad.getValue(1));
   8196     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
   8197   }
   8198 
   8199   return SDValue();
   8200 }
   8201 
   8202 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
   8203   SDValue N0 = N->getOperand(0);
   8204   EVT VT = N->getValueType(0);
   8205 
   8206   // fold (fceil c1) -> fceil(c1)
   8207   if (isConstantFPBuildVectorOrConstantFP(N0))
   8208     return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
   8209 
   8210   return SDValue();
   8211 }
   8212 
   8213 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
   8214   SDValue N0 = N->getOperand(0);
   8215   EVT VT = N->getValueType(0);
   8216 
   8217   // fold (ftrunc c1) -> ftrunc(c1)
   8218   if (isConstantFPBuildVectorOrConstantFP(N0))
   8219     return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
   8220 
   8221   return SDValue();
   8222 }
   8223 
   8224 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
   8225   SDValue N0 = N->getOperand(0);
   8226   EVT VT = N->getValueType(0);
   8227 
   8228   // fold (ffloor c1) -> ffloor(c1)
   8229   if (isConstantFPBuildVectorOrConstantFP(N0))
   8230     return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
   8231 
   8232   return SDValue();
   8233 }
   8234 
   8235 // FIXME: FNEG and FABS have a lot in common; refactor.
   8236 SDValue DAGCombiner::visitFNEG(SDNode *N) {
   8237   SDValue N0 = N->getOperand(0);
   8238   EVT VT = N->getValueType(0);
   8239 
   8240   // Constant fold FNEG.
   8241   if (isConstantFPBuildVectorOrConstantFP(N0))
   8242     return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
   8243 
   8244   if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
   8245                          &DAG.getTarget().Options))
   8246     return GetNegatedExpression(N0, DAG, LegalOperations);
   8247 
   8248   // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading
   8249   // constant pool values.
   8250   if (!TLI.isFNegFree(VT) &&
   8251       N0.getOpcode() == ISD::BITCAST &&
   8252       N0.getNode()->hasOneUse()) {
   8253     SDValue Int = N0.getOperand(0);
   8254     EVT IntVT = Int.getValueType();
   8255     if (IntVT.isInteger() && !IntVT.isVector()) {
   8256       APInt SignMask;
   8257       if (N0.getValueType().isVector()) {
   8258         // For a vector, get a mask such as 0x80... per scalar element
   8259         // and splat it.
   8260         SignMask = APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
   8261         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
   8262       } else {
   8263         // For a scalar, just generate 0x80...
   8264         SignMask = APInt::getSignBit(IntVT.getSizeInBits());
   8265       }
   8266       Int = DAG.getNode(ISD::XOR, SDLoc(N0), IntVT, Int,
   8267                         DAG.getConstant(SignMask, IntVT));
   8268       AddToWorklist(Int.getNode());
   8269       return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Int);
   8270     }
   8271   }
   8272 
   8273   // (fneg (fmul c, x)) -> (fmul -c, x)
   8274   if (N0.getOpcode() == ISD::FMUL) {
   8275     ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
   8276     if (CFP1) {
   8277       APFloat CVal = CFP1->getValueAPF();
   8278       CVal.changeSign();
   8279       if (Level >= AfterLegalizeDAG &&
   8280           (TLI.isFPImmLegal(CVal, N->getValueType(0)) ||
   8281            TLI.isOperationLegal(ISD::ConstantFP, N->getValueType(0))))
   8282         return DAG.getNode(
   8283             ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
   8284             DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0.getOperand(1)));
   8285     }
   8286   }
   8287 
   8288   return SDValue();
   8289 }
   8290 
   8291 SDValue DAGCombiner::visitFMINNUM(SDNode *N) {
   8292   SDValue N0 = N->getOperand(0);
   8293   SDValue N1 = N->getOperand(1);
   8294   const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
   8295   const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
   8296 
   8297   if (N0CFP && N1CFP) {
   8298     const APFloat &C0 = N0CFP->getValueAPF();
   8299     const APFloat &C1 = N1CFP->getValueAPF();
   8300     return DAG.getConstantFP(minnum(C0, C1), N->getValueType(0));
   8301   }
   8302 
   8303   if (N0CFP) {
   8304     EVT VT = N->getValueType(0);
   8305     // Canonicalize to constant on RHS.
   8306     return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0);
   8307   }
   8308 
   8309   return SDValue();
   8310 }
   8311 
   8312 SDValue DAGCombiner::visitFMAXNUM(SDNode *N) {
   8313   SDValue N0 = N->getOperand(0);
   8314   SDValue N1 = N->getOperand(1);
   8315   const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
   8316   const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
   8317 
   8318   if (N0CFP && N1CFP) {
   8319     const APFloat &C0 = N0CFP->getValueAPF();
   8320     const APFloat &C1 = N1CFP->getValueAPF();
   8321     return DAG.getConstantFP(maxnum(C0, C1), N->getValueType(0));
   8322   }
   8323 
   8324   if (N0CFP) {
   8325     EVT VT = N->getValueType(0);
   8326     // Canonicalize to constant on RHS.
   8327     return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0);
   8328   }
   8329 
   8330   return SDValue();
   8331 }
   8332 
   8333 SDValue DAGCombiner::visitFABS(SDNode *N) {
   8334   SDValue N0 = N->getOperand(0);
   8335   EVT VT = N->getValueType(0);
   8336 
   8337   // fold (fabs c1) -> fabs(c1)
   8338   if (isConstantFPBuildVectorOrConstantFP(N0))
   8339     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
   8340 
   8341   // fold (fabs (fabs x)) -> (fabs x)
   8342   if (N0.getOpcode() == ISD::FABS)
   8343     return N->getOperand(0);
   8344 
   8345   // fold (fabs (fneg x)) -> (fabs x)
   8346   // fold (fabs (fcopysign x, y)) -> (fabs x)
   8347   if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
   8348     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
   8349 
   8350   // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading
   8351   // constant pool values.
   8352   if (!TLI.isFAbsFree(VT) &&
   8353       N0.getOpcode() == ISD::BITCAST &&
   8354       N0.getNode()->hasOneUse()) {
   8355     SDValue Int = N0.getOperand(0);
   8356     EVT IntVT = Int.getValueType();
   8357     if (IntVT.isInteger() && !IntVT.isVector()) {
   8358       APInt SignMask;
   8359       if (N0.getValueType().isVector()) {
   8360         // For a vector, get a mask such as 0x7f... per scalar element
   8361         // and splat it.
   8362         SignMask = ~APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
   8363         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
   8364       } else {
   8365         // For a scalar, just generate 0x7f...
   8366         SignMask = ~APInt::getSignBit(IntVT.getSizeInBits());
   8367       }
   8368       Int = DAG.getNode(ISD::AND, SDLoc(N0), IntVT, Int,
   8369                         DAG.getConstant(SignMask, IntVT));
   8370       AddToWorklist(Int.getNode());
   8371       return DAG.getNode(ISD::BITCAST, SDLoc(N), N->getValueType(0), Int);
   8372     }
   8373   }
   8374 
   8375   return SDValue();
   8376 }
   8377 
   8378 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
   8379   SDValue Chain = N->getOperand(0);
   8380   SDValue N1 = N->getOperand(1);
   8381   SDValue N2 = N->getOperand(2);
   8382 
   8383   // If N is a constant we could fold this into a fallthrough or unconditional
   8384   // branch. However that doesn't happen very often in normal code, because
   8385   // Instcombine/SimplifyCFG should have handled the available opportunities.
   8386   // If we did this folding here, it would be necessary to update the
   8387   // MachineBasicBlock CFG, which is awkward.
   8388 
   8389   // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
   8390   // on the target.
   8391   if (N1.getOpcode() == ISD::SETCC &&
   8392       TLI.isOperationLegalOrCustom(ISD::BR_CC,
   8393                                    N1.getOperand(0).getValueType())) {
   8394     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
   8395                        Chain, N1.getOperand(2),
   8396                        N1.getOperand(0), N1.getOperand(1), N2);
   8397   }
   8398 
   8399   if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
   8400       ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
   8401        (N1.getOperand(0).hasOneUse() &&
   8402         N1.getOperand(0).getOpcode() == ISD::SRL))) {
   8403     SDNode *Trunc = nullptr;
   8404     if (N1.getOpcode() == ISD::TRUNCATE) {
   8405       // Look pass the truncate.
   8406       Trunc = N1.getNode();
   8407       N1 = N1.getOperand(0);
   8408     }
   8409 
   8410     // Match this pattern so that we can generate simpler code:
   8411     //
   8412     //   %a = ...
   8413     //   %b = and i32 %a, 2
   8414     //   %c = srl i32 %b, 1
   8415     //   brcond i32 %c ...
   8416     //
   8417     // into
   8418     //
   8419     //   %a = ...
   8420     //   %b = and i32 %a, 2
   8421     //   %c = setcc eq %b, 0
   8422     //   brcond %c ...
   8423     //
   8424     // This applies only when the AND constant value has one bit set and the
   8425     // SRL constant is equal to the log2 of the AND constant. The back-end is
   8426     // smart enough to convert the result into a TEST/JMP sequence.
   8427     SDValue Op0 = N1.getOperand(0);
   8428     SDValue Op1 = N1.getOperand(1);
   8429 
   8430     if (Op0.getOpcode() == ISD::AND &&
   8431         Op1.getOpcode() == ISD::Constant) {
   8432       SDValue AndOp1 = Op0.getOperand(1);
   8433 
   8434       if (AndOp1.getOpcode() == ISD::Constant) {
   8435         const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
   8436 
   8437         if (AndConst.isPowerOf2() &&
   8438             cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
   8439           SDValue SetCC =
   8440             DAG.getSetCC(SDLoc(N),
   8441                          getSetCCResultType(Op0.getValueType()),
   8442                          Op0, DAG.getConstant(0, Op0.getValueType()),
   8443                          ISD::SETNE);
   8444 
   8445           SDValue NewBRCond = DAG.getNode(ISD::BRCOND, SDLoc(N),
   8446                                           MVT::Other, Chain, SetCC, N2);
   8447           // Don't add the new BRCond into the worklist or else SimplifySelectCC
   8448           // will convert it back to (X & C1) >> C2.
   8449           CombineTo(N, NewBRCond, false);
   8450           // Truncate is dead.
   8451           if (Trunc)
   8452             deleteAndRecombine(Trunc);
   8453           // Replace the uses of SRL with SETCC
   8454           WorklistRemover DeadNodes(*this);
   8455           DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
   8456           deleteAndRecombine(N1.getNode());
   8457           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
   8458         }
   8459       }
   8460     }
   8461 
   8462     if (Trunc)
   8463       // Restore N1 if the above transformation doesn't match.
   8464       N1 = N->getOperand(1);
   8465   }
   8466 
   8467   // Transform br(xor(x, y)) -> br(x != y)
   8468   // Transform br(xor(xor(x,y), 1)) -> br (x == y)
   8469   if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
   8470     SDNode *TheXor = N1.getNode();
   8471     SDValue Op0 = TheXor->getOperand(0);
   8472     SDValue Op1 = TheXor->getOperand(1);
   8473     if (Op0.getOpcode() == Op1.getOpcode()) {
   8474       // Avoid missing important xor optimizations.
   8475       SDValue Tmp = visitXOR(TheXor);
   8476       if (Tmp.getNode()) {
   8477         if (Tmp.getNode() != TheXor) {
   8478           DEBUG(dbgs() << "\nReplacing.8 ";
   8479                 TheXor->dump(&DAG);
   8480                 dbgs() << "\nWith: ";
   8481                 Tmp.getNode()->dump(&DAG);
   8482                 dbgs() << '\n');
   8483           WorklistRemover DeadNodes(*this);
   8484           DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
   8485           deleteAndRecombine(TheXor);
   8486           return DAG.getNode(ISD::BRCOND, SDLoc(N),
   8487                              MVT::Other, Chain, Tmp, N2);
   8488         }
   8489 
   8490         // visitXOR has changed XOR's operands or replaced the XOR completely,
   8491         // bail out.
   8492         return SDValue(N, 0);
   8493       }
   8494     }
   8495 
   8496     if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
   8497       bool Equal = false;
   8498       if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
   8499         if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
   8500             Op0.getOpcode() == ISD::XOR) {
   8501           TheXor = Op0.getNode();
   8502           Equal = true;
   8503         }
   8504 
   8505       EVT SetCCVT = N1.getValueType();
   8506       if (LegalTypes)
   8507         SetCCVT = getSetCCResultType(SetCCVT);
   8508       SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
   8509                                    SetCCVT,
   8510                                    Op0, Op1,
   8511                                    Equal ? ISD::SETEQ : ISD::SETNE);
   8512       // Replace the uses of XOR with SETCC
   8513       WorklistRemover DeadNodes(*this);
   8514       DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
   8515       deleteAndRecombine(N1.getNode());
   8516       return DAG.getNode(ISD::BRCOND, SDLoc(N),
   8517                          MVT::Other, Chain, SetCC, N2);
   8518     }
   8519   }
   8520 
   8521   return SDValue();
   8522 }
   8523 
   8524 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
   8525 //
   8526 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
   8527   CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
   8528   SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
   8529 
   8530   // If N is a constant we could fold this into a fallthrough or unconditional
   8531   // branch. However that doesn't happen very often in normal code, because
   8532   // Instcombine/SimplifyCFG should have handled the available opportunities.
   8533   // If we did this folding here, it would be necessary to update the
   8534   // MachineBasicBlock CFG, which is awkward.
   8535 
   8536   // Use SimplifySetCC to simplify SETCC's.
   8537   SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
   8538                                CondLHS, CondRHS, CC->get(), SDLoc(N),
   8539                                false);
   8540   if (Simp.getNode()) AddToWorklist(Simp.getNode());
   8541 
   8542   // fold to a simpler setcc
   8543   if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
   8544     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
   8545                        N->getOperand(0), Simp.getOperand(2),
   8546                        Simp.getOperand(0), Simp.getOperand(1),
   8547                        N->getOperand(4));
   8548 
   8549   return SDValue();
   8550 }
   8551 
   8552 /// Return true if 'Use' is a load or a store that uses N as its base pointer
   8553 /// and that N may be folded in the load / store addressing mode.
   8554 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
   8555                                     SelectionDAG &DAG,
   8556                                     const TargetLowering &TLI) {
   8557   EVT VT;
   8558   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(Use)) {
   8559     if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
   8560       return false;
   8561     VT = Use->getValueType(0);
   8562   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(Use)) {
   8563     if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
   8564       return false;
   8565     VT = ST->getValue().getValueType();
   8566   } else
   8567     return false;
   8568 
   8569   TargetLowering::AddrMode AM;
   8570   if (N->getOpcode() == ISD::ADD) {
   8571     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
   8572     if (Offset)
   8573       // [reg +/- imm]
   8574       AM.BaseOffs = Offset->getSExtValue();
   8575     else
   8576       // [reg +/- reg]
   8577       AM.Scale = 1;
   8578   } else if (N->getOpcode() == ISD::SUB) {
   8579     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
   8580     if (Offset)
   8581       // [reg +/- imm]
   8582       AM.BaseOffs = -Offset->getSExtValue();
   8583     else
   8584       // [reg +/- reg]
   8585       AM.Scale = 1;
   8586   } else
   8587     return false;
   8588 
   8589   return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
   8590 }
   8591 
   8592 /// Try turning a load/store into a pre-indexed load/store when the base
   8593 /// pointer is an add or subtract and it has other uses besides the load/store.
   8594 /// After the transformation, the new indexed load/store has effectively folded
   8595 /// the add/subtract in and all of its other uses are redirected to the
   8596 /// new load/store.
   8597 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
   8598   if (Level < AfterLegalizeDAG)
   8599     return false;
   8600 
   8601   bool isLoad = true;
   8602   SDValue Ptr;
   8603   EVT VT;
   8604   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
   8605     if (LD->isIndexed())
   8606       return false;
   8607     VT = LD->getMemoryVT();
   8608     if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
   8609         !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
   8610       return false;
   8611     Ptr = LD->getBasePtr();
   8612   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
   8613     if (ST->isIndexed())
   8614       return false;
   8615     VT = ST->getMemoryVT();
   8616     if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
   8617         !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
   8618       return false;
   8619     Ptr = ST->getBasePtr();
   8620     isLoad = false;
   8621   } else {
   8622     return false;
   8623   }
   8624 
   8625   // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
   8626   // out.  There is no reason to make this a preinc/predec.
   8627   if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
   8628       Ptr.getNode()->hasOneUse())
   8629     return false;
   8630 
   8631   // Ask the target to do addressing mode selection.
   8632   SDValue BasePtr;
   8633   SDValue Offset;
   8634   ISD::MemIndexedMode AM = ISD::UNINDEXED;
   8635   if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
   8636     return false;
   8637 
   8638   // Backends without true r+i pre-indexed forms may need to pass a
   8639   // constant base with a variable offset so that constant coercion
   8640   // will work with the patterns in canonical form.
   8641   bool Swapped = false;
   8642   if (isa<ConstantSDNode>(BasePtr)) {
   8643     std::swap(BasePtr, Offset);
   8644     Swapped = true;
   8645   }
   8646 
   8647   // Don't create a indexed load / store with zero offset.
   8648   if (isa<ConstantSDNode>(Offset) &&
   8649       cast<ConstantSDNode>(Offset)->isNullValue())
   8650     return false;
   8651 
   8652   // Try turning it into a pre-indexed load / store except when:
   8653   // 1) The new base ptr is a frame index.
   8654   // 2) If N is a store and the new base ptr is either the same as or is a
   8655   //    predecessor of the value being stored.
   8656   // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
   8657   //    that would create a cycle.
   8658   // 4) All uses are load / store ops that use it as old base ptr.
   8659 
   8660   // Check #1.  Preinc'ing a frame index would require copying the stack pointer
   8661   // (plus the implicit offset) to a register to preinc anyway.
   8662   if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
   8663     return false;
   8664 
   8665   // Check #2.
   8666   if (!isLoad) {
   8667     SDValue Val = cast<StoreSDNode>(N)->getValue();
   8668     if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
   8669       return false;
   8670   }
   8671 
   8672   // If the offset is a constant, there may be other adds of constants that
   8673   // can be folded with this one. We should do this to avoid having to keep
   8674   // a copy of the original base pointer.
   8675   SmallVector<SDNode *, 16> OtherUses;
   8676   if (isa<ConstantSDNode>(Offset))
   8677     for (SDNode *Use : BasePtr.getNode()->uses()) {
   8678       if (Use == Ptr.getNode())
   8679         continue;
   8680 
   8681       if (Use->isPredecessorOf(N))
   8682         continue;
   8683 
   8684       if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) {
   8685         OtherUses.clear();
   8686         break;
   8687       }
   8688 
   8689       SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1);
   8690       if (Op1.getNode() == BasePtr.getNode())
   8691         std::swap(Op0, Op1);
   8692       assert(Op0.getNode() == BasePtr.getNode() &&
   8693              "Use of ADD/SUB but not an operand");
   8694 
   8695       if (!isa<ConstantSDNode>(Op1)) {
   8696         OtherUses.clear();
   8697         break;
   8698       }
   8699 
   8700       // FIXME: In some cases, we can be smarter about this.
   8701       if (Op1.getValueType() != Offset.getValueType()) {
   8702         OtherUses.clear();
   8703         break;
   8704       }
   8705 
   8706       OtherUses.push_back(Use);
   8707     }
   8708 
   8709   if (Swapped)
   8710     std::swap(BasePtr, Offset);
   8711 
   8712   // Now check for #3 and #4.
   8713   bool RealUse = false;
   8714 
   8715   // Caches for hasPredecessorHelper
   8716   SmallPtrSet<const SDNode *, 32> Visited;
   8717   SmallVector<const SDNode *, 16> Worklist;
   8718 
   8719   for (SDNode *Use : Ptr.getNode()->uses()) {
   8720     if (Use == N)
   8721       continue;
   8722     if (N->hasPredecessorHelper(Use, Visited, Worklist))
   8723       return false;
   8724 
   8725     // If Ptr may be folded in addressing mode of other use, then it's
   8726     // not profitable to do this transformation.
   8727     if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
   8728       RealUse = true;
   8729   }
   8730 
   8731   if (!RealUse)
   8732     return false;
   8733 
   8734   SDValue Result;
   8735   if (isLoad)
   8736     Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
   8737                                 BasePtr, Offset, AM);
   8738   else
   8739     Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
   8740                                  BasePtr, Offset, AM);
   8741   ++PreIndexedNodes;
   8742   ++NodesCombined;
   8743   DEBUG(dbgs() << "\nReplacing.4 ";
   8744         N->dump(&DAG);
   8745         dbgs() << "\nWith: ";
   8746         Result.getNode()->dump(&DAG);
   8747         dbgs() << '\n');
   8748   WorklistRemover DeadNodes(*this);
   8749   if (isLoad) {
   8750     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
   8751     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
   8752   } else {
   8753     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
   8754   }
   8755 
   8756   // Finally, since the node is now dead, remove it from the graph.
   8757   deleteAndRecombine(N);
   8758 
   8759   if (Swapped)
   8760     std::swap(BasePtr, Offset);
   8761 
   8762   // Replace other uses of BasePtr that can be updated to use Ptr
   8763   for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
   8764     unsigned OffsetIdx = 1;
   8765     if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
   8766       OffsetIdx = 0;
   8767     assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
   8768            BasePtr.getNode() && "Expected BasePtr operand");
   8769 
   8770     // We need to replace ptr0 in the following expression:
   8771     //   x0 * offset0 + y0 * ptr0 = t0
   8772     // knowing that
   8773     //   x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
   8774     //
   8775     // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
   8776     // indexed load/store and the expresion that needs to be re-written.
   8777     //
   8778     // Therefore, we have:
   8779     //   t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
   8780 
   8781     ConstantSDNode *CN =
   8782       cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
   8783     int X0, X1, Y0, Y1;
   8784     APInt Offset0 = CN->getAPIntValue();
   8785     APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
   8786 
   8787     X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
   8788     Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
   8789     X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
   8790     Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
   8791 
   8792     unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
   8793 
   8794     APInt CNV = Offset0;
   8795     if (X0 < 0) CNV = -CNV;
   8796     if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
   8797     else CNV = CNV - Offset1;
   8798 
   8799     // We can now generate the new expression.
   8800     SDValue NewOp1 = DAG.getConstant(CNV, CN->getValueType(0));
   8801     SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
   8802 
   8803     SDValue NewUse = DAG.getNode(Opcode,
   8804                                  SDLoc(OtherUses[i]),
   8805                                  OtherUses[i]->getValueType(0), NewOp1, NewOp2);
   8806     DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
   8807     deleteAndRecombine(OtherUses[i]);
   8808   }
   8809 
   8810   // Replace the uses of Ptr with uses of the updated base value.
   8811   DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
   8812   deleteAndRecombine(Ptr.getNode());
   8813 
   8814   return true;
   8815 }
   8816 
   8817 /// Try to combine a load/store with a add/sub of the base pointer node into a
   8818 /// post-indexed load/store. The transformation folded the add/subtract into the
   8819 /// new indexed load/store effectively and all of its uses are redirected to the
   8820 /// new load/store.
   8821 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
   8822   if (Level < AfterLegalizeDAG)
   8823     return false;
   8824 
   8825   bool isLoad = true;
   8826   SDValue Ptr;
   8827   EVT VT;
   8828   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
   8829     if (LD->isIndexed())
   8830       return false;
   8831     VT = LD->getMemoryVT();
   8832     if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
   8833         !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
   8834       return false;
   8835     Ptr = LD->getBasePtr();
   8836   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
   8837     if (ST->isIndexed())
   8838       return false;
   8839     VT = ST->getMemoryVT();
   8840     if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
   8841         !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
   8842       return false;
   8843     Ptr = ST->getBasePtr();
   8844     isLoad = false;
   8845   } else {
   8846     return false;
   8847   }
   8848 
   8849   if (Ptr.getNode()->hasOneUse())
   8850     return false;
   8851 
   8852   for (SDNode *Op : Ptr.getNode()->uses()) {
   8853     if (Op == N ||
   8854         (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
   8855       continue;
   8856 
   8857     SDValue BasePtr;
   8858     SDValue Offset;
   8859     ISD::MemIndexedMode AM = ISD::UNINDEXED;
   8860     if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
   8861       // Don't create a indexed load / store with zero offset.
   8862       if (isa<ConstantSDNode>(Offset) &&
   8863           cast<ConstantSDNode>(Offset)->isNullValue())
   8864         continue;
   8865 
   8866       // Try turning it into a post-indexed load / store except when
   8867       // 1) All uses are load / store ops that use it as base ptr (and
   8868       //    it may be folded as addressing mmode).
   8869       // 2) Op must be independent of N, i.e. Op is neither a predecessor
   8870       //    nor a successor of N. Otherwise, if Op is folded that would
   8871       //    create a cycle.
   8872 
   8873       if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
   8874         continue;
   8875 
   8876       // Check for #1.
   8877       bool TryNext = false;
   8878       for (SDNode *Use : BasePtr.getNode()->uses()) {
   8879         if (Use == Ptr.getNode())
   8880           continue;
   8881 
   8882         // If all the uses are load / store addresses, then don't do the
   8883         // transformation.
   8884         if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
   8885           bool RealUse = false;
   8886           for (SDNode *UseUse : Use->uses()) {
   8887             if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
   8888               RealUse = true;
   8889           }
   8890 
   8891           if (!RealUse) {
   8892             TryNext = true;
   8893             break;
   8894           }
   8895         }
   8896       }
   8897 
   8898       if (TryNext)
   8899         continue;
   8900 
   8901       // Check for #2
   8902       if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
   8903         SDValue Result = isLoad
   8904           ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
   8905                                BasePtr, Offset, AM)
   8906           : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
   8907                                 BasePtr, Offset, AM);
   8908         ++PostIndexedNodes;
   8909         ++NodesCombined;
   8910         DEBUG(dbgs() << "\nReplacing.5 ";
   8911               N->dump(&DAG);
   8912               dbgs() << "\nWith: ";
   8913               Result.getNode()->dump(&DAG);
   8914               dbgs() << '\n');
   8915         WorklistRemover DeadNodes(*this);
   8916         if (isLoad) {
   8917           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
   8918           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
   8919         } else {
   8920           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
   8921         }
   8922 
   8923         // Finally, since the node is now dead, remove it from the graph.
   8924         deleteAndRecombine(N);
   8925 
   8926         // Replace the uses of Use with uses of the updated base value.
   8927         DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
   8928                                       Result.getValue(isLoad ? 1 : 0));
   8929         deleteAndRecombine(Op);
   8930         return true;
   8931       }
   8932     }
   8933   }
   8934 
   8935   return false;
   8936 }
   8937 
   8938 /// \brief Return the base-pointer arithmetic from an indexed \p LD.
   8939 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) {
   8940   ISD::MemIndexedMode AM = LD->getAddressingMode();
   8941   assert(AM != ISD::UNINDEXED);
   8942   SDValue BP = LD->getOperand(1);
   8943   SDValue Inc = LD->getOperand(2);
   8944 
   8945   // Some backends use TargetConstants for load offsets, but don't expect
   8946   // TargetConstants in general ADD nodes. We can convert these constants into
   8947   // regular Constants (if the constant is not opaque).
   8948   assert((Inc.getOpcode() != ISD::TargetConstant ||
   8949           !cast<ConstantSDNode>(Inc)->isOpaque()) &&
   8950          "Cannot split out indexing using opaque target constants");
   8951   if (Inc.getOpcode() == ISD::TargetConstant) {
   8952     ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc);
   8953     Inc = DAG.getConstant(*ConstInc->getConstantIntValue(),
   8954                           ConstInc->getValueType(0));
   8955   }
   8956 
   8957   unsigned Opc =
   8958       (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB);
   8959   return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc);
   8960 }
   8961 
   8962 SDValue DAGCombiner::visitLOAD(SDNode *N) {
   8963   LoadSDNode *LD  = cast<LoadSDNode>(N);
   8964   SDValue Chain = LD->getChain();
   8965   SDValue Ptr   = LD->getBasePtr();
   8966 
   8967   // If load is not volatile and there are no uses of the loaded value (and
   8968   // the updated indexed value in case of indexed loads), change uses of the
   8969   // chain value into uses of the chain input (i.e. delete the dead load).
   8970   if (!LD->isVolatile()) {
   8971     if (N->getValueType(1) == MVT::Other) {
   8972       // Unindexed loads.
   8973       if (!N->hasAnyUseOfValue(0)) {
   8974         // It's not safe to use the two value CombineTo variant here. e.g.
   8975         // v1, chain2 = load chain1, loc
   8976         // v2, chain3 = load chain2, loc
   8977         // v3         = add v2, c
   8978         // Now we replace use of chain2 with chain1.  This makes the second load
   8979         // isomorphic to the one we are deleting, and thus makes this load live.
   8980         DEBUG(dbgs() << "\nReplacing.6 ";
   8981               N->dump(&DAG);
   8982               dbgs() << "\nWith chain: ";
   8983               Chain.getNode()->dump(&DAG);
   8984               dbgs() << "\n");
   8985         WorklistRemover DeadNodes(*this);
   8986         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
   8987 
   8988         if (N->use_empty())
   8989           deleteAndRecombine(N);
   8990 
   8991         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
   8992       }
   8993     } else {
   8994       // Indexed loads.
   8995       assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
   8996 
   8997       // If this load has an opaque TargetConstant offset, then we cannot split
   8998       // the indexing into an add/sub directly (that TargetConstant may not be
   8999       // valid for a different type of node, and we cannot convert an opaque
   9000       // target constant into a regular constant).
   9001       bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant &&
   9002                        cast<ConstantSDNode>(LD->getOperand(2))->isOpaque();
   9003 
   9004       if (!N->hasAnyUseOfValue(0) &&
   9005           ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) {
   9006         SDValue Undef = DAG.getUNDEF(N->getValueType(0));
   9007         SDValue Index;
   9008         if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) {
   9009           Index = SplitIndexingFromLoad(LD);
   9010           // Try to fold the base pointer arithmetic into subsequent loads and
   9011           // stores.
   9012           AddUsersToWorklist(N);
   9013         } else
   9014           Index = DAG.getUNDEF(N->getValueType(1));
   9015         DEBUG(dbgs() << "\nReplacing.7 ";
   9016               N->dump(&DAG);
   9017               dbgs() << "\nWith: ";
   9018               Undef.getNode()->dump(&DAG);
   9019               dbgs() << " and 2 other values\n");
   9020         WorklistRemover DeadNodes(*this);
   9021         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
   9022         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index);
   9023         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
   9024         deleteAndRecombine(N);
   9025         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
   9026       }
   9027     }
   9028   }
   9029 
   9030   // If this load is directly stored, replace the load value with the stored
   9031   // value.
   9032   // TODO: Handle store large -> read small portion.
   9033   // TODO: Handle TRUNCSTORE/LOADEXT
   9034   if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
   9035     if (ISD::isNON_TRUNCStore(Chain.getNode())) {
   9036       StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
   9037       if (PrevST->getBasePtr() == Ptr &&
   9038           PrevST->getValue().getValueType() == N->getValueType(0))
   9039       return CombineTo(N, Chain.getOperand(1), Chain);
   9040     }
   9041   }
   9042 
   9043   // Try to infer better alignment information than the load already has.
   9044   if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
   9045     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
   9046       if (Align > LD->getMemOperand()->getBaseAlignment()) {
   9047         SDValue NewLoad =
   9048                DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
   9049                               LD->getValueType(0),
   9050                               Chain, Ptr, LD->getPointerInfo(),
   9051                               LD->getMemoryVT(),
   9052                               LD->isVolatile(), LD->isNonTemporal(),
   9053                               LD->isInvariant(), Align, LD->getAAInfo());
   9054         if (NewLoad.getNode() != N)
   9055           return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
   9056       }
   9057     }
   9058   }
   9059 
   9060   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
   9061                                                   : DAG.getSubtarget().useAA();
   9062 #ifndef NDEBUG
   9063   if (CombinerAAOnlyFunc.getNumOccurrences() &&
   9064       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
   9065     UseAA = false;
   9066 #endif
   9067   if (UseAA && LD->isUnindexed()) {
   9068     // Walk up chain skipping non-aliasing memory nodes.
   9069     SDValue BetterChain = FindBetterChain(N, Chain);
   9070 
   9071     // If there is a better chain.
   9072     if (Chain != BetterChain) {
   9073       SDValue ReplLoad;
   9074 
   9075       // Replace the chain to void dependency.
   9076       if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
   9077         ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
   9078                                BetterChain, Ptr, LD->getMemOperand());
   9079       } else {
   9080         ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
   9081                                   LD->getValueType(0),
   9082                                   BetterChain, Ptr, LD->getMemoryVT(),
   9083                                   LD->getMemOperand());
   9084       }
   9085 
   9086       // Create token factor to keep old chain connected.
   9087       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
   9088                                   MVT::Other, Chain, ReplLoad.getValue(1));
   9089 
   9090       // Make sure the new and old chains are cleaned up.
   9091       AddToWorklist(Token.getNode());
   9092 
   9093       // Replace uses with load result and token factor. Don't add users
   9094       // to work list.
   9095       return CombineTo(N, ReplLoad.getValue(0), Token, false);
   9096     }
   9097   }
   9098 
   9099   // Try transforming N to an indexed load.
   9100   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
   9101     return SDValue(N, 0);
   9102 
   9103   // Try to slice up N to more direct loads if the slices are mapped to
   9104   // different register banks or pairing can take place.
   9105   if (SliceUpLoad(N))
   9106     return SDValue(N, 0);
   9107 
   9108   return SDValue();
   9109 }
   9110 
   9111 namespace {
   9112 /// \brief Helper structure used to slice a load in smaller loads.
   9113 /// Basically a slice is obtained from the following sequence:
   9114 /// Origin = load Ty1, Base
   9115 /// Shift = srl Ty1 Origin, CstTy Amount
   9116 /// Inst = trunc Shift to Ty2
   9117 ///
   9118 /// Then, it will be rewriten into:
   9119 /// Slice = load SliceTy, Base + SliceOffset
   9120 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
   9121 ///
   9122 /// SliceTy is deduced from the number of bits that are actually used to
   9123 /// build Inst.
   9124 struct LoadedSlice {
   9125   /// \brief Helper structure used to compute the cost of a slice.
   9126   struct Cost {
   9127     /// Are we optimizing for code size.
   9128     bool ForCodeSize;
   9129     /// Various cost.
   9130     unsigned Loads;
   9131     unsigned Truncates;
   9132     unsigned CrossRegisterBanksCopies;
   9133     unsigned ZExts;
   9134     unsigned Shift;
   9135 
   9136     Cost(bool ForCodeSize = false)
   9137         : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
   9138           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
   9139 
   9140     /// \brief Get the cost of one isolated slice.
   9141     Cost(const LoadedSlice &LS, bool ForCodeSize = false)
   9142         : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
   9143           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
   9144       EVT TruncType = LS.Inst->getValueType(0);
   9145       EVT LoadedType = LS.getLoadedType();
   9146       if (TruncType != LoadedType &&
   9147           !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
   9148         ZExts = 1;
   9149     }
   9150 
   9151     /// \brief Account for slicing gain in the current cost.
   9152     /// Slicing provide a few gains like removing a shift or a
   9153     /// truncate. This method allows to grow the cost of the original
   9154     /// load with the gain from this slice.
   9155     void addSliceGain(const LoadedSlice &LS) {
   9156       // Each slice saves a truncate.
   9157       const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
   9158       if (!TLI.isTruncateFree(LS.Inst->getValueType(0),
   9159                               LS.Inst->getOperand(0).getValueType()))
   9160         ++Truncates;
   9161       // If there is a shift amount, this slice gets rid of it.
   9162       if (LS.Shift)
   9163         ++Shift;
   9164       // If this slice can merge a cross register bank copy, account for it.
   9165       if (LS.canMergeExpensiveCrossRegisterBankCopy())
   9166         ++CrossRegisterBanksCopies;
   9167     }
   9168 
   9169     Cost &operator+=(const Cost &RHS) {
   9170       Loads += RHS.Loads;
   9171       Truncates += RHS.Truncates;
   9172       CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
   9173       ZExts += RHS.ZExts;
   9174       Shift += RHS.Shift;
   9175       return *this;
   9176     }
   9177 
   9178     bool operator==(const Cost &RHS) const {
   9179       return Loads == RHS.Loads && Truncates == RHS.Truncates &&
   9180              CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
   9181              ZExts == RHS.ZExts && Shift == RHS.Shift;
   9182     }
   9183 
   9184     bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
   9185 
   9186     bool operator<(const Cost &RHS) const {
   9187       // Assume cross register banks copies are as expensive as loads.
   9188       // FIXME: Do we want some more target hooks?
   9189       unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
   9190       unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
   9191       // Unless we are optimizing for code size, consider the
   9192       // expensive operation first.
   9193       if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
   9194         return ExpensiveOpsLHS < ExpensiveOpsRHS;
   9195       return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
   9196              (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
   9197     }
   9198 
   9199     bool operator>(const Cost &RHS) const { return RHS < *this; }
   9200 
   9201     bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
   9202 
   9203     bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
   9204   };
   9205   // The last instruction that represent the slice. This should be a
   9206   // truncate instruction.
   9207   SDNode *Inst;
   9208   // The original load instruction.
   9209   LoadSDNode *Origin;
   9210   // The right shift amount in bits from the original load.
   9211   unsigned Shift;
   9212   // The DAG from which Origin came from.
   9213   // This is used to get some contextual information about legal types, etc.
   9214   SelectionDAG *DAG;
   9215 
   9216   LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
   9217               unsigned Shift = 0, SelectionDAG *DAG = nullptr)
   9218       : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
   9219 
   9220   /// \brief Get the bits used in a chunk of bits \p BitWidth large.
   9221   /// \return Result is \p BitWidth and has used bits set to 1 and
   9222   ///         not used bits set to 0.
   9223   APInt getUsedBits() const {
   9224     // Reproduce the trunc(lshr) sequence:
   9225     // - Start from the truncated value.
   9226     // - Zero extend to the desired bit width.
   9227     // - Shift left.
   9228     assert(Origin && "No original load to compare against.");
   9229     unsigned BitWidth = Origin->getValueSizeInBits(0);
   9230     assert(Inst && "This slice is not bound to an instruction");
   9231     assert(Inst->getValueSizeInBits(0) <= BitWidth &&
   9232            "Extracted slice is bigger than the whole type!");
   9233     APInt UsedBits(Inst->getValueSizeInBits(0), 0);
   9234     UsedBits.setAllBits();
   9235     UsedBits = UsedBits.zext(BitWidth);
   9236     UsedBits <<= Shift;
   9237     return UsedBits;
   9238   }
   9239 
   9240   /// \brief Get the size of the slice to be loaded in bytes.
   9241   unsigned getLoadedSize() const {
   9242     unsigned SliceSize = getUsedBits().countPopulation();
   9243     assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
   9244     return SliceSize / 8;
   9245   }
   9246 
   9247   /// \brief Get the type that will be loaded for this slice.
   9248   /// Note: This may not be the final type for the slice.
   9249   EVT getLoadedType() const {
   9250     assert(DAG && "Missing context");
   9251     LLVMContext &Ctxt = *DAG->getContext();
   9252     return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
   9253   }
   9254 
   9255   /// \brief Get the alignment of the load used for this slice.
   9256   unsigned getAlignment() const {
   9257     unsigned Alignment = Origin->getAlignment();
   9258     unsigned Offset = getOffsetFromBase();
   9259     if (Offset != 0)
   9260       Alignment = MinAlign(Alignment, Alignment + Offset);
   9261     return Alignment;
   9262   }
   9263 
   9264   /// \brief Check if this slice can be rewritten with legal operations.
   9265   bool isLegal() const {
   9266     // An invalid slice is not legal.
   9267     if (!Origin || !Inst || !DAG)
   9268       return false;
   9269 
   9270     // Offsets are for indexed load only, we do not handle that.
   9271     if (Origin->getOffset().getOpcode() != ISD::UNDEF)
   9272       return false;
   9273 
   9274     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
   9275 
   9276     // Check that the type is legal.
   9277     EVT SliceType = getLoadedType();
   9278     if (!TLI.isTypeLegal(SliceType))
   9279       return false;
   9280 
   9281     // Check that the load is legal for this type.
   9282     if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
   9283       return false;
   9284 
   9285     // Check that the offset can be computed.
   9286     // 1. Check its type.
   9287     EVT PtrType = Origin->getBasePtr().getValueType();
   9288     if (PtrType == MVT::Untyped || PtrType.isExtended())
   9289       return false;
   9290 
   9291     // 2. Check that it fits in the immediate.
   9292     if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
   9293       return false;
   9294 
   9295     // 3. Check that the computation is legal.
   9296     if (!TLI.isOperationLegal(ISD::ADD, PtrType))
   9297       return false;
   9298 
   9299     // Check that the zext is legal if it needs one.
   9300     EVT TruncateType = Inst->getValueType(0);
   9301     if (TruncateType != SliceType &&
   9302         !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
   9303       return false;
   9304 
   9305     return true;
   9306   }
   9307 
   9308   /// \brief Get the offset in bytes of this slice in the original chunk of
   9309   /// bits.
   9310   /// \pre DAG != nullptr.
   9311   uint64_t getOffsetFromBase() const {
   9312     assert(DAG && "Missing context.");
   9313     bool IsBigEndian =
   9314         DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian();
   9315     assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
   9316     uint64_t Offset = Shift / 8;
   9317     unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
   9318     assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
   9319            "The size of the original loaded type is not a multiple of a"
   9320            " byte.");
   9321     // If Offset is bigger than TySizeInBytes, it means we are loading all
   9322     // zeros. This should have been optimized before in the process.
   9323     assert(TySizeInBytes > Offset &&
   9324            "Invalid shift amount for given loaded size");
   9325     if (IsBigEndian)
   9326       Offset = TySizeInBytes - Offset - getLoadedSize();
   9327     return Offset;
   9328   }
   9329 
   9330   /// \brief Generate the sequence of instructions to load the slice
   9331   /// represented by this object and redirect the uses of this slice to
   9332   /// this new sequence of instructions.
   9333   /// \pre this->Inst && this->Origin are valid Instructions and this
   9334   /// object passed the legal check: LoadedSlice::isLegal returned true.
   9335   /// \return The last instruction of the sequence used to load the slice.
   9336   SDValue loadSlice() const {
   9337     assert(Inst && Origin && "Unable to replace a non-existing slice.");
   9338     const SDValue &OldBaseAddr = Origin->getBasePtr();
   9339     SDValue BaseAddr = OldBaseAddr;
   9340     // Get the offset in that chunk of bytes w.r.t. the endianess.
   9341     int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
   9342     assert(Offset >= 0 && "Offset too big to fit in int64_t!");
   9343     if (Offset) {
   9344       // BaseAddr = BaseAddr + Offset.
   9345       EVT ArithType = BaseAddr.getValueType();
   9346       BaseAddr = DAG->getNode(ISD::ADD, SDLoc(Origin), ArithType, BaseAddr,
   9347                               DAG->getConstant(Offset, ArithType));
   9348     }
   9349 
   9350     // Create the type of the loaded slice according to its size.
   9351     EVT SliceType = getLoadedType();
   9352 
   9353     // Create the load for the slice.
   9354     SDValue LastInst = DAG->getLoad(
   9355         SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
   9356         Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
   9357         Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
   9358     // If the final type is not the same as the loaded type, this means that
   9359     // we have to pad with zero. Create a zero extend for that.
   9360     EVT FinalType = Inst->getValueType(0);
   9361     if (SliceType != FinalType)
   9362       LastInst =
   9363           DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
   9364     return LastInst;
   9365   }
   9366 
   9367   /// \brief Check if this slice can be merged with an expensive cross register
   9368   /// bank copy. E.g.,
   9369   /// i = load i32
   9370   /// f = bitcast i32 i to float
   9371   bool canMergeExpensiveCrossRegisterBankCopy() const {
   9372     if (!Inst || !Inst->hasOneUse())
   9373       return false;
   9374     SDNode *Use = *Inst->use_begin();
   9375     if (Use->getOpcode() != ISD::BITCAST)
   9376       return false;
   9377     assert(DAG && "Missing context");
   9378     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
   9379     EVT ResVT = Use->getValueType(0);
   9380     const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
   9381     const TargetRegisterClass *ArgRC =
   9382         TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
   9383     if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
   9384       return false;
   9385 
   9386     // At this point, we know that we perform a cross-register-bank copy.
   9387     // Check if it is expensive.
   9388     const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo();
   9389     // Assume bitcasts are cheap, unless both register classes do not
   9390     // explicitly share a common sub class.
   9391     if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
   9392       return false;
   9393 
   9394     // Check if it will be merged with the load.
   9395     // 1. Check the alignment constraint.
   9396     unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment(
   9397         ResVT.getTypeForEVT(*DAG->getContext()));
   9398 
   9399     if (RequiredAlignment > getAlignment())
   9400       return false;
   9401 
   9402     // 2. Check that the load is a legal operation for that type.
   9403     if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
   9404       return false;
   9405 
   9406     // 3. Check that we do not have a zext in the way.
   9407     if (Inst->getValueType(0) != getLoadedType())
   9408       return false;
   9409 
   9410     return true;
   9411   }
   9412 };
   9413 }
   9414 
   9415 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
   9416 /// \p UsedBits looks like 0..0 1..1 0..0.
   9417 static bool areUsedBitsDense(const APInt &UsedBits) {
   9418   // If all the bits are one, this is dense!
   9419   if (UsedBits.isAllOnesValue())
   9420     return true;
   9421 
   9422   // Get rid of the unused bits on the right.
   9423   APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
   9424   // Get rid of the unused bits on the left.
   9425   if (NarrowedUsedBits.countLeadingZeros())
   9426     NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
   9427   // Check that the chunk of bits is completely used.
   9428   return NarrowedUsedBits.isAllOnesValue();
   9429 }
   9430 
   9431 /// \brief Check whether or not \p First and \p Second are next to each other
   9432 /// in memory. This means that there is no hole between the bits loaded
   9433 /// by \p First and the bits loaded by \p Second.
   9434 static bool areSlicesNextToEachOther(const LoadedSlice &First,
   9435                                      const LoadedSlice &Second) {
   9436   assert(First.Origin == Second.Origin && First.Origin &&
   9437          "Unable to match different memory origins.");
   9438   APInt UsedBits = First.getUsedBits();
   9439   assert((UsedBits & Second.getUsedBits()) == 0 &&
   9440          "Slices are not supposed to overlap.");
   9441   UsedBits |= Second.getUsedBits();
   9442   return areUsedBitsDense(UsedBits);
   9443 }
   9444 
   9445 /// \brief Adjust the \p GlobalLSCost according to the target
   9446 /// paring capabilities and the layout of the slices.
   9447 /// \pre \p GlobalLSCost should account for at least as many loads as
   9448 /// there is in the slices in \p LoadedSlices.
   9449 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
   9450                                  LoadedSlice::Cost &GlobalLSCost) {
   9451   unsigned NumberOfSlices = LoadedSlices.size();
   9452   // If there is less than 2 elements, no pairing is possible.
   9453   if (NumberOfSlices < 2)
   9454     return;
   9455 
   9456   // Sort the slices so that elements that are likely to be next to each
   9457   // other in memory are next to each other in the list.
   9458   std::sort(LoadedSlices.begin(), LoadedSlices.end(),
   9459             [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
   9460     assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
   9461     return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
   9462   });
   9463   const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
   9464   // First (resp. Second) is the first (resp. Second) potentially candidate
   9465   // to be placed in a paired load.
   9466   const LoadedSlice *First = nullptr;
   9467   const LoadedSlice *Second = nullptr;
   9468   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
   9469                 // Set the beginning of the pair.
   9470                                                            First = Second) {
   9471 
   9472     Second = &LoadedSlices[CurrSlice];
   9473 
   9474     // If First is NULL, it means we start a new pair.
   9475     // Get to the next slice.
   9476     if (!First)
   9477       continue;
   9478 
   9479     EVT LoadedType = First->getLoadedType();
   9480 
   9481     // If the types of the slices are different, we cannot pair them.
   9482     if (LoadedType != Second->getLoadedType())
   9483       continue;
   9484 
   9485     // Check if the target supplies paired loads for this type.
   9486     unsigned RequiredAlignment = 0;
   9487     if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
   9488       // move to the next pair, this type is hopeless.
   9489       Second = nullptr;
   9490       continue;
   9491     }
   9492     // Check if we meet the alignment requirement.
   9493     if (RequiredAlignment > First->getAlignment())
   9494       continue;
   9495 
   9496     // Check that both loads are next to each other in memory.
   9497     if (!areSlicesNextToEachOther(*First, *Second))
   9498       continue;
   9499 
   9500     assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
   9501     --GlobalLSCost.Loads;
   9502     // Move to the next pair.
   9503     Second = nullptr;
   9504   }
   9505 }
   9506 
   9507 /// \brief Check the profitability of all involved LoadedSlice.
   9508 /// Currently, it is considered profitable if there is exactly two
   9509 /// involved slices (1) which are (2) next to each other in memory, and
   9510 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
   9511 ///
   9512 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
   9513 /// the elements themselves.
   9514 ///
   9515 /// FIXME: When the cost model will be mature enough, we can relax
   9516 /// constraints (1) and (2).
   9517 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
   9518                                 const APInt &UsedBits, bool ForCodeSize) {
   9519   unsigned NumberOfSlices = LoadedSlices.size();
   9520   if (StressLoadSlicing)
   9521     return NumberOfSlices > 1;
   9522 
   9523   // Check (1).
   9524   if (NumberOfSlices != 2)
   9525     return false;
   9526 
   9527   // Check (2).
   9528   if (!areUsedBitsDense(UsedBits))
   9529     return false;
   9530 
   9531   // Check (3).
   9532   LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
   9533   // The original code has one big load.
   9534   OrigCost.Loads = 1;
   9535   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
   9536     const LoadedSlice &LS = LoadedSlices[CurrSlice];
   9537     // Accumulate the cost of all the slices.
   9538     LoadedSlice::Cost SliceCost(LS, ForCodeSize);
   9539     GlobalSlicingCost += SliceCost;
   9540 
   9541     // Account as cost in the original configuration the gain obtained
   9542     // with the current slices.
   9543     OrigCost.addSliceGain(LS);
   9544   }
   9545 
   9546   // If the target supports paired load, adjust the cost accordingly.
   9547   adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
   9548   return OrigCost > GlobalSlicingCost;
   9549 }
   9550 
   9551 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
   9552 /// operations, split it in the various pieces being extracted.
   9553 ///
   9554 /// This sort of thing is introduced by SROA.
   9555 /// This slicing takes care not to insert overlapping loads.
   9556 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
   9557 bool DAGCombiner::SliceUpLoad(SDNode *N) {
   9558   if (Level < AfterLegalizeDAG)
   9559     return false;
   9560 
   9561   LoadSDNode *LD = cast<LoadSDNode>(N);
   9562   if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
   9563       !LD->getValueType(0).isInteger())
   9564     return false;
   9565 
   9566   // Keep track of already used bits to detect overlapping values.
   9567   // In that case, we will just abort the transformation.
   9568   APInt UsedBits(LD->getValueSizeInBits(0), 0);
   9569 
   9570   SmallVector<LoadedSlice, 4> LoadedSlices;
   9571 
   9572   // Check if this load is used as several smaller chunks of bits.
   9573   // Basically, look for uses in trunc or trunc(lshr) and record a new chain
   9574   // of computation for each trunc.
   9575   for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
   9576        UI != UIEnd; ++UI) {
   9577     // Skip the uses of the chain.
   9578     if (UI.getUse().getResNo() != 0)
   9579       continue;
   9580 
   9581     SDNode *User = *UI;
   9582     unsigned Shift = 0;
   9583 
   9584     // Check if this is a trunc(lshr).
   9585     if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
   9586         isa<ConstantSDNode>(User->getOperand(1))) {
   9587       Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
   9588       User = *User->use_begin();
   9589     }
   9590 
   9591     // At this point, User is a Truncate, iff we encountered, trunc or
   9592     // trunc(lshr).
   9593     if (User->getOpcode() != ISD::TRUNCATE)
   9594       return false;
   9595 
   9596     // The width of the type must be a power of 2 and greater than 8-bits.
   9597     // Otherwise the load cannot be represented in LLVM IR.
   9598     // Moreover, if we shifted with a non-8-bits multiple, the slice
   9599     // will be across several bytes. We do not support that.
   9600     unsigned Width = User->getValueSizeInBits(0);
   9601     if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
   9602       return 0;
   9603 
   9604     // Build the slice for this chain of computations.
   9605     LoadedSlice LS(User, LD, Shift, &DAG);
   9606     APInt CurrentUsedBits = LS.getUsedBits();
   9607 
   9608     // Check if this slice overlaps with another.
   9609     if ((CurrentUsedBits & UsedBits) != 0)
   9610       return false;
   9611     // Update the bits used globally.
   9612     UsedBits |= CurrentUsedBits;
   9613 
   9614     // Check if the new slice would be legal.
   9615     if (!LS.isLegal())
   9616       return false;
   9617 
   9618     // Record the slice.
   9619     LoadedSlices.push_back(LS);
   9620   }
   9621 
   9622   // Abort slicing if it does not seem to be profitable.
   9623   if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
   9624     return false;
   9625 
   9626   ++SlicedLoads;
   9627 
   9628   // Rewrite each chain to use an independent load.
   9629   // By construction, each chain can be represented by a unique load.
   9630 
   9631   // Prepare the argument for the new token factor for all the slices.
   9632   SmallVector<SDValue, 8> ArgChains;
   9633   for (SmallVectorImpl<LoadedSlice>::const_iterator
   9634            LSIt = LoadedSlices.begin(),
   9635            LSItEnd = LoadedSlices.end();
   9636        LSIt != LSItEnd; ++LSIt) {
   9637     SDValue SliceInst = LSIt->loadSlice();
   9638     CombineTo(LSIt->Inst, SliceInst, true);
   9639     if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
   9640       SliceInst = SliceInst.getOperand(0);
   9641     assert(SliceInst->getOpcode() == ISD::LOAD &&
   9642            "It takes more than a zext to get to the loaded slice!!");
   9643     ArgChains.push_back(SliceInst.getValue(1));
   9644   }
   9645 
   9646   SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
   9647                               ArgChains);
   9648   DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
   9649   return true;
   9650 }
   9651 
   9652 /// Check to see if V is (and load (ptr), imm), where the load is having
   9653 /// specific bytes cleared out.  If so, return the byte size being masked out
   9654 /// and the shift amount.
   9655 static std::pair<unsigned, unsigned>
   9656 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
   9657   std::pair<unsigned, unsigned> Result(0, 0);
   9658 
   9659   // Check for the structure we're looking for.
   9660   if (V->getOpcode() != ISD::AND ||
   9661       !isa<ConstantSDNode>(V->getOperand(1)) ||
   9662       !ISD::isNormalLoad(V->getOperand(0).getNode()))
   9663     return Result;
   9664 
   9665   // Check the chain and pointer.
   9666   LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
   9667   if (LD->getBasePtr() != Ptr) return Result;  // Not from same pointer.
   9668 
   9669   // The store should be chained directly to the load or be an operand of a
   9670   // tokenfactor.
   9671   if (LD == Chain.getNode())
   9672     ; // ok.
   9673   else if (Chain->getOpcode() != ISD::TokenFactor)
   9674     return Result; // Fail.
   9675   else {
   9676     bool isOk = false;
   9677     for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
   9678       if (Chain->getOperand(i).getNode() == LD) {
   9679         isOk = true;
   9680         break;
   9681       }
   9682     if (!isOk) return Result;
   9683   }
   9684 
   9685   // This only handles simple types.
   9686   if (V.getValueType() != MVT::i16 &&
   9687       V.getValueType() != MVT::i32 &&
   9688       V.getValueType() != MVT::i64)
   9689     return Result;
   9690 
   9691   // Check the constant mask.  Invert it so that the bits being masked out are
   9692   // 0 and the bits being kept are 1.  Use getSExtValue so that leading bits
   9693   // follow the sign bit for uniformity.
   9694   uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
   9695   unsigned NotMaskLZ = countLeadingZeros(NotMask);
   9696   if (NotMaskLZ & 7) return Result;  // Must be multiple of a byte.
   9697   unsigned NotMaskTZ = countTrailingZeros(NotMask);
   9698   if (NotMaskTZ & 7) return Result;  // Must be multiple of a byte.
   9699   if (NotMaskLZ == 64) return Result;  // All zero mask.
   9700 
   9701   // See if we have a continuous run of bits.  If so, we have 0*1+0*
   9702   if (countTrailingOnes(NotMask >> NotMaskTZ) + NotMaskTZ + NotMaskLZ != 64)
   9703     return Result;
   9704 
   9705   // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
   9706   if (V.getValueType() != MVT::i64 && NotMaskLZ)
   9707     NotMaskLZ -= 64-V.getValueSizeInBits();
   9708 
   9709   unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
   9710   switch (MaskedBytes) {
   9711   case 1:
   9712   case 2:
   9713   case 4: break;
   9714   default: return Result; // All one mask, or 5-byte mask.
   9715   }
   9716 
   9717   // Verify that the first bit starts at a multiple of mask so that the access
   9718   // is aligned the same as the access width.
   9719   if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
   9720 
   9721   Result.first = MaskedBytes;
   9722   Result.second = NotMaskTZ/8;
   9723   return Result;
   9724 }
   9725 
   9726 
   9727 /// Check to see if IVal is something that provides a value as specified by
   9728 /// MaskInfo. If so, replace the specified store with a narrower store of
   9729 /// truncated IVal.
   9730 static SDNode *
   9731 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
   9732                                 SDValue IVal, StoreSDNode *St,
   9733                                 DAGCombiner *DC) {
   9734   unsigned NumBytes = MaskInfo.first;
   9735   unsigned ByteShift = MaskInfo.second;
   9736   SelectionDAG &DAG = DC->getDAG();
   9737 
   9738   // Check to see if IVal is all zeros in the part being masked in by the 'or'
   9739   // that uses this.  If not, this is not a replacement.
   9740   APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
   9741                                   ByteShift*8, (ByteShift+NumBytes)*8);
   9742   if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
   9743 
   9744   // Check that it is legal on the target to do this.  It is legal if the new
   9745   // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
   9746   // legalization.
   9747   MVT VT = MVT::getIntegerVT(NumBytes*8);
   9748   if (!DC->isTypeLegal(VT))
   9749     return nullptr;
   9750 
   9751   // Okay, we can do this!  Replace the 'St' store with a store of IVal that is
   9752   // shifted by ByteShift and truncated down to NumBytes.
   9753   if (ByteShift)
   9754     IVal = DAG.getNode(ISD::SRL, SDLoc(IVal), IVal.getValueType(), IVal,
   9755                        DAG.getConstant(ByteShift*8,
   9756                                     DC->getShiftAmountTy(IVal.getValueType())));
   9757 
   9758   // Figure out the offset for the store and the alignment of the access.
   9759   unsigned StOffset;
   9760   unsigned NewAlign = St->getAlignment();
   9761 
   9762   if (DAG.getTargetLoweringInfo().isLittleEndian())
   9763     StOffset = ByteShift;
   9764   else
   9765     StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
   9766 
   9767   SDValue Ptr = St->getBasePtr();
   9768   if (StOffset) {
   9769     Ptr = DAG.getNode(ISD::ADD, SDLoc(IVal), Ptr.getValueType(),
   9770                       Ptr, DAG.getConstant(StOffset, Ptr.getValueType()));
   9771     NewAlign = MinAlign(NewAlign, StOffset);
   9772   }
   9773 
   9774   // Truncate down to the new size.
   9775   IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
   9776 
   9777   ++OpsNarrowed;
   9778   return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
   9779                       St->getPointerInfo().getWithOffset(StOffset),
   9780                       false, false, NewAlign).getNode();
   9781 }
   9782 
   9783 
   9784 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and
   9785 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try
   9786 /// narrowing the load and store if it would end up being a win for performance
   9787 /// or code size.
   9788 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
   9789   StoreSDNode *ST  = cast<StoreSDNode>(N);
   9790   if (ST->isVolatile())
   9791     return SDValue();
   9792 
   9793   SDValue Chain = ST->getChain();
   9794   SDValue Value = ST->getValue();
   9795   SDValue Ptr   = ST->getBasePtr();
   9796   EVT VT = Value.getValueType();
   9797 
   9798   if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
   9799     return SDValue();
   9800 
   9801   unsigned Opc = Value.getOpcode();
   9802 
   9803   // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
   9804   // is a byte mask indicating a consecutive number of bytes, check to see if
   9805   // Y is known to provide just those bytes.  If so, we try to replace the
   9806   // load + replace + store sequence with a single (narrower) store, which makes
   9807   // the load dead.
   9808   if (Opc == ISD::OR) {
   9809     std::pair<unsigned, unsigned> MaskedLoad;
   9810     MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
   9811     if (MaskedLoad.first)
   9812       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
   9813                                                   Value.getOperand(1), ST,this))
   9814         return SDValue(NewST, 0);
   9815 
   9816     // Or is commutative, so try swapping X and Y.
   9817     MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
   9818     if (MaskedLoad.first)
   9819       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
   9820                                                   Value.getOperand(0), ST,this))
   9821         return SDValue(NewST, 0);
   9822   }
   9823 
   9824   if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
   9825       Value.getOperand(1).getOpcode() != ISD::Constant)
   9826     return SDValue();
   9827 
   9828   SDValue N0 = Value.getOperand(0);
   9829   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
   9830       Chain == SDValue(N0.getNode(), 1)) {
   9831     LoadSDNode *LD = cast<LoadSDNode>(N0);
   9832     if (LD->getBasePtr() != Ptr ||
   9833         LD->getPointerInfo().getAddrSpace() !=
   9834         ST->getPointerInfo().getAddrSpace())
   9835       return SDValue();
   9836 
   9837     // Find the type to narrow it the load / op / store to.
   9838     SDValue N1 = Value.getOperand(1);
   9839     unsigned BitWidth = N1.getValueSizeInBits();
   9840     APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
   9841     if (Opc == ISD::AND)
   9842       Imm ^= APInt::getAllOnesValue(BitWidth);
   9843     if (Imm == 0 || Imm.isAllOnesValue())
   9844       return SDValue();
   9845     unsigned ShAmt = Imm.countTrailingZeros();
   9846     unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
   9847     unsigned NewBW = NextPowerOf2(MSB - ShAmt);
   9848     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
   9849     // The narrowing should be profitable, the load/store operation should be
   9850     // legal (or custom) and the store size should be equal to the NewVT width.
   9851     while (NewBW < BitWidth &&
   9852            (NewVT.getStoreSizeInBits() != NewBW ||
   9853             !TLI.isOperationLegalOrCustom(Opc, NewVT) ||
   9854             !TLI.isNarrowingProfitable(VT, NewVT))) {
   9855       NewBW = NextPowerOf2(NewBW);
   9856       NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
   9857     }
   9858     if (NewBW >= BitWidth)
   9859       return SDValue();
   9860 
   9861     // If the lsb changed does not start at the type bitwidth boundary,
   9862     // start at the previous one.
   9863     if (ShAmt % NewBW)
   9864       ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
   9865     APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
   9866                                    std::min(BitWidth, ShAmt + NewBW));
   9867     if ((Imm & Mask) == Imm) {
   9868       APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
   9869       if (Opc == ISD::AND)
   9870         NewImm ^= APInt::getAllOnesValue(NewBW);
   9871       uint64_t PtrOff = ShAmt / 8;
   9872       // For big endian targets, we need to adjust the offset to the pointer to
   9873       // load the correct bytes.
   9874       if (TLI.isBigEndian())
   9875         PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
   9876 
   9877       unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
   9878       Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
   9879       if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
   9880         return SDValue();
   9881 
   9882       SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
   9883                                    Ptr.getValueType(), Ptr,
   9884                                    DAG.getConstant(PtrOff, Ptr.getValueType()));
   9885       SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
   9886                                   LD->getChain(), NewPtr,
   9887                                   LD->getPointerInfo().getWithOffset(PtrOff),
   9888                                   LD->isVolatile(), LD->isNonTemporal(),
   9889                                   LD->isInvariant(), NewAlign,
   9890                                   LD->getAAInfo());
   9891       SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
   9892                                    DAG.getConstant(NewImm, NewVT));
   9893       SDValue NewST = DAG.getStore(Chain, SDLoc(N),
   9894                                    NewVal, NewPtr,
   9895                                    ST->getPointerInfo().getWithOffset(PtrOff),
   9896                                    false, false, NewAlign);
   9897 
   9898       AddToWorklist(NewPtr.getNode());
   9899       AddToWorklist(NewLD.getNode());
   9900       AddToWorklist(NewVal.getNode());
   9901       WorklistRemover DeadNodes(*this);
   9902       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
   9903       ++OpsNarrowed;
   9904       return NewST;
   9905     }
   9906   }
   9907 
   9908   return SDValue();
   9909 }
   9910 
   9911 /// For a given floating point load / store pair, if the load value isn't used
   9912 /// by any other operations, then consider transforming the pair to integer
   9913 /// load / store operations if the target deems the transformation profitable.
   9914 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
   9915   StoreSDNode *ST  = cast<StoreSDNode>(N);
   9916   SDValue Chain = ST->getChain();
   9917   SDValue Value = ST->getValue();
   9918   if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
   9919       Value.hasOneUse() &&
   9920       Chain == SDValue(Value.getNode(), 1)) {
   9921     LoadSDNode *LD = cast<LoadSDNode>(Value);
   9922     EVT VT = LD->getMemoryVT();
   9923     if (!VT.isFloatingPoint() ||
   9924         VT != ST->getMemoryVT() ||
   9925         LD->isNonTemporal() ||
   9926         ST->isNonTemporal() ||
   9927         LD->getPointerInfo().getAddrSpace() != 0 ||
   9928         ST->getPointerInfo().getAddrSpace() != 0)
   9929       return SDValue();
   9930 
   9931     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
   9932     if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
   9933         !TLI.isOperationLegal(ISD::STORE, IntVT) ||
   9934         !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
   9935         !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
   9936       return SDValue();
   9937 
   9938     unsigned LDAlign = LD->getAlignment();
   9939     unsigned STAlign = ST->getAlignment();
   9940     Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
   9941     unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
   9942     if (LDAlign < ABIAlign || STAlign < ABIAlign)
   9943       return SDValue();
   9944 
   9945     SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
   9946                                 LD->getChain(), LD->getBasePtr(),
   9947                                 LD->getPointerInfo(),
   9948                                 false, false, false, LDAlign);
   9949 
   9950     SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
   9951                                  NewLD, ST->getBasePtr(),
   9952                                  ST->getPointerInfo(),
   9953                                  false, false, STAlign);
   9954 
   9955     AddToWorklist(NewLD.getNode());
   9956     AddToWorklist(NewST.getNode());
   9957     WorklistRemover DeadNodes(*this);
   9958     DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
   9959     ++LdStFP2Int;
   9960     return NewST;
   9961   }
   9962 
   9963   return SDValue();
   9964 }
   9965 
   9966 namespace {
   9967 /// Helper struct to parse and store a memory address as base + index + offset.
   9968 /// We ignore sign extensions when it is safe to do so.
   9969 /// The following two expressions are not equivalent. To differentiate we need
   9970 /// to store whether there was a sign extension involved in the index
   9971 /// computation.
   9972 ///  (load (i64 add (i64 copyfromreg %c)
   9973 ///                 (i64 signextend (add (i8 load %index)
   9974 ///                                      (i8 1))))
   9975 /// vs
   9976 ///
   9977 /// (load (i64 add (i64 copyfromreg %c)
   9978 ///                (i64 signextend (i32 add (i32 signextend (i8 load %index))
   9979 ///                                         (i32 1)))))
   9980 struct BaseIndexOffset {
   9981   SDValue Base;
   9982   SDValue Index;
   9983   int64_t Offset;
   9984   bool IsIndexSignExt;
   9985 
   9986   BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
   9987 
   9988   BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
   9989                   bool IsIndexSignExt) :
   9990     Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
   9991 
   9992   bool equalBaseIndex(const BaseIndexOffset &Other) {
   9993     return Other.Base == Base && Other.Index == Index &&
   9994       Other.IsIndexSignExt == IsIndexSignExt;
   9995   }
   9996 
   9997   /// Parses tree in Ptr for base, index, offset addresses.
   9998   static BaseIndexOffset match(SDValue Ptr) {
   9999     bool IsIndexSignExt = false;
   10000 
   10001     // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
   10002     // instruction, then it could be just the BASE or everything else we don't
   10003     // know how to handle. Just use Ptr as BASE and give up.
   10004     if (Ptr->getOpcode() != ISD::ADD)
   10005       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
   10006 
   10007     // We know that we have at least an ADD instruction. Try to pattern match
   10008     // the simple case of BASE + OFFSET.
   10009     if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
   10010       int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
   10011       return  BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
   10012                               IsIndexSignExt);
   10013     }
   10014 
   10015     // Inside a loop the current BASE pointer is calculated using an ADD and a
   10016     // MUL instruction. In this case Ptr is the actual BASE pointer.
   10017     // (i64 add (i64 %array_ptr)
   10018     //          (i64 mul (i64 %induction_var)
   10019     //                   (i64 %element_size)))
   10020     if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
   10021       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
   10022 
   10023     // Look at Base + Index + Offset cases.
   10024     SDValue Base = Ptr->getOperand(0);
   10025     SDValue IndexOffset = Ptr->getOperand(1);
   10026 
   10027     // Skip signextends.
   10028     if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
   10029       IndexOffset = IndexOffset->getOperand(0);
   10030       IsIndexSignExt = true;
   10031     }
   10032 
   10033     // Either the case of Base + Index (no offset) or something else.
   10034     if (IndexOffset->getOpcode() != ISD::ADD)
   10035       return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
   10036 
   10037     // Now we have the case of Base + Index + offset.
   10038     SDValue Index = IndexOffset->getOperand(0);
   10039     SDValue Offset = IndexOffset->getOperand(1);
   10040 
   10041     if (!isa<ConstantSDNode>(Offset))
   10042       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
   10043 
   10044     // Ignore signextends.
   10045     if (Index->getOpcode() == ISD::SIGN_EXTEND) {
   10046       Index = Index->getOperand(0);
   10047       IsIndexSignExt = true;
   10048     } else IsIndexSignExt = false;
   10049 
   10050     int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
   10051     return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
   10052   }
   10053 };
   10054 } // namespace
   10055 
   10056 bool DAGCombiner::MergeStoresOfConstantsOrVecElts(
   10057                   SmallVectorImpl<MemOpLink> &StoreNodes, EVT MemVT,
   10058                   unsigned NumElem, bool IsConstantSrc, bool UseVector) {
   10059   // Make sure we have something to merge.
   10060   if (NumElem < 2)
   10061     return false;
   10062 
   10063   int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
   10064   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
   10065   unsigned LatestNodeUsed = 0;
   10066 
   10067   for (unsigned i=0; i < NumElem; ++i) {
   10068     // Find a chain for the new wide-store operand. Notice that some
   10069     // of the store nodes that we found may not be selected for inclusion
   10070     // in the wide store. The chain we use needs to be the chain of the
   10071     // latest store node which is *used* and replaced by the wide store.
   10072     if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum)
   10073       LatestNodeUsed = i;
   10074   }
   10075 
   10076   // The latest Node in the DAG.
   10077   LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode;
   10078   SDLoc DL(StoreNodes[0].MemNode);
   10079 
   10080   SDValue StoredVal;
   10081   if (UseVector) {
   10082     // Find a legal type for the vector store.
   10083     EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
   10084     assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
   10085     if (IsConstantSrc) {
   10086       // A vector store with a constant source implies that the constant is
   10087       // zero; we only handle merging stores of constant zeros because the zero
   10088       // can be materialized without a load.
   10089       // It may be beneficial to loosen this restriction to allow non-zero
   10090       // store merging.
   10091       StoredVal = DAG.getConstant(0, Ty);
   10092     } else {
   10093       SmallVector<SDValue, 8> Ops;
   10094       for (unsigned i = 0; i < NumElem ; ++i) {
   10095         StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
   10096         SDValue Val = St->getValue();
   10097         // All of the operands of a BUILD_VECTOR must have the same type.
   10098         if (Val.getValueType() != MemVT)
   10099           return false;
   10100         Ops.push_back(Val);
   10101       }
   10102 
   10103       // Build the extracted vector elements back into a vector.
   10104       StoredVal = DAG.getNode(ISD::BUILD_VECTOR, DL, Ty, Ops);
   10105     }
   10106   } else {
   10107     // We should always use a vector store when merging extracted vector
   10108     // elements, so this path implies a store of constants.
   10109     assert(IsConstantSrc && "Merged vector elements should use vector store");
   10110 
   10111     unsigned StoreBW = NumElem * ElementSizeBytes * 8;
   10112     APInt StoreInt(StoreBW, 0);
   10113 
   10114     // Construct a single integer constant which is made of the smaller
   10115     // constant inputs.
   10116     bool IsLE = TLI.isLittleEndian();
   10117     for (unsigned i = 0; i < NumElem ; ++i) {
   10118       unsigned Idx = IsLE ? (NumElem - 1 - i) : i;
   10119       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
   10120       SDValue Val = St->getValue();
   10121       StoreInt <<= ElementSizeBytes*8;
   10122       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
   10123         StoreInt |= C->getAPIntValue().zext(StoreBW);
   10124       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
   10125         StoreInt |= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
   10126       } else {
   10127         llvm_unreachable("Invalid constant element type");
   10128       }
   10129     }
   10130 
   10131     // Create the new Load and Store operations.
   10132     EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
   10133     StoredVal = DAG.getConstant(StoreInt, StoreTy);
   10134   }
   10135 
   10136   SDValue NewStore = DAG.getStore(LatestOp->getChain(), DL, StoredVal,
   10137                                   FirstInChain->getBasePtr(),
   10138                                   FirstInChain->getPointerInfo(),
   10139                                   false, false,
   10140                                   FirstInChain->getAlignment());
   10141 
   10142   // Replace the last store with the new store
   10143   CombineTo(LatestOp, NewStore);
   10144   // Erase all other stores.
   10145   for (unsigned i = 0; i < NumElem ; ++i) {
   10146     if (StoreNodes[i].MemNode == LatestOp)
   10147       continue;
   10148     StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
   10149     // ReplaceAllUsesWith will replace all uses that existed when it was
   10150     // called, but graph optimizations may cause new ones to appear. For
   10151     // example, the case in pr14333 looks like
   10152     //
   10153     //  St's chain -> St -> another store -> X
   10154     //
   10155     // And the only difference from St to the other store is the chain.
   10156     // When we change it's chain to be St's chain they become identical,
   10157     // get CSEed and the net result is that X is now a use of St.
   10158     // Since we know that St is redundant, just iterate.
   10159     while (!St->use_empty())
   10160       DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
   10161     deleteAndRecombine(St);
   10162   }
   10163 
   10164   return true;
   10165 }
   10166 
   10167 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
   10168   if (OptLevel == CodeGenOpt::None)
   10169     return false;
   10170 
   10171   EVT MemVT = St->getMemoryVT();
   10172   int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
   10173   bool NoVectors = DAG.getMachineFunction().getFunction()->hasFnAttribute(
   10174       Attribute::NoImplicitFloat);
   10175 
   10176   // Don't merge vectors into wider inputs.
   10177   if (MemVT.isVector() || !MemVT.isSimple())
   10178     return false;
   10179 
   10180   // Perform an early exit check. Do not bother looking at stored values that
   10181   // are not constants, loads, or extracted vector elements.
   10182   SDValue StoredVal = St->getValue();
   10183   bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
   10184   bool IsConstantSrc = isa<ConstantSDNode>(StoredVal) ||
   10185                        isa<ConstantFPSDNode>(StoredVal);
   10186   bool IsExtractVecEltSrc = (StoredVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT);
   10187 
   10188   if (!IsConstantSrc && !IsLoadSrc && !IsExtractVecEltSrc)
   10189     return false;
   10190 
   10191   // Only look at ends of store sequences.
   10192   SDValue Chain = SDValue(St, 0);
   10193   if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
   10194     return false;
   10195 
   10196   // This holds the base pointer, index, and the offset in bytes from the base
   10197   // pointer.
   10198   BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
   10199 
   10200   // We must have a base and an offset.
   10201   if (!BasePtr.Base.getNode())
   10202     return false;
   10203 
   10204   // Do not handle stores to undef base pointers.
   10205   if (BasePtr.Base.getOpcode() == ISD::UNDEF)
   10206     return false;
   10207 
   10208   // Save the LoadSDNodes that we find in the chain.
   10209   // We need to make sure that these nodes do not interfere with
   10210   // any of the store nodes.
   10211   SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
   10212 
   10213   // Save the StoreSDNodes that we find in the chain.
   10214   SmallVector<MemOpLink, 8> StoreNodes;
   10215 
   10216   // Walk up the chain and look for nodes with offsets from the same
   10217   // base pointer. Stop when reaching an instruction with a different kind
   10218   // or instruction which has a different base pointer.
   10219   unsigned Seq = 0;
   10220   StoreSDNode *Index = St;
   10221   while (Index) {
   10222     // If the chain has more than one use, then we can't reorder the mem ops.
   10223     if (Index != St && !SDValue(Index, 0)->hasOneUse())
   10224       break;
   10225 
   10226     // Find the base pointer and offset for this memory node.
   10227     BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
   10228 
   10229     // Check that the base pointer is the same as the original one.
   10230     if (!Ptr.equalBaseIndex(BasePtr))
   10231       break;
   10232 
   10233     // Check that the alignment is the same.
   10234     if (Index->getAlignment() != St->getAlignment())
   10235       break;
   10236 
   10237     // The memory operands must not be volatile.
   10238     if (Index->isVolatile() || Index->isIndexed())
   10239       break;
   10240 
   10241     // No truncation.
   10242     if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
   10243       if (St->isTruncatingStore())
   10244         break;
   10245 
   10246     // The stored memory type must be the same.
   10247     if (Index->getMemoryVT() != MemVT)
   10248       break;
   10249 
   10250     // We do not allow unaligned stores because we want to prevent overriding
   10251     // stores.
   10252     if (Index->getAlignment()*8 != MemVT.getSizeInBits())
   10253       break;
   10254 
   10255     // We found a potential memory operand to merge.
   10256     StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
   10257 
   10258     // Find the next memory operand in the chain. If the next operand in the
   10259     // chain is a store then move up and continue the scan with the next
   10260     // memory operand. If the next operand is a load save it and use alias
   10261     // information to check if it interferes with anything.
   10262     SDNode *NextInChain = Index->getChain().getNode();
   10263     while (1) {
   10264       if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
   10265         // We found a store node. Use it for the next iteration.
   10266         Index = STn;
   10267         break;
   10268       } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
   10269         if (Ldn->isVolatile()) {
   10270           Index = nullptr;
   10271           break;
   10272         }
   10273 
   10274         // Save the load node for later. Continue the scan.
   10275         AliasLoadNodes.push_back(Ldn);
   10276         NextInChain = Ldn->getChain().getNode();
   10277         continue;
   10278       } else {
   10279         Index = nullptr;
   10280         break;
   10281       }
   10282     }
   10283   }
   10284 
   10285   // Check if there is anything to merge.
   10286   if (StoreNodes.size() < 2)
   10287     return false;
   10288 
   10289   // Sort the memory operands according to their distance from the base pointer.
   10290   std::sort(StoreNodes.begin(), StoreNodes.end(),
   10291             [](MemOpLink LHS, MemOpLink RHS) {
   10292     return LHS.OffsetFromBase < RHS.OffsetFromBase ||
   10293            (LHS.OffsetFromBase == RHS.OffsetFromBase &&
   10294             LHS.SequenceNum > RHS.SequenceNum);
   10295   });
   10296 
   10297   // Scan the memory operations on the chain and find the first non-consecutive
   10298   // store memory address.
   10299   unsigned LastConsecutiveStore = 0;
   10300   int64_t StartAddress = StoreNodes[0].OffsetFromBase;
   10301   for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
   10302 
   10303     // Check that the addresses are consecutive starting from the second
   10304     // element in the list of stores.
   10305     if (i > 0) {
   10306       int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
   10307       if (CurrAddress - StartAddress != (ElementSizeBytes * i))
   10308         break;
   10309     }
   10310 
   10311     bool Alias = false;
   10312     // Check if this store interferes with any of the loads that we found.
   10313     for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
   10314       if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
   10315         Alias = true;
   10316         break;
   10317       }
   10318     // We found a load that alias with this store. Stop the sequence.
   10319     if (Alias)
   10320       break;
   10321 
   10322     // Mark this node as useful.
   10323     LastConsecutiveStore = i;
   10324   }
   10325 
   10326   // The node with the lowest store address.
   10327   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
   10328 
   10329   // Store the constants into memory as one consecutive store.
   10330   if (IsConstantSrc) {
   10331     unsigned LastLegalType = 0;
   10332     unsigned LastLegalVectorType = 0;
   10333     bool NonZero = false;
   10334     for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
   10335       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
   10336       SDValue StoredVal = St->getValue();
   10337 
   10338       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
   10339         NonZero |= !C->isNullValue();
   10340       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
   10341         NonZero |= !C->getConstantFPValue()->isNullValue();
   10342       } else {
   10343         // Non-constant.
   10344         break;
   10345       }
   10346 
   10347       // Find a legal type for the constant store.
   10348       unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
   10349       EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
   10350       if (TLI.isTypeLegal(StoreTy))
   10351         LastLegalType = i+1;
   10352       // Or check whether a truncstore is legal.
   10353       else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
   10354                TargetLowering::TypePromoteInteger) {
   10355         EVT LegalizedStoredValueTy =
   10356           TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
   10357         if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy))
   10358           LastLegalType = i+1;
   10359       }
   10360 
   10361       // Find a legal type for the vector store.
   10362       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
   10363       if (TLI.isTypeLegal(Ty))
   10364         LastLegalVectorType = i + 1;
   10365     }
   10366 
   10367     // We only use vectors if the constant is known to be zero and the
   10368     // function is not marked with the noimplicitfloat attribute.
   10369     if (NonZero || NoVectors)
   10370       LastLegalVectorType = 0;
   10371 
   10372     // Check if we found a legal integer type to store.
   10373     if (LastLegalType == 0 && LastLegalVectorType == 0)
   10374       return false;
   10375 
   10376     bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
   10377     unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
   10378 
   10379     return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem,
   10380                                            true, UseVector);
   10381   }
   10382 
   10383   // When extracting multiple vector elements, try to store them
   10384   // in one vector store rather than a sequence of scalar stores.
   10385   if (IsExtractVecEltSrc) {
   10386     unsigned NumElem = 0;
   10387     for (unsigned i = 0; i < LastConsecutiveStore + 1; ++i) {
   10388       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
   10389       SDValue StoredVal = St->getValue();
   10390       // This restriction could be loosened.
   10391       // Bail out if any stored values are not elements extracted from a vector.
   10392       // It should be possible to handle mixed sources, but load sources need
   10393       // more careful handling (see the block of code below that handles
   10394       // consecutive loads).
   10395       if (StoredVal.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
   10396         return false;
   10397 
   10398       // Find a legal type for the vector store.
   10399       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
   10400       if (TLI.isTypeLegal(Ty))
   10401         NumElem = i + 1;
   10402     }
   10403 
   10404     return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem,
   10405                                            false, true);
   10406   }
   10407 
   10408   // Below we handle the case of multiple consecutive stores that
   10409   // come from multiple consecutive loads. We merge them into a single
   10410   // wide load and a single wide store.
   10411 
   10412   // Look for load nodes which are used by the stored values.
   10413   SmallVector<MemOpLink, 8> LoadNodes;
   10414 
   10415   // Find acceptable loads. Loads need to have the same chain (token factor),
   10416   // must not be zext, volatile, indexed, and they must be consecutive.
   10417   BaseIndexOffset LdBasePtr;
   10418   for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
   10419     StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
   10420     LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
   10421     if (!Ld) break;
   10422 
   10423     // Loads must only have one use.
   10424     if (!Ld->hasNUsesOfValue(1, 0))
   10425       break;
   10426 
   10427     // Check that the alignment is the same as the stores.
   10428     if (Ld->getAlignment() != St->getAlignment())
   10429       break;
   10430 
   10431     // The memory operands must not be volatile.
   10432     if (Ld->isVolatile() || Ld->isIndexed())
   10433       break;
   10434 
   10435     // We do not accept ext loads.
   10436     if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
   10437       break;
   10438 
   10439     // The stored memory type must be the same.
   10440     if (Ld->getMemoryVT() != MemVT)
   10441       break;
   10442 
   10443     BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
   10444     // If this is not the first ptr that we check.
   10445     if (LdBasePtr.Base.getNode()) {
   10446       // The base ptr must be the same.
   10447       if (!LdPtr.equalBaseIndex(LdBasePtr))
   10448         break;
   10449     } else {
   10450       // Check that all other base pointers are the same as this one.
   10451       LdBasePtr = LdPtr;
   10452     }
   10453 
   10454     // We found a potential memory operand to merge.
   10455     LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
   10456   }
   10457 
   10458   if (LoadNodes.size() < 2)
   10459     return false;
   10460 
   10461   // If we have load/store pair instructions and we only have two values,
   10462   // don't bother.
   10463   unsigned RequiredAlignment;
   10464   if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) &&
   10465       St->getAlignment() >= RequiredAlignment)
   10466     return false;
   10467 
   10468   // Scan the memory operations on the chain and find the first non-consecutive
   10469   // load memory address. These variables hold the index in the store node
   10470   // array.
   10471   unsigned LastConsecutiveLoad = 0;
   10472   // This variable refers to the size and not index in the array.
   10473   unsigned LastLegalVectorType = 0;
   10474   unsigned LastLegalIntegerType = 0;
   10475   StartAddress = LoadNodes[0].OffsetFromBase;
   10476   SDValue FirstChain = LoadNodes[0].MemNode->getChain();
   10477   for (unsigned i = 1; i < LoadNodes.size(); ++i) {
   10478     // All loads much share the same chain.
   10479     if (LoadNodes[i].MemNode->getChain() != FirstChain)
   10480       break;
   10481 
   10482     int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
   10483     if (CurrAddress - StartAddress != (ElementSizeBytes * i))
   10484       break;
   10485     LastConsecutiveLoad = i;
   10486 
   10487     // Find a legal type for the vector store.
   10488     EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
   10489     if (TLI.isTypeLegal(StoreTy))
   10490       LastLegalVectorType = i + 1;
   10491 
   10492     // Find a legal type for the integer store.
   10493     unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
   10494     StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
   10495     if (TLI.isTypeLegal(StoreTy))
   10496       LastLegalIntegerType = i + 1;
   10497     // Or check whether a truncstore and extload is legal.
   10498     else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
   10499              TargetLowering::TypePromoteInteger) {
   10500       EVT LegalizedStoredValueTy =
   10501         TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
   10502       if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
   10503           TLI.isLoadExtLegal(ISD::ZEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
   10504           TLI.isLoadExtLegal(ISD::SEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
   10505           TLI.isLoadExtLegal(ISD::EXTLOAD, LegalizedStoredValueTy, StoreTy))
   10506         LastLegalIntegerType = i+1;
   10507     }
   10508   }
   10509 
   10510   // Only use vector types if the vector type is larger than the integer type.
   10511   // If they are the same, use integers.
   10512   bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
   10513   unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
   10514 
   10515   // We add +1 here because the LastXXX variables refer to location while
   10516   // the NumElem refers to array/index size.
   10517   unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
   10518   NumElem = std::min(LastLegalType, NumElem);
   10519 
   10520   if (NumElem < 2)
   10521     return false;
   10522 
   10523   // The latest Node in the DAG.
   10524   unsigned LatestNodeUsed = 0;
   10525   for (unsigned i=1; i<NumElem; ++i) {
   10526     // Find a chain for the new wide-store operand. Notice that some
   10527     // of the store nodes that we found may not be selected for inclusion
   10528     // in the wide store. The chain we use needs to be the chain of the
   10529     // latest store node which is *used* and replaced by the wide store.
   10530     if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum)
   10531       LatestNodeUsed = i;
   10532   }
   10533 
   10534   LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode;
   10535 
   10536   // Find if it is better to use vectors or integers to load and store
   10537   // to memory.
   10538   EVT JointMemOpVT;
   10539   if (UseVectorTy) {
   10540     JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
   10541   } else {
   10542     unsigned StoreBW = NumElem * ElementSizeBytes * 8;
   10543     JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
   10544   }
   10545 
   10546   SDLoc LoadDL(LoadNodes[0].MemNode);
   10547   SDLoc StoreDL(StoreNodes[0].MemNode);
   10548 
   10549   LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
   10550   SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL,
   10551                                 FirstLoad->getChain(),
   10552                                 FirstLoad->getBasePtr(),
   10553                                 FirstLoad->getPointerInfo(),
   10554                                 false, false, false,
   10555                                 FirstLoad->getAlignment());
   10556 
   10557   SDValue NewStore = DAG.getStore(LatestOp->getChain(), StoreDL, NewLoad,
   10558                                   FirstInChain->getBasePtr(),
   10559                                   FirstInChain->getPointerInfo(), false, false,
   10560                                   FirstInChain->getAlignment());
   10561 
   10562   // Replace one of the loads with the new load.
   10563   LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
   10564   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
   10565                                 SDValue(NewLoad.getNode(), 1));
   10566 
   10567   // Remove the rest of the load chains.
   10568   for (unsigned i = 1; i < NumElem ; ++i) {
   10569     // Replace all chain users of the old load nodes with the chain of the new
   10570     // load node.
   10571     LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
   10572     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
   10573   }
   10574 
   10575   // Replace the last store with the new store.
   10576   CombineTo(LatestOp, NewStore);
   10577   // Erase all other stores.
   10578   for (unsigned i = 0; i < NumElem ; ++i) {
   10579     // Remove all Store nodes.
   10580     if (StoreNodes[i].MemNode == LatestOp)
   10581       continue;
   10582     StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
   10583     DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
   10584     deleteAndRecombine(St);
   10585   }
   10586 
   10587   return true;
   10588 }
   10589 
   10590 SDValue DAGCombiner::visitSTORE(SDNode *N) {
   10591   StoreSDNode *ST  = cast<StoreSDNode>(N);
   10592   SDValue Chain = ST->getChain();
   10593   SDValue Value = ST->getValue();
   10594   SDValue Ptr   = ST->getBasePtr();
   10595 
   10596   // If this is a store of a bit convert, store the input value if the
   10597   // resultant store does not need a higher alignment than the original.
   10598   if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
   10599       ST->isUnindexed()) {
   10600     unsigned OrigAlign = ST->getAlignment();
   10601     EVT SVT = Value.getOperand(0).getValueType();
   10602     unsigned Align = TLI.getDataLayout()->
   10603       getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
   10604     if (Align <= OrigAlign &&
   10605         ((!LegalOperations && !ST->isVolatile()) ||
   10606          TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
   10607       return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
   10608                           Ptr, ST->getPointerInfo(), ST->isVolatile(),
   10609                           ST->isNonTemporal(), OrigAlign,
   10610                           ST->getAAInfo());
   10611   }
   10612 
   10613   // Turn 'store undef, Ptr' -> nothing.
   10614   if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
   10615     return Chain;
   10616 
   10617   // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
   10618   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
   10619     // NOTE: If the original store is volatile, this transform must not increase
   10620     // the number of stores.  For example, on x86-32 an f64 can be stored in one
   10621     // processor operation but an i64 (which is not legal) requires two.  So the
   10622     // transform should not be done in this case.
   10623     if (Value.getOpcode() != ISD::TargetConstantFP) {
   10624       SDValue Tmp;
   10625       switch (CFP->getSimpleValueType(0).SimpleTy) {
   10626       default: llvm_unreachable("Unknown FP type");
   10627       case MVT::f16:    // We don't do this for these yet.
   10628       case MVT::f80:
   10629       case MVT::f128:
   10630       case MVT::ppcf128:
   10631         break;
   10632       case MVT::f32:
   10633         if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
   10634             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
   10635           Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
   10636                               bitcastToAPInt().getZExtValue(), MVT::i32);
   10637           return DAG.getStore(Chain, SDLoc(N), Tmp,
   10638                               Ptr, ST->getMemOperand());
   10639         }
   10640         break;
   10641       case MVT::f64:
   10642         if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
   10643              !ST->isVolatile()) ||
   10644             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
   10645           Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
   10646                                 getZExtValue(), MVT::i64);
   10647           return DAG.getStore(Chain, SDLoc(N), Tmp,
   10648                               Ptr, ST->getMemOperand());
   10649         }
   10650 
   10651         if (!ST->isVolatile() &&
   10652             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
   10653           // Many FP stores are not made apparent until after legalize, e.g. for
   10654           // argument passing.  Since this is so common, custom legalize the
   10655           // 64-bit integer store into two 32-bit stores.
   10656           uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
   10657           SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
   10658           SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
   10659           if (TLI.isBigEndian()) std::swap(Lo, Hi);
   10660 
   10661           unsigned Alignment = ST->getAlignment();
   10662           bool isVolatile = ST->isVolatile();
   10663           bool isNonTemporal = ST->isNonTemporal();
   10664           AAMDNodes AAInfo = ST->getAAInfo();
   10665 
   10666           SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
   10667                                      Ptr, ST->getPointerInfo(),
   10668                                      isVolatile, isNonTemporal,
   10669                                      ST->getAlignment(), AAInfo);
   10670           Ptr = DAG.getNode(ISD::ADD, SDLoc(N), Ptr.getValueType(), Ptr,
   10671                             DAG.getConstant(4, Ptr.getValueType()));
   10672           Alignment = MinAlign(Alignment, 4U);
   10673           SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
   10674                                      Ptr, ST->getPointerInfo().getWithOffset(4),
   10675                                      isVolatile, isNonTemporal,
   10676                                      Alignment, AAInfo);
   10677           return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
   10678                              St0, St1);
   10679         }
   10680 
   10681         break;
   10682       }
   10683     }
   10684   }
   10685 
   10686   // Try to infer better alignment information than the store already has.
   10687   if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
   10688     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
   10689       if (Align > ST->getAlignment()) {
   10690         SDValue NewStore =
   10691                DAG.getTruncStore(Chain, SDLoc(N), Value,
   10692                                  Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
   10693                                  ST->isVolatile(), ST->isNonTemporal(), Align,
   10694                                  ST->getAAInfo());
   10695         if (NewStore.getNode() != N)
   10696           return CombineTo(ST, NewStore, true);
   10697       }
   10698     }
   10699   }
   10700 
   10701   // Try transforming a pair floating point load / store ops to integer
   10702   // load / store ops.
   10703   SDValue NewST = TransformFPLoadStorePair(N);
   10704   if (NewST.getNode())
   10705     return NewST;
   10706 
   10707   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
   10708                                                   : DAG.getSubtarget().useAA();
   10709 #ifndef NDEBUG
   10710   if (CombinerAAOnlyFunc.getNumOccurrences() &&
   10711       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
   10712     UseAA = false;
   10713 #endif
   10714   if (UseAA && ST->isUnindexed()) {
   10715     // Walk up chain skipping non-aliasing memory nodes.
   10716     SDValue BetterChain = FindBetterChain(N, Chain);
   10717 
   10718     // If there is a better chain.
   10719     if (Chain != BetterChain) {
   10720       SDValue ReplStore;
   10721 
   10722       // Replace the chain to avoid dependency.
   10723       if (ST->isTruncatingStore()) {
   10724         ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
   10725                                       ST->getMemoryVT(), ST->getMemOperand());
   10726       } else {
   10727         ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
   10728                                  ST->getMemOperand());
   10729       }
   10730 
   10731       // Create token to keep both nodes around.
   10732       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
   10733                                   MVT::Other, Chain, ReplStore);
   10734 
   10735       // Make sure the new and old chains are cleaned up.
   10736       AddToWorklist(Token.getNode());
   10737 
   10738       // Don't add users to work list.
   10739       return CombineTo(N, Token, false);
   10740     }
   10741   }
   10742 
   10743   // Try transforming N to an indexed store.
   10744   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
   10745     return SDValue(N, 0);
   10746 
   10747   // FIXME: is there such a thing as a truncating indexed store?
   10748   if (ST->isTruncatingStore() && ST->isUnindexed() &&
   10749       Value.getValueType().isInteger()) {
   10750     // See if we can simplify the input to this truncstore with knowledge that
   10751     // only the low bits are being used.  For example:
   10752     // "truncstore (or (shl x, 8), y), i8"  -> "truncstore y, i8"
   10753     SDValue Shorter =
   10754       GetDemandedBits(Value,
   10755                       APInt::getLowBitsSet(
   10756                         Value.getValueType().getScalarType().getSizeInBits(),
   10757                         ST->getMemoryVT().getScalarType().getSizeInBits()));
   10758     AddToWorklist(Value.getNode());
   10759     if (Shorter.getNode())
   10760       return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
   10761                                Ptr, ST->getMemoryVT(), ST->getMemOperand());
   10762 
   10763     // Otherwise, see if we can simplify the operation with
   10764     // SimplifyDemandedBits, which only works if the value has a single use.
   10765     if (SimplifyDemandedBits(Value,
   10766                         APInt::getLowBitsSet(
   10767                           Value.getValueType().getScalarType().getSizeInBits(),
   10768                           ST->getMemoryVT().getScalarType().getSizeInBits())))
   10769       return SDValue(N, 0);
   10770   }
   10771 
   10772   // If this is a load followed by a store to the same location, then the store
   10773   // is dead/noop.
   10774   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
   10775     if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
   10776         ST->isUnindexed() && !ST->isVolatile() &&
   10777         // There can't be any side effects between the load and store, such as
   10778         // a call or store.
   10779         Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
   10780       // The store is dead, remove it.
   10781       return Chain;
   10782     }
   10783   }
   10784 
   10785   // If this is a store followed by a store with the same value to the same
   10786   // location, then the store is dead/noop.
   10787   if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) {
   10788     if (ST1->getBasePtr() == Ptr && ST->getMemoryVT() == ST1->getMemoryVT() &&
   10789         ST1->getValue() == Value && ST->isUnindexed() && !ST->isVolatile() &&
   10790         ST1->isUnindexed() && !ST1->isVolatile()) {
   10791       // The store is dead, remove it.
   10792       return Chain;
   10793     }
   10794   }
   10795 
   10796   // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
   10797   // truncating store.  We can do this even if this is already a truncstore.
   10798   if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
   10799       && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
   10800       TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
   10801                             ST->getMemoryVT())) {
   10802     return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
   10803                              Ptr, ST->getMemoryVT(), ST->getMemOperand());
   10804   }
   10805 
   10806   // Only perform this optimization before the types are legal, because we
   10807   // don't want to perform this optimization on every DAGCombine invocation.
   10808   if (!LegalTypes) {
   10809     bool EverChanged = false;
   10810 
   10811     do {
   10812       // There can be multiple store sequences on the same chain.
   10813       // Keep trying to merge store sequences until we are unable to do so
   10814       // or until we merge the last store on the chain.
   10815       bool Changed = MergeConsecutiveStores(ST);
   10816       EverChanged |= Changed;
   10817       if (!Changed) break;
   10818     } while (ST->getOpcode() != ISD::DELETED_NODE);
   10819 
   10820     if (EverChanged)
   10821       return SDValue(N, 0);
   10822   }
   10823 
   10824   return ReduceLoadOpStoreWidth(N);
   10825 }
   10826 
   10827 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
   10828   SDValue InVec = N->getOperand(0);
   10829   SDValue InVal = N->getOperand(1);
   10830   SDValue EltNo = N->getOperand(2);
   10831   SDLoc dl(N);
   10832 
   10833   // If the inserted element is an UNDEF, just use the input vector.
   10834   if (InVal.getOpcode() == ISD::UNDEF)
   10835     return InVec;
   10836 
   10837   EVT VT = InVec.getValueType();
   10838 
   10839   // If we can't generate a legal BUILD_VECTOR, exit
   10840   if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
   10841     return SDValue();
   10842 
   10843   // Check that we know which element is being inserted
   10844   if (!isa<ConstantSDNode>(EltNo))
   10845     return SDValue();
   10846   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
   10847 
   10848   // Canonicalize insert_vector_elt dag nodes.
   10849   // Example:
   10850   // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
   10851   // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
   10852   //
   10853   // Do this only if the child insert_vector node has one use; also
   10854   // do this only if indices are both constants and Idx1 < Idx0.
   10855   if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
   10856       && isa<ConstantSDNode>(InVec.getOperand(2))) {
   10857     unsigned OtherElt =
   10858       cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue();
   10859     if (Elt < OtherElt) {
   10860       // Swap nodes.
   10861       SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT,
   10862                                   InVec.getOperand(0), InVal, EltNo);
   10863       AddToWorklist(NewOp.getNode());
   10864       return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
   10865                          VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
   10866     }
   10867   }
   10868 
   10869   // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
   10870   // be converted to a BUILD_VECTOR).  Fill in the Ops vector with the
   10871   // vector elements.
   10872   SmallVector<SDValue, 8> Ops;
   10873   // Do not combine these two vectors if the output vector will not replace
   10874   // the input vector.
   10875   if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
   10876     Ops.append(InVec.getNode()->op_begin(),
   10877                InVec.getNode()->op_end());
   10878   } else if (InVec.getOpcode() == ISD::UNDEF) {
   10879     unsigned NElts = VT.getVectorNumElements();
   10880     Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
   10881   } else {
   10882     return SDValue();
   10883   }
   10884 
   10885   // Insert the element
   10886   if (Elt < Ops.size()) {
   10887     // All the operands of BUILD_VECTOR must have the same type;
   10888     // we enforce that here.
   10889     EVT OpVT = Ops[0].getValueType();
   10890     if (InVal.getValueType() != OpVT)
   10891       InVal = OpVT.bitsGT(InVal.getValueType()) ?
   10892                 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
   10893                 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
   10894     Ops[Elt] = InVal;
   10895   }
   10896 
   10897   // Return the new vector
   10898   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
   10899 }
   10900 
   10901 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
   10902     SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) {
   10903   EVT ResultVT = EVE->getValueType(0);
   10904   EVT VecEltVT = InVecVT.getVectorElementType();
   10905   unsigned Align = OriginalLoad->getAlignment();
   10906   unsigned NewAlign = TLI.getDataLayout()->getABITypeAlignment(
   10907       VecEltVT.getTypeForEVT(*DAG.getContext()));
   10908 
   10909   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
   10910     return SDValue();
   10911 
   10912   Align = NewAlign;
   10913 
   10914   SDValue NewPtr = OriginalLoad->getBasePtr();
   10915   SDValue Offset;
   10916   EVT PtrType = NewPtr.getValueType();
   10917   MachinePointerInfo MPI;
   10918   if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
   10919     int Elt = ConstEltNo->getZExtValue();
   10920     unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
   10921     if (TLI.isBigEndian())
   10922       PtrOff = InVecVT.getSizeInBits() / 8 - PtrOff;
   10923     Offset = DAG.getConstant(PtrOff, PtrType);
   10924     MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
   10925   } else {
   10926     Offset = DAG.getNode(
   10927         ISD::MUL, SDLoc(EVE), EltNo.getValueType(), EltNo,
   10928         DAG.getConstant(VecEltVT.getStoreSize(), EltNo.getValueType()));
   10929     if (TLI.isBigEndian())
   10930       Offset = DAG.getNode(
   10931           ISD::SUB, SDLoc(EVE), EltNo.getValueType(),
   10932           DAG.getConstant(InVecVT.getStoreSize(), EltNo.getValueType()), Offset);
   10933     MPI = OriginalLoad->getPointerInfo();
   10934   }
   10935   NewPtr = DAG.getNode(ISD::ADD, SDLoc(EVE), PtrType, NewPtr, Offset);
   10936 
   10937   // The replacement we need to do here is a little tricky: we need to
   10938   // replace an extractelement of a load with a load.
   10939   // Use ReplaceAllUsesOfValuesWith to do the replacement.
   10940   // Note that this replacement assumes that the extractvalue is the only
   10941   // use of the load; that's okay because we don't want to perform this
   10942   // transformation in other cases anyway.
   10943   SDValue Load;
   10944   SDValue Chain;
   10945   if (ResultVT.bitsGT(VecEltVT)) {
   10946     // If the result type of vextract is wider than the load, then issue an
   10947     // extending load instead.
   10948     ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, ResultVT,
   10949                                                   VecEltVT)
   10950                                    ? ISD::ZEXTLOAD
   10951                                    : ISD::EXTLOAD;
   10952     Load = DAG.getExtLoad(
   10953         ExtType, SDLoc(EVE), ResultVT, OriginalLoad->getChain(), NewPtr, MPI,
   10954         VecEltVT, OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
   10955         OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
   10956     Chain = Load.getValue(1);
   10957   } else {
   10958     Load = DAG.getLoad(
   10959         VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, MPI,
   10960         OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
   10961         OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
   10962     Chain = Load.getValue(1);
   10963     if (ResultVT.bitsLT(VecEltVT))
   10964       Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
   10965     else
   10966       Load = DAG.getNode(ISD::BITCAST, SDLoc(EVE), ResultVT, Load);
   10967   }
   10968   WorklistRemover DeadNodes(*this);
   10969   SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
   10970   SDValue To[] = { Load, Chain };
   10971   DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
   10972   // Since we're explicitly calling ReplaceAllUses, add the new node to the
   10973   // worklist explicitly as well.
   10974   AddToWorklist(Load.getNode());
   10975   AddUsersToWorklist(Load.getNode()); // Add users too
   10976   // Make sure to revisit this node to clean it up; it will usually be dead.
   10977   AddToWorklist(EVE);
   10978   ++OpsNarrowed;
   10979   return SDValue(EVE, 0);
   10980 }
   10981 
   10982 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
   10983   // (vextract (scalar_to_vector val, 0) -> val
   10984   SDValue InVec = N->getOperand(0);
   10985   EVT VT = InVec.getValueType();
   10986   EVT NVT = N->getValueType(0);
   10987 
   10988   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
   10989     // Check if the result type doesn't match the inserted element type. A
   10990     // SCALAR_TO_VECTOR may truncate the inserted element and the
   10991     // EXTRACT_VECTOR_ELT may widen the extracted vector.
   10992     SDValue InOp = InVec.getOperand(0);
   10993     if (InOp.getValueType() != NVT) {
   10994       assert(InOp.getValueType().isInteger() && NVT.isInteger());
   10995       return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
   10996     }
   10997     return InOp;
   10998   }
   10999 
   11000   SDValue EltNo = N->getOperand(1);
   11001   bool ConstEltNo = isa<ConstantSDNode>(EltNo);
   11002 
   11003   // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
   11004   // We only perform this optimization before the op legalization phase because
   11005   // we may introduce new vector instructions which are not backed by TD
   11006   // patterns. For example on AVX, extracting elements from a wide vector
   11007   // without using extract_subvector. However, if we can find an underlying
   11008   // scalar value, then we can always use that.
   11009   if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
   11010       && ConstEltNo) {
   11011     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
   11012     int NumElem = VT.getVectorNumElements();
   11013     ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
   11014     // Find the new index to extract from.
   11015     int OrigElt = SVOp->getMaskElt(Elt);
   11016 
   11017     // Extracting an undef index is undef.
   11018     if (OrigElt == -1)
   11019       return DAG.getUNDEF(NVT);
   11020 
   11021     // Select the right vector half to extract from.
   11022     SDValue SVInVec;
   11023     if (OrigElt < NumElem) {
   11024       SVInVec = InVec->getOperand(0);
   11025     } else {
   11026       SVInVec = InVec->getOperand(1);
   11027       OrigElt -= NumElem;
   11028     }
   11029 
   11030     if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
   11031       SDValue InOp = SVInVec.getOperand(OrigElt);
   11032       if (InOp.getValueType() != NVT) {
   11033         assert(InOp.getValueType().isInteger() && NVT.isInteger());
   11034         InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
   11035       }
   11036 
   11037       return InOp;
   11038     }
   11039 
   11040     // FIXME: We should handle recursing on other vector shuffles and
   11041     // scalar_to_vector here as well.
   11042 
   11043     if (!LegalOperations) {
   11044       EVT IndexTy = TLI.getVectorIdxTy();
   11045       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT,
   11046                          SVInVec, DAG.getConstant(OrigElt, IndexTy));
   11047     }
   11048   }
   11049 
   11050   bool BCNumEltsChanged = false;
   11051   EVT ExtVT = VT.getVectorElementType();
   11052   EVT LVT = ExtVT;
   11053 
   11054   // If the result of load has to be truncated, then it's not necessarily
   11055   // profitable.
   11056   if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
   11057     return SDValue();
   11058 
   11059   if (InVec.getOpcode() == ISD::BITCAST) {
   11060     // Don't duplicate a load with other uses.
   11061     if (!InVec.hasOneUse())
   11062       return SDValue();
   11063 
   11064     EVT BCVT = InVec.getOperand(0).getValueType();
   11065     if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
   11066       return SDValue();
   11067     if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
   11068       BCNumEltsChanged = true;
   11069     InVec = InVec.getOperand(0);
   11070     ExtVT = BCVT.getVectorElementType();
   11071   }
   11072 
   11073   // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size)
   11074   if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() &&
   11075       ISD::isNormalLoad(InVec.getNode()) &&
   11076       !N->getOperand(1)->hasPredecessor(InVec.getNode())) {
   11077     SDValue Index = N->getOperand(1);
   11078     if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec))
   11079       return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index,
   11080                                                            OrigLoad);
   11081   }
   11082 
   11083   // Perform only after legalization to ensure build_vector / vector_shuffle
   11084   // optimizations have already been done.
   11085   if (!LegalOperations) return SDValue();
   11086 
   11087   // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
   11088   // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
   11089   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
   11090 
   11091   if (ConstEltNo) {
   11092     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
   11093 
   11094     LoadSDNode *LN0 = nullptr;
   11095     const ShuffleVectorSDNode *SVN = nullptr;
   11096     if (ISD::isNormalLoad(InVec.getNode())) {
   11097       LN0 = cast<LoadSDNode>(InVec);
   11098     } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
   11099                InVec.getOperand(0).getValueType() == ExtVT &&
   11100                ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
   11101       // Don't duplicate a load with other uses.
   11102       if (!InVec.hasOneUse())
   11103         return SDValue();
   11104 
   11105       LN0 = cast<LoadSDNode>(InVec.getOperand(0));
   11106     } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
   11107       // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
   11108       // =>
   11109       // (load $addr+1*size)
   11110 
   11111       // Don't duplicate a load with other uses.
   11112       if (!InVec.hasOneUse())
   11113         return SDValue();
   11114 
   11115       // If the bit convert changed the number of elements, it is unsafe
   11116       // to examine the mask.
   11117       if (BCNumEltsChanged)
   11118         return SDValue();
   11119 
   11120       // Select the input vector, guarding against out of range extract vector.
   11121       unsigned NumElems = VT.getVectorNumElements();
   11122       int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
   11123       InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
   11124 
   11125       if (InVec.getOpcode() == ISD::BITCAST) {
   11126         // Don't duplicate a load with other uses.
   11127         if (!InVec.hasOneUse())
   11128           return SDValue();
   11129 
   11130         InVec = InVec.getOperand(0);
   11131       }
   11132       if (ISD::isNormalLoad(InVec.getNode())) {
   11133         LN0 = cast<LoadSDNode>(InVec);
   11134         Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
   11135         EltNo = DAG.getConstant(Elt, EltNo.getValueType());
   11136       }
   11137     }
   11138 
   11139     // Make sure we found a non-volatile load and the extractelement is
   11140     // the only use.
   11141     if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
   11142       return SDValue();
   11143 
   11144     // If Idx was -1 above, Elt is going to be -1, so just return undef.
   11145     if (Elt == -1)
   11146       return DAG.getUNDEF(LVT);
   11147 
   11148     return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0);
   11149   }
   11150 
   11151   return SDValue();
   11152 }
   11153 
   11154 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
   11155 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
   11156   // We perform this optimization post type-legalization because
   11157   // the type-legalizer often scalarizes integer-promoted vectors.
   11158   // Performing this optimization before may create bit-casts which
   11159   // will be type-legalized to complex code sequences.
   11160   // We perform this optimization only before the operation legalizer because we
   11161   // may introduce illegal operations.
   11162   if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
   11163     return SDValue();
   11164 
   11165   unsigned NumInScalars = N->getNumOperands();
   11166   SDLoc dl(N);
   11167   EVT VT = N->getValueType(0);
   11168 
   11169   // Check to see if this is a BUILD_VECTOR of a bunch of values
   11170   // which come from any_extend or zero_extend nodes. If so, we can create
   11171   // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
   11172   // optimizations. We do not handle sign-extend because we can't fill the sign
   11173   // using shuffles.
   11174   EVT SourceType = MVT::Other;
   11175   bool AllAnyExt = true;
   11176 
   11177   for (unsigned i = 0; i != NumInScalars; ++i) {
   11178     SDValue In = N->getOperand(i);
   11179     // Ignore undef inputs.
   11180     if (In.getOpcode() == ISD::UNDEF) continue;
   11181 
   11182     bool AnyExt  = In.getOpcode() == ISD::ANY_EXTEND;
   11183     bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
   11184 
   11185     // Abort if the element is not an extension.
   11186     if (!ZeroExt && !AnyExt) {
   11187       SourceType = MVT::Other;
   11188       break;
   11189     }
   11190 
   11191     // The input is a ZeroExt or AnyExt. Check the original type.
   11192     EVT InTy = In.getOperand(0).getValueType();
   11193 
   11194     // Check that all of the widened source types are the same.
   11195     if (SourceType == MVT::Other)
   11196       // First time.
   11197       SourceType = InTy;
   11198     else if (InTy != SourceType) {
   11199       // Multiple income types. Abort.
   11200       SourceType = MVT::Other;
   11201       break;
   11202     }
   11203 
   11204     // Check if all of the extends are ANY_EXTENDs.
   11205     AllAnyExt &= AnyExt;
   11206   }
   11207 
   11208   // In order to have valid types, all of the inputs must be extended from the
   11209   // same source type and all of the inputs must be any or zero extend.
   11210   // Scalar sizes must be a power of two.
   11211   EVT OutScalarTy = VT.getScalarType();
   11212   bool ValidTypes = SourceType != MVT::Other &&
   11213                  isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
   11214                  isPowerOf2_32(SourceType.getSizeInBits());
   11215 
   11216   // Create a new simpler BUILD_VECTOR sequence which other optimizations can
   11217   // turn into a single shuffle instruction.
   11218   if (!ValidTypes)
   11219     return SDValue();
   11220 
   11221   bool isLE = TLI.isLittleEndian();
   11222   unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
   11223   assert(ElemRatio > 1 && "Invalid element size ratio");
   11224   SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
   11225                                DAG.getConstant(0, SourceType);
   11226 
   11227   unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
   11228   SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
   11229 
   11230   // Populate the new build_vector
   11231   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
   11232     SDValue Cast = N->getOperand(i);
   11233     assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
   11234             Cast.getOpcode() == ISD::ZERO_EXTEND ||
   11235             Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
   11236     SDValue In;
   11237     if (Cast.getOpcode() == ISD::UNDEF)
   11238       In = DAG.getUNDEF(SourceType);
   11239     else
   11240       In = Cast->getOperand(0);
   11241     unsigned Index = isLE ? (i * ElemRatio) :
   11242                             (i * ElemRatio + (ElemRatio - 1));
   11243 
   11244     assert(Index < Ops.size() && "Invalid index");
   11245     Ops[Index] = In;
   11246   }
   11247 
   11248   // The type of the new BUILD_VECTOR node.
   11249   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
   11250   assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
   11251          "Invalid vector size");
   11252   // Check if the new vector type is legal.
   11253   if (!isTypeLegal(VecVT)) return SDValue();
   11254 
   11255   // Make the new BUILD_VECTOR.
   11256   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
   11257 
   11258   // The new BUILD_VECTOR node has the potential to be further optimized.
   11259   AddToWorklist(BV.getNode());
   11260   // Bitcast to the desired type.
   11261   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
   11262 }
   11263 
   11264 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
   11265   EVT VT = N->getValueType(0);
   11266 
   11267   unsigned NumInScalars = N->getNumOperands();
   11268   SDLoc dl(N);
   11269 
   11270   EVT SrcVT = MVT::Other;
   11271   unsigned Opcode = ISD::DELETED_NODE;
   11272   unsigned NumDefs = 0;
   11273 
   11274   for (unsigned i = 0; i != NumInScalars; ++i) {
   11275     SDValue In = N->getOperand(i);
   11276     unsigned Opc = In.getOpcode();
   11277 
   11278     if (Opc == ISD::UNDEF)
   11279       continue;
   11280 
   11281     // If all scalar values are floats and converted from integers.
   11282     if (Opcode == ISD::DELETED_NODE &&
   11283         (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
   11284       Opcode = Opc;
   11285     }
   11286 
   11287     if (Opc != Opcode)
   11288       return SDValue();
   11289 
   11290     EVT InVT = In.getOperand(0).getValueType();
   11291 
   11292     // If all scalar values are typed differently, bail out. It's chosen to
   11293     // simplify BUILD_VECTOR of integer types.
   11294     if (SrcVT == MVT::Other)
   11295       SrcVT = InVT;
   11296     if (SrcVT != InVT)
   11297       return SDValue();
   11298     NumDefs++;
   11299   }
   11300 
   11301   // If the vector has just one element defined, it's not worth to fold it into
   11302   // a vectorized one.
   11303   if (NumDefs < 2)
   11304     return SDValue();
   11305 
   11306   assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
   11307          && "Should only handle conversion from integer to float.");
   11308   assert(SrcVT != MVT::Other && "Cannot determine source type!");
   11309 
   11310   EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
   11311 
   11312   if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
   11313     return SDValue();
   11314 
   11315   // Just because the floating-point vector type is legal does not necessarily
   11316   // mean that the corresponding integer vector type is.
   11317   if (!isTypeLegal(NVT))
   11318     return SDValue();
   11319 
   11320   SmallVector<SDValue, 8> Opnds;
   11321   for (unsigned i = 0; i != NumInScalars; ++i) {
   11322     SDValue In = N->getOperand(i);
   11323 
   11324     if (In.getOpcode() == ISD::UNDEF)
   11325       Opnds.push_back(DAG.getUNDEF(SrcVT));
   11326     else
   11327       Opnds.push_back(In.getOperand(0));
   11328   }
   11329   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds);
   11330   AddToWorklist(BV.getNode());
   11331 
   11332   return DAG.getNode(Opcode, dl, VT, BV);
   11333 }
   11334 
   11335 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
   11336   unsigned NumInScalars = N->getNumOperands();
   11337   SDLoc dl(N);
   11338   EVT VT = N->getValueType(0);
   11339 
   11340   // A vector built entirely of undefs is undef.
   11341   if (ISD::allOperandsUndef(N))
   11342     return DAG.getUNDEF(VT);
   11343 
   11344   if (SDValue V = reduceBuildVecExtToExtBuildVec(N))
   11345     return V;
   11346 
   11347   if (SDValue V = reduceBuildVecConvertToConvertBuildVec(N))
   11348     return V;
   11349 
   11350   // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
   11351   // operations.  If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
   11352   // at most two distinct vectors, turn this into a shuffle node.
   11353 
   11354   // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
   11355   if (!isTypeLegal(VT))
   11356     return SDValue();
   11357 
   11358   // May only combine to shuffle after legalize if shuffle is legal.
   11359   if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT))
   11360     return SDValue();
   11361 
   11362   SDValue VecIn1, VecIn2;
   11363   bool UsesZeroVector = false;
   11364   for (unsigned i = 0; i != NumInScalars; ++i) {
   11365     SDValue Op = N->getOperand(i);
   11366     // Ignore undef inputs.
   11367     if (Op.getOpcode() == ISD::UNDEF) continue;
   11368 
   11369     // See if we can combine this build_vector into a blend with a zero vector.
   11370     if (!VecIn2.getNode() && ((Op.getOpcode() == ISD::Constant &&
   11371         cast<ConstantSDNode>(Op.getNode())->isNullValue()) ||
   11372         (Op.getOpcode() == ISD::ConstantFP &&
   11373         cast<ConstantFPSDNode>(Op.getNode())->getValueAPF().isZero()))) {
   11374       UsesZeroVector = true;
   11375       continue;
   11376     }
   11377 
   11378     // If this input is something other than a EXTRACT_VECTOR_ELT with a
   11379     // constant index, bail out.
   11380     if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
   11381         !isa<ConstantSDNode>(Op.getOperand(1))) {
   11382       VecIn1 = VecIn2 = SDValue(nullptr, 0);
   11383       break;
   11384     }
   11385 
   11386     // We allow up to two distinct input vectors.
   11387     SDValue ExtractedFromVec = Op.getOperand(0);
   11388     if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
   11389       continue;
   11390 
   11391     if (!VecIn1.getNode()) {
   11392       VecIn1 = ExtractedFromVec;
   11393     } else if (!VecIn2.getNode() && !UsesZeroVector) {
   11394       VecIn2 = ExtractedFromVec;
   11395     } else {
   11396       // Too many inputs.
   11397       VecIn1 = VecIn2 = SDValue(nullptr, 0);
   11398       break;
   11399     }
   11400   }
   11401 
   11402   // If everything is good, we can make a shuffle operation.
   11403   if (VecIn1.getNode()) {
   11404     unsigned InNumElements = VecIn1.getValueType().getVectorNumElements();
   11405     SmallVector<int, 8> Mask;
   11406     for (unsigned i = 0; i != NumInScalars; ++i) {
   11407       unsigned Opcode = N->getOperand(i).getOpcode();
   11408       if (Opcode == ISD::UNDEF) {
   11409         Mask.push_back(-1);
   11410         continue;
   11411       }
   11412 
   11413       // Operands can also be zero.
   11414       if (Opcode != ISD::EXTRACT_VECTOR_ELT) {
   11415         assert(UsesZeroVector &&
   11416                (Opcode == ISD::Constant || Opcode == ISD::ConstantFP) &&
   11417                "Unexpected node found!");
   11418         Mask.push_back(NumInScalars+i);
   11419         continue;
   11420       }
   11421 
   11422       // If extracting from the first vector, just use the index directly.
   11423       SDValue Extract = N->getOperand(i);
   11424       SDValue ExtVal = Extract.getOperand(1);
   11425       unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
   11426       if (Extract.getOperand(0) == VecIn1) {
   11427         Mask.push_back(ExtIndex);
   11428         continue;
   11429       }
   11430 
   11431       // Otherwise, use InIdx + InputVecSize
   11432       Mask.push_back(InNumElements + ExtIndex);
   11433     }
   11434 
   11435     // Avoid introducing illegal shuffles with zero.
   11436     if (UsesZeroVector && !TLI.isVectorClearMaskLegal(Mask, VT))
   11437       return SDValue();
   11438 
   11439     // We can't generate a shuffle node with mismatched input and output types.
   11440     // Attempt to transform a single input vector to the correct type.
   11441     if ((VT != VecIn1.getValueType())) {
   11442       // If the input vector type has a different base type to the output
   11443       // vector type, bail out.
   11444       EVT VTElemType = VT.getVectorElementType();
   11445       if ((VecIn1.getValueType().getVectorElementType() != VTElemType) ||
   11446           (VecIn2.getNode() &&
   11447            (VecIn2.getValueType().getVectorElementType() != VTElemType)))
   11448         return SDValue();
   11449 
   11450       // If the input vector is too small, widen it.
   11451       // We only support widening of vectors which are half the size of the
   11452       // output registers. For example XMM->YMM widening on X86 with AVX.
   11453       EVT VecInT = VecIn1.getValueType();
   11454       if (VecInT.getSizeInBits() * 2 == VT.getSizeInBits()) {
   11455         // If we only have one small input, widen it by adding undef values.
   11456         if (!VecIn2.getNode())
   11457           VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1,
   11458                                DAG.getUNDEF(VecIn1.getValueType()));
   11459         else if (VecIn1.getValueType() == VecIn2.getValueType()) {
   11460           // If we have two small inputs of the same type, try to concat them.
   11461           VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1, VecIn2);
   11462           VecIn2 = SDValue(nullptr, 0);
   11463         } else
   11464           return SDValue();
   11465       } else if (VecInT.getSizeInBits() == VT.getSizeInBits() * 2) {
   11466         // If the input vector is too large, try to split it.
   11467         // We don't support having two input vectors that are too large.
   11468         // If the zero vector was used, we can not split the vector,
   11469         // since we'd need 3 inputs.
   11470         if (UsesZeroVector || VecIn2.getNode())
   11471           return SDValue();
   11472 
   11473         if (!TLI.isExtractSubvectorCheap(VT, VT.getVectorNumElements()))
   11474           return SDValue();
   11475 
   11476         // Try to replace VecIn1 with two extract_subvectors
   11477         // No need to update the masks, they should still be correct.
   11478         VecIn2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
   11479           DAG.getConstant(VT.getVectorNumElements(), TLI.getVectorIdxTy()));
   11480         VecIn1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
   11481           DAG.getConstant(0, TLI.getVectorIdxTy()));
   11482       } else
   11483         return SDValue();
   11484     }
   11485 
   11486     if (UsesZeroVector)
   11487       VecIn2 = VT.isInteger() ? DAG.getConstant(0, VT) :
   11488                                 DAG.getConstantFP(0.0, VT);
   11489     else
   11490       // If VecIn2 is unused then change it to undef.
   11491       VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
   11492 
   11493     // Check that we were able to transform all incoming values to the same
   11494     // type.
   11495     if (VecIn2.getValueType() != VecIn1.getValueType() ||
   11496         VecIn1.getValueType() != VT)
   11497           return SDValue();
   11498 
   11499     // Return the new VECTOR_SHUFFLE node.
   11500     SDValue Ops[2];
   11501     Ops[0] = VecIn1;
   11502     Ops[1] = VecIn2;
   11503     return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
   11504   }
   11505 
   11506   return SDValue();
   11507 }
   11508 
   11509 static SDValue combineConcatVectorOfScalars(SDNode *N, SelectionDAG &DAG) {
   11510   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
   11511   EVT OpVT = N->getOperand(0).getValueType();
   11512 
   11513   // If the operands are legal vectors, leave them alone.
   11514   if (TLI.isTypeLegal(OpVT))
   11515     return SDValue();
   11516 
   11517   SDLoc DL(N);
   11518   EVT VT = N->getValueType(0);
   11519   SmallVector<SDValue, 8> Ops;
   11520 
   11521   EVT SVT = EVT::getIntegerVT(*DAG.getContext(), OpVT.getSizeInBits());
   11522   SDValue ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
   11523 
   11524   // Keep track of what we encounter.
   11525   bool AnyInteger = false;
   11526   bool AnyFP = false;
   11527   for (const SDValue &Op : N->ops()) {
   11528     if (ISD::BITCAST == Op.getOpcode() &&
   11529         !Op.getOperand(0).getValueType().isVector())
   11530       Ops.push_back(Op.getOperand(0));
   11531     else if (ISD::UNDEF == Op.getOpcode())
   11532       Ops.push_back(ScalarUndef);
   11533     else
   11534       return SDValue();
   11535 
   11536     // Note whether we encounter an integer or floating point scalar.
   11537     // If it's neither, bail out, it could be something weird like x86mmx.
   11538     EVT LastOpVT = Ops.back().getValueType();
   11539     if (LastOpVT.isFloatingPoint())
   11540       AnyFP = true;
   11541     else if (LastOpVT.isInteger())
   11542       AnyInteger = true;
   11543     else
   11544       return SDValue();
   11545   }
   11546 
   11547   // If any of the operands is a floating point scalar bitcast to a vector,
   11548   // use floating point types throughout, and bitcast everything.
   11549   // Replace UNDEFs by another scalar UNDEF node, of the final desired type.
   11550   if (AnyFP) {
   11551     SVT = EVT::getFloatingPointVT(OpVT.getSizeInBits());
   11552     ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
   11553     if (AnyInteger) {
   11554       for (SDValue &Op : Ops) {
   11555         if (Op.getValueType() == SVT)
   11556           continue;
   11557         if (Op.getOpcode() == ISD::UNDEF)
   11558           Op = ScalarUndef;
   11559         else
   11560           Op = DAG.getNode(ISD::BITCAST, DL, SVT, Op);
   11561       }
   11562     }
   11563   }
   11564 
   11565   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SVT,
   11566                                VT.getSizeInBits() / SVT.getSizeInBits());
   11567   return DAG.getNode(ISD::BITCAST, DL, VT,
   11568                      DAG.getNode(ISD::BUILD_VECTOR, DL, VecVT, Ops));
   11569 }
   11570 
   11571 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
   11572   // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
   11573   // EXTRACT_SUBVECTOR operations.  If so, and if the EXTRACT_SUBVECTOR vector
   11574   // inputs come from at most two distinct vectors, turn this into a shuffle
   11575   // node.
   11576 
   11577   // If we only have one input vector, we don't need to do any concatenation.
   11578   if (N->getNumOperands() == 1)
   11579     return N->getOperand(0);
   11580 
   11581   // Check if all of the operands are undefs.
   11582   EVT VT = N->getValueType(0);
   11583   if (ISD::allOperandsUndef(N))
   11584     return DAG.getUNDEF(VT);
   11585 
   11586   // Optimize concat_vectors where all but the first of the vectors are undef.
   11587   if (std::all_of(std::next(N->op_begin()), N->op_end(), [](const SDValue &Op) {
   11588         return Op.getOpcode() == ISD::UNDEF;
   11589       })) {
   11590     SDValue In = N->getOperand(0);
   11591     assert(In.getValueType().isVector() && "Must concat vectors");
   11592 
   11593     // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
   11594     if (In->getOpcode() == ISD::BITCAST &&
   11595         !In->getOperand(0)->getValueType(0).isVector()) {
   11596       SDValue Scalar = In->getOperand(0);
   11597 
   11598       // If the bitcast type isn't legal, it might be a trunc of a legal type;
   11599       // look through the trunc so we can still do the transform:
   11600       //   concat_vectors(trunc(scalar), undef) -> scalar_to_vector(scalar)
   11601       if (Scalar->getOpcode() == ISD::TRUNCATE &&
   11602           !TLI.isTypeLegal(Scalar.getValueType()) &&
   11603           TLI.isTypeLegal(Scalar->getOperand(0).getValueType()))
   11604         Scalar = Scalar->getOperand(0);
   11605 
   11606       EVT SclTy = Scalar->getValueType(0);
   11607 
   11608       if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
   11609         return SDValue();
   11610 
   11611       EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
   11612                                  VT.getSizeInBits() / SclTy.getSizeInBits());
   11613       if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
   11614         return SDValue();
   11615 
   11616       SDLoc dl = SDLoc(N);
   11617       SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
   11618       return DAG.getNode(ISD::BITCAST, dl, VT, Res);
   11619     }
   11620   }
   11621 
   11622   // Fold any combination of BUILD_VECTOR or UNDEF nodes into one BUILD_VECTOR.
   11623   // We have already tested above for an UNDEF only concatenation.
   11624   // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
   11625   // -> (BUILD_VECTOR A, B, ..., C, D, ...)
   11626   auto IsBuildVectorOrUndef = [](const SDValue &Op) {
   11627     return ISD::UNDEF == Op.getOpcode() || ISD::BUILD_VECTOR == Op.getOpcode();
   11628   };
   11629   bool AllBuildVectorsOrUndefs =
   11630       std::all_of(N->op_begin(), N->op_end(), IsBuildVectorOrUndef);
   11631   if (AllBuildVectorsOrUndefs) {
   11632     SmallVector<SDValue, 8> Opnds;
   11633     EVT SVT = VT.getScalarType();
   11634 
   11635     EVT MinVT = SVT;
   11636     if (!SVT.isFloatingPoint()) {
   11637       // If BUILD_VECTOR are from built from integer, they may have different
   11638       // operand types. Get the smallest type and truncate all operands to it.
   11639       bool FoundMinVT = false;
   11640       for (const SDValue &Op : N->ops())
   11641         if (ISD::BUILD_VECTOR == Op.getOpcode()) {
   11642           EVT OpSVT = Op.getOperand(0)->getValueType(0);
   11643           MinVT = (!FoundMinVT || OpSVT.bitsLE(MinVT)) ? OpSVT : MinVT;
   11644           FoundMinVT = true;
   11645         }
   11646       assert(FoundMinVT && "Concat vector type mismatch");
   11647     }
   11648 
   11649     for (const SDValue &Op : N->ops()) {
   11650       EVT OpVT = Op.getValueType();
   11651       unsigned NumElts = OpVT.getVectorNumElements();
   11652 
   11653       if (ISD::UNDEF == Op.getOpcode())
   11654         Opnds.append(NumElts, DAG.getUNDEF(MinVT));
   11655 
   11656       if (ISD::BUILD_VECTOR == Op.getOpcode()) {
   11657         if (SVT.isFloatingPoint()) {
   11658           assert(SVT == OpVT.getScalarType() && "Concat vector type mismatch");
   11659           Opnds.append(Op->op_begin(), Op->op_begin() + NumElts);
   11660         } else {
   11661           for (unsigned i = 0; i != NumElts; ++i)
   11662             Opnds.push_back(
   11663                 DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinVT, Op.getOperand(i)));
   11664         }
   11665       }
   11666     }
   11667 
   11668     assert(VT.getVectorNumElements() == Opnds.size() &&
   11669            "Concat vector type mismatch");
   11670     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
   11671   }
   11672 
   11673   // Fold CONCAT_VECTORS of only bitcast scalars (or undef) to BUILD_VECTOR.
   11674   if (SDValue V = combineConcatVectorOfScalars(N, DAG))
   11675     return V;
   11676 
   11677   // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
   11678   // nodes often generate nop CONCAT_VECTOR nodes.
   11679   // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
   11680   // place the incoming vectors at the exact same location.
   11681   SDValue SingleSource = SDValue();
   11682   unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
   11683 
   11684   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
   11685     SDValue Op = N->getOperand(i);
   11686 
   11687     if (Op.getOpcode() == ISD::UNDEF)
   11688       continue;
   11689 
   11690     // Check if this is the identity extract:
   11691     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
   11692       return SDValue();
   11693 
   11694     // Find the single incoming vector for the extract_subvector.
   11695     if (SingleSource.getNode()) {
   11696       if (Op.getOperand(0) != SingleSource)
   11697         return SDValue();
   11698     } else {
   11699       SingleSource = Op.getOperand(0);
   11700 
   11701       // Check the source type is the same as the type of the result.
   11702       // If not, this concat may extend the vector, so we can not
   11703       // optimize it away.
   11704       if (SingleSource.getValueType() != N->getValueType(0))
   11705         return SDValue();
   11706     }
   11707 
   11708     unsigned IdentityIndex = i * PartNumElem;
   11709     ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
   11710     // The extract index must be constant.
   11711     if (!CS)
   11712       return SDValue();
   11713 
   11714     // Check that we are reading from the identity index.
   11715     if (CS->getZExtValue() != IdentityIndex)
   11716       return SDValue();
   11717   }
   11718 
   11719   if (SingleSource.getNode())
   11720     return SingleSource;
   11721 
   11722   return SDValue();
   11723 }
   11724 
   11725 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
   11726   EVT NVT = N->getValueType(0);
   11727   SDValue V = N->getOperand(0);
   11728 
   11729   if (V->getOpcode() == ISD::CONCAT_VECTORS) {
   11730     // Combine:
   11731     //    (extract_subvec (concat V1, V2, ...), i)
   11732     // Into:
   11733     //    Vi if possible
   11734     // Only operand 0 is checked as 'concat' assumes all inputs of the same
   11735     // type.
   11736     if (V->getOperand(0).getValueType() != NVT)
   11737       return SDValue();
   11738     unsigned Idx = N->getConstantOperandVal(1);
   11739     unsigned NumElems = NVT.getVectorNumElements();
   11740     assert((Idx % NumElems) == 0 &&
   11741            "IDX in concat is not a multiple of the result vector length.");
   11742     return V->getOperand(Idx / NumElems);
   11743   }
   11744 
   11745   // Skip bitcasting
   11746   if (V->getOpcode() == ISD::BITCAST)
   11747     V = V.getOperand(0);
   11748 
   11749   if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
   11750     SDLoc dl(N);
   11751     // Handle only simple case where vector being inserted and vector
   11752     // being extracted are of same type, and are half size of larger vectors.
   11753     EVT BigVT = V->getOperand(0).getValueType();
   11754     EVT SmallVT = V->getOperand(1).getValueType();
   11755     if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
   11756       return SDValue();
   11757 
   11758     // Only handle cases where both indexes are constants with the same type.
   11759     ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
   11760     ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
   11761 
   11762     if (InsIdx && ExtIdx &&
   11763         InsIdx->getValueType(0).getSizeInBits() <= 64 &&
   11764         ExtIdx->getValueType(0).getSizeInBits() <= 64) {
   11765       // Combine:
   11766       //    (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
   11767       // Into:
   11768       //    indices are equal or bit offsets are equal => V1
   11769       //    otherwise => (extract_subvec V1, ExtIdx)
   11770       if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
   11771           ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
   11772         return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
   11773       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
   11774                          DAG.getNode(ISD::BITCAST, dl,
   11775                                      N->getOperand(0).getValueType(),
   11776                                      V->getOperand(0)), N->getOperand(1));
   11777     }
   11778   }
   11779 
   11780   return SDValue();
   11781 }
   11782 
   11783 static SDValue simplifyShuffleOperandRecursively(SmallBitVector &UsedElements,
   11784                                                  SDValue V, SelectionDAG &DAG) {
   11785   SDLoc DL(V);
   11786   EVT VT = V.getValueType();
   11787 
   11788   switch (V.getOpcode()) {
   11789   default:
   11790     return V;
   11791 
   11792   case ISD::CONCAT_VECTORS: {
   11793     EVT OpVT = V->getOperand(0).getValueType();
   11794     int OpSize = OpVT.getVectorNumElements();
   11795     SmallBitVector OpUsedElements(OpSize, false);
   11796     bool FoundSimplification = false;
   11797     SmallVector<SDValue, 4> NewOps;
   11798     NewOps.reserve(V->getNumOperands());
   11799     for (int i = 0, NumOps = V->getNumOperands(); i < NumOps; ++i) {
   11800       SDValue Op = V->getOperand(i);
   11801       bool OpUsed = false;
   11802       for (int j = 0; j < OpSize; ++j)
   11803         if (UsedElements[i * OpSize + j]) {
   11804           OpUsedElements[j] = true;
   11805           OpUsed = true;
   11806         }
   11807       NewOps.push_back(
   11808           OpUsed ? simplifyShuffleOperandRecursively(OpUsedElements, Op, DAG)
   11809                  : DAG.getUNDEF(OpVT));
   11810       FoundSimplification |= Op == NewOps.back();
   11811       OpUsedElements.reset();
   11812     }
   11813     if (FoundSimplification)
   11814       V = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, NewOps);
   11815     return V;
   11816   }
   11817 
   11818   case ISD::INSERT_SUBVECTOR: {
   11819     SDValue BaseV = V->getOperand(0);
   11820     SDValue SubV = V->getOperand(1);
   11821     auto *IdxN = dyn_cast<ConstantSDNode>(V->getOperand(2));
   11822     if (!IdxN)
   11823       return V;
   11824 
   11825     int SubSize = SubV.getValueType().getVectorNumElements();
   11826     int Idx = IdxN->getZExtValue();
   11827     bool SubVectorUsed = false;
   11828     SmallBitVector SubUsedElements(SubSize, false);
   11829     for (int i = 0; i < SubSize; ++i)
   11830       if (UsedElements[i + Idx]) {
   11831         SubVectorUsed = true;
   11832         SubUsedElements[i] = true;
   11833         UsedElements[i + Idx] = false;
   11834       }
   11835 
   11836     // Now recurse on both the base and sub vectors.
   11837     SDValue SimplifiedSubV =
   11838         SubVectorUsed
   11839             ? simplifyShuffleOperandRecursively(SubUsedElements, SubV, DAG)
   11840             : DAG.getUNDEF(SubV.getValueType());
   11841     SDValue SimplifiedBaseV = simplifyShuffleOperandRecursively(UsedElements, BaseV, DAG);
   11842     if (SimplifiedSubV != SubV || SimplifiedBaseV != BaseV)
   11843       V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
   11844                       SimplifiedBaseV, SimplifiedSubV, V->getOperand(2));
   11845     return V;
   11846   }
   11847   }
   11848 }
   11849 
   11850 static SDValue simplifyShuffleOperands(ShuffleVectorSDNode *SVN, SDValue N0,
   11851                                        SDValue N1, SelectionDAG &DAG) {
   11852   EVT VT = SVN->getValueType(0);
   11853   int NumElts = VT.getVectorNumElements();
   11854   SmallBitVector N0UsedElements(NumElts, false), N1UsedElements(NumElts, false);
   11855   for (int M : SVN->getMask())
   11856     if (M >= 0 && M < NumElts)
   11857       N0UsedElements[M] = true;
   11858     else if (M >= NumElts)
   11859       N1UsedElements[M - NumElts] = true;
   11860 
   11861   SDValue S0 = simplifyShuffleOperandRecursively(N0UsedElements, N0, DAG);
   11862   SDValue S1 = simplifyShuffleOperandRecursively(N1UsedElements, N1, DAG);
   11863   if (S0 == N0 && S1 == N1)
   11864     return SDValue();
   11865 
   11866   return DAG.getVectorShuffle(VT, SDLoc(SVN), S0, S1, SVN->getMask());
   11867 }
   11868 
   11869 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat,
   11870 // or turn a shuffle of a single concat into simpler shuffle then concat.
   11871 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
   11872   EVT VT = N->getValueType(0);
   11873   unsigned NumElts = VT.getVectorNumElements();
   11874 
   11875   SDValue N0 = N->getOperand(0);
   11876   SDValue N1 = N->getOperand(1);
   11877   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
   11878 
   11879   SmallVector<SDValue, 4> Ops;
   11880   EVT ConcatVT = N0.getOperand(0).getValueType();
   11881   unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
   11882   unsigned NumConcats = NumElts / NumElemsPerConcat;
   11883 
   11884   // Special case: shuffle(concat(A,B)) can be more efficiently represented
   11885   // as concat(shuffle(A,B),UNDEF) if the shuffle doesn't set any of the high
   11886   // half vector elements.
   11887   if (NumElemsPerConcat * 2 == NumElts && N1.getOpcode() == ISD::UNDEF &&
   11888       std::all_of(SVN->getMask().begin() + NumElemsPerConcat,
   11889                   SVN->getMask().end(), [](int i) { return i == -1; })) {
   11890     N0 = DAG.getVectorShuffle(ConcatVT, SDLoc(N), N0.getOperand(0), N0.getOperand(1),
   11891                               ArrayRef<int>(SVN->getMask().begin(), NumElemsPerConcat));
   11892     N1 = DAG.getUNDEF(ConcatVT);
   11893     return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0, N1);
   11894   }
   11895 
   11896   // Look at every vector that's inserted. We're looking for exact
   11897   // subvector-sized copies from a concatenated vector
   11898   for (unsigned I = 0; I != NumConcats; ++I) {
   11899     // Make sure we're dealing with a copy.
   11900     unsigned Begin = I * NumElemsPerConcat;
   11901     bool AllUndef = true, NoUndef = true;
   11902     for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
   11903       if (SVN->getMaskElt(J) >= 0)
   11904         AllUndef = false;
   11905       else
   11906         NoUndef = false;
   11907     }
   11908 
   11909     if (NoUndef) {
   11910       if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
   11911         return SDValue();
   11912 
   11913       for (unsigned J = 1; J != NumElemsPerConcat; ++J)
   11914         if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
   11915           return SDValue();
   11916 
   11917       unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
   11918       if (FirstElt < N0.getNumOperands())
   11919         Ops.push_back(N0.getOperand(FirstElt));
   11920       else
   11921         Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
   11922 
   11923     } else if (AllUndef) {
   11924       Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
   11925     } else { // Mixed with general masks and undefs, can't do optimization.
   11926       return SDValue();
   11927     }
   11928   }
   11929 
   11930   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
   11931 }
   11932 
   11933 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
   11934   EVT VT = N->getValueType(0);
   11935   unsigned NumElts = VT.getVectorNumElements();
   11936 
   11937   SDValue N0 = N->getOperand(0);
   11938   SDValue N1 = N->getOperand(1);
   11939 
   11940   assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
   11941 
   11942   // Canonicalize shuffle undef, undef -> undef
   11943   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
   11944     return DAG.getUNDEF(VT);
   11945 
   11946   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
   11947 
   11948   // Canonicalize shuffle v, v -> v, undef
   11949   if (N0 == N1) {
   11950     SmallVector<int, 8> NewMask;
   11951     for (unsigned i = 0; i != NumElts; ++i) {
   11952       int Idx = SVN->getMaskElt(i);
   11953       if (Idx >= (int)NumElts) Idx -= NumElts;
   11954       NewMask.push_back(Idx);
   11955     }
   11956     return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
   11957                                 &NewMask[0]);
   11958   }
   11959 
   11960   // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
   11961   if (N0.getOpcode() == ISD::UNDEF) {
   11962     SmallVector<int, 8> NewMask;
   11963     for (unsigned i = 0; i != NumElts; ++i) {
   11964       int Idx = SVN->getMaskElt(i);
   11965       if (Idx >= 0) {
   11966         if (Idx >= (int)NumElts)
   11967           Idx -= NumElts;
   11968         else
   11969           Idx = -1; // remove reference to lhs
   11970       }
   11971       NewMask.push_back(Idx);
   11972     }
   11973     return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
   11974                                 &NewMask[0]);
   11975   }
   11976 
   11977   // Remove references to rhs if it is undef
   11978   if (N1.getOpcode() == ISD::UNDEF) {
   11979     bool Changed = false;
   11980     SmallVector<int, 8> NewMask;
   11981     for (unsigned i = 0; i != NumElts; ++i) {
   11982       int Idx = SVN->getMaskElt(i);
   11983       if (Idx >= (int)NumElts) {
   11984         Idx = -1;
   11985         Changed = true;
   11986       }
   11987       NewMask.push_back(Idx);
   11988     }
   11989     if (Changed)
   11990       return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
   11991   }
   11992 
   11993   // If it is a splat, check if the argument vector is another splat or a
   11994   // build_vector.
   11995   if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
   11996     SDNode *V = N0.getNode();
   11997 
   11998     // If this is a bit convert that changes the element type of the vector but
   11999     // not the number of vector elements, look through it.  Be careful not to
   12000     // look though conversions that change things like v4f32 to v2f64.
   12001     if (V->getOpcode() == ISD::BITCAST) {
   12002       SDValue ConvInput = V->getOperand(0);
   12003       if (ConvInput.getValueType().isVector() &&
   12004           ConvInput.getValueType().getVectorNumElements() == NumElts)
   12005         V = ConvInput.getNode();
   12006     }
   12007 
   12008     if (V->getOpcode() == ISD::BUILD_VECTOR) {
   12009       assert(V->getNumOperands() == NumElts &&
   12010              "BUILD_VECTOR has wrong number of operands");
   12011       SDValue Base;
   12012       bool AllSame = true;
   12013       for (unsigned i = 0; i != NumElts; ++i) {
   12014         if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
   12015           Base = V->getOperand(i);
   12016           break;
   12017         }
   12018       }
   12019       // Splat of <u, u, u, u>, return <u, u, u, u>
   12020       if (!Base.getNode())
   12021         return N0;
   12022       for (unsigned i = 0; i != NumElts; ++i) {
   12023         if (V->getOperand(i) != Base) {
   12024           AllSame = false;
   12025           break;
   12026         }
   12027       }
   12028       // Splat of <x, x, x, x>, return <x, x, x, x>
   12029       if (AllSame)
   12030         return N0;
   12031 
   12032       // Canonicalize any other splat as a build_vector.
   12033       const SDValue &Splatted = V->getOperand(SVN->getSplatIndex());
   12034       SmallVector<SDValue, 8> Ops(NumElts, Splatted);
   12035       SDValue NewBV = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
   12036                                   V->getValueType(0), Ops);
   12037 
   12038       // We may have jumped through bitcasts, so the type of the
   12039       // BUILD_VECTOR may not match the type of the shuffle.
   12040       if (V->getValueType(0) != VT)
   12041         NewBV = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, NewBV);
   12042       return NewBV;
   12043     }
   12044   }
   12045 
   12046   // There are various patterns used to build up a vector from smaller vectors,
   12047   // subvectors, or elements. Scan chains of these and replace unused insertions
   12048   // or components with undef.
   12049   if (SDValue S = simplifyShuffleOperands(SVN, N0, N1, DAG))
   12050     return S;
   12051 
   12052   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
   12053       Level < AfterLegalizeVectorOps &&
   12054       (N1.getOpcode() == ISD::UNDEF ||
   12055       (N1.getOpcode() == ISD::CONCAT_VECTORS &&
   12056        N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
   12057     SDValue V = partitionShuffleOfConcats(N, DAG);
   12058 
   12059     if (V.getNode())
   12060       return V;
   12061   }
   12062 
   12063   // Attempt to combine a shuffle of 2 inputs of 'scalar sources' -
   12064   // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR.
   12065   if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT)) {
   12066     SmallVector<SDValue, 8> Ops;
   12067     for (int M : SVN->getMask()) {
   12068       SDValue Op = DAG.getUNDEF(VT.getScalarType());
   12069       if (M >= 0) {
   12070         int Idx = M % NumElts;
   12071         SDValue &S = (M < (int)NumElts ? N0 : N1);
   12072         if (S.getOpcode() == ISD::BUILD_VECTOR && S.hasOneUse()) {
   12073           Op = S.getOperand(Idx);
   12074         } else if (S.getOpcode() == ISD::SCALAR_TO_VECTOR && S.hasOneUse()) {
   12075           if (Idx == 0)
   12076             Op = S.getOperand(0);
   12077         } else {
   12078           // Operand can't be combined - bail out.
   12079           break;
   12080         }
   12081       }
   12082       Ops.push_back(Op);
   12083     }
   12084     if (Ops.size() == VT.getVectorNumElements()) {
   12085       // BUILD_VECTOR requires all inputs to be of the same type, find the
   12086       // maximum type and extend them all.
   12087       EVT SVT = VT.getScalarType();
   12088       if (SVT.isInteger())
   12089         for (SDValue &Op : Ops)
   12090           SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
   12091       if (SVT != VT.getScalarType())
   12092         for (SDValue &Op : Ops)
   12093           Op = TLI.isZExtFree(Op.getValueType(), SVT)
   12094                    ? DAG.getZExtOrTrunc(Op, SDLoc(N), SVT)
   12095                    : DAG.getSExtOrTrunc(Op, SDLoc(N), SVT);
   12096       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Ops);
   12097     }
   12098   }
   12099 
   12100   // If this shuffle only has a single input that is a bitcasted shuffle,
   12101   // attempt to merge the 2 shuffles and suitably bitcast the inputs/output
   12102   // back to their original types.
   12103   if (N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
   12104       N1.getOpcode() == ISD::UNDEF && Level < AfterLegalizeVectorOps &&
   12105       TLI.isTypeLegal(VT)) {
   12106 
   12107     // Peek through the bitcast only if there is one user.
   12108     SDValue BC0 = N0;
   12109     while (BC0.getOpcode() == ISD::BITCAST) {
   12110       if (!BC0.hasOneUse())
   12111         break;
   12112       BC0 = BC0.getOperand(0);
   12113     }
   12114 
   12115     auto ScaleShuffleMask = [](ArrayRef<int> Mask, int Scale) {
   12116       if (Scale == 1)
   12117         return SmallVector<int, 8>(Mask.begin(), Mask.end());
   12118 
   12119       SmallVector<int, 8> NewMask;
   12120       for (int M : Mask)
   12121         for (int s = 0; s != Scale; ++s)
   12122           NewMask.push_back(M < 0 ? -1 : Scale * M + s);
   12123       return NewMask;
   12124     };
   12125 
   12126     if (BC0.getOpcode() == ISD::VECTOR_SHUFFLE && BC0.hasOneUse()) {
   12127       EVT SVT = VT.getScalarType();
   12128       EVT InnerVT = BC0->getValueType(0);
   12129       EVT InnerSVT = InnerVT.getScalarType();
   12130 
   12131       // Determine which shuffle works with the smaller scalar type.
   12132       EVT ScaleVT = SVT.bitsLT(InnerSVT) ? VT : InnerVT;
   12133       EVT ScaleSVT = ScaleVT.getScalarType();
   12134 
   12135       if (TLI.isTypeLegal(ScaleVT) &&
   12136           0 == (InnerSVT.getSizeInBits() % ScaleSVT.getSizeInBits()) &&
   12137           0 == (SVT.getSizeInBits() % ScaleSVT.getSizeInBits())) {
   12138 
   12139         int InnerScale = InnerSVT.getSizeInBits() / ScaleSVT.getSizeInBits();
   12140         int OuterScale = SVT.getSizeInBits() / ScaleSVT.getSizeInBits();
   12141 
   12142         // Scale the shuffle masks to the smaller scalar type.
   12143         ShuffleVectorSDNode *InnerSVN = cast<ShuffleVectorSDNode>(BC0);
   12144         SmallVector<int, 8> InnerMask =
   12145             ScaleShuffleMask(InnerSVN->getMask(), InnerScale);
   12146         SmallVector<int, 8> OuterMask =
   12147             ScaleShuffleMask(SVN->getMask(), OuterScale);
   12148 
   12149         // Merge the shuffle masks.
   12150         SmallVector<int, 8> NewMask;
   12151         for (int M : OuterMask)
   12152           NewMask.push_back(M < 0 ? -1 : InnerMask[M]);
   12153 
   12154         // Test for shuffle mask legality over both commutations.
   12155         SDValue SV0 = BC0->getOperand(0);
   12156         SDValue SV1 = BC0->getOperand(1);
   12157         bool LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
   12158         if (!LegalMask) {
   12159           std::swap(SV0, SV1);
   12160           ShuffleVectorSDNode::commuteMask(NewMask);
   12161           LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
   12162         }
   12163 
   12164         if (LegalMask) {
   12165           SV0 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV0);
   12166           SV1 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV1);
   12167           return DAG.getNode(
   12168               ISD::BITCAST, SDLoc(N), VT,
   12169               DAG.getVectorShuffle(ScaleVT, SDLoc(N), SV0, SV1, NewMask));
   12170         }
   12171       }
   12172     }
   12173   }
   12174 
   12175   // Canonicalize shuffles according to rules:
   12176   //  shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
   12177   //  shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
   12178   //  shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
   12179   if (N1.getOpcode() == ISD::VECTOR_SHUFFLE &&
   12180       N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
   12181       TLI.isTypeLegal(VT)) {
   12182     // The incoming shuffle must be of the same type as the result of the
   12183     // current shuffle.
   12184     assert(N1->getOperand(0).getValueType() == VT &&
   12185            "Shuffle types don't match");
   12186 
   12187     SDValue SV0 = N1->getOperand(0);
   12188     SDValue SV1 = N1->getOperand(1);
   12189     bool HasSameOp0 = N0 == SV0;
   12190     bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
   12191     if (HasSameOp0 || IsSV1Undef || N0 == SV1)
   12192       // Commute the operands of this shuffle so that next rule
   12193       // will trigger.
   12194       return DAG.getCommutedVectorShuffle(*SVN);
   12195   }
   12196 
   12197   // Try to fold according to rules:
   12198   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
   12199   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
   12200   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
   12201   // Don't try to fold shuffles with illegal type.
   12202   // Only fold if this shuffle is the only user of the other shuffle.
   12203   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && N->isOnlyUserOf(N0.getNode()) &&
   12204       Level < AfterLegalizeDAG && TLI.isTypeLegal(VT)) {
   12205     ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
   12206 
   12207     // The incoming shuffle must be of the same type as the result of the
   12208     // current shuffle.
   12209     assert(OtherSV->getOperand(0).getValueType() == VT &&
   12210            "Shuffle types don't match");
   12211 
   12212     SDValue SV0, SV1;
   12213     SmallVector<int, 4> Mask;
   12214     // Compute the combined shuffle mask for a shuffle with SV0 as the first
   12215     // operand, and SV1 as the second operand.
   12216     for (unsigned i = 0; i != NumElts; ++i) {
   12217       int Idx = SVN->getMaskElt(i);
   12218       if (Idx < 0) {
   12219         // Propagate Undef.
   12220         Mask.push_back(Idx);
   12221         continue;
   12222       }
   12223 
   12224       SDValue CurrentVec;
   12225       if (Idx < (int)NumElts) {
   12226         // This shuffle index refers to the inner shuffle N0. Lookup the inner
   12227         // shuffle mask to identify which vector is actually referenced.
   12228         Idx = OtherSV->getMaskElt(Idx);
   12229         if (Idx < 0) {
   12230           // Propagate Undef.
   12231           Mask.push_back(Idx);
   12232           continue;
   12233         }
   12234 
   12235         CurrentVec = (Idx < (int) NumElts) ? OtherSV->getOperand(0)
   12236                                            : OtherSV->getOperand(1);
   12237       } else {
   12238         // This shuffle index references an element within N1.
   12239         CurrentVec = N1;
   12240       }
   12241 
   12242       // Simple case where 'CurrentVec' is UNDEF.
   12243       if (CurrentVec.getOpcode() == ISD::UNDEF) {
   12244         Mask.push_back(-1);
   12245         continue;
   12246       }
   12247 
   12248       // Canonicalize the shuffle index. We don't know yet if CurrentVec
   12249       // will be the first or second operand of the combined shuffle.
   12250       Idx = Idx % NumElts;
   12251       if (!SV0.getNode() || SV0 == CurrentVec) {
   12252         // Ok. CurrentVec is the left hand side.
   12253         // Update the mask accordingly.
   12254         SV0 = CurrentVec;
   12255         Mask.push_back(Idx);
   12256         continue;
   12257       }
   12258 
   12259       // Bail out if we cannot convert the shuffle pair into a single shuffle.
   12260       if (SV1.getNode() && SV1 != CurrentVec)
   12261         return SDValue();
   12262 
   12263       // Ok. CurrentVec is the right hand side.
   12264       // Update the mask accordingly.
   12265       SV1 = CurrentVec;
   12266       Mask.push_back(Idx + NumElts);
   12267     }
   12268 
   12269     // Check if all indices in Mask are Undef. In case, propagate Undef.
   12270     bool isUndefMask = true;
   12271     for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
   12272       isUndefMask &= Mask[i] < 0;
   12273 
   12274     if (isUndefMask)
   12275       return DAG.getUNDEF(VT);
   12276 
   12277     if (!SV0.getNode())
   12278       SV0 = DAG.getUNDEF(VT);
   12279     if (!SV1.getNode())
   12280       SV1 = DAG.getUNDEF(VT);
   12281 
   12282     // Avoid introducing shuffles with illegal mask.
   12283     if (!TLI.isShuffleMaskLegal(Mask, VT)) {
   12284       ShuffleVectorSDNode::commuteMask(Mask);
   12285 
   12286       if (!TLI.isShuffleMaskLegal(Mask, VT))
   12287         return SDValue();
   12288 
   12289       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2)
   12290       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2)
   12291       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2)
   12292       std::swap(SV0, SV1);
   12293     }
   12294 
   12295     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
   12296     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
   12297     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
   12298     return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, &Mask[0]);
   12299   }
   12300 
   12301   return SDValue();
   12302 }
   12303 
   12304 SDValue DAGCombiner::visitSCALAR_TO_VECTOR(SDNode *N) {
   12305   SDValue InVal = N->getOperand(0);
   12306   EVT VT = N->getValueType(0);
   12307 
   12308   // Replace a SCALAR_TO_VECTOR(EXTRACT_VECTOR_ELT(V,C0)) pattern
   12309   // with a VECTOR_SHUFFLE.
   12310   if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
   12311     SDValue InVec = InVal->getOperand(0);
   12312     SDValue EltNo = InVal->getOperand(1);
   12313 
   12314     // FIXME: We could support implicit truncation if the shuffle can be
   12315     // scaled to a smaller vector scalar type.
   12316     ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(EltNo);
   12317     if (C0 && VT == InVec.getValueType() &&
   12318         VT.getScalarType() == InVal.getValueType()) {
   12319       SmallVector<int, 8> NewMask(VT.getVectorNumElements(), -1);
   12320       int Elt = C0->getZExtValue();
   12321       NewMask[0] = Elt;
   12322 
   12323       if (TLI.isShuffleMaskLegal(NewMask, VT))
   12324         return DAG.getVectorShuffle(VT, SDLoc(N), InVec, DAG.getUNDEF(VT),
   12325                                     NewMask);
   12326     }
   12327   }
   12328 
   12329   return SDValue();
   12330 }
   12331 
   12332 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
   12333   SDValue N0 = N->getOperand(0);
   12334   SDValue N2 = N->getOperand(2);
   12335 
   12336   // If the input vector is a concatenation, and the insert replaces
   12337   // one of the halves, we can optimize into a single concat_vectors.
   12338   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
   12339       N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
   12340     APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
   12341     EVT VT = N->getValueType(0);
   12342 
   12343     // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
   12344     // (concat_vectors Z, Y)
   12345     if (InsIdx == 0)
   12346       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
   12347                          N->getOperand(1), N0.getOperand(1));
   12348 
   12349     // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
   12350     // (concat_vectors X, Z)
   12351     if (InsIdx == VT.getVectorNumElements()/2)
   12352       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
   12353                          N0.getOperand(0), N->getOperand(1));
   12354   }
   12355 
   12356   return SDValue();
   12357 }
   12358 
   12359 SDValue DAGCombiner::visitFP_TO_FP16(SDNode *N) {
   12360   SDValue N0 = N->getOperand(0);
   12361 
   12362   // fold (fp_to_fp16 (fp16_to_fp op)) -> op
   12363   if (N0->getOpcode() == ISD::FP16_TO_FP)
   12364     return N0->getOperand(0);
   12365 
   12366   return SDValue();
   12367 }
   12368 
   12369 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle
   12370 /// with the destination vector and a zero vector.
   12371 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
   12372 ///      vector_shuffle V, Zero, <0, 4, 2, 4>
   12373 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
   12374   EVT VT = N->getValueType(0);
   12375   SDValue LHS = N->getOperand(0);
   12376   SDValue RHS = N->getOperand(1);
   12377   SDLoc dl(N);
   12378 
   12379   // Make sure we're not running after operation legalization where it
   12380   // may have custom lowered the vector shuffles.
   12381   if (LegalOperations)
   12382     return SDValue();
   12383 
   12384   if (N->getOpcode() != ISD::AND)
   12385     return SDValue();
   12386 
   12387   if (RHS.getOpcode() == ISD::BITCAST)
   12388     RHS = RHS.getOperand(0);
   12389 
   12390   if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
   12391     SmallVector<int, 8> Indices;
   12392     unsigned NumElts = RHS.getNumOperands();
   12393 
   12394     for (unsigned i = 0; i != NumElts; ++i) {
   12395       SDValue Elt = RHS.getOperand(i);
   12396       if (!isa<ConstantSDNode>(Elt))
   12397         return SDValue();
   12398 
   12399       if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
   12400         Indices.push_back(i);
   12401       else if (cast<ConstantSDNode>(Elt)->isNullValue())
   12402         Indices.push_back(NumElts+i);
   12403       else
   12404         return SDValue();
   12405     }
   12406 
   12407     // Let's see if the target supports this vector_shuffle.
   12408     EVT RVT = RHS.getValueType();
   12409     if (!TLI.isVectorClearMaskLegal(Indices, RVT))
   12410       return SDValue();
   12411 
   12412     // Return the new VECTOR_SHUFFLE node.
   12413     EVT EltVT = RVT.getVectorElementType();
   12414     SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
   12415                                    DAG.getConstant(0, EltVT));
   12416     SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), RVT, ZeroOps);
   12417     LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
   12418     SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
   12419     return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
   12420   }
   12421 
   12422   return SDValue();
   12423 }
   12424 
   12425 /// Visit a binary vector operation, like ADD.
   12426 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
   12427   assert(N->getValueType(0).isVector() &&
   12428          "SimplifyVBinOp only works on vectors!");
   12429 
   12430   SDValue LHS = N->getOperand(0);
   12431   SDValue RHS = N->getOperand(1);
   12432 
   12433   if (SDValue Shuffle = XformToShuffleWithZero(N))
   12434     return Shuffle;
   12435 
   12436   // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
   12437   // this operation.
   12438   if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
   12439       RHS.getOpcode() == ISD::BUILD_VECTOR) {
   12440     // Check if both vectors are constants. If not bail out.
   12441     if (!(cast<BuildVectorSDNode>(LHS)->isConstant() &&
   12442           cast<BuildVectorSDNode>(RHS)->isConstant()))
   12443       return SDValue();
   12444 
   12445     SmallVector<SDValue, 8> Ops;
   12446     for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
   12447       SDValue LHSOp = LHS.getOperand(i);
   12448       SDValue RHSOp = RHS.getOperand(i);
   12449 
   12450       // Can't fold divide by zero.
   12451       if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
   12452           N->getOpcode() == ISD::FDIV) {
   12453         if ((RHSOp.getOpcode() == ISD::Constant &&
   12454              cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
   12455             (RHSOp.getOpcode() == ISD::ConstantFP &&
   12456              cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
   12457           break;
   12458       }
   12459 
   12460       EVT VT = LHSOp.getValueType();
   12461       EVT RVT = RHSOp.getValueType();
   12462       if (RVT != VT) {
   12463         // Integer BUILD_VECTOR operands may have types larger than the element
   12464         // size (e.g., when the element type is not legal).  Prior to type
   12465         // legalization, the types may not match between the two BUILD_VECTORS.
   12466         // Truncate one of the operands to make them match.
   12467         if (RVT.getSizeInBits() > VT.getSizeInBits()) {
   12468           RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
   12469         } else {
   12470           LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
   12471           VT = RVT;
   12472         }
   12473       }
   12474       SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
   12475                                    LHSOp, RHSOp);
   12476       if (FoldOp.getOpcode() != ISD::UNDEF &&
   12477           FoldOp.getOpcode() != ISD::Constant &&
   12478           FoldOp.getOpcode() != ISD::ConstantFP)
   12479         break;
   12480       Ops.push_back(FoldOp);
   12481       AddToWorklist(FoldOp.getNode());
   12482     }
   12483 
   12484     if (Ops.size() == LHS.getNumOperands())
   12485       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), LHS.getValueType(), Ops);
   12486   }
   12487 
   12488   // Type legalization might introduce new shuffles in the DAG.
   12489   // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
   12490   //   -> (shuffle (VBinOp (A, B)), Undef, Mask).
   12491   if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
   12492       isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
   12493       LHS.getOperand(1).getOpcode() == ISD::UNDEF &&
   12494       RHS.getOperand(1).getOpcode() == ISD::UNDEF) {
   12495     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
   12496     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
   12497 
   12498     if (SVN0->getMask().equals(SVN1->getMask())) {
   12499       EVT VT = N->getValueType(0);
   12500       SDValue UndefVector = LHS.getOperand(1);
   12501       SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
   12502                                      LHS.getOperand(0), RHS.getOperand(0));
   12503       AddUsersToWorklist(N);
   12504       return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
   12505                                   &SVN0->getMask()[0]);
   12506     }
   12507   }
   12508 
   12509   return SDValue();
   12510 }
   12511 
   12512 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
   12513                                     SDValue N1, SDValue N2){
   12514   assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
   12515 
   12516   SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
   12517                                  cast<CondCodeSDNode>(N0.getOperand(2))->get());
   12518 
   12519   // If we got a simplified select_cc node back from SimplifySelectCC, then
   12520   // break it down into a new SETCC node, and a new SELECT node, and then return
   12521   // the SELECT node, since we were called with a SELECT node.
   12522   if (SCC.getNode()) {
   12523     // Check to see if we got a select_cc back (to turn into setcc/select).
   12524     // Otherwise, just return whatever node we got back, like fabs.
   12525     if (SCC.getOpcode() == ISD::SELECT_CC) {
   12526       SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
   12527                                   N0.getValueType(),
   12528                                   SCC.getOperand(0), SCC.getOperand(1),
   12529                                   SCC.getOperand(4));
   12530       AddToWorklist(SETCC.getNode());
   12531       return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC,
   12532                            SCC.getOperand(2), SCC.getOperand(3));
   12533     }
   12534 
   12535     return SCC;
   12536   }
   12537   return SDValue();
   12538 }
   12539 
   12540 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values
   12541 /// being selected between, see if we can simplify the select.  Callers of this
   12542 /// should assume that TheSelect is deleted if this returns true.  As such, they
   12543 /// should return the appropriate thing (e.g. the node) back to the top-level of
   12544 /// the DAG combiner loop to avoid it being looked at.
   12545 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
   12546                                     SDValue RHS) {
   12547 
   12548   // Cannot simplify select with vector condition
   12549   if (TheSelect->getOperand(0).getValueType().isVector()) return false;
   12550 
   12551   // If this is a select from two identical things, try to pull the operation
   12552   // through the select.
   12553   if (LHS.getOpcode() != RHS.getOpcode() ||
   12554       !LHS.hasOneUse() || !RHS.hasOneUse())
   12555     return false;
   12556 
   12557   // If this is a load and the token chain is identical, replace the select
   12558   // of two loads with a load through a select of the address to load from.
   12559   // This triggers in things like "select bool X, 10.0, 123.0" after the FP
   12560   // constants have been dropped into the constant pool.
   12561   if (LHS.getOpcode() == ISD::LOAD) {
   12562     LoadSDNode *LLD = cast<LoadSDNode>(LHS);
   12563     LoadSDNode *RLD = cast<LoadSDNode>(RHS);
   12564 
   12565     // Token chains must be identical.
   12566     if (LHS.getOperand(0) != RHS.getOperand(0) ||
   12567         // Do not let this transformation reduce the number of volatile loads.
   12568         LLD->isVolatile() || RLD->isVolatile() ||
   12569         // If this is an EXTLOAD, the VT's must match.
   12570         LLD->getMemoryVT() != RLD->getMemoryVT() ||
   12571         // If this is an EXTLOAD, the kind of extension must match.
   12572         (LLD->getExtensionType() != RLD->getExtensionType() &&
   12573          // The only exception is if one of the extensions is anyext.
   12574          LLD->getExtensionType() != ISD::EXTLOAD &&
   12575          RLD->getExtensionType() != ISD::EXTLOAD) ||
   12576         // FIXME: this discards src value information.  This is
   12577         // over-conservative. It would be beneficial to be able to remember
   12578         // both potential memory locations.  Since we are discarding
   12579         // src value info, don't do the transformation if the memory
   12580         // locations are not in the default address space.
   12581         LLD->getPointerInfo().getAddrSpace() != 0 ||
   12582         RLD->getPointerInfo().getAddrSpace() != 0 ||
   12583         !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
   12584                                       LLD->getBasePtr().getValueType()))
   12585       return false;
   12586 
   12587     // Check that the select condition doesn't reach either load.  If so,
   12588     // folding this will induce a cycle into the DAG.  If not, this is safe to
   12589     // xform, so create a select of the addresses.
   12590     SDValue Addr;
   12591     if (TheSelect->getOpcode() == ISD::SELECT) {
   12592       SDNode *CondNode = TheSelect->getOperand(0).getNode();
   12593       if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
   12594           (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
   12595         return false;
   12596       // The loads must not depend on one another.
   12597       if (LLD->isPredecessorOf(RLD) ||
   12598           RLD->isPredecessorOf(LLD))
   12599         return false;
   12600       Addr = DAG.getSelect(SDLoc(TheSelect),
   12601                            LLD->getBasePtr().getValueType(),
   12602                            TheSelect->getOperand(0), LLD->getBasePtr(),
   12603                            RLD->getBasePtr());
   12604     } else {  // Otherwise SELECT_CC
   12605       SDNode *CondLHS = TheSelect->getOperand(0).getNode();
   12606       SDNode *CondRHS = TheSelect->getOperand(1).getNode();
   12607 
   12608       if ((LLD->hasAnyUseOfValue(1) &&
   12609            (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
   12610           (RLD->hasAnyUseOfValue(1) &&
   12611            (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
   12612         return false;
   12613 
   12614       Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
   12615                          LLD->getBasePtr().getValueType(),
   12616                          TheSelect->getOperand(0),
   12617                          TheSelect->getOperand(1),
   12618                          LLD->getBasePtr(), RLD->getBasePtr(),
   12619                          TheSelect->getOperand(4));
   12620     }
   12621 
   12622     SDValue Load;
   12623     // It is safe to replace the two loads if they have different alignments,
   12624     // but the new load must be the minimum (most restrictive) alignment of the
   12625     // inputs.
   12626     bool isInvariant = LLD->isInvariant() & RLD->isInvariant();
   12627     unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment());
   12628     if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
   12629       Load = DAG.getLoad(TheSelect->getValueType(0),
   12630                          SDLoc(TheSelect),
   12631                          // FIXME: Discards pointer and AA info.
   12632                          LLD->getChain(), Addr, MachinePointerInfo(),
   12633                          LLD->isVolatile(), LLD->isNonTemporal(),
   12634                          isInvariant, Alignment);
   12635     } else {
   12636       Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
   12637                             RLD->getExtensionType() : LLD->getExtensionType(),
   12638                             SDLoc(TheSelect),
   12639                             TheSelect->getValueType(0),
   12640                             // FIXME: Discards pointer and AA info.
   12641                             LLD->getChain(), Addr, MachinePointerInfo(),
   12642                             LLD->getMemoryVT(), LLD->isVolatile(),
   12643                             LLD->isNonTemporal(), isInvariant, Alignment);
   12644     }
   12645 
   12646     // Users of the select now use the result of the load.
   12647     CombineTo(TheSelect, Load);
   12648 
   12649     // Users of the old loads now use the new load's chain.  We know the
   12650     // old-load value is dead now.
   12651     CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
   12652     CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
   12653     return true;
   12654   }
   12655 
   12656   return false;
   12657 }
   12658 
   12659 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3
   12660 /// where 'cond' is the comparison specified by CC.
   12661 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
   12662                                       SDValue N2, SDValue N3,
   12663                                       ISD::CondCode CC, bool NotExtCompare) {
   12664   // (x ? y : y) -> y.
   12665   if (N2 == N3) return N2;
   12666 
   12667   EVT VT = N2.getValueType();
   12668   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
   12669   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
   12670   ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
   12671 
   12672   // Determine if the condition we're dealing with is constant
   12673   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
   12674                               N0, N1, CC, DL, false);
   12675   if (SCC.getNode()) AddToWorklist(SCC.getNode());
   12676   ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
   12677 
   12678   // fold select_cc true, x, y -> x
   12679   if (SCCC && !SCCC->isNullValue())
   12680     return N2;
   12681   // fold select_cc false, x, y -> y
   12682   if (SCCC && SCCC->isNullValue())
   12683     return N3;
   12684 
   12685   // Check to see if we can simplify the select into an fabs node
   12686   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
   12687     // Allow either -0.0 or 0.0
   12688     if (CFP->getValueAPF().isZero()) {
   12689       // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
   12690       if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
   12691           N0 == N2 && N3.getOpcode() == ISD::FNEG &&
   12692           N2 == N3.getOperand(0))
   12693         return DAG.getNode(ISD::FABS, DL, VT, N0);
   12694 
   12695       // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
   12696       if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
   12697           N0 == N3 && N2.getOpcode() == ISD::FNEG &&
   12698           N2.getOperand(0) == N3)
   12699         return DAG.getNode(ISD::FABS, DL, VT, N3);
   12700     }
   12701   }
   12702 
   12703   // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
   12704   // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
   12705   // in it.  This is a win when the constant is not otherwise available because
   12706   // it replaces two constant pool loads with one.  We only do this if the FP
   12707   // type is known to be legal, because if it isn't, then we are before legalize
   12708   // types an we want the other legalization to happen first (e.g. to avoid
   12709   // messing with soft float) and if the ConstantFP is not legal, because if
   12710   // it is legal, we may not need to store the FP constant in a constant pool.
   12711   if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
   12712     if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
   12713       if (TLI.isTypeLegal(N2.getValueType()) &&
   12714           (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
   12715                TargetLowering::Legal &&
   12716            !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
   12717            !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
   12718           // If both constants have multiple uses, then we won't need to do an
   12719           // extra load, they are likely around in registers for other users.
   12720           (TV->hasOneUse() || FV->hasOneUse())) {
   12721         Constant *Elts[] = {
   12722           const_cast<ConstantFP*>(FV->getConstantFPValue()),
   12723           const_cast<ConstantFP*>(TV->getConstantFPValue())
   12724         };
   12725         Type *FPTy = Elts[0]->getType();
   12726         const DataLayout &TD = *TLI.getDataLayout();
   12727 
   12728         // Create a ConstantArray of the two constants.
   12729         Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
   12730         SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
   12731                                             TD.getPrefTypeAlignment(FPTy));
   12732         unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
   12733 
   12734         // Get the offsets to the 0 and 1 element of the array so that we can
   12735         // select between them.
   12736         SDValue Zero = DAG.getIntPtrConstant(0);
   12737         unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
   12738         SDValue One = DAG.getIntPtrConstant(EltSize);
   12739 
   12740         SDValue Cond = DAG.getSetCC(DL,
   12741                                     getSetCCResultType(N0.getValueType()),
   12742                                     N0, N1, CC);
   12743         AddToWorklist(Cond.getNode());
   12744         SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
   12745                                           Cond, One, Zero);
   12746         AddToWorklist(CstOffset.getNode());
   12747         CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
   12748                             CstOffset);
   12749         AddToWorklist(CPIdx.getNode());
   12750         return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
   12751                            MachinePointerInfo::getConstantPool(), false,
   12752                            false, false, Alignment);
   12753 
   12754       }
   12755     }
   12756 
   12757   // Check to see if we can perform the "gzip trick", transforming
   12758   // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
   12759   if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
   12760       (N1C->isNullValue() ||                         // (a < 0) ? b : 0
   12761        (N1C->getAPIntValue() == 1 && N0 == N2))) {   // (a < 1) ? a : 0
   12762     EVT XType = N0.getValueType();
   12763     EVT AType = N2.getValueType();
   12764     if (XType.bitsGE(AType)) {
   12765       // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
   12766       // single-bit constant.
   12767       if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
   12768         unsigned ShCtV = N2C->getAPIntValue().logBase2();
   12769         ShCtV = XType.getSizeInBits()-ShCtV-1;
   12770         SDValue ShCt = DAG.getConstant(ShCtV,
   12771                                        getShiftAmountTy(N0.getValueType()));
   12772         SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
   12773                                     XType, N0, ShCt);
   12774         AddToWorklist(Shift.getNode());
   12775 
   12776         if (XType.bitsGT(AType)) {
   12777           Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
   12778           AddToWorklist(Shift.getNode());
   12779         }
   12780 
   12781         return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
   12782       }
   12783 
   12784       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
   12785                                   XType, N0,
   12786                                   DAG.getConstant(XType.getSizeInBits()-1,
   12787                                          getShiftAmountTy(N0.getValueType())));
   12788       AddToWorklist(Shift.getNode());
   12789 
   12790       if (XType.bitsGT(AType)) {
   12791         Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
   12792         AddToWorklist(Shift.getNode());
   12793       }
   12794 
   12795       return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
   12796     }
   12797   }
   12798 
   12799   // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
   12800   // where y is has a single bit set.
   12801   // A plaintext description would be, we can turn the SELECT_CC into an AND
   12802   // when the condition can be materialized as an all-ones register.  Any
   12803   // single bit-test can be materialized as an all-ones register with
   12804   // shift-left and shift-right-arith.
   12805   if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
   12806       N0->getValueType(0) == VT &&
   12807       N1C && N1C->isNullValue() &&
   12808       N2C && N2C->isNullValue()) {
   12809     SDValue AndLHS = N0->getOperand(0);
   12810     ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
   12811     if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
   12812       // Shift the tested bit over the sign bit.
   12813       APInt AndMask = ConstAndRHS->getAPIntValue();
   12814       SDValue ShlAmt =
   12815         DAG.getConstant(AndMask.countLeadingZeros(),
   12816                         getShiftAmountTy(AndLHS.getValueType()));
   12817       SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
   12818 
   12819       // Now arithmetic right shift it all the way over, so the result is either
   12820       // all-ones, or zero.
   12821       SDValue ShrAmt =
   12822         DAG.getConstant(AndMask.getBitWidth()-1,
   12823                         getShiftAmountTy(Shl.getValueType()));
   12824       SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
   12825 
   12826       return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
   12827     }
   12828   }
   12829 
   12830   // fold select C, 16, 0 -> shl C, 4
   12831   if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
   12832       TLI.getBooleanContents(N0.getValueType()) ==
   12833           TargetLowering::ZeroOrOneBooleanContent) {
   12834 
   12835     // If the caller doesn't want us to simplify this into a zext of a compare,
   12836     // don't do it.
   12837     if (NotExtCompare && N2C->getAPIntValue() == 1)
   12838       return SDValue();
   12839 
   12840     // Get a SetCC of the condition
   12841     // NOTE: Don't create a SETCC if it's not legal on this target.
   12842     if (!LegalOperations ||
   12843         TLI.isOperationLegal(ISD::SETCC,
   12844           LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
   12845       SDValue Temp, SCC;
   12846       // cast from setcc result type to select result type
   12847       if (LegalTypes) {
   12848         SCC  = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
   12849                             N0, N1, CC);
   12850         if (N2.getValueType().bitsLT(SCC.getValueType()))
   12851           Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
   12852                                         N2.getValueType());
   12853         else
   12854           Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
   12855                              N2.getValueType(), SCC);
   12856       } else {
   12857         SCC  = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
   12858         Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
   12859                            N2.getValueType(), SCC);
   12860       }
   12861 
   12862       AddToWorklist(SCC.getNode());
   12863       AddToWorklist(Temp.getNode());
   12864 
   12865       if (N2C->getAPIntValue() == 1)
   12866         return Temp;
   12867 
   12868       // shl setcc result by log2 n2c
   12869       return DAG.getNode(
   12870           ISD::SHL, DL, N2.getValueType(), Temp,
   12871           DAG.getConstant(N2C->getAPIntValue().logBase2(),
   12872                           getShiftAmountTy(Temp.getValueType())));
   12873     }
   12874   }
   12875 
   12876   // Check to see if this is the equivalent of setcc
   12877   // FIXME: Turn all of these into setcc if setcc if setcc is legal
   12878   // otherwise, go ahead with the folds.
   12879   if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
   12880     EVT XType = N0.getValueType();
   12881     if (!LegalOperations ||
   12882         TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
   12883       SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
   12884       if (Res.getValueType() != VT)
   12885         Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
   12886       return Res;
   12887     }
   12888 
   12889     // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
   12890     if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
   12891         (!LegalOperations ||
   12892          TLI.isOperationLegal(ISD::CTLZ, XType))) {
   12893       SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
   12894       return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
   12895                          DAG.getConstant(Log2_32(XType.getSizeInBits()),
   12896                                        getShiftAmountTy(Ctlz.getValueType())));
   12897     }
   12898     // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
   12899     if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
   12900       SDValue NegN0 = DAG.getNode(ISD::SUB, SDLoc(N0),
   12901                                   XType, DAG.getConstant(0, XType), N0);
   12902       SDValue NotN0 = DAG.getNOT(SDLoc(N0), N0, XType);
   12903       return DAG.getNode(ISD::SRL, DL, XType,
   12904                          DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
   12905                          DAG.getConstant(XType.getSizeInBits()-1,
   12906                                          getShiftAmountTy(XType)));
   12907     }
   12908     // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
   12909     if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
   12910       SDValue Sign = DAG.getNode(ISD::SRL, SDLoc(N0), XType, N0,
   12911                                  DAG.getConstant(XType.getSizeInBits()-1,
   12912                                          getShiftAmountTy(N0.getValueType())));
   12913       return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
   12914     }
   12915   }
   12916 
   12917   // Check to see if this is an integer abs.
   12918   // select_cc setg[te] X,  0,  X, -X ->
   12919   // select_cc setgt    X, -1,  X, -X ->
   12920   // select_cc setl[te] X,  0, -X,  X ->
   12921   // select_cc setlt    X,  1, -X,  X ->
   12922   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
   12923   if (N1C) {
   12924     ConstantSDNode *SubC = nullptr;
   12925     if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
   12926          (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
   12927         N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
   12928       SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
   12929     else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
   12930               (N1C->isOne() && CC == ISD::SETLT)) &&
   12931              N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
   12932       SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
   12933 
   12934     EVT XType = N0.getValueType();
   12935     if (SubC && SubC->isNullValue() && XType.isInteger()) {
   12936       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), XType,
   12937                                   N0,
   12938                                   DAG.getConstant(XType.getSizeInBits()-1,
   12939                                          getShiftAmountTy(N0.getValueType())));
   12940       SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0),
   12941                                 XType, N0, Shift);
   12942       AddToWorklist(Shift.getNode());
   12943       AddToWorklist(Add.getNode());
   12944       return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
   12945     }
   12946   }
   12947 
   12948   return SDValue();
   12949 }
   12950 
   12951 /// This is a stub for TargetLowering::SimplifySetCC.
   12952 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
   12953                                    SDValue N1, ISD::CondCode Cond,
   12954                                    SDLoc DL, bool foldBooleans) {
   12955   TargetLowering::DAGCombinerInfo
   12956     DagCombineInfo(DAG, Level, false, this);
   12957   return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
   12958 }
   12959 
   12960 /// Given an ISD::SDIV node expressing a divide by constant, return
   12961 /// a DAG expression to select that will generate the same value by multiplying
   12962 /// by a magic number.
   12963 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
   12964 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
   12965   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
   12966   if (!C)
   12967     return SDValue();
   12968 
   12969   // Avoid division by zero.
   12970   if (!C->getAPIntValue())
   12971     return SDValue();
   12972 
   12973   std::vector<SDNode*> Built;
   12974   SDValue S =
   12975       TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
   12976 
   12977   for (SDNode *N : Built)
   12978     AddToWorklist(N);
   12979   return S;
   12980 }
   12981 
   12982 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a
   12983 /// DAG expression that will generate the same value by right shifting.
   12984 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
   12985   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
   12986   if (!C)
   12987     return SDValue();
   12988 
   12989   // Avoid division by zero.
   12990   if (!C->getAPIntValue())
   12991     return SDValue();
   12992 
   12993   std::vector<SDNode *> Built;
   12994   SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
   12995 
   12996   for (SDNode *N : Built)
   12997     AddToWorklist(N);
   12998   return S;
   12999 }
   13000 
   13001 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG
   13002 /// expression that will generate the same value by multiplying by a magic
   13003 /// number.
   13004 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
   13005 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
   13006   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
   13007   if (!C)
   13008     return SDValue();
   13009 
   13010   // Avoid division by zero.
   13011   if (!C->getAPIntValue())
   13012     return SDValue();
   13013 
   13014   std::vector<SDNode*> Built;
   13015   SDValue S =
   13016       TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
   13017 
   13018   for (SDNode *N : Built)
   13019     AddToWorklist(N);
   13020   return S;
   13021 }
   13022 
   13023 SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op) {
   13024   if (Level >= AfterLegalizeDAG)
   13025     return SDValue();
   13026 
   13027   // Expose the DAG combiner to the target combiner implementations.
   13028   TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
   13029 
   13030   unsigned Iterations = 0;
   13031   if (SDValue Est = TLI.getRecipEstimate(Op, DCI, Iterations)) {
   13032     if (Iterations) {
   13033       // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
   13034       // For the reciprocal, we need to find the zero of the function:
   13035       //   F(X) = A X - 1 [which has a zero at X = 1/A]
   13036       //     =>
   13037       //   X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
   13038       //     does not require additional intermediate precision]
   13039       EVT VT = Op.getValueType();
   13040       SDLoc DL(Op);
   13041       SDValue FPOne = DAG.getConstantFP(1.0, VT);
   13042 
   13043       AddToWorklist(Est.getNode());
   13044 
   13045       // Newton iterations: Est = Est + Est (1 - Arg * Est)
   13046       for (unsigned i = 0; i < Iterations; ++i) {
   13047         SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est);
   13048         AddToWorklist(NewEst.getNode());
   13049 
   13050         NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst);
   13051         AddToWorklist(NewEst.getNode());
   13052 
   13053         NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst);
   13054         AddToWorklist(NewEst.getNode());
   13055 
   13056         Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst);
   13057         AddToWorklist(Est.getNode());
   13058       }
   13059     }
   13060     return Est;
   13061   }
   13062 
   13063   return SDValue();
   13064 }
   13065 
   13066 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
   13067 /// For the reciprocal sqrt, we need to find the zero of the function:
   13068 ///   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
   13069 ///     =>
   13070 ///   X_{i+1} = X_i (1.5 - A X_i^2 / 2)
   13071 /// As a result, we precompute A/2 prior to the iteration loop.
   13072 SDValue DAGCombiner::BuildRsqrtNROneConst(SDValue Arg, SDValue Est,
   13073                                           unsigned Iterations) {
   13074   EVT VT = Arg.getValueType();
   13075   SDLoc DL(Arg);
   13076   SDValue ThreeHalves = DAG.getConstantFP(1.5, VT);
   13077 
   13078   // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that
   13079   // this entire sequence requires only one FP constant.
   13080   SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg);
   13081   AddToWorklist(HalfArg.getNode());
   13082 
   13083   HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg);
   13084   AddToWorklist(HalfArg.getNode());
   13085 
   13086   // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
   13087   for (unsigned i = 0; i < Iterations; ++i) {
   13088     SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est);
   13089     AddToWorklist(NewEst.getNode());
   13090 
   13091     NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst);
   13092     AddToWorklist(NewEst.getNode());
   13093 
   13094     NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst);
   13095     AddToWorklist(NewEst.getNode());
   13096 
   13097     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst);
   13098     AddToWorklist(Est.getNode());
   13099   }
   13100   return Est;
   13101 }
   13102 
   13103 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
   13104 /// For the reciprocal sqrt, we need to find the zero of the function:
   13105 ///   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
   13106 ///     =>
   13107 ///   X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0))
   13108 SDValue DAGCombiner::BuildRsqrtNRTwoConst(SDValue Arg, SDValue Est,
   13109                                           unsigned Iterations) {
   13110   EVT VT = Arg.getValueType();
   13111   SDLoc DL(Arg);
   13112   SDValue MinusThree = DAG.getConstantFP(-3.0, VT);
   13113   SDValue MinusHalf = DAG.getConstantFP(-0.5, VT);
   13114 
   13115   // Newton iterations: Est = -0.5 * Est * (-3.0 + Arg * Est * Est)
   13116   for (unsigned i = 0; i < Iterations; ++i) {
   13117     SDValue HalfEst = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf);
   13118     AddToWorklist(HalfEst.getNode());
   13119 
   13120     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Est);
   13121     AddToWorklist(Est.getNode());
   13122 
   13123     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg);
   13124     AddToWorklist(Est.getNode());
   13125 
   13126     Est = DAG.getNode(ISD::FADD, DL, VT, Est, MinusThree);
   13127     AddToWorklist(Est.getNode());
   13128 
   13129     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, HalfEst);
   13130     AddToWorklist(Est.getNode());
   13131   }
   13132   return Est;
   13133 }
   13134 
   13135 SDValue DAGCombiner::BuildRsqrtEstimate(SDValue Op) {
   13136   if (Level >= AfterLegalizeDAG)
   13137     return SDValue();
   13138 
   13139   // Expose the DAG combiner to the target combiner implementations.
   13140   TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
   13141   unsigned Iterations = 0;
   13142   bool UseOneConstNR = false;
   13143   if (SDValue Est = TLI.getRsqrtEstimate(Op, DCI, Iterations, UseOneConstNR)) {
   13144     AddToWorklist(Est.getNode());
   13145     if (Iterations) {
   13146       Est = UseOneConstNR ?
   13147         BuildRsqrtNROneConst(Op, Est, Iterations) :
   13148         BuildRsqrtNRTwoConst(Op, Est, Iterations);
   13149     }
   13150     return Est;
   13151   }
   13152 
   13153   return SDValue();
   13154 }
   13155 
   13156 /// Return true if base is a frame index, which is known not to alias with
   13157 /// anything but itself.  Provides base object and offset as results.
   13158 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
   13159                            const GlobalValue *&GV, const void *&CV) {
   13160   // Assume it is a primitive operation.
   13161   Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
   13162 
   13163   // If it's an adding a simple constant then integrate the offset.
   13164   if (Base.getOpcode() == ISD::ADD) {
   13165     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
   13166       Base = Base.getOperand(0);
   13167       Offset += C->getZExtValue();
   13168     }
   13169   }
   13170 
   13171   // Return the underlying GlobalValue, and update the Offset.  Return false
   13172   // for GlobalAddressSDNode since the same GlobalAddress may be represented
   13173   // by multiple nodes with different offsets.
   13174   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
   13175     GV = G->getGlobal();
   13176     Offset += G->getOffset();
   13177     return false;
   13178   }
   13179 
   13180   // Return the underlying Constant value, and update the Offset.  Return false
   13181   // for ConstantSDNodes since the same constant pool entry may be represented
   13182   // by multiple nodes with different offsets.
   13183   if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
   13184     CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
   13185                                          : (const void *)C->getConstVal();
   13186     Offset += C->getOffset();
   13187     return false;
   13188   }
   13189   // If it's any of the following then it can't alias with anything but itself.
   13190   return isa<FrameIndexSDNode>(Base);
   13191 }
   13192 
   13193 /// Return true if there is any possibility that the two addresses overlap.
   13194 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
   13195   // If they are the same then they must be aliases.
   13196   if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
   13197 
   13198   // If they are both volatile then they cannot be reordered.
   13199   if (Op0->isVolatile() && Op1->isVolatile()) return true;
   13200 
   13201   // Gather base node and offset information.
   13202   SDValue Base1, Base2;
   13203   int64_t Offset1, Offset2;
   13204   const GlobalValue *GV1, *GV2;
   13205   const void *CV1, *CV2;
   13206   bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
   13207                                       Base1, Offset1, GV1, CV1);
   13208   bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
   13209                                       Base2, Offset2, GV2, CV2);
   13210 
   13211   // If they have a same base address then check to see if they overlap.
   13212   if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
   13213     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
   13214              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
   13215 
   13216   // It is possible for different frame indices to alias each other, mostly
   13217   // when tail call optimization reuses return address slots for arguments.
   13218   // To catch this case, look up the actual index of frame indices to compute
   13219   // the real alias relationship.
   13220   if (isFrameIndex1 && isFrameIndex2) {
   13221     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
   13222     Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
   13223     Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
   13224     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
   13225              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
   13226   }
   13227 
   13228   // Otherwise, if we know what the bases are, and they aren't identical, then
   13229   // we know they cannot alias.
   13230   if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
   13231     return false;
   13232 
   13233   // If we know required SrcValue1 and SrcValue2 have relatively large alignment
   13234   // compared to the size and offset of the access, we may be able to prove they
   13235   // do not alias.  This check is conservative for now to catch cases created by
   13236   // splitting vector types.
   13237   if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
   13238       (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
   13239       (Op0->getMemoryVT().getSizeInBits() >> 3 ==
   13240        Op1->getMemoryVT().getSizeInBits() >> 3) &&
   13241       (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) {
   13242     int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
   13243     int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
   13244 
   13245     // There is no overlap between these relatively aligned accesses of similar
   13246     // size, return no alias.
   13247     if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
   13248         (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
   13249       return false;
   13250   }
   13251 
   13252   bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0
   13253                    ? CombinerGlobalAA
   13254                    : DAG.getSubtarget().useAA();
   13255 #ifndef NDEBUG
   13256   if (CombinerAAOnlyFunc.getNumOccurrences() &&
   13257       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
   13258     UseAA = false;
   13259 #endif
   13260   if (UseAA &&
   13261       Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
   13262     // Use alias analysis information.
   13263     int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
   13264                                  Op1->getSrcValueOffset());
   13265     int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
   13266         Op0->getSrcValueOffset() - MinOffset;
   13267     int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
   13268         Op1->getSrcValueOffset() - MinOffset;
   13269     AliasAnalysis::AliasResult AAResult =
   13270         AA.alias(AliasAnalysis::Location(Op0->getMemOperand()->getValue(),
   13271                                          Overlap1,
   13272                                          UseTBAA ? Op0->getAAInfo() : AAMDNodes()),
   13273                  AliasAnalysis::Location(Op1->getMemOperand()->getValue(),
   13274                                          Overlap2,
   13275                                          UseTBAA ? Op1->getAAInfo() : AAMDNodes()));
   13276     if (AAResult == AliasAnalysis::NoAlias)
   13277       return false;
   13278   }
   13279 
   13280   // Otherwise we have to assume they alias.
   13281   return true;
   13282 }
   13283 
   13284 /// Walk up chain skipping non-aliasing memory nodes,
   13285 /// looking for aliasing nodes and adding them to the Aliases vector.
   13286 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
   13287                                    SmallVectorImpl<SDValue> &Aliases) {
   13288   SmallVector<SDValue, 8> Chains;     // List of chains to visit.
   13289   SmallPtrSet<SDNode *, 16> Visited;  // Visited node set.
   13290 
   13291   // Get alias information for node.
   13292   bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
   13293 
   13294   // Starting off.
   13295   Chains.push_back(OriginalChain);
   13296   unsigned Depth = 0;
   13297 
   13298   // Look at each chain and determine if it is an alias.  If so, add it to the
   13299   // aliases list.  If not, then continue up the chain looking for the next
   13300   // candidate.
   13301   while (!Chains.empty()) {
   13302     SDValue Chain = Chains.back();
   13303     Chains.pop_back();
   13304 
   13305     // For TokenFactor nodes, look at each operand and only continue up the
   13306     // chain until we find two aliases.  If we've seen two aliases, assume we'll
   13307     // find more and revert to original chain since the xform is unlikely to be
   13308     // profitable.
   13309     //
   13310     // FIXME: The depth check could be made to return the last non-aliasing
   13311     // chain we found before we hit a tokenfactor rather than the original
   13312     // chain.
   13313     if (Depth > 6 || Aliases.size() == 2) {
   13314       Aliases.clear();
   13315       Aliases.push_back(OriginalChain);
   13316       return;
   13317     }
   13318 
   13319     // Don't bother if we've been before.
   13320     if (!Visited.insert(Chain.getNode()).second)
   13321       continue;
   13322 
   13323     switch (Chain.getOpcode()) {
   13324     case ISD::EntryToken:
   13325       // Entry token is ideal chain operand, but handled in FindBetterChain.
   13326       break;
   13327 
   13328     case ISD::LOAD:
   13329     case ISD::STORE: {
   13330       // Get alias information for Chain.
   13331       bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
   13332           !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
   13333 
   13334       // If chain is alias then stop here.
   13335       if (!(IsLoad && IsOpLoad) &&
   13336           isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
   13337         Aliases.push_back(Chain);
   13338       } else {
   13339         // Look further up the chain.
   13340         Chains.push_back(Chain.getOperand(0));
   13341         ++Depth;
   13342       }
   13343       break;
   13344     }
   13345 
   13346     case ISD::TokenFactor:
   13347       // We have to check each of the operands of the token factor for "small"
   13348       // token factors, so we queue them up.  Adding the operands to the queue
   13349       // (stack) in reverse order maintains the original order and increases the
   13350       // likelihood that getNode will find a matching token factor (CSE.)
   13351       if (Chain.getNumOperands() > 16) {
   13352         Aliases.push_back(Chain);
   13353         break;
   13354       }
   13355       for (unsigned n = Chain.getNumOperands(); n;)
   13356         Chains.push_back(Chain.getOperand(--n));
   13357       ++Depth;
   13358       break;
   13359 
   13360     default:
   13361       // For all other instructions we will just have to take what we can get.
   13362       Aliases.push_back(Chain);
   13363       break;
   13364     }
   13365   }
   13366 
   13367   // We need to be careful here to also search for aliases through the
   13368   // value operand of a store, etc. Consider the following situation:
   13369   //   Token1 = ...
   13370   //   L1 = load Token1, %52
   13371   //   S1 = store Token1, L1, %51
   13372   //   L2 = load Token1, %52+8
   13373   //   S2 = store Token1, L2, %51+8
   13374   //   Token2 = Token(S1, S2)
   13375   //   L3 = load Token2, %53
   13376   //   S3 = store Token2, L3, %52
   13377   //   L4 = load Token2, %53+8
   13378   //   S4 = store Token2, L4, %52+8
   13379   // If we search for aliases of S3 (which loads address %52), and we look
   13380   // only through the chain, then we'll miss the trivial dependence on L1
   13381   // (which also loads from %52). We then might change all loads and
   13382   // stores to use Token1 as their chain operand, which could result in
   13383   // copying %53 into %52 before copying %52 into %51 (which should
   13384   // happen first).
   13385   //
   13386   // The problem is, however, that searching for such data dependencies
   13387   // can become expensive, and the cost is not directly related to the
   13388   // chain depth. Instead, we'll rule out such configurations here by
   13389   // insisting that we've visited all chain users (except for users
   13390   // of the original chain, which is not necessary). When doing this,
   13391   // we need to look through nodes we don't care about (otherwise, things
   13392   // like register copies will interfere with trivial cases).
   13393 
   13394   SmallVector<const SDNode *, 16> Worklist;
   13395   for (const SDNode *N : Visited)
   13396     if (N != OriginalChain.getNode())
   13397       Worklist.push_back(N);
   13398 
   13399   while (!Worklist.empty()) {
   13400     const SDNode *M = Worklist.pop_back_val();
   13401 
   13402     // We have already visited M, and want to make sure we've visited any uses
   13403     // of M that we care about. For uses that we've not visisted, and don't
   13404     // care about, queue them to the worklist.
   13405 
   13406     for (SDNode::use_iterator UI = M->use_begin(),
   13407          UIE = M->use_end(); UI != UIE; ++UI)
   13408       if (UI.getUse().getValueType() == MVT::Other &&
   13409           Visited.insert(*UI).second) {
   13410         if (isa<MemIntrinsicSDNode>(*UI) || isa<MemSDNode>(*UI)) {
   13411           // We've not visited this use, and we care about it (it could have an
   13412           // ordering dependency with the original node).
   13413           Aliases.clear();
   13414           Aliases.push_back(OriginalChain);
   13415           return;
   13416         }
   13417 
   13418         // We've not visited this use, but we don't care about it. Mark it as
   13419         // visited and enqueue it to the worklist.
   13420         Worklist.push_back(*UI);
   13421       }
   13422   }
   13423 }
   13424 
   13425 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain
   13426 /// (aliasing node.)
   13427 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
   13428   SmallVector<SDValue, 8> Aliases;  // Ops for replacing token factor.
   13429 
   13430   // Accumulate all the aliases to this node.
   13431   GatherAllAliases(N, OldChain, Aliases);
   13432 
   13433   // If no operands then chain to entry token.
   13434   if (Aliases.size() == 0)
   13435     return DAG.getEntryNode();
   13436 
   13437   // If a single operand then chain to it.  We don't need to revisit it.
   13438   if (Aliases.size() == 1)
   13439     return Aliases[0];
   13440 
   13441   // Construct a custom tailored token factor.
   13442   return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
   13443 }
   13444 
   13445 /// This is the entry point for the file.
   13446 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
   13447                            CodeGenOpt::Level OptLevel) {
   13448   /// This is the main entry point to this class.
   13449   DAGCombiner(*this, AA, OptLevel).Run(Level);
   13450 }
   13451