Use local vars to improve readability. No functional change.
[oota-llvm.git] / lib / CodeGen / SelectionDAG / DAGCombiner.cpp
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/SmallPtrSet.h"
21 #include "llvm/ADT/SetVector.h"
22 #include "llvm/ADT/Statistic.h"
23 #include "llvm/Analysis/AliasAnalysis.h"
24 #include "llvm/CodeGen/MachineFrameInfo.h"
25 #include "llvm/CodeGen/MachineFunction.h"
26 #include "llvm/IR/DataLayout.h"
27 #include "llvm/IR/DerivedTypes.h"
28 #include "llvm/IR/Function.h"
29 #include "llvm/IR/LLVMContext.h"
30 #include "llvm/Support/CommandLine.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/Support/ErrorHandling.h"
33 #include "llvm/Support/MathExtras.h"
34 #include "llvm/Support/raw_ostream.h"
35 #include "llvm/Target/TargetLowering.h"
36 #include "llvm/Target/TargetMachine.h"
37 #include "llvm/Target/TargetOptions.h"
38 #include "llvm/Target/TargetRegisterInfo.h"
39 #include "llvm/Target/TargetSubtargetInfo.h"
40 #include <algorithm>
41 using namespace llvm;
42
43 #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 //------------------------------ DAGCombiner ---------------------------------//
81
82   class DAGCombiner {
83     SelectionDAG &DAG;
84     const TargetLowering &TLI;
85     CombineLevel Level;
86     CodeGenOpt::Level OptLevel;
87     bool LegalOperations;
88     bool LegalTypes;
89     bool ForCodeSize;
90
91     /// \brief Worklist of all of the nodes that need to be simplified.
92     ///
93     /// This must behave as a stack -- new nodes to process are pushed onto the
94     /// back and when processing we pop off of the back.
95     ///
96     /// The worklist will not contain duplicates but may contain null entries
97     /// due to nodes being deleted from the underlying DAG.
98     SmallVector<SDNode *, 64> Worklist;
99
100     /// \brief Mapping from an SDNode to its position on the worklist.
101     ///
102     /// This is used to find and remove nodes from the worklist (by nulling
103     /// them) when they are deleted from the underlying DAG. It relies on
104     /// stable indices of nodes within the worklist.
105     DenseMap<SDNode *, unsigned> WorklistMap;
106
107     /// \brief Set of nodes which have been combined (at least once).
108     ///
109     /// This is used to allow us to reliably add any operands of a DAG node
110     /// which have not yet been combined to the worklist.
111     SmallPtrSet<SDNode *, 64> CombinedNodes;
112
113     // AA - Used for DAG load/store alias analysis.
114     AliasAnalysis &AA;
115
116     /// AddUsersToWorklist - When an instruction is simplified, add all users of
117     /// the instruction to the work lists because they might get more simplified
118     /// now.
119     ///
120     void AddUsersToWorklist(SDNode *N) {
121       for (SDNode *Node : N->uses())
122         AddToWorklist(Node);
123     }
124
125     /// visit - call the node-specific routine that knows how to fold each
126     /// particular type of node.
127     SDValue visit(SDNode *N);
128
129   public:
130     /// AddToWorklist - Add to the work list making sure its instance is at the
131     /// back (next to be processed.)
132     void AddToWorklist(SDNode *N) {
133       // Skip handle nodes as they can't usefully be combined and confuse the
134       // zero-use deletion strategy.
135       if (N->getOpcode() == ISD::HANDLENODE)
136         return;
137
138       if (WorklistMap.insert(std::make_pair(N, Worklist.size())).second)
139         Worklist.push_back(N);
140     }
141
142     /// removeFromWorklist - remove all instances of N from the worklist.
143     ///
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     /// SimplifyDemandedBits - Check the specified integer node value to see if
177     /// it can be simplified or if things it uses can be simplified by bit
178     /// propagation.  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     bool SliceUpLoad(SDNode *N);
190
191     /// \brief Replace an ISD::EXTRACT_VECTOR_ELT of a load with a narrowed
192     ///   load.
193     ///
194     /// \param EVE ISD::EXTRACT_VECTOR_ELT to be replaced.
195     /// \param InVecVT type of the input vector to EVE with bitcasts resolved.
196     /// \param EltNo index of the vector element to load.
197     /// \param OriginalLoad load that EVE came from to be replaced.
198     /// \returns EVE on success SDValue() on failure.
199     SDValue ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
200         SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad);
201     void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
202     SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
203     SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
204     SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
205     SDValue PromoteIntBinOp(SDValue Op);
206     SDValue PromoteIntShiftOp(SDValue Op);
207     SDValue PromoteExtend(SDValue Op);
208     bool PromoteLoad(SDValue Op);
209
210     void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
211                          SDValue Trunc, SDValue ExtLoad, SDLoc DL,
212                          ISD::NodeType ExtType);
213
214     /// combine - call the node-specific routine that knows how to fold each
215     /// particular type of node. If that doesn't do anything, try the
216     /// target-specific DAG combines.
217     SDValue combine(SDNode *N);
218
219     // Visitation implementation - Implement dag node combining for different
220     // node types.  The semantics are as follows:
221     // Return Value:
222     //   SDValue.getNode() == 0 - No change was made
223     //   SDValue.getNode() == N - N was replaced, is dead and has been handled.
224     //   otherwise              - N should be replaced by the returned Operand.
225     //
226     SDValue visitTokenFactor(SDNode *N);
227     SDValue visitMERGE_VALUES(SDNode *N);
228     SDValue visitADD(SDNode *N);
229     SDValue visitSUB(SDNode *N);
230     SDValue visitADDC(SDNode *N);
231     SDValue visitSUBC(SDNode *N);
232     SDValue visitADDE(SDNode *N);
233     SDValue visitSUBE(SDNode *N);
234     SDValue visitMUL(SDNode *N);
235     SDValue visitSDIV(SDNode *N);
236     SDValue visitUDIV(SDNode *N);
237     SDValue visitSREM(SDNode *N);
238     SDValue visitUREM(SDNode *N);
239     SDValue visitMULHU(SDNode *N);
240     SDValue visitMULHS(SDNode *N);
241     SDValue visitSMUL_LOHI(SDNode *N);
242     SDValue visitUMUL_LOHI(SDNode *N);
243     SDValue visitSMULO(SDNode *N);
244     SDValue visitUMULO(SDNode *N);
245     SDValue visitSDIVREM(SDNode *N);
246     SDValue visitUDIVREM(SDNode *N);
247     SDValue visitAND(SDNode *N);
248     SDValue visitOR(SDNode *N);
249     SDValue visitXOR(SDNode *N);
250     SDValue SimplifyVBinOp(SDNode *N);
251     SDValue SimplifyVUnaryOp(SDNode *N);
252     SDValue visitSHL(SDNode *N);
253     SDValue visitSRA(SDNode *N);
254     SDValue visitSRL(SDNode *N);
255     SDValue visitRotate(SDNode *N);
256     SDValue visitCTLZ(SDNode *N);
257     SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
258     SDValue visitCTTZ(SDNode *N);
259     SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
260     SDValue visitCTPOP(SDNode *N);
261     SDValue visitSELECT(SDNode *N);
262     SDValue visitVSELECT(SDNode *N);
263     SDValue visitSELECT_CC(SDNode *N);
264     SDValue visitSETCC(SDNode *N);
265     SDValue visitSIGN_EXTEND(SDNode *N);
266     SDValue visitZERO_EXTEND(SDNode *N);
267     SDValue visitANY_EXTEND(SDNode *N);
268     SDValue visitSIGN_EXTEND_INREG(SDNode *N);
269     SDValue visitTRUNCATE(SDNode *N);
270     SDValue visitBITCAST(SDNode *N);
271     SDValue visitBUILD_PAIR(SDNode *N);
272     SDValue visitFADD(SDNode *N);
273     SDValue visitFSUB(SDNode *N);
274     SDValue visitFMUL(SDNode *N);
275     SDValue visitFMA(SDNode *N);
276     SDValue visitFDIV(SDNode *N);
277     SDValue visitFREM(SDNode *N);
278     SDValue visitFCOPYSIGN(SDNode *N);
279     SDValue visitSINT_TO_FP(SDNode *N);
280     SDValue visitUINT_TO_FP(SDNode *N);
281     SDValue visitFP_TO_SINT(SDNode *N);
282     SDValue visitFP_TO_UINT(SDNode *N);
283     SDValue visitFP_ROUND(SDNode *N);
284     SDValue visitFP_ROUND_INREG(SDNode *N);
285     SDValue visitFP_EXTEND(SDNode *N);
286     SDValue visitFNEG(SDNode *N);
287     SDValue visitFABS(SDNode *N);
288     SDValue visitFCEIL(SDNode *N);
289     SDValue visitFTRUNC(SDNode *N);
290     SDValue visitFFLOOR(SDNode *N);
291     SDValue visitBRCOND(SDNode *N);
292     SDValue visitBR_CC(SDNode *N);
293     SDValue visitLOAD(SDNode *N);
294     SDValue visitSTORE(SDNode *N);
295     SDValue visitINSERT_VECTOR_ELT(SDNode *N);
296     SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
297     SDValue visitBUILD_VECTOR(SDNode *N);
298     SDValue visitCONCAT_VECTORS(SDNode *N);
299     SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
300     SDValue visitVECTOR_SHUFFLE(SDNode *N);
301     SDValue visitINSERT_SUBVECTOR(SDNode *N);
302
303     SDValue XformToShuffleWithZero(SDNode *N);
304     SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS);
305
306     SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt);
307
308     bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
309     SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
310     SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2);
311     SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2,
312                              SDValue N3, ISD::CondCode CC,
313                              bool NotExtCompare = false);
314     SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
315                           SDLoc DL, bool foldBooleans = true);
316
317     bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
318                            SDValue &CC) const;
319     bool isOneUseSetCC(SDValue N) const;
320
321     SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
322                                          unsigned HiOp);
323     SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
324     SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
325     SDValue BuildSDIV(SDNode *N);
326     SDValue BuildSDIVPow2(SDNode *N);
327     SDValue BuildUDIV(SDNode *N);
328     SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
329                                bool DemandHighBits = true);
330     SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
331     SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
332                               SDValue InnerPos, SDValue InnerNeg,
333                               unsigned PosOpcode, unsigned NegOpcode,
334                               SDLoc DL);
335     SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL);
336     SDValue ReduceLoadWidth(SDNode *N);
337     SDValue ReduceLoadOpStoreWidth(SDNode *N);
338     SDValue TransformFPLoadStorePair(SDNode *N);
339     SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
340     SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
341
342     SDValue GetDemandedBits(SDValue V, const APInt &Mask);
343
344     /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
345     /// looking for aliasing nodes and adding them to the Aliases vector.
346     void GatherAllAliases(SDNode *N, SDValue OriginalChain,
347                           SmallVectorImpl<SDValue> &Aliases);
348
349     /// isAlias - Return true if there is any possibility that the two addresses
350     /// overlap.
351     bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const;
352
353     /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes,
354     /// looking for a better chain (aliasing node.)
355     SDValue FindBetterChain(SDNode *N, SDValue Chain);
356
357     /// Merge consecutive store operations into a wide store.
358     /// This optimization uses wide integers or vectors when possible.
359     /// \return True if some memory operations were changed.
360     bool MergeConsecutiveStores(StoreSDNode *N);
361
362     /// \brief Try to transform a truncation where C is a constant:
363     ///     (trunc (and X, C)) -> (and (trunc X), (trunc C))
364     ///
365     /// \p N needs to be a truncation and its first operand an AND. Other
366     /// requirements are checked by the function (e.g. that trunc is
367     /// single-use) and if missed an empty SDValue is returned.
368     SDValue distributeTruncateThroughAnd(SDNode *N);
369
370   public:
371     DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
372         : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
373           OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
374       AttributeSet FnAttrs =
375           DAG.getMachineFunction().getFunction()->getAttributes();
376       ForCodeSize =
377           FnAttrs.hasAttribute(AttributeSet::FunctionIndex,
378                                Attribute::OptimizeForSize) ||
379           FnAttrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::MinSize);
380     }
381
382     /// Run - runs the dag combiner on all nodes in the work list
383     void Run(CombineLevel AtLevel);
384
385     SelectionDAG &getDAG() const { return DAG; }
386
387     /// getShiftAmountTy - Returns a type large enough to hold any valid
388     /// shift amount - before type legalization these can be huge.
389     EVT getShiftAmountTy(EVT LHSTy) {
390       assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
391       if (LHSTy.isVector())
392         return LHSTy;
393       return LegalTypes ? TLI.getScalarShiftAmountTy(LHSTy)
394                         : TLI.getPointerTy();
395     }
396
397     /// isTypeLegal - This method returns true if we are running before type
398     /// legalization or if the specified VT is legal.
399     bool isTypeLegal(const EVT &VT) {
400       if (!LegalTypes) return true;
401       return TLI.isTypeLegal(VT);
402     }
403
404     /// getSetCCResultType - Convenience wrapper around
405     /// TargetLowering::getSetCCResultType
406     EVT getSetCCResultType(EVT VT) const {
407       return TLI.getSetCCResultType(*DAG.getContext(), VT);
408     }
409   };
410 }
411
412
413 namespace {
414 /// WorklistRemover - This class is a DAGUpdateListener that removes any deleted
415 /// nodes from the worklist.
416 class WorklistRemover : public SelectionDAG::DAGUpdateListener {
417   DAGCombiner &DC;
418 public:
419   explicit WorklistRemover(DAGCombiner &dc)
420     : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
421
422   void NodeDeleted(SDNode *N, SDNode *E) override {
423     DC.removeFromWorklist(N);
424   }
425 };
426 }
427
428 //===----------------------------------------------------------------------===//
429 //  TargetLowering::DAGCombinerInfo implementation
430 //===----------------------------------------------------------------------===//
431
432 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
433   ((DAGCombiner*)DC)->AddToWorklist(N);
434 }
435
436 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
437   ((DAGCombiner*)DC)->removeFromWorklist(N);
438 }
439
440 SDValue TargetLowering::DAGCombinerInfo::
441 CombineTo(SDNode *N, const std::vector<SDValue> &To, bool AddTo) {
442   return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
443 }
444
445 SDValue TargetLowering::DAGCombinerInfo::
446 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
447   return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
448 }
449
450
451 SDValue TargetLowering::DAGCombinerInfo::
452 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
453   return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
454 }
455
456 void TargetLowering::DAGCombinerInfo::
457 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
458   return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
459 }
460
461 //===----------------------------------------------------------------------===//
462 // Helper Functions
463 //===----------------------------------------------------------------------===//
464
465 void DAGCombiner::deleteAndRecombine(SDNode *N) {
466   removeFromWorklist(N);
467
468   // If the operands of this node are only used by the node, they will now be
469   // dead. Make sure to re-visit them and recursively delete dead nodes.
470   for (const SDValue &Op : N->ops())
471     if (Op->hasOneUse())
472       AddToWorklist(Op.getNode());
473
474   DAG.DeleteNode(N);
475 }
476
477 /// isNegatibleForFree - Return 1 if we can compute the negated form of the
478 /// specified expression for the same cost as the expression itself, or 2 if we
479 /// can compute the negated form more cheaply than the expression itself.
480 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
481                                const TargetLowering &TLI,
482                                const TargetOptions *Options,
483                                unsigned Depth = 0) {
484   // fneg is removable even if it has multiple uses.
485   if (Op.getOpcode() == ISD::FNEG) return 2;
486
487   // Don't allow anything with multiple uses.
488   if (!Op.hasOneUse()) return 0;
489
490   // Don't recurse exponentially.
491   if (Depth > 6) return 0;
492
493   switch (Op.getOpcode()) {
494   default: return false;
495   case ISD::ConstantFP:
496     // Don't invert constant FP values after legalize.  The negated constant
497     // isn't necessarily legal.
498     return LegalOperations ? 0 : 1;
499   case ISD::FADD:
500     // FIXME: determine better conditions for this xform.
501     if (!Options->UnsafeFPMath) return 0;
502
503     // After operation legalization, it might not be legal to create new FSUBs.
504     if (LegalOperations &&
505         !TLI.isOperationLegalOrCustom(ISD::FSUB,  Op.getValueType()))
506       return 0;
507
508     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
509     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
510                                     Options, Depth + 1))
511       return V;
512     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
513     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
514                               Depth + 1);
515   case ISD::FSUB:
516     // We can't turn -(A-B) into B-A when we honor signed zeros.
517     if (!Options->UnsafeFPMath) return 0;
518
519     // fold (fneg (fsub A, B)) -> (fsub B, A)
520     return 1;
521
522   case ISD::FMUL:
523   case ISD::FDIV:
524     if (Options->HonorSignDependentRoundingFPMath()) return 0;
525
526     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
527     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
528                                     Options, Depth + 1))
529       return V;
530
531     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
532                               Depth + 1);
533
534   case ISD::FP_EXTEND:
535   case ISD::FP_ROUND:
536   case ISD::FSIN:
537     return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
538                               Depth + 1);
539   }
540 }
541
542 /// GetNegatedExpression - If isNegatibleForFree returns true, this function
543 /// returns the newly negated expression.
544 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
545                                     bool LegalOperations, unsigned Depth = 0) {
546   const TargetOptions &Options = DAG.getTarget().Options;
547   // fneg is removable even if it has multiple uses.
548   if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
549
550   // Don't allow anything with multiple uses.
551   assert(Op.hasOneUse() && "Unknown reuse!");
552
553   assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
554   switch (Op.getOpcode()) {
555   default: llvm_unreachable("Unknown code");
556   case ISD::ConstantFP: {
557     APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
558     V.changeSign();
559     return DAG.getConstantFP(V, Op.getValueType());
560   }
561   case ISD::FADD:
562     // FIXME: determine better conditions for this xform.
563     assert(Options.UnsafeFPMath);
564
565     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
566     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
567                            DAG.getTargetLoweringInfo(), &Options, Depth+1))
568       return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
569                          GetNegatedExpression(Op.getOperand(0), DAG,
570                                               LegalOperations, Depth+1),
571                          Op.getOperand(1));
572     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
573     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
574                        GetNegatedExpression(Op.getOperand(1), DAG,
575                                             LegalOperations, Depth+1),
576                        Op.getOperand(0));
577   case ISD::FSUB:
578     // We can't turn -(A-B) into B-A when we honor signed zeros.
579     assert(Options.UnsafeFPMath);
580
581     // fold (fneg (fsub 0, B)) -> B
582     if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
583       if (N0CFP->getValueAPF().isZero())
584         return Op.getOperand(1);
585
586     // fold (fneg (fsub A, B)) -> (fsub B, A)
587     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
588                        Op.getOperand(1), Op.getOperand(0));
589
590   case ISD::FMUL:
591   case ISD::FDIV:
592     assert(!Options.HonorSignDependentRoundingFPMath());
593
594     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
595     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
596                            DAG.getTargetLoweringInfo(), &Options, Depth+1))
597       return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
598                          GetNegatedExpression(Op.getOperand(0), DAG,
599                                               LegalOperations, Depth+1),
600                          Op.getOperand(1));
601
602     // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
603     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
604                        Op.getOperand(0),
605                        GetNegatedExpression(Op.getOperand(1), DAG,
606                                             LegalOperations, Depth+1));
607
608   case ISD::FP_EXTEND:
609   case ISD::FSIN:
610     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
611                        GetNegatedExpression(Op.getOperand(0), DAG,
612                                             LegalOperations, Depth+1));
613   case ISD::FP_ROUND:
614       return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
615                          GetNegatedExpression(Op.getOperand(0), DAG,
616                                               LegalOperations, Depth+1),
617                          Op.getOperand(1));
618   }
619 }
620
621 // isSetCCEquivalent - Return true if this node is a setcc, or is a select_cc
622 // that selects between the target values used for true and false, making it
623 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
624 // the appropriate nodes based on the type of node we are checking. This
625 // simplifies life a bit for the callers.
626 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
627                                     SDValue &CC) const {
628   if (N.getOpcode() == ISD::SETCC) {
629     LHS = N.getOperand(0);
630     RHS = N.getOperand(1);
631     CC  = N.getOperand(2);
632     return true;
633   }
634
635   if (N.getOpcode() != ISD::SELECT_CC ||
636       !TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
637       !TLI.isConstFalseVal(N.getOperand(3).getNode()))
638     return false;
639
640   LHS = N.getOperand(0);
641   RHS = N.getOperand(1);
642   CC  = N.getOperand(4);
643   return true;
644 }
645
646 // isOneUseSetCC - Return true if this is a SetCC-equivalent operation with only
647 // one use.  If this is true, it allows the users to invert the operation for
648 // free when it is profitable to do so.
649 bool DAGCombiner::isOneUseSetCC(SDValue N) const {
650   SDValue N0, N1, N2;
651   if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
652     return true;
653   return false;
654 }
655
656 /// isConstantSplatVector - Returns true if N is a BUILD_VECTOR node whose
657 /// elements are all the same constant or undefined.
658 static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
659   BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
660   if (!C)
661     return false;
662
663   APInt SplatUndef;
664   unsigned SplatBitSize;
665   bool HasAnyUndefs;
666   EVT EltVT = N->getValueType(0).getVectorElementType();
667   return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
668                              HasAnyUndefs) &&
669           EltVT.getSizeInBits() >= SplatBitSize);
670 }
671
672 // \brief Returns the SDNode if it is a constant BuildVector or constant.
673 static SDNode *isConstantBuildVectorOrConstantInt(SDValue N) {
674   if (isa<ConstantSDNode>(N))
675     return N.getNode();
676   BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N);
677   if(BV && BV->isConstant())
678     return BV;
679   return nullptr;
680 }
681
682 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
683 // int.
684 static ConstantSDNode *isConstOrConstSplat(SDValue N) {
685   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
686     return CN;
687
688   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
689     BitVector UndefElements;
690     ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
691
692     // BuildVectors can truncate their operands. Ignore that case here.
693     // FIXME: We blindly ignore splats which include undef which is overly
694     // pessimistic.
695     if (CN && UndefElements.none() &&
696         CN->getValueType(0) == N.getValueType().getScalarType())
697       return CN;
698   }
699
700   return nullptr;
701 }
702
703 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
704 // float.
705 static ConstantFPSDNode *isConstOrConstSplatFP(SDValue N) {
706   if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
707     return CN;
708
709   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
710     BitVector UndefElements;
711     ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements);
712
713     // BuildVectors can truncate their operands. Ignore that case here.
714     // FIXME: We blindly ignore splats which include undef which is overly
715     // pessimistic.
716     if (CN && UndefElements.none() &&
717         CN->getValueType(0) == N.getValueType().getScalarType())
718       return CN;
719   }
720
721   return nullptr;
722 }
723
724 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
725                                     SDValue N0, SDValue N1) {
726   EVT VT = N0.getValueType();
727   if (N0.getOpcode() == Opc) {
728     if (SDNode *L = isConstantBuildVectorOrConstantInt(N0.getOperand(1))) {
729       if (SDNode *R = isConstantBuildVectorOrConstantInt(N1)) {
730         // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
731         SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, L, R);
732         if (!OpNode.getNode())
733           return SDValue();
734         return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
735       }
736       if (N0.hasOneUse()) {
737         // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
738         // use
739         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
740         if (!OpNode.getNode())
741           return SDValue();
742         AddToWorklist(OpNode.getNode());
743         return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
744       }
745     }
746   }
747
748   if (N1.getOpcode() == Opc) {
749     if (SDNode *R = isConstantBuildVectorOrConstantInt(N1.getOperand(1))) {
750       if (SDNode *L = isConstantBuildVectorOrConstantInt(N0)) {
751         // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
752         SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, R, L);
753         if (!OpNode.getNode())
754           return SDValue();
755         return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
756       }
757       if (N1.hasOneUse()) {
758         // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one
759         // use
760         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0);
761         if (!OpNode.getNode())
762           return SDValue();
763         AddToWorklist(OpNode.getNode());
764         return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
765       }
766     }
767   }
768
769   return SDValue();
770 }
771
772 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
773                                bool AddTo) {
774   assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
775   ++NodesCombined;
776   DEBUG(dbgs() << "\nReplacing.1 ";
777         N->dump(&DAG);
778         dbgs() << "\nWith: ";
779         To[0].getNode()->dump(&DAG);
780         dbgs() << " and " << NumTo-1 << " other values\n";
781         for (unsigned i = 0, e = NumTo; i != e; ++i)
782           assert((!To[i].getNode() ||
783                   N->getValueType(i) == To[i].getValueType()) &&
784                  "Cannot combine value to value of different type!"));
785   WorklistRemover DeadNodes(*this);
786   DAG.ReplaceAllUsesWith(N, To);
787   if (AddTo) {
788     // Push the new nodes and any users onto the worklist
789     for (unsigned i = 0, e = NumTo; i != e; ++i) {
790       if (To[i].getNode()) {
791         AddToWorklist(To[i].getNode());
792         AddUsersToWorklist(To[i].getNode());
793       }
794     }
795   }
796
797   // Finally, if the node is now dead, remove it from the graph.  The node
798   // may not be dead if the replacement process recursively simplified to
799   // something else needing this node.
800   if (N->use_empty())
801     deleteAndRecombine(N);
802   return SDValue(N, 0);
803 }
804
805 void DAGCombiner::
806 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
807   // Replace all uses.  If any nodes become isomorphic to other nodes and
808   // are deleted, make sure to remove them from our worklist.
809   WorklistRemover DeadNodes(*this);
810   DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
811
812   // Push the new node and any (possibly new) users onto the worklist.
813   AddToWorklist(TLO.New.getNode());
814   AddUsersToWorklist(TLO.New.getNode());
815
816   // Finally, if the node is now dead, remove it from the graph.  The node
817   // may not be dead if the replacement process recursively simplified to
818   // something else needing this node.
819   if (TLO.Old.getNode()->use_empty())
820     deleteAndRecombine(TLO.Old.getNode());
821 }
822
823 /// SimplifyDemandedBits - Check the specified integer node value to see if
824 /// it can be simplified or if things it uses can be simplified by bit
825 /// propagation.  If so, return true.
826 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
827   TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
828   APInt KnownZero, KnownOne;
829   if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
830     return false;
831
832   // Revisit the node.
833   AddToWorklist(Op.getNode());
834
835   // Replace the old value with the new one.
836   ++NodesCombined;
837   DEBUG(dbgs() << "\nReplacing.2 ";
838         TLO.Old.getNode()->dump(&DAG);
839         dbgs() << "\nWith: ";
840         TLO.New.getNode()->dump(&DAG);
841         dbgs() << '\n');
842
843   CommitTargetLoweringOpt(TLO);
844   return true;
845 }
846
847 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
848   SDLoc dl(Load);
849   EVT VT = Load->getValueType(0);
850   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
851
852   DEBUG(dbgs() << "\nReplacing.9 ";
853         Load->dump(&DAG);
854         dbgs() << "\nWith: ";
855         Trunc.getNode()->dump(&DAG);
856         dbgs() << '\n');
857   WorklistRemover DeadNodes(*this);
858   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
859   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
860   deleteAndRecombine(Load);
861   AddToWorklist(Trunc.getNode());
862 }
863
864 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
865   Replace = false;
866   SDLoc dl(Op);
867   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
868     EVT MemVT = LD->getMemoryVT();
869     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
870       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
871                                                   : ISD::EXTLOAD)
872       : LD->getExtensionType();
873     Replace = true;
874     return DAG.getExtLoad(ExtType, dl, PVT,
875                           LD->getChain(), LD->getBasePtr(),
876                           MemVT, LD->getMemOperand());
877   }
878
879   unsigned Opc = Op.getOpcode();
880   switch (Opc) {
881   default: break;
882   case ISD::AssertSext:
883     return DAG.getNode(ISD::AssertSext, dl, PVT,
884                        SExtPromoteOperand(Op.getOperand(0), PVT),
885                        Op.getOperand(1));
886   case ISD::AssertZext:
887     return DAG.getNode(ISD::AssertZext, dl, PVT,
888                        ZExtPromoteOperand(Op.getOperand(0), PVT),
889                        Op.getOperand(1));
890   case ISD::Constant: {
891     unsigned ExtOpc =
892       Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
893     return DAG.getNode(ExtOpc, dl, PVT, Op);
894   }
895   }
896
897   if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
898     return SDValue();
899   return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
900 }
901
902 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
903   if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
904     return SDValue();
905   EVT OldVT = Op.getValueType();
906   SDLoc dl(Op);
907   bool Replace = false;
908   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
909   if (!NewOp.getNode())
910     return SDValue();
911   AddToWorklist(NewOp.getNode());
912
913   if (Replace)
914     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
915   return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
916                      DAG.getValueType(OldVT));
917 }
918
919 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
920   EVT OldVT = Op.getValueType();
921   SDLoc dl(Op);
922   bool Replace = false;
923   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
924   if (!NewOp.getNode())
925     return SDValue();
926   AddToWorklist(NewOp.getNode());
927
928   if (Replace)
929     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
930   return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
931 }
932
933 /// PromoteIntBinOp - Promote the specified integer binary operation if the
934 /// target indicates it is beneficial. e.g. On x86, it's usually better to
935 /// promote i16 operations to i32 since i16 instructions are longer.
936 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
937   if (!LegalOperations)
938     return SDValue();
939
940   EVT VT = Op.getValueType();
941   if (VT.isVector() || !VT.isInteger())
942     return SDValue();
943
944   // If operation type is 'undesirable', e.g. i16 on x86, consider
945   // promoting it.
946   unsigned Opc = Op.getOpcode();
947   if (TLI.isTypeDesirableForOp(Opc, VT))
948     return SDValue();
949
950   EVT PVT = VT;
951   // Consult target whether it is a good idea to promote this operation and
952   // what's the right type to promote it to.
953   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
954     assert(PVT != VT && "Don't know what type to promote to!");
955
956     bool Replace0 = false;
957     SDValue N0 = Op.getOperand(0);
958     SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
959     if (!NN0.getNode())
960       return SDValue();
961
962     bool Replace1 = false;
963     SDValue N1 = Op.getOperand(1);
964     SDValue NN1;
965     if (N0 == N1)
966       NN1 = NN0;
967     else {
968       NN1 = PromoteOperand(N1, PVT, Replace1);
969       if (!NN1.getNode())
970         return SDValue();
971     }
972
973     AddToWorklist(NN0.getNode());
974     if (NN1.getNode())
975       AddToWorklist(NN1.getNode());
976
977     if (Replace0)
978       ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
979     if (Replace1)
980       ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
981
982     DEBUG(dbgs() << "\nPromoting ";
983           Op.getNode()->dump(&DAG));
984     SDLoc dl(Op);
985     return DAG.getNode(ISD::TRUNCATE, dl, VT,
986                        DAG.getNode(Opc, dl, PVT, NN0, NN1));
987   }
988   return SDValue();
989 }
990
991 /// PromoteIntShiftOp - Promote the specified integer shift operation if the
992 /// target indicates it is beneficial. e.g. On x86, it's usually better to
993 /// promote i16 operations to i32 since i16 instructions are longer.
994 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
995   if (!LegalOperations)
996     return SDValue();
997
998   EVT VT = Op.getValueType();
999   if (VT.isVector() || !VT.isInteger())
1000     return SDValue();
1001
1002   // If operation type is 'undesirable', e.g. i16 on x86, consider
1003   // promoting it.
1004   unsigned Opc = Op.getOpcode();
1005   if (TLI.isTypeDesirableForOp(Opc, VT))
1006     return SDValue();
1007
1008   EVT PVT = VT;
1009   // Consult target whether it is a good idea to promote this operation and
1010   // what's the right type to promote it to.
1011   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1012     assert(PVT != VT && "Don't know what type to promote to!");
1013
1014     bool Replace = false;
1015     SDValue N0 = Op.getOperand(0);
1016     if (Opc == ISD::SRA)
1017       N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
1018     else if (Opc == ISD::SRL)
1019       N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
1020     else
1021       N0 = PromoteOperand(N0, PVT, Replace);
1022     if (!N0.getNode())
1023       return SDValue();
1024
1025     AddToWorklist(N0.getNode());
1026     if (Replace)
1027       ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
1028
1029     DEBUG(dbgs() << "\nPromoting ";
1030           Op.getNode()->dump(&DAG));
1031     SDLoc dl(Op);
1032     return DAG.getNode(ISD::TRUNCATE, dl, VT,
1033                        DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
1034   }
1035   return SDValue();
1036 }
1037
1038 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
1039   if (!LegalOperations)
1040     return SDValue();
1041
1042   EVT VT = Op.getValueType();
1043   if (VT.isVector() || !VT.isInteger())
1044     return SDValue();
1045
1046   // If operation type is 'undesirable', e.g. i16 on x86, consider
1047   // promoting it.
1048   unsigned Opc = Op.getOpcode();
1049   if (TLI.isTypeDesirableForOp(Opc, VT))
1050     return SDValue();
1051
1052   EVT PVT = VT;
1053   // Consult target whether it is a good idea to promote this operation and
1054   // what's the right type to promote it to.
1055   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1056     assert(PVT != VT && "Don't know what type to promote to!");
1057     // fold (aext (aext x)) -> (aext x)
1058     // fold (aext (zext x)) -> (zext x)
1059     // fold (aext (sext x)) -> (sext x)
1060     DEBUG(dbgs() << "\nPromoting ";
1061           Op.getNode()->dump(&DAG));
1062     return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1063   }
1064   return SDValue();
1065 }
1066
1067 bool DAGCombiner::PromoteLoad(SDValue Op) {
1068   if (!LegalOperations)
1069     return false;
1070
1071   EVT VT = Op.getValueType();
1072   if (VT.isVector() || !VT.isInteger())
1073     return false;
1074
1075   // If operation type is 'undesirable', e.g. i16 on x86, consider
1076   // promoting it.
1077   unsigned Opc = Op.getOpcode();
1078   if (TLI.isTypeDesirableForOp(Opc, VT))
1079     return false;
1080
1081   EVT PVT = VT;
1082   // Consult target whether it is a good idea to promote this operation and
1083   // what's the right type to promote it to.
1084   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1085     assert(PVT != VT && "Don't know what type to promote to!");
1086
1087     SDLoc dl(Op);
1088     SDNode *N = Op.getNode();
1089     LoadSDNode *LD = cast<LoadSDNode>(N);
1090     EVT MemVT = LD->getMemoryVT();
1091     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1092       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
1093                                                   : ISD::EXTLOAD)
1094       : LD->getExtensionType();
1095     SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
1096                                    LD->getChain(), LD->getBasePtr(),
1097                                    MemVT, LD->getMemOperand());
1098     SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
1099
1100     DEBUG(dbgs() << "\nPromoting ";
1101           N->dump(&DAG);
1102           dbgs() << "\nTo: ";
1103           Result.getNode()->dump(&DAG);
1104           dbgs() << '\n');
1105     WorklistRemover DeadNodes(*this);
1106     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1107     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1108     deleteAndRecombine(N);
1109     AddToWorklist(Result.getNode());
1110     return true;
1111   }
1112   return false;
1113 }
1114
1115 /// \brief Recursively delete a node which has no uses and any operands for
1116 /// which it is the only use.
1117 ///
1118 /// Note that this both deletes the nodes and removes them from the worklist.
1119 /// It also adds any nodes who have had a user deleted to the worklist as they
1120 /// may now have only one use and subject to other combines.
1121 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) {
1122   if (!N->use_empty())
1123     return false;
1124
1125   SmallSetVector<SDNode *, 16> Nodes;
1126   Nodes.insert(N);
1127   do {
1128     N = Nodes.pop_back_val();
1129     if (!N)
1130       continue;
1131
1132     if (N->use_empty()) {
1133       for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1134         Nodes.insert(N->getOperand(i).getNode());
1135
1136       removeFromWorklist(N);
1137       DAG.DeleteNode(N);
1138     } else {
1139       AddToWorklist(N);
1140     }
1141   } while (!Nodes.empty());
1142   return true;
1143 }
1144
1145 //===----------------------------------------------------------------------===//
1146 //  Main DAG Combiner implementation
1147 //===----------------------------------------------------------------------===//
1148
1149 void DAGCombiner::Run(CombineLevel AtLevel) {
1150   // set the instance variables, so that the various visit routines may use it.
1151   Level = AtLevel;
1152   LegalOperations = Level >= AfterLegalizeVectorOps;
1153   LegalTypes = Level >= AfterLegalizeTypes;
1154
1155   // Add all the dag nodes to the worklist.
1156   for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
1157        E = DAG.allnodes_end(); I != E; ++I)
1158     AddToWorklist(I);
1159
1160   // Create a dummy node (which is not added to allnodes), that adds a reference
1161   // to the root node, preventing it from being deleted, and tracking any
1162   // changes of the root.
1163   HandleSDNode Dummy(DAG.getRoot());
1164
1165   // while the worklist isn't empty, find a node and
1166   // try and combine it.
1167   while (!WorklistMap.empty()) {
1168     SDNode *N;
1169     // The Worklist holds the SDNodes in order, but it may contain null entries.
1170     do {
1171       N = Worklist.pop_back_val();
1172     } while (!N);
1173
1174     bool GoodWorklistEntry = WorklistMap.erase(N);
1175     (void)GoodWorklistEntry;
1176     assert(GoodWorklistEntry &&
1177            "Found a worklist entry without a corresponding map entry!");
1178
1179     // If N has no uses, it is dead.  Make sure to revisit all N's operands once
1180     // N is deleted from the DAG, since they too may now be dead or may have a
1181     // reduced number of uses, allowing other xforms.
1182     if (recursivelyDeleteUnusedNodes(N))
1183       continue;
1184
1185     WorklistRemover DeadNodes(*this);
1186
1187     // If this combine is running after legalizing the DAG, re-legalize any
1188     // nodes pulled off the worklist.
1189     if (Level == AfterLegalizeDAG) {
1190       SmallSetVector<SDNode *, 16> UpdatedNodes;
1191       bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes);
1192
1193       for (SDNode *LN : UpdatedNodes) {
1194         AddToWorklist(LN);
1195         AddUsersToWorklist(LN);
1196       }
1197       if (!NIsValid)
1198         continue;
1199     }
1200
1201     DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG));
1202
1203     // Add any operands of the new node which have not yet been combined to the
1204     // worklist as well. Because the worklist uniques things already, this
1205     // won't repeatedly process the same operand.
1206     CombinedNodes.insert(N);
1207     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1208       if (!CombinedNodes.count(N->getOperand(i).getNode()))
1209         AddToWorklist(N->getOperand(i).getNode());
1210
1211     SDValue RV = combine(N);
1212
1213     if (!RV.getNode())
1214       continue;
1215
1216     ++NodesCombined;
1217
1218     // If we get back the same node we passed in, rather than a new node or
1219     // zero, we know that the node must have defined multiple values and
1220     // CombineTo was used.  Since CombineTo takes care of the worklist
1221     // mechanics for us, we have no work to do in this case.
1222     if (RV.getNode() == N)
1223       continue;
1224
1225     assert(N->getOpcode() != ISD::DELETED_NODE &&
1226            RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1227            "Node was deleted but visit returned new node!");
1228
1229     DEBUG(dbgs() << " ... into: ";
1230           RV.getNode()->dump(&DAG));
1231
1232     // Transfer debug value.
1233     DAG.TransferDbgValues(SDValue(N, 0), RV);
1234     if (N->getNumValues() == RV.getNode()->getNumValues())
1235       DAG.ReplaceAllUsesWith(N, RV.getNode());
1236     else {
1237       assert(N->getValueType(0) == RV.getValueType() &&
1238              N->getNumValues() == 1 && "Type mismatch");
1239       SDValue OpV = RV;
1240       DAG.ReplaceAllUsesWith(N, &OpV);
1241     }
1242
1243     // Push the new node and any users onto the worklist
1244     AddToWorklist(RV.getNode());
1245     AddUsersToWorklist(RV.getNode());
1246
1247     // Finally, if the node is now dead, remove it from the graph.  The node
1248     // may not be dead if the replacement process recursively simplified to
1249     // something else needing this node. This will also take care of adding any
1250     // operands which have lost a user to the worklist.
1251     recursivelyDeleteUnusedNodes(N);
1252   }
1253
1254   // If the root changed (e.g. it was a dead load, update the root).
1255   DAG.setRoot(Dummy.getValue());
1256   DAG.RemoveDeadNodes();
1257 }
1258
1259 SDValue DAGCombiner::visit(SDNode *N) {
1260   switch (N->getOpcode()) {
1261   default: break;
1262   case ISD::TokenFactor:        return visitTokenFactor(N);
1263   case ISD::MERGE_VALUES:       return visitMERGE_VALUES(N);
1264   case ISD::ADD:                return visitADD(N);
1265   case ISD::SUB:                return visitSUB(N);
1266   case ISD::ADDC:               return visitADDC(N);
1267   case ISD::SUBC:               return visitSUBC(N);
1268   case ISD::ADDE:               return visitADDE(N);
1269   case ISD::SUBE:               return visitSUBE(N);
1270   case ISD::MUL:                return visitMUL(N);
1271   case ISD::SDIV:               return visitSDIV(N);
1272   case ISD::UDIV:               return visitUDIV(N);
1273   case ISD::SREM:               return visitSREM(N);
1274   case ISD::UREM:               return visitUREM(N);
1275   case ISD::MULHU:              return visitMULHU(N);
1276   case ISD::MULHS:              return visitMULHS(N);
1277   case ISD::SMUL_LOHI:          return visitSMUL_LOHI(N);
1278   case ISD::UMUL_LOHI:          return visitUMUL_LOHI(N);
1279   case ISD::SMULO:              return visitSMULO(N);
1280   case ISD::UMULO:              return visitUMULO(N);
1281   case ISD::SDIVREM:            return visitSDIVREM(N);
1282   case ISD::UDIVREM:            return visitUDIVREM(N);
1283   case ISD::AND:                return visitAND(N);
1284   case ISD::OR:                 return visitOR(N);
1285   case ISD::XOR:                return visitXOR(N);
1286   case ISD::SHL:                return visitSHL(N);
1287   case ISD::SRA:                return visitSRA(N);
1288   case ISD::SRL:                return visitSRL(N);
1289   case ISD::ROTR:
1290   case ISD::ROTL:               return visitRotate(N);
1291   case ISD::CTLZ:               return visitCTLZ(N);
1292   case ISD::CTLZ_ZERO_UNDEF:    return visitCTLZ_ZERO_UNDEF(N);
1293   case ISD::CTTZ:               return visitCTTZ(N);
1294   case ISD::CTTZ_ZERO_UNDEF:    return visitCTTZ_ZERO_UNDEF(N);
1295   case ISD::CTPOP:              return visitCTPOP(N);
1296   case ISD::SELECT:             return visitSELECT(N);
1297   case ISD::VSELECT:            return visitVSELECT(N);
1298   case ISD::SELECT_CC:          return visitSELECT_CC(N);
1299   case ISD::SETCC:              return visitSETCC(N);
1300   case ISD::SIGN_EXTEND:        return visitSIGN_EXTEND(N);
1301   case ISD::ZERO_EXTEND:        return visitZERO_EXTEND(N);
1302   case ISD::ANY_EXTEND:         return visitANY_EXTEND(N);
1303   case ISD::SIGN_EXTEND_INREG:  return visitSIGN_EXTEND_INREG(N);
1304   case ISD::TRUNCATE:           return visitTRUNCATE(N);
1305   case ISD::BITCAST:            return visitBITCAST(N);
1306   case ISD::BUILD_PAIR:         return visitBUILD_PAIR(N);
1307   case ISD::FADD:               return visitFADD(N);
1308   case ISD::FSUB:               return visitFSUB(N);
1309   case ISD::FMUL:               return visitFMUL(N);
1310   case ISD::FMA:                return visitFMA(N);
1311   case ISD::FDIV:               return visitFDIV(N);
1312   case ISD::FREM:               return visitFREM(N);
1313   case ISD::FCOPYSIGN:          return visitFCOPYSIGN(N);
1314   case ISD::SINT_TO_FP:         return visitSINT_TO_FP(N);
1315   case ISD::UINT_TO_FP:         return visitUINT_TO_FP(N);
1316   case ISD::FP_TO_SINT:         return visitFP_TO_SINT(N);
1317   case ISD::FP_TO_UINT:         return visitFP_TO_UINT(N);
1318   case ISD::FP_ROUND:           return visitFP_ROUND(N);
1319   case ISD::FP_ROUND_INREG:     return visitFP_ROUND_INREG(N);
1320   case ISD::FP_EXTEND:          return visitFP_EXTEND(N);
1321   case ISD::FNEG:               return visitFNEG(N);
1322   case ISD::FABS:               return visitFABS(N);
1323   case ISD::FFLOOR:             return visitFFLOOR(N);
1324   case ISD::FCEIL:              return visitFCEIL(N);
1325   case ISD::FTRUNC:             return visitFTRUNC(N);
1326   case ISD::BRCOND:             return visitBRCOND(N);
1327   case ISD::BR_CC:              return visitBR_CC(N);
1328   case ISD::LOAD:               return visitLOAD(N);
1329   case ISD::STORE:              return visitSTORE(N);
1330   case ISD::INSERT_VECTOR_ELT:  return visitINSERT_VECTOR_ELT(N);
1331   case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1332   case ISD::BUILD_VECTOR:       return visitBUILD_VECTOR(N);
1333   case ISD::CONCAT_VECTORS:     return visitCONCAT_VECTORS(N);
1334   case ISD::EXTRACT_SUBVECTOR:  return visitEXTRACT_SUBVECTOR(N);
1335   case ISD::VECTOR_SHUFFLE:     return visitVECTOR_SHUFFLE(N);
1336   case ISD::INSERT_SUBVECTOR:   return visitINSERT_SUBVECTOR(N);
1337   }
1338   return SDValue();
1339 }
1340
1341 SDValue DAGCombiner::combine(SDNode *N) {
1342   SDValue RV = visit(N);
1343
1344   // If nothing happened, try a target-specific DAG combine.
1345   if (!RV.getNode()) {
1346     assert(N->getOpcode() != ISD::DELETED_NODE &&
1347            "Node was deleted but visit returned NULL!");
1348
1349     if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1350         TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1351
1352       // Expose the DAG combiner to the target combiner impls.
1353       TargetLowering::DAGCombinerInfo
1354         DagCombineInfo(DAG, Level, false, this);
1355
1356       RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1357     }
1358   }
1359
1360   // If nothing happened still, try promoting the operation.
1361   if (!RV.getNode()) {
1362     switch (N->getOpcode()) {
1363     default: break;
1364     case ISD::ADD:
1365     case ISD::SUB:
1366     case ISD::MUL:
1367     case ISD::AND:
1368     case ISD::OR:
1369     case ISD::XOR:
1370       RV = PromoteIntBinOp(SDValue(N, 0));
1371       break;
1372     case ISD::SHL:
1373     case ISD::SRA:
1374     case ISD::SRL:
1375       RV = PromoteIntShiftOp(SDValue(N, 0));
1376       break;
1377     case ISD::SIGN_EXTEND:
1378     case ISD::ZERO_EXTEND:
1379     case ISD::ANY_EXTEND:
1380       RV = PromoteExtend(SDValue(N, 0));
1381       break;
1382     case ISD::LOAD:
1383       if (PromoteLoad(SDValue(N, 0)))
1384         RV = SDValue(N, 0);
1385       break;
1386     }
1387   }
1388
1389   // If N is a commutative binary node, try commuting it to enable more
1390   // sdisel CSE.
1391   if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1392       N->getNumValues() == 1) {
1393     SDValue N0 = N->getOperand(0);
1394     SDValue N1 = N->getOperand(1);
1395
1396     // Constant operands are canonicalized to RHS.
1397     if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1398       SDValue Ops[] = {N1, N0};
1399       SDNode *CSENode;
1400       if (const BinaryWithFlagsSDNode *BinNode =
1401               dyn_cast<BinaryWithFlagsSDNode>(N)) {
1402         CSENode = DAG.getNodeIfExists(
1403             N->getOpcode(), N->getVTList(), Ops, BinNode->hasNoUnsignedWrap(),
1404             BinNode->hasNoSignedWrap(), BinNode->isExact());
1405       } else {
1406         CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops);
1407       }
1408       if (CSENode)
1409         return SDValue(CSENode, 0);
1410     }
1411   }
1412
1413   return RV;
1414 }
1415
1416 /// getInputChainForNode - Given a node, return its input chain if it has one,
1417 /// otherwise return a null sd operand.
1418 static SDValue getInputChainForNode(SDNode *N) {
1419   if (unsigned NumOps = N->getNumOperands()) {
1420     if (N->getOperand(0).getValueType() == MVT::Other)
1421       return N->getOperand(0);
1422     if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1423       return N->getOperand(NumOps-1);
1424     for (unsigned i = 1; i < NumOps-1; ++i)
1425       if (N->getOperand(i).getValueType() == MVT::Other)
1426         return N->getOperand(i);
1427   }
1428   return SDValue();
1429 }
1430
1431 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1432   // If N has two operands, where one has an input chain equal to the other,
1433   // the 'other' chain is redundant.
1434   if (N->getNumOperands() == 2) {
1435     if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1436       return N->getOperand(0);
1437     if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1438       return N->getOperand(1);
1439   }
1440
1441   SmallVector<SDNode *, 8> TFs;     // List of token factors to visit.
1442   SmallVector<SDValue, 8> Ops;    // Ops for replacing token factor.
1443   SmallPtrSet<SDNode*, 16> SeenOps;
1444   bool Changed = false;             // If we should replace this token factor.
1445
1446   // Start out with this token factor.
1447   TFs.push_back(N);
1448
1449   // Iterate through token factors.  The TFs grows when new token factors are
1450   // encountered.
1451   for (unsigned i = 0; i < TFs.size(); ++i) {
1452     SDNode *TF = TFs[i];
1453
1454     // Check each of the operands.
1455     for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
1456       SDValue Op = TF->getOperand(i);
1457
1458       switch (Op.getOpcode()) {
1459       case ISD::EntryToken:
1460         // Entry tokens don't need to be added to the list. They are
1461         // rededundant.
1462         Changed = true;
1463         break;
1464
1465       case ISD::TokenFactor:
1466         if (Op.hasOneUse() &&
1467             std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1468           // Queue up for processing.
1469           TFs.push_back(Op.getNode());
1470           // Clean up in case the token factor is removed.
1471           AddToWorklist(Op.getNode());
1472           Changed = true;
1473           break;
1474         }
1475         // Fall thru
1476
1477       default:
1478         // Only add if it isn't already in the list.
1479         if (SeenOps.insert(Op.getNode()))
1480           Ops.push_back(Op);
1481         else
1482           Changed = true;
1483         break;
1484       }
1485     }
1486   }
1487
1488   SDValue Result;
1489
1490   // If we've change things around then replace token factor.
1491   if (Changed) {
1492     if (Ops.empty()) {
1493       // The entry token is the only possible outcome.
1494       Result = DAG.getEntryNode();
1495     } else {
1496       // New and improved token factor.
1497       Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
1498     }
1499
1500     // Don't add users to work list.
1501     return CombineTo(N, Result, false);
1502   }
1503
1504   return Result;
1505 }
1506
1507 /// MERGE_VALUES can always be eliminated.
1508 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1509   WorklistRemover DeadNodes(*this);
1510   // Replacing results may cause a different MERGE_VALUES to suddenly
1511   // be CSE'd with N, and carry its uses with it. Iterate until no
1512   // uses remain, to ensure that the node can be safely deleted.
1513   // First add the users of this node to the work list so that they
1514   // can be tried again once they have new operands.
1515   AddUsersToWorklist(N);
1516   do {
1517     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1518       DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1519   } while (!N->use_empty());
1520   deleteAndRecombine(N);
1521   return SDValue(N, 0);   // Return N so it doesn't get rechecked!
1522 }
1523
1524 static
1525 SDValue combineShlAddConstant(SDLoc DL, SDValue N0, SDValue N1,
1526                               SelectionDAG &DAG) {
1527   EVT VT = N0.getValueType();
1528   SDValue N00 = N0.getOperand(0);
1529   SDValue N01 = N0.getOperand(1);
1530   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N01);
1531
1532   if (N01C && N00.getOpcode() == ISD::ADD && N00.getNode()->hasOneUse() &&
1533       isa<ConstantSDNode>(N00.getOperand(1))) {
1534     // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1535     N0 = DAG.getNode(ISD::ADD, SDLoc(N0), VT,
1536                      DAG.getNode(ISD::SHL, SDLoc(N00), VT,
1537                                  N00.getOperand(0), N01),
1538                      DAG.getNode(ISD::SHL, SDLoc(N01), VT,
1539                                  N00.getOperand(1), N01));
1540     return DAG.getNode(ISD::ADD, DL, VT, N0, N1);
1541   }
1542
1543   return SDValue();
1544 }
1545
1546 SDValue DAGCombiner::visitADD(SDNode *N) {
1547   SDValue N0 = N->getOperand(0);
1548   SDValue N1 = N->getOperand(1);
1549   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1550   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1551   EVT VT = N0.getValueType();
1552
1553   // fold vector ops
1554   if (VT.isVector()) {
1555     SDValue FoldedVOp = SimplifyVBinOp(N);
1556     if (FoldedVOp.getNode()) return FoldedVOp;
1557
1558     // fold (add x, 0) -> x, vector edition
1559     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1560       return N0;
1561     if (ISD::isBuildVectorAllZeros(N0.getNode()))
1562       return N1;
1563   }
1564
1565   // fold (add x, undef) -> undef
1566   if (N0.getOpcode() == ISD::UNDEF)
1567     return N0;
1568   if (N1.getOpcode() == ISD::UNDEF)
1569     return N1;
1570   // fold (add c1, c2) -> c1+c2
1571   if (N0C && N1C)
1572     return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C);
1573   // canonicalize constant to RHS
1574   if (N0C && !N1C)
1575     return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
1576   // fold (add x, 0) -> x
1577   if (N1C && N1C->isNullValue())
1578     return N0;
1579   // fold (add Sym, c) -> Sym+c
1580   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1581     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1582         GA->getOpcode() == ISD::GlobalAddress)
1583       return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1584                                   GA->getOffset() +
1585                                     (uint64_t)N1C->getSExtValue());
1586   // fold ((c1-A)+c2) -> (c1+c2)-A
1587   if (N1C && N0.getOpcode() == ISD::SUB)
1588     if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
1589       return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1590                          DAG.getConstant(N1C->getAPIntValue()+
1591                                          N0C->getAPIntValue(), VT),
1592                          N0.getOperand(1));
1593   // reassociate add
1594   SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1);
1595   if (RADD.getNode())
1596     return RADD;
1597   // fold ((0-A) + B) -> B-A
1598   if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
1599       cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
1600     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
1601   // fold (A + (0-B)) -> A-B
1602   if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1603       cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
1604     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
1605   // fold (A+(B-A)) -> B
1606   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1607     return N1.getOperand(0);
1608   // fold ((B-A)+A) -> B
1609   if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1610     return N0.getOperand(0);
1611   // fold (A+(B-(A+C))) to (B-C)
1612   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1613       N0 == N1.getOperand(1).getOperand(0))
1614     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1615                        N1.getOperand(1).getOperand(1));
1616   // fold (A+(B-(C+A))) to (B-C)
1617   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1618       N0 == N1.getOperand(1).getOperand(1))
1619     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1620                        N1.getOperand(1).getOperand(0));
1621   // fold (A+((B-A)+or-C)) to (B+or-C)
1622   if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1623       N1.getOperand(0).getOpcode() == ISD::SUB &&
1624       N0 == N1.getOperand(0).getOperand(1))
1625     return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
1626                        N1.getOperand(0).getOperand(0), N1.getOperand(1));
1627
1628   // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1629   if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1630     SDValue N00 = N0.getOperand(0);
1631     SDValue N01 = N0.getOperand(1);
1632     SDValue N10 = N1.getOperand(0);
1633     SDValue N11 = N1.getOperand(1);
1634
1635     if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1636       return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1637                          DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1638                          DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1639   }
1640
1641   if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1642     return SDValue(N, 0);
1643
1644   // fold (a+b) -> (a|b) iff a and b share no bits.
1645   if (VT.isInteger() && !VT.isVector()) {
1646     APInt LHSZero, LHSOne;
1647     APInt RHSZero, RHSOne;
1648     DAG.computeKnownBits(N0, LHSZero, LHSOne);
1649
1650     if (LHSZero.getBoolValue()) {
1651       DAG.computeKnownBits(N1, RHSZero, RHSOne);
1652
1653       // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1654       // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1655       if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){
1656         if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT))
1657           return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1658       }
1659     }
1660   }
1661
1662   // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1663   if (N0.getOpcode() == ISD::SHL && N0.getNode()->hasOneUse()) {
1664     SDValue Result = combineShlAddConstant(SDLoc(N), N0, N1, DAG);
1665     if (Result.getNode()) return Result;
1666   }
1667   if (N1.getOpcode() == ISD::SHL && N1.getNode()->hasOneUse()) {
1668     SDValue Result = combineShlAddConstant(SDLoc(N), N1, N0, DAG);
1669     if (Result.getNode()) return Result;
1670   }
1671
1672   // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1673   if (N1.getOpcode() == ISD::SHL &&
1674       N1.getOperand(0).getOpcode() == ISD::SUB)
1675     if (ConstantSDNode *C =
1676           dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
1677       if (C->getAPIntValue() == 0)
1678         return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1679                            DAG.getNode(ISD::SHL, SDLoc(N), VT,
1680                                        N1.getOperand(0).getOperand(1),
1681                                        N1.getOperand(1)));
1682   if (N0.getOpcode() == ISD::SHL &&
1683       N0.getOperand(0).getOpcode() == ISD::SUB)
1684     if (ConstantSDNode *C =
1685           dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
1686       if (C->getAPIntValue() == 0)
1687         return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1688                            DAG.getNode(ISD::SHL, SDLoc(N), VT,
1689                                        N0.getOperand(0).getOperand(1),
1690                                        N0.getOperand(1)));
1691
1692   if (N1.getOpcode() == ISD::AND) {
1693     SDValue AndOp0 = N1.getOperand(0);
1694     ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1));
1695     unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1696     unsigned DestBits = VT.getScalarType().getSizeInBits();
1697
1698     // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1699     // and similar xforms where the inner op is either ~0 or 0.
1700     if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) {
1701       SDLoc DL(N);
1702       return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1703     }
1704   }
1705
1706   // add (sext i1), X -> sub X, (zext i1)
1707   if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1708       N0.getOperand(0).getValueType() == MVT::i1 &&
1709       !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1710     SDLoc DL(N);
1711     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1712     return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1713   }
1714
1715   return SDValue();
1716 }
1717
1718 SDValue DAGCombiner::visitADDC(SDNode *N) {
1719   SDValue N0 = N->getOperand(0);
1720   SDValue N1 = N->getOperand(1);
1721   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1722   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1723   EVT VT = N0.getValueType();
1724
1725   // If the flag result is dead, turn this into an ADD.
1726   if (!N->hasAnyUseOfValue(1))
1727     return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1728                      DAG.getNode(ISD::CARRY_FALSE,
1729                                  SDLoc(N), MVT::Glue));
1730
1731   // canonicalize constant to RHS.
1732   if (N0C && !N1C)
1733     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1734
1735   // fold (addc x, 0) -> x + no carry out
1736   if (N1C && N1C->isNullValue())
1737     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1738                                         SDLoc(N), MVT::Glue));
1739
1740   // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1741   APInt LHSZero, LHSOne;
1742   APInt RHSZero, RHSOne;
1743   DAG.computeKnownBits(N0, LHSZero, LHSOne);
1744
1745   if (LHSZero.getBoolValue()) {
1746     DAG.computeKnownBits(N1, RHSZero, RHSOne);
1747
1748     // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1749     // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1750     if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1751       return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1752                        DAG.getNode(ISD::CARRY_FALSE,
1753                                    SDLoc(N), MVT::Glue));
1754   }
1755
1756   return SDValue();
1757 }
1758
1759 SDValue DAGCombiner::visitADDE(SDNode *N) {
1760   SDValue N0 = N->getOperand(0);
1761   SDValue N1 = N->getOperand(1);
1762   SDValue CarryIn = N->getOperand(2);
1763   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1764   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1765
1766   // canonicalize constant to RHS
1767   if (N0C && !N1C)
1768     return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1769                        N1, N0, CarryIn);
1770
1771   // fold (adde x, y, false) -> (addc x, y)
1772   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1773     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1774
1775   return SDValue();
1776 }
1777
1778 // Since it may not be valid to emit a fold to zero for vector initializers
1779 // check if we can before folding.
1780 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
1781                              SelectionDAG &DAG,
1782                              bool LegalOperations, bool LegalTypes) {
1783   if (!VT.isVector())
1784     return DAG.getConstant(0, VT);
1785   if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1786     return DAG.getConstant(0, VT);
1787   return SDValue();
1788 }
1789
1790 SDValue DAGCombiner::visitSUB(SDNode *N) {
1791   SDValue N0 = N->getOperand(0);
1792   SDValue N1 = N->getOperand(1);
1793   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1794   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1795   ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr :
1796     dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1797   EVT VT = N0.getValueType();
1798
1799   // fold vector ops
1800   if (VT.isVector()) {
1801     SDValue FoldedVOp = SimplifyVBinOp(N);
1802     if (FoldedVOp.getNode()) return FoldedVOp;
1803
1804     // fold (sub x, 0) -> x, vector edition
1805     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1806       return N0;
1807   }
1808
1809   // fold (sub x, x) -> 0
1810   // FIXME: Refactor this and xor and other similar operations together.
1811   if (N0 == N1)
1812     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
1813   // fold (sub c1, c2) -> c1-c2
1814   if (N0C && N1C)
1815     return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C);
1816   // fold (sub x, c) -> (add x, -c)
1817   if (N1C)
1818     return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0,
1819                        DAG.getConstant(-N1C->getAPIntValue(), VT));
1820   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1821   if (N0C && N0C->isAllOnesValue())
1822     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
1823   // fold A-(A-B) -> B
1824   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1825     return N1.getOperand(1);
1826   // fold (A+B)-A -> B
1827   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1828     return N0.getOperand(1);
1829   // fold (A+B)-B -> A
1830   if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1831     return N0.getOperand(0);
1832   // fold C2-(A+C1) -> (C2-C1)-A
1833   if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1834     SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1835                                    VT);
1836     return DAG.getNode(ISD::SUB, SDLoc(N), VT, NewC,
1837                        N1.getOperand(0));
1838   }
1839   // fold ((A+(B+or-C))-B) -> A+or-C
1840   if (N0.getOpcode() == ISD::ADD &&
1841       (N0.getOperand(1).getOpcode() == ISD::SUB ||
1842        N0.getOperand(1).getOpcode() == ISD::ADD) &&
1843       N0.getOperand(1).getOperand(0) == N1)
1844     return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
1845                        N0.getOperand(0), N0.getOperand(1).getOperand(1));
1846   // fold ((A+(C+B))-B) -> A+C
1847   if (N0.getOpcode() == ISD::ADD &&
1848       N0.getOperand(1).getOpcode() == ISD::ADD &&
1849       N0.getOperand(1).getOperand(1) == N1)
1850     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1851                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1852   // fold ((A-(B-C))-C) -> A-B
1853   if (N0.getOpcode() == ISD::SUB &&
1854       N0.getOperand(1).getOpcode() == ISD::SUB &&
1855       N0.getOperand(1).getOperand(1) == N1)
1856     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1857                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1858
1859   // If either operand of a sub is undef, the result is undef
1860   if (N0.getOpcode() == ISD::UNDEF)
1861     return N0;
1862   if (N1.getOpcode() == ISD::UNDEF)
1863     return N1;
1864
1865   // If the relocation model supports it, consider symbol offsets.
1866   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1867     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1868       // fold (sub Sym, c) -> Sym-c
1869       if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1870         return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1871                                     GA->getOffset() -
1872                                       (uint64_t)N1C->getSExtValue());
1873       // fold (sub Sym+c1, Sym+c2) -> c1-c2
1874       if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1875         if (GA->getGlobal() == GB->getGlobal())
1876           return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1877                                  VT);
1878     }
1879
1880   return SDValue();
1881 }
1882
1883 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1884   SDValue N0 = N->getOperand(0);
1885   SDValue N1 = N->getOperand(1);
1886   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1887   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1888   EVT VT = N0.getValueType();
1889
1890   // If the flag result is dead, turn this into an SUB.
1891   if (!N->hasAnyUseOfValue(1))
1892     return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1893                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1894                                  MVT::Glue));
1895
1896   // fold (subc x, x) -> 0 + no borrow
1897   if (N0 == N1)
1898     return CombineTo(N, DAG.getConstant(0, VT),
1899                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1900                                  MVT::Glue));
1901
1902   // fold (subc x, 0) -> x + no borrow
1903   if (N1C && N1C->isNullValue())
1904     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1905                                         MVT::Glue));
1906
1907   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1908   if (N0C && N0C->isAllOnesValue())
1909     return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
1910                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1911                                  MVT::Glue));
1912
1913   return SDValue();
1914 }
1915
1916 SDValue DAGCombiner::visitSUBE(SDNode *N) {
1917   SDValue N0 = N->getOperand(0);
1918   SDValue N1 = N->getOperand(1);
1919   SDValue CarryIn = N->getOperand(2);
1920
1921   // fold (sube x, y, false) -> (subc x, y)
1922   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1923     return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
1924
1925   return SDValue();
1926 }
1927
1928 SDValue DAGCombiner::visitMUL(SDNode *N) {
1929   SDValue N0 = N->getOperand(0);
1930   SDValue N1 = N->getOperand(1);
1931   EVT VT = N0.getValueType();
1932
1933   // fold (mul x, undef) -> 0
1934   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1935     return DAG.getConstant(0, VT);
1936
1937   bool N0IsConst = false;
1938   bool N1IsConst = false;
1939   APInt ConstValue0, ConstValue1;
1940   // fold vector ops
1941   if (VT.isVector()) {
1942     SDValue FoldedVOp = SimplifyVBinOp(N);
1943     if (FoldedVOp.getNode()) return FoldedVOp;
1944
1945     N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
1946     N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
1947   } else {
1948     N0IsConst = dyn_cast<ConstantSDNode>(N0) != nullptr;
1949     ConstValue0 = N0IsConst ? (dyn_cast<ConstantSDNode>(N0))->getAPIntValue()
1950                             : APInt();
1951     N1IsConst = dyn_cast<ConstantSDNode>(N1) != nullptr;
1952     ConstValue1 = N1IsConst ? (dyn_cast<ConstantSDNode>(N1))->getAPIntValue()
1953                             : APInt();
1954   }
1955
1956   // fold (mul c1, c2) -> c1*c2
1957   if (N0IsConst && N1IsConst)
1958     return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0.getNode(), N1.getNode());
1959
1960   // canonicalize constant to RHS
1961   if (N0IsConst && !N1IsConst)
1962     return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
1963   // fold (mul x, 0) -> 0
1964   if (N1IsConst && ConstValue1 == 0)
1965     return N1;
1966   // We require a splat of the entire scalar bit width for non-contiguous
1967   // bit patterns.
1968   bool IsFullSplat =
1969     ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
1970   // fold (mul x, 1) -> x
1971   if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
1972     return N0;
1973   // fold (mul x, -1) -> 0-x
1974   if (N1IsConst && ConstValue1.isAllOnesValue())
1975     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1976                        DAG.getConstant(0, VT), N0);
1977   // fold (mul x, (1 << c)) -> x << c
1978   if (N1IsConst && ConstValue1.isPowerOf2() && IsFullSplat)
1979     return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1980                        DAG.getConstant(ConstValue1.logBase2(),
1981                                        getShiftAmountTy(N0.getValueType())));
1982   // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
1983   if (N1IsConst && (-ConstValue1).isPowerOf2() && IsFullSplat) {
1984     unsigned Log2Val = (-ConstValue1).logBase2();
1985     // FIXME: If the input is something that is easily negated (e.g. a
1986     // single-use add), we should put the negate there.
1987     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1988                        DAG.getConstant(0, VT),
1989                        DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1990                             DAG.getConstant(Log2Val,
1991                                       getShiftAmountTy(N0.getValueType()))));
1992   }
1993
1994   APInt Val;
1995   // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
1996   if (N1IsConst && N0.getOpcode() == ISD::SHL &&
1997       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1998                      isa<ConstantSDNode>(N0.getOperand(1)))) {
1999     SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
2000                              N1, N0.getOperand(1));
2001     AddToWorklist(C3.getNode());
2002     return DAG.getNode(ISD::MUL, SDLoc(N), VT,
2003                        N0.getOperand(0), C3);
2004   }
2005
2006   // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
2007   // use.
2008   {
2009     SDValue Sh(nullptr,0), Y(nullptr,0);
2010     // Check for both (mul (shl X, C), Y)  and  (mul Y, (shl X, C)).
2011     if (N0.getOpcode() == ISD::SHL &&
2012         (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2013                        isa<ConstantSDNode>(N0.getOperand(1))) &&
2014         N0.getNode()->hasOneUse()) {
2015       Sh = N0; Y = N1;
2016     } else if (N1.getOpcode() == ISD::SHL &&
2017                isa<ConstantSDNode>(N1.getOperand(1)) &&
2018                N1.getNode()->hasOneUse()) {
2019       Sh = N1; Y = N0;
2020     }
2021
2022     if (Sh.getNode()) {
2023       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2024                                 Sh.getOperand(0), Y);
2025       return DAG.getNode(ISD::SHL, SDLoc(N), VT,
2026                          Mul, Sh.getOperand(1));
2027     }
2028   }
2029
2030   // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
2031   if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
2032       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2033                      isa<ConstantSDNode>(N0.getOperand(1))))
2034     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
2035                        DAG.getNode(ISD::MUL, SDLoc(N0), VT,
2036                                    N0.getOperand(0), N1),
2037                        DAG.getNode(ISD::MUL, SDLoc(N1), VT,
2038                                    N0.getOperand(1), N1));
2039
2040   // reassociate mul
2041   SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1);
2042   if (RMUL.getNode())
2043     return RMUL;
2044
2045   return SDValue();
2046 }
2047
2048 SDValue DAGCombiner::visitSDIV(SDNode *N) {
2049   SDValue N0 = N->getOperand(0);
2050   SDValue N1 = N->getOperand(1);
2051   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2052   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2053   EVT VT = N->getValueType(0);
2054
2055   // fold vector ops
2056   if (VT.isVector()) {
2057     SDValue FoldedVOp = SimplifyVBinOp(N);
2058     if (FoldedVOp.getNode()) return FoldedVOp;
2059   }
2060
2061   // fold (sdiv c1, c2) -> c1/c2
2062   if (N0C && N1C && !N1C->isNullValue())
2063     return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C);
2064   // fold (sdiv X, 1) -> X
2065   if (N1C && N1C->getAPIntValue() == 1LL)
2066     return N0;
2067   // fold (sdiv X, -1) -> 0-X
2068   if (N1C && N1C->isAllOnesValue())
2069     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
2070                        DAG.getConstant(0, VT), N0);
2071   // If we know the sign bits of both operands are zero, strength reduce to a
2072   // udiv instead.  Handles (X&15) /s 4 -> X&15 >> 2
2073   if (!VT.isVector()) {
2074     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2075       return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
2076                          N0, N1);
2077   }
2078
2079   // fold (sdiv X, pow2) -> simple ops after legalize
2080   if (N1C && !N1C->isNullValue() && (N1C->getAPIntValue().isPowerOf2() ||
2081                                      (-N1C->getAPIntValue()).isPowerOf2())) {
2082     // If dividing by powers of two is cheap, then don't perform the following
2083     // fold.
2084     if (TLI.isPow2SDivCheap())
2085       return SDValue();
2086
2087     // Target-specific implementation of sdiv x, pow2.
2088     SDValue Res = BuildSDIVPow2(N);
2089     if (Res.getNode())
2090       return Res;
2091
2092     unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
2093
2094     // Splat the sign bit into the register
2095     SDValue SGN =
2096         DAG.getNode(ISD::SRA, SDLoc(N), VT, N0,
2097                     DAG.getConstant(VT.getScalarSizeInBits() - 1,
2098                                     getShiftAmountTy(N0.getValueType())));
2099     AddToWorklist(SGN.getNode());
2100
2101     // Add (N0 < 0) ? abs2 - 1 : 0;
2102     SDValue SRL =
2103         DAG.getNode(ISD::SRL, SDLoc(N), VT, SGN,
2104                     DAG.getConstant(VT.getScalarSizeInBits() - lg2,
2105                                     getShiftAmountTy(SGN.getValueType())));
2106     SDValue ADD = DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, SRL);
2107     AddToWorklist(SRL.getNode());
2108     AddToWorklist(ADD.getNode());    // Divide by pow2
2109     SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), VT, ADD,
2110                   DAG.getConstant(lg2, getShiftAmountTy(ADD.getValueType())));
2111
2112     // If we're dividing by a positive value, we're done.  Otherwise, we must
2113     // negate the result.
2114     if (N1C->getAPIntValue().isNonNegative())
2115       return SRA;
2116
2117     AddToWorklist(SRA.getNode());
2118     return DAG.getNode(ISD::SUB, SDLoc(N), VT, DAG.getConstant(0, VT), SRA);
2119   }
2120
2121   // if integer divide is expensive and we satisfy the requirements, emit an
2122   // alternate sequence.
2123   if (N1C && !TLI.isIntDivCheap()) {
2124     SDValue Op = BuildSDIV(N);
2125     if (Op.getNode()) return Op;
2126   }
2127
2128   // undef / X -> 0
2129   if (N0.getOpcode() == ISD::UNDEF)
2130     return DAG.getConstant(0, VT);
2131   // X / undef -> undef
2132   if (N1.getOpcode() == ISD::UNDEF)
2133     return N1;
2134
2135   return SDValue();
2136 }
2137
2138 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2139   SDValue N0 = N->getOperand(0);
2140   SDValue N1 = N->getOperand(1);
2141   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2142   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2143   EVT VT = N->getValueType(0);
2144
2145   // fold vector ops
2146   if (VT.isVector()) {
2147     SDValue FoldedVOp = SimplifyVBinOp(N);
2148     if (FoldedVOp.getNode()) return FoldedVOp;
2149   }
2150
2151   // fold (udiv c1, c2) -> c1/c2
2152   if (N0C && N1C && !N1C->isNullValue())
2153     return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C);
2154   // fold (udiv x, (1 << c)) -> x >>u c
2155   if (N1C && N1C->getAPIntValue().isPowerOf2())
2156     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0,
2157                        DAG.getConstant(N1C->getAPIntValue().logBase2(),
2158                                        getShiftAmountTy(N0.getValueType())));
2159   // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2160   if (N1.getOpcode() == ISD::SHL) {
2161     if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2162       if (SHC->getAPIntValue().isPowerOf2()) {
2163         EVT ADDVT = N1.getOperand(1).getValueType();
2164         SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N), ADDVT,
2165                                   N1.getOperand(1),
2166                                   DAG.getConstant(SHC->getAPIntValue()
2167                                                                   .logBase2(),
2168                                                   ADDVT));
2169         AddToWorklist(Add.getNode());
2170         return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, Add);
2171       }
2172     }
2173   }
2174   // fold (udiv x, c) -> alternate
2175   if (N1C && !TLI.isIntDivCheap()) {
2176     SDValue Op = BuildUDIV(N);
2177     if (Op.getNode()) return Op;
2178   }
2179
2180   // undef / X -> 0
2181   if (N0.getOpcode() == ISD::UNDEF)
2182     return DAG.getConstant(0, VT);
2183   // X / undef -> undef
2184   if (N1.getOpcode() == ISD::UNDEF)
2185     return N1;
2186
2187   return SDValue();
2188 }
2189
2190 SDValue DAGCombiner::visitSREM(SDNode *N) {
2191   SDValue N0 = N->getOperand(0);
2192   SDValue N1 = N->getOperand(1);
2193   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2194   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2195   EVT VT = N->getValueType(0);
2196
2197   // fold (srem c1, c2) -> c1%c2
2198   if (N0C && N1C && !N1C->isNullValue())
2199     return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C);
2200   // If we know the sign bits of both operands are zero, strength reduce to a
2201   // urem instead.  Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2202   if (!VT.isVector()) {
2203     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2204       return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
2205   }
2206
2207   // If X/C can be simplified by the division-by-constant logic, lower
2208   // X%C to the equivalent of X-X/C*C.
2209   if (N1C && !N1C->isNullValue()) {
2210     SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
2211     AddToWorklist(Div.getNode());
2212     SDValue OptimizedDiv = combine(Div.getNode());
2213     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2214       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2215                                 OptimizedDiv, N1);
2216       SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2217       AddToWorklist(Mul.getNode());
2218       return Sub;
2219     }
2220   }
2221
2222   // undef % X -> 0
2223   if (N0.getOpcode() == ISD::UNDEF)
2224     return DAG.getConstant(0, VT);
2225   // X % undef -> undef
2226   if (N1.getOpcode() == ISD::UNDEF)
2227     return N1;
2228
2229   return SDValue();
2230 }
2231
2232 SDValue DAGCombiner::visitUREM(SDNode *N) {
2233   SDValue N0 = N->getOperand(0);
2234   SDValue N1 = N->getOperand(1);
2235   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2236   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2237   EVT VT = N->getValueType(0);
2238
2239   // fold (urem c1, c2) -> c1%c2
2240   if (N0C && N1C && !N1C->isNullValue())
2241     return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C);
2242   // fold (urem x, pow2) -> (and x, pow2-1)
2243   if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
2244     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0,
2245                        DAG.getConstant(N1C->getAPIntValue()-1,VT));
2246   // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2247   if (N1.getOpcode() == ISD::SHL) {
2248     if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2249       if (SHC->getAPIntValue().isPowerOf2()) {
2250         SDValue Add =
2251           DAG.getNode(ISD::ADD, SDLoc(N), VT, N1,
2252                  DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
2253                                  VT));
2254         AddToWorklist(Add.getNode());
2255         return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, Add);
2256       }
2257     }
2258   }
2259
2260   // If X/C can be simplified by the division-by-constant logic, lower
2261   // X%C to the equivalent of X-X/C*C.
2262   if (N1C && !N1C->isNullValue()) {
2263     SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
2264     AddToWorklist(Div.getNode());
2265     SDValue OptimizedDiv = combine(Div.getNode());
2266     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2267       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2268                                 OptimizedDiv, N1);
2269       SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2270       AddToWorklist(Mul.getNode());
2271       return Sub;
2272     }
2273   }
2274
2275   // undef % X -> 0
2276   if (N0.getOpcode() == ISD::UNDEF)
2277     return DAG.getConstant(0, VT);
2278   // X % undef -> undef
2279   if (N1.getOpcode() == ISD::UNDEF)
2280     return N1;
2281
2282   return SDValue();
2283 }
2284
2285 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2286   SDValue N0 = N->getOperand(0);
2287   SDValue N1 = N->getOperand(1);
2288   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2289   EVT VT = N->getValueType(0);
2290   SDLoc DL(N);
2291
2292   // fold (mulhs x, 0) -> 0
2293   if (N1C && N1C->isNullValue())
2294     return N1;
2295   // fold (mulhs x, 1) -> (sra x, size(x)-1)
2296   if (N1C && N1C->getAPIntValue() == 1)
2297     return DAG.getNode(ISD::SRA, SDLoc(N), N0.getValueType(), N0,
2298                        DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2299                                        getShiftAmountTy(N0.getValueType())));
2300   // fold (mulhs x, undef) -> 0
2301   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2302     return DAG.getConstant(0, VT);
2303
2304   // If the type twice as wide is legal, transform the mulhs to a wider multiply
2305   // plus a shift.
2306   if (VT.isSimple() && !VT.isVector()) {
2307     MVT Simple = VT.getSimpleVT();
2308     unsigned SimpleSize = Simple.getSizeInBits();
2309     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2310     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2311       N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2312       N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2313       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2314       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2315             DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2316       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2317     }
2318   }
2319
2320   return SDValue();
2321 }
2322
2323 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2324   SDValue N0 = N->getOperand(0);
2325   SDValue N1 = N->getOperand(1);
2326   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2327   EVT VT = N->getValueType(0);
2328   SDLoc DL(N);
2329
2330   // fold (mulhu x, 0) -> 0
2331   if (N1C && N1C->isNullValue())
2332     return N1;
2333   // fold (mulhu x, 1) -> 0
2334   if (N1C && N1C->getAPIntValue() == 1)
2335     return DAG.getConstant(0, N0.getValueType());
2336   // fold (mulhu x, undef) -> 0
2337   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2338     return DAG.getConstant(0, VT);
2339
2340   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2341   // plus a shift.
2342   if (VT.isSimple() && !VT.isVector()) {
2343     MVT Simple = VT.getSimpleVT();
2344     unsigned SimpleSize = Simple.getSizeInBits();
2345     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2346     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2347       N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2348       N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2349       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2350       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2351             DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2352       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2353     }
2354   }
2355
2356   return SDValue();
2357 }
2358
2359 /// SimplifyNodeWithTwoResults - Perform optimizations common to nodes that
2360 /// compute two values. LoOp and HiOp give the opcodes for the two computations
2361 /// that are being performed. Return true if a simplification was made.
2362 ///
2363 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2364                                                 unsigned HiOp) {
2365   // If the high half is not needed, just compute the low half.
2366   bool HiExists = N->hasAnyUseOfValue(1);
2367   if (!HiExists &&
2368       (!LegalOperations ||
2369        TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
2370     SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2371     return CombineTo(N, Res, Res);
2372   }
2373
2374   // If the low half is not needed, just compute the high half.
2375   bool LoExists = N->hasAnyUseOfValue(0);
2376   if (!LoExists &&
2377       (!LegalOperations ||
2378        TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2379     SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2380     return CombineTo(N, Res, Res);
2381   }
2382
2383   // If both halves are used, return as it is.
2384   if (LoExists && HiExists)
2385     return SDValue();
2386
2387   // If the two computed results can be simplified separately, separate them.
2388   if (LoExists) {
2389     SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2390     AddToWorklist(Lo.getNode());
2391     SDValue LoOpt = combine(Lo.getNode());
2392     if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2393         (!LegalOperations ||
2394          TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2395       return CombineTo(N, LoOpt, LoOpt);
2396   }
2397
2398   if (HiExists) {
2399     SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2400     AddToWorklist(Hi.getNode());
2401     SDValue HiOpt = combine(Hi.getNode());
2402     if (HiOpt.getNode() && HiOpt != Hi &&
2403         (!LegalOperations ||
2404          TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2405       return CombineTo(N, HiOpt, HiOpt);
2406   }
2407
2408   return SDValue();
2409 }
2410
2411 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2412   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
2413   if (Res.getNode()) return Res;
2414
2415   EVT VT = N->getValueType(0);
2416   SDLoc DL(N);
2417
2418   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2419   // plus a shift.
2420   if (VT.isSimple() && !VT.isVector()) {
2421     MVT Simple = VT.getSimpleVT();
2422     unsigned SimpleSize = Simple.getSizeInBits();
2423     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2424     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2425       SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2426       SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2427       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2428       // Compute the high part as N1.
2429       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2430             DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2431       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2432       // Compute the low part as N0.
2433       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2434       return CombineTo(N, Lo, Hi);
2435     }
2436   }
2437
2438   return SDValue();
2439 }
2440
2441 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2442   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
2443   if (Res.getNode()) return Res;
2444
2445   EVT VT = N->getValueType(0);
2446   SDLoc DL(N);
2447
2448   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2449   // plus a shift.
2450   if (VT.isSimple() && !VT.isVector()) {
2451     MVT Simple = VT.getSimpleVT();
2452     unsigned SimpleSize = Simple.getSizeInBits();
2453     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2454     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2455       SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2456       SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2457       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2458       // Compute the high part as N1.
2459       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2460             DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2461       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2462       // Compute the low part as N0.
2463       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2464       return CombineTo(N, Lo, Hi);
2465     }
2466   }
2467
2468   return SDValue();
2469 }
2470
2471 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2472   // (smulo x, 2) -> (saddo x, x)
2473   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2474     if (C2->getAPIntValue() == 2)
2475       return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2476                          N->getOperand(0), N->getOperand(0));
2477
2478   return SDValue();
2479 }
2480
2481 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2482   // (umulo x, 2) -> (uaddo x, x)
2483   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2484     if (C2->getAPIntValue() == 2)
2485       return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2486                          N->getOperand(0), N->getOperand(0));
2487
2488   return SDValue();
2489 }
2490
2491 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2492   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
2493   if (Res.getNode()) return Res;
2494
2495   return SDValue();
2496 }
2497
2498 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2499   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
2500   if (Res.getNode()) return Res;
2501
2502   return SDValue();
2503 }
2504
2505 /// SimplifyBinOpWithSameOpcodeHands - If this is a binary operator with
2506 /// two operands of the same opcode, try to simplify it.
2507 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2508   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2509   EVT VT = N0.getValueType();
2510   assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2511
2512   // Bail early if none of these transforms apply.
2513   if (N0.getNode()->getNumOperands() == 0) return SDValue();
2514
2515   // For each of OP in AND/OR/XOR:
2516   // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2517   // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2518   // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2519   // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2520   //
2521   // do not sink logical op inside of a vector extend, since it may combine
2522   // into a vsetcc.
2523   EVT Op0VT = N0.getOperand(0).getValueType();
2524   if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2525        N0.getOpcode() == ISD::SIGN_EXTEND ||
2526        // Avoid infinite looping with PromoteIntBinOp.
2527        (N0.getOpcode() == ISD::ANY_EXTEND &&
2528         (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2529        (N0.getOpcode() == ISD::TRUNCATE &&
2530         (!TLI.isZExtFree(VT, Op0VT) ||
2531          !TLI.isTruncateFree(Op0VT, VT)) &&
2532         TLI.isTypeLegal(Op0VT))) &&
2533       !VT.isVector() &&
2534       Op0VT == N1.getOperand(0).getValueType() &&
2535       (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2536     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2537                                  N0.getOperand(0).getValueType(),
2538                                  N0.getOperand(0), N1.getOperand(0));
2539     AddToWorklist(ORNode.getNode());
2540     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2541   }
2542
2543   // For each of OP in SHL/SRL/SRA/AND...
2544   //   fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2545   //   fold (or  (OP x, z), (OP y, z)) -> (OP (or  x, y), z)
2546   //   fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2547   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2548        N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2549       N0.getOperand(1) == N1.getOperand(1)) {
2550     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2551                                  N0.getOperand(0).getValueType(),
2552                                  N0.getOperand(0), N1.getOperand(0));
2553     AddToWorklist(ORNode.getNode());
2554     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2555                        ORNode, N0.getOperand(1));
2556   }
2557
2558   // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2559   // Only perform this optimization after type legalization and before
2560   // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2561   // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2562   // we don't want to undo this promotion.
2563   // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2564   // on scalars.
2565   if ((N0.getOpcode() == ISD::BITCAST ||
2566        N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2567       Level == AfterLegalizeTypes) {
2568     SDValue In0 = N0.getOperand(0);
2569     SDValue In1 = N1.getOperand(0);
2570     EVT In0Ty = In0.getValueType();
2571     EVT In1Ty = In1.getValueType();
2572     SDLoc DL(N);
2573     // If both incoming values are integers, and the original types are the
2574     // same.
2575     if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2576       SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2577       SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2578       AddToWorklist(Op.getNode());
2579       return BC;
2580     }
2581   }
2582
2583   // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2584   // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2585   // If both shuffles use the same mask, and both shuffle within a single
2586   // vector, then it is worthwhile to move the swizzle after the operation.
2587   // The type-legalizer generates this pattern when loading illegal
2588   // vector types from memory. In many cases this allows additional shuffle
2589   // optimizations.
2590   // There are other cases where moving the shuffle after the xor/and/or
2591   // is profitable even if shuffles don't perform a swizzle.
2592   // If both shuffles use the same mask, and both shuffles have the same first
2593   // or second operand, then it might still be profitable to move the shuffle
2594   // after the xor/and/or operation.
2595   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
2596     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2597     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2598
2599     assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
2600            "Inputs to shuffles are not the same type");
2601
2602     // Check that both shuffles use the same mask. The masks are known to be of
2603     // the same length because the result vector type is the same.
2604     // Check also that shuffles have only one use to avoid introducing extra
2605     // instructions.
2606     if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2607         SVN0->getMask().equals(SVN1->getMask())) {
2608       SDValue ShOp = N0->getOperand(1);
2609
2610       // Don't try to fold this node if it requires introducing a
2611       // build vector of all zeros that might be illegal at this stage.
2612       if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2613         if (!LegalTypes)
2614           ShOp = DAG.getConstant(0, VT);
2615         else
2616           ShOp = SDValue();
2617       }
2618
2619       // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2620       // (OR  (shuf (A, C), shuf (B, C)) -> shuf (OR  (A, B), C)
2621       // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2622       if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2623         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2624                                       N0->getOperand(0), N1->getOperand(0));
2625         AddToWorklist(NewNode.getNode());
2626         return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2627                                     &SVN0->getMask()[0]);
2628       }
2629
2630       // Don't try to fold this node if it requires introducing a
2631       // build vector of all zeros that might be illegal at this stage.
2632       ShOp = N0->getOperand(0);
2633       if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2634         if (!LegalTypes)
2635           ShOp = DAG.getConstant(0, VT);
2636         else
2637           ShOp = SDValue();
2638       }
2639
2640       // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2641       // (OR  (shuf (C, A), shuf (C, B)) -> shuf (C, OR  (A, B))
2642       // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2643       if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2644         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2645                                       N0->getOperand(1), N1->getOperand(1));
2646         AddToWorklist(NewNode.getNode());
2647         return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2648                                     &SVN0->getMask()[0]);
2649       }
2650     }
2651   }
2652
2653   return SDValue();
2654 }
2655
2656 SDValue DAGCombiner::visitAND(SDNode *N) {
2657   SDValue N0 = N->getOperand(0);
2658   SDValue N1 = N->getOperand(1);
2659   SDValue LL, LR, RL, RR, CC0, CC1;
2660   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2661   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2662   EVT VT = N1.getValueType();
2663   unsigned BitWidth = VT.getScalarType().getSizeInBits();
2664
2665   // fold vector ops
2666   if (VT.isVector()) {
2667     SDValue FoldedVOp = SimplifyVBinOp(N);
2668     if (FoldedVOp.getNode()) return FoldedVOp;
2669
2670     // fold (and x, 0) -> 0, vector edition
2671     if (ISD::isBuildVectorAllZeros(N0.getNode()))
2672       return N0;
2673     if (ISD::isBuildVectorAllZeros(N1.getNode()))
2674       return N1;
2675
2676     // fold (and x, -1) -> x, vector edition
2677     if (ISD::isBuildVectorAllOnes(N0.getNode()))
2678       return N1;
2679     if (ISD::isBuildVectorAllOnes(N1.getNode()))
2680       return N0;
2681   }
2682
2683   // fold (and x, undef) -> 0
2684   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2685     return DAG.getConstant(0, VT);
2686   // fold (and c1, c2) -> c1&c2
2687   if (N0C && N1C)
2688     return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C);
2689   // canonicalize constant to RHS
2690   if (N0C && !N1C)
2691     return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
2692   // fold (and x, -1) -> x
2693   if (N1C && N1C->isAllOnesValue())
2694     return N0;
2695   // if (and x, c) is known to be zero, return 0
2696   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2697                                    APInt::getAllOnesValue(BitWidth)))
2698     return DAG.getConstant(0, VT);
2699   // reassociate and
2700   SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1);
2701   if (RAND.getNode())
2702     return RAND;
2703   // fold (and (or x, C), D) -> D if (C & D) == D
2704   if (N1C && N0.getOpcode() == ISD::OR)
2705     if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2706       if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2707         return N1;
2708   // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2709   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2710     SDValue N0Op0 = N0.getOperand(0);
2711     APInt Mask = ~N1C->getAPIntValue();
2712     Mask = Mask.trunc(N0Op0.getValueSizeInBits());
2713     if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2714       SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
2715                                  N0.getValueType(), N0Op0);
2716
2717       // Replace uses of the AND with uses of the Zero extend node.
2718       CombineTo(N, Zext);
2719
2720       // We actually want to replace all uses of the any_extend with the
2721       // zero_extend, to avoid duplicating things.  This will later cause this
2722       // AND to be folded.
2723       CombineTo(N0.getNode(), Zext);
2724       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2725     }
2726   }
2727   // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
2728   // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2729   // already be zero by virtue of the width of the base type of the load.
2730   //
2731   // the 'X' node here can either be nothing or an extract_vector_elt to catch
2732   // more cases.
2733   if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2734        N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2735       N0.getOpcode() == ISD::LOAD) {
2736     LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2737                                          N0 : N0.getOperand(0) );
2738
2739     // Get the constant (if applicable) the zero'th operand is being ANDed with.
2740     // This can be a pure constant or a vector splat, in which case we treat the
2741     // vector as a scalar and use the splat value.
2742     APInt Constant = APInt::getNullValue(1);
2743     if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2744       Constant = C->getAPIntValue();
2745     } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2746       APInt SplatValue, SplatUndef;
2747       unsigned SplatBitSize;
2748       bool HasAnyUndefs;
2749       bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2750                                              SplatBitSize, HasAnyUndefs);
2751       if (IsSplat) {
2752         // Undef bits can contribute to a possible optimisation if set, so
2753         // set them.
2754         SplatValue |= SplatUndef;
2755
2756         // The splat value may be something like "0x00FFFFFF", which means 0 for
2757         // the first vector value and FF for the rest, repeating. We need a mask
2758         // that will apply equally to all members of the vector, so AND all the
2759         // lanes of the constant together.
2760         EVT VT = Vector->getValueType(0);
2761         unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
2762
2763         // If the splat value has been compressed to a bitlength lower
2764         // than the size of the vector lane, we need to re-expand it to
2765         // the lane size.
2766         if (BitWidth > SplatBitSize)
2767           for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
2768                SplatBitSize < BitWidth;
2769                SplatBitSize = SplatBitSize * 2)
2770             SplatValue |= SplatValue.shl(SplatBitSize);
2771
2772         Constant = APInt::getAllOnesValue(BitWidth);
2773         for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
2774           Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
2775       }
2776     }
2777
2778     // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
2779     // actually legal and isn't going to get expanded, else this is a false
2780     // optimisation.
2781     bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
2782                                                     Load->getMemoryVT());
2783
2784     // Resize the constant to the same size as the original memory access before
2785     // extension. If it is still the AllOnesValue then this AND is completely
2786     // unneeded.
2787     Constant =
2788       Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
2789
2790     bool B;
2791     switch (Load->getExtensionType()) {
2792     default: B = false; break;
2793     case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
2794     case ISD::ZEXTLOAD:
2795     case ISD::NON_EXTLOAD: B = true; break;
2796     }
2797
2798     if (B && Constant.isAllOnesValue()) {
2799       // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
2800       // preserve semantics once we get rid of the AND.
2801       SDValue NewLoad(Load, 0);
2802       if (Load->getExtensionType() == ISD::EXTLOAD) {
2803         NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
2804                               Load->getValueType(0), SDLoc(Load),
2805                               Load->getChain(), Load->getBasePtr(),
2806                               Load->getOffset(), Load->getMemoryVT(),
2807                               Load->getMemOperand());
2808         // Replace uses of the EXTLOAD with the new ZEXTLOAD.
2809         if (Load->getNumValues() == 3) {
2810           // PRE/POST_INC loads have 3 values.
2811           SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
2812                            NewLoad.getValue(2) };
2813           CombineTo(Load, To, 3, true);
2814         } else {
2815           CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
2816         }
2817       }
2818
2819       // Fold the AND away, taking care not to fold to the old load node if we
2820       // replaced it.
2821       CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
2822
2823       return SDValue(N, 0); // Return N so it doesn't get rechecked!
2824     }
2825   }
2826   // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2827   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2828     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2829     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2830
2831     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2832         LL.getValueType().isInteger()) {
2833       // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2834       if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
2835         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2836                                      LR.getValueType(), LL, RL);
2837         AddToWorklist(ORNode.getNode());
2838         return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2839       }
2840       // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2841       if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
2842         SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2843                                       LR.getValueType(), LL, RL);
2844         AddToWorklist(ANDNode.getNode());
2845         return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
2846       }
2847       // fold (and (setgt X,  -1), (setgt Y,  -1)) -> (setgt (or X, Y), -1)
2848       if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
2849         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2850                                      LR.getValueType(), LL, RL);
2851         AddToWorklist(ORNode.getNode());
2852         return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2853       }
2854     }
2855     // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2856     if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2857         Op0 == Op1 && LL.getValueType().isInteger() &&
2858       Op0 == ISD::SETNE && ((cast<ConstantSDNode>(LR)->isNullValue() &&
2859                                  cast<ConstantSDNode>(RR)->isAllOnesValue()) ||
2860                                 (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
2861                                  cast<ConstantSDNode>(RR)->isNullValue()))) {
2862       SDValue ADDNode = DAG.getNode(ISD::ADD, SDLoc(N0), LL.getValueType(),
2863                                     LL, DAG.getConstant(1, LL.getValueType()));
2864       AddToWorklist(ADDNode.getNode());
2865       return DAG.getSetCC(SDLoc(N), VT, ADDNode,
2866                           DAG.getConstant(2, LL.getValueType()), ISD::SETUGE);
2867     }
2868     // canonicalize equivalent to ll == rl
2869     if (LL == RR && LR == RL) {
2870       Op1 = ISD::getSetCCSwappedOperands(Op1);
2871       std::swap(RL, RR);
2872     }
2873     if (LL == RL && LR == RR) {
2874       bool isInteger = LL.getValueType().isInteger();
2875       ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2876       if (Result != ISD::SETCC_INVALID &&
2877           (!LegalOperations ||
2878            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2879             TLI.isOperationLegal(ISD::SETCC,
2880                             getSetCCResultType(N0.getSimpleValueType())))))
2881         return DAG.getSetCC(SDLoc(N), N0.getValueType(),
2882                             LL, LR, Result);
2883     }
2884   }
2885
2886   // Simplify: (and (op x...), (op y...))  -> (op (and x, y))
2887   if (N0.getOpcode() == N1.getOpcode()) {
2888     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
2889     if (Tmp.getNode()) return Tmp;
2890   }
2891
2892   // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
2893   // fold (and (sra)) -> (and (srl)) when possible.
2894   if (!VT.isVector() &&
2895       SimplifyDemandedBits(SDValue(N, 0)))
2896     return SDValue(N, 0);
2897
2898   // fold (zext_inreg (extload x)) -> (zextload x)
2899   if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
2900     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2901     EVT MemVT = LN0->getMemoryVT();
2902     // If we zero all the possible extended bits, then we can turn this into
2903     // a zextload if we are running before legalize or the operation is legal.
2904     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2905     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2906                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2907         ((!LegalOperations && !LN0->isVolatile()) ||
2908          TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2909       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2910                                        LN0->getChain(), LN0->getBasePtr(),
2911                                        MemVT, LN0->getMemOperand());
2912       AddToWorklist(N);
2913       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2914       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2915     }
2916   }
2917   // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
2918   if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
2919       N0.hasOneUse()) {
2920     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2921     EVT MemVT = LN0->getMemoryVT();
2922     // If we zero all the possible extended bits, then we can turn this into
2923     // a zextload if we are running before legalize or the operation is legal.
2924     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2925     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2926                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2927         ((!LegalOperations && !LN0->isVolatile()) ||
2928          TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2929       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2930                                        LN0->getChain(), LN0->getBasePtr(),
2931                                        MemVT, LN0->getMemOperand());
2932       AddToWorklist(N);
2933       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2934       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2935     }
2936   }
2937
2938   // fold (and (load x), 255) -> (zextload x, i8)
2939   // fold (and (extload x, i16), 255) -> (zextload x, i8)
2940   // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
2941   if (N1C && (N0.getOpcode() == ISD::LOAD ||
2942               (N0.getOpcode() == ISD::ANY_EXTEND &&
2943                N0.getOperand(0).getOpcode() == ISD::LOAD))) {
2944     bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
2945     LoadSDNode *LN0 = HasAnyExt
2946       ? cast<LoadSDNode>(N0.getOperand(0))
2947       : cast<LoadSDNode>(N0);
2948     if (LN0->getExtensionType() != ISD::SEXTLOAD &&
2949         LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
2950       uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
2951       if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
2952         EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
2953         EVT LoadedVT = LN0->getMemoryVT();
2954
2955         if (ExtVT == LoadedVT &&
2956             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2957           EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2958
2959           SDValue NewLoad =
2960             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2961                            LN0->getChain(), LN0->getBasePtr(), ExtVT,
2962                            LN0->getMemOperand());
2963           AddToWorklist(N);
2964           CombineTo(LN0, NewLoad, NewLoad.getValue(1));
2965           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2966         }
2967
2968         // Do not change the width of a volatile load.
2969         // Do not generate loads of non-round integer types since these can
2970         // be expensive (and would be wrong if the type is not byte sized).
2971         if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
2972             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2973           EVT PtrType = LN0->getOperand(1).getValueType();
2974
2975           unsigned Alignment = LN0->getAlignment();
2976           SDValue NewPtr = LN0->getBasePtr();
2977
2978           // For big endian targets, we need to add an offset to the pointer
2979           // to load the correct bytes.  For little endian systems, we merely
2980           // need to read fewer bytes from the same pointer.
2981           if (TLI.isBigEndian()) {
2982             unsigned LVTStoreBytes = LoadedVT.getStoreSize();
2983             unsigned EVTStoreBytes = ExtVT.getStoreSize();
2984             unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
2985             NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0), PtrType,
2986                                  NewPtr, DAG.getConstant(PtrOff, PtrType));
2987             Alignment = MinAlign(Alignment, PtrOff);
2988           }
2989
2990           AddToWorklist(NewPtr.getNode());
2991
2992           EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2993           SDValue Load =
2994             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2995                            LN0->getChain(), NewPtr,
2996                            LN0->getPointerInfo(),
2997                            ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
2998                            LN0->isInvariant(), Alignment, LN0->getAAInfo());
2999           AddToWorklist(N);
3000           CombineTo(LN0, Load, Load.getValue(1));
3001           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3002         }
3003       }
3004     }
3005   }
3006
3007   if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
3008       VT.getSizeInBits() <= 64) {
3009     if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3010       APInt ADDC = ADDI->getAPIntValue();
3011       if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
3012         // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
3013         // immediate for an add, but it is legal if its top c2 bits are set,
3014         // transform the ADD so the immediate doesn't need to be materialized
3015         // in a register.
3016         if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
3017           APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
3018                                              SRLI->getZExtValue());
3019           if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
3020             ADDC |= Mask;
3021             if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
3022               SDValue NewAdd =
3023                 DAG.getNode(ISD::ADD, SDLoc(N0), VT,
3024                             N0.getOperand(0), DAG.getConstant(ADDC, VT));
3025               CombineTo(N0.getNode(), NewAdd);
3026               return SDValue(N, 0); // Return N so it doesn't get rechecked!
3027             }
3028           }
3029         }
3030       }
3031     }
3032   }
3033
3034   // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
3035   if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
3036     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
3037                                        N0.getOperand(1), false);
3038     if (BSwap.getNode())
3039       return BSwap;
3040   }
3041
3042   return SDValue();
3043 }
3044
3045 /// MatchBSwapHWord - Match (a >> 8) | (a << 8) as (bswap a) >> 16
3046 ///
3047 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
3048                                         bool DemandHighBits) {
3049   if (!LegalOperations)
3050     return SDValue();
3051
3052   EVT VT = N->getValueType(0);
3053   if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
3054     return SDValue();
3055   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3056     return SDValue();
3057
3058   // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
3059   bool LookPassAnd0 = false;
3060   bool LookPassAnd1 = false;
3061   if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
3062       std::swap(N0, N1);
3063   if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
3064       std::swap(N0, N1);
3065   if (N0.getOpcode() == ISD::AND) {
3066     if (!N0.getNode()->hasOneUse())
3067       return SDValue();
3068     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3069     if (!N01C || N01C->getZExtValue() != 0xFF00)
3070       return SDValue();
3071     N0 = N0.getOperand(0);
3072     LookPassAnd0 = true;
3073   }
3074
3075   if (N1.getOpcode() == ISD::AND) {
3076     if (!N1.getNode()->hasOneUse())
3077       return SDValue();
3078     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3079     if (!N11C || N11C->getZExtValue() != 0xFF)
3080       return SDValue();
3081     N1 = N1.getOperand(0);
3082     LookPassAnd1 = true;
3083   }
3084
3085   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3086     std::swap(N0, N1);
3087   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3088     return SDValue();
3089   if (!N0.getNode()->hasOneUse() ||
3090       !N1.getNode()->hasOneUse())
3091     return SDValue();
3092
3093   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3094   ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3095   if (!N01C || !N11C)
3096     return SDValue();
3097   if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3098     return SDValue();
3099
3100   // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3101   SDValue N00 = N0->getOperand(0);
3102   if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3103     if (!N00.getNode()->hasOneUse())
3104       return SDValue();
3105     ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3106     if (!N001C || N001C->getZExtValue() != 0xFF)
3107       return SDValue();
3108     N00 = N00.getOperand(0);
3109     LookPassAnd0 = true;
3110   }
3111
3112   SDValue N10 = N1->getOperand(0);
3113   if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3114     if (!N10.getNode()->hasOneUse())
3115       return SDValue();
3116     ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3117     if (!N101C || N101C->getZExtValue() != 0xFF00)
3118       return SDValue();
3119     N10 = N10.getOperand(0);
3120     LookPassAnd1 = true;
3121   }
3122
3123   if (N00 != N10)
3124     return SDValue();
3125
3126   // Make sure everything beyond the low halfword gets set to zero since the SRL
3127   // 16 will clear the top bits.
3128   unsigned OpSizeInBits = VT.getSizeInBits();
3129   if (DemandHighBits && OpSizeInBits > 16) {
3130     // If the left-shift isn't masked out then the only way this is a bswap is
3131     // if all bits beyond the low 8 are 0. In that case the entire pattern
3132     // reduces to a left shift anyway: leave it for other parts of the combiner.
3133     if (!LookPassAnd0)
3134       return SDValue();
3135
3136     // However, if the right shift isn't masked out then it might be because
3137     // it's not needed. See if we can spot that too.
3138     if (!LookPassAnd1 &&
3139         !DAG.MaskedValueIsZero(
3140             N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3141       return SDValue();
3142   }
3143
3144   SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
3145   if (OpSizeInBits > 16)
3146     Res = DAG.getNode(ISD::SRL, SDLoc(N), VT, Res,
3147                       DAG.getConstant(OpSizeInBits-16, getShiftAmountTy(VT)));
3148   return Res;
3149 }
3150
3151 /// isBSwapHWordElement - Return true if the specified node is an element
3152 /// that makes up a 32-bit packed halfword byteswap. i.e.
3153 /// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
3154 static bool isBSwapHWordElement(SDValue N, SmallVectorImpl<SDNode *> &Parts) {
3155   if (!N.getNode()->hasOneUse())
3156     return false;
3157
3158   unsigned Opc = N.getOpcode();
3159   if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3160     return false;
3161
3162   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3163   if (!N1C)
3164     return false;
3165
3166   unsigned Num;
3167   switch (N1C->getZExtValue()) {
3168   default:
3169     return false;
3170   case 0xFF:       Num = 0; break;
3171   case 0xFF00:     Num = 1; break;
3172   case 0xFF0000:   Num = 2; break;
3173   case 0xFF000000: Num = 3; break;
3174   }
3175
3176   // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3177   SDValue N0 = N.getOperand(0);
3178   if (Opc == ISD::AND) {
3179     if (Num == 0 || Num == 2) {
3180       // (x >> 8) & 0xff
3181       // (x >> 8) & 0xff0000
3182       if (N0.getOpcode() != ISD::SRL)
3183         return false;
3184       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3185       if (!C || C->getZExtValue() != 8)
3186         return false;
3187     } else {
3188       // (x << 8) & 0xff00
3189       // (x << 8) & 0xff000000
3190       if (N0.getOpcode() != ISD::SHL)
3191         return false;
3192       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3193       if (!C || C->getZExtValue() != 8)
3194         return false;
3195     }
3196   } else if (Opc == ISD::SHL) {
3197     // (x & 0xff) << 8
3198     // (x & 0xff0000) << 8
3199     if (Num != 0 && Num != 2)
3200       return false;
3201     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3202     if (!C || C->getZExtValue() != 8)
3203       return false;
3204   } else { // Opc == ISD::SRL
3205     // (x & 0xff00) >> 8
3206     // (x & 0xff000000) >> 8
3207     if (Num != 1 && Num != 3)
3208       return false;
3209     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3210     if (!C || C->getZExtValue() != 8)
3211       return false;
3212   }
3213
3214   if (Parts[Num])
3215     return false;
3216
3217   Parts[Num] = N0.getOperand(0).getNode();
3218   return true;
3219 }
3220
3221 /// MatchBSwapHWord - Match a 32-bit packed halfword bswap. That is
3222 /// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
3223 /// => (rotl (bswap x), 16)
3224 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3225   if (!LegalOperations)
3226     return SDValue();
3227
3228   EVT VT = N->getValueType(0);
3229   if (VT != MVT::i32)
3230     return SDValue();
3231   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3232     return SDValue();
3233
3234   SmallVector<SDNode*,4> Parts(4, (SDNode*)nullptr);
3235   // Look for either
3236   // (or (or (and), (and)), (or (and), (and)))
3237   // (or (or (or (and), (and)), (and)), (and))
3238   if (N0.getOpcode() != ISD::OR)
3239     return SDValue();
3240   SDValue N00 = N0.getOperand(0);
3241   SDValue N01 = N0.getOperand(1);
3242
3243   if (N1.getOpcode() == ISD::OR &&
3244       N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3245     // (or (or (and), (and)), (or (and), (and)))
3246     SDValue N000 = N00.getOperand(0);
3247     if (!isBSwapHWordElement(N000, Parts))
3248       return SDValue();
3249
3250     SDValue N001 = N00.getOperand(1);
3251     if (!isBSwapHWordElement(N001, Parts))
3252       return SDValue();
3253     SDValue N010 = N01.getOperand(0);
3254     if (!isBSwapHWordElement(N010, Parts))
3255       return SDValue();
3256     SDValue N011 = N01.getOperand(1);
3257     if (!isBSwapHWordElement(N011, Parts))
3258       return SDValue();
3259   } else {
3260     // (or (or (or (and), (and)), (and)), (and))
3261     if (!isBSwapHWordElement(N1, Parts))
3262       return SDValue();
3263     if (!isBSwapHWordElement(N01, Parts))
3264       return SDValue();
3265     if (N00.getOpcode() != ISD::OR)
3266       return SDValue();
3267     SDValue N000 = N00.getOperand(0);
3268     if (!isBSwapHWordElement(N000, Parts))
3269       return SDValue();
3270     SDValue N001 = N00.getOperand(1);
3271     if (!isBSwapHWordElement(N001, Parts))
3272       return SDValue();
3273   }
3274
3275   // Make sure the parts are all coming from the same node.
3276   if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3277     return SDValue();
3278
3279   SDValue BSwap = DAG.getNode(ISD::BSWAP, SDLoc(N), VT,
3280                               SDValue(Parts[0],0));
3281
3282   // Result of the bswap should be rotated by 16. If it's not legal, then
3283   // do  (x << 16) | (x >> 16).
3284   SDValue ShAmt = DAG.getConstant(16, getShiftAmountTy(VT));
3285   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3286     return DAG.getNode(ISD::ROTL, SDLoc(N), VT, BSwap, ShAmt);
3287   if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3288     return DAG.getNode(ISD::ROTR, SDLoc(N), VT, BSwap, ShAmt);
3289   return DAG.getNode(ISD::OR, SDLoc(N), VT,
3290                      DAG.getNode(ISD::SHL, SDLoc(N), VT, BSwap, ShAmt),
3291                      DAG.getNode(ISD::SRL, SDLoc(N), VT, BSwap, ShAmt));
3292 }
3293
3294 SDValue DAGCombiner::visitOR(SDNode *N) {
3295   SDValue N0 = N->getOperand(0);
3296   SDValue N1 = N->getOperand(1);
3297   SDValue LL, LR, RL, RR, CC0, CC1;
3298   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3299   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3300   EVT VT = N1.getValueType();
3301
3302   // fold vector ops
3303   if (VT.isVector()) {
3304     SDValue FoldedVOp = SimplifyVBinOp(N);
3305     if (FoldedVOp.getNode()) return FoldedVOp;
3306
3307     // fold (or x, 0) -> x, vector edition
3308     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3309       return N1;
3310     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3311       return N0;
3312
3313     // fold (or x, -1) -> -1, vector edition
3314     if (ISD::isBuildVectorAllOnes(N0.getNode()))
3315       return N0;
3316     if (ISD::isBuildVectorAllOnes(N1.getNode()))
3317       return N1;
3318
3319     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
3320     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
3321     // Do this only if the resulting shuffle is legal.
3322     if (isa<ShuffleVectorSDNode>(N0) &&
3323         isa<ShuffleVectorSDNode>(N1) &&
3324         // Avoid folding a node with illegal type.
3325         TLI.isTypeLegal(VT) &&
3326         N0->getOperand(1) == N1->getOperand(1) &&
3327         ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
3328       bool CanFold = true;
3329       unsigned NumElts = VT.getVectorNumElements();
3330       const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3331       const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3332       // We construct two shuffle masks:
3333       // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
3334       // and N1 as the second operand.
3335       // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
3336       // and N0 as the second operand.
3337       // We do this because OR is commutable and therefore there might be
3338       // two ways to fold this node into a shuffle.
3339       SmallVector<int,4> Mask1;
3340       SmallVector<int,4> Mask2;
3341
3342       for (unsigned i = 0; i != NumElts && CanFold; ++i) {
3343         int M0 = SV0->getMaskElt(i);
3344         int M1 = SV1->getMaskElt(i);
3345
3346         // Both shuffle indexes are undef. Propagate Undef.
3347         if (M0 < 0 && M1 < 0) {
3348           Mask1.push_back(M0);
3349           Mask2.push_back(M0);
3350           continue;
3351         }
3352
3353         if (M0 < 0 || M1 < 0 ||
3354             (M0 < (int)NumElts && M1 < (int)NumElts) ||
3355             (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
3356           CanFold = false;
3357           break;
3358         }
3359
3360         Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
3361         Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
3362       }
3363
3364       if (CanFold) {
3365         // Fold this sequence only if the resulting shuffle is 'legal'.
3366         if (TLI.isShuffleMaskLegal(Mask1, VT))
3367           return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
3368                                       N1->getOperand(0), &Mask1[0]);
3369         if (TLI.isShuffleMaskLegal(Mask2, VT))
3370           return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
3371                                       N0->getOperand(0), &Mask2[0]);
3372       }
3373     }
3374   }
3375
3376   // fold (or x, undef) -> -1
3377   if (!LegalOperations &&
3378       (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3379     EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3380     return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
3381   }
3382   // fold (or c1, c2) -> c1|c2
3383   if (N0C && N1C)
3384     return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C);
3385   // canonicalize constant to RHS
3386   if (N0C && !N1C)
3387     return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3388   // fold (or x, 0) -> x
3389   if (N1C && N1C->isNullValue())
3390     return N0;
3391   // fold (or x, -1) -> -1
3392   if (N1C && N1C->isAllOnesValue())
3393     return N1;
3394   // fold (or x, c) -> c iff (x & ~c) == 0
3395   if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3396     return N1;
3397
3398   // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3399   SDValue BSwap = MatchBSwapHWord(N, N0, N1);
3400   if (BSwap.getNode())
3401     return BSwap;
3402   BSwap = MatchBSwapHWordLow(N, N0, N1);
3403   if (BSwap.getNode())
3404     return BSwap;
3405
3406   // reassociate or
3407   SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1);
3408   if (ROR.getNode())
3409     return ROR;
3410   // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3411   // iff (c1 & c2) == 0.
3412   if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3413              isa<ConstantSDNode>(N0.getOperand(1))) {
3414     ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3415     if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3416       SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1);
3417       if (!COR.getNode())
3418         return SDValue();
3419       return DAG.getNode(ISD::AND, SDLoc(N), VT,
3420                          DAG.getNode(ISD::OR, SDLoc(N0), VT,
3421                                      N0.getOperand(0), N1), COR);
3422     }
3423   }
3424   // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3425   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3426     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3427     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3428
3429     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
3430         LL.getValueType().isInteger()) {
3431       // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3432       // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3433       if (cast<ConstantSDNode>(LR)->isNullValue() &&
3434           (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3435         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3436                                      LR.getValueType(), LL, RL);
3437         AddToWorklist(ORNode.getNode());
3438         return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
3439       }
3440       // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3441       // fold (or (setgt X, -1), (setgt Y  -1)) -> (setgt (and X, Y), -1)
3442       if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
3443           (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3444         SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3445                                       LR.getValueType(), LL, RL);
3446         AddToWorklist(ANDNode.getNode());
3447         return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
3448       }
3449     }
3450     // canonicalize equivalent to ll == rl
3451     if (LL == RR && LR == RL) {
3452       Op1 = ISD::getSetCCSwappedOperands(Op1);
3453       std::swap(RL, RR);
3454     }
3455     if (LL == RL && LR == RR) {
3456       bool isInteger = LL.getValueType().isInteger();
3457       ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3458       if (Result != ISD::SETCC_INVALID &&
3459           (!LegalOperations ||
3460            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3461             TLI.isOperationLegal(ISD::SETCC,
3462               getSetCCResultType(N0.getValueType())))))
3463         return DAG.getSetCC(SDLoc(N), N0.getValueType(),
3464                             LL, LR, Result);
3465     }
3466   }
3467
3468   // Simplify: (or (op x...), (op y...))  -> (op (or x, y))
3469   if (N0.getOpcode() == N1.getOpcode()) {
3470     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3471     if (Tmp.getNode()) return Tmp;
3472   }
3473
3474   // (or (and X, C1), (and Y, C2))  -> (and (or X, Y), C3) if possible.
3475   if (N0.getOpcode() == ISD::AND &&
3476       N1.getOpcode() == ISD::AND &&
3477       N0.getOperand(1).getOpcode() == ISD::Constant &&
3478       N1.getOperand(1).getOpcode() == ISD::Constant &&
3479       // Don't increase # computations.
3480       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3481     // We can only do this xform if we know that bits from X that are set in C2
3482     // but not in C1 are already zero.  Likewise for Y.
3483     const APInt &LHSMask =
3484       cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3485     const APInt &RHSMask =
3486       cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
3487
3488     if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3489         DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3490       SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3491                               N0.getOperand(0), N1.getOperand(0));
3492       return DAG.getNode(ISD::AND, SDLoc(N), VT, X,
3493                          DAG.getConstant(LHSMask | RHSMask, VT));
3494     }
3495   }
3496
3497   // See if this is some rotate idiom.
3498   if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3499     return SDValue(Rot, 0);
3500
3501   // Simplify the operands using demanded-bits information.
3502   if (!VT.isVector() &&
3503       SimplifyDemandedBits(SDValue(N, 0)))
3504     return SDValue(N, 0);
3505
3506   return SDValue();
3507 }
3508
3509 /// MatchRotateHalf - Match "(X shl/srl V1) & V2" where V2 may not be present.
3510 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3511   if (Op.getOpcode() == ISD::AND) {
3512     if (isa<ConstantSDNode>(Op.getOperand(1))) {
3513       Mask = Op.getOperand(1);
3514       Op = Op.getOperand(0);
3515     } else {
3516       return false;
3517     }
3518   }
3519
3520   if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3521     Shift = Op;
3522     return true;
3523   }
3524
3525   return false;
3526 }
3527
3528 // Return true if we can prove that, whenever Neg and Pos are both in the
3529 // range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos).  This means that
3530 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3531 //
3532 //     (or (shift1 X, Neg), (shift2 X, Pos))
3533 //
3534 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3535 // in direction shift1 by Neg.  The range [0, OpSize) means that we only need
3536 // to consider shift amounts with defined behavior.
3537 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) {
3538   // If OpSize is a power of 2 then:
3539   //
3540   //  (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1)
3541   //  (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize).
3542   //
3543   // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check
3544   // for the stronger condition:
3545   //
3546   //     Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1)    [A]
3547   //
3548   // for all Neg and Pos.  Since Neg & (OpSize - 1) == Neg' & (OpSize - 1)
3549   // we can just replace Neg with Neg' for the rest of the function.
3550   //
3551   // In other cases we check for the even stronger condition:
3552   //
3553   //     Neg == OpSize - Pos                                    [B]
3554   //
3555   // for all Neg and Pos.  Note that the (or ...) then invokes undefined
3556   // behavior if Pos == 0 (and consequently Neg == OpSize).
3557   //
3558   // We could actually use [A] whenever OpSize is a power of 2, but the
3559   // only extra cases that it would match are those uninteresting ones
3560   // where Neg and Pos are never in range at the same time.  E.g. for
3561   // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3562   // as well as (sub 32, Pos), but:
3563   //
3564   //     (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3565   //
3566   // always invokes undefined behavior for 32-bit X.
3567   //
3568   // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise.
3569   unsigned MaskLoBits = 0;
3570   if (Neg.getOpcode() == ISD::AND &&
3571       isPowerOf2_64(OpSize) &&
3572       Neg.getOperand(1).getOpcode() == ISD::Constant &&
3573       cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) {
3574     Neg = Neg.getOperand(0);
3575     MaskLoBits = Log2_64(OpSize);
3576   }
3577
3578   // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3579   if (Neg.getOpcode() != ISD::SUB)
3580     return 0;
3581   ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0));
3582   if (!NegC)
3583     return 0;
3584   SDValue NegOp1 = Neg.getOperand(1);
3585
3586   // On the RHS of [A], if Pos is Pos' & (OpSize - 1), just replace Pos with
3587   // Pos'.  The truncation is redundant for the purpose of the equality.
3588   if (MaskLoBits &&
3589       Pos.getOpcode() == ISD::AND &&
3590       Pos.getOperand(1).getOpcode() == ISD::Constant &&
3591       cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() == OpSize - 1)
3592     Pos = Pos.getOperand(0);
3593
3594   // The condition we need is now:
3595   //
3596   //     (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask
3597   //
3598   // If NegOp1 == Pos then we need:
3599   //
3600   //              OpSize & Mask == NegC & Mask
3601   //
3602   // (because "x & Mask" is a truncation and distributes through subtraction).
3603   APInt Width;
3604   if (Pos == NegOp1)
3605     Width = NegC->getAPIntValue();
3606   // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3607   // Then the condition we want to prove becomes:
3608   //
3609   //     (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask
3610   //
3611   // which, again because "x & Mask" is a truncation, becomes:
3612   //
3613   //                NegC & Mask == (OpSize - PosC) & Mask
3614   //              OpSize & Mask == (NegC + PosC) & Mask
3615   else if (Pos.getOpcode() == ISD::ADD &&
3616            Pos.getOperand(0) == NegOp1 &&
3617            Pos.getOperand(1).getOpcode() == ISD::Constant)
3618     Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() +
3619              NegC->getAPIntValue());
3620   else
3621     return false;
3622
3623   // Now we just need to check that OpSize & Mask == Width & Mask.
3624   if (MaskLoBits)
3625     // Opsize & Mask is 0 since Mask is Opsize - 1.
3626     return Width.getLoBits(MaskLoBits) == 0;
3627   return Width == OpSize;
3628 }
3629
3630 // A subroutine of MatchRotate used once we have found an OR of two opposite
3631 // shifts of Shifted.  If Neg == <operand size> - Pos then the OR reduces
3632 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3633 // former being preferred if supported.  InnerPos and InnerNeg are Pos and
3634 // Neg with outer conversions stripped away.
3635 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3636                                        SDValue Neg, SDValue InnerPos,
3637                                        SDValue InnerNeg, unsigned PosOpcode,
3638                                        unsigned NegOpcode, SDLoc DL) {
3639   // fold (or (shl x, (*ext y)),
3640   //          (srl x, (*ext (sub 32, y)))) ->
3641   //   (rotl x, y) or (rotr x, (sub 32, y))
3642   //
3643   // fold (or (shl x, (*ext (sub 32, y))),
3644   //          (srl x, (*ext y))) ->
3645   //   (rotr x, y) or (rotl x, (sub 32, y))
3646   EVT VT = Shifted.getValueType();
3647   if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) {
3648     bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3649     return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3650                        HasPos ? Pos : Neg).getNode();
3651   }
3652
3653   return nullptr;
3654 }
3655
3656 // MatchRotate - Handle an 'or' of two operands.  If this is one of the many
3657 // idioms for rotate, and if the target supports rotation instructions, generate
3658 // a rot[lr].
3659 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
3660   // Must be a legal type.  Expanded 'n promoted things won't work with rotates.
3661   EVT VT = LHS.getValueType();
3662   if (!TLI.isTypeLegal(VT)) return nullptr;
3663
3664   // The target must have at least one rotate flavor.
3665   bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3666   bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3667   if (!HasROTL && !HasROTR) return nullptr;
3668
3669   // Match "(X shl/srl V1) & V2" where V2 may not be present.
3670   SDValue LHSShift;   // The shift.
3671   SDValue LHSMask;    // AND value if any.
3672   if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3673     return nullptr; // Not part of a rotate.
3674
3675   SDValue RHSShift;   // The shift.
3676   SDValue RHSMask;    // AND value if any.
3677   if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3678     return nullptr; // Not part of a rotate.
3679
3680   if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3681     return nullptr;   // Not shifting the same value.
3682
3683   if (LHSShift.getOpcode() == RHSShift.getOpcode())
3684     return nullptr;   // Shifts must disagree.
3685
3686   // Canonicalize shl to left side in a shl/srl pair.
3687   if (RHSShift.getOpcode() == ISD::SHL) {
3688     std::swap(LHS, RHS);
3689     std::swap(LHSShift, RHSShift);
3690     std::swap(LHSMask , RHSMask );
3691   }
3692
3693   unsigned OpSizeInBits = VT.getSizeInBits();
3694   SDValue LHSShiftArg = LHSShift.getOperand(0);
3695   SDValue LHSShiftAmt = LHSShift.getOperand(1);
3696   SDValue RHSShiftArg = RHSShift.getOperand(0);
3697   SDValue RHSShiftAmt = RHSShift.getOperand(1);
3698
3699   // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3700   // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
3701   if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3702       RHSShiftAmt.getOpcode() == ISD::Constant) {
3703     uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3704     uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
3705     if ((LShVal + RShVal) != OpSizeInBits)
3706       return nullptr;
3707
3708     SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3709                               LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3710
3711     // If there is an AND of either shifted operand, apply it to the result.
3712     if (LHSMask.getNode() || RHSMask.getNode()) {
3713       APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
3714
3715       if (LHSMask.getNode()) {
3716         APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3717         Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
3718       }
3719       if (RHSMask.getNode()) {
3720         APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3721         Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
3722       }
3723
3724       Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT));
3725     }
3726
3727     return Rot.getNode();
3728   }
3729
3730   // If there is a mask here, and we have a variable shift, we can't be sure
3731   // that we're masking out the right stuff.
3732   if (LHSMask.getNode() || RHSMask.getNode())
3733     return nullptr;
3734
3735   // If the shift amount is sign/zext/any-extended just peel it off.
3736   SDValue LExtOp0 = LHSShiftAmt;
3737   SDValue RExtOp0 = RHSShiftAmt;
3738   if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3739        LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3740        LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3741        LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3742       (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3743        RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3744        RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3745        RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
3746     LExtOp0 = LHSShiftAmt.getOperand(0);
3747     RExtOp0 = RHSShiftAmt.getOperand(0);
3748   }
3749
3750   SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
3751                                    LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
3752   if (TryL)
3753     return TryL;
3754
3755   SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
3756                                    RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
3757   if (TryR)
3758     return TryR;
3759
3760   return nullptr;
3761 }
3762
3763 SDValue DAGCombiner::visitXOR(SDNode *N) {
3764   SDValue N0 = N->getOperand(0);
3765   SDValue N1 = N->getOperand(1);
3766   SDValue LHS, RHS, CC;
3767   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3768   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3769   EVT VT = N0.getValueType();
3770
3771   // fold vector ops
3772   if (VT.isVector()) {
3773     SDValue FoldedVOp = SimplifyVBinOp(N);
3774     if (FoldedVOp.getNode()) return FoldedVOp;
3775
3776     // fold (xor x, 0) -> x, vector edition
3777     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3778       return N1;
3779     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3780       return N0;
3781   }
3782
3783   // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3784   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3785     return DAG.getConstant(0, VT);
3786   // fold (xor x, undef) -> undef
3787   if (N0.getOpcode() == ISD::UNDEF)
3788     return N0;
3789   if (N1.getOpcode() == ISD::UNDEF)
3790     return N1;
3791   // fold (xor c1, c2) -> c1^c2
3792   if (N0C && N1C)
3793     return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
3794   // canonicalize constant to RHS
3795   if (N0C && !N1C)
3796     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
3797   // fold (xor x, 0) -> x
3798   if (N1C && N1C->isNullValue())
3799     return N0;
3800   // reassociate xor
3801   SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1);
3802   if (RXOR.getNode())
3803     return RXOR;
3804
3805   // fold !(x cc y) -> (x !cc y)
3806   if (N1C && N1C->getAPIntValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) {
3807     bool isInt = LHS.getValueType().isInteger();
3808     ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3809                                                isInt);
3810
3811     if (!LegalOperations ||
3812         TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
3813       switch (N0.getOpcode()) {
3814       default:
3815         llvm_unreachable("Unhandled SetCC Equivalent!");
3816       case ISD::SETCC:
3817         return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
3818       case ISD::SELECT_CC:
3819         return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
3820                                N0.getOperand(3), NotCC);
3821       }
3822     }
3823   }
3824
3825   // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
3826   if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
3827       N0.getNode()->hasOneUse() &&
3828       isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
3829     SDValue V = N0.getOperand(0);
3830     V = DAG.getNode(ISD::XOR, SDLoc(N0), V.getValueType(), V,
3831                     DAG.getConstant(1, V.getValueType()));
3832     AddToWorklist(V.getNode());
3833     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
3834   }
3835
3836   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
3837   if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
3838       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3839     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3840     if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
3841       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3842       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3843       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3844       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
3845       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3846     }
3847   }
3848   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
3849   if (N1C && N1C->isAllOnesValue() &&
3850       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3851     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3852     if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
3853       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3854       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3855       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3856       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
3857       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3858     }
3859   }
3860   // fold (xor (and x, y), y) -> (and (not x), y)
3861   if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3862       N0->getOperand(1) == N1) {
3863     SDValue X = N0->getOperand(0);
3864     SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
3865     AddToWorklist(NotX.getNode());
3866     return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
3867   }
3868   // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
3869   if (N1C && N0.getOpcode() == ISD::XOR) {
3870     ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
3871     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3872     if (N00C)
3873       return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(1),
3874                          DAG.getConstant(N1C->getAPIntValue() ^
3875                                          N00C->getAPIntValue(), VT));
3876     if (N01C)
3877       return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(0),
3878                          DAG.getConstant(N1C->getAPIntValue() ^
3879                                          N01C->getAPIntValue(), VT));
3880   }
3881   // fold (xor x, x) -> 0
3882   if (N0 == N1)
3883     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
3884
3885   // Simplify: xor (op x...), (op y...)  -> (op (xor x, y))
3886   if (N0.getOpcode() == N1.getOpcode()) {
3887     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3888     if (Tmp.getNode()) return Tmp;
3889   }
3890
3891   // Simplify the expression using non-local knowledge.
3892   if (!VT.isVector() &&
3893       SimplifyDemandedBits(SDValue(N, 0)))
3894     return SDValue(N, 0);
3895
3896   return SDValue();
3897 }
3898
3899 /// visitShiftByConstant - Handle transforms common to the three shifts, when
3900 /// the shift amount is a constant.
3901 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
3902   // We can't and shouldn't fold opaque constants.
3903   if (Amt->isOpaque())
3904     return SDValue();
3905
3906   SDNode *LHS = N->getOperand(0).getNode();
3907   if (!LHS->hasOneUse()) return SDValue();
3908
3909   // We want to pull some binops through shifts, so that we have (and (shift))
3910   // instead of (shift (and)), likewise for add, or, xor, etc.  This sort of
3911   // thing happens with address calculations, so it's important to canonicalize
3912   // it.
3913   bool HighBitSet = false;  // Can we transform this if the high bit is set?
3914
3915   switch (LHS->getOpcode()) {
3916   default: return SDValue();
3917   case ISD::OR:
3918   case ISD::XOR:
3919     HighBitSet = false; // We can only transform sra if the high bit is clear.
3920     break;
3921   case ISD::AND:
3922     HighBitSet = true;  // We can only transform sra if the high bit is set.
3923     break;
3924   case ISD::ADD:
3925     if (N->getOpcode() != ISD::SHL)
3926       return SDValue(); // only shl(add) not sr[al](add).
3927     HighBitSet = false; // We can only transform sra if the high bit is clear.
3928     break;
3929   }
3930
3931   // We require the RHS of the binop to be a constant and not opaque as well.
3932   ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
3933   if (!BinOpCst || BinOpCst->isOpaque()) return SDValue();
3934
3935   // FIXME: disable this unless the input to the binop is a shift by a constant.
3936   // If it is not a shift, it pessimizes some common cases like:
3937   //
3938   //    void foo(int *X, int i) { X[i & 1235] = 1; }
3939   //    int bar(int *X, int i) { return X[i & 255]; }
3940   SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
3941   if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
3942        BinOpLHSVal->getOpcode() != ISD::SRA &&
3943        BinOpLHSVal->getOpcode() != ISD::SRL) ||
3944       !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
3945     return SDValue();
3946
3947   EVT VT = N->getValueType(0);
3948
3949   // If this is a signed shift right, and the high bit is modified by the
3950   // logical operation, do not perform the transformation. The highBitSet
3951   // boolean indicates the value of the high bit of the constant which would
3952   // cause it to be modified for this operation.
3953   if (N->getOpcode() == ISD::SRA) {
3954     bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
3955     if (BinOpRHSSignSet != HighBitSet)
3956       return SDValue();
3957   }
3958
3959   if (!TLI.isDesirableToCommuteWithShift(LHS))
3960     return SDValue();
3961
3962   // Fold the constants, shifting the binop RHS by the shift amount.
3963   SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
3964                                N->getValueType(0),
3965                                LHS->getOperand(1), N->getOperand(1));
3966   assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
3967
3968   // Create the new shift.
3969   SDValue NewShift = DAG.getNode(N->getOpcode(),
3970                                  SDLoc(LHS->getOperand(0)),
3971                                  VT, LHS->getOperand(0), N->getOperand(1));
3972
3973   // Create the new binop.
3974   return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
3975 }
3976
3977 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
3978   assert(N->getOpcode() == ISD::TRUNCATE);
3979   assert(N->getOperand(0).getOpcode() == ISD::AND);
3980
3981   // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
3982   if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
3983     SDValue N01 = N->getOperand(0).getOperand(1);
3984
3985     if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
3986       EVT TruncVT = N->getValueType(0);
3987       SDValue N00 = N->getOperand(0).getOperand(0);
3988       APInt TruncC = N01C->getAPIntValue();
3989       TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
3990
3991       return DAG.getNode(ISD::AND, SDLoc(N), TruncVT,
3992                          DAG.getNode(ISD::TRUNCATE, SDLoc(N), TruncVT, N00),
3993                          DAG.getConstant(TruncC, TruncVT));
3994     }
3995   }
3996
3997   return SDValue();
3998 }
3999
4000 SDValue DAGCombiner::visitRotate(SDNode *N) {
4001   // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
4002   if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
4003       N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
4004     SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode());
4005     if (NewOp1.getNode())
4006       return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
4007                          N->getOperand(0), NewOp1);
4008   }
4009   return SDValue();
4010 }
4011
4012 SDValue DAGCombiner::visitSHL(SDNode *N) {
4013   SDValue N0 = N->getOperand(0);
4014   SDValue N1 = N->getOperand(1);
4015   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4016   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4017   EVT VT = N0.getValueType();
4018   unsigned OpSizeInBits = VT.getScalarSizeInBits();
4019
4020   // fold vector ops
4021   if (VT.isVector()) {
4022     SDValue FoldedVOp = SimplifyVBinOp(N);
4023     if (FoldedVOp.getNode()) return FoldedVOp;
4024
4025     BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
4026     // If setcc produces all-one true value then:
4027     // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
4028     if (N1CV && N1CV->isConstant()) {
4029       if (N0.getOpcode() == ISD::AND) {
4030         SDValue N00 = N0->getOperand(0);
4031         SDValue N01 = N0->getOperand(1);
4032         BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
4033
4034         if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
4035             TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
4036                 TargetLowering::ZeroOrNegativeOneBooleanContent) {
4037           SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, VT, N01CV, N1CV);
4038           if (C.getNode())
4039             return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
4040         }
4041       } else {
4042         N1C = isConstOrConstSplat(N1);
4043       }
4044     }
4045   }
4046
4047   // fold (shl c1, c2) -> c1<<c2
4048   if (N0C && N1C)
4049     return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
4050   // fold (shl 0, x) -> 0
4051   if (N0C && N0C->isNullValue())
4052     return N0;
4053   // fold (shl x, c >= size(x)) -> undef
4054   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4055     return DAG.getUNDEF(VT);
4056   // fold (shl x, 0) -> x
4057   if (N1C && N1C->isNullValue())
4058     return N0;
4059   // fold (shl undef, x) -> 0
4060   if (N0.getOpcode() == ISD::UNDEF)
4061     return DAG.getConstant(0, VT);
4062   // if (shl x, c) is known to be zero, return 0
4063   if (DAG.MaskedValueIsZero(SDValue(N, 0),
4064                             APInt::getAllOnesValue(OpSizeInBits)))
4065     return DAG.getConstant(0, VT);
4066   // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
4067   if (N1.getOpcode() == ISD::TRUNCATE &&
4068       N1.getOperand(0).getOpcode() == ISD::AND) {
4069     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4070     if (NewOp1.getNode())
4071       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
4072   }
4073
4074   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4075     return SDValue(N, 0);
4076
4077   // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
4078   if (N1C && N0.getOpcode() == ISD::SHL) {
4079     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4080       uint64_t c1 = N0C1->getZExtValue();
4081       uint64_t c2 = N1C->getZExtValue();
4082       if (c1 + c2 >= OpSizeInBits)
4083         return DAG.getConstant(0, VT);
4084       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4085                          DAG.getConstant(c1 + c2, N1.getValueType()));
4086     }
4087   }
4088
4089   // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4090   // For this to be valid, the second form must not preserve any of the bits
4091   // that are shifted out by the inner shift in the first form.  This means
4092   // the outer shift size must be >= the number of bits added by the ext.
4093   // As a corollary, we don't care what kind of ext it is.
4094   if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4095               N0.getOpcode() == ISD::ANY_EXTEND ||
4096               N0.getOpcode() == ISD::SIGN_EXTEND) &&
4097       N0.getOperand(0).getOpcode() == ISD::SHL) {
4098     SDValue N0Op0 = N0.getOperand(0);
4099     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4100       uint64_t c1 = N0Op0C1->getZExtValue();
4101       uint64_t c2 = N1C->getZExtValue();
4102       EVT InnerShiftVT = N0Op0.getValueType();
4103       uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4104       if (c2 >= OpSizeInBits - InnerShiftSize) {
4105         if (c1 + c2 >= OpSizeInBits)
4106           return DAG.getConstant(0, VT);
4107         return DAG.getNode(ISD::SHL, SDLoc(N0), VT,
4108                            DAG.getNode(N0.getOpcode(), SDLoc(N0), VT,
4109                                        N0Op0->getOperand(0)),
4110                            DAG.getConstant(c1 + c2, N1.getValueType()));
4111       }
4112     }
4113   }
4114
4115   // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4116   // Only fold this if the inner zext has no other uses to avoid increasing
4117   // the total number of instructions.
4118   if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
4119       N0.getOperand(0).getOpcode() == ISD::SRL) {
4120     SDValue N0Op0 = N0.getOperand(0);
4121     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4122       uint64_t c1 = N0Op0C1->getZExtValue();
4123       if (c1 < VT.getScalarSizeInBits()) {
4124         uint64_t c2 = N1C->getZExtValue();
4125         if (c1 == c2) {
4126           SDValue NewOp0 = N0.getOperand(0);
4127           EVT CountVT = NewOp0.getOperand(1).getValueType();
4128           SDValue NewSHL = DAG.getNode(ISD::SHL, SDLoc(N), NewOp0.getValueType(),
4129                                        NewOp0, DAG.getConstant(c2, CountVT));
4130           AddToWorklist(NewSHL.getNode());
4131           return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4132         }
4133       }
4134     }
4135   }
4136
4137   // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4138   //                               (and (srl x, (sub c1, c2), MASK)
4139   // Only fold this if the inner shift has no other uses -- if it does, folding
4140   // this will increase the total number of instructions.
4141   if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4142     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4143       uint64_t c1 = N0C1->getZExtValue();
4144       if (c1 < OpSizeInBits) {
4145         uint64_t c2 = N1C->getZExtValue();
4146         APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4147         SDValue Shift;
4148         if (c2 > c1) {
4149           Mask = Mask.shl(c2 - c1);
4150           Shift = DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4151                               DAG.getConstant(c2 - c1, N1.getValueType()));
4152         } else {
4153           Mask = Mask.lshr(c1 - c2);
4154           Shift = DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4155                               DAG.getConstant(c1 - c2, N1.getValueType()));
4156         }
4157         return DAG.getNode(ISD::AND, SDLoc(N0), VT, Shift,
4158                            DAG.getConstant(Mask, VT));
4159       }
4160     }
4161   }
4162   // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
4163   if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
4164     unsigned BitSize = VT.getScalarSizeInBits();
4165     SDValue HiBitsMask =
4166       DAG.getConstant(APInt::getHighBitsSet(BitSize,
4167                                             BitSize - N1C->getZExtValue()), VT);
4168     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4169                        HiBitsMask);
4170   }
4171
4172   if (N1C) {
4173     SDValue NewSHL = visitShiftByConstant(N, N1C);
4174     if (NewSHL.getNode())
4175       return NewSHL;
4176   }
4177
4178   return SDValue();
4179 }
4180
4181 SDValue DAGCombiner::visitSRA(SDNode *N) {
4182   SDValue N0 = N->getOperand(0);
4183   SDValue N1 = N->getOperand(1);
4184   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4185   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4186   EVT VT = N0.getValueType();
4187   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4188
4189   // fold vector ops
4190   if (VT.isVector()) {
4191     SDValue FoldedVOp = SimplifyVBinOp(N);
4192     if (FoldedVOp.getNode()) return FoldedVOp;
4193
4194     N1C = isConstOrConstSplat(N1);
4195   }
4196
4197   // fold (sra c1, c2) -> (sra c1, c2)
4198   if (N0C && N1C)
4199     return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
4200   // fold (sra 0, x) -> 0
4201   if (N0C && N0C->isNullValue())
4202     return N0;
4203   // fold (sra -1, x) -> -1
4204   if (N0C && N0C->isAllOnesValue())
4205     return N0;
4206   // fold (sra x, (setge c, size(x))) -> undef
4207   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4208     return DAG.getUNDEF(VT);
4209   // fold (sra x, 0) -> x
4210   if (N1C && N1C->isNullValue())
4211     return N0;
4212   // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4213   // sext_inreg.
4214   if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
4215     unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
4216     EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4217     if (VT.isVector())
4218       ExtVT = EVT::getVectorVT(*DAG.getContext(),
4219                                ExtVT, VT.getVectorNumElements());
4220     if ((!LegalOperations ||
4221          TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
4222       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
4223                          N0.getOperand(0), DAG.getValueType(ExtVT));
4224   }
4225
4226   // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
4227   if (N1C && N0.getOpcode() == ISD::SRA) {
4228     if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
4229       unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
4230       if (Sum >= OpSizeInBits)
4231         Sum = OpSizeInBits - 1;
4232       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0.getOperand(0),
4233                          DAG.getConstant(Sum, N1.getValueType()));
4234     }
4235   }
4236
4237   // fold (sra (shl X, m), (sub result_size, n))
4238   // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
4239   // result_size - n != m.
4240   // If truncate is free for the target sext(shl) is likely to result in better
4241   // code.
4242   if (N0.getOpcode() == ISD::SHL && N1C) {
4243     // Get the two constanst of the shifts, CN0 = m, CN = n.
4244     const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4245     if (N01C) {
4246       LLVMContext &Ctx = *DAG.getContext();
4247       // Determine what the truncate's result bitsize and type would be.
4248       EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4249
4250       if (VT.isVector())
4251         TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4252
4253       // Determine the residual right-shift amount.
4254       signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
4255
4256       // If the shift is not a no-op (in which case this should be just a sign
4257       // extend already), the truncated to type is legal, sign_extend is legal
4258       // on that type, and the truncate to that type is both legal and free,
4259       // perform the transform.
4260       if ((ShiftAmt > 0) &&
4261           TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4262           TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
4263           TLI.isTruncateFree(VT, TruncVT)) {
4264
4265           SDValue Amt = DAG.getConstant(ShiftAmt,
4266               getShiftAmountTy(N0.getOperand(0).getValueType()));
4267           SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), VT,
4268                                       N0.getOperand(0), Amt);
4269           SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), TruncVT,
4270                                       Shift);
4271           return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N),
4272                              N->getValueType(0), Trunc);
4273       }
4274     }
4275   }
4276
4277   // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
4278   if (N1.getOpcode() == ISD::TRUNCATE &&
4279       N1.getOperand(0).getOpcode() == ISD::AND) {
4280     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4281     if (NewOp1.getNode())
4282       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
4283   }
4284
4285   // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
4286   //      if c1 is equal to the number of bits the trunc removes
4287   if (N0.getOpcode() == ISD::TRUNCATE &&
4288       (N0.getOperand(0).getOpcode() == ISD::SRL ||
4289        N0.getOperand(0).getOpcode() == ISD::SRA) &&
4290       N0.getOperand(0).hasOneUse() &&
4291       N0.getOperand(0).getOperand(1).hasOneUse() &&
4292       N1C) {
4293     SDValue N0Op0 = N0.getOperand(0);
4294     if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4295       unsigned LargeShiftVal = LargeShift->getZExtValue();
4296       EVT LargeVT = N0Op0.getValueType();
4297
4298       if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4299         SDValue Amt =
4300           DAG.getConstant(LargeShiftVal + N1C->getZExtValue(),
4301                           getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4302         SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), LargeVT,
4303                                   N0Op0.getOperand(0), Amt);
4304         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, SRA);
4305       }
4306     }
4307   }
4308
4309   // Simplify, based on bits shifted out of the LHS.
4310   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4311     return SDValue(N, 0);
4312
4313
4314   // If the sign bit is known to be zero, switch this to a SRL.
4315   if (DAG.SignBitIsZero(N0))
4316     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
4317
4318   if (N1C) {
4319     SDValue NewSRA = visitShiftByConstant(N, N1C);
4320     if (NewSRA.getNode())
4321       return NewSRA;
4322   }
4323
4324   return SDValue();
4325 }
4326
4327 SDValue DAGCombiner::visitSRL(SDNode *N) {
4328   SDValue N0 = N->getOperand(0);
4329   SDValue N1 = N->getOperand(1);
4330   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4331   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4332   EVT VT = N0.getValueType();
4333   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4334
4335   // fold vector ops
4336   if (VT.isVector()) {
4337     SDValue FoldedVOp = SimplifyVBinOp(N);
4338     if (FoldedVOp.getNode()) return FoldedVOp;
4339
4340     N1C = isConstOrConstSplat(N1);
4341   }
4342
4343   // fold (srl c1, c2) -> c1 >>u c2
4344   if (N0C && N1C)
4345     return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C);
4346   // fold (srl 0, x) -> 0
4347   if (N0C && N0C->isNullValue())
4348     return N0;
4349   // fold (srl x, c >= size(x)) -> undef
4350   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4351     return DAG.getUNDEF(VT);
4352   // fold (srl x, 0) -> x
4353   if (N1C && N1C->isNullValue())
4354     return N0;
4355   // if (srl x, c) is known to be zero, return 0
4356   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4357                                    APInt::getAllOnesValue(OpSizeInBits)))
4358     return DAG.getConstant(0, VT);
4359
4360   // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
4361   if (N1C && N0.getOpcode() == ISD::SRL) {
4362     if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
4363       uint64_t c1 = N01C->getZExtValue();
4364       uint64_t c2 = N1C->getZExtValue();
4365       if (c1 + c2 >= OpSizeInBits)
4366         return DAG.getConstant(0, VT);
4367       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4368                          DAG.getConstant(c1 + c2, N1.getValueType()));
4369     }
4370   }
4371
4372   // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4373   if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4374       N0.getOperand(0).getOpcode() == ISD::SRL &&
4375       isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4376     uint64_t c1 =
4377       cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4378     uint64_t c2 = N1C->getZExtValue();
4379     EVT InnerShiftVT = N0.getOperand(0).getValueType();
4380     EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4381     uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
4382     // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4383     if (c1 + OpSizeInBits == InnerShiftSize) {
4384       if (c1 + c2 >= InnerShiftSize)
4385         return DAG.getConstant(0, VT);
4386       return DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT,
4387                          DAG.getNode(ISD::SRL, SDLoc(N0), InnerShiftVT,
4388                                      N0.getOperand(0)->getOperand(0),
4389                                      DAG.getConstant(c1 + c2, ShiftCountVT)));
4390     }
4391   }
4392
4393   // fold (srl (shl x, c), c) -> (and x, cst2)
4394   if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4395     unsigned BitSize = N0.getScalarValueSizeInBits();
4396     if (BitSize <= 64) {
4397       uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4398       return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4399                          DAG.getConstant(~0ULL >> ShAmt, VT));
4400     }
4401   }
4402
4403   // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4404   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4405     // Shifting in all undef bits?
4406     EVT SmallVT = N0.getOperand(0).getValueType();
4407     unsigned BitSize = SmallVT.getScalarSizeInBits();
4408     if (N1C->getZExtValue() >= BitSize)
4409       return DAG.getUNDEF(VT);
4410
4411     if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4412       uint64_t ShiftAmt = N1C->getZExtValue();
4413       SDValue SmallShift = DAG.getNode(ISD::SRL, SDLoc(N0), SmallVT,
4414                                        N0.getOperand(0),
4415                           DAG.getConstant(ShiftAmt, getShiftAmountTy(SmallVT)));
4416       AddToWorklist(SmallShift.getNode());
4417       APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
4418       return DAG.getNode(ISD::AND, SDLoc(N), VT,
4419                          DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, SmallShift),
4420                          DAG.getConstant(Mask, VT));
4421     }
4422   }
4423
4424   // fold (srl (sra X, Y), 31) -> (srl X, 31).  This srl only looks at the sign
4425   // bit, which is unmodified by sra.
4426   if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
4427     if (N0.getOpcode() == ISD::SRA)
4428       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4429   }
4430
4431   // fold (srl (ctlz x), "5") -> x  iff x has one bit set (the low bit).
4432   if (N1C && N0.getOpcode() == ISD::CTLZ &&
4433       N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
4434     APInt KnownZero, KnownOne;
4435     DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne);
4436
4437     // If any of the input bits are KnownOne, then the input couldn't be all
4438     // zeros, thus the result of the srl will always be zero.
4439     if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
4440
4441     // If all of the bits input the to ctlz node are known to be zero, then
4442     // the result of the ctlz is "32" and the result of the shift is one.
4443     APInt UnknownBits = ~KnownZero;
4444     if (UnknownBits == 0) return DAG.getConstant(1, VT);
4445
4446     // Otherwise, check to see if there is exactly one bit input to the ctlz.
4447     if ((UnknownBits & (UnknownBits - 1)) == 0) {
4448       // Okay, we know that only that the single bit specified by UnknownBits
4449       // could be set on input to the CTLZ node. If this bit is set, the SRL
4450       // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4451       // to an SRL/XOR pair, which is likely to simplify more.
4452       unsigned ShAmt = UnknownBits.countTrailingZeros();
4453       SDValue Op = N0.getOperand(0);
4454
4455       if (ShAmt) {
4456         Op = DAG.getNode(ISD::SRL, SDLoc(N0), VT, Op,
4457                   DAG.getConstant(ShAmt, getShiftAmountTy(Op.getValueType())));
4458         AddToWorklist(Op.getNode());
4459       }
4460
4461       return DAG.getNode(ISD::XOR, SDLoc(N), VT,
4462                          Op, DAG.getConstant(1, VT));
4463     }
4464   }
4465
4466   // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4467   if (N1.getOpcode() == ISD::TRUNCATE &&
4468       N1.getOperand(0).getOpcode() == ISD::AND) {
4469     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4470     if (NewOp1.getNode())
4471       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
4472   }
4473
4474   // fold operands of srl based on knowledge that the low bits are not
4475   // demanded.
4476   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4477     return SDValue(N, 0);
4478
4479   if (N1C) {
4480     SDValue NewSRL = visitShiftByConstant(N, N1C);
4481     if (NewSRL.getNode())
4482       return NewSRL;
4483   }
4484
4485   // Attempt to convert a srl of a load into a narrower zero-extending load.
4486   SDValue NarrowLoad = ReduceLoadWidth(N);
4487   if (NarrowLoad.getNode())
4488     return NarrowLoad;
4489
4490   // Here is a common situation. We want to optimize:
4491   //
4492   //   %a = ...
4493   //   %b = and i32 %a, 2
4494   //   %c = srl i32 %b, 1
4495   //   brcond i32 %c ...
4496   //
4497   // into
4498   //
4499   //   %a = ...
4500   //   %b = and %a, 2
4501   //   %c = setcc eq %b, 0
4502   //   brcond %c ...
4503   //
4504   // However when after the source operand of SRL is optimized into AND, the SRL
4505   // itself may not be optimized further. Look for it and add the BRCOND into
4506   // the worklist.
4507   if (N->hasOneUse()) {
4508     SDNode *Use = *N->use_begin();
4509     if (Use->getOpcode() == ISD::BRCOND)
4510       AddToWorklist(Use);
4511     else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4512       // Also look pass the truncate.
4513       Use = *Use->use_begin();
4514       if (Use->getOpcode() == ISD::BRCOND)
4515         AddToWorklist(Use);
4516     }
4517   }
4518
4519   return SDValue();
4520 }
4521
4522 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4523   SDValue N0 = N->getOperand(0);
4524   EVT VT = N->getValueType(0);
4525
4526   // fold (ctlz c1) -> c2
4527   if (isa<ConstantSDNode>(N0))
4528     return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
4529   return SDValue();
4530 }
4531
4532 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4533   SDValue N0 = N->getOperand(0);
4534   EVT VT = N->getValueType(0);
4535
4536   // fold (ctlz_zero_undef c1) -> c2
4537   if (isa<ConstantSDNode>(N0))
4538     return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4539   return SDValue();
4540 }
4541
4542 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4543   SDValue N0 = N->getOperand(0);
4544   EVT VT = N->getValueType(0);
4545
4546   // fold (cttz c1) -> c2
4547   if (isa<ConstantSDNode>(N0))
4548     return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
4549   return SDValue();
4550 }
4551
4552 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4553   SDValue N0 = N->getOperand(0);
4554   EVT VT = N->getValueType(0);
4555
4556   // fold (cttz_zero_undef c1) -> c2
4557   if (isa<ConstantSDNode>(N0))
4558     return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4559   return SDValue();
4560 }
4561
4562 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4563   SDValue N0 = N->getOperand(0);
4564   EVT VT = N->getValueType(0);
4565
4566   // fold (ctpop c1) -> c2
4567   if (isa<ConstantSDNode>(N0))
4568     return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
4569   return SDValue();
4570 }
4571
4572 SDValue DAGCombiner::visitSELECT(SDNode *N) {
4573   SDValue N0 = N->getOperand(0);
4574   SDValue N1 = N->getOperand(1);
4575   SDValue N2 = N->getOperand(2);
4576   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4577   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4578   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
4579   EVT VT = N->getValueType(0);
4580   EVT VT0 = N0.getValueType();
4581
4582   // fold (select C, X, X) -> X
4583   if (N1 == N2)
4584     return N1;
4585   // fold (select true, X, Y) -> X
4586   if (N0C && !N0C->isNullValue())
4587     return N1;
4588   // fold (select false, X, Y) -> Y
4589   if (N0C && N0C->isNullValue())
4590     return N2;
4591   // fold (select C, 1, X) -> (or C, X)
4592   if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
4593     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4594   // fold (select C, 0, 1) -> (xor C, 1)
4595   // We can't do this reliably if integer based booleans have different contents
4596   // to floating point based booleans. This is because we can't tell whether we
4597   // have an integer-based boolean or a floating-point-based boolean unless we
4598   // can find the SETCC that produced it and inspect its operands. This is
4599   // fairly easy if C is the SETCC node, but it can potentially be
4600   // undiscoverable (or not reasonably discoverable). For example, it could be
4601   // in another basic block or it could require searching a complicated
4602   // expression.
4603   if (VT.isInteger() &&
4604       (VT0 == MVT::i1 || (VT0.isInteger() &&
4605                           TLI.getBooleanContents(false, false) ==
4606                               TLI.getBooleanContents(false, true) &&
4607                           TLI.getBooleanContents(false, false) ==
4608                               TargetLowering::ZeroOrOneBooleanContent)) &&
4609       N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
4610     SDValue XORNode;
4611     if (VT == VT0)
4612       return DAG.getNode(ISD::XOR, SDLoc(N), VT0,
4613                          N0, DAG.getConstant(1, VT0));
4614     XORNode = DAG.getNode(ISD::XOR, SDLoc(N0), VT0,
4615                           N0, DAG.getConstant(1, VT0));
4616     AddToWorklist(XORNode.getNode());
4617     if (VT.bitsGT(VT0))
4618       return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4619     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
4620   }
4621   // fold (select C, 0, X) -> (and (not C), X)
4622   if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
4623     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4624     AddToWorklist(NOTNode.getNode());
4625     return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
4626   }
4627   // fold (select C, X, 1) -> (or (not C), X)
4628   if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
4629     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4630     AddToWorklist(NOTNode.getNode());
4631     return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
4632   }
4633   // fold (select C, X, 0) -> (and C, X)
4634   if (VT == MVT::i1 && N2C && N2C->isNullValue())
4635     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4636   // fold (select X, X, Y) -> (or X, Y)
4637   // fold (select X, 1, Y) -> (or X, Y)
4638   if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
4639     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4640   // fold (select X, Y, X) -> (and X, Y)
4641   // fold (select X, Y, 0) -> (and X, Y)
4642   if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
4643     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4644
4645   // If we can fold this based on the true/false value, do so.
4646   if (SimplifySelectOps(N, N1, N2))
4647     return SDValue(N, 0);  // Don't revisit N.
4648
4649   // fold selects based on a setcc into other things, such as min/max/abs
4650   if (N0.getOpcode() == ISD::SETCC) {
4651     if ((!LegalOperations &&
4652          TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
4653         TLI.isOperationLegal(ISD::SELECT_CC, VT))
4654       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
4655                          N0.getOperand(0), N0.getOperand(1),
4656                          N1, N2, N0.getOperand(2));
4657     return SimplifySelect(SDLoc(N), N0, N1, N2);
4658   }
4659
4660   return SDValue();
4661 }
4662
4663 static
4664 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
4665   SDLoc DL(N);
4666   EVT LoVT, HiVT;
4667   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
4668
4669   // Split the inputs.
4670   SDValue Lo, Hi, LL, LH, RL, RH;
4671   std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
4672   std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
4673
4674   Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
4675   Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
4676
4677   return std::make_pair(Lo, Hi);
4678 }
4679
4680 // This function assumes all the vselect's arguments are CONCAT_VECTOR
4681 // nodes and that the condition is a BV of ConstantSDNodes (or undefs).
4682 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
4683   SDLoc dl(N);
4684   SDValue Cond = N->getOperand(0);
4685   SDValue LHS = N->getOperand(1);
4686   SDValue RHS = N->getOperand(2);
4687   EVT VT = N->getValueType(0);
4688   int NumElems = VT.getVectorNumElements();
4689   assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
4690          RHS.getOpcode() == ISD::CONCAT_VECTORS &&
4691          Cond.getOpcode() == ISD::BUILD_VECTOR);
4692
4693   // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about
4694   // binary ones here.
4695   if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2)
4696     return SDValue();
4697
4698   // We're sure we have an even number of elements due to the
4699   // concat_vectors we have as arguments to vselect.
4700   // Skip BV elements until we find one that's not an UNDEF
4701   // After we find an UNDEF element, keep looping until we get to half the
4702   // length of the BV and see if all the non-undef nodes are the same.
4703   ConstantSDNode *BottomHalf = nullptr;
4704   for (int i = 0; i < NumElems / 2; ++i) {
4705     if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
4706       continue;
4707
4708     if (BottomHalf == nullptr)
4709       BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
4710     else if (Cond->getOperand(i).getNode() != BottomHalf)
4711       return SDValue();
4712   }
4713
4714   // Do the same for the second half of the BuildVector
4715   ConstantSDNode *TopHalf = nullptr;
4716   for (int i = NumElems / 2; i < NumElems; ++i) {
4717     if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
4718       continue;
4719
4720     if (TopHalf == nullptr)
4721       TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
4722     else if (Cond->getOperand(i).getNode() != TopHalf)
4723       return SDValue();
4724   }
4725
4726   assert(TopHalf && BottomHalf &&
4727          "One half of the selector was all UNDEFs and the other was all the "
4728          "same value. This should have been addressed before this function.");
4729   return DAG.getNode(
4730       ISD::CONCAT_VECTORS, dl, VT,
4731       BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
4732       TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
4733 }
4734
4735 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
4736   SDValue N0 = N->getOperand(0);
4737   SDValue N1 = N->getOperand(1);
4738   SDValue N2 = N->getOperand(2);
4739   SDLoc DL(N);
4740
4741   // Canonicalize integer abs.
4742   // vselect (setg[te] X,  0),  X, -X ->
4743   // vselect (setgt    X, -1),  X, -X ->
4744   // vselect (setl[te] X,  0), -X,  X ->
4745   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
4746   if (N0.getOpcode() == ISD::SETCC) {
4747     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4748     ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4749     bool isAbs = false;
4750     bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
4751
4752     if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
4753          (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
4754         N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
4755       isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
4756     else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
4757              N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
4758       isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
4759
4760     if (isAbs) {
4761       EVT VT = LHS.getValueType();
4762       SDValue Shift = DAG.getNode(
4763           ISD::SRA, DL, VT, LHS,
4764           DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, VT));
4765       SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
4766       AddToWorklist(Shift.getNode());
4767       AddToWorklist(Add.getNode());
4768       return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
4769     }
4770   }
4771
4772   // If the VSELECT result requires splitting and the mask is provided by a
4773   // SETCC, then split both nodes and its operands before legalization. This
4774   // prevents the type legalizer from unrolling SETCC into scalar comparisons
4775   // and enables future optimizations (e.g. min/max pattern matching on X86).
4776   if (N0.getOpcode() == ISD::SETCC) {
4777     EVT VT = N->getValueType(0);
4778
4779     // Check if any splitting is required.
4780     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
4781         TargetLowering::TypeSplitVector)
4782       return SDValue();
4783
4784     SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
4785     std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
4786     std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
4787     std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
4788
4789     Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
4790     Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
4791
4792     // Add the new VSELECT nodes to the work list in case they need to be split
4793     // again.
4794     AddToWorklist(Lo.getNode());
4795     AddToWorklist(Hi.getNode());
4796
4797     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
4798   }
4799
4800   // Fold (vselect (build_vector all_ones), N1, N2) -> N1
4801   if (ISD::isBuildVectorAllOnes(N0.getNode()))
4802     return N1;
4803   // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
4804   if (ISD::isBuildVectorAllZeros(N0.getNode()))
4805     return N2;
4806
4807   // The ConvertSelectToConcatVector function is assuming both the above
4808   // checks for (vselect (build_vector all{ones,zeros) ...) have been made
4809   // and addressed.
4810   if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
4811       N2.getOpcode() == ISD::CONCAT_VECTORS &&
4812       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
4813     SDValue CV = ConvertSelectToConcatVector(N, DAG);
4814     if (CV.getNode())
4815       return CV;
4816   }
4817
4818   return SDValue();
4819 }
4820
4821 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
4822   SDValue N0 = N->getOperand(0);
4823   SDValue N1 = N->getOperand(1);
4824   SDValue N2 = N->getOperand(2);
4825   SDValue N3 = N->getOperand(3);
4826   SDValue N4 = N->getOperand(4);
4827   ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
4828
4829   // fold select_cc lhs, rhs, x, x, cc -> x
4830   if (N2 == N3)
4831     return N2;
4832
4833   // Determine if the condition we're dealing with is constant
4834   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
4835                               N0, N1, CC, SDLoc(N), false);
4836   if (SCC.getNode()) {
4837     AddToWorklist(SCC.getNode());
4838
4839     if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
4840       if (!SCCC->isNullValue())
4841         return N2;    // cond always true -> true val
4842       else
4843         return N3;    // cond always false -> false val
4844     }
4845
4846     // Fold to a simpler select_cc
4847     if (SCC.getOpcode() == ISD::SETCC)
4848       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
4849                          SCC.getOperand(0), SCC.getOperand(1), N2, N3,
4850                          SCC.getOperand(2));
4851   }
4852
4853   // If we can fold this based on the true/false value, do so.
4854   if (SimplifySelectOps(N, N2, N3))
4855     return SDValue(N, 0);  // Don't revisit N.
4856
4857   // fold select_cc into other things, such as min/max/abs
4858   return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
4859 }
4860
4861 SDValue DAGCombiner::visitSETCC(SDNode *N) {
4862   return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
4863                        cast<CondCodeSDNode>(N->getOperand(2))->get(),
4864                        SDLoc(N));
4865 }
4866
4867 // tryToFoldExtendOfConstant - Try to fold a sext/zext/aext
4868 // dag node into a ConstantSDNode or a build_vector of constants.
4869 // This function is called by the DAGCombiner when visiting sext/zext/aext
4870 // dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
4871 // Vector extends are not folded if operations are legal; this is to
4872 // avoid introducing illegal build_vector dag nodes.
4873 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
4874                                          SelectionDAG &DAG, bool LegalTypes,
4875                                          bool LegalOperations) {
4876   unsigned Opcode = N->getOpcode();
4877   SDValue N0 = N->getOperand(0);
4878   EVT VT = N->getValueType(0);
4879
4880   assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
4881          Opcode == ISD::ANY_EXTEND) && "Expected EXTEND dag node in input!");
4882
4883   // fold (sext c1) -> c1
4884   // fold (zext c1) -> c1
4885   // fold (aext c1) -> c1
4886   if (isa<ConstantSDNode>(N0))
4887     return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
4888
4889   // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
4890   // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
4891   // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
4892   EVT SVT = VT.getScalarType();
4893   if (!(VT.isVector() &&
4894       (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
4895       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
4896     return nullptr;
4897
4898   // We can fold this node into a build_vector.
4899   unsigned VTBits = SVT.getSizeInBits();
4900   unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
4901   unsigned ShAmt = VTBits - EVTBits;
4902   SmallVector<SDValue, 8> Elts;
4903   unsigned NumElts = N0->getNumOperands();
4904   SDLoc DL(N);
4905
4906   for (unsigned i=0; i != NumElts; ++i) {
4907     SDValue Op = N0->getOperand(i);
4908     if (Op->getOpcode() == ISD::UNDEF) {
4909       Elts.push_back(DAG.getUNDEF(SVT));
4910       continue;
4911     }
4912
4913     ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
4914     const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
4915     if (Opcode == ISD::SIGN_EXTEND)
4916       Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
4917                                      SVT));
4918     else
4919       Elts.push_back(DAG.getConstant(C.shl(ShAmt).lshr(ShAmt).getZExtValue(),
4920                                      SVT));
4921   }
4922
4923   return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts).getNode();
4924 }
4925
4926 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
4927 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
4928 // transformation. Returns true if extension are possible and the above
4929 // mentioned transformation is profitable.
4930 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
4931                                     unsigned ExtOpc,
4932                                     SmallVectorImpl<SDNode *> &ExtendNodes,
4933                                     const TargetLowering &TLI) {
4934   bool HasCopyToRegUses = false;
4935   bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
4936   for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
4937                             UE = N0.getNode()->use_end();
4938        UI != UE; ++UI) {
4939     SDNode *User = *UI;
4940     if (User == N)
4941       continue;
4942     if (UI.getUse().getResNo() != N0.getResNo())
4943       continue;
4944     // FIXME: Only extend SETCC N, N and SETCC N, c for now.
4945     if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
4946       ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
4947       if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
4948         // Sign bits will be lost after a zext.
4949         return false;
4950       bool Add = false;
4951       for (unsigned i = 0; i != 2; ++i) {
4952         SDValue UseOp = User->getOperand(i);
4953         if (UseOp == N0)
4954           continue;
4955         if (!isa<ConstantSDNode>(UseOp))
4956           return false;
4957         Add = true;
4958       }
4959       if (Add)
4960         ExtendNodes.push_back(User);
4961       continue;
4962     }
4963     // If truncates aren't free and there are users we can't
4964     // extend, it isn't worthwhile.
4965     if (!isTruncFree)
4966       return false;
4967     // Remember if this value is live-out.
4968     if (User->getOpcode() == ISD::CopyToReg)
4969       HasCopyToRegUses = true;
4970   }
4971
4972   if (HasCopyToRegUses) {
4973     bool BothLiveOut = false;
4974     for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
4975          UI != UE; ++UI) {
4976       SDUse &Use = UI.getUse();
4977       if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
4978         BothLiveOut = true;
4979         break;
4980       }
4981     }
4982     if (BothLiveOut)
4983       // Both unextended and extended values are live out. There had better be
4984       // a good reason for the transformation.
4985       return ExtendNodes.size();
4986   }
4987   return true;
4988 }
4989
4990 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
4991                                   SDValue Trunc, SDValue ExtLoad, SDLoc DL,
4992                                   ISD::NodeType ExtType) {
4993   // Extend SetCC uses if necessary.
4994   for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
4995     SDNode *SetCC = SetCCs[i];
4996     SmallVector<SDValue, 4> Ops;
4997
4998     for (unsigned j = 0; j != 2; ++j) {
4999       SDValue SOp = SetCC->getOperand(j);
5000       if (SOp == Trunc)
5001         Ops.push_back(ExtLoad);
5002       else
5003         Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
5004     }
5005
5006     Ops.push_back(SetCC->getOperand(2));
5007     CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
5008   }
5009 }
5010
5011 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
5012   SDValue N0 = N->getOperand(0);
5013   EVT VT = N->getValueType(0);
5014
5015   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5016                                               LegalOperations))
5017     return SDValue(Res, 0);
5018
5019   // fold (sext (sext x)) -> (sext x)
5020   // fold (sext (aext x)) -> (sext x)
5021   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5022     return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
5023                        N0.getOperand(0));
5024
5025   if (N0.getOpcode() == ISD::TRUNCATE) {
5026     // fold (sext (truncate (load x))) -> (sext (smaller load x))
5027     // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
5028     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5029     if (NarrowLoad.getNode()) {
5030       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5031       if (NarrowLoad.getNode() != N0.getNode()) {
5032         CombineTo(N0.getNode(), NarrowLoad);
5033         // CombineTo deleted the truncate, if needed, but not what's under it.
5034         AddToWorklist(oye);
5035       }
5036       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5037     }
5038
5039     // See if the value being truncated is already sign extended.  If so, just
5040     // eliminate the trunc/sext pair.
5041     SDValue Op = N0.getOperand(0);
5042     unsigned OpBits   = Op.getValueType().getScalarType().getSizeInBits();
5043     unsigned MidBits  = N0.getValueType().getScalarType().getSizeInBits();
5044     unsigned DestBits = VT.getScalarType().getSizeInBits();
5045     unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
5046
5047     if (OpBits == DestBits) {
5048       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
5049       // bits, it is already ready.
5050       if (NumSignBits > DestBits-MidBits)
5051         return Op;
5052     } else if (OpBits < DestBits) {
5053       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
5054       // bits, just sext from i32.
5055       if (NumSignBits > OpBits-MidBits)
5056         return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
5057     } else {
5058       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
5059       // bits, just truncate to i32.
5060       if (NumSignBits > OpBits-MidBits)
5061         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5062     }
5063
5064     // fold (sext (truncate x)) -> (sextinreg x).
5065     if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
5066                                                  N0.getValueType())) {
5067       if (OpBits < DestBits)
5068         Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
5069       else if (OpBits > DestBits)
5070         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
5071       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
5072                          DAG.getValueType(N0.getValueType()));
5073     }
5074   }
5075
5076   // fold (sext (load x)) -> (sext (truncate (sextload x)))
5077   // None of the supported targets knows how to perform load and sign extend
5078   // on vectors in one instruction.  We only perform this transformation on
5079   // scalars.
5080   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5081       ISD::isUNINDEXEDLoad(N0.getNode()) &&
5082       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5083        TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()))) {
5084     bool DoXform = true;
5085     SmallVector<SDNode*, 4> SetCCs;
5086     if (!N0.hasOneUse())
5087       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
5088     if (DoXform) {
5089       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5090       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5091                                        LN0->getChain(),
5092                                        LN0->getBasePtr(), N0.getValueType(),
5093                                        LN0->getMemOperand());
5094       CombineTo(N, ExtLoad);
5095       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5096                                   N0.getValueType(), ExtLoad);
5097       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5098       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5099                       ISD::SIGN_EXTEND);
5100       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5101     }
5102   }
5103
5104   // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
5105   // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
5106   if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5107       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5108     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5109     EVT MemVT = LN0->getMemoryVT();
5110     if ((!LegalOperations && !LN0->isVolatile()) ||
5111         TLI.isLoadExtLegal(ISD::SEXTLOAD, MemVT)) {
5112       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5113                                        LN0->getChain(),
5114                                        LN0->getBasePtr(), MemVT,
5115                                        LN0->getMemOperand());
5116       CombineTo(N, ExtLoad);
5117       CombineTo(N0.getNode(),
5118                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5119                             N0.getValueType(), ExtLoad),
5120                 ExtLoad.getValue(1));
5121       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5122     }
5123   }
5124
5125   // fold (sext (and/or/xor (load x), cst)) ->
5126   //      (and/or/xor (sextload x), (sext cst))
5127   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5128        N0.getOpcode() == ISD::XOR) &&
5129       isa<LoadSDNode>(N0.getOperand(0)) &&
5130       N0.getOperand(1).getOpcode() == ISD::Constant &&
5131       TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()) &&
5132       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5133     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5134     if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
5135       bool DoXform = true;
5136       SmallVector<SDNode*, 4> SetCCs;
5137       if (!N0.hasOneUse())
5138         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
5139                                           SetCCs, TLI);
5140       if (DoXform) {
5141         SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
5142                                          LN0->getChain(), LN0->getBasePtr(),
5143                                          LN0->getMemoryVT(),
5144                                          LN0->getMemOperand());
5145         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5146         Mask = Mask.sext(VT.getSizeInBits());
5147         SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5148                                   ExtLoad, DAG.getConstant(Mask, VT));
5149         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5150                                     SDLoc(N0.getOperand(0)),
5151                                     N0.getOperand(0).getValueType(), ExtLoad);
5152         CombineTo(N, And);
5153         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5154         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5155                         ISD::SIGN_EXTEND);
5156         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5157       }
5158     }
5159   }
5160
5161   if (N0.getOpcode() == ISD::SETCC) {
5162     EVT N0VT = N0.getOperand(0).getValueType();
5163     // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
5164     // Only do this before legalize for now.
5165     if (VT.isVector() && !LegalOperations &&
5166         TLI.getBooleanContents(N0VT) ==
5167             TargetLowering::ZeroOrNegativeOneBooleanContent) {
5168       // On some architectures (such as SSE/NEON/etc) the SETCC result type is
5169       // of the same size as the compared operands. Only optimize sext(setcc())
5170       // if this is the case.
5171       EVT SVT = getSetCCResultType(N0VT);
5172
5173       // We know that the # elements of the results is the same as the
5174       // # elements of the compare (and the # elements of the compare result
5175       // for that matter).  Check to see that they are the same size.  If so,
5176       // we know that the element size of the sext'd result matches the
5177       // element size of the compare operands.
5178       if (VT.getSizeInBits() == SVT.getSizeInBits())
5179         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5180                              N0.getOperand(1),
5181                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
5182
5183       // If the desired elements are smaller or larger than the source
5184       // elements we can use a matching integer vector type and then
5185       // truncate/sign extend
5186       EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5187       if (SVT == MatchingVectorType) {
5188         SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
5189                                N0.getOperand(0), N0.getOperand(1),
5190                                cast<CondCodeSDNode>(N0.getOperand(2))->get());
5191         return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
5192       }
5193     }
5194
5195     // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
5196     unsigned ElementWidth = VT.getScalarType().getSizeInBits();
5197     SDValue NegOne =
5198       DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT);
5199     SDValue SCC =
5200       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5201                        NegOne, DAG.getConstant(0, VT),
5202                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5203     if (SCC.getNode()) return SCC;
5204
5205     if (!VT.isVector()) {
5206       EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
5207       if (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, SetCCVT)) {
5208         SDLoc DL(N);
5209         ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5210         SDValue SetCC = DAG.getSetCC(DL,
5211                                      SetCCVT,
5212                                      N0.getOperand(0), N0.getOperand(1), CC);
5213         EVT SelectVT = getSetCCResultType(VT);
5214         return DAG.getSelect(DL, VT,
5215                              DAG.getSExtOrTrunc(SetCC, DL, SelectVT),
5216                              NegOne, DAG.getConstant(0, VT));
5217
5218       }
5219     }
5220   }
5221
5222   // fold (sext x) -> (zext x) if the sign bit is known zero.
5223   if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
5224       DAG.SignBitIsZero(N0))
5225     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
5226
5227   return SDValue();
5228 }
5229
5230 // isTruncateOf - If N is a truncate of some other value, return true, record
5231 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
5232 // This function computes KnownZero to avoid a duplicated call to
5233 // computeKnownBits in the caller.
5234 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
5235                          APInt &KnownZero) {
5236   APInt KnownOne;
5237   if (N->getOpcode() == ISD::TRUNCATE) {
5238     Op = N->getOperand(0);
5239     DAG.computeKnownBits(Op, KnownZero, KnownOne);
5240     return true;
5241   }
5242
5243   if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
5244       cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
5245     return false;
5246
5247   SDValue Op0 = N->getOperand(0);
5248   SDValue Op1 = N->getOperand(1);
5249   assert(Op0.getValueType() == Op1.getValueType());
5250
5251   ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0);
5252   ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
5253   if (COp0 && COp0->isNullValue())
5254     Op = Op1;
5255   else if (COp1 && COp1->isNullValue())
5256     Op = Op0;
5257   else
5258     return false;
5259
5260   DAG.computeKnownBits(Op, KnownZero, KnownOne);
5261
5262   if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
5263     return false;
5264
5265   return true;
5266 }
5267
5268 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
5269   SDValue N0 = N->getOperand(0);
5270   EVT VT = N->getValueType(0);
5271
5272   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5273                                               LegalOperations))
5274     return SDValue(Res, 0);
5275
5276   // fold (zext (zext x)) -> (zext x)
5277   // fold (zext (aext x)) -> (zext x)
5278   if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5279     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
5280                        N0.getOperand(0));
5281
5282   // fold (zext (truncate x)) -> (zext x) or
5283   //      (zext (truncate x)) -> (truncate x)
5284   // This is valid when the truncated bits of x are already zero.
5285   // FIXME: We should extend this to work for vectors too.
5286   SDValue Op;
5287   APInt KnownZero;
5288   if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
5289     APInt TruncatedBits =
5290       (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
5291       APInt(Op.getValueSizeInBits(), 0) :
5292       APInt::getBitsSet(Op.getValueSizeInBits(),
5293                         N0.getValueSizeInBits(),
5294                         std::min(Op.getValueSizeInBits(),
5295                                  VT.getSizeInBits()));
5296     if (TruncatedBits == (KnownZero & TruncatedBits)) {
5297       if (VT.bitsGT(Op.getValueType()))
5298         return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
5299       if (VT.bitsLT(Op.getValueType()))
5300         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5301
5302       return Op;
5303     }
5304   }
5305
5306   // fold (zext (truncate (load x))) -> (zext (smaller load x))
5307   // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
5308   if (N0.getOpcode() == ISD::TRUNCATE) {
5309     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5310     if (NarrowLoad.getNode()) {
5311       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5312       if (NarrowLoad.getNode() != N0.getNode()) {
5313         CombineTo(N0.getNode(), NarrowLoad);
5314         // CombineTo deleted the truncate, if needed, but not what's under it.
5315         AddToWorklist(oye);
5316       }
5317       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5318     }
5319   }
5320
5321   // fold (zext (truncate x)) -> (and x, mask)
5322   if (N0.getOpcode() == ISD::TRUNCATE &&
5323       (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
5324
5325     // fold (zext (truncate (load x))) -> (zext (smaller load x))
5326     // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
5327     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5328     if (NarrowLoad.getNode()) {
5329       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5330       if (NarrowLoad.getNode() != N0.getNode()) {
5331         CombineTo(N0.getNode(), NarrowLoad);
5332         // CombineTo deleted the truncate, if needed, but not what's under it.
5333         AddToWorklist(oye);
5334       }
5335       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5336     }
5337
5338     SDValue Op = N0.getOperand(0);
5339     if (Op.getValueType().bitsLT(VT)) {
5340       Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
5341       AddToWorklist(Op.getNode());
5342     } else if (Op.getValueType().bitsGT(VT)) {
5343       Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5344       AddToWorklist(Op.getNode());
5345     }
5346     return DAG.getZeroExtendInReg(Op, SDLoc(N),
5347                                   N0.getValueType().getScalarType());
5348   }
5349
5350   // Fold (zext (and (trunc x), cst)) -> (and x, cst),
5351   // if either of the casts is not free.
5352   if (N0.getOpcode() == ISD::AND &&
5353       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5354       N0.getOperand(1).getOpcode() == ISD::Constant &&
5355       (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5356                            N0.getValueType()) ||
5357        !TLI.isZExtFree(N0.getValueType(), VT))) {
5358     SDValue X = N0.getOperand(0).getOperand(0);
5359     if (X.getValueType().bitsLT(VT)) {
5360       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
5361     } else if (X.getValueType().bitsGT(VT)) {
5362       X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
5363     }
5364     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5365     Mask = Mask.zext(VT.getSizeInBits());
5366     return DAG.getNode(ISD::AND, SDLoc(N), VT,
5367                        X, DAG.getConstant(Mask, VT));
5368   }
5369
5370   // fold (zext (load x)) -> (zext (truncate (zextload x)))
5371   // None of the supported targets knows how to perform load and vector_zext
5372   // on vectors in one instruction.  We only perform this transformation on
5373   // scalars.
5374   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5375       ISD::isUNINDEXEDLoad(N0.getNode()) &&
5376       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5377        TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()))) {
5378     bool DoXform = true;
5379     SmallVector<SDNode*, 4> SetCCs;
5380     if (!N0.hasOneUse())
5381       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
5382     if (DoXform) {
5383       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5384       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5385                                        LN0->getChain(),
5386                                        LN0->getBasePtr(), N0.getValueType(),
5387                                        LN0->getMemOperand());
5388       CombineTo(N, ExtLoad);
5389       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5390                                   N0.getValueType(), ExtLoad);
5391       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5392
5393       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5394                       ISD::ZERO_EXTEND);
5395       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5396     }
5397   }
5398
5399   // fold (zext (and/or/xor (load x), cst)) ->
5400   //      (and/or/xor (zextload x), (zext cst))
5401   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5402        N0.getOpcode() == ISD::XOR) &&
5403       isa<LoadSDNode>(N0.getOperand(0)) &&
5404       N0.getOperand(1).getOpcode() == ISD::Constant &&
5405       TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()) &&
5406       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5407     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5408     if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
5409       bool DoXform = true;
5410       SmallVector<SDNode*, 4> SetCCs;
5411       if (!N0.hasOneUse())
5412         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
5413                                           SetCCs, TLI);
5414       if (DoXform) {
5415         SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
5416                                          LN0->getChain(), LN0->getBasePtr(),
5417                                          LN0->getMemoryVT(),
5418                                          LN0->getMemOperand());
5419         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5420         Mask = Mask.zext(VT.getSizeInBits());
5421         SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5422                                   ExtLoad, DAG.getConstant(Mask, VT));
5423         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5424                                     SDLoc(N0.getOperand(0)),
5425                                     N0.getOperand(0).getValueType(), ExtLoad);
5426         CombineTo(N, And);
5427         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5428         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5429                         ISD::ZERO_EXTEND);
5430         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5431       }
5432     }
5433   }
5434
5435   // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
5436   // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
5437   if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5438       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5439     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5440     EVT MemVT = LN0->getMemoryVT();
5441     if ((!LegalOperations && !LN0->isVolatile()) ||
5442         TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT)) {
5443       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5444                                        LN0->getChain(),
5445                                        LN0->getBasePtr(), MemVT,
5446                                        LN0->getMemOperand());
5447       CombineTo(N, ExtLoad);
5448       CombineTo(N0.getNode(),
5449                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
5450                             ExtLoad),
5451                 ExtLoad.getValue(1));
5452       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5453     }
5454   }
5455
5456   if (N0.getOpcode() == ISD::SETCC) {
5457     if (!LegalOperations && VT.isVector() &&
5458         N0.getValueType().getVectorElementType() == MVT::i1) {
5459       EVT N0VT = N0.getOperand(0).getValueType();
5460       if (getSetCCResultType(N0VT) == N0.getValueType())
5461         return SDValue();
5462
5463       // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
5464       // Only do this before legalize for now.
5465       EVT EltVT = VT.getVectorElementType();
5466       SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
5467                                     DAG.getConstant(1, EltVT));
5468       if (VT.getSizeInBits() == N0VT.getSizeInBits())
5469         // We know that the # elements of the results is the same as the
5470         // # elements of the compare (and the # elements of the compare result
5471         // for that matter).  Check to see that they are the same size.  If so,
5472         // we know that the element size of the sext'd result matches the
5473         // element size of the compare operands.
5474         return DAG.getNode(ISD::AND, SDLoc(N), VT,
5475                            DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5476                                          N0.getOperand(1),
5477                                  cast<CondCodeSDNode>(N0.getOperand(2))->get()),
5478                            DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
5479                                        OneOps));
5480
5481       // If the desired elements are smaller or larger than the source
5482       // elements we can use a matching integer vector type and then
5483       // truncate/sign extend
5484       EVT MatchingElementType =
5485         EVT::getIntegerVT(*DAG.getContext(),
5486                           N0VT.getScalarType().getSizeInBits());
5487       EVT MatchingVectorType =
5488         EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
5489                          N0VT.getVectorNumElements());
5490       SDValue VsetCC =
5491         DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5492                       N0.getOperand(1),
5493                       cast<CondCodeSDNode>(N0.getOperand(2))->get());
5494       return DAG.getNode(ISD::AND, SDLoc(N), VT,
5495                          DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT),
5496                          DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, OneOps));
5497     }
5498
5499     // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5500     SDValue SCC =
5501       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5502                        DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5503                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5504     if (SCC.getNode()) return SCC;
5505   }
5506
5507   // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
5508   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
5509       isa<ConstantSDNode>(N0.getOperand(1)) &&
5510       N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
5511       N0.hasOneUse()) {
5512     SDValue ShAmt = N0.getOperand(1);
5513     unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
5514     if (N0.getOpcode() == ISD::SHL) {
5515       SDValue InnerZExt = N0.getOperand(0);
5516       // If the original shl may be shifting out bits, do not perform this
5517       // transformation.
5518       unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
5519         InnerZExt.getOperand(0).getValueType().getSizeInBits();
5520       if (ShAmtVal > KnownZeroBits)
5521         return SDValue();
5522     }
5523
5524     SDLoc DL(N);
5525
5526     // Ensure that the shift amount is wide enough for the shifted value.
5527     if (VT.getSizeInBits() >= 256)
5528       ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
5529
5530     return DAG.getNode(N0.getOpcode(), DL, VT,
5531                        DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
5532                        ShAmt);
5533   }
5534
5535   return SDValue();
5536 }
5537
5538 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
5539   SDValue N0 = N->getOperand(0);
5540   EVT VT = N->getValueType(0);
5541
5542   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5543                                               LegalOperations))
5544     return SDValue(Res, 0);
5545
5546   // fold (aext (aext x)) -> (aext x)
5547   // fold (aext (zext x)) -> (zext x)
5548   // fold (aext (sext x)) -> (sext x)
5549   if (N0.getOpcode() == ISD::ANY_EXTEND  ||
5550       N0.getOpcode() == ISD::ZERO_EXTEND ||
5551       N0.getOpcode() == ISD::SIGN_EXTEND)
5552     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
5553
5554   // fold (aext (truncate (load x))) -> (aext (smaller load x))
5555   // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
5556   if (N0.getOpcode() == ISD::TRUNCATE) {
5557     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5558     if (NarrowLoad.getNode()) {
5559       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5560       if (NarrowLoad.getNode() != N0.getNode()) {
5561         CombineTo(N0.getNode(), NarrowLoad);
5562         // CombineTo deleted the truncate, if needed, but not what's under it.
5563         AddToWorklist(oye);
5564       }
5565       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5566     }
5567   }
5568
5569   // fold (aext (truncate x))
5570   if (N0.getOpcode() == ISD::TRUNCATE) {
5571     SDValue TruncOp = N0.getOperand(0);
5572     if (TruncOp.getValueType() == VT)
5573       return TruncOp; // x iff x size == zext size.
5574     if (TruncOp.getValueType().bitsGT(VT))
5575       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
5576     return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
5577   }
5578
5579   // Fold (aext (and (trunc x), cst)) -> (and x, cst)
5580   // if the trunc is not free.
5581   if (N0.getOpcode() == ISD::AND &&
5582       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5583       N0.getOperand(1).getOpcode() == ISD::Constant &&
5584       !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5585                           N0.getValueType())) {
5586     SDValue X = N0.getOperand(0).getOperand(0);
5587     if (X.getValueType().bitsLT(VT)) {
5588       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
5589     } else if (X.getValueType().bitsGT(VT)) {
5590       X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
5591     }
5592     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5593     Mask = Mask.zext(VT.getSizeInBits());
5594     return DAG.getNode(ISD::AND, SDLoc(N), VT,
5595                        X, DAG.getConstant(Mask, VT));
5596   }
5597
5598   // fold (aext (load x)) -> (aext (truncate (extload x)))
5599   // None of the supported targets knows how to perform load and any_ext
5600   // on vectors in one instruction.  We only perform this transformation on
5601   // scalars.
5602   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5603       ISD::isUNINDEXEDLoad(N0.getNode()) &&
5604       TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType())) {
5605     bool DoXform = true;
5606     SmallVector<SDNode*, 4> SetCCs;
5607     if (!N0.hasOneUse())
5608       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
5609     if (DoXform) {
5610       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5611       SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, 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::ANY_EXTEND);
5621       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5622     }
5623   }
5624
5625   // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
5626   // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
5627   // fold (aext ( extload x)) -> (aext (truncate (extload  x)))
5628   if (N0.getOpcode() == ISD::LOAD &&
5629       !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5630       N0.hasOneUse()) {
5631     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5632     ISD::LoadExtType ExtType = LN0->getExtensionType();
5633     EVT MemVT = LN0->getMemoryVT();
5634     if (!LegalOperations || TLI.isLoadExtLegal(ExtType, MemVT)) {
5635       SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
5636                                        VT, LN0->getChain(), LN0->getBasePtr(),
5637                                        MemVT, LN0->getMemOperand());
5638       CombineTo(N, ExtLoad);
5639       CombineTo(N0.getNode(),
5640                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5641                             N0.getValueType(), ExtLoad),
5642                 ExtLoad.getValue(1));
5643       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5644     }
5645   }
5646
5647   if (N0.getOpcode() == ISD::SETCC) {
5648     // For vectors:
5649     // aext(setcc) -> vsetcc
5650     // aext(setcc) -> truncate(vsetcc)
5651     // aext(setcc) -> aext(vsetcc)
5652     // Only do this before legalize for now.
5653     if (VT.isVector() && !LegalOperations) {
5654       EVT N0VT = N0.getOperand(0).getValueType();
5655         // We know that the # elements of the results is the same as the
5656         // # elements of the compare (and the # elements of the compare result
5657         // for that matter).  Check to see that they are the same size.  If so,
5658         // we know that the element size of the sext'd result matches the
5659         // element size of the compare operands.
5660       if (VT.getSizeInBits() == N0VT.getSizeInBits())
5661         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5662                              N0.getOperand(1),
5663                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
5664       // If the desired elements are smaller or larger than the source
5665       // elements we can use a matching integer vector type and then
5666       // truncate/any extend
5667       else {
5668         EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5669         SDValue VsetCC =
5670           DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5671                         N0.getOperand(1),
5672                         cast<CondCodeSDNode>(N0.getOperand(2))->get());
5673         return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
5674       }
5675     }
5676
5677     // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5678     SDValue SCC =
5679       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5680                        DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5681                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5682     if (SCC.getNode())
5683       return SCC;
5684   }
5685
5686   return SDValue();
5687 }
5688
5689 /// GetDemandedBits - See if the specified operand can be simplified with the
5690 /// knowledge that only the bits specified by Mask are used.  If so, return the
5691 /// simpler operand, otherwise return a null SDValue.
5692 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
5693   switch (V.getOpcode()) {
5694   default: break;
5695   case ISD::Constant: {
5696     const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
5697     assert(CV && "Const value should be ConstSDNode.");
5698     const APInt &CVal = CV->getAPIntValue();
5699     APInt NewVal = CVal & Mask;
5700     if (NewVal != CVal)
5701       return DAG.getConstant(NewVal, V.getValueType());
5702     break;
5703   }
5704   case ISD::OR:
5705   case ISD::XOR:
5706     // If the LHS or RHS don't contribute bits to the or, drop them.
5707     if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
5708       return V.getOperand(1);
5709     if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
5710       return V.getOperand(0);
5711     break;
5712   case ISD::SRL:
5713     // Only look at single-use SRLs.
5714     if (!V.getNode()->hasOneUse())
5715       break;
5716     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
5717       // See if we can recursively simplify the LHS.
5718       unsigned Amt = RHSC->getZExtValue();
5719
5720       // Watch out for shift count overflow though.
5721       if (Amt >= Mask.getBitWidth()) break;
5722       APInt NewMask = Mask << Amt;
5723       SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
5724       if (SimplifyLHS.getNode())
5725         return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
5726                            SimplifyLHS, V.getOperand(1));
5727     }
5728   }
5729   return SDValue();
5730 }
5731
5732 /// ReduceLoadWidth - If the result of a wider load is shifted to right of N
5733 /// bits and then truncated to a narrower type and where N is a multiple
5734 /// of number of bits of the narrower type, transform it to a narrower load
5735 /// from address + N / num of bits of new type. If the result is to be
5736 /// extended, also fold the extension to form a extending load.
5737 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
5738   unsigned Opc = N->getOpcode();
5739
5740   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
5741   SDValue N0 = N->getOperand(0);
5742   EVT VT = N->getValueType(0);
5743   EVT ExtVT = VT;
5744
5745   // This transformation isn't valid for vector loads.
5746   if (VT.isVector())
5747     return SDValue();
5748
5749   // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
5750   // extended to VT.
5751   if (Opc == ISD::SIGN_EXTEND_INREG) {
5752     ExtType = ISD::SEXTLOAD;
5753     ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
5754   } else if (Opc == ISD::SRL) {
5755     // Another special-case: SRL is basically zero-extending a narrower value.
5756     ExtType = ISD::ZEXTLOAD;
5757     N0 = SDValue(N, 0);
5758     ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
5759     if (!N01) return SDValue();
5760     ExtVT = EVT::getIntegerVT(*DAG.getContext(),
5761                               VT.getSizeInBits() - N01->getZExtValue());
5762   }
5763   if (LegalOperations && !TLI.isLoadExtLegal(ExtType, ExtVT))
5764     return SDValue();
5765
5766   unsigned EVTBits = ExtVT.getSizeInBits();
5767
5768   // Do not generate loads of non-round integer types since these can
5769   // be expensive (and would be wrong if the type is not byte sized).
5770   if (!ExtVT.isRound())
5771     return SDValue();
5772
5773   unsigned ShAmt = 0;
5774   if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
5775     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5776       ShAmt = N01->getZExtValue();
5777       // Is the shift amount a multiple of size of VT?
5778       if ((ShAmt & (EVTBits-1)) == 0) {
5779         N0 = N0.getOperand(0);
5780         // Is the load width a multiple of size of VT?
5781         if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
5782           return SDValue();
5783       }
5784
5785       // At this point, we must have a load or else we can't do the transform.
5786       if (!isa<LoadSDNode>(N0)) return SDValue();
5787
5788       // Because a SRL must be assumed to *need* to zero-extend the high bits
5789       // (as opposed to anyext the high bits), we can't combine the zextload
5790       // lowering of SRL and an sextload.
5791       if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
5792         return SDValue();
5793
5794       // If the shift amount is larger than the input type then we're not
5795       // accessing any of the loaded bytes.  If the load was a zextload/extload
5796       // then the result of the shift+trunc is zero/undef (handled elsewhere).
5797       if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
5798         return SDValue();
5799     }
5800   }
5801
5802   // If the load is shifted left (and the result isn't shifted back right),
5803   // we can fold the truncate through the shift.
5804   unsigned ShLeftAmt = 0;
5805   if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
5806       ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
5807     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5808       ShLeftAmt = N01->getZExtValue();
5809       N0 = N0.getOperand(0);
5810     }
5811   }
5812
5813   // If we haven't found a load, we can't narrow it.  Don't transform one with
5814   // multiple uses, this would require adding a new load.
5815   if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
5816     return SDValue();
5817
5818   // Don't change the width of a volatile load.
5819   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5820   if (LN0->isVolatile())
5821     return SDValue();
5822
5823   // Verify that we are actually reducing a load width here.
5824   if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
5825     return SDValue();
5826
5827   // For the transform to be legal, the load must produce only two values
5828   // (the value loaded and the chain).  Don't transform a pre-increment
5829   // load, for example, which produces an extra value.  Otherwise the
5830   // transformation is not equivalent, and the downstream logic to replace
5831   // uses gets things wrong.
5832   if (LN0->getNumValues() > 2)
5833     return SDValue();
5834
5835   // If the load that we're shrinking is an extload and we're not just
5836   // discarding the extension we can't simply shrink the load. Bail.
5837   // TODO: It would be possible to merge the extensions in some cases.
5838   if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
5839       LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
5840     return SDValue();
5841
5842   EVT PtrType = N0.getOperand(1).getValueType();
5843
5844   if (PtrType == MVT::Untyped || PtrType.isExtended())
5845     // It's not possible to generate a constant of extended or untyped type.
5846     return SDValue();
5847
5848   // For big endian targets, we need to adjust the offset to the pointer to
5849   // load the correct bytes.
5850   if (TLI.isBigEndian()) {
5851     unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
5852     unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
5853     ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
5854   }
5855
5856   uint64_t PtrOff = ShAmt / 8;
5857   unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
5858   SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0),
5859                                PtrType, LN0->getBasePtr(),
5860                                DAG.getConstant(PtrOff, PtrType));
5861   AddToWorklist(NewPtr.getNode());
5862
5863   SDValue Load;
5864   if (ExtType == ISD::NON_EXTLOAD)
5865     Load =  DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
5866                         LN0->getPointerInfo().getWithOffset(PtrOff),
5867                         LN0->isVolatile(), LN0->isNonTemporal(),
5868                         LN0->isInvariant(), NewAlign, LN0->getAAInfo());
5869   else
5870     Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
5871                           LN0->getPointerInfo().getWithOffset(PtrOff),
5872                           ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
5873                           LN0->isInvariant(), NewAlign, LN0->getAAInfo());
5874
5875   // Replace the old load's chain with the new load's chain.
5876   WorklistRemover DeadNodes(*this);
5877   DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
5878
5879   // Shift the result left, if we've swallowed a left shift.
5880   SDValue Result = Load;
5881   if (ShLeftAmt != 0) {
5882     EVT ShImmTy = getShiftAmountTy(Result.getValueType());
5883     if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
5884       ShImmTy = VT;
5885     // If the shift amount is as large as the result size (but, presumably,
5886     // no larger than the source) then the useful bits of the result are
5887     // zero; we can't simply return the shortened shift, because the result
5888     // of that operation is undefined.
5889     if (ShLeftAmt >= VT.getSizeInBits())
5890       Result = DAG.getConstant(0, VT);
5891     else
5892       Result = DAG.getNode(ISD::SHL, SDLoc(N0), VT,
5893                           Result, DAG.getConstant(ShLeftAmt, ShImmTy));
5894   }
5895
5896   // Return the new loaded value.
5897   return Result;
5898 }
5899
5900 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
5901   SDValue N0 = N->getOperand(0);
5902   SDValue N1 = N->getOperand(1);
5903   EVT VT = N->getValueType(0);
5904   EVT EVT = cast<VTSDNode>(N1)->getVT();
5905   unsigned VTBits = VT.getScalarType().getSizeInBits();
5906   unsigned EVTBits = EVT.getScalarType().getSizeInBits();
5907
5908   // fold (sext_in_reg c1) -> c1
5909   if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
5910     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
5911
5912   // If the input is already sign extended, just drop the extension.
5913   if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
5914     return N0;
5915
5916   // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
5917   if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
5918       EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
5919     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5920                        N0.getOperand(0), N1);
5921
5922   // fold (sext_in_reg (sext x)) -> (sext x)
5923   // fold (sext_in_reg (aext x)) -> (sext x)
5924   // if x is small enough.
5925   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
5926     SDValue N00 = N0.getOperand(0);
5927     if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
5928         (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
5929       return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
5930   }
5931
5932   // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
5933   if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
5934     return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
5935
5936   // fold operands of sext_in_reg based on knowledge that the top bits are not
5937   // demanded.
5938   if (SimplifyDemandedBits(SDValue(N, 0)))
5939     return SDValue(N, 0);
5940
5941   // fold (sext_in_reg (load x)) -> (smaller sextload x)
5942   // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
5943   SDValue NarrowLoad = ReduceLoadWidth(N);
5944   if (NarrowLoad.getNode())
5945     return NarrowLoad;
5946
5947   // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
5948   // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
5949   // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
5950   if (N0.getOpcode() == ISD::SRL) {
5951     if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
5952       if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
5953         // We can turn this into an SRA iff the input to the SRL is already sign
5954         // extended enough.
5955         unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
5956         if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
5957           return DAG.getNode(ISD::SRA, SDLoc(N), VT,
5958                              N0.getOperand(0), N0.getOperand(1));
5959       }
5960   }
5961
5962   // fold (sext_inreg (extload x)) -> (sextload x)
5963   if (ISD::isEXTLoad(N0.getNode()) &&
5964       ISD::isUNINDEXEDLoad(N0.getNode()) &&
5965       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5966       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5967        TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5968     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5969     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5970                                      LN0->getChain(),
5971                                      LN0->getBasePtr(), EVT,
5972                                      LN0->getMemOperand());
5973     CombineTo(N, ExtLoad);
5974     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5975     AddToWorklist(ExtLoad.getNode());
5976     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5977   }
5978   // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
5979   if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5980       N0.hasOneUse() &&
5981       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5982       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5983        TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5984     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5985     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5986                                      LN0->getChain(),
5987                                      LN0->getBasePtr(), EVT,
5988                                      LN0->getMemOperand());
5989     CombineTo(N, ExtLoad);
5990     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5991     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5992   }
5993
5994   // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
5995   if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
5996     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
5997                                        N0.getOperand(1), false);
5998     if (BSwap.getNode())
5999       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6000                          BSwap, N1);
6001   }
6002
6003   // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs
6004   // into a build_vector.
6005   if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
6006     SmallVector<SDValue, 8> Elts;
6007     unsigned NumElts = N0->getNumOperands();
6008     unsigned ShAmt = VTBits - EVTBits;
6009
6010     for (unsigned i = 0; i != NumElts; ++i) {
6011       SDValue Op = N0->getOperand(i);
6012       if (Op->getOpcode() == ISD::UNDEF) {
6013         Elts.push_back(Op);
6014         continue;
6015       }
6016
6017       ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
6018       const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
6019       Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
6020                                      Op.getValueType()));
6021     }
6022
6023     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Elts);
6024   }
6025
6026   return SDValue();
6027 }
6028
6029 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
6030   SDValue N0 = N->getOperand(0);
6031   EVT VT = N->getValueType(0);
6032   bool isLE = TLI.isLittleEndian();
6033
6034   // noop truncate
6035   if (N0.getValueType() == N->getValueType(0))
6036     return N0;
6037   // fold (truncate c1) -> c1
6038   if (isa<ConstantSDNode>(N0))
6039     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
6040   // fold (truncate (truncate x)) -> (truncate x)
6041   if (N0.getOpcode() == ISD::TRUNCATE)
6042     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6043   // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
6044   if (N0.getOpcode() == ISD::ZERO_EXTEND ||
6045       N0.getOpcode() == ISD::SIGN_EXTEND ||
6046       N0.getOpcode() == ISD::ANY_EXTEND) {
6047     if (N0.getOperand(0).getValueType().bitsLT(VT))
6048       // if the source is smaller than the dest, we still need an extend
6049       return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
6050                          N0.getOperand(0));
6051     if (N0.getOperand(0).getValueType().bitsGT(VT))
6052       // if the source is larger than the dest, than we just need the truncate
6053       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6054     // if the source and dest are the same type, we can drop both the extend
6055     // and the truncate.
6056     return N0.getOperand(0);
6057   }
6058
6059   // Fold extract-and-trunc into a narrow extract. For example:
6060   //   i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
6061   //   i32 y = TRUNCATE(i64 x)
6062   //        -- becomes --
6063   //   v16i8 b = BITCAST (v2i64 val)
6064   //   i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
6065   //
6066   // Note: We only run this optimization after type legalization (which often
6067   // creates this pattern) and before operation legalization after which
6068   // we need to be more careful about the vector instructions that we generate.
6069   if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6070       LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
6071
6072     EVT VecTy = N0.getOperand(0).getValueType();
6073     EVT ExTy = N0.getValueType();
6074     EVT TrTy = N->getValueType(0);
6075
6076     unsigned NumElem = VecTy.getVectorNumElements();
6077     unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
6078
6079     EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
6080     assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
6081
6082     SDValue EltNo = N0->getOperand(1);
6083     if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
6084       int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
6085       EVT IndexTy = TLI.getVectorIdxTy();
6086       int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
6087
6088       SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
6089                               NVT, N0.getOperand(0));
6090
6091       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
6092                          SDLoc(N), TrTy, V,
6093                          DAG.getConstant(Index, IndexTy));
6094     }
6095   }
6096
6097   // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
6098   if (N0.getOpcode() == ISD::SELECT) {
6099     EVT SrcVT = N0.getValueType();
6100     if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
6101         TLI.isTruncateFree(SrcVT, VT)) {
6102       SDLoc SL(N0);
6103       SDValue Cond = N0.getOperand(0);
6104       SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
6105       SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
6106       return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
6107     }
6108   }
6109
6110   // Fold a series of buildvector, bitcast, and truncate if possible.
6111   // For example fold
6112   //   (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
6113   //   (2xi32 (buildvector x, y)).
6114   if (Level == AfterLegalizeVectorOps && VT.isVector() &&
6115       N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
6116       N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
6117       N0.getOperand(0).hasOneUse()) {
6118
6119     SDValue BuildVect = N0.getOperand(0);
6120     EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
6121     EVT TruncVecEltTy = VT.getVectorElementType();
6122
6123     // Check that the element types match.
6124     if (BuildVectEltTy == TruncVecEltTy) {
6125       // Now we only need to compute the offset of the truncated elements.
6126       unsigned BuildVecNumElts =  BuildVect.getNumOperands();
6127       unsigned TruncVecNumElts = VT.getVectorNumElements();
6128       unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
6129
6130       assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
6131              "Invalid number of elements");
6132
6133       SmallVector<SDValue, 8> Opnds;
6134       for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
6135         Opnds.push_back(BuildVect.getOperand(i));
6136
6137       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
6138     }
6139   }
6140
6141   // See if we can simplify the input to this truncate through knowledge that
6142   // only the low bits are being used.
6143   // For example "trunc (or (shl x, 8), y)" // -> trunc y
6144   // Currently we only perform this optimization on scalars because vectors
6145   // may have different active low bits.
6146   if (!VT.isVector()) {
6147     SDValue Shorter =
6148       GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
6149                                                VT.getSizeInBits()));
6150     if (Shorter.getNode())
6151       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
6152   }
6153   // fold (truncate (load x)) -> (smaller load x)
6154   // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
6155   if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
6156     SDValue Reduced = ReduceLoadWidth(N);
6157     if (Reduced.getNode())
6158       return Reduced;
6159     // Handle the case where the load remains an extending load even
6160     // after truncation.
6161     if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
6162       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6163       if (!LN0->isVolatile() &&
6164           LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
6165         SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
6166                                          VT, LN0->getChain(), LN0->getBasePtr(),
6167                                          LN0->getMemoryVT(),
6168                                          LN0->getMemOperand());
6169         DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
6170         return NewLoad;
6171       }
6172     }
6173   }
6174   // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
6175   // where ... are all 'undef'.
6176   if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
6177     SmallVector<EVT, 8> VTs;
6178     SDValue V;
6179     unsigned Idx = 0;
6180     unsigned NumDefs = 0;
6181
6182     for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
6183       SDValue X = N0.getOperand(i);
6184       if (X.getOpcode() != ISD::UNDEF) {
6185         V = X;
6186         Idx = i;
6187         NumDefs++;
6188       }
6189       // Stop if more than one members are non-undef.
6190       if (NumDefs > 1)
6191         break;
6192       VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
6193                                      VT.getVectorElementType(),
6194                                      X.getValueType().getVectorNumElements()));
6195     }
6196
6197     if (NumDefs == 0)
6198       return DAG.getUNDEF(VT);
6199
6200     if (NumDefs == 1) {
6201       assert(V.getNode() && "The single defined operand is empty!");
6202       SmallVector<SDValue, 8> Opnds;
6203       for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
6204         if (i != Idx) {
6205           Opnds.push_back(DAG.getUNDEF(VTs[i]));
6206           continue;
6207         }
6208         SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
6209         AddToWorklist(NV.getNode());
6210         Opnds.push_back(NV);
6211       }
6212       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
6213     }
6214   }
6215
6216   // Simplify the operands using demanded-bits information.
6217   if (!VT.isVector() &&
6218       SimplifyDemandedBits(SDValue(N, 0)))
6219     return SDValue(N, 0);
6220
6221   return SDValue();
6222 }
6223
6224 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
6225   SDValue Elt = N->getOperand(i);
6226   if (Elt.getOpcode() != ISD::MERGE_VALUES)
6227     return Elt.getNode();
6228   return Elt.getOperand(Elt.getResNo()).getNode();
6229 }
6230
6231 /// CombineConsecutiveLoads - build_pair (load, load) -> load
6232 /// if load locations are consecutive.
6233 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
6234   assert(N->getOpcode() == ISD::BUILD_PAIR);
6235
6236   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
6237   LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
6238   if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
6239       LD1->getAddressSpace() != LD2->getAddressSpace())
6240     return SDValue();
6241   EVT LD1VT = LD1->getValueType(0);
6242
6243   if (ISD::isNON_EXTLoad(LD2) &&
6244       LD2->hasOneUse() &&
6245       // If both are volatile this would reduce the number of volatile loads.
6246       // If one is volatile it might be ok, but play conservative and bail out.
6247       !LD1->isVolatile() &&
6248       !LD2->isVolatile() &&
6249       DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
6250     unsigned Align = LD1->getAlignment();
6251     unsigned NewAlign = TLI.getDataLayout()->
6252       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6253
6254     if (NewAlign <= Align &&
6255         (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
6256       return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
6257                          LD1->getBasePtr(), LD1->getPointerInfo(),
6258                          false, false, false, Align);
6259   }
6260
6261   return SDValue();
6262 }
6263
6264 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
6265   SDValue N0 = N->getOperand(0);
6266   EVT VT = N->getValueType(0);
6267
6268   // If the input is a BUILD_VECTOR with all constant elements, fold this now.
6269   // Only do this before legalize, since afterward the target may be depending
6270   // on the bitconvert.
6271   // First check to see if this is all constant.
6272   if (!LegalTypes &&
6273       N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
6274       VT.isVector()) {
6275     bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
6276
6277     EVT DestEltVT = N->getValueType(0).getVectorElementType();
6278     assert(!DestEltVT.isVector() &&
6279            "Element type of vector ValueType must not be vector!");
6280     if (isSimple)
6281       return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
6282   }
6283
6284   // If the input is a constant, let getNode fold it.
6285   if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
6286     SDValue Res = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
6287     if (Res.getNode() != N) {
6288       if (!LegalOperations ||
6289           TLI.isOperationLegal(Res.getNode()->getOpcode(), VT))
6290         return Res;
6291
6292       // Folding it resulted in an illegal node, and it's too late to
6293       // do that. Clean up the old node and forego the transformation.
6294       // Ideally this won't happen very often, because instcombine
6295       // and the earlier dagcombine runs (where illegal nodes are
6296       // permitted) should have folded most of them already.
6297       deleteAndRecombine(Res.getNode());
6298     }
6299   }
6300
6301   // (conv (conv x, t1), t2) -> (conv x, t2)
6302   if (N0.getOpcode() == ISD::BITCAST)
6303     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
6304                        N0.getOperand(0));
6305
6306   // fold (conv (load x)) -> (load (conv*)x)
6307   // If the resultant load doesn't need a higher alignment than the original!
6308   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
6309       // Do not change the width of a volatile load.
6310       !cast<LoadSDNode>(N0)->isVolatile() &&
6311       // Do not remove the cast if the types differ in endian layout.
6312       TLI.hasBigEndianPartOrdering(N0.getValueType()) ==
6313       TLI.hasBigEndianPartOrdering(VT) &&
6314       (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
6315       TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
6316     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6317     unsigned Align = TLI.getDataLayout()->
6318       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6319     unsigned OrigAlign = LN0->getAlignment();
6320
6321     if (Align <= OrigAlign) {
6322       SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
6323                                  LN0->getBasePtr(), LN0->getPointerInfo(),
6324                                  LN0->isVolatile(), LN0->isNonTemporal(),
6325                                  LN0->isInvariant(), OrigAlign,
6326                                  LN0->getAAInfo());
6327       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
6328       return Load;
6329     }
6330   }
6331
6332   // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
6333   // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
6334   // This often reduces constant pool loads.
6335   if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
6336        (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
6337       N0.getNode()->hasOneUse() && VT.isInteger() &&
6338       !VT.isVector() && !N0.getValueType().isVector()) {
6339     SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
6340                                   N0.getOperand(0));
6341     AddToWorklist(NewConv.getNode());
6342
6343     APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6344     if (N0.getOpcode() == ISD::FNEG)
6345       return DAG.getNode(ISD::XOR, SDLoc(N), VT,
6346                          NewConv, DAG.getConstant(SignBit, VT));
6347     assert(N0.getOpcode() == ISD::FABS);
6348     return DAG.getNode(ISD::AND, SDLoc(N), VT,
6349                        NewConv, DAG.getConstant(~SignBit, VT));
6350   }
6351
6352   // fold (bitconvert (fcopysign cst, x)) ->
6353   //         (or (and (bitconvert x), sign), (and cst, (not sign)))
6354   // Note that we don't handle (copysign x, cst) because this can always be
6355   // folded to an fneg or fabs.
6356   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
6357       isa<ConstantFPSDNode>(N0.getOperand(0)) &&
6358       VT.isInteger() && !VT.isVector()) {
6359     unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
6360     EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
6361     if (isTypeLegal(IntXVT)) {
6362       SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6363                               IntXVT, N0.getOperand(1));
6364       AddToWorklist(X.getNode());
6365
6366       // If X has a different width than the result/lhs, sext it or truncate it.
6367       unsigned VTWidth = VT.getSizeInBits();
6368       if (OrigXWidth < VTWidth) {
6369         X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
6370         AddToWorklist(X.getNode());
6371       } else if (OrigXWidth > VTWidth) {
6372         // To get the sign bit in the right place, we have to shift it right
6373         // before truncating.
6374         X = DAG.getNode(ISD::SRL, SDLoc(X),
6375                         X.getValueType(), X,
6376                         DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
6377         AddToWorklist(X.getNode());
6378         X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
6379         AddToWorklist(X.getNode());
6380       }
6381
6382       APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6383       X = DAG.getNode(ISD::AND, SDLoc(X), VT,
6384                       X, DAG.getConstant(SignBit, VT));
6385       AddToWorklist(X.getNode());
6386
6387       SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6388                                 VT, N0.getOperand(0));
6389       Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
6390                         Cst, DAG.getConstant(~SignBit, VT));
6391       AddToWorklist(Cst.getNode());
6392
6393       return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
6394     }
6395   }
6396
6397   // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
6398   if (N0.getOpcode() == ISD::BUILD_PAIR) {
6399     SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
6400     if (CombineLD.getNode())
6401       return CombineLD;
6402   }
6403
6404   return SDValue();
6405 }
6406
6407 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
6408   EVT VT = N->getValueType(0);
6409   return CombineConsecutiveLoads(N, VT);
6410 }
6411
6412 /// ConstantFoldBITCASTofBUILD_VECTOR - We know that BV is a build_vector
6413 /// node with Constant, ConstantFP or Undef operands.  DstEltVT indicates the
6414 /// destination element value type.
6415 SDValue DAGCombiner::
6416 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
6417   EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
6418
6419   // If this is already the right type, we're done.
6420   if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
6421
6422   unsigned SrcBitSize = SrcEltVT.getSizeInBits();
6423   unsigned DstBitSize = DstEltVT.getSizeInBits();
6424
6425   // If this is a conversion of N elements of one type to N elements of another
6426   // type, convert each element.  This handles FP<->INT cases.
6427   if (SrcBitSize == DstBitSize) {
6428     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6429                               BV->getValueType(0).getVectorNumElements());
6430
6431     // Due to the FP element handling below calling this routine recursively,
6432     // we can end up with a scalar-to-vector node here.
6433     if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
6434       return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6435                          DAG.getNode(ISD::BITCAST, SDLoc(BV),
6436                                      DstEltVT, BV->getOperand(0)));
6437
6438     SmallVector<SDValue, 8> Ops;
6439     for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6440       SDValue Op = BV->getOperand(i);
6441       // If the vector element type is not legal, the BUILD_VECTOR operands
6442       // are promoted and implicitly truncated.  Make that explicit here.
6443       if (Op.getValueType() != SrcEltVT)
6444         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
6445       Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
6446                                 DstEltVT, Op));
6447       AddToWorklist(Ops.back().getNode());
6448     }
6449     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6450   }
6451
6452   // Otherwise, we're growing or shrinking the elements.  To avoid having to
6453   // handle annoying details of growing/shrinking FP values, we convert them to
6454   // int first.
6455   if (SrcEltVT.isFloatingPoint()) {
6456     // Convert the input float vector to a int vector where the elements are the
6457     // same sizes.
6458     assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!");
6459     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
6460     BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
6461     SrcEltVT = IntVT;
6462   }
6463
6464   // Now we know the input is an integer vector.  If the output is a FP type,
6465   // convert to integer first, then to FP of the right size.
6466   if (DstEltVT.isFloatingPoint()) {
6467     assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!");
6468     EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
6469     SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
6470
6471     // Next, convert to FP elements of the same size.
6472     return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
6473   }
6474
6475   // Okay, we know the src/dst types are both integers of differing types.
6476   // Handling growing first.
6477   assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
6478   if (SrcBitSize < DstBitSize) {
6479     unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
6480
6481     SmallVector<SDValue, 8> Ops;
6482     for (unsigned i = 0, e = BV->getNumOperands(); i != e;
6483          i += NumInputsPerOutput) {
6484       bool isLE = TLI.isLittleEndian();
6485       APInt NewBits = APInt(DstBitSize, 0);
6486       bool EltIsUndef = true;
6487       for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
6488         // Shift the previously computed bits over.
6489         NewBits <<= SrcBitSize;
6490         SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
6491         if (Op.getOpcode() == ISD::UNDEF) continue;
6492         EltIsUndef = false;
6493
6494         NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
6495                    zextOrTrunc(SrcBitSize).zext(DstBitSize);
6496       }
6497
6498       if (EltIsUndef)
6499         Ops.push_back(DAG.getUNDEF(DstEltVT));
6500       else
6501         Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
6502     }
6503
6504     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
6505     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6506   }
6507
6508   // Finally, this must be the case where we are shrinking elements: each input
6509   // turns into multiple outputs.
6510   bool isS2V = ISD::isScalarToVector(BV);
6511   unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
6512   EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6513                             NumOutputsPerInput*BV->getNumOperands());
6514   SmallVector<SDValue, 8> Ops;
6515
6516   for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6517     if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
6518       for (unsigned j = 0; j != NumOutputsPerInput; ++j)
6519         Ops.push_back(DAG.getUNDEF(DstEltVT));
6520       continue;
6521     }
6522
6523     APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
6524                   getAPIntValue().zextOrTrunc(SrcBitSize);
6525
6526     for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
6527       APInt ThisVal = OpVal.trunc(DstBitSize);
6528       Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
6529       if (isS2V && i == 0 && j == 0 && ThisVal.zext(SrcBitSize) == OpVal)
6530         // Simply turn this into a SCALAR_TO_VECTOR of the new type.
6531         return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6532                            Ops[0]);
6533       OpVal = OpVal.lshr(DstBitSize);
6534     }
6535
6536     // For big endian targets, swap the order of the pieces of each element.
6537     if (TLI.isBigEndian())
6538       std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
6539   }
6540
6541   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6542 }
6543
6544 SDValue DAGCombiner::visitFADD(SDNode *N) {
6545   SDValue N0 = N->getOperand(0);
6546   SDValue N1 = N->getOperand(1);
6547   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6548   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6549   EVT VT = N->getValueType(0);
6550   const TargetOptions &Options = DAG.getTarget().Options;
6551   
6552   // fold vector ops
6553   if (VT.isVector()) {
6554     SDValue FoldedVOp = SimplifyVBinOp(N);
6555     if (FoldedVOp.getNode()) return FoldedVOp;
6556   }
6557
6558   // fold (fadd c1, c2) -> c1 + c2
6559   if (N0CFP && N1CFP)
6560     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N1);
6561   // canonicalize constant to RHS
6562   if (N0CFP && !N1CFP)
6563     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N0);
6564   // fold (fadd A, 0) -> A
6565   if (Options.UnsafeFPMath && N1CFP && N1CFP->getValueAPF().isZero())
6566     return N0;
6567   // fold (fadd A, (fneg B)) -> (fsub A, B)
6568   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6569     isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2)
6570     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0,
6571                        GetNegatedExpression(N1, DAG, LegalOperations));
6572   // fold (fadd (fneg A), B) -> (fsub B, A)
6573   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6574     isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2)
6575     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N1,
6576                        GetNegatedExpression(N0, DAG, LegalOperations));
6577
6578   // If allowed, fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
6579   if (Options.UnsafeFPMath && N1CFP &&
6580       N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
6581       isa<ConstantFPSDNode>(N0.getOperand(1)))
6582     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0.getOperand(0),
6583                        DAG.getNode(ISD::FADD, SDLoc(N), VT,
6584                                    N0.getOperand(1), N1));
6585
6586   // No FP constant should be created after legalization as Instruction
6587   // Selection pass has hard time in dealing with FP constant.
6588   //
6589   // We don't need test this condition for transformation like following, as
6590   // the DAG being transformed implies it is legal to take FP constant as
6591   // operand.
6592   //
6593   //  (fadd (fmul c, x), x) -> (fmul c+1, x)
6594   //
6595   bool AllowNewFpConst = (Level < AfterLegalizeDAG);
6596
6597   // If allow, fold (fadd (fneg x), x) -> 0.0
6598   if (AllowNewFpConst && Options.UnsafeFPMath &&
6599       N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
6600     return DAG.getConstantFP(0.0, VT);
6601
6602   // If allow, fold (fadd x, (fneg x)) -> 0.0
6603   if (AllowNewFpConst && Options.UnsafeFPMath &&
6604       N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
6605     return DAG.getConstantFP(0.0, VT);
6606
6607   // In unsafe math mode, we can fold chains of FADD's of the same value
6608   // into multiplications.  This transform is not safe in general because
6609   // we are reducing the number of rounding steps.
6610   if (Options.UnsafeFPMath && TLI.isOperationLegalOrCustom(ISD::FMUL, VT) &&
6611       !N0CFP && !N1CFP) {
6612     if (N0.getOpcode() == ISD::FMUL) {
6613       ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6614       ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
6615
6616       // (fadd (fmul c, x), x) -> (fmul x, c+1)
6617       if (CFP00 && !CFP01 && N0.getOperand(1) == N1) {
6618         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6619                                      SDValue(CFP00, 0),
6620                                      DAG.getConstantFP(1.0, VT));
6621         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6622                            N1, NewCFP);
6623       }
6624
6625       // (fadd (fmul x, c), x) -> (fmul x, c+1)
6626       if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
6627         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6628                                      SDValue(CFP01, 0),
6629                                      DAG.getConstantFP(1.0, VT));
6630         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6631                            N1, NewCFP);
6632       }
6633
6634       // (fadd (fmul c, x), (fadd x, x)) -> (fmul x, c+2)
6635       if (CFP00 && !CFP01 && N1.getOpcode() == ISD::FADD &&
6636           N1.getOperand(0) == N1.getOperand(1) &&
6637           N0.getOperand(1) == N1.getOperand(0)) {
6638         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6639                                      SDValue(CFP00, 0),
6640                                      DAG.getConstantFP(2.0, VT));
6641         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6642                            N0.getOperand(1), NewCFP);
6643       }
6644
6645       // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
6646       if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
6647           N1.getOperand(0) == N1.getOperand(1) &&
6648           N0.getOperand(0) == N1.getOperand(0)) {
6649         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6650                                      SDValue(CFP01, 0),
6651                                      DAG.getConstantFP(2.0, VT));
6652         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6653                            N0.getOperand(0), NewCFP);
6654       }
6655     }
6656
6657     if (N1.getOpcode() == ISD::FMUL) {
6658       ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6659       ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
6660
6661       // (fadd x, (fmul c, x)) -> (fmul x, c+1)
6662       if (CFP10 && !CFP11 && N1.getOperand(1) == N0) {
6663         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6664                                      SDValue(CFP10, 0),
6665                                      DAG.getConstantFP(1.0, VT));
6666         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6667                            N0, NewCFP);
6668       }
6669
6670       // (fadd x, (fmul x, c)) -> (fmul x, c+1)
6671       if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
6672         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6673                                      SDValue(CFP11, 0),
6674                                      DAG.getConstantFP(1.0, VT));
6675         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6676                            N0, NewCFP);
6677       }
6678
6679
6680       // (fadd (fadd x, x), (fmul c, x)) -> (fmul x, c+2)
6681       if (CFP10 && !CFP11 && N0.getOpcode() == ISD::FADD &&
6682           N0.getOperand(0) == N0.getOperand(1) &&
6683           N1.getOperand(1) == N0.getOperand(0)) {
6684         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6685                                      SDValue(CFP10, 0),
6686                                      DAG.getConstantFP(2.0, VT));
6687         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6688                            N1.getOperand(1), NewCFP);
6689       }
6690
6691       // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
6692       if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
6693           N0.getOperand(0) == N0.getOperand(1) &&
6694           N1.getOperand(0) == N0.getOperand(0)) {
6695         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6696                                      SDValue(CFP11, 0),
6697                                      DAG.getConstantFP(2.0, VT));
6698         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6699                            N1.getOperand(0), NewCFP);
6700       }
6701     }
6702
6703     if (N0.getOpcode() == ISD::FADD && AllowNewFpConst) {
6704       ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6705       // (fadd (fadd x, x), x) -> (fmul x, 3.0)
6706       if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
6707           (N0.getOperand(0) == N1))
6708         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6709                            N1, DAG.getConstantFP(3.0, VT));
6710     }
6711
6712     if (N1.getOpcode() == ISD::FADD && AllowNewFpConst) {
6713       ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6714       // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
6715       if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
6716           N1.getOperand(0) == N0)
6717         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6718                            N0, DAG.getConstantFP(3.0, VT));
6719     }
6720
6721     // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
6722     if (AllowNewFpConst &&
6723         N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
6724         N0.getOperand(0) == N0.getOperand(1) &&
6725         N1.getOperand(0) == N1.getOperand(1) &&
6726         N0.getOperand(0) == N1.getOperand(0))
6727       return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6728                          N0.getOperand(0),
6729                          DAG.getConstantFP(4.0, VT));
6730   }
6731
6732   // FADD -> FMA combines:
6733   if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath) &&
6734       DAG.getTarget()
6735           .getSubtargetImpl()
6736           ->getTargetLowering()
6737           ->isFMAFasterThanFMulAndFAdd(VT) &&
6738       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6739
6740     // fold (fadd (fmul x, y), z) -> (fma x, y, z)
6741     if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
6742       return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6743                          N0.getOperand(0), N0.getOperand(1), N1);
6744
6745     // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
6746     // Note: Commutes FADD operands.
6747     if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
6748       return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6749                          N1.getOperand(0), N1.getOperand(1), N0);
6750   }
6751
6752   return SDValue();
6753 }
6754
6755 SDValue DAGCombiner::visitFSUB(SDNode *N) {
6756   SDValue N0 = N->getOperand(0);
6757   SDValue N1 = N->getOperand(1);
6758   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6759   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6760   EVT VT = N->getValueType(0);
6761   SDLoc dl(N);
6762   const TargetOptions &Options = DAG.getTarget().Options;
6763
6764   // fold vector ops
6765   if (VT.isVector()) {
6766     SDValue FoldedVOp = SimplifyVBinOp(N);
6767     if (FoldedVOp.getNode()) return FoldedVOp;
6768   }
6769
6770   // fold (fsub c1, c2) -> c1-c2
6771   if (N0CFP && N1CFP)
6772     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0, N1);
6773
6774   // fold (fsub A, (fneg B)) -> (fadd A, B)
6775   if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
6776     return DAG.getNode(ISD::FADD, dl, VT, N0,
6777                        GetNegatedExpression(N1, DAG, LegalOperations));
6778
6779   // If 'unsafe math' is enabled, fold lots of things.
6780   if (Options.UnsafeFPMath) {
6781     // (fsub A, 0) -> A
6782     if (N1CFP && N1CFP->getValueAPF().isZero())
6783       return N0;
6784
6785     // (fsub 0, B) -> -B
6786     if (N0CFP && N0CFP->getValueAPF().isZero()) {
6787       if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
6788         return GetNegatedExpression(N1, DAG, LegalOperations);
6789       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6790         return DAG.getNode(ISD::FNEG, dl, VT, N1);
6791     }
6792
6793     // (fsub x, x) -> 0.0
6794     if (N0 == N1)
6795       return DAG.getConstantFP(0.0f, VT);
6796
6797     // (fsub x, (fadd x, y)) -> (fneg y)
6798     // (fsub x, (fadd y, x)) -> (fneg y)
6799     if (N1.getOpcode() == ISD::FADD) {
6800       SDValue N10 = N1->getOperand(0);
6801       SDValue N11 = N1->getOperand(1);
6802
6803       if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options))
6804         return GetNegatedExpression(N11, DAG, LegalOperations);
6805
6806       if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options))
6807         return GetNegatedExpression(N10, DAG, LegalOperations);
6808     }
6809   }
6810
6811   // FSUB -> FMA combines:
6812   if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath) &&
6813       DAG.getTarget().getSubtargetImpl()
6814           ->getTargetLowering()
6815           ->isFMAFasterThanFMulAndFAdd(VT) &&
6816       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6817
6818     // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
6819     if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
6820       return DAG.getNode(ISD::FMA, dl, VT,
6821                          N0.getOperand(0), N0.getOperand(1),
6822                          DAG.getNode(ISD::FNEG, dl, VT, N1));
6823
6824     // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
6825     // Note: Commutes FSUB operands.
6826     if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
6827       return DAG.getNode(ISD::FMA, dl, VT,
6828                          DAG.getNode(ISD::FNEG, dl, VT,
6829                          N1.getOperand(0)),
6830                          N1.getOperand(1), N0);
6831
6832     // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
6833     if (N0.getOpcode() == ISD::FNEG &&
6834         N0.getOperand(0).getOpcode() == ISD::FMUL &&
6835         N0->hasOneUse() && N0.getOperand(0).hasOneUse()) {
6836       SDValue N00 = N0.getOperand(0).getOperand(0);
6837       SDValue N01 = N0.getOperand(0).getOperand(1);
6838       return DAG.getNode(ISD::FMA, dl, VT,
6839                          DAG.getNode(ISD::FNEG, dl, VT, N00), N01,
6840                          DAG.getNode(ISD::FNEG, dl, VT, N1));
6841     }
6842   }
6843
6844   return SDValue();
6845 }
6846
6847 SDValue DAGCombiner::visitFMUL(SDNode *N) {
6848   SDValue N0 = N->getOperand(0);
6849   SDValue N1 = N->getOperand(1);
6850   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
6851   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
6852   EVT VT = N->getValueType(0);
6853   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6854   const TargetOptions &Options = DAG.getTarget().Options;
6855
6856   // fold vector ops
6857   if (VT.isVector()) {
6858     SDValue FoldedVOp = SimplifyVBinOp(N);
6859     if (FoldedVOp.getNode()) return FoldedVOp;
6860   }
6861
6862   // fold (fmul c1, c2) -> c1*c2
6863   if (N0CFP && N1CFP)
6864     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, N1);
6865   // canonicalize constant to RHS
6866   if (N0CFP && !N1CFP)
6867     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, N0);
6868   // fold (fmul A, 0) -> 0
6869   if (Options.UnsafeFPMath && N1CFP && N1CFP->getValueAPF().isZero())
6870     return N1;
6871   // fold (fmul A, 1.0) -> A
6872   if (N1CFP && N1CFP->isExactlyValue(1.0))
6873     return N0;
6874
6875   // fold (fmul X, 2.0) -> (fadd X, X)
6876   if (N1CFP && N1CFP->isExactlyValue(+2.0))
6877     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N0);
6878   // fold (fmul X, -1.0) -> (fneg X)
6879   if (N1CFP && N1CFP->isExactlyValue(-1.0))
6880     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6881       return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
6882
6883   // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
6884   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
6885     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
6886       // Both can be negated for free, check to see if at least one is cheaper
6887       // negated.
6888       if (LHSNeg == 2 || RHSNeg == 2)
6889         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6890                            GetNegatedExpression(N0, DAG, LegalOperations),
6891                            GetNegatedExpression(N1, DAG, LegalOperations));
6892     }
6893   }
6894
6895   // If allowed, fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
6896   if (Options.UnsafeFPMath && N1CFP && N0.getOpcode() == ISD::FMUL &&
6897       N0.getNode()->hasOneUse() && isConstOrConstSplatFP(N0.getOperand(1))) {
6898     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
6899                        DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6900                                    N0.getOperand(1), N1));
6901   }
6902
6903   return SDValue();
6904 }
6905
6906 SDValue DAGCombiner::visitFMA(SDNode *N) {
6907   SDValue N0 = N->getOperand(0);
6908   SDValue N1 = N->getOperand(1);
6909   SDValue N2 = N->getOperand(2);
6910   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6911   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6912   EVT VT = N->getValueType(0);
6913   SDLoc dl(N);
6914   const TargetOptions &Options = DAG.getTarget().Options;
6915
6916   // Constant fold FMA.
6917   if (isa<ConstantFPSDNode>(N0) &&
6918       isa<ConstantFPSDNode>(N1) &&
6919       isa<ConstantFPSDNode>(N2)) {
6920     return DAG.getNode(ISD::FMA, dl, VT, N0, N1, N2);
6921   }
6922
6923   if (Options.UnsafeFPMath) {
6924     if (N0CFP && N0CFP->isZero())
6925       return N2;
6926     if (N1CFP && N1CFP->isZero())
6927       return N2;
6928   }
6929   if (N0CFP && N0CFP->isExactlyValue(1.0))
6930     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
6931   if (N1CFP && N1CFP->isExactlyValue(1.0))
6932     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
6933
6934   // Canonicalize (fma c, x, y) -> (fma x, c, y)
6935   if (N0CFP && !N1CFP)
6936     return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
6937
6938   // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
6939   if (Options.UnsafeFPMath && N1CFP &&
6940       N2.getOpcode() == ISD::FMUL &&
6941       N0 == N2.getOperand(0) &&
6942       N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
6943     return DAG.getNode(ISD::FMUL, dl, VT, N0,
6944                        DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
6945   }
6946
6947
6948   // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
6949   if (Options.UnsafeFPMath &&
6950       N0.getOpcode() == ISD::FMUL && N1CFP &&
6951       N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
6952     return DAG.getNode(ISD::FMA, dl, VT,
6953                        N0.getOperand(0),
6954                        DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
6955                        N2);
6956   }
6957
6958   // (fma x, 1, y) -> (fadd x, y)
6959   // (fma x, -1, y) -> (fadd (fneg x), y)
6960   if (N1CFP) {
6961     if (N1CFP->isExactlyValue(1.0))
6962       return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
6963
6964     if (N1CFP->isExactlyValue(-1.0) &&
6965         (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
6966       SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
6967       AddToWorklist(RHSNeg.getNode());
6968       return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
6969     }
6970   }
6971
6972   // (fma x, c, x) -> (fmul x, (c+1))
6973   if (Options.UnsafeFPMath && N1CFP && N0 == N2)
6974     return DAG.getNode(ISD::FMUL, dl, VT, N0,
6975                        DAG.getNode(ISD::FADD, dl, VT,
6976                                    N1, DAG.getConstantFP(1.0, VT)));
6977
6978   // (fma x, c, (fneg x)) -> (fmul x, (c-1))
6979   if (Options.UnsafeFPMath && N1CFP &&
6980       N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
6981     return DAG.getNode(ISD::FMUL, dl, VT, N0,
6982                        DAG.getNode(ISD::FADD, dl, VT,
6983                                    N1, DAG.getConstantFP(-1.0, VT)));
6984
6985
6986   return SDValue();
6987 }
6988
6989 SDValue DAGCombiner::visitFDIV(SDNode *N) {
6990   SDValue N0 = N->getOperand(0);
6991   SDValue N1 = N->getOperand(1);
6992   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6993   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6994   EVT VT = N->getValueType(0);
6995   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6996   const TargetOptions &Options = DAG.getTarget().Options;
6997
6998   // fold vector ops
6999   if (VT.isVector()) {
7000     SDValue FoldedVOp = SimplifyVBinOp(N);
7001     if (FoldedVOp.getNode()) return FoldedVOp;
7002   }
7003
7004   // fold (fdiv c1, c2) -> c1/c2
7005   if (N0CFP && N1CFP)
7006     return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
7007
7008   // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
7009   if (N1CFP && Options.UnsafeFPMath) {
7010     // Compute the reciprocal 1.0 / c2.
7011     APFloat N1APF = N1CFP->getValueAPF();
7012     APFloat Recip(N1APF.getSemantics(), 1); // 1.0
7013     APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
7014     // Only do the transform if the reciprocal is a legal fp immediate that
7015     // isn't too nasty (eg NaN, denormal, ...).
7016     if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
7017         (!LegalOperations ||
7018          // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
7019          // backend)... we should handle this gracefully after Legalize.
7020          // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
7021          TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
7022          TLI.isFPImmLegal(Recip, VT)))
7023       return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0,
7024                          DAG.getConstantFP(Recip, VT));
7025   }
7026
7027   // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
7028   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
7029     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
7030       // Both can be negated for free, check to see if at least one is cheaper
7031       // negated.
7032       if (LHSNeg == 2 || RHSNeg == 2)
7033         return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
7034                            GetNegatedExpression(N0, DAG, LegalOperations),
7035                            GetNegatedExpression(N1, DAG, LegalOperations));
7036     }
7037   }
7038
7039   return SDValue();
7040 }
7041
7042 SDValue DAGCombiner::visitFREM(SDNode *N) {
7043   SDValue N0 = N->getOperand(0);
7044   SDValue N1 = N->getOperand(1);
7045   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7046   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7047   EVT VT = N->getValueType(0);
7048
7049   // fold (frem c1, c2) -> fmod(c1,c2)
7050   if (N0CFP && N1CFP)
7051     return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
7052
7053   return SDValue();
7054 }
7055
7056 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
7057   SDValue N0 = N->getOperand(0);
7058   SDValue N1 = N->getOperand(1);
7059   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7060   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7061   EVT VT = N->getValueType(0);
7062
7063   if (N0CFP && N1CFP)  // Constant fold
7064     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
7065
7066   if (N1CFP) {
7067     const APFloat& V = N1CFP->getValueAPF();
7068     // copysign(x, c1) -> fabs(x)       iff ispos(c1)
7069     // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
7070     if (!V.isNegative()) {
7071       if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
7072         return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7073     } else {
7074       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
7075         return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
7076                            DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
7077     }
7078   }
7079
7080   // copysign(fabs(x), y) -> copysign(x, y)
7081   // copysign(fneg(x), y) -> copysign(x, y)
7082   // copysign(copysign(x,z), y) -> copysign(x, y)
7083   if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
7084       N0.getOpcode() == ISD::FCOPYSIGN)
7085     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7086                        N0.getOperand(0), N1);
7087
7088   // copysign(x, abs(y)) -> abs(x)
7089   if (N1.getOpcode() == ISD::FABS)
7090     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7091
7092   // copysign(x, copysign(y,z)) -> copysign(x, z)
7093   if (N1.getOpcode() == ISD::FCOPYSIGN)
7094     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7095                        N0, N1.getOperand(1));
7096
7097   // copysign(x, fp_extend(y)) -> copysign(x, y)
7098   // copysign(x, fp_round(y)) -> copysign(x, y)
7099   if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
7100     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7101                        N0, N1.getOperand(0));
7102
7103   return SDValue();
7104 }
7105
7106 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
7107   SDValue N0 = N->getOperand(0);
7108   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
7109   EVT VT = N->getValueType(0);
7110   EVT OpVT = N0.getValueType();
7111
7112   // fold (sint_to_fp c1) -> c1fp
7113   if (N0C &&
7114       // ...but only if the target supports immediate floating-point values
7115       (!LegalOperations ||
7116        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
7117     return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
7118
7119   // If the input is a legal type, and SINT_TO_FP is not legal on this target,
7120   // but UINT_TO_FP is legal on this target, try to convert.
7121   if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
7122       TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
7123     // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
7124     if (DAG.SignBitIsZero(N0))
7125       return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
7126   }
7127
7128   // The next optimizations are desirable only if SELECT_CC can be lowered.
7129   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
7130     // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
7131     if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
7132         !VT.isVector() &&
7133         (!LegalOperations ||
7134          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7135       SDValue Ops[] =
7136         { N0.getOperand(0), N0.getOperand(1),
7137           DAG.getConstantFP(-1.0, VT) , DAG.getConstantFP(0.0, VT),
7138           N0.getOperand(2) };
7139       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7140     }
7141
7142     // fold (sint_to_fp (zext (setcc x, y, cc))) ->
7143     //      (select_cc x, y, 1.0, 0.0,, cc)
7144     if (N0.getOpcode() == ISD::ZERO_EXTEND &&
7145         N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
7146         (!LegalOperations ||
7147          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7148       SDValue Ops[] =
7149         { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
7150           DAG.getConstantFP(1.0, VT) , DAG.getConstantFP(0.0, VT),
7151           N0.getOperand(0).getOperand(2) };
7152       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7153     }
7154   }
7155
7156   return SDValue();
7157 }
7158
7159 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
7160   SDValue N0 = N->getOperand(0);
7161   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
7162   EVT VT = N->getValueType(0);
7163   EVT OpVT = N0.getValueType();
7164
7165   // fold (uint_to_fp c1) -> c1fp
7166   if (N0C &&
7167       // ...but only if the target supports immediate floating-point values
7168       (!LegalOperations ||
7169        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
7170     return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
7171
7172   // If the input is a legal type, and UINT_TO_FP is not legal on this target,
7173   // but SINT_TO_FP is legal on this target, try to convert.
7174   if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
7175       TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
7176     // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
7177     if (DAG.SignBitIsZero(N0))
7178       return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
7179   }
7180
7181   // The next optimizations are desirable only if SELECT_CC can be lowered.
7182   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
7183     // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
7184
7185     if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
7186         (!LegalOperations ||
7187          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7188       SDValue Ops[] =
7189         { N0.getOperand(0), N0.getOperand(1),
7190           DAG.getConstantFP(1.0, VT),  DAG.getConstantFP(0.0, VT),
7191           N0.getOperand(2) };
7192       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7193     }
7194   }
7195
7196   return SDValue();
7197 }
7198
7199 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
7200   SDValue N0 = N->getOperand(0);
7201   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7202   EVT VT = N->getValueType(0);
7203
7204   // fold (fp_to_sint c1fp) -> c1
7205   if (N0CFP)
7206     return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
7207
7208   return SDValue();
7209 }
7210
7211 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
7212   SDValue N0 = N->getOperand(0);
7213   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7214   EVT VT = N->getValueType(0);
7215
7216   // fold (fp_to_uint c1fp) -> c1
7217   if (N0CFP)
7218     return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
7219
7220   return SDValue();
7221 }
7222
7223 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
7224   SDValue N0 = N->getOperand(0);
7225   SDValue N1 = N->getOperand(1);
7226   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7227   EVT VT = N->getValueType(0);
7228
7229   // fold (fp_round c1fp) -> c1fp
7230   if (N0CFP)
7231     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
7232
7233   // fold (fp_round (fp_extend x)) -> x
7234   if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
7235     return N0.getOperand(0);
7236
7237   // fold (fp_round (fp_round x)) -> (fp_round x)
7238   if (N0.getOpcode() == ISD::FP_ROUND) {
7239     // This is a value preserving truncation if both round's are.
7240     bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
7241                    N0.getNode()->getConstantOperandVal(1) == 1;
7242     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0.getOperand(0),
7243                        DAG.getIntPtrConstant(IsTrunc));
7244   }
7245
7246   // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
7247   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
7248     SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
7249                               N0.getOperand(0), N1);
7250     AddToWorklist(Tmp.getNode());
7251     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7252                        Tmp, N0.getOperand(1));
7253   }
7254
7255   return SDValue();
7256 }
7257
7258 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
7259   SDValue N0 = N->getOperand(0);
7260   EVT VT = N->getValueType(0);
7261   EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
7262   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7263
7264   // fold (fp_round_inreg c1fp) -> c1fp
7265   if (N0CFP && isTypeLegal(EVT)) {
7266     SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
7267     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, Round);
7268   }
7269
7270   return SDValue();
7271 }
7272
7273 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
7274   SDValue N0 = N->getOperand(0);
7275   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7276   EVT VT = N->getValueType(0);
7277
7278   // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
7279   if (N->hasOneUse() &&
7280       N->use_begin()->getOpcode() == ISD::FP_ROUND)
7281     return SDValue();
7282
7283   // fold (fp_extend c1fp) -> c1fp
7284   if (N0CFP)
7285     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
7286
7287   // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
7288   // value of X.
7289   if (N0.getOpcode() == ISD::FP_ROUND
7290       && N0.getNode()->getConstantOperandVal(1) == 1) {
7291     SDValue In = N0.getOperand(0);
7292     if (In.getValueType() == VT) return In;
7293     if (VT.bitsLT(In.getValueType()))
7294       return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
7295                          In, N0.getOperand(1));
7296     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
7297   }
7298
7299   // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
7300   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7301        TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType())) {
7302     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7303     SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
7304                                      LN0->getChain(),
7305                                      LN0->getBasePtr(), N0.getValueType(),
7306                                      LN0->getMemOperand());
7307     CombineTo(N, ExtLoad);
7308     CombineTo(N0.getNode(),
7309               DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
7310                           N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
7311               ExtLoad.getValue(1));
7312     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7313   }
7314
7315   return SDValue();
7316 }
7317
7318 SDValue DAGCombiner::visitFNEG(SDNode *N) {
7319   SDValue N0 = N->getOperand(0);
7320   EVT VT = N->getValueType(0);
7321
7322   // Constant fold FNEG.
7323   if (isa<ConstantFPSDNode>(N0))
7324     return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N->getOperand(0));
7325
7326   if (VT.isVector()) {
7327     SDValue FoldedVOp = SimplifyVUnaryOp(N);
7328     if (FoldedVOp.getNode()) return FoldedVOp;
7329   }
7330
7331   if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
7332                          &DAG.getTarget().Options))
7333     return GetNegatedExpression(N0, DAG, LegalOperations);
7334
7335   // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading
7336   // constant pool values.
7337   if (!TLI.isFNegFree(VT) && N0.getOpcode() == ISD::BITCAST &&
7338       N0.getNode()->hasOneUse()) {
7339     SDValue Int = N0.getOperand(0);
7340     EVT IntVT = Int.getValueType();
7341     if (IntVT.isInteger() && !IntVT.isVector()) {
7342       APInt SignMask;
7343       if (N0.getValueType().isVector()) {
7344         // For a vector, get a mask such as 0x80... per scalar element
7345         // and splat it.
7346         SignMask = APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
7347         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
7348       } else {
7349         // For a scalar, just generate 0x80...
7350         SignMask = APInt::getSignBit(IntVT.getSizeInBits());
7351       }
7352       Int = DAG.getNode(ISD::XOR, SDLoc(N0), IntVT, Int,
7353                         DAG.getConstant(SignMask, IntVT));
7354       AddToWorklist(Int.getNode());
7355       return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Int);
7356     }
7357   }
7358
7359   // (fneg (fmul c, x)) -> (fmul -c, x)
7360   if (N0.getOpcode() == ISD::FMUL) {
7361     ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
7362     if (CFP1) {
7363       APFloat CVal = CFP1->getValueAPF();
7364       CVal.changeSign();
7365       if (Level >= AfterLegalizeDAG &&
7366           (TLI.isFPImmLegal(CVal, N->getValueType(0)) ||
7367            TLI.isOperationLegal(ISD::ConstantFP, N->getValueType(0))))
7368         return DAG.getNode(
7369             ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
7370             DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0.getOperand(1)));
7371     }
7372   }
7373
7374   return SDValue();
7375 }
7376
7377 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
7378   SDValue N0 = N->getOperand(0);
7379   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7380   EVT VT = N->getValueType(0);
7381
7382   // fold (fceil c1) -> fceil(c1)
7383   if (N0CFP)
7384     return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
7385
7386   return SDValue();
7387 }
7388
7389 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
7390   SDValue N0 = N->getOperand(0);
7391   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7392   EVT VT = N->getValueType(0);
7393
7394   // fold (ftrunc c1) -> ftrunc(c1)
7395   if (N0CFP)
7396     return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
7397
7398   return SDValue();
7399 }
7400
7401 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
7402   SDValue N0 = N->getOperand(0);
7403   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7404   EVT VT = N->getValueType(0);
7405
7406   // fold (ffloor c1) -> ffloor(c1)
7407   if (N0CFP)
7408     return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
7409
7410   return SDValue();
7411 }
7412
7413 SDValue DAGCombiner::visitFABS(SDNode *N) {
7414   SDValue N0 = N->getOperand(0);
7415   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7416   EVT VT = N->getValueType(0);
7417
7418   if (VT.isVector()) {
7419     SDValue FoldedVOp = SimplifyVUnaryOp(N);
7420     if (FoldedVOp.getNode()) return FoldedVOp;
7421   }
7422
7423   // fold (fabs c1) -> fabs(c1)
7424   if (N0CFP)
7425     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7426   // fold (fabs (fabs x)) -> (fabs x)
7427   if (N0.getOpcode() == ISD::FABS)
7428     return N->getOperand(0);
7429   // fold (fabs (fneg x)) -> (fabs x)
7430   // fold (fabs (fcopysign x, y)) -> (fabs x)
7431   if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
7432     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
7433
7434   // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading
7435   // constant pool values.
7436   if (!TLI.isFAbsFree(VT) &&
7437       N0.getOpcode() == ISD::BITCAST &&
7438       N0.getNode()->hasOneUse()) {
7439     SDValue Int = N0.getOperand(0);
7440     EVT IntVT = Int.getValueType();
7441     if (IntVT.isInteger() && !IntVT.isVector()) {
7442       APInt SignMask;
7443       if (N0.getValueType().isVector()) {
7444         // For a vector, get a mask such as 0x7f... per scalar element
7445         // and splat it.
7446         SignMask = ~APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
7447         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
7448       } else {
7449         // For a scalar, just generate 0x7f...
7450         SignMask = ~APInt::getSignBit(IntVT.getSizeInBits());
7451       }
7452       Int = DAG.getNode(ISD::AND, SDLoc(N0), IntVT, Int,
7453                         DAG.getConstant(SignMask, IntVT));
7454       AddToWorklist(Int.getNode());
7455       return DAG.getNode(ISD::BITCAST, SDLoc(N), N->getValueType(0), Int);
7456     }
7457   }
7458
7459   return SDValue();
7460 }
7461
7462 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
7463   SDValue Chain = N->getOperand(0);
7464   SDValue N1 = N->getOperand(1);
7465   SDValue N2 = N->getOperand(2);
7466
7467   // If N is a constant we could fold this into a fallthrough or unconditional
7468   // branch. However that doesn't happen very often in normal code, because
7469   // Instcombine/SimplifyCFG should have handled the available opportunities.
7470   // If we did this folding here, it would be necessary to update the
7471   // MachineBasicBlock CFG, which is awkward.
7472
7473   // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
7474   // on the target.
7475   if (N1.getOpcode() == ISD::SETCC &&
7476       TLI.isOperationLegalOrCustom(ISD::BR_CC,
7477                                    N1.getOperand(0).getValueType())) {
7478     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7479                        Chain, N1.getOperand(2),
7480                        N1.getOperand(0), N1.getOperand(1), N2);
7481   }
7482
7483   if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
7484       ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
7485        (N1.getOperand(0).hasOneUse() &&
7486         N1.getOperand(0).getOpcode() == ISD::SRL))) {
7487     SDNode *Trunc = nullptr;
7488     if (N1.getOpcode() == ISD::TRUNCATE) {
7489       // Look pass the truncate.
7490       Trunc = N1.getNode();
7491       N1 = N1.getOperand(0);
7492     }
7493
7494     // Match this pattern so that we can generate simpler code:
7495     //
7496     //   %a = ...
7497     //   %b = and i32 %a, 2
7498     //   %c = srl i32 %b, 1
7499     //   brcond i32 %c ...
7500     //
7501     // into
7502     //
7503     //   %a = ...
7504     //   %b = and i32 %a, 2
7505     //   %c = setcc eq %b, 0
7506     //   brcond %c ...
7507     //
7508     // This applies only when the AND constant value has one bit set and the
7509     // SRL constant is equal to the log2 of the AND constant. The back-end is
7510     // smart enough to convert the result into a TEST/JMP sequence.
7511     SDValue Op0 = N1.getOperand(0);
7512     SDValue Op1 = N1.getOperand(1);
7513
7514     if (Op0.getOpcode() == ISD::AND &&
7515         Op1.getOpcode() == ISD::Constant) {
7516       SDValue AndOp1 = Op0.getOperand(1);
7517
7518       if (AndOp1.getOpcode() == ISD::Constant) {
7519         const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
7520
7521         if (AndConst.isPowerOf2() &&
7522             cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
7523           SDValue SetCC =
7524             DAG.getSetCC(SDLoc(N),
7525                          getSetCCResultType(Op0.getValueType()),
7526                          Op0, DAG.getConstant(0, Op0.getValueType()),
7527                          ISD::SETNE);
7528
7529           SDValue NewBRCond = DAG.getNode(ISD::BRCOND, SDLoc(N),
7530                                           MVT::Other, Chain, SetCC, N2);
7531           // Don't add the new BRCond into the worklist or else SimplifySelectCC
7532           // will convert it back to (X & C1) >> C2.
7533           CombineTo(N, NewBRCond, false);
7534           // Truncate is dead.
7535           if (Trunc)
7536             deleteAndRecombine(Trunc);
7537           // Replace the uses of SRL with SETCC
7538           WorklistRemover DeadNodes(*this);
7539           DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
7540           deleteAndRecombine(N1.getNode());
7541           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7542         }
7543       }
7544     }
7545
7546     if (Trunc)
7547       // Restore N1 if the above transformation doesn't match.
7548       N1 = N->getOperand(1);
7549   }
7550
7551   // Transform br(xor(x, y)) -> br(x != y)
7552   // Transform br(xor(xor(x,y), 1)) -> br (x == y)
7553   if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
7554     SDNode *TheXor = N1.getNode();
7555     SDValue Op0 = TheXor->getOperand(0);
7556     SDValue Op1 = TheXor->getOperand(1);
7557     if (Op0.getOpcode() == Op1.getOpcode()) {
7558       // Avoid missing important xor optimizations.
7559       SDValue Tmp = visitXOR(TheXor);
7560       if (Tmp.getNode()) {
7561         if (Tmp.getNode() != TheXor) {
7562           DEBUG(dbgs() << "\nReplacing.8 ";
7563                 TheXor->dump(&DAG);
7564                 dbgs() << "\nWith: ";
7565                 Tmp.getNode()->dump(&DAG);
7566                 dbgs() << '\n');
7567           WorklistRemover DeadNodes(*this);
7568           DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
7569           deleteAndRecombine(TheXor);
7570           return DAG.getNode(ISD::BRCOND, SDLoc(N),
7571                              MVT::Other, Chain, Tmp, N2);
7572         }
7573
7574         // visitXOR has changed XOR's operands or replaced the XOR completely,
7575         // bail out.
7576         return SDValue(N, 0);
7577       }
7578     }
7579
7580     if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
7581       bool Equal = false;
7582       if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
7583         if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
7584             Op0.getOpcode() == ISD::XOR) {
7585           TheXor = Op0.getNode();
7586           Equal = true;
7587         }
7588
7589       EVT SetCCVT = N1.getValueType();
7590       if (LegalTypes)
7591         SetCCVT = getSetCCResultType(SetCCVT);
7592       SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
7593                                    SetCCVT,
7594                                    Op0, Op1,
7595                                    Equal ? ISD::SETEQ : ISD::SETNE);
7596       // Replace the uses of XOR with SETCC
7597       WorklistRemover DeadNodes(*this);
7598       DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
7599       deleteAndRecombine(N1.getNode());
7600       return DAG.getNode(ISD::BRCOND, SDLoc(N),
7601                          MVT::Other, Chain, SetCC, N2);
7602     }
7603   }
7604
7605   return SDValue();
7606 }
7607
7608 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
7609 //
7610 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
7611   CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
7612   SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
7613
7614   // If N is a constant we could fold this into a fallthrough or unconditional
7615   // branch. However that doesn't happen very often in normal code, because
7616   // Instcombine/SimplifyCFG should have handled the available opportunities.
7617   // If we did this folding here, it would be necessary to update the
7618   // MachineBasicBlock CFG, which is awkward.
7619
7620   // Use SimplifySetCC to simplify SETCC's.
7621   SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
7622                                CondLHS, CondRHS, CC->get(), SDLoc(N),
7623                                false);
7624   if (Simp.getNode()) AddToWorklist(Simp.getNode());
7625
7626   // fold to a simpler setcc
7627   if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
7628     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7629                        N->getOperand(0), Simp.getOperand(2),
7630                        Simp.getOperand(0), Simp.getOperand(1),
7631                        N->getOperand(4));
7632
7633   return SDValue();
7634 }
7635
7636 /// canFoldInAddressingMode - Return true if 'Use' is a load or a store that
7637 /// uses N as its base pointer and that N may be folded in the load / store
7638 /// addressing mode.
7639 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
7640                                     SelectionDAG &DAG,
7641                                     const TargetLowering &TLI) {
7642   EVT VT;
7643   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(Use)) {
7644     if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
7645       return false;
7646     VT = Use->getValueType(0);
7647   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(Use)) {
7648     if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
7649       return false;
7650     VT = ST->getValue().getValueType();
7651   } else
7652     return false;
7653
7654   TargetLowering::AddrMode AM;
7655   if (N->getOpcode() == ISD::ADD) {
7656     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7657     if (Offset)
7658       // [reg +/- imm]
7659       AM.BaseOffs = Offset->getSExtValue();
7660     else
7661       // [reg +/- reg]
7662       AM.Scale = 1;
7663   } else if (N->getOpcode() == ISD::SUB) {
7664     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7665     if (Offset)
7666       // [reg +/- imm]
7667       AM.BaseOffs = -Offset->getSExtValue();
7668     else
7669       // [reg +/- reg]
7670       AM.Scale = 1;
7671   } else
7672     return false;
7673
7674   return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
7675 }
7676
7677 /// CombineToPreIndexedLoadStore - Try turning a load / store into a
7678 /// pre-indexed load / store when the base pointer is an add or subtract
7679 /// and it has other uses besides the load / store. After the
7680 /// transformation, the new indexed load / store has effectively folded
7681 /// the add / subtract in and all of its other uses are redirected to the
7682 /// new load / store.
7683 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
7684   if (Level < AfterLegalizeDAG)
7685     return false;
7686
7687   bool isLoad = true;
7688   SDValue Ptr;
7689   EVT VT;
7690   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
7691     if (LD->isIndexed())
7692       return false;
7693     VT = LD->getMemoryVT();
7694     if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
7695         !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
7696       return false;
7697     Ptr = LD->getBasePtr();
7698   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
7699     if (ST->isIndexed())
7700       return false;
7701     VT = ST->getMemoryVT();
7702     if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
7703         !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
7704       return false;
7705     Ptr = ST->getBasePtr();
7706     isLoad = false;
7707   } else {
7708     return false;
7709   }
7710
7711   // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
7712   // out.  There is no reason to make this a preinc/predec.
7713   if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
7714       Ptr.getNode()->hasOneUse())
7715     return false;
7716
7717   // Ask the target to do addressing mode selection.
7718   SDValue BasePtr;
7719   SDValue Offset;
7720   ISD::MemIndexedMode AM = ISD::UNINDEXED;
7721   if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
7722     return false;
7723
7724   // Backends without true r+i pre-indexed forms may need to pass a
7725   // constant base with a variable offset so that constant coercion
7726   // will work with the patterns in canonical form.
7727   bool Swapped = false;
7728   if (isa<ConstantSDNode>(BasePtr)) {
7729     std::swap(BasePtr, Offset);
7730     Swapped = true;
7731   }
7732
7733   // Don't create a indexed load / store with zero offset.
7734   if (isa<ConstantSDNode>(Offset) &&
7735       cast<ConstantSDNode>(Offset)->isNullValue())
7736     return false;
7737
7738   // Try turning it into a pre-indexed load / store except when:
7739   // 1) The new base ptr is a frame index.
7740   // 2) If N is a store and the new base ptr is either the same as or is a
7741   //    predecessor of the value being stored.
7742   // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
7743   //    that would create a cycle.
7744   // 4) All uses are load / store ops that use it as old base ptr.
7745
7746   // Check #1.  Preinc'ing a frame index would require copying the stack pointer
7747   // (plus the implicit offset) to a register to preinc anyway.
7748   if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7749     return false;
7750
7751   // Check #2.
7752   if (!isLoad) {
7753     SDValue Val = cast<StoreSDNode>(N)->getValue();
7754     if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
7755       return false;
7756   }
7757
7758   // If the offset is a constant, there may be other adds of constants that
7759   // can be folded with this one. We should do this to avoid having to keep
7760   // a copy of the original base pointer.
7761   SmallVector<SDNode *, 16> OtherUses;
7762   if (isa<ConstantSDNode>(Offset))
7763     for (SDNode *Use : BasePtr.getNode()->uses()) {
7764       if (Use == Ptr.getNode())
7765         continue;
7766
7767       if (Use->isPredecessorOf(N))
7768         continue;
7769
7770       if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) {
7771         OtherUses.clear();
7772         break;
7773       }
7774
7775       SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1);
7776       if (Op1.getNode() == BasePtr.getNode())
7777         std::swap(Op0, Op1);
7778       assert(Op0.getNode() == BasePtr.getNode() &&
7779              "Use of ADD/SUB but not an operand");
7780
7781       if (!isa<ConstantSDNode>(Op1)) {
7782         OtherUses.clear();
7783         break;
7784       }
7785
7786       // FIXME: In some cases, we can be smarter about this.
7787       if (Op1.getValueType() != Offset.getValueType()) {
7788         OtherUses.clear();
7789         break;
7790       }
7791
7792       OtherUses.push_back(Use);
7793     }
7794
7795   if (Swapped)
7796     std::swap(BasePtr, Offset);
7797
7798   // Now check for #3 and #4.
7799   bool RealUse = false;
7800
7801   // Caches for hasPredecessorHelper
7802   SmallPtrSet<const SDNode *, 32> Visited;
7803   SmallVector<const SDNode *, 16> Worklist;
7804
7805   for (SDNode *Use : Ptr.getNode()->uses()) {
7806     if (Use == N)
7807       continue;
7808     if (N->hasPredecessorHelper(Use, Visited, Worklist))
7809       return false;
7810
7811     // If Ptr may be folded in addressing mode of other use, then it's
7812     // not profitable to do this transformation.
7813     if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
7814       RealUse = true;
7815   }
7816
7817   if (!RealUse)
7818     return false;
7819
7820   SDValue Result;
7821   if (isLoad)
7822     Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
7823                                 BasePtr, Offset, AM);
7824   else
7825     Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
7826                                  BasePtr, Offset, AM);
7827   ++PreIndexedNodes;
7828   ++NodesCombined;
7829   DEBUG(dbgs() << "\nReplacing.4 ";
7830         N->dump(&DAG);
7831         dbgs() << "\nWith: ";
7832         Result.getNode()->dump(&DAG);
7833         dbgs() << '\n');
7834   WorklistRemover DeadNodes(*this);
7835   if (isLoad) {
7836     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7837     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
7838   } else {
7839     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
7840   }
7841
7842   // Finally, since the node is now dead, remove it from the graph.
7843   deleteAndRecombine(N);
7844
7845   if (Swapped)
7846     std::swap(BasePtr, Offset);
7847
7848   // Replace other uses of BasePtr that can be updated to use Ptr
7849   for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
7850     unsigned OffsetIdx = 1;
7851     if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
7852       OffsetIdx = 0;
7853     assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
7854            BasePtr.getNode() && "Expected BasePtr operand");
7855
7856     // We need to replace ptr0 in the following expression:
7857     //   x0 * offset0 + y0 * ptr0 = t0
7858     // knowing that
7859     //   x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
7860     //
7861     // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
7862     // indexed load/store and the expresion that needs to be re-written.
7863     //
7864     // Therefore, we have:
7865     //   t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
7866
7867     ConstantSDNode *CN =
7868       cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
7869     int X0, X1, Y0, Y1;
7870     APInt Offset0 = CN->getAPIntValue();
7871     APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
7872
7873     X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
7874     Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
7875     X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
7876     Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
7877
7878     unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
7879
7880     APInt CNV = Offset0;
7881     if (X0 < 0) CNV = -CNV;
7882     if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
7883     else CNV = CNV - Offset1;
7884
7885     // We can now generate the new expression.
7886     SDValue NewOp1 = DAG.getConstant(CNV, CN->getValueType(0));
7887     SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
7888
7889     SDValue NewUse = DAG.getNode(Opcode,
7890                                  SDLoc(OtherUses[i]),
7891                                  OtherUses[i]->getValueType(0), NewOp1, NewOp2);
7892     DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
7893     deleteAndRecombine(OtherUses[i]);
7894   }
7895
7896   // Replace the uses of Ptr with uses of the updated base value.
7897   DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
7898   deleteAndRecombine(Ptr.getNode());
7899
7900   return true;
7901 }
7902
7903 /// CombineToPostIndexedLoadStore - Try to combine a load / store with a
7904 /// add / sub of the base pointer node into a post-indexed load / store.
7905 /// The transformation folded the add / subtract into the new indexed
7906 /// load / store effectively and all of its uses are redirected to the
7907 /// new load / store.
7908 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
7909   if (Level < AfterLegalizeDAG)
7910     return false;
7911
7912   bool isLoad = true;
7913   SDValue Ptr;
7914   EVT VT;
7915   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
7916     if (LD->isIndexed())
7917       return false;
7918     VT = LD->getMemoryVT();
7919     if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
7920         !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
7921       return false;
7922     Ptr = LD->getBasePtr();
7923   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
7924     if (ST->isIndexed())
7925       return false;
7926     VT = ST->getMemoryVT();
7927     if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
7928         !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
7929       return false;
7930     Ptr = ST->getBasePtr();
7931     isLoad = false;
7932   } else {
7933     return false;
7934   }
7935
7936   if (Ptr.getNode()->hasOneUse())
7937     return false;
7938
7939   for (SDNode *Op : Ptr.getNode()->uses()) {
7940     if (Op == N ||
7941         (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
7942       continue;
7943
7944     SDValue BasePtr;
7945     SDValue Offset;
7946     ISD::MemIndexedMode AM = ISD::UNINDEXED;
7947     if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
7948       // Don't create a indexed load / store with zero offset.
7949       if (isa<ConstantSDNode>(Offset) &&
7950           cast<ConstantSDNode>(Offset)->isNullValue())
7951         continue;
7952
7953       // Try turning it into a post-indexed load / store except when
7954       // 1) All uses are load / store ops that use it as base ptr (and
7955       //    it may be folded as addressing mmode).
7956       // 2) Op must be independent of N, i.e. Op is neither a predecessor
7957       //    nor a successor of N. Otherwise, if Op is folded that would
7958       //    create a cycle.
7959
7960       if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7961         continue;
7962
7963       // Check for #1.
7964       bool TryNext = false;
7965       for (SDNode *Use : BasePtr.getNode()->uses()) {
7966         if (Use == Ptr.getNode())
7967           continue;
7968
7969         // If all the uses are load / store addresses, then don't do the
7970         // transformation.
7971         if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
7972           bool RealUse = false;
7973           for (SDNode *UseUse : Use->uses()) {
7974             if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
7975               RealUse = true;
7976           }
7977
7978           if (!RealUse) {
7979             TryNext = true;
7980             break;
7981           }
7982         }
7983       }
7984
7985       if (TryNext)
7986         continue;
7987
7988       // Check for #2
7989       if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
7990         SDValue Result = isLoad
7991           ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
7992                                BasePtr, Offset, AM)
7993           : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
7994                                 BasePtr, Offset, AM);
7995         ++PostIndexedNodes;
7996         ++NodesCombined;
7997         DEBUG(dbgs() << "\nReplacing.5 ";
7998               N->dump(&DAG);
7999               dbgs() << "\nWith: ";
8000               Result.getNode()->dump(&DAG);
8001               dbgs() << '\n');
8002         WorklistRemover DeadNodes(*this);
8003         if (isLoad) {
8004           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
8005           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
8006         } else {
8007           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
8008         }
8009
8010         // Finally, since the node is now dead, remove it from the graph.
8011         deleteAndRecombine(N);
8012
8013         // Replace the uses of Use with uses of the updated base value.
8014         DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
8015                                       Result.getValue(isLoad ? 1 : 0));
8016         deleteAndRecombine(Op);
8017         return true;
8018       }
8019     }
8020   }
8021
8022   return false;
8023 }
8024
8025 SDValue DAGCombiner::visitLOAD(SDNode *N) {
8026   LoadSDNode *LD  = cast<LoadSDNode>(N);
8027   SDValue Chain = LD->getChain();
8028   SDValue Ptr   = LD->getBasePtr();
8029
8030   // If load is not volatile and there are no uses of the loaded value (and
8031   // the updated indexed value in case of indexed loads), change uses of the
8032   // chain value into uses of the chain input (i.e. delete the dead load).
8033   if (!LD->isVolatile()) {
8034     if (N->getValueType(1) == MVT::Other) {
8035       // Unindexed loads.
8036       if (!N->hasAnyUseOfValue(0)) {
8037         // It's not safe to use the two value CombineTo variant here. e.g.
8038         // v1, chain2 = load chain1, loc
8039         // v2, chain3 = load chain2, loc
8040         // v3         = add v2, c
8041         // Now we replace use of chain2 with chain1.  This makes the second load
8042         // isomorphic to the one we are deleting, and thus makes this load live.
8043         DEBUG(dbgs() << "\nReplacing.6 ";
8044               N->dump(&DAG);
8045               dbgs() << "\nWith chain: ";
8046               Chain.getNode()->dump(&DAG);
8047               dbgs() << "\n");
8048         WorklistRemover DeadNodes(*this);
8049         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
8050
8051         if (N->use_empty())
8052           deleteAndRecombine(N);
8053
8054         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
8055       }
8056     } else {
8057       // Indexed loads.
8058       assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
8059       if (!N->hasAnyUseOfValue(0) && !N->hasAnyUseOfValue(1)) {
8060         SDValue Undef = DAG.getUNDEF(N->getValueType(0));
8061         DEBUG(dbgs() << "\nReplacing.7 ";
8062               N->dump(&DAG);
8063               dbgs() << "\nWith: ";
8064               Undef.getNode()->dump(&DAG);
8065               dbgs() << " and 2 other values\n");
8066         WorklistRemover DeadNodes(*this);
8067         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
8068         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1),
8069                                       DAG.getUNDEF(N->getValueType(1)));
8070         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
8071         deleteAndRecombine(N);
8072         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
8073       }
8074     }
8075   }
8076
8077   // If this load is directly stored, replace the load value with the stored
8078   // value.
8079   // TODO: Handle store large -> read small portion.
8080   // TODO: Handle TRUNCSTORE/LOADEXT
8081   if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
8082     if (ISD::isNON_TRUNCStore(Chain.getNode())) {
8083       StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
8084       if (PrevST->getBasePtr() == Ptr &&
8085           PrevST->getValue().getValueType() == N->getValueType(0))
8086       return CombineTo(N, Chain.getOperand(1), Chain);
8087     }
8088   }
8089
8090   // Try to infer better alignment information than the load already has.
8091   if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
8092     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
8093       if (Align > LD->getMemOperand()->getBaseAlignment()) {
8094         SDValue NewLoad =
8095                DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
8096                               LD->getValueType(0),
8097                               Chain, Ptr, LD->getPointerInfo(),
8098                               LD->getMemoryVT(),
8099                               LD->isVolatile(), LD->isNonTemporal(),
8100                               LD->isInvariant(), Align, LD->getAAInfo());
8101         return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
8102       }
8103     }
8104   }
8105
8106   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
8107     TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
8108 #ifndef NDEBUG
8109   if (CombinerAAOnlyFunc.getNumOccurrences() &&
8110       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
8111     UseAA = false;
8112 #endif
8113   if (UseAA && LD->isUnindexed()) {
8114     // Walk up chain skipping non-aliasing memory nodes.
8115     SDValue BetterChain = FindBetterChain(N, Chain);
8116
8117     // If there is a better chain.
8118     if (Chain != BetterChain) {
8119       SDValue ReplLoad;
8120
8121       // Replace the chain to void dependency.
8122       if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
8123         ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
8124                                BetterChain, Ptr, LD->getMemOperand());
8125       } else {
8126         ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
8127                                   LD->getValueType(0),
8128                                   BetterChain, Ptr, LD->getMemoryVT(),
8129                                   LD->getMemOperand());
8130       }
8131
8132       // Create token factor to keep old chain connected.
8133       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
8134                                   MVT::Other, Chain, ReplLoad.getValue(1));
8135
8136       // Make sure the new and old chains are cleaned up.
8137       AddToWorklist(Token.getNode());
8138
8139       // Replace uses with load result and token factor. Don't add users
8140       // to work list.
8141       return CombineTo(N, ReplLoad.getValue(0), Token, false);
8142     }
8143   }
8144
8145   // Try transforming N to an indexed load.
8146   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
8147     return SDValue(N, 0);
8148
8149   // Try to slice up N to more direct loads if the slices are mapped to
8150   // different register banks or pairing can take place.
8151   if (SliceUpLoad(N))
8152     return SDValue(N, 0);
8153
8154   return SDValue();
8155 }
8156
8157 namespace {
8158 /// \brief Helper structure used to slice a load in smaller loads.
8159 /// Basically a slice is obtained from the following sequence:
8160 /// Origin = load Ty1, Base
8161 /// Shift = srl Ty1 Origin, CstTy Amount
8162 /// Inst = trunc Shift to Ty2
8163 ///
8164 /// Then, it will be rewriten into:
8165 /// Slice = load SliceTy, Base + SliceOffset
8166 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
8167 ///
8168 /// SliceTy is deduced from the number of bits that are actually used to
8169 /// build Inst.
8170 struct LoadedSlice {
8171   /// \brief Helper structure used to compute the cost of a slice.
8172   struct Cost {
8173     /// Are we optimizing for code size.
8174     bool ForCodeSize;
8175     /// Various cost.
8176     unsigned Loads;
8177     unsigned Truncates;
8178     unsigned CrossRegisterBanksCopies;
8179     unsigned ZExts;
8180     unsigned Shift;
8181
8182     Cost(bool ForCodeSize = false)
8183         : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
8184           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
8185
8186     /// \brief Get the cost of one isolated slice.
8187     Cost(const LoadedSlice &LS, bool ForCodeSize = false)
8188         : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
8189           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
8190       EVT TruncType = LS.Inst->getValueType(0);
8191       EVT LoadedType = LS.getLoadedType();
8192       if (TruncType != LoadedType &&
8193           !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
8194         ZExts = 1;
8195     }
8196
8197     /// \brief Account for slicing gain in the current cost.
8198     /// Slicing provide a few gains like removing a shift or a
8199     /// truncate. This method allows to grow the cost of the original
8200     /// load with the gain from this slice.
8201     void addSliceGain(const LoadedSlice &LS) {
8202       // Each slice saves a truncate.
8203       const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
8204       if (!TLI.isTruncateFree(LS.Inst->getValueType(0),
8205                               LS.Inst->getOperand(0).getValueType()))
8206         ++Truncates;
8207       // If there is a shift amount, this slice gets rid of it.
8208       if (LS.Shift)
8209         ++Shift;
8210       // If this slice can merge a cross register bank copy, account for it.
8211       if (LS.canMergeExpensiveCrossRegisterBankCopy())
8212         ++CrossRegisterBanksCopies;
8213     }
8214
8215     Cost &operator+=(const Cost &RHS) {
8216       Loads += RHS.Loads;
8217       Truncates += RHS.Truncates;
8218       CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
8219       ZExts += RHS.ZExts;
8220       Shift += RHS.Shift;
8221       return *this;
8222     }
8223
8224     bool operator==(const Cost &RHS) const {
8225       return Loads == RHS.Loads && Truncates == RHS.Truncates &&
8226              CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
8227              ZExts == RHS.ZExts && Shift == RHS.Shift;
8228     }
8229
8230     bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
8231
8232     bool operator<(const Cost &RHS) const {
8233       // Assume cross register banks copies are as expensive as loads.
8234       // FIXME: Do we want some more target hooks?
8235       unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
8236       unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
8237       // Unless we are optimizing for code size, consider the
8238       // expensive operation first.
8239       if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
8240         return ExpensiveOpsLHS < ExpensiveOpsRHS;
8241       return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
8242              (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
8243     }
8244
8245     bool operator>(const Cost &RHS) const { return RHS < *this; }
8246
8247     bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
8248
8249     bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
8250   };
8251   // The last instruction that represent the slice. This should be a
8252   // truncate instruction.
8253   SDNode *Inst;
8254   // The original load instruction.
8255   LoadSDNode *Origin;
8256   // The right shift amount in bits from the original load.
8257   unsigned Shift;
8258   // The DAG from which Origin came from.
8259   // This is used to get some contextual information about legal types, etc.
8260   SelectionDAG *DAG;
8261
8262   LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
8263               unsigned Shift = 0, SelectionDAG *DAG = nullptr)
8264       : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
8265
8266   LoadedSlice(const LoadedSlice &LS)
8267       : Inst(LS.Inst), Origin(LS.Origin), Shift(LS.Shift), DAG(LS.DAG) {}
8268
8269   /// \brief Get the bits used in a chunk of bits \p BitWidth large.
8270   /// \return Result is \p BitWidth and has used bits set to 1 and
8271   ///         not used bits set to 0.
8272   APInt getUsedBits() const {
8273     // Reproduce the trunc(lshr) sequence:
8274     // - Start from the truncated value.
8275     // - Zero extend to the desired bit width.
8276     // - Shift left.
8277     assert(Origin && "No original load to compare against.");
8278     unsigned BitWidth = Origin->getValueSizeInBits(0);
8279     assert(Inst && "This slice is not bound to an instruction");
8280     assert(Inst->getValueSizeInBits(0) <= BitWidth &&
8281            "Extracted slice is bigger than the whole type!");
8282     APInt UsedBits(Inst->getValueSizeInBits(0), 0);
8283     UsedBits.setAllBits();
8284     UsedBits = UsedBits.zext(BitWidth);
8285     UsedBits <<= Shift;
8286     return UsedBits;
8287   }
8288
8289   /// \brief Get the size of the slice to be loaded in bytes.
8290   unsigned getLoadedSize() const {
8291     unsigned SliceSize = getUsedBits().countPopulation();
8292     assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
8293     return SliceSize / 8;
8294   }
8295
8296   /// \brief Get the type that will be loaded for this slice.
8297   /// Note: This may not be the final type for the slice.
8298   EVT getLoadedType() const {
8299     assert(DAG && "Missing context");
8300     LLVMContext &Ctxt = *DAG->getContext();
8301     return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
8302   }
8303
8304   /// \brief Get the alignment of the load used for this slice.
8305   unsigned getAlignment() const {
8306     unsigned Alignment = Origin->getAlignment();
8307     unsigned Offset = getOffsetFromBase();
8308     if (Offset != 0)
8309       Alignment = MinAlign(Alignment, Alignment + Offset);
8310     return Alignment;
8311   }
8312
8313   /// \brief Check if this slice can be rewritten with legal operations.
8314   bool isLegal() const {
8315     // An invalid slice is not legal.
8316     if (!Origin || !Inst || !DAG)
8317       return false;
8318
8319     // Offsets are for indexed load only, we do not handle that.
8320     if (Origin->getOffset().getOpcode() != ISD::UNDEF)
8321       return false;
8322
8323     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8324
8325     // Check that the type is legal.
8326     EVT SliceType = getLoadedType();
8327     if (!TLI.isTypeLegal(SliceType))
8328       return false;
8329
8330     // Check that the load is legal for this type.
8331     if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
8332       return false;
8333
8334     // Check that the offset can be computed.
8335     // 1. Check its type.
8336     EVT PtrType = Origin->getBasePtr().getValueType();
8337     if (PtrType == MVT::Untyped || PtrType.isExtended())
8338       return false;
8339
8340     // 2. Check that it fits in the immediate.
8341     if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
8342       return false;
8343
8344     // 3. Check that the computation is legal.
8345     if (!TLI.isOperationLegal(ISD::ADD, PtrType))
8346       return false;
8347
8348     // Check that the zext is legal if it needs one.
8349     EVT TruncateType = Inst->getValueType(0);
8350     if (TruncateType != SliceType &&
8351         !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
8352       return false;
8353
8354     return true;
8355   }
8356
8357   /// \brief Get the offset in bytes of this slice in the original chunk of
8358   /// bits.
8359   /// \pre DAG != nullptr.
8360   uint64_t getOffsetFromBase() const {
8361     assert(DAG && "Missing context.");
8362     bool IsBigEndian =
8363         DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian();
8364     assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
8365     uint64_t Offset = Shift / 8;
8366     unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
8367     assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
8368            "The size of the original loaded type is not a multiple of a"
8369            " byte.");
8370     // If Offset is bigger than TySizeInBytes, it means we are loading all
8371     // zeros. This should have been optimized before in the process.
8372     assert(TySizeInBytes > Offset &&
8373            "Invalid shift amount for given loaded size");
8374     if (IsBigEndian)
8375       Offset = TySizeInBytes - Offset - getLoadedSize();
8376     return Offset;
8377   }
8378
8379   /// \brief Generate the sequence of instructions to load the slice
8380   /// represented by this object and redirect the uses of this slice to
8381   /// this new sequence of instructions.
8382   /// \pre this->Inst && this->Origin are valid Instructions and this
8383   /// object passed the legal check: LoadedSlice::isLegal returned true.
8384   /// \return The last instruction of the sequence used to load the slice.
8385   SDValue loadSlice() const {
8386     assert(Inst && Origin && "Unable to replace a non-existing slice.");
8387     const SDValue &OldBaseAddr = Origin->getBasePtr();
8388     SDValue BaseAddr = OldBaseAddr;
8389     // Get the offset in that chunk of bytes w.r.t. the endianess.
8390     int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
8391     assert(Offset >= 0 && "Offset too big to fit in int64_t!");
8392     if (Offset) {
8393       // BaseAddr = BaseAddr + Offset.
8394       EVT ArithType = BaseAddr.getValueType();
8395       BaseAddr = DAG->getNode(ISD::ADD, SDLoc(Origin), ArithType, BaseAddr,
8396                               DAG->getConstant(Offset, ArithType));
8397     }
8398
8399     // Create the type of the loaded slice according to its size.
8400     EVT SliceType = getLoadedType();
8401
8402     // Create the load for the slice.
8403     SDValue LastInst = DAG->getLoad(
8404         SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
8405         Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
8406         Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
8407     // If the final type is not the same as the loaded type, this means that
8408     // we have to pad with zero. Create a zero extend for that.
8409     EVT FinalType = Inst->getValueType(0);
8410     if (SliceType != FinalType)
8411       LastInst =
8412           DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
8413     return LastInst;
8414   }
8415
8416   /// \brief Check if this slice can be merged with an expensive cross register
8417   /// bank copy. E.g.,
8418   /// i = load i32
8419   /// f = bitcast i32 i to float
8420   bool canMergeExpensiveCrossRegisterBankCopy() const {
8421     if (!Inst || !Inst->hasOneUse())
8422       return false;
8423     SDNode *Use = *Inst->use_begin();
8424     if (Use->getOpcode() != ISD::BITCAST)
8425       return false;
8426     assert(DAG && "Missing context");
8427     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8428     EVT ResVT = Use->getValueType(0);
8429     const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
8430     const TargetRegisterClass *ArgRC =
8431         TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
8432     if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
8433       return false;
8434
8435     // At this point, we know that we perform a cross-register-bank copy.
8436     // Check if it is expensive.
8437     const TargetRegisterInfo *TRI =
8438         TLI.getTargetMachine().getSubtargetImpl()->getRegisterInfo();
8439     // Assume bitcasts are cheap, unless both register classes do not
8440     // explicitly share a common sub class.
8441     if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
8442       return false;
8443
8444     // Check if it will be merged with the load.
8445     // 1. Check the alignment constraint.
8446     unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment(
8447         ResVT.getTypeForEVT(*DAG->getContext()));
8448
8449     if (RequiredAlignment > getAlignment())
8450       return false;
8451
8452     // 2. Check that the load is a legal operation for that type.
8453     if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
8454       return false;
8455
8456     // 3. Check that we do not have a zext in the way.
8457     if (Inst->getValueType(0) != getLoadedType())
8458       return false;
8459
8460     return true;
8461   }
8462 };
8463 }
8464
8465 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
8466 /// \p UsedBits looks like 0..0 1..1 0..0.
8467 static bool areUsedBitsDense(const APInt &UsedBits) {
8468   // If all the bits are one, this is dense!
8469   if (UsedBits.isAllOnesValue())
8470     return true;
8471
8472   // Get rid of the unused bits on the right.
8473   APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
8474   // Get rid of the unused bits on the left.
8475   if (NarrowedUsedBits.countLeadingZeros())
8476     NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
8477   // Check that the chunk of bits is completely used.
8478   return NarrowedUsedBits.isAllOnesValue();
8479 }
8480
8481 /// \brief Check whether or not \p First and \p Second are next to each other
8482 /// in memory. This means that there is no hole between the bits loaded
8483 /// by \p First and the bits loaded by \p Second.
8484 static bool areSlicesNextToEachOther(const LoadedSlice &First,
8485                                      const LoadedSlice &Second) {
8486   assert(First.Origin == Second.Origin && First.Origin &&
8487          "Unable to match different memory origins.");
8488   APInt UsedBits = First.getUsedBits();
8489   assert((UsedBits & Second.getUsedBits()) == 0 &&
8490          "Slices are not supposed to overlap.");
8491   UsedBits |= Second.getUsedBits();
8492   return areUsedBitsDense(UsedBits);
8493 }
8494
8495 /// \brief Adjust the \p GlobalLSCost according to the target
8496 /// paring capabilities and the layout of the slices.
8497 /// \pre \p GlobalLSCost should account for at least as many loads as
8498 /// there is in the slices in \p LoadedSlices.
8499 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8500                                  LoadedSlice::Cost &GlobalLSCost) {
8501   unsigned NumberOfSlices = LoadedSlices.size();
8502   // If there is less than 2 elements, no pairing is possible.
8503   if (NumberOfSlices < 2)
8504     return;
8505
8506   // Sort the slices so that elements that are likely to be next to each
8507   // other in memory are next to each other in the list.
8508   std::sort(LoadedSlices.begin(), LoadedSlices.end(),
8509             [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
8510     assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
8511     return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
8512   });
8513   const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
8514   // First (resp. Second) is the first (resp. Second) potentially candidate
8515   // to be placed in a paired load.
8516   const LoadedSlice *First = nullptr;
8517   const LoadedSlice *Second = nullptr;
8518   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
8519                 // Set the beginning of the pair.
8520                                                            First = Second) {
8521
8522     Second = &LoadedSlices[CurrSlice];
8523
8524     // If First is NULL, it means we start a new pair.
8525     // Get to the next slice.
8526     if (!First)
8527       continue;
8528
8529     EVT LoadedType = First->getLoadedType();
8530
8531     // If the types of the slices are different, we cannot pair them.
8532     if (LoadedType != Second->getLoadedType())
8533       continue;
8534
8535     // Check if the target supplies paired loads for this type.
8536     unsigned RequiredAlignment = 0;
8537     if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
8538       // move to the next pair, this type is hopeless.
8539       Second = nullptr;
8540       continue;
8541     }
8542     // Check if we meet the alignment requirement.
8543     if (RequiredAlignment > First->getAlignment())
8544       continue;
8545
8546     // Check that both loads are next to each other in memory.
8547     if (!areSlicesNextToEachOther(*First, *Second))
8548       continue;
8549
8550     assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
8551     --GlobalLSCost.Loads;
8552     // Move to the next pair.
8553     Second = nullptr;
8554   }
8555 }
8556
8557 /// \brief Check the profitability of all involved LoadedSlice.
8558 /// Currently, it is considered profitable if there is exactly two
8559 /// involved slices (1) which are (2) next to each other in memory, and
8560 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
8561 ///
8562 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
8563 /// the elements themselves.
8564 ///
8565 /// FIXME: When the cost model will be mature enough, we can relax
8566 /// constraints (1) and (2).
8567 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8568                                 const APInt &UsedBits, bool ForCodeSize) {
8569   unsigned NumberOfSlices = LoadedSlices.size();
8570   if (StressLoadSlicing)
8571     return NumberOfSlices > 1;
8572
8573   // Check (1).
8574   if (NumberOfSlices != 2)
8575     return false;
8576
8577   // Check (2).
8578   if (!areUsedBitsDense(UsedBits))
8579     return false;
8580
8581   // Check (3).
8582   LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
8583   // The original code has one big load.
8584   OrigCost.Loads = 1;
8585   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
8586     const LoadedSlice &LS = LoadedSlices[CurrSlice];
8587     // Accumulate the cost of all the slices.
8588     LoadedSlice::Cost SliceCost(LS, ForCodeSize);
8589     GlobalSlicingCost += SliceCost;
8590
8591     // Account as cost in the original configuration the gain obtained
8592     // with the current slices.
8593     OrigCost.addSliceGain(LS);
8594   }
8595
8596   // If the target supports paired load, adjust the cost accordingly.
8597   adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
8598   return OrigCost > GlobalSlicingCost;
8599 }
8600
8601 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
8602 /// operations, split it in the various pieces being extracted.
8603 ///
8604 /// This sort of thing is introduced by SROA.
8605 /// This slicing takes care not to insert overlapping loads.
8606 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
8607 bool DAGCombiner::SliceUpLoad(SDNode *N) {
8608   if (Level < AfterLegalizeDAG)
8609     return false;
8610
8611   LoadSDNode *LD = cast<LoadSDNode>(N);
8612   if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
8613       !LD->getValueType(0).isInteger())
8614     return false;
8615
8616   // Keep track of already used bits to detect overlapping values.
8617   // In that case, we will just abort the transformation.
8618   APInt UsedBits(LD->getValueSizeInBits(0), 0);
8619
8620   SmallVector<LoadedSlice, 4> LoadedSlices;
8621
8622   // Check if this load is used as several smaller chunks of bits.
8623   // Basically, look for uses in trunc or trunc(lshr) and record a new chain
8624   // of computation for each trunc.
8625   for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
8626        UI != UIEnd; ++UI) {
8627     // Skip the uses of the chain.
8628     if (UI.getUse().getResNo() != 0)
8629       continue;
8630
8631     SDNode *User = *UI;
8632     unsigned Shift = 0;
8633
8634     // Check if this is a trunc(lshr).
8635     if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
8636         isa<ConstantSDNode>(User->getOperand(1))) {
8637       Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
8638       User = *User->use_begin();
8639     }
8640
8641     // At this point, User is a Truncate, iff we encountered, trunc or
8642     // trunc(lshr).
8643     if (User->getOpcode() != ISD::TRUNCATE)
8644       return false;
8645
8646     // The width of the type must be a power of 2 and greater than 8-bits.
8647     // Otherwise the load cannot be represented in LLVM IR.
8648     // Moreover, if we shifted with a non-8-bits multiple, the slice
8649     // will be across several bytes. We do not support that.
8650     unsigned Width = User->getValueSizeInBits(0);
8651     if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
8652       return 0;
8653
8654     // Build the slice for this chain of computations.
8655     LoadedSlice LS(User, LD, Shift, &DAG);
8656     APInt CurrentUsedBits = LS.getUsedBits();
8657
8658     // Check if this slice overlaps with another.
8659     if ((CurrentUsedBits & UsedBits) != 0)
8660       return false;
8661     // Update the bits used globally.
8662     UsedBits |= CurrentUsedBits;
8663
8664     // Check if the new slice would be legal.
8665     if (!LS.isLegal())
8666       return false;
8667
8668     // Record the slice.
8669     LoadedSlices.push_back(LS);
8670   }
8671
8672   // Abort slicing if it does not seem to be profitable.
8673   if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
8674     return false;
8675
8676   ++SlicedLoads;
8677
8678   // Rewrite each chain to use an independent load.
8679   // By construction, each chain can be represented by a unique load.
8680
8681   // Prepare the argument for the new token factor for all the slices.
8682   SmallVector<SDValue, 8> ArgChains;
8683   for (SmallVectorImpl<LoadedSlice>::const_iterator
8684            LSIt = LoadedSlices.begin(),
8685            LSItEnd = LoadedSlices.end();
8686        LSIt != LSItEnd; ++LSIt) {
8687     SDValue SliceInst = LSIt->loadSlice();
8688     CombineTo(LSIt->Inst, SliceInst, true);
8689     if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
8690       SliceInst = SliceInst.getOperand(0);
8691     assert(SliceInst->getOpcode() == ISD::LOAD &&
8692            "It takes more than a zext to get to the loaded slice!!");
8693     ArgChains.push_back(SliceInst.getValue(1));
8694   }
8695
8696   SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
8697                               ArgChains);
8698   DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
8699   return true;
8700 }
8701
8702 /// CheckForMaskedLoad - Check to see if V is (and load (ptr), imm), where the
8703 /// load is having specific bytes cleared out.  If so, return the byte size
8704 /// being masked out and the shift amount.
8705 static std::pair<unsigned, unsigned>
8706 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
8707   std::pair<unsigned, unsigned> Result(0, 0);
8708
8709   // Check for the structure we're looking for.
8710   if (V->getOpcode() != ISD::AND ||
8711       !isa<ConstantSDNode>(V->getOperand(1)) ||
8712       !ISD::isNormalLoad(V->getOperand(0).getNode()))
8713     return Result;
8714
8715   // Check the chain and pointer.
8716   LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
8717   if (LD->getBasePtr() != Ptr) return Result;  // Not from same pointer.
8718
8719   // The store should be chained directly to the load or be an operand of a
8720   // tokenfactor.
8721   if (LD == Chain.getNode())
8722     ; // ok.
8723   else if (Chain->getOpcode() != ISD::TokenFactor)
8724     return Result; // Fail.
8725   else {
8726     bool isOk = false;
8727     for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
8728       if (Chain->getOperand(i).getNode() == LD) {
8729         isOk = true;
8730         break;
8731       }
8732     if (!isOk) return Result;
8733   }
8734
8735   // This only handles simple types.
8736   if (V.getValueType() != MVT::i16 &&
8737       V.getValueType() != MVT::i32 &&
8738       V.getValueType() != MVT::i64)
8739     return Result;
8740
8741   // Check the constant mask.  Invert it so that the bits being masked out are
8742   // 0 and the bits being kept are 1.  Use getSExtValue so that leading bits
8743   // follow the sign bit for uniformity.
8744   uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
8745   unsigned NotMaskLZ = countLeadingZeros(NotMask);
8746   if (NotMaskLZ & 7) return Result;  // Must be multiple of a byte.
8747   unsigned NotMaskTZ = countTrailingZeros(NotMask);
8748   if (NotMaskTZ & 7) return Result;  // Must be multiple of a byte.
8749   if (NotMaskLZ == 64) return Result;  // All zero mask.
8750
8751   // See if we have a continuous run of bits.  If so, we have 0*1+0*
8752   if (CountTrailingOnes_64(NotMask >> NotMaskTZ)+NotMaskTZ+NotMaskLZ != 64)
8753     return Result;
8754
8755   // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
8756   if (V.getValueType() != MVT::i64 && NotMaskLZ)
8757     NotMaskLZ -= 64-V.getValueSizeInBits();
8758
8759   unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
8760   switch (MaskedBytes) {
8761   case 1:
8762   case 2:
8763   case 4: break;
8764   default: return Result; // All one mask, or 5-byte mask.
8765   }
8766
8767   // Verify that the first bit starts at a multiple of mask so that the access
8768   // is aligned the same as the access width.
8769   if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
8770
8771   Result.first = MaskedBytes;
8772   Result.second = NotMaskTZ/8;
8773   return Result;
8774 }
8775
8776
8777 /// ShrinkLoadReplaceStoreWithStore - Check to see if IVal is something that
8778 /// provides a value as specified by MaskInfo.  If so, replace the specified
8779 /// store with a narrower store of truncated IVal.
8780 static SDNode *
8781 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
8782                                 SDValue IVal, StoreSDNode *St,
8783                                 DAGCombiner *DC) {
8784   unsigned NumBytes = MaskInfo.first;
8785   unsigned ByteShift = MaskInfo.second;
8786   SelectionDAG &DAG = DC->getDAG();
8787
8788   // Check to see if IVal is all zeros in the part being masked in by the 'or'
8789   // that uses this.  If not, this is not a replacement.
8790   APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
8791                                   ByteShift*8, (ByteShift+NumBytes)*8);
8792   if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
8793
8794   // Check that it is legal on the target to do this.  It is legal if the new
8795   // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
8796   // legalization.
8797   MVT VT = MVT::getIntegerVT(NumBytes*8);
8798   if (!DC->isTypeLegal(VT))
8799     return nullptr;
8800
8801   // Okay, we can do this!  Replace the 'St' store with a store of IVal that is
8802   // shifted by ByteShift and truncated down to NumBytes.
8803   if (ByteShift)
8804     IVal = DAG.getNode(ISD::SRL, SDLoc(IVal), IVal.getValueType(), IVal,
8805                        DAG.getConstant(ByteShift*8,
8806                                     DC->getShiftAmountTy(IVal.getValueType())));
8807
8808   // Figure out the offset for the store and the alignment of the access.
8809   unsigned StOffset;
8810   unsigned NewAlign = St->getAlignment();
8811
8812   if (DAG.getTargetLoweringInfo().isLittleEndian())
8813     StOffset = ByteShift;
8814   else
8815     StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
8816
8817   SDValue Ptr = St->getBasePtr();
8818   if (StOffset) {
8819     Ptr = DAG.getNode(ISD::ADD, SDLoc(IVal), Ptr.getValueType(),
8820                       Ptr, DAG.getConstant(StOffset, Ptr.getValueType()));
8821     NewAlign = MinAlign(NewAlign, StOffset);
8822   }
8823
8824   // Truncate down to the new size.
8825   IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
8826
8827   ++OpsNarrowed;
8828   return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
8829                       St->getPointerInfo().getWithOffset(StOffset),
8830                       false, false, NewAlign).getNode();
8831 }
8832
8833
8834 /// ReduceLoadOpStoreWidth - Look for sequence of load / op / store where op is
8835 /// one of 'or', 'xor', and 'and' of immediates. If 'op' is only touching some
8836 /// of the loaded bits, try narrowing the load and store if it would end up
8837 /// being a win for performance or code size.
8838 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
8839   StoreSDNode *ST  = cast<StoreSDNode>(N);
8840   if (ST->isVolatile())
8841     return SDValue();
8842
8843   SDValue Chain = ST->getChain();
8844   SDValue Value = ST->getValue();
8845   SDValue Ptr   = ST->getBasePtr();
8846   EVT VT = Value.getValueType();
8847
8848   if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
8849     return SDValue();
8850
8851   unsigned Opc = Value.getOpcode();
8852
8853   // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
8854   // is a byte mask indicating a consecutive number of bytes, check to see if
8855   // Y is known to provide just those bytes.  If so, we try to replace the
8856   // load + replace + store sequence with a single (narrower) store, which makes
8857   // the load dead.
8858   if (Opc == ISD::OR) {
8859     std::pair<unsigned, unsigned> MaskedLoad;
8860     MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
8861     if (MaskedLoad.first)
8862       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8863                                                   Value.getOperand(1), ST,this))
8864         return SDValue(NewST, 0);
8865
8866     // Or is commutative, so try swapping X and Y.
8867     MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
8868     if (MaskedLoad.first)
8869       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8870                                                   Value.getOperand(0), ST,this))
8871         return SDValue(NewST, 0);
8872   }
8873
8874   if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
8875       Value.getOperand(1).getOpcode() != ISD::Constant)
8876     return SDValue();
8877
8878   SDValue N0 = Value.getOperand(0);
8879   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8880       Chain == SDValue(N0.getNode(), 1)) {
8881     LoadSDNode *LD = cast<LoadSDNode>(N0);
8882     if (LD->getBasePtr() != Ptr ||
8883         LD->getPointerInfo().getAddrSpace() !=
8884         ST->getPointerInfo().getAddrSpace())
8885       return SDValue();
8886
8887     // Find the type to narrow it the load / op / store to.
8888     SDValue N1 = Value.getOperand(1);
8889     unsigned BitWidth = N1.getValueSizeInBits();
8890     APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
8891     if (Opc == ISD::AND)
8892       Imm ^= APInt::getAllOnesValue(BitWidth);
8893     if (Imm == 0 || Imm.isAllOnesValue())
8894       return SDValue();
8895     unsigned ShAmt = Imm.countTrailingZeros();
8896     unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
8897     unsigned NewBW = NextPowerOf2(MSB - ShAmt);
8898     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
8899     while (NewBW < BitWidth &&
8900            !(TLI.isOperationLegalOrCustom(Opc, NewVT) &&
8901              TLI.isNarrowingProfitable(VT, NewVT))) {
8902       NewBW = NextPowerOf2(NewBW);
8903       NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
8904     }
8905     if (NewBW >= BitWidth)
8906       return SDValue();
8907
8908     // If the lsb changed does not start at the type bitwidth boundary,
8909     // start at the previous one.
8910     if (ShAmt % NewBW)
8911       ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
8912     APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
8913                                    std::min(BitWidth, ShAmt + NewBW));
8914     if ((Imm & Mask) == Imm) {
8915       APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
8916       if (Opc == ISD::AND)
8917         NewImm ^= APInt::getAllOnesValue(NewBW);
8918       uint64_t PtrOff = ShAmt / 8;
8919       // For big endian targets, we need to adjust the offset to the pointer to
8920       // load the correct bytes.
8921       if (TLI.isBigEndian())
8922         PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
8923
8924       unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
8925       Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
8926       if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
8927         return SDValue();
8928
8929       SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
8930                                    Ptr.getValueType(), Ptr,
8931                                    DAG.getConstant(PtrOff, Ptr.getValueType()));
8932       SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
8933                                   LD->getChain(), NewPtr,
8934                                   LD->getPointerInfo().getWithOffset(PtrOff),
8935                                   LD->isVolatile(), LD->isNonTemporal(),
8936                                   LD->isInvariant(), NewAlign,
8937                                   LD->getAAInfo());
8938       SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
8939                                    DAG.getConstant(NewImm, NewVT));
8940       SDValue NewST = DAG.getStore(Chain, SDLoc(N),
8941                                    NewVal, NewPtr,
8942                                    ST->getPointerInfo().getWithOffset(PtrOff),
8943                                    false, false, NewAlign);
8944
8945       AddToWorklist(NewPtr.getNode());
8946       AddToWorklist(NewLD.getNode());
8947       AddToWorklist(NewVal.getNode());
8948       WorklistRemover DeadNodes(*this);
8949       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
8950       ++OpsNarrowed;
8951       return NewST;
8952     }
8953   }
8954
8955   return SDValue();
8956 }
8957
8958 /// TransformFPLoadStorePair - For a given floating point load / store pair,
8959 /// if the load value isn't used by any other operations, then consider
8960 /// transforming the pair to integer load / store operations if the target
8961 /// deems the transformation profitable.
8962 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
8963   StoreSDNode *ST  = cast<StoreSDNode>(N);
8964   SDValue Chain = ST->getChain();
8965   SDValue Value = ST->getValue();
8966   if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
8967       Value.hasOneUse() &&
8968       Chain == SDValue(Value.getNode(), 1)) {
8969     LoadSDNode *LD = cast<LoadSDNode>(Value);
8970     EVT VT = LD->getMemoryVT();
8971     if (!VT.isFloatingPoint() ||
8972         VT != ST->getMemoryVT() ||
8973         LD->isNonTemporal() ||
8974         ST->isNonTemporal() ||
8975         LD->getPointerInfo().getAddrSpace() != 0 ||
8976         ST->getPointerInfo().getAddrSpace() != 0)
8977       return SDValue();
8978
8979     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
8980     if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
8981         !TLI.isOperationLegal(ISD::STORE, IntVT) ||
8982         !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
8983         !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
8984       return SDValue();
8985
8986     unsigned LDAlign = LD->getAlignment();
8987     unsigned STAlign = ST->getAlignment();
8988     Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
8989     unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
8990     if (LDAlign < ABIAlign || STAlign < ABIAlign)
8991       return SDValue();
8992
8993     SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
8994                                 LD->getChain(), LD->getBasePtr(),
8995                                 LD->getPointerInfo(),
8996                                 false, false, false, LDAlign);
8997
8998     SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
8999                                  NewLD, ST->getBasePtr(),
9000                                  ST->getPointerInfo(),
9001                                  false, false, STAlign);
9002
9003     AddToWorklist(NewLD.getNode());
9004     AddToWorklist(NewST.getNode());
9005     WorklistRemover DeadNodes(*this);
9006     DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
9007     ++LdStFP2Int;
9008     return NewST;
9009   }
9010
9011   return SDValue();
9012 }
9013
9014 /// Helper struct to parse and store a memory address as base + index + offset.
9015 /// We ignore sign extensions when it is safe to do so.
9016 /// The following two expressions are not equivalent. To differentiate we need
9017 /// to store whether there was a sign extension involved in the index
9018 /// computation.
9019 ///  (load (i64 add (i64 copyfromreg %c)
9020 ///                 (i64 signextend (add (i8 load %index)
9021 ///                                      (i8 1))))
9022 /// vs
9023 ///
9024 /// (load (i64 add (i64 copyfromreg %c)
9025 ///                (i64 signextend (i32 add (i32 signextend (i8 load %index))
9026 ///                                         (i32 1)))))
9027 struct BaseIndexOffset {
9028   SDValue Base;
9029   SDValue Index;
9030   int64_t Offset;
9031   bool IsIndexSignExt;
9032
9033   BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
9034
9035   BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
9036                   bool IsIndexSignExt) :
9037     Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
9038
9039   bool equalBaseIndex(const BaseIndexOffset &Other) {
9040     return Other.Base == Base && Other.Index == Index &&
9041       Other.IsIndexSignExt == IsIndexSignExt;
9042   }
9043
9044   /// Parses tree in Ptr for base, index, offset addresses.
9045   static BaseIndexOffset match(SDValue Ptr) {
9046     bool IsIndexSignExt = false;
9047
9048     // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
9049     // instruction, then it could be just the BASE or everything else we don't
9050     // know how to handle. Just use Ptr as BASE and give up.
9051     if (Ptr->getOpcode() != ISD::ADD)
9052       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9053
9054     // We know that we have at least an ADD instruction. Try to pattern match
9055     // the simple case of BASE + OFFSET.
9056     if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
9057       int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
9058       return  BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
9059                               IsIndexSignExt);
9060     }
9061
9062     // Inside a loop the current BASE pointer is calculated using an ADD and a
9063     // MUL instruction. In this case Ptr is the actual BASE pointer.
9064     // (i64 add (i64 %array_ptr)
9065     //          (i64 mul (i64 %induction_var)
9066     //                   (i64 %element_size)))
9067     if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
9068       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9069
9070     // Look at Base + Index + Offset cases.
9071     SDValue Base = Ptr->getOperand(0);
9072     SDValue IndexOffset = Ptr->getOperand(1);
9073
9074     // Skip signextends.
9075     if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
9076       IndexOffset = IndexOffset->getOperand(0);
9077       IsIndexSignExt = true;
9078     }
9079
9080     // Either the case of Base + Index (no offset) or something else.
9081     if (IndexOffset->getOpcode() != ISD::ADD)
9082       return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
9083
9084     // Now we have the case of Base + Index + offset.
9085     SDValue Index = IndexOffset->getOperand(0);
9086     SDValue Offset = IndexOffset->getOperand(1);
9087
9088     if (!isa<ConstantSDNode>(Offset))
9089       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9090
9091     // Ignore signextends.
9092     if (Index->getOpcode() == ISD::SIGN_EXTEND) {
9093       Index = Index->getOperand(0);
9094       IsIndexSignExt = true;
9095     } else IsIndexSignExt = false;
9096
9097     int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
9098     return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
9099   }
9100 };
9101
9102 /// Holds a pointer to an LSBaseSDNode as well as information on where it
9103 /// is located in a sequence of memory operations connected by a chain.
9104 struct MemOpLink {
9105   MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
9106     MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
9107   // Ptr to the mem node.
9108   LSBaseSDNode *MemNode;
9109   // Offset from the base ptr.
9110   int64_t OffsetFromBase;
9111   // What is the sequence number of this mem node.
9112   // Lowest mem operand in the DAG starts at zero.
9113   unsigned SequenceNum;
9114 };
9115
9116 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
9117   EVT MemVT = St->getMemoryVT();
9118   int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
9119   bool NoVectors = DAG.getMachineFunction().getFunction()->getAttributes().
9120     hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
9121
9122   // Don't merge vectors into wider inputs.
9123   if (MemVT.isVector() || !MemVT.isSimple())
9124     return false;
9125
9126   // Perform an early exit check. Do not bother looking at stored values that
9127   // are not constants or loads.
9128   SDValue StoredVal = St->getValue();
9129   bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
9130   if (!isa<ConstantSDNode>(StoredVal) && !isa<ConstantFPSDNode>(StoredVal) &&
9131       !IsLoadSrc)
9132     return false;
9133
9134   // Only look at ends of store sequences.
9135   SDValue Chain = SDValue(St, 0);
9136   if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
9137     return false;
9138
9139   // This holds the base pointer, index, and the offset in bytes from the base
9140   // pointer.
9141   BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
9142
9143   // We must have a base and an offset.
9144   if (!BasePtr.Base.getNode())
9145     return false;
9146
9147   // Do not handle stores to undef base pointers.
9148   if (BasePtr.Base.getOpcode() == ISD::UNDEF)
9149     return false;
9150
9151   // Save the LoadSDNodes that we find in the chain.
9152   // We need to make sure that these nodes do not interfere with
9153   // any of the store nodes.
9154   SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
9155
9156   // Save the StoreSDNodes that we find in the chain.
9157   SmallVector<MemOpLink, 8> StoreNodes;
9158
9159   // Walk up the chain and look for nodes with offsets from the same
9160   // base pointer. Stop when reaching an instruction with a different kind
9161   // or instruction which has a different base pointer.
9162   unsigned Seq = 0;
9163   StoreSDNode *Index = St;
9164   while (Index) {
9165     // If the chain has more than one use, then we can't reorder the mem ops.
9166     if (Index != St && !SDValue(Index, 0)->hasOneUse())
9167       break;
9168
9169     // Find the base pointer and offset for this memory node.
9170     BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
9171
9172     // Check that the base pointer is the same as the original one.
9173     if (!Ptr.equalBaseIndex(BasePtr))
9174       break;
9175
9176     // Check that the alignment is the same.
9177     if (Index->getAlignment() != St->getAlignment())
9178       break;
9179
9180     // The memory operands must not be volatile.
9181     if (Index->isVolatile() || Index->isIndexed())
9182       break;
9183
9184     // No truncation.
9185     if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
9186       if (St->isTruncatingStore())
9187         break;
9188
9189     // The stored memory type must be the same.
9190     if (Index->getMemoryVT() != MemVT)
9191       break;
9192
9193     // We do not allow unaligned stores because we want to prevent overriding
9194     // stores.
9195     if (Index->getAlignment()*8 != MemVT.getSizeInBits())
9196       break;
9197
9198     // We found a potential memory operand to merge.
9199     StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
9200
9201     // Find the next memory operand in the chain. If the next operand in the
9202     // chain is a store then move up and continue the scan with the next
9203     // memory operand. If the next operand is a load save it and use alias
9204     // information to check if it interferes with anything.
9205     SDNode *NextInChain = Index->getChain().getNode();
9206     while (1) {
9207       if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
9208         // We found a store node. Use it for the next iteration.
9209         Index = STn;
9210         break;
9211       } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
9212         if (Ldn->isVolatile()) {
9213           Index = nullptr;
9214           break;
9215         }
9216
9217         // Save the load node for later. Continue the scan.
9218         AliasLoadNodes.push_back(Ldn);
9219         NextInChain = Ldn->getChain().getNode();
9220         continue;
9221       } else {
9222         Index = nullptr;
9223         break;
9224       }
9225     }
9226   }
9227
9228   // Check if there is anything to merge.
9229   if (StoreNodes.size() < 2)
9230     return false;
9231
9232   // Sort the memory operands according to their distance from the base pointer.
9233   std::sort(StoreNodes.begin(), StoreNodes.end(),
9234             [](MemOpLink LHS, MemOpLink RHS) {
9235     return LHS.OffsetFromBase < RHS.OffsetFromBase ||
9236            (LHS.OffsetFromBase == RHS.OffsetFromBase &&
9237             LHS.SequenceNum > RHS.SequenceNum);
9238   });
9239
9240   // Scan the memory operations on the chain and find the first non-consecutive
9241   // store memory address.
9242   unsigned LastConsecutiveStore = 0;
9243   int64_t StartAddress = StoreNodes[0].OffsetFromBase;
9244   for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
9245
9246     // Check that the addresses are consecutive starting from the second
9247     // element in the list of stores.
9248     if (i > 0) {
9249       int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
9250       if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9251         break;
9252     }
9253
9254     bool Alias = false;
9255     // Check if this store interferes with any of the loads that we found.
9256     for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
9257       if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
9258         Alias = true;
9259         break;
9260       }
9261     // We found a load that alias with this store. Stop the sequence.
9262     if (Alias)
9263       break;
9264
9265     // Mark this node as useful.
9266     LastConsecutiveStore = i;
9267   }
9268
9269   // The node with the lowest store address.
9270   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
9271
9272   // Store the constants into memory as one consecutive store.
9273   if (!IsLoadSrc) {
9274     unsigned LastLegalType = 0;
9275     unsigned LastLegalVectorType = 0;
9276     bool NonZero = false;
9277     for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9278       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
9279       SDValue StoredVal = St->getValue();
9280
9281       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
9282         NonZero |= !C->isNullValue();
9283       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
9284         NonZero |= !C->getConstantFPValue()->isNullValue();
9285       } else {
9286         // Non-constant.
9287         break;
9288       }
9289
9290       // Find a legal type for the constant store.
9291       unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9292       EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9293       if (TLI.isTypeLegal(StoreTy))
9294         LastLegalType = i+1;
9295       // Or check whether a truncstore is legal.
9296       else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9297                TargetLowering::TypePromoteInteger) {
9298         EVT LegalizedStoredValueTy =
9299           TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
9300         if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy))
9301           LastLegalType = i+1;
9302       }
9303
9304       // Find a legal type for the vector store.
9305       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9306       if (TLI.isTypeLegal(Ty))
9307         LastLegalVectorType = i + 1;
9308     }
9309
9310     // We only use vectors if the constant is known to be zero and the
9311     // function is not marked with the noimplicitfloat attribute.
9312     if (NonZero || NoVectors)
9313       LastLegalVectorType = 0;
9314
9315     // Check if we found a legal integer type to store.
9316     if (LastLegalType == 0 && LastLegalVectorType == 0)
9317       return false;
9318
9319     bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
9320     unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
9321
9322     // Make sure we have something to merge.
9323     if (NumElem < 2)
9324       return false;
9325
9326     unsigned EarliestNodeUsed = 0;
9327     for (unsigned i=0; i < NumElem; ++i) {
9328       // Find a chain for the new wide-store operand. Notice that some
9329       // of the store nodes that we found may not be selected for inclusion
9330       // in the wide store. The chain we use needs to be the chain of the
9331       // earliest store node which is *used* and replaced by the wide store.
9332       if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9333         EarliestNodeUsed = i;
9334     }
9335
9336     // The earliest Node in the DAG.
9337     LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9338     SDLoc DL(StoreNodes[0].MemNode);
9339
9340     SDValue StoredVal;
9341     if (UseVector) {
9342       // Find a legal type for the vector store.
9343       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9344       assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
9345       StoredVal = DAG.getConstant(0, Ty);
9346     } else {
9347       unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9348       APInt StoreInt(StoreBW, 0);
9349
9350       // Construct a single integer constant which is made of the smaller
9351       // constant inputs.
9352       bool IsLE = TLI.isLittleEndian();
9353       for (unsigned i = 0; i < NumElem ; ++i) {
9354         unsigned Idx = IsLE ?(NumElem - 1 - i) : i;
9355         StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
9356         SDValue Val = St->getValue();
9357         StoreInt<<=ElementSizeBytes*8;
9358         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
9359           StoreInt|=C->getAPIntValue().zext(StoreBW);
9360         } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
9361           StoreInt|= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
9362         } else {
9363           assert(false && "Invalid constant element type");
9364         }
9365       }
9366
9367       // Create the new Load and Store operations.
9368       EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9369       StoredVal = DAG.getConstant(StoreInt, StoreTy);
9370     }
9371
9372     SDValue NewStore = DAG.getStore(EarliestOp->getChain(), DL, StoredVal,
9373                                     FirstInChain->getBasePtr(),
9374                                     FirstInChain->getPointerInfo(),
9375                                     false, false,
9376                                     FirstInChain->getAlignment());
9377
9378     // Replace the first store with the new store
9379     CombineTo(EarliestOp, NewStore);
9380     // Erase all other stores.
9381     for (unsigned i = 0; i < NumElem ; ++i) {
9382       if (StoreNodes[i].MemNode == EarliestOp)
9383         continue;
9384       StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9385       // ReplaceAllUsesWith will replace all uses that existed when it was
9386       // called, but graph optimizations may cause new ones to appear. For
9387       // example, the case in pr14333 looks like
9388       //
9389       //  St's chain -> St -> another store -> X
9390       //
9391       // And the only difference from St to the other store is the chain.
9392       // When we change it's chain to be St's chain they become identical,
9393       // get CSEed and the net result is that X is now a use of St.
9394       // Since we know that St is redundant, just iterate.
9395       while (!St->use_empty())
9396         DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
9397       deleteAndRecombine(St);
9398     }
9399
9400     return true;
9401   }
9402
9403   // Below we handle the case of multiple consecutive stores that
9404   // come from multiple consecutive loads. We merge them into a single
9405   // wide load and a single wide store.
9406
9407   // Look for load nodes which are used by the stored values.
9408   SmallVector<MemOpLink, 8> LoadNodes;
9409
9410   // Find acceptable loads. Loads need to have the same chain (token factor),
9411   // must not be zext, volatile, indexed, and they must be consecutive.
9412   BaseIndexOffset LdBasePtr;
9413   for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9414     StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
9415     LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
9416     if (!Ld) break;
9417
9418     // Loads must only have one use.
9419     if (!Ld->hasNUsesOfValue(1, 0))
9420       break;
9421
9422     // Check that the alignment is the same as the stores.
9423     if (Ld->getAlignment() != St->getAlignment())
9424       break;
9425
9426     // The memory operands must not be volatile.
9427     if (Ld->isVolatile() || Ld->isIndexed())
9428       break;
9429
9430     // We do not accept ext loads.
9431     if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
9432       break;
9433
9434     // The stored memory type must be the same.
9435     if (Ld->getMemoryVT() != MemVT)
9436       break;
9437
9438     BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
9439     // If this is not the first ptr that we check.
9440     if (LdBasePtr.Base.getNode()) {
9441       // The base ptr must be the same.
9442       if (!LdPtr.equalBaseIndex(LdBasePtr))
9443         break;
9444     } else {
9445       // Check that all other base pointers are the same as this one.
9446       LdBasePtr = LdPtr;
9447     }
9448
9449     // We found a potential memory operand to merge.
9450     LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
9451   }
9452
9453   if (LoadNodes.size() < 2)
9454     return false;
9455
9456   // If we have load/store pair instructions and we only have two values,
9457   // don't bother.
9458   unsigned RequiredAlignment;
9459   if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) &&
9460       St->getAlignment() >= RequiredAlignment)
9461     return false;
9462
9463   // Scan the memory operations on the chain and find the first non-consecutive
9464   // load memory address. These variables hold the index in the store node
9465   // array.
9466   unsigned LastConsecutiveLoad = 0;
9467   // This variable refers to the size and not index in the array.
9468   unsigned LastLegalVectorType = 0;
9469   unsigned LastLegalIntegerType = 0;
9470   StartAddress = LoadNodes[0].OffsetFromBase;
9471   SDValue FirstChain = LoadNodes[0].MemNode->getChain();
9472   for (unsigned i = 1; i < LoadNodes.size(); ++i) {
9473     // All loads much share the same chain.
9474     if (LoadNodes[i].MemNode->getChain() != FirstChain)
9475       break;
9476
9477     int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
9478     if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9479       break;
9480     LastConsecutiveLoad = i;
9481
9482     // Find a legal type for the vector store.
9483     EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9484     if (TLI.isTypeLegal(StoreTy))
9485       LastLegalVectorType = i + 1;
9486
9487     // Find a legal type for the integer store.
9488     unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9489     StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9490     if (TLI.isTypeLegal(StoreTy))
9491       LastLegalIntegerType = i + 1;
9492     // Or check whether a truncstore and extload is legal.
9493     else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9494              TargetLowering::TypePromoteInteger) {
9495       EVT LegalizedStoredValueTy =
9496         TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
9497       if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
9498           TLI.isLoadExtLegal(ISD::ZEXTLOAD, StoreTy) &&
9499           TLI.isLoadExtLegal(ISD::SEXTLOAD, StoreTy) &&
9500           TLI.isLoadExtLegal(ISD::EXTLOAD, StoreTy))
9501         LastLegalIntegerType = i+1;
9502     }
9503   }
9504
9505   // Only use vector types if the vector type is larger than the integer type.
9506   // If they are the same, use integers.
9507   bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
9508   unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
9509
9510   // We add +1 here because the LastXXX variables refer to location while
9511   // the NumElem refers to array/index size.
9512   unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
9513   NumElem = std::min(LastLegalType, NumElem);
9514
9515   if (NumElem < 2)
9516     return false;
9517
9518   // The earliest Node in the DAG.
9519   unsigned EarliestNodeUsed = 0;
9520   LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9521   for (unsigned i=1; i<NumElem; ++i) {
9522     // Find a chain for the new wide-store operand. Notice that some
9523     // of the store nodes that we found may not be selected for inclusion
9524     // in the wide store. The chain we use needs to be the chain of the
9525     // earliest store node which is *used* and replaced by the wide store.
9526     if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9527       EarliestNodeUsed = i;
9528   }
9529
9530   // Find if it is better to use vectors or integers to load and store
9531   // to memory.
9532   EVT JointMemOpVT;
9533   if (UseVectorTy) {
9534     JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9535   } else {
9536     unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9537     JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9538   }
9539
9540   SDLoc LoadDL(LoadNodes[0].MemNode);
9541   SDLoc StoreDL(StoreNodes[0].MemNode);
9542
9543   LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
9544   SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL,
9545                                 FirstLoad->getChain(),
9546                                 FirstLoad->getBasePtr(),
9547                                 FirstLoad->getPointerInfo(),
9548                                 false, false, false,
9549                                 FirstLoad->getAlignment());
9550
9551   SDValue NewStore = DAG.getStore(EarliestOp->getChain(), StoreDL, NewLoad,
9552                                   FirstInChain->getBasePtr(),
9553                                   FirstInChain->getPointerInfo(), false, false,
9554                                   FirstInChain->getAlignment());
9555
9556   // Replace one of the loads with the new load.
9557   LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
9558   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
9559                                 SDValue(NewLoad.getNode(), 1));
9560
9561   // Remove the rest of the load chains.
9562   for (unsigned i = 1; i < NumElem ; ++i) {
9563     // Replace all chain users of the old load nodes with the chain of the new
9564     // load node.
9565     LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
9566     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
9567   }
9568
9569   // Replace the first store with the new store.
9570   CombineTo(EarliestOp, NewStore);
9571   // Erase all other stores.
9572   for (unsigned i = 0; i < NumElem ; ++i) {
9573     // Remove all Store nodes.
9574     if (StoreNodes[i].MemNode == EarliestOp)
9575       continue;
9576     StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9577     DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
9578     deleteAndRecombine(St);
9579   }
9580
9581   return true;
9582 }
9583
9584 SDValue DAGCombiner::visitSTORE(SDNode *N) {
9585   StoreSDNode *ST  = cast<StoreSDNode>(N);
9586   SDValue Chain = ST->getChain();
9587   SDValue Value = ST->getValue();
9588   SDValue Ptr   = ST->getBasePtr();
9589
9590   // If this is a store of a bit convert, store the input value if the
9591   // resultant store does not need a higher alignment than the original.
9592   if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
9593       ST->isUnindexed()) {
9594     unsigned OrigAlign = ST->getAlignment();
9595     EVT SVT = Value.getOperand(0).getValueType();
9596     unsigned Align = TLI.getDataLayout()->
9597       getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
9598     if (Align <= OrigAlign &&
9599         ((!LegalOperations && !ST->isVolatile()) ||
9600          TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
9601       return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
9602                           Ptr, ST->getPointerInfo(), ST->isVolatile(),
9603                           ST->isNonTemporal(), OrigAlign,
9604                           ST->getAAInfo());
9605   }
9606
9607   // Turn 'store undef, Ptr' -> nothing.
9608   if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
9609     return Chain;
9610
9611   // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
9612   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
9613     // NOTE: If the original store is volatile, this transform must not increase
9614     // the number of stores.  For example, on x86-32 an f64 can be stored in one
9615     // processor operation but an i64 (which is not legal) requires two.  So the
9616     // transform should not be done in this case.
9617     if (Value.getOpcode() != ISD::TargetConstantFP) {
9618       SDValue Tmp;
9619       switch (CFP->getSimpleValueType(0).SimpleTy) {
9620       default: llvm_unreachable("Unknown FP type");
9621       case MVT::f16:    // We don't do this for these yet.
9622       case MVT::f80:
9623       case MVT::f128:
9624       case MVT::ppcf128:
9625         break;
9626       case MVT::f32:
9627         if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
9628             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
9629           Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
9630                               bitcastToAPInt().getZExtValue(), MVT::i32);
9631           return DAG.getStore(Chain, SDLoc(N), Tmp,
9632                               Ptr, ST->getMemOperand());
9633         }
9634         break;
9635       case MVT::f64:
9636         if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
9637              !ST->isVolatile()) ||
9638             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
9639           Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
9640                                 getZExtValue(), MVT::i64);
9641           return DAG.getStore(Chain, SDLoc(N), Tmp,
9642                               Ptr, ST->getMemOperand());
9643         }
9644
9645         if (!ST->isVolatile() &&
9646             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
9647           // Many FP stores are not made apparent until after legalize, e.g. for
9648           // argument passing.  Since this is so common, custom legalize the
9649           // 64-bit integer store into two 32-bit stores.
9650           uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
9651           SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
9652           SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
9653           if (TLI.isBigEndian()) std::swap(Lo, Hi);
9654
9655           unsigned Alignment = ST->getAlignment();
9656           bool isVolatile = ST->isVolatile();
9657           bool isNonTemporal = ST->isNonTemporal();
9658           AAMDNodes AAInfo = ST->getAAInfo();
9659
9660           SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
9661                                      Ptr, ST->getPointerInfo(),
9662                                      isVolatile, isNonTemporal,
9663                                      ST->getAlignment(), AAInfo);
9664           Ptr = DAG.getNode(ISD::ADD, SDLoc(N), Ptr.getValueType(), Ptr,
9665                             DAG.getConstant(4, Ptr.getValueType()));
9666           Alignment = MinAlign(Alignment, 4U);
9667           SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
9668                                      Ptr, ST->getPointerInfo().getWithOffset(4),
9669                                      isVolatile, isNonTemporal,
9670                                      Alignment, AAInfo);
9671           return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
9672                              St0, St1);
9673         }
9674
9675         break;
9676       }
9677     }
9678   }
9679
9680   // Try to infer better alignment information than the store already has.
9681   if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
9682     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
9683       if (Align > ST->getAlignment())
9684         return DAG.getTruncStore(Chain, SDLoc(N), Value,
9685                                  Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
9686                                  ST->isVolatile(), ST->isNonTemporal(), Align,
9687                                  ST->getAAInfo());
9688     }
9689   }
9690
9691   // Try transforming a pair floating point load / store ops to integer
9692   // load / store ops.
9693   SDValue NewST = TransformFPLoadStorePair(N);
9694   if (NewST.getNode())
9695     return NewST;
9696
9697   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
9698     TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
9699 #ifndef NDEBUG
9700   if (CombinerAAOnlyFunc.getNumOccurrences() &&
9701       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
9702     UseAA = false;
9703 #endif
9704   if (UseAA && ST->isUnindexed()) {
9705     // Walk up chain skipping non-aliasing memory nodes.
9706     SDValue BetterChain = FindBetterChain(N, Chain);
9707
9708     // If there is a better chain.
9709     if (Chain != BetterChain) {
9710       SDValue ReplStore;
9711
9712       // Replace the chain to avoid dependency.
9713       if (ST->isTruncatingStore()) {
9714         ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
9715                                       ST->getMemoryVT(), ST->getMemOperand());
9716       } else {
9717         ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
9718                                  ST->getMemOperand());
9719       }
9720
9721       // Create token to keep both nodes around.
9722       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
9723                                   MVT::Other, Chain, ReplStore);
9724
9725       // Make sure the new and old chains are cleaned up.
9726       AddToWorklist(Token.getNode());
9727
9728       // Don't add users to work list.
9729       return CombineTo(N, Token, false);
9730     }
9731   }
9732
9733   // Try transforming N to an indexed store.
9734   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
9735     return SDValue(N, 0);
9736
9737   // FIXME: is there such a thing as a truncating indexed store?
9738   if (ST->isTruncatingStore() && ST->isUnindexed() &&
9739       Value.getValueType().isInteger()) {
9740     // See if we can simplify the input to this truncstore with knowledge that
9741     // only the low bits are being used.  For example:
9742     // "truncstore (or (shl x, 8), y), i8"  -> "truncstore y, i8"
9743     SDValue Shorter =
9744       GetDemandedBits(Value,
9745                       APInt::getLowBitsSet(
9746                         Value.getValueType().getScalarType().getSizeInBits(),
9747                         ST->getMemoryVT().getScalarType().getSizeInBits()));
9748     AddToWorklist(Value.getNode());
9749     if (Shorter.getNode())
9750       return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
9751                                Ptr, ST->getMemoryVT(), ST->getMemOperand());
9752
9753     // Otherwise, see if we can simplify the operation with
9754     // SimplifyDemandedBits, which only works if the value has a single use.
9755     if (SimplifyDemandedBits(Value,
9756                         APInt::getLowBitsSet(
9757                           Value.getValueType().getScalarType().getSizeInBits(),
9758                           ST->getMemoryVT().getScalarType().getSizeInBits())))
9759       return SDValue(N, 0);
9760   }
9761
9762   // If this is a load followed by a store to the same location, then the store
9763   // is dead/noop.
9764   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
9765     if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
9766         ST->isUnindexed() && !ST->isVolatile() &&
9767         // There can't be any side effects between the load and store, such as
9768         // a call or store.
9769         Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
9770       // The store is dead, remove it.
9771       return Chain;
9772     }
9773   }
9774
9775   // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
9776   // truncating store.  We can do this even if this is already a truncstore.
9777   if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
9778       && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
9779       TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
9780                             ST->getMemoryVT())) {
9781     return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
9782                              Ptr, ST->getMemoryVT(), ST->getMemOperand());
9783   }
9784
9785   // Only perform this optimization before the types are legal, because we
9786   // don't want to perform this optimization on every DAGCombine invocation.
9787   if (!LegalTypes) {
9788     bool EverChanged = false;
9789
9790     do {
9791       // There can be multiple store sequences on the same chain.
9792       // Keep trying to merge store sequences until we are unable to do so
9793       // or until we merge the last store on the chain.
9794       bool Changed = MergeConsecutiveStores(ST);
9795       EverChanged |= Changed;
9796       if (!Changed) break;
9797     } while (ST->getOpcode() != ISD::DELETED_NODE);
9798
9799     if (EverChanged)
9800       return SDValue(N, 0);
9801   }
9802
9803   return ReduceLoadOpStoreWidth(N);
9804 }
9805
9806 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
9807   SDValue InVec = N->getOperand(0);
9808   SDValue InVal = N->getOperand(1);
9809   SDValue EltNo = N->getOperand(2);
9810   SDLoc dl(N);
9811
9812   // If the inserted element is an UNDEF, just use the input vector.
9813   if (InVal.getOpcode() == ISD::UNDEF)
9814     return InVec;
9815
9816   EVT VT = InVec.getValueType();
9817
9818   // If we can't generate a legal BUILD_VECTOR, exit
9819   if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
9820     return SDValue();
9821
9822   // Check that we know which element is being inserted
9823   if (!isa<ConstantSDNode>(EltNo))
9824     return SDValue();
9825   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9826
9827   // Canonicalize insert_vector_elt dag nodes.
9828   // Example:
9829   // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
9830   // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
9831   //
9832   // Do this only if the child insert_vector node has one use; also
9833   // do this only if indices are both constants and Idx1 < Idx0.
9834   if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
9835       && isa<ConstantSDNode>(InVec.getOperand(2))) {
9836     unsigned OtherElt =
9837       cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue();
9838     if (Elt < OtherElt) {
9839       // Swap nodes.
9840       SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT,
9841                                   InVec.getOperand(0), InVal, EltNo);
9842       AddToWorklist(NewOp.getNode());
9843       return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
9844                          VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
9845     }
9846   }
9847
9848   // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
9849   // be converted to a BUILD_VECTOR).  Fill in the Ops vector with the
9850   // vector elements.
9851   SmallVector<SDValue, 8> Ops;
9852   // Do not combine these two vectors if the output vector will not replace
9853   // the input vector.
9854   if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
9855     Ops.append(InVec.getNode()->op_begin(),
9856                InVec.getNode()->op_end());
9857   } else if (InVec.getOpcode() == ISD::UNDEF) {
9858     unsigned NElts = VT.getVectorNumElements();
9859     Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
9860   } else {
9861     return SDValue();
9862   }
9863
9864   // Insert the element
9865   if (Elt < Ops.size()) {
9866     // All the operands of BUILD_VECTOR must have the same type;
9867     // we enforce that here.
9868     EVT OpVT = Ops[0].getValueType();
9869     if (InVal.getValueType() != OpVT)
9870       InVal = OpVT.bitsGT(InVal.getValueType()) ?
9871                 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
9872                 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
9873     Ops[Elt] = InVal;
9874   }
9875
9876   // Return the new vector
9877   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
9878 }
9879
9880 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
9881     SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) {
9882   EVT ResultVT = EVE->getValueType(0);
9883   EVT VecEltVT = InVecVT.getVectorElementType();
9884   unsigned Align = OriginalLoad->getAlignment();
9885   unsigned NewAlign = TLI.getDataLayout()->getABITypeAlignment(
9886       VecEltVT.getTypeForEVT(*DAG.getContext()));
9887
9888   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
9889     return SDValue();
9890
9891   Align = NewAlign;
9892
9893   SDValue NewPtr = OriginalLoad->getBasePtr();
9894   SDValue Offset;
9895   EVT PtrType = NewPtr.getValueType();
9896   MachinePointerInfo MPI;
9897   if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
9898     int Elt = ConstEltNo->getZExtValue();
9899     unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
9900     if (TLI.isBigEndian())
9901       PtrOff = InVecVT.getSizeInBits() / 8 - PtrOff;
9902     Offset = DAG.getConstant(PtrOff, PtrType);
9903     MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
9904   } else {
9905     Offset = DAG.getNode(
9906         ISD::MUL, SDLoc(EVE), EltNo.getValueType(), EltNo,
9907         DAG.getConstant(VecEltVT.getStoreSize(), EltNo.getValueType()));
9908     if (TLI.isBigEndian())
9909       Offset = DAG.getNode(
9910           ISD::SUB, SDLoc(EVE), EltNo.getValueType(),
9911           DAG.getConstant(InVecVT.getStoreSize(), EltNo.getValueType()), Offset);
9912     MPI = OriginalLoad->getPointerInfo();
9913   }
9914   NewPtr = DAG.getNode(ISD::ADD, SDLoc(EVE), PtrType, NewPtr, Offset);
9915
9916   // The replacement we need to do here is a little tricky: we need to
9917   // replace an extractelement of a load with a load.
9918   // Use ReplaceAllUsesOfValuesWith to do the replacement.
9919   // Note that this replacement assumes that the extractvalue is the only
9920   // use of the load; that's okay because we don't want to perform this
9921   // transformation in other cases anyway.
9922   SDValue Load;
9923   SDValue Chain;
9924   if (ResultVT.bitsGT(VecEltVT)) {
9925     // If the result type of vextract is wider than the load, then issue an
9926     // extending load instead.
9927     ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, VecEltVT)
9928                                    ? ISD::ZEXTLOAD
9929                                    : ISD::EXTLOAD;
9930     Load = DAG.getExtLoad(
9931         ExtType, SDLoc(EVE), ResultVT, OriginalLoad->getChain(), NewPtr, MPI,
9932         VecEltVT, OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
9933         OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
9934     Chain = Load.getValue(1);
9935   } else {
9936     Load = DAG.getLoad(
9937         VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, MPI,
9938         OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
9939         OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
9940     Chain = Load.getValue(1);
9941     if (ResultVT.bitsLT(VecEltVT))
9942       Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
9943     else
9944       Load = DAG.getNode(ISD::BITCAST, SDLoc(EVE), ResultVT, Load);
9945   }
9946   WorklistRemover DeadNodes(*this);
9947   SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
9948   SDValue To[] = { Load, Chain };
9949   DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
9950   // Since we're explicitly calling ReplaceAllUses, add the new node to the
9951   // worklist explicitly as well.
9952   AddToWorklist(Load.getNode());
9953   AddUsersToWorklist(Load.getNode()); // Add users too
9954   // Make sure to revisit this node to clean it up; it will usually be dead.
9955   AddToWorklist(EVE);
9956   ++OpsNarrowed;
9957   return SDValue(EVE, 0);
9958 }
9959
9960 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
9961   // (vextract (scalar_to_vector val, 0) -> val
9962   SDValue InVec = N->getOperand(0);
9963   EVT VT = InVec.getValueType();
9964   EVT NVT = N->getValueType(0);
9965
9966   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
9967     // Check if the result type doesn't match the inserted element type. A
9968     // SCALAR_TO_VECTOR may truncate the inserted element and the
9969     // EXTRACT_VECTOR_ELT may widen the extracted vector.
9970     SDValue InOp = InVec.getOperand(0);
9971     if (InOp.getValueType() != NVT) {
9972       assert(InOp.getValueType().isInteger() && NVT.isInteger());
9973       return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
9974     }
9975     return InOp;
9976   }
9977
9978   SDValue EltNo = N->getOperand(1);
9979   bool ConstEltNo = isa<ConstantSDNode>(EltNo);
9980
9981   // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
9982   // We only perform this optimization before the op legalization phase because
9983   // we may introduce new vector instructions which are not backed by TD
9984   // patterns. For example on AVX, extracting elements from a wide vector
9985   // without using extract_subvector. However, if we can find an underlying
9986   // scalar value, then we can always use that.
9987   if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
9988       && ConstEltNo) {
9989     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9990     int NumElem = VT.getVectorNumElements();
9991     ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
9992     // Find the new index to extract from.
9993     int OrigElt = SVOp->getMaskElt(Elt);
9994
9995     // Extracting an undef index is undef.
9996     if (OrigElt == -1)
9997       return DAG.getUNDEF(NVT);
9998
9999     // Select the right vector half to extract from.
10000     SDValue SVInVec;
10001     if (OrigElt < NumElem) {
10002       SVInVec = InVec->getOperand(0);
10003     } else {
10004       SVInVec = InVec->getOperand(1);
10005       OrigElt -= NumElem;
10006     }
10007
10008     if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
10009       SDValue InOp = SVInVec.getOperand(OrigElt);
10010       if (InOp.getValueType() != NVT) {
10011         assert(InOp.getValueType().isInteger() && NVT.isInteger());
10012         InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
10013       }
10014
10015       return InOp;
10016     }
10017
10018     // FIXME: We should handle recursing on other vector shuffles and
10019     // scalar_to_vector here as well.
10020
10021     if (!LegalOperations) {
10022       EVT IndexTy = TLI.getVectorIdxTy();
10023       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT,
10024                          SVInVec, DAG.getConstant(OrigElt, IndexTy));
10025     }
10026   }
10027
10028   bool BCNumEltsChanged = false;
10029   EVT ExtVT = VT.getVectorElementType();
10030   EVT LVT = ExtVT;
10031
10032   // If the result of load has to be truncated, then it's not necessarily
10033   // profitable.
10034   if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
10035     return SDValue();
10036
10037   if (InVec.getOpcode() == ISD::BITCAST) {
10038     // Don't duplicate a load with other uses.
10039     if (!InVec.hasOneUse())
10040       return SDValue();
10041
10042     EVT BCVT = InVec.getOperand(0).getValueType();
10043     if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
10044       return SDValue();
10045     if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
10046       BCNumEltsChanged = true;
10047     InVec = InVec.getOperand(0);
10048     ExtVT = BCVT.getVectorElementType();
10049   }
10050
10051   // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size)
10052   if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() &&
10053       ISD::isNormalLoad(InVec.getNode()) &&
10054       !N->getOperand(1)->hasPredecessor(InVec.getNode())) {
10055     SDValue Index = N->getOperand(1);
10056     if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec))
10057       return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index,
10058                                                            OrigLoad);
10059   }
10060
10061   // Perform only after legalization to ensure build_vector / vector_shuffle
10062   // optimizations have already been done.
10063   if (!LegalOperations) return SDValue();
10064
10065   // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
10066   // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
10067   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
10068
10069   if (ConstEltNo) {
10070     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
10071
10072     LoadSDNode *LN0 = nullptr;
10073     const ShuffleVectorSDNode *SVN = nullptr;
10074     if (ISD::isNormalLoad(InVec.getNode())) {
10075       LN0 = cast<LoadSDNode>(InVec);
10076     } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
10077                InVec.getOperand(0).getValueType() == ExtVT &&
10078                ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
10079       // Don't duplicate a load with other uses.
10080       if (!InVec.hasOneUse())
10081         return SDValue();
10082
10083       LN0 = cast<LoadSDNode>(InVec.getOperand(0));
10084     } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
10085       // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
10086       // =>
10087       // (load $addr+1*size)
10088
10089       // Don't duplicate a load with other uses.
10090       if (!InVec.hasOneUse())
10091         return SDValue();
10092
10093       // If the bit convert changed the number of elements, it is unsafe
10094       // to examine the mask.
10095       if (BCNumEltsChanged)
10096         return SDValue();
10097
10098       // Select the input vector, guarding against out of range extract vector.
10099       unsigned NumElems = VT.getVectorNumElements();
10100       int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
10101       InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
10102
10103       if (InVec.getOpcode() == ISD::BITCAST) {
10104         // Don't duplicate a load with other uses.
10105         if (!InVec.hasOneUse())
10106           return SDValue();
10107
10108         InVec = InVec.getOperand(0);
10109       }
10110       if (ISD::isNormalLoad(InVec.getNode())) {
10111         LN0 = cast<LoadSDNode>(InVec);
10112         Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
10113         EltNo = DAG.getConstant(Elt, EltNo.getValueType());
10114       }
10115     }
10116
10117     // Make sure we found a non-volatile load and the extractelement is
10118     // the only use.
10119     if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
10120       return SDValue();
10121
10122     // If Idx was -1 above, Elt is going to be -1, so just return undef.
10123     if (Elt == -1)
10124       return DAG.getUNDEF(LVT);
10125
10126     return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0);
10127   }
10128
10129   return SDValue();
10130 }
10131
10132 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
10133 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
10134   // We perform this optimization post type-legalization because
10135   // the type-legalizer often scalarizes integer-promoted vectors.
10136   // Performing this optimization before may create bit-casts which
10137   // will be type-legalized to complex code sequences.
10138   // We perform this optimization only before the operation legalizer because we
10139   // may introduce illegal operations.
10140   if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
10141     return SDValue();
10142
10143   unsigned NumInScalars = N->getNumOperands();
10144   SDLoc dl(N);
10145   EVT VT = N->getValueType(0);
10146
10147   // Check to see if this is a BUILD_VECTOR of a bunch of values
10148   // which come from any_extend or zero_extend nodes. If so, we can create
10149   // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
10150   // optimizations. We do not handle sign-extend because we can't fill the sign
10151   // using shuffles.
10152   EVT SourceType = MVT::Other;
10153   bool AllAnyExt = true;
10154
10155   for (unsigned i = 0; i != NumInScalars; ++i) {
10156     SDValue In = N->getOperand(i);
10157     // Ignore undef inputs.
10158     if (In.getOpcode() == ISD::UNDEF) continue;
10159
10160     bool AnyExt  = In.getOpcode() == ISD::ANY_EXTEND;
10161     bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
10162
10163     // Abort if the element is not an extension.
10164     if (!ZeroExt && !AnyExt) {
10165       SourceType = MVT::Other;
10166       break;
10167     }
10168
10169     // The input is a ZeroExt or AnyExt. Check the original type.
10170     EVT InTy = In.getOperand(0).getValueType();
10171
10172     // Check that all of the widened source types are the same.
10173     if (SourceType == MVT::Other)
10174       // First time.
10175       SourceType = InTy;
10176     else if (InTy != SourceType) {
10177       // Multiple income types. Abort.
10178       SourceType = MVT::Other;
10179       break;
10180     }
10181
10182     // Check if all of the extends are ANY_EXTENDs.
10183     AllAnyExt &= AnyExt;
10184   }
10185
10186   // In order to have valid types, all of the inputs must be extended from the
10187   // same source type and all of the inputs must be any or zero extend.
10188   // Scalar sizes must be a power of two.
10189   EVT OutScalarTy = VT.getScalarType();
10190   bool ValidTypes = SourceType != MVT::Other &&
10191                  isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
10192                  isPowerOf2_32(SourceType.getSizeInBits());
10193
10194   // Create a new simpler BUILD_VECTOR sequence which other optimizations can
10195   // turn into a single shuffle instruction.
10196   if (!ValidTypes)
10197     return SDValue();
10198
10199   bool isLE = TLI.isLittleEndian();
10200   unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
10201   assert(ElemRatio > 1 && "Invalid element size ratio");
10202   SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
10203                                DAG.getConstant(0, SourceType);
10204
10205   unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
10206   SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
10207
10208   // Populate the new build_vector
10209   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
10210     SDValue Cast = N->getOperand(i);
10211     assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
10212             Cast.getOpcode() == ISD::ZERO_EXTEND ||
10213             Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
10214     SDValue In;
10215     if (Cast.getOpcode() == ISD::UNDEF)
10216       In = DAG.getUNDEF(SourceType);
10217     else
10218       In = Cast->getOperand(0);
10219     unsigned Index = isLE ? (i * ElemRatio) :
10220                             (i * ElemRatio + (ElemRatio - 1));
10221
10222     assert(Index < Ops.size() && "Invalid index");
10223     Ops[Index] = In;
10224   }
10225
10226   // The type of the new BUILD_VECTOR node.
10227   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
10228   assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
10229          "Invalid vector size");
10230   // Check if the new vector type is legal.
10231   if (!isTypeLegal(VecVT)) return SDValue();
10232
10233   // Make the new BUILD_VECTOR.
10234   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
10235
10236   // The new BUILD_VECTOR node has the potential to be further optimized.
10237   AddToWorklist(BV.getNode());
10238   // Bitcast to the desired type.
10239   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
10240 }
10241
10242 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
10243   EVT VT = N->getValueType(0);
10244
10245   unsigned NumInScalars = N->getNumOperands();
10246   SDLoc dl(N);
10247
10248   EVT SrcVT = MVT::Other;
10249   unsigned Opcode = ISD::DELETED_NODE;
10250   unsigned NumDefs = 0;
10251
10252   for (unsigned i = 0; i != NumInScalars; ++i) {
10253     SDValue In = N->getOperand(i);
10254     unsigned Opc = In.getOpcode();
10255
10256     if (Opc == ISD::UNDEF)
10257       continue;
10258
10259     // If all scalar values are floats and converted from integers.
10260     if (Opcode == ISD::DELETED_NODE &&
10261         (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
10262       Opcode = Opc;
10263     }
10264
10265     if (Opc != Opcode)
10266       return SDValue();
10267
10268     EVT InVT = In.getOperand(0).getValueType();
10269
10270     // If all scalar values are typed differently, bail out. It's chosen to
10271     // simplify BUILD_VECTOR of integer types.
10272     if (SrcVT == MVT::Other)
10273       SrcVT = InVT;
10274     if (SrcVT != InVT)
10275       return SDValue();
10276     NumDefs++;
10277   }
10278
10279   // If the vector has just one element defined, it's not worth to fold it into
10280   // a vectorized one.
10281   if (NumDefs < 2)
10282     return SDValue();
10283
10284   assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
10285          && "Should only handle conversion from integer to float.");
10286   assert(SrcVT != MVT::Other && "Cannot determine source type!");
10287
10288   EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
10289
10290   if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
10291     return SDValue();
10292
10293   SmallVector<SDValue, 8> Opnds;
10294   for (unsigned i = 0; i != NumInScalars; ++i) {
10295     SDValue In = N->getOperand(i);
10296
10297     if (In.getOpcode() == ISD::UNDEF)
10298       Opnds.push_back(DAG.getUNDEF(SrcVT));
10299     else
10300       Opnds.push_back(In.getOperand(0));
10301   }
10302   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds);
10303   AddToWorklist(BV.getNode());
10304
10305   return DAG.getNode(Opcode, dl, VT, BV);
10306 }
10307
10308 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
10309   unsigned NumInScalars = N->getNumOperands();
10310   SDLoc dl(N);
10311   EVT VT = N->getValueType(0);
10312
10313   // A vector built entirely of undefs is undef.
10314   if (ISD::allOperandsUndef(N))
10315     return DAG.getUNDEF(VT);
10316
10317   SDValue V = reduceBuildVecExtToExtBuildVec(N);
10318   if (V.getNode())
10319     return V;
10320
10321   V = reduceBuildVecConvertToConvertBuildVec(N);
10322   if (V.getNode())
10323     return V;
10324
10325   // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
10326   // operations.  If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
10327   // at most two distinct vectors, turn this into a shuffle node.
10328
10329   // May only combine to shuffle after legalize if shuffle is legal.
10330   if (LegalOperations &&
10331       !TLI.isOperationLegalOrCustom(ISD::VECTOR_SHUFFLE, VT))
10332     return SDValue();
10333
10334   SDValue VecIn1, VecIn2;
10335   for (unsigned i = 0; i != NumInScalars; ++i) {
10336     // Ignore undef inputs.
10337     if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
10338
10339     // If this input is something other than a EXTRACT_VECTOR_ELT with a
10340     // constant index, bail out.
10341     if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10342         !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) {
10343       VecIn1 = VecIn2 = SDValue(nullptr, 0);
10344       break;
10345     }
10346
10347     // We allow up to two distinct input vectors.
10348     SDValue ExtractedFromVec = N->getOperand(i).getOperand(0);
10349     if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
10350       continue;
10351
10352     if (!VecIn1.getNode()) {
10353       VecIn1 = ExtractedFromVec;
10354     } else if (!VecIn2.getNode()) {
10355       VecIn2 = ExtractedFromVec;
10356     } else {
10357       // Too many inputs.
10358       VecIn1 = VecIn2 = SDValue(nullptr, 0);
10359       break;
10360     }
10361   }
10362
10363   // If everything is good, we can make a shuffle operation.
10364   if (VecIn1.getNode()) {
10365     SmallVector<int, 8> Mask;
10366     for (unsigned i = 0; i != NumInScalars; ++i) {
10367       if (N->getOperand(i).getOpcode() == ISD::UNDEF) {
10368         Mask.push_back(-1);
10369         continue;
10370       }
10371
10372       // If extracting from the first vector, just use the index directly.
10373       SDValue Extract = N->getOperand(i);
10374       SDValue ExtVal = Extract.getOperand(1);
10375       if (Extract.getOperand(0) == VecIn1) {
10376         unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
10377         if (ExtIndex > VT.getVectorNumElements())
10378           return SDValue();
10379
10380         Mask.push_back(ExtIndex);
10381         continue;
10382       }
10383
10384       // Otherwise, use InIdx + VecSize
10385       unsigned Idx = cast<ConstantSDNode>(ExtVal)->getZExtValue();
10386       Mask.push_back(Idx+NumInScalars);
10387     }
10388
10389     // We can't generate a shuffle node with mismatched input and output types.
10390     // Attempt to transform a single input vector to the correct type.
10391     if ((VT != VecIn1.getValueType())) {
10392       // We don't support shuffeling between TWO values of different types.
10393       if (VecIn2.getNode())
10394         return SDValue();
10395
10396       // We only support widening of vectors which are half the size of the
10397       // output registers. For example XMM->YMM widening on X86 with AVX.
10398       if (VecIn1.getValueType().getSizeInBits()*2 != VT.getSizeInBits())
10399         return SDValue();
10400
10401       // If the input vector type has a different base type to the output
10402       // vector type, bail out.
10403       if (VecIn1.getValueType().getVectorElementType() !=
10404           VT.getVectorElementType())
10405         return SDValue();
10406
10407       // Widen the input vector by adding undef values.
10408       VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10409                            VecIn1, DAG.getUNDEF(VecIn1.getValueType()));
10410     }
10411
10412     // If VecIn2 is unused then change it to undef.
10413     VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
10414
10415     // Check that we were able to transform all incoming values to the same
10416     // type.
10417     if (VecIn2.getValueType() != VecIn1.getValueType() ||
10418         VecIn1.getValueType() != VT)
10419           return SDValue();
10420
10421     // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
10422     if (!isTypeLegal(VT))
10423       return SDValue();
10424
10425     // Return the new VECTOR_SHUFFLE node.
10426     SDValue Ops[2];
10427     Ops[0] = VecIn1;
10428     Ops[1] = VecIn2;
10429     return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
10430   }
10431
10432   return SDValue();
10433 }
10434
10435 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
10436   // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
10437   // EXTRACT_SUBVECTOR operations.  If so, and if the EXTRACT_SUBVECTOR vector
10438   // inputs come from at most two distinct vectors, turn this into a shuffle
10439   // node.
10440
10441   // If we only have one input vector, we don't need to do any concatenation.
10442   if (N->getNumOperands() == 1)
10443     return N->getOperand(0);
10444
10445   // Check if all of the operands are undefs.
10446   EVT VT = N->getValueType(0);
10447   if (ISD::allOperandsUndef(N))
10448     return DAG.getUNDEF(VT);
10449
10450   // Optimize concat_vectors where one of the vectors is undef.
10451   if (N->getNumOperands() == 2 &&
10452       N->getOperand(1)->getOpcode() == ISD::UNDEF) {
10453     SDValue In = N->getOperand(0);
10454     assert(In.getValueType().isVector() && "Must concat vectors");
10455
10456     // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
10457     if (In->getOpcode() == ISD::BITCAST &&
10458         !In->getOperand(0)->getValueType(0).isVector()) {
10459       SDValue Scalar = In->getOperand(0);
10460       EVT SclTy = Scalar->getValueType(0);
10461
10462       if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
10463         return SDValue();
10464
10465       EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
10466                                  VT.getSizeInBits() / SclTy.getSizeInBits());
10467       if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
10468         return SDValue();
10469
10470       SDLoc dl = SDLoc(N);
10471       SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
10472       return DAG.getNode(ISD::BITCAST, dl, VT, Res);
10473     }
10474   }
10475
10476   // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
10477   // -> (BUILD_VECTOR A, B, ..., C, D, ...)
10478   if (N->getNumOperands() == 2 &&
10479       N->getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
10480       N->getOperand(1).getOpcode() == ISD::BUILD_VECTOR) {
10481     EVT VT = N->getValueType(0);
10482     SDValue N0 = N->getOperand(0);
10483     SDValue N1 = N->getOperand(1);
10484     SmallVector<SDValue, 8> Opnds;
10485     unsigned BuildVecNumElts =  N0.getNumOperands();
10486
10487     EVT SclTy0 = N0.getOperand(0)->getValueType(0);
10488     EVT SclTy1 = N1.getOperand(0)->getValueType(0);
10489     if (SclTy0.isFloatingPoint()) {
10490       for (unsigned i = 0; i != BuildVecNumElts; ++i)
10491         Opnds.push_back(N0.getOperand(i));
10492       for (unsigned i = 0; i != BuildVecNumElts; ++i)
10493         Opnds.push_back(N1.getOperand(i));
10494     } else {
10495       // If BUILD_VECTOR are from built from integer, they may have different
10496       // operand types. Get the smaller type and truncate all operands to it.
10497       EVT MinTy = SclTy0.bitsLE(SclTy1) ? SclTy0 : SclTy1;
10498       for (unsigned i = 0; i != BuildVecNumElts; ++i)
10499         Opnds.push_back(DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinTy,
10500                         N0.getOperand(i)));
10501       for (unsigned i = 0; i != BuildVecNumElts; ++i)
10502         Opnds.push_back(DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinTy,
10503                         N1.getOperand(i)));
10504     }
10505
10506     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
10507   }
10508
10509   // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
10510   // nodes often generate nop CONCAT_VECTOR nodes.
10511   // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
10512   // place the incoming vectors at the exact same location.
10513   SDValue SingleSource = SDValue();
10514   unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
10515
10516   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
10517     SDValue Op = N->getOperand(i);
10518
10519     if (Op.getOpcode() == ISD::UNDEF)
10520       continue;
10521
10522     // Check if this is the identity extract:
10523     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
10524       return SDValue();
10525
10526     // Find the single incoming vector for the extract_subvector.
10527     if (SingleSource.getNode()) {
10528       if (Op.getOperand(0) != SingleSource)
10529         return SDValue();
10530     } else {
10531       SingleSource = Op.getOperand(0);
10532
10533       // Check the source type is the same as the type of the result.
10534       // If not, this concat may extend the vector, so we can not
10535       // optimize it away.
10536       if (SingleSource.getValueType() != N->getValueType(0))
10537         return SDValue();
10538     }
10539
10540     unsigned IdentityIndex = i * PartNumElem;
10541     ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
10542     // The extract index must be constant.
10543     if (!CS)
10544       return SDValue();
10545
10546     // Check that we are reading from the identity index.
10547     if (CS->getZExtValue() != IdentityIndex)
10548       return SDValue();
10549   }
10550
10551   if (SingleSource.getNode())
10552     return SingleSource;
10553
10554   return SDValue();
10555 }
10556
10557 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
10558   EVT NVT = N->getValueType(0);
10559   SDValue V = N->getOperand(0);
10560
10561   if (V->getOpcode() == ISD::CONCAT_VECTORS) {
10562     // Combine:
10563     //    (extract_subvec (concat V1, V2, ...), i)
10564     // Into:
10565     //    Vi if possible
10566     // Only operand 0 is checked as 'concat' assumes all inputs of the same
10567     // type.
10568     if (V->getOperand(0).getValueType() != NVT)
10569       return SDValue();
10570     unsigned Idx = dyn_cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
10571     unsigned NumElems = NVT.getVectorNumElements();
10572     assert((Idx % NumElems) == 0 &&
10573            "IDX in concat is not a multiple of the result vector length.");
10574     return V->getOperand(Idx / NumElems);
10575   }
10576
10577   // Skip bitcasting
10578   if (V->getOpcode() == ISD::BITCAST)
10579     V = V.getOperand(0);
10580
10581   if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
10582     SDLoc dl(N);
10583     // Handle only simple case where vector being inserted and vector
10584     // being extracted are of same type, and are half size of larger vectors.
10585     EVT BigVT = V->getOperand(0).getValueType();
10586     EVT SmallVT = V->getOperand(1).getValueType();
10587     if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
10588       return SDValue();
10589
10590     // Only handle cases where both indexes are constants with the same type.
10591     ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
10592     ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
10593
10594     if (InsIdx && ExtIdx &&
10595         InsIdx->getValueType(0).getSizeInBits() <= 64 &&
10596         ExtIdx->getValueType(0).getSizeInBits() <= 64) {
10597       // Combine:
10598       //    (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
10599       // Into:
10600       //    indices are equal or bit offsets are equal => V1
10601       //    otherwise => (extract_subvec V1, ExtIdx)
10602       if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
10603           ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
10604         return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
10605       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
10606                          DAG.getNode(ISD::BITCAST, dl,
10607                                      N->getOperand(0).getValueType(),
10608                                      V->getOperand(0)), N->getOperand(1));
10609     }
10610   }
10611
10612   return SDValue();
10613 }
10614
10615 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat.
10616 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
10617   EVT VT = N->getValueType(0);
10618   unsigned NumElts = VT.getVectorNumElements();
10619
10620   SDValue N0 = N->getOperand(0);
10621   SDValue N1 = N->getOperand(1);
10622   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10623
10624   SmallVector<SDValue, 4> Ops;
10625   EVT ConcatVT = N0.getOperand(0).getValueType();
10626   unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
10627   unsigned NumConcats = NumElts / NumElemsPerConcat;
10628
10629   // Look at every vector that's inserted. We're looking for exact
10630   // subvector-sized copies from a concatenated vector
10631   for (unsigned I = 0; I != NumConcats; ++I) {
10632     // Make sure we're dealing with a copy.
10633     unsigned Begin = I * NumElemsPerConcat;
10634     bool AllUndef = true, NoUndef = true;
10635     for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
10636       if (SVN->getMaskElt(J) >= 0)
10637         AllUndef = false;
10638       else
10639         NoUndef = false;
10640     }
10641
10642     if (NoUndef) {
10643       if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
10644         return SDValue();
10645
10646       for (unsigned J = 1; J != NumElemsPerConcat; ++J)
10647         if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
10648           return SDValue();
10649
10650       unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
10651       if (FirstElt < N0.getNumOperands())
10652         Ops.push_back(N0.getOperand(FirstElt));
10653       else
10654         Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
10655
10656     } else if (AllUndef) {
10657       Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
10658     } else { // Mixed with general masks and undefs, can't do optimization.
10659       return SDValue();
10660     }
10661   }
10662
10663   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
10664 }
10665
10666 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
10667   EVT VT = N->getValueType(0);
10668   unsigned NumElts = VT.getVectorNumElements();
10669
10670   SDValue N0 = N->getOperand(0);
10671   SDValue N1 = N->getOperand(1);
10672
10673   assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
10674
10675   // Canonicalize shuffle undef, undef -> undef
10676   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
10677     return DAG.getUNDEF(VT);
10678
10679   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10680
10681   // Canonicalize shuffle v, v -> v, undef
10682   if (N0 == N1) {
10683     SmallVector<int, 8> NewMask;
10684     for (unsigned i = 0; i != NumElts; ++i) {
10685       int Idx = SVN->getMaskElt(i);
10686       if (Idx >= (int)NumElts) Idx -= NumElts;
10687       NewMask.push_back(Idx);
10688     }
10689     return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
10690                                 &NewMask[0]);
10691   }
10692
10693   // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
10694   if (N0.getOpcode() == ISD::UNDEF) {
10695     SmallVector<int, 8> NewMask;
10696     for (unsigned i = 0; i != NumElts; ++i) {
10697       int Idx = SVN->getMaskElt(i);
10698       if (Idx >= 0) {
10699         if (Idx >= (int)NumElts)
10700           Idx -= NumElts;
10701         else
10702           Idx = -1; // remove reference to lhs
10703       }
10704       NewMask.push_back(Idx);
10705     }
10706     return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
10707                                 &NewMask[0]);
10708   }
10709
10710   // Remove references to rhs if it is undef
10711   if (N1.getOpcode() == ISD::UNDEF) {
10712     bool Changed = false;
10713     SmallVector<int, 8> NewMask;
10714     for (unsigned i = 0; i != NumElts; ++i) {
10715       int Idx = SVN->getMaskElt(i);
10716       if (Idx >= (int)NumElts) {
10717         Idx = -1;
10718         Changed = true;
10719       }
10720       NewMask.push_back(Idx);
10721     }
10722     if (Changed)
10723       return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
10724   }
10725
10726   // If it is a splat, check if the argument vector is another splat or a
10727   // build_vector with all scalar elements the same.
10728   if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
10729     SDNode *V = N0.getNode();
10730
10731     // If this is a bit convert that changes the element type of the vector but
10732     // not the number of vector elements, look through it.  Be careful not to
10733     // look though conversions that change things like v4f32 to v2f64.
10734     if (V->getOpcode() == ISD::BITCAST) {
10735       SDValue ConvInput = V->getOperand(0);
10736       if (ConvInput.getValueType().isVector() &&
10737           ConvInput.getValueType().getVectorNumElements() == NumElts)
10738         V = ConvInput.getNode();
10739     }
10740
10741     if (V->getOpcode() == ISD::BUILD_VECTOR) {
10742       assert(V->getNumOperands() == NumElts &&
10743              "BUILD_VECTOR has wrong number of operands");
10744       SDValue Base;
10745       bool AllSame = true;
10746       for (unsigned i = 0; i != NumElts; ++i) {
10747         if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
10748           Base = V->getOperand(i);
10749           break;
10750         }
10751       }
10752       // Splat of <u, u, u, u>, return <u, u, u, u>
10753       if (!Base.getNode())
10754         return N0;
10755       for (unsigned i = 0; i != NumElts; ++i) {
10756         if (V->getOperand(i) != Base) {
10757           AllSame = false;
10758           break;
10759         }
10760       }
10761       // Splat of <x, x, x, x>, return <x, x, x, x>
10762       if (AllSame)
10763         return N0;
10764     }
10765   }
10766
10767   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
10768       Level < AfterLegalizeVectorOps &&
10769       (N1.getOpcode() == ISD::UNDEF ||
10770       (N1.getOpcode() == ISD::CONCAT_VECTORS &&
10771        N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
10772     SDValue V = partitionShuffleOfConcats(N, DAG);
10773
10774     if (V.getNode())
10775       return V;
10776   }
10777
10778   // If this shuffle node is simply a swizzle of another shuffle node,
10779   // then try to simplify it.
10780   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
10781       N1.getOpcode() == ISD::UNDEF) {
10782
10783     ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
10784
10785     // The incoming shuffle must be of the same type as the result of the
10786     // current shuffle.
10787     assert(OtherSV->getOperand(0).getValueType() == VT &&
10788            "Shuffle types don't match");
10789
10790     SmallVector<int, 4> Mask;
10791     // Compute the combined shuffle mask.
10792     for (unsigned i = 0; i != NumElts; ++i) {
10793       int Idx = SVN->getMaskElt(i);
10794       assert(Idx < (int)NumElts && "Index references undef operand");
10795       // Next, this index comes from the first value, which is the incoming
10796       // shuffle. Adopt the incoming index.
10797       if (Idx >= 0)
10798         Idx = OtherSV->getMaskElt(Idx);
10799       Mask.push_back(Idx);
10800     }
10801
10802     // Check if all indices in Mask are Undef. In case, propagate Undef.
10803     bool isUndefMask = true;
10804     for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
10805       isUndefMask &= Mask[i] < 0;
10806
10807     if (isUndefMask)
10808       return DAG.getUNDEF(VT);
10809     
10810     bool CommuteOperands = false;
10811     if (N0.getOperand(1).getOpcode() != ISD::UNDEF) {
10812       // To be valid, the combine shuffle mask should only reference elements
10813       // from one of the two vectors in input to the inner shufflevector.
10814       bool IsValidMask = true;
10815       for (unsigned i = 0; i != NumElts && IsValidMask; ++i)
10816         // See if the combined mask only reference undefs or elements coming
10817         // from the first shufflevector operand.
10818         IsValidMask = Mask[i] < 0 || (unsigned)Mask[i] < NumElts;
10819
10820       if (!IsValidMask) {
10821         IsValidMask = true;
10822         for (unsigned i = 0; i != NumElts && IsValidMask; ++i)
10823           // Check that all the elements come from the second shuffle operand.
10824           IsValidMask = Mask[i] < 0 || (unsigned)Mask[i] >= NumElts;
10825         CommuteOperands = IsValidMask;
10826       }
10827
10828       // Early exit if the combined shuffle mask is not valid.
10829       if (!IsValidMask)
10830         return SDValue();
10831     }
10832
10833     // See if this pair of shuffles can be safely folded according to either
10834     // of the following rules:
10835     //   shuffle(shuffle(x, y), undef) -> x
10836     //   shuffle(shuffle(x, undef), undef) -> x
10837     //   shuffle(shuffle(x, y), undef) -> y
10838     bool IsIdentityMask = true;
10839     unsigned BaseMaskIndex = CommuteOperands ? NumElts : 0;
10840     for (unsigned i = 0; i != NumElts && IsIdentityMask; ++i) {
10841       // Skip Undefs.
10842       if (Mask[i] < 0)
10843         continue;
10844
10845       // The combined shuffle must map each index to itself.
10846       IsIdentityMask = (unsigned)Mask[i] == i + BaseMaskIndex;
10847     }
10848     
10849     if (IsIdentityMask) {
10850       if (CommuteOperands)
10851         // optimize shuffle(shuffle(x, y), undef) -> y.
10852         return OtherSV->getOperand(1);
10853       
10854       // optimize shuffle(shuffle(x, undef), undef) -> x
10855       // optimize shuffle(shuffle(x, y), undef) -> x
10856       return OtherSV->getOperand(0);
10857     }
10858
10859     // It may still be beneficial to combine the two shuffles if the
10860     // resulting shuffle is legal.
10861     if (TLI.isTypeLegal(VT)) {
10862       if (!CommuteOperands) {
10863         if (TLI.isShuffleMaskLegal(Mask, VT))
10864           // shuffle(shuffle(x, undef, M1), undef, M2) -> shuffle(x, undef, M3).
10865           // shuffle(shuffle(x, y, M1), undef, M2) -> shuffle(x, undef, M3)
10866           return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0), N1,
10867                                       &Mask[0]);
10868       } else {
10869         // Compute the commuted shuffle mask.
10870         for (unsigned i = 0; i != NumElts; ++i) {
10871           int idx = Mask[i];
10872           if (idx < 0)
10873             continue;
10874           else if (idx < (int)NumElts)
10875             Mask[i] = idx + NumElts;
10876           else
10877             Mask[i] = idx - NumElts;
10878         }
10879
10880         if (TLI.isShuffleMaskLegal(Mask, VT))
10881           //   shuffle(shuffle(x, y, M1), undef, M2) -> shuffle(y, undef, M3)
10882           return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(1), N1,
10883                                       &Mask[0]);
10884       }
10885     }
10886   }
10887
10888   // Canonicalize shuffles according to rules:
10889   //  shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
10890   //  shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
10891   //  shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
10892   if (N1.getOpcode() == ISD::VECTOR_SHUFFLE && N0.getOpcode() != ISD::UNDEF &&
10893       N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
10894       TLI.isTypeLegal(VT)) {
10895     // The incoming shuffle must be of the same type as the result of the
10896     // current shuffle.
10897     assert(N1->getOperand(0).getValueType() == VT &&
10898            "Shuffle types don't match");
10899
10900     SDValue SV0 = N1->getOperand(0);
10901     SDValue SV1 = N1->getOperand(1);
10902     bool HasSameOp0 = N0 == SV0;
10903     bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
10904     if (HasSameOp0 || IsSV1Undef || N0 == SV1)
10905       // Commute the operands of this shuffle so that next rule
10906       // will trigger.
10907       return DAG.getCommutedVectorShuffle(*SVN);
10908   }
10909
10910   // Try to fold according to rules:
10911   //   shuffle(shuffle(A, B, M0), B, M1) -> shuffle(A, B, M2)
10912   //   shuffle(shuffle(A, B, M0), A, M1) -> shuffle(A, B, M2)
10913   //   shuffle(shuffle(A, Undef, M0), B, M1) -> shuffle(A, B, M2)
10914   //   shuffle(shuffle(A, Undef, M0), A, M1) -> shuffle(A, Undef, M2)
10915   // Don't try to fold shuffles with illegal type.
10916   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
10917       N1.getOpcode() != ISD::UNDEF && TLI.isTypeLegal(VT)) {
10918     ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
10919
10920     // The incoming shuffle must be of the same type as the result of the
10921     // current shuffle.
10922     assert(OtherSV->getOperand(0).getValueType() == VT &&
10923            "Shuffle types don't match");
10924
10925     SDValue SV0 = OtherSV->getOperand(0);
10926     SDValue SV1 = OtherSV->getOperand(1);
10927     bool HasSameOp0 = N1 == SV0;
10928     bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
10929     if (!HasSameOp0 && !IsSV1Undef && N1 != SV1)
10930       // Early exit.
10931       return SDValue();
10932
10933     SmallVector<int, 4> Mask;
10934     // Compute the combined shuffle mask for a shuffle with SV0 as the first
10935     // operand, and SV1 as the second operand.
10936     for (unsigned i = 0; i != NumElts; ++i) {
10937       int Idx = SVN->getMaskElt(i);
10938       if (Idx < 0) {
10939         // Propagate Undef.
10940         Mask.push_back(Idx);
10941         continue;
10942       }
10943
10944       if (Idx < (int)NumElts) {
10945         Idx = OtherSV->getMaskElt(Idx);
10946         if (IsSV1Undef && Idx >= (int) NumElts)
10947           Idx = -1;  // Propagate Undef.
10948       } else
10949         Idx = HasSameOp0 ? Idx - NumElts : Idx;
10950
10951       Mask.push_back(Idx);
10952     }
10953
10954     // Check if all indices in Mask are Undef. In case, propagate Undef.
10955     bool isUndefMask = true;
10956     for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
10957       isUndefMask &= Mask[i] < 0;
10958
10959     if (isUndefMask)
10960       return DAG.getUNDEF(VT);
10961
10962     // Avoid introducing shuffles with illegal mask.
10963     if (TLI.isShuffleMaskLegal(Mask, VT)) {
10964       if (IsSV1Undef)
10965         //   shuffle(shuffle(A, Undef, M0), B, M1) -> shuffle(A, B, M2)
10966         //   shuffle(shuffle(A, Undef, M0), A, M1) -> shuffle(A, Undef, M2)
10967         return DAG.getVectorShuffle(VT, SDLoc(N), SV0, N1, &Mask[0]);
10968       return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, &Mask[0]);
10969     }
10970   }
10971
10972   return SDValue();
10973 }
10974
10975 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
10976   SDValue N0 = N->getOperand(0);
10977   SDValue N2 = N->getOperand(2);
10978
10979   // If the input vector is a concatenation, and the insert replaces
10980   // one of the halves, we can optimize into a single concat_vectors.
10981   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
10982       N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
10983     APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
10984     EVT VT = N->getValueType(0);
10985
10986     // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
10987     // (concat_vectors Z, Y)
10988     if (InsIdx == 0)
10989       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
10990                          N->getOperand(1), N0.getOperand(1));
10991
10992     // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
10993     // (concat_vectors X, Z)
10994     if (InsIdx == VT.getVectorNumElements()/2)
10995       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
10996                          N0.getOperand(0), N->getOperand(1));
10997   }
10998
10999   return SDValue();
11000 }
11001
11002 /// XformToShuffleWithZero - Returns a vector_shuffle if it able to transform
11003 /// an AND to a vector_shuffle with the destination vector and a zero vector.
11004 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
11005 ///      vector_shuffle V, Zero, <0, 4, 2, 4>
11006 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
11007   EVT VT = N->getValueType(0);
11008   SDLoc dl(N);
11009   SDValue LHS = N->getOperand(0);
11010   SDValue RHS = N->getOperand(1);
11011   if (N->getOpcode() == ISD::AND) {
11012     if (RHS.getOpcode() == ISD::BITCAST)
11013       RHS = RHS.getOperand(0);
11014     if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
11015       SmallVector<int, 8> Indices;
11016       unsigned NumElts = RHS.getNumOperands();
11017       for (unsigned i = 0; i != NumElts; ++i) {
11018         SDValue Elt = RHS.getOperand(i);
11019         if (!isa<ConstantSDNode>(Elt))
11020           return SDValue();
11021
11022         if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
11023           Indices.push_back(i);
11024         else if (cast<ConstantSDNode>(Elt)->isNullValue())
11025           Indices.push_back(NumElts);
11026         else
11027           return SDValue();
11028       }
11029
11030       // Let's see if the target supports this vector_shuffle.
11031       EVT RVT = RHS.getValueType();
11032       if (!TLI.isVectorClearMaskLegal(Indices, RVT))
11033         return SDValue();
11034
11035       // Return the new VECTOR_SHUFFLE node.
11036       EVT EltVT = RVT.getVectorElementType();
11037       SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
11038                                      DAG.getConstant(0, EltVT));
11039       SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), RVT, ZeroOps);
11040       LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
11041       SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
11042       return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
11043     }
11044   }
11045
11046   return SDValue();
11047 }
11048
11049 /// SimplifyVBinOp - Visit a binary vector operation, like ADD.
11050 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
11051   assert(N->getValueType(0).isVector() &&
11052          "SimplifyVBinOp only works on vectors!");
11053
11054   SDValue LHS = N->getOperand(0);
11055   SDValue RHS = N->getOperand(1);
11056   SDValue Shuffle = XformToShuffleWithZero(N);
11057   if (Shuffle.getNode()) return Shuffle;
11058
11059   // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
11060   // this operation.
11061   if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
11062       RHS.getOpcode() == ISD::BUILD_VECTOR) {
11063     // Check if both vectors are constants. If not bail out.
11064     if (!(cast<BuildVectorSDNode>(LHS)->isConstant() &&
11065           cast<BuildVectorSDNode>(RHS)->isConstant()))
11066       return SDValue();
11067
11068     SmallVector<SDValue, 8> Ops;
11069     for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
11070       SDValue LHSOp = LHS.getOperand(i);
11071       SDValue RHSOp = RHS.getOperand(i);
11072
11073       // Can't fold divide by zero.
11074       if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
11075           N->getOpcode() == ISD::FDIV) {
11076         if ((RHSOp.getOpcode() == ISD::Constant &&
11077              cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
11078             (RHSOp.getOpcode() == ISD::ConstantFP &&
11079              cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
11080           break;
11081       }
11082
11083       EVT VT = LHSOp.getValueType();
11084       EVT RVT = RHSOp.getValueType();
11085       if (RVT != VT) {
11086         // Integer BUILD_VECTOR operands may have types larger than the element
11087         // size (e.g., when the element type is not legal).  Prior to type
11088         // legalization, the types may not match between the two BUILD_VECTORS.
11089         // Truncate one of the operands to make them match.
11090         if (RVT.getSizeInBits() > VT.getSizeInBits()) {
11091           RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
11092         } else {
11093           LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
11094           VT = RVT;
11095         }
11096       }
11097       SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
11098                                    LHSOp, RHSOp);
11099       if (FoldOp.getOpcode() != ISD::UNDEF &&
11100           FoldOp.getOpcode() != ISD::Constant &&
11101           FoldOp.getOpcode() != ISD::ConstantFP)
11102         break;
11103       Ops.push_back(FoldOp);
11104       AddToWorklist(FoldOp.getNode());
11105     }
11106
11107     if (Ops.size() == LHS.getNumOperands())
11108       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), LHS.getValueType(), Ops);
11109   }
11110
11111   // Type legalization might introduce new shuffles in the DAG.
11112   // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
11113   //   -> (shuffle (VBinOp (A, B)), Undef, Mask).
11114   if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
11115       isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
11116       LHS.getOperand(1).getOpcode() == ISD::UNDEF &&
11117       RHS.getOperand(1).getOpcode() == ISD::UNDEF) {
11118     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
11119     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
11120
11121     if (SVN0->getMask().equals(SVN1->getMask())) {
11122       EVT VT = N->getValueType(0);
11123       SDValue UndefVector = LHS.getOperand(1);
11124       SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
11125                                      LHS.getOperand(0), RHS.getOperand(0));
11126       AddUsersToWorklist(N);
11127       return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
11128                                   &SVN0->getMask()[0]);
11129     }
11130   }
11131
11132   return SDValue();
11133 }
11134
11135 /// SimplifyVUnaryOp - Visit a binary vector operation, like FABS/FNEG.
11136 SDValue DAGCombiner::SimplifyVUnaryOp(SDNode *N) {
11137   assert(N->getValueType(0).isVector() &&
11138          "SimplifyVUnaryOp only works on vectors!");
11139
11140   SDValue N0 = N->getOperand(0);
11141
11142   if (N0.getOpcode() != ISD::BUILD_VECTOR)
11143     return SDValue();
11144
11145   // Operand is a BUILD_VECTOR node, see if we can constant fold it.
11146   SmallVector<SDValue, 8> Ops;
11147   for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
11148     SDValue Op = N0.getOperand(i);
11149     if (Op.getOpcode() != ISD::UNDEF &&
11150         Op.getOpcode() != ISD::ConstantFP)
11151       break;
11152     EVT EltVT = Op.getValueType();
11153     SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(N0), EltVT, Op);
11154     if (FoldOp.getOpcode() != ISD::UNDEF &&
11155         FoldOp.getOpcode() != ISD::ConstantFP)
11156       break;
11157     Ops.push_back(FoldOp);
11158     AddToWorklist(FoldOp.getNode());
11159   }
11160
11161   if (Ops.size() != N0.getNumOperands())
11162     return SDValue();
11163
11164   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), N0.getValueType(), Ops);
11165 }
11166
11167 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
11168                                     SDValue N1, SDValue N2){
11169   assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
11170
11171   SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
11172                                  cast<CondCodeSDNode>(N0.getOperand(2))->get());
11173
11174   // If we got a simplified select_cc node back from SimplifySelectCC, then
11175   // break it down into a new SETCC node, and a new SELECT node, and then return
11176   // the SELECT node, since we were called with a SELECT node.
11177   if (SCC.getNode()) {
11178     // Check to see if we got a select_cc back (to turn into setcc/select).
11179     // Otherwise, just return whatever node we got back, like fabs.
11180     if (SCC.getOpcode() == ISD::SELECT_CC) {
11181       SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
11182                                   N0.getValueType(),
11183                                   SCC.getOperand(0), SCC.getOperand(1),
11184                                   SCC.getOperand(4));
11185       AddToWorklist(SETCC.getNode());
11186       return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC,
11187                            SCC.getOperand(2), SCC.getOperand(3));
11188     }
11189
11190     return SCC;
11191   }
11192   return SDValue();
11193 }
11194
11195 /// SimplifySelectOps - Given a SELECT or a SELECT_CC node, where LHS and RHS
11196 /// are the two values being selected between, see if we can simplify the
11197 /// select.  Callers of this should assume that TheSelect is deleted if this
11198 /// returns true.  As such, they should return the appropriate thing (e.g. the
11199 /// node) back to the top-level of the DAG combiner loop to avoid it being
11200 /// looked at.
11201 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
11202                                     SDValue RHS) {
11203
11204   // Cannot simplify select with vector condition
11205   if (TheSelect->getOperand(0).getValueType().isVector()) return false;
11206
11207   // If this is a select from two identical things, try to pull the operation
11208   // through the select.
11209   if (LHS.getOpcode() != RHS.getOpcode() ||
11210       !LHS.hasOneUse() || !RHS.hasOneUse())
11211     return false;
11212
11213   // If this is a load and the token chain is identical, replace the select
11214   // of two loads with a load through a select of the address to load from.
11215   // This triggers in things like "select bool X, 10.0, 123.0" after the FP
11216   // constants have been dropped into the constant pool.
11217   if (LHS.getOpcode() == ISD::LOAD) {
11218     LoadSDNode *LLD = cast<LoadSDNode>(LHS);
11219     LoadSDNode *RLD = cast<LoadSDNode>(RHS);
11220
11221     // Token chains must be identical.
11222     if (LHS.getOperand(0) != RHS.getOperand(0) ||
11223         // Do not let this transformation reduce the number of volatile loads.
11224         LLD->isVolatile() || RLD->isVolatile() ||
11225         // If this is an EXTLOAD, the VT's must match.
11226         LLD->getMemoryVT() != RLD->getMemoryVT() ||
11227         // If this is an EXTLOAD, the kind of extension must match.
11228         (LLD->getExtensionType() != RLD->getExtensionType() &&
11229          // The only exception is if one of the extensions is anyext.
11230          LLD->getExtensionType() != ISD::EXTLOAD &&
11231          RLD->getExtensionType() != ISD::EXTLOAD) ||
11232         // FIXME: this discards src value information.  This is
11233         // over-conservative. It would be beneficial to be able to remember
11234         // both potential memory locations.  Since we are discarding
11235         // src value info, don't do the transformation if the memory
11236         // locations are not in the default address space.
11237         LLD->getPointerInfo().getAddrSpace() != 0 ||
11238         RLD->getPointerInfo().getAddrSpace() != 0 ||
11239         !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
11240                                       LLD->getBasePtr().getValueType()))
11241       return false;
11242
11243     // Check that the select condition doesn't reach either load.  If so,
11244     // folding this will induce a cycle into the DAG.  If not, this is safe to
11245     // xform, so create a select of the addresses.
11246     SDValue Addr;
11247     if (TheSelect->getOpcode() == ISD::SELECT) {
11248       SDNode *CondNode = TheSelect->getOperand(0).getNode();
11249       if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
11250           (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
11251         return false;
11252       // The loads must not depend on one another.
11253       if (LLD->isPredecessorOf(RLD) ||
11254           RLD->isPredecessorOf(LLD))
11255         return false;
11256       Addr = DAG.getSelect(SDLoc(TheSelect),
11257                            LLD->getBasePtr().getValueType(),
11258                            TheSelect->getOperand(0), LLD->getBasePtr(),
11259                            RLD->getBasePtr());
11260     } else {  // Otherwise SELECT_CC
11261       SDNode *CondLHS = TheSelect->getOperand(0).getNode();
11262       SDNode *CondRHS = TheSelect->getOperand(1).getNode();
11263
11264       if ((LLD->hasAnyUseOfValue(1) &&
11265            (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
11266           (RLD->hasAnyUseOfValue(1) &&
11267            (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
11268         return false;
11269
11270       Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
11271                          LLD->getBasePtr().getValueType(),
11272                          TheSelect->getOperand(0),
11273                          TheSelect->getOperand(1),
11274                          LLD->getBasePtr(), RLD->getBasePtr(),
11275                          TheSelect->getOperand(4));
11276     }
11277
11278     SDValue Load;
11279     // It is safe to replace the two loads if they have different alignments,
11280     // but the new load must be the minimum (most restrictive) alignment of the
11281     // inputs.
11282     bool isInvariant = LLD->getAlignment() & RLD->getAlignment();
11283     unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment());
11284     if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
11285       Load = DAG.getLoad(TheSelect->getValueType(0),
11286                          SDLoc(TheSelect),
11287                          // FIXME: Discards pointer and AA info.
11288                          LLD->getChain(), Addr, MachinePointerInfo(),
11289                          LLD->isVolatile(), LLD->isNonTemporal(),
11290                          isInvariant, Alignment);
11291     } else {
11292       Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
11293                             RLD->getExtensionType() : LLD->getExtensionType(),
11294                             SDLoc(TheSelect),
11295                             TheSelect->getValueType(0),
11296                             // FIXME: Discards pointer and AA info.
11297                             LLD->getChain(), Addr, MachinePointerInfo(),
11298                             LLD->getMemoryVT(), LLD->isVolatile(),
11299                             LLD->isNonTemporal(), isInvariant, Alignment);
11300     }
11301
11302     // Users of the select now use the result of the load.
11303     CombineTo(TheSelect, Load);
11304
11305     // Users of the old loads now use the new load's chain.  We know the
11306     // old-load value is dead now.
11307     CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
11308     CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
11309     return true;
11310   }
11311
11312   return false;
11313 }
11314
11315 /// SimplifySelectCC - Simplify an expression of the form (N0 cond N1) ? N2 : N3
11316 /// where 'cond' is the comparison specified by CC.
11317 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
11318                                       SDValue N2, SDValue N3,
11319                                       ISD::CondCode CC, bool NotExtCompare) {
11320   // (x ? y : y) -> y.
11321   if (N2 == N3) return N2;
11322
11323   EVT VT = N2.getValueType();
11324   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
11325   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
11326   ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
11327
11328   // Determine if the condition we're dealing with is constant
11329   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
11330                               N0, N1, CC, DL, false);
11331   if (SCC.getNode()) AddToWorklist(SCC.getNode());
11332   ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
11333
11334   // fold select_cc true, x, y -> x
11335   if (SCCC && !SCCC->isNullValue())
11336     return N2;
11337   // fold select_cc false, x, y -> y
11338   if (SCCC && SCCC->isNullValue())
11339     return N3;
11340
11341   // Check to see if we can simplify the select into an fabs node
11342   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
11343     // Allow either -0.0 or 0.0
11344     if (CFP->getValueAPF().isZero()) {
11345       // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
11346       if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
11347           N0 == N2 && N3.getOpcode() == ISD::FNEG &&
11348           N2 == N3.getOperand(0))
11349         return DAG.getNode(ISD::FABS, DL, VT, N0);
11350
11351       // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
11352       if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
11353           N0 == N3 && N2.getOpcode() == ISD::FNEG &&
11354           N2.getOperand(0) == N3)
11355         return DAG.getNode(ISD::FABS, DL, VT, N3);
11356     }
11357   }
11358
11359   // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
11360   // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
11361   // in it.  This is a win when the constant is not otherwise available because
11362   // it replaces two constant pool loads with one.  We only do this if the FP
11363   // type is known to be legal, because if it isn't, then we are before legalize
11364   // types an we want the other legalization to happen first (e.g. to avoid
11365   // messing with soft float) and if the ConstantFP is not legal, because if
11366   // it is legal, we may not need to store the FP constant in a constant pool.
11367   if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
11368     if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
11369       if (TLI.isTypeLegal(N2.getValueType()) &&
11370           (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
11371                TargetLowering::Legal &&
11372            !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
11373            !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
11374           // If both constants have multiple uses, then we won't need to do an
11375           // extra load, they are likely around in registers for other users.
11376           (TV->hasOneUse() || FV->hasOneUse())) {
11377         Constant *Elts[] = {
11378           const_cast<ConstantFP*>(FV->getConstantFPValue()),
11379           const_cast<ConstantFP*>(TV->getConstantFPValue())
11380         };
11381         Type *FPTy = Elts[0]->getType();
11382         const DataLayout &TD = *TLI.getDataLayout();
11383
11384         // Create a ConstantArray of the two constants.
11385         Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
11386         SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
11387                                             TD.getPrefTypeAlignment(FPTy));
11388         unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
11389
11390         // Get the offsets to the 0 and 1 element of the array so that we can
11391         // select between them.
11392         SDValue Zero = DAG.getIntPtrConstant(0);
11393         unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
11394         SDValue One = DAG.getIntPtrConstant(EltSize);
11395
11396         SDValue Cond = DAG.getSetCC(DL,
11397                                     getSetCCResultType(N0.getValueType()),
11398                                     N0, N1, CC);
11399         AddToWorklist(Cond.getNode());
11400         SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
11401                                           Cond, One, Zero);
11402         AddToWorklist(CstOffset.getNode());
11403         CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
11404                             CstOffset);
11405         AddToWorklist(CPIdx.getNode());
11406         return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
11407                            MachinePointerInfo::getConstantPool(), false,
11408                            false, false, Alignment);
11409
11410       }
11411     }
11412
11413   // Check to see if we can perform the "gzip trick", transforming
11414   // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
11415   if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
11416       (N1C->isNullValue() ||                         // (a < 0) ? b : 0
11417        (N1C->getAPIntValue() == 1 && N0 == N2))) {   // (a < 1) ? a : 0
11418     EVT XType = N0.getValueType();
11419     EVT AType = N2.getValueType();
11420     if (XType.bitsGE(AType)) {
11421       // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
11422       // single-bit constant.
11423       if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
11424         unsigned ShCtV = N2C->getAPIntValue().logBase2();
11425         ShCtV = XType.getSizeInBits()-ShCtV-1;
11426         SDValue ShCt = DAG.getConstant(ShCtV,
11427                                        getShiftAmountTy(N0.getValueType()));
11428         SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
11429                                     XType, N0, ShCt);
11430         AddToWorklist(Shift.getNode());
11431
11432         if (XType.bitsGT(AType)) {
11433           Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
11434           AddToWorklist(Shift.getNode());
11435         }
11436
11437         return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
11438       }
11439
11440       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
11441                                   XType, N0,
11442                                   DAG.getConstant(XType.getSizeInBits()-1,
11443                                          getShiftAmountTy(N0.getValueType())));
11444       AddToWorklist(Shift.getNode());
11445
11446       if (XType.bitsGT(AType)) {
11447         Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
11448         AddToWorklist(Shift.getNode());
11449       }
11450
11451       return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
11452     }
11453   }
11454
11455   // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
11456   // where y is has a single bit set.
11457   // A plaintext description would be, we can turn the SELECT_CC into an AND
11458   // when the condition can be materialized as an all-ones register.  Any
11459   // single bit-test can be materialized as an all-ones register with
11460   // shift-left and shift-right-arith.
11461   if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
11462       N0->getValueType(0) == VT &&
11463       N1C && N1C->isNullValue() &&
11464       N2C && N2C->isNullValue()) {
11465     SDValue AndLHS = N0->getOperand(0);
11466     ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
11467     if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
11468       // Shift the tested bit over the sign bit.
11469       APInt AndMask = ConstAndRHS->getAPIntValue();
11470       SDValue ShlAmt =
11471         DAG.getConstant(AndMask.countLeadingZeros(),
11472                         getShiftAmountTy(AndLHS.getValueType()));
11473       SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
11474
11475       // Now arithmetic right shift it all the way over, so the result is either
11476       // all-ones, or zero.
11477       SDValue ShrAmt =
11478         DAG.getConstant(AndMask.getBitWidth()-1,
11479                         getShiftAmountTy(Shl.getValueType()));
11480       SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
11481
11482       return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
11483     }
11484   }
11485
11486   // fold select C, 16, 0 -> shl C, 4
11487   if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
11488       TLI.getBooleanContents(N0.getValueType()) ==
11489           TargetLowering::ZeroOrOneBooleanContent) {
11490
11491     // If the caller doesn't want us to simplify this into a zext of a compare,
11492     // don't do it.
11493     if (NotExtCompare && N2C->getAPIntValue() == 1)
11494       return SDValue();
11495
11496     // Get a SetCC of the condition
11497     // NOTE: Don't create a SETCC if it's not legal on this target.
11498     if (!LegalOperations ||
11499         TLI.isOperationLegal(ISD::SETCC,
11500           LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
11501       SDValue Temp, SCC;
11502       // cast from setcc result type to select result type
11503       if (LegalTypes) {
11504         SCC  = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
11505                             N0, N1, CC);
11506         if (N2.getValueType().bitsLT(SCC.getValueType()))
11507           Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
11508                                         N2.getValueType());
11509         else
11510           Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
11511                              N2.getValueType(), SCC);
11512       } else {
11513         SCC  = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
11514         Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
11515                            N2.getValueType(), SCC);
11516       }
11517
11518       AddToWorklist(SCC.getNode());
11519       AddToWorklist(Temp.getNode());
11520
11521       if (N2C->getAPIntValue() == 1)
11522         return Temp;
11523
11524       // shl setcc result by log2 n2c
11525       return DAG.getNode(
11526           ISD::SHL, DL, N2.getValueType(), Temp,
11527           DAG.getConstant(N2C->getAPIntValue().logBase2(),
11528                           getShiftAmountTy(Temp.getValueType())));
11529     }
11530   }
11531
11532   // Check to see if this is the equivalent of setcc
11533   // FIXME: Turn all of these into setcc if setcc if setcc is legal
11534   // otherwise, go ahead with the folds.
11535   if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
11536     EVT XType = N0.getValueType();
11537     if (!LegalOperations ||
11538         TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
11539       SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
11540       if (Res.getValueType() != VT)
11541         Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
11542       return Res;
11543     }
11544
11545     // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
11546     if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
11547         (!LegalOperations ||
11548          TLI.isOperationLegal(ISD::CTLZ, XType))) {
11549       SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
11550       return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
11551                          DAG.getConstant(Log2_32(XType.getSizeInBits()),
11552                                        getShiftAmountTy(Ctlz.getValueType())));
11553     }
11554     // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
11555     if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
11556       SDValue NegN0 = DAG.getNode(ISD::SUB, SDLoc(N0),
11557                                   XType, DAG.getConstant(0, XType), N0);
11558       SDValue NotN0 = DAG.getNOT(SDLoc(N0), N0, XType);
11559       return DAG.getNode(ISD::SRL, DL, XType,
11560                          DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
11561                          DAG.getConstant(XType.getSizeInBits()-1,
11562                                          getShiftAmountTy(XType)));
11563     }
11564     // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
11565     if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
11566       SDValue Sign = DAG.getNode(ISD::SRL, SDLoc(N0), XType, N0,
11567                                  DAG.getConstant(XType.getSizeInBits()-1,
11568                                          getShiftAmountTy(N0.getValueType())));
11569       return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
11570     }
11571   }
11572
11573   // Check to see if this is an integer abs.
11574   // select_cc setg[te] X,  0,  X, -X ->
11575   // select_cc setgt    X, -1,  X, -X ->
11576   // select_cc setl[te] X,  0, -X,  X ->
11577   // select_cc setlt    X,  1, -X,  X ->
11578   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
11579   if (N1C) {
11580     ConstantSDNode *SubC = nullptr;
11581     if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
11582          (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
11583         N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
11584       SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
11585     else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
11586               (N1C->isOne() && CC == ISD::SETLT)) &&
11587              N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
11588       SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
11589
11590     EVT XType = N0.getValueType();
11591     if (SubC && SubC->isNullValue() && XType.isInteger()) {
11592       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), XType,
11593                                   N0,
11594                                   DAG.getConstant(XType.getSizeInBits()-1,
11595                                          getShiftAmountTy(N0.getValueType())));
11596       SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0),
11597                                 XType, N0, Shift);
11598       AddToWorklist(Shift.getNode());
11599       AddToWorklist(Add.getNode());
11600       return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
11601     }
11602   }
11603
11604   return SDValue();
11605 }
11606
11607 /// SimplifySetCC - This is a stub for TargetLowering::SimplifySetCC.
11608 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
11609                                    SDValue N1, ISD::CondCode Cond,
11610                                    SDLoc DL, bool foldBooleans) {
11611   TargetLowering::DAGCombinerInfo
11612     DagCombineInfo(DAG, Level, false, this);
11613   return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
11614 }
11615
11616 /// BuildSDIV - Given an ISD::SDIV node expressing a divide by constant, return
11617 /// a DAG expression to select that will generate the same value by multiplying
11618 /// by a magic number.  See:
11619 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
11620 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
11621   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
11622   if (!C)
11623     return SDValue();
11624
11625   // Avoid division by zero.
11626   if (!C->getAPIntValue())
11627     return SDValue();
11628
11629   std::vector<SDNode*> Built;
11630   SDValue S =
11631       TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
11632
11633   for (SDNode *N : Built)
11634     AddToWorklist(N);
11635   return S;
11636 }
11637
11638 /// BuildSDIVPow2 - Given an ISD::SDIV node expressing a divide by constant
11639 /// power of 2, return a DAG expression to select that will generate the same
11640 /// value by right shifting.
11641 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
11642   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
11643   if (!C)
11644     return SDValue();
11645
11646   // Avoid division by zero.
11647   if (!C->getAPIntValue())
11648     return SDValue();
11649
11650   std::vector<SDNode *> Built;
11651   SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
11652
11653   for (SDNode *N : Built)
11654     AddToWorklist(N);
11655   return S;
11656 }
11657
11658 /// BuildUDIV - Given an ISD::UDIV node expressing a divide by constant,
11659 /// return a DAG expression to select that will generate the same value by
11660 /// multiplying by a magic number.  See:
11661 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
11662 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
11663   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
11664   if (!C)
11665     return SDValue();
11666
11667   // Avoid division by zero.
11668   if (!C->getAPIntValue())
11669     return SDValue();
11670
11671   std::vector<SDNode*> Built;
11672   SDValue S =
11673       TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
11674
11675   for (SDNode *N : Built)
11676     AddToWorklist(N);
11677   return S;
11678 }
11679
11680 /// FindBaseOffset - Return true if base is a frame index, which is known not
11681 // to alias with anything but itself.  Provides base object and offset as
11682 // results.
11683 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
11684                            const GlobalValue *&GV, const void *&CV) {
11685   // Assume it is a primitive operation.
11686   Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
11687
11688   // If it's an adding a simple constant then integrate the offset.
11689   if (Base.getOpcode() == ISD::ADD) {
11690     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
11691       Base = Base.getOperand(0);
11692       Offset += C->getZExtValue();
11693     }
11694   }
11695
11696   // Return the underlying GlobalValue, and update the Offset.  Return false
11697   // for GlobalAddressSDNode since the same GlobalAddress may be represented
11698   // by multiple nodes with different offsets.
11699   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
11700     GV = G->getGlobal();
11701     Offset += G->getOffset();
11702     return false;
11703   }
11704
11705   // Return the underlying Constant value, and update the Offset.  Return false
11706   // for ConstantSDNodes since the same constant pool entry may be represented
11707   // by multiple nodes with different offsets.
11708   if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
11709     CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
11710                                          : (const void *)C->getConstVal();
11711     Offset += C->getOffset();
11712     return false;
11713   }
11714   // If it's any of the following then it can't alias with anything but itself.
11715   return isa<FrameIndexSDNode>(Base);
11716 }
11717
11718 /// isAlias - Return true if there is any possibility that the two addresses
11719 /// overlap.
11720 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
11721   // If they are the same then they must be aliases.
11722   if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
11723
11724   // If they are both volatile then they cannot be reordered.
11725   if (Op0->isVolatile() && Op1->isVolatile()) return true;
11726
11727   // Gather base node and offset information.
11728   SDValue Base1, Base2;
11729   int64_t Offset1, Offset2;
11730   const GlobalValue *GV1, *GV2;
11731   const void *CV1, *CV2;
11732   bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
11733                                       Base1, Offset1, GV1, CV1);
11734   bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
11735                                       Base2, Offset2, GV2, CV2);
11736
11737   // If they have a same base address then check to see if they overlap.
11738   if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
11739     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
11740              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
11741
11742   // It is possible for different frame indices to alias each other, mostly
11743   // when tail call optimization reuses return address slots for arguments.
11744   // To catch this case, look up the actual index of frame indices to compute
11745   // the real alias relationship.
11746   if (isFrameIndex1 && isFrameIndex2) {
11747     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11748     Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
11749     Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
11750     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
11751              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
11752   }
11753
11754   // Otherwise, if we know what the bases are, and they aren't identical, then
11755   // we know they cannot alias.
11756   if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
11757     return false;
11758
11759   // If we know required SrcValue1 and SrcValue2 have relatively large alignment
11760   // compared to the size and offset of the access, we may be able to prove they
11761   // do not alias.  This check is conservative for now to catch cases created by
11762   // splitting vector types.
11763   if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
11764       (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
11765       (Op0->getMemoryVT().getSizeInBits() >> 3 ==
11766        Op1->getMemoryVT().getSizeInBits() >> 3) &&
11767       (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) {
11768     int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
11769     int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
11770
11771     // There is no overlap between these relatively aligned accesses of similar
11772     // size, return no alias.
11773     if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
11774         (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
11775       return false;
11776   }
11777
11778   bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0 ? CombinerGlobalAA :
11779     TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
11780 #ifndef NDEBUG
11781   if (CombinerAAOnlyFunc.getNumOccurrences() &&
11782       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
11783     UseAA = false;
11784 #endif
11785   if (UseAA &&
11786       Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
11787     // Use alias analysis information.
11788     int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
11789                                  Op1->getSrcValueOffset());
11790     int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
11791         Op0->getSrcValueOffset() - MinOffset;
11792     int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
11793         Op1->getSrcValueOffset() - MinOffset;
11794     AliasAnalysis::AliasResult AAResult =
11795         AA.alias(AliasAnalysis::Location(Op0->getMemOperand()->getValue(),
11796                                          Overlap1,
11797                                          UseTBAA ? Op0->getAAInfo() : AAMDNodes()),
11798                  AliasAnalysis::Location(Op1->getMemOperand()->getValue(),
11799                                          Overlap2,
11800                                          UseTBAA ? Op1->getAAInfo() : AAMDNodes()));
11801     if (AAResult == AliasAnalysis::NoAlias)
11802       return false;
11803   }
11804
11805   // Otherwise we have to assume they alias.
11806   return true;
11807 }
11808
11809 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
11810 /// looking for aliasing nodes and adding them to the Aliases vector.
11811 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
11812                                    SmallVectorImpl<SDValue> &Aliases) {
11813   SmallVector<SDValue, 8> Chains;     // List of chains to visit.
11814   SmallPtrSet<SDNode *, 16> Visited;  // Visited node set.
11815
11816   // Get alias information for node.
11817   bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
11818
11819   // Starting off.
11820   Chains.push_back(OriginalChain);
11821   unsigned Depth = 0;
11822
11823   // Look at each chain and determine if it is an alias.  If so, add it to the
11824   // aliases list.  If not, then continue up the chain looking for the next
11825   // candidate.
11826   while (!Chains.empty()) {
11827     SDValue Chain = Chains.back();
11828     Chains.pop_back();
11829
11830     // For TokenFactor nodes, look at each operand and only continue up the
11831     // chain until we find two aliases.  If we've seen two aliases, assume we'll
11832     // find more and revert to original chain since the xform is unlikely to be
11833     // profitable.
11834     //
11835     // FIXME: The depth check could be made to return the last non-aliasing
11836     // chain we found before we hit a tokenfactor rather than the original
11837     // chain.
11838     if (Depth > 6 || Aliases.size() == 2) {
11839       Aliases.clear();
11840       Aliases.push_back(OriginalChain);
11841       return;
11842     }
11843
11844     // Don't bother if we've been before.
11845     if (!Visited.insert(Chain.getNode()))
11846       continue;
11847
11848     switch (Chain.getOpcode()) {
11849     case ISD::EntryToken:
11850       // Entry token is ideal chain operand, but handled in FindBetterChain.
11851       break;
11852
11853     case ISD::LOAD:
11854     case ISD::STORE: {
11855       // Get alias information for Chain.
11856       bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
11857           !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
11858
11859       // If chain is alias then stop here.
11860       if (!(IsLoad && IsOpLoad) &&
11861           isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
11862         Aliases.push_back(Chain);
11863       } else {
11864         // Look further up the chain.
11865         Chains.push_back(Chain.getOperand(0));
11866         ++Depth;
11867       }
11868       break;
11869     }
11870
11871     case ISD::TokenFactor:
11872       // We have to check each of the operands of the token factor for "small"
11873       // token factors, so we queue them up.  Adding the operands to the queue
11874       // (stack) in reverse order maintains the original order and increases the
11875       // likelihood that getNode will find a matching token factor (CSE.)
11876       if (Chain.getNumOperands() > 16) {
11877         Aliases.push_back(Chain);
11878         break;
11879       }
11880       for (unsigned n = Chain.getNumOperands(); n;)
11881         Chains.push_back(Chain.getOperand(--n));
11882       ++Depth;
11883       break;
11884
11885     default:
11886       // For all other instructions we will just have to take what we can get.
11887       Aliases.push_back(Chain);
11888       break;
11889     }
11890   }
11891
11892   // We need to be careful here to also search for aliases through the
11893   // value operand of a store, etc. Consider the following situation:
11894   //   Token1 = ...
11895   //   L1 = load Token1, %52
11896   //   S1 = store Token1, L1, %51
11897   //   L2 = load Token1, %52+8
11898   //   S2 = store Token1, L2, %51+8
11899   //   Token2 = Token(S1, S2)
11900   //   L3 = load Token2, %53
11901   //   S3 = store Token2, L3, %52
11902   //   L4 = load Token2, %53+8
11903   //   S4 = store Token2, L4, %52+8
11904   // If we search for aliases of S3 (which loads address %52), and we look
11905   // only through the chain, then we'll miss the trivial dependence on L1
11906   // (which also loads from %52). We then might change all loads and
11907   // stores to use Token1 as their chain operand, which could result in
11908   // copying %53 into %52 before copying %52 into %51 (which should
11909   // happen first).
11910   //
11911   // The problem is, however, that searching for such data dependencies
11912   // can become expensive, and the cost is not directly related to the
11913   // chain depth. Instead, we'll rule out such configurations here by
11914   // insisting that we've visited all chain users (except for users
11915   // of the original chain, which is not necessary). When doing this,
11916   // we need to look through nodes we don't care about (otherwise, things
11917   // like register copies will interfere with trivial cases).
11918
11919   SmallVector<const SDNode *, 16> Worklist;
11920   for (const SDNode *N : Visited)
11921     if (N != OriginalChain.getNode())
11922       Worklist.push_back(N);
11923
11924   while (!Worklist.empty()) {
11925     const SDNode *M = Worklist.pop_back_val();
11926
11927     // We have already visited M, and want to make sure we've visited any uses
11928     // of M that we care about. For uses that we've not visisted, and don't
11929     // care about, queue them to the worklist.
11930
11931     for (SDNode::use_iterator UI = M->use_begin(),
11932          UIE = M->use_end(); UI != UIE; ++UI)
11933       if (UI.getUse().getValueType() == MVT::Other && Visited.insert(*UI)) {
11934         if (isa<MemIntrinsicSDNode>(*UI) || isa<MemSDNode>(*UI)) {
11935           // We've not visited this use, and we care about it (it could have an
11936           // ordering dependency with the original node).
11937           Aliases.clear();
11938           Aliases.push_back(OriginalChain);
11939           return;
11940         }
11941
11942         // We've not visited this use, but we don't care about it. Mark it as
11943         // visited and enqueue it to the worklist.
11944         Worklist.push_back(*UI);
11945       }
11946   }
11947 }
11948
11949 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes, looking
11950 /// for a better chain (aliasing node.)
11951 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
11952   SmallVector<SDValue, 8> Aliases;  // Ops for replacing token factor.
11953
11954   // Accumulate all the aliases to this node.
11955   GatherAllAliases(N, OldChain, Aliases);
11956
11957   // If no operands then chain to entry token.
11958   if (Aliases.size() == 0)
11959     return DAG.getEntryNode();
11960
11961   // If a single operand then chain to it.  We don't need to revisit it.
11962   if (Aliases.size() == 1)
11963     return Aliases[0];
11964
11965   // Construct a custom tailored token factor.
11966   return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
11967 }
11968
11969 // SelectionDAG::Combine - This is the entry point for the file.
11970 //
11971 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
11972                            CodeGenOpt::Level OptLevel) {
11973   /// run - This is the main entry point to this class.
11974   ///
11975   DAGCombiner(*this, AA, OptLevel).Run(Level);
11976 }