Update SetVector to rely on the underlying set's insert to return a pair<iterator...
[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/SmallBitVector.h"
21 #include "llvm/ADT/SmallPtrSet.h"
22 #include "llvm/ADT/SetVector.h"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/Analysis/AliasAnalysis.h"
25 #include "llvm/CodeGen/MachineFrameInfo.h"
26 #include "llvm/CodeGen/MachineFunction.h"
27 #include "llvm/IR/DataLayout.h"
28 #include "llvm/IR/DerivedTypes.h"
29 #include "llvm/IR/Function.h"
30 #include "llvm/IR/LLVMContext.h"
31 #include "llvm/Support/CommandLine.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Support/ErrorHandling.h"
34 #include "llvm/Support/MathExtras.h"
35 #include "llvm/Support/raw_ostream.h"
36 #include "llvm/Target/TargetLowering.h"
37 #include "llvm/Target/TargetOptions.h"
38 #include "llvm/Target/TargetRegisterInfo.h"
39 #include "llvm/Target/TargetSubtargetInfo.h"
40 #include <algorithm>
41 using namespace llvm;
42
43 #define DEBUG_TYPE "dagcombine"
44
45 STATISTIC(NodesCombined   , "Number of dag nodes combined");
46 STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created");
47 STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created");
48 STATISTIC(OpsNarrowed     , "Number of load/op/store narrowed");
49 STATISTIC(LdStFP2Int      , "Number of fp load/store pairs transformed to int");
50 STATISTIC(SlicedLoads, "Number of load sliced");
51
52 namespace {
53   static cl::opt<bool>
54     CombinerAA("combiner-alias-analysis", cl::Hidden,
55                cl::desc("Enable DAG combiner alias-analysis heuristics"));
56
57   static cl::opt<bool>
58     CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
59                cl::desc("Enable DAG combiner's use of IR alias analysis"));
60
61   static cl::opt<bool>
62     UseTBAA("combiner-use-tbaa", cl::Hidden, cl::init(true),
63                cl::desc("Enable DAG combiner's use of TBAA"));
64
65 #ifndef NDEBUG
66   static cl::opt<std::string>
67     CombinerAAOnlyFunc("combiner-aa-only-func", cl::Hidden,
68                cl::desc("Only use DAG-combiner alias analysis in this"
69                         " function"));
70 #endif
71
72   /// Hidden option to stress test load slicing, i.e., when this option
73   /// is enabled, load slicing bypasses most of its profitability guards.
74   static cl::opt<bool>
75   StressLoadSlicing("combiner-stress-load-slicing", cl::Hidden,
76                     cl::desc("Bypass the profitability model of load "
77                              "slicing"),
78                     cl::init(false));
79
80   static cl::opt<bool>
81     MaySplitLoadIndex("combiner-split-load-index", cl::Hidden, cl::init(true),
82                       cl::desc("DAG combiner may split indexing from loads"));
83
84 //------------------------------ DAGCombiner ---------------------------------//
85
86   class DAGCombiner {
87     SelectionDAG &DAG;
88     const TargetLowering &TLI;
89     CombineLevel Level;
90     CodeGenOpt::Level OptLevel;
91     bool LegalOperations;
92     bool LegalTypes;
93     bool ForCodeSize;
94
95     /// \brief Worklist of all of the nodes that need to be simplified.
96     ///
97     /// This must behave as a stack -- new nodes to process are pushed onto the
98     /// back and when processing we pop off of the back.
99     ///
100     /// The worklist will not contain duplicates but may contain null entries
101     /// due to nodes being deleted from the underlying DAG.
102     SmallVector<SDNode *, 64> Worklist;
103
104     /// \brief Mapping from an SDNode to its position on the worklist.
105     ///
106     /// This is used to find and remove nodes from the worklist (by nulling
107     /// them) when they are deleted from the underlying DAG. It relies on
108     /// stable indices of nodes within the worklist.
109     DenseMap<SDNode *, unsigned> WorklistMap;
110
111     /// \brief Set of nodes which have been combined (at least once).
112     ///
113     /// This is used to allow us to reliably add any operands of a DAG node
114     /// which have not yet been combined to the worklist.
115     SmallPtrSet<SDNode *, 64> CombinedNodes;
116
117     // AA - Used for DAG load/store alias analysis.
118     AliasAnalysis &AA;
119
120     /// When an instruction is simplified, add all users of the instruction to
121     /// the work lists because they might get more simplified now.
122     void AddUsersToWorklist(SDNode *N) {
123       for (SDNode *Node : N->uses())
124         AddToWorklist(Node);
125     }
126
127     /// Call the node-specific routine that folds each particular type of node.
128     SDValue visit(SDNode *N);
129
130   public:
131     /// Add to the worklist making sure its instance is at the back (next to be
132     /// processed.)
133     void AddToWorklist(SDNode *N) {
134       // Skip handle nodes as they can't usefully be combined and confuse the
135       // zero-use deletion strategy.
136       if (N->getOpcode() == ISD::HANDLENODE)
137         return;
138
139       if (WorklistMap.insert(std::make_pair(N, Worklist.size())).second)
140         Worklist.push_back(N);
141     }
142
143     /// Remove all instances of N from the worklist.
144     void removeFromWorklist(SDNode *N) {
145       CombinedNodes.erase(N);
146
147       auto It = WorklistMap.find(N);
148       if (It == WorklistMap.end())
149         return; // Not in the worklist.
150
151       // Null out the entry rather than erasing it to avoid a linear operation.
152       Worklist[It->second] = nullptr;
153       WorklistMap.erase(It);
154     }
155
156     void deleteAndRecombine(SDNode *N);
157     bool recursivelyDeleteUnusedNodes(SDNode *N);
158
159     SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
160                       bool AddTo = true);
161
162     SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
163       return CombineTo(N, &Res, 1, AddTo);
164     }
165
166     SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
167                       bool AddTo = true) {
168       SDValue To[] = { Res0, Res1 };
169       return CombineTo(N, To, 2, AddTo);
170     }
171
172     void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
173
174   private:
175
176     /// Check the specified integer node value to see if it can be simplified or
177     /// if things it uses can be simplified by bit propagation.
178     /// If so, return true.
179     bool SimplifyDemandedBits(SDValue Op) {
180       unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits();
181       APInt Demanded = APInt::getAllOnesValue(BitWidth);
182       return SimplifyDemandedBits(Op, Demanded);
183     }
184
185     bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded);
186
187     bool CombineToPreIndexedLoadStore(SDNode *N);
188     bool CombineToPostIndexedLoadStore(SDNode *N);
189     SDValue SplitIndexingFromLoad(LoadSDNode *LD);
190     bool SliceUpLoad(SDNode *N);
191
192     /// \brief Replace an ISD::EXTRACT_VECTOR_ELT of a load with a narrowed
193     ///   load.
194     ///
195     /// \param EVE ISD::EXTRACT_VECTOR_ELT to be replaced.
196     /// \param InVecVT type of the input vector to EVE with bitcasts resolved.
197     /// \param EltNo index of the vector element to load.
198     /// \param OriginalLoad load that EVE came from to be replaced.
199     /// \returns EVE on success SDValue() on failure.
200     SDValue ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
201         SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad);
202     void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
203     SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
204     SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
205     SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
206     SDValue PromoteIntBinOp(SDValue Op);
207     SDValue PromoteIntShiftOp(SDValue Op);
208     SDValue PromoteExtend(SDValue Op);
209     bool PromoteLoad(SDValue Op);
210
211     void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
212                          SDValue Trunc, SDValue ExtLoad, SDLoc DL,
213                          ISD::NodeType ExtType);
214
215     /// Call the node-specific routine that knows how to fold each
216     /// particular type of node. If that doesn't do anything, try the
217     /// target-specific DAG combines.
218     SDValue combine(SDNode *N);
219
220     // Visitation implementation - Implement dag node combining for different
221     // node types.  The semantics are as follows:
222     // Return Value:
223     //   SDValue.getNode() == 0 - No change was made
224     //   SDValue.getNode() == N - N was replaced, is dead and has been handled.
225     //   otherwise              - N should be replaced by the returned Operand.
226     //
227     SDValue visitTokenFactor(SDNode *N);
228     SDValue visitMERGE_VALUES(SDNode *N);
229     SDValue visitADD(SDNode *N);
230     SDValue visitSUB(SDNode *N);
231     SDValue visitADDC(SDNode *N);
232     SDValue visitSUBC(SDNode *N);
233     SDValue visitADDE(SDNode *N);
234     SDValue visitSUBE(SDNode *N);
235     SDValue visitMUL(SDNode *N);
236     SDValue visitSDIV(SDNode *N);
237     SDValue visitUDIV(SDNode *N);
238     SDValue visitSREM(SDNode *N);
239     SDValue visitUREM(SDNode *N);
240     SDValue visitMULHU(SDNode *N);
241     SDValue visitMULHS(SDNode *N);
242     SDValue visitSMUL_LOHI(SDNode *N);
243     SDValue visitUMUL_LOHI(SDNode *N);
244     SDValue visitSMULO(SDNode *N);
245     SDValue visitUMULO(SDNode *N);
246     SDValue visitSDIVREM(SDNode *N);
247     SDValue visitUDIVREM(SDNode *N);
248     SDValue visitAND(SDNode *N);
249     SDValue visitOR(SDNode *N);
250     SDValue visitXOR(SDNode *N);
251     SDValue SimplifyVBinOp(SDNode *N);
252     SDValue SimplifyVUnaryOp(SDNode *N);
253     SDValue visitSHL(SDNode *N);
254     SDValue visitSRA(SDNode *N);
255     SDValue visitSRL(SDNode *N);
256     SDValue visitRotate(SDNode *N);
257     SDValue visitCTLZ(SDNode *N);
258     SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
259     SDValue visitCTTZ(SDNode *N);
260     SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
261     SDValue visitCTPOP(SDNode *N);
262     SDValue visitSELECT(SDNode *N);
263     SDValue visitVSELECT(SDNode *N);
264     SDValue visitSELECT_CC(SDNode *N);
265     SDValue visitSETCC(SDNode *N);
266     SDValue visitSIGN_EXTEND(SDNode *N);
267     SDValue visitZERO_EXTEND(SDNode *N);
268     SDValue visitANY_EXTEND(SDNode *N);
269     SDValue visitSIGN_EXTEND_INREG(SDNode *N);
270     SDValue visitTRUNCATE(SDNode *N);
271     SDValue visitBITCAST(SDNode *N);
272     SDValue visitBUILD_PAIR(SDNode *N);
273     SDValue visitFADD(SDNode *N);
274     SDValue visitFSUB(SDNode *N);
275     SDValue visitFMUL(SDNode *N);
276     SDValue visitFMA(SDNode *N);
277     SDValue visitFDIV(SDNode *N);
278     SDValue visitFREM(SDNode *N);
279     SDValue visitFSQRT(SDNode *N);
280     SDValue visitFCOPYSIGN(SDNode *N);
281     SDValue visitSINT_TO_FP(SDNode *N);
282     SDValue visitUINT_TO_FP(SDNode *N);
283     SDValue visitFP_TO_SINT(SDNode *N);
284     SDValue visitFP_TO_UINT(SDNode *N);
285     SDValue visitFP_ROUND(SDNode *N);
286     SDValue visitFP_ROUND_INREG(SDNode *N);
287     SDValue visitFP_EXTEND(SDNode *N);
288     SDValue visitFNEG(SDNode *N);
289     SDValue visitFABS(SDNode *N);
290     SDValue visitFCEIL(SDNode *N);
291     SDValue visitFTRUNC(SDNode *N);
292     SDValue visitFFLOOR(SDNode *N);
293     SDValue visitFMINNUM(SDNode *N);
294     SDValue visitFMAXNUM(SDNode *N);
295     SDValue visitBRCOND(SDNode *N);
296     SDValue visitBR_CC(SDNode *N);
297     SDValue visitLOAD(SDNode *N);
298     SDValue visitSTORE(SDNode *N);
299     SDValue visitINSERT_VECTOR_ELT(SDNode *N);
300     SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
301     SDValue visitBUILD_VECTOR(SDNode *N);
302     SDValue visitCONCAT_VECTORS(SDNode *N);
303     SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
304     SDValue visitVECTOR_SHUFFLE(SDNode *N);
305     SDValue visitINSERT_SUBVECTOR(SDNode *N);
306
307     SDValue XformToShuffleWithZero(SDNode *N);
308     SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS);
309
310     SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt);
311
312     bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
313     SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
314     SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2);
315     SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2,
316                              SDValue N3, ISD::CondCode CC,
317                              bool NotExtCompare = false);
318     SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
319                           SDLoc DL, bool foldBooleans = true);
320
321     bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
322                            SDValue &CC) const;
323     bool isOneUseSetCC(SDValue N) const;
324
325     SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
326                                          unsigned HiOp);
327     SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
328     SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
329     SDValue BuildSDIV(SDNode *N);
330     SDValue BuildSDIVPow2(SDNode *N);
331     SDValue BuildUDIV(SDNode *N);
332     SDValue BuildReciprocalEstimate(SDValue Op);
333     SDValue BuildRsqrtEstimate(SDValue Op);
334     SDValue BuildRsqrtNROneConst(SDValue Op, SDValue Est, unsigned Iterations);
335     SDValue BuildRsqrtNRTwoConst(SDValue Op, SDValue Est, unsigned Iterations);
336     SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
337                                bool DemandHighBits = true);
338     SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
339     SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
340                               SDValue InnerPos, SDValue InnerNeg,
341                               unsigned PosOpcode, unsigned NegOpcode,
342                               SDLoc DL);
343     SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL);
344     SDValue ReduceLoadWidth(SDNode *N);
345     SDValue ReduceLoadOpStoreWidth(SDNode *N);
346     SDValue TransformFPLoadStorePair(SDNode *N);
347     SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
348     SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
349
350     SDValue GetDemandedBits(SDValue V, const APInt &Mask);
351
352     /// Walk up chain skipping non-aliasing memory nodes,
353     /// looking for aliasing nodes and adding them to the Aliases vector.
354     void GatherAllAliases(SDNode *N, SDValue OriginalChain,
355                           SmallVectorImpl<SDValue> &Aliases);
356
357     /// Return true if there is any possibility that the two addresses overlap.
358     bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const;
359
360     /// Walk up chain skipping non-aliasing memory nodes, looking for a better
361     /// chain (aliasing node.)
362     SDValue FindBetterChain(SDNode *N, SDValue Chain);
363
364     /// Merge consecutive store operations into a wide store.
365     /// This optimization uses wide integers or vectors when possible.
366     /// \return True if some memory operations were changed.
367     bool MergeConsecutiveStores(StoreSDNode *N);
368
369     /// \brief Try to transform a truncation where C is a constant:
370     ///     (trunc (and X, C)) -> (and (trunc X), (trunc C))
371     ///
372     /// \p N needs to be a truncation and its first operand an AND. Other
373     /// requirements are checked by the function (e.g. that trunc is
374     /// single-use) and if missed an empty SDValue is returned.
375     SDValue distributeTruncateThroughAnd(SDNode *N);
376
377   public:
378     DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
379         : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
380           OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
381       AttributeSet FnAttrs =
382           DAG.getMachineFunction().getFunction()->getAttributes();
383       ForCodeSize =
384           FnAttrs.hasAttribute(AttributeSet::FunctionIndex,
385                                Attribute::OptimizeForSize) ||
386           FnAttrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::MinSize);
387     }
388
389     /// Runs the dag combiner on all nodes in the work list
390     void Run(CombineLevel AtLevel);
391
392     SelectionDAG &getDAG() const { return DAG; }
393
394     /// Returns a type large enough to hold any valid shift amount - before type
395     /// legalization these can be huge.
396     EVT getShiftAmountTy(EVT LHSTy) {
397       assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
398       if (LHSTy.isVector())
399         return LHSTy;
400       return LegalTypes ? TLI.getScalarShiftAmountTy(LHSTy)
401                         : TLI.getPointerTy();
402     }
403
404     /// This method returns true if we are running before type legalization or
405     /// if the specified VT is legal.
406     bool isTypeLegal(const EVT &VT) {
407       if (!LegalTypes) return true;
408       return TLI.isTypeLegal(VT);
409     }
410
411     /// Convenience wrapper around TargetLowering::getSetCCResultType
412     EVT getSetCCResultType(EVT VT) const {
413       return TLI.getSetCCResultType(*DAG.getContext(), VT);
414     }
415   };
416 }
417
418
419 namespace {
420 /// This class is a DAGUpdateListener that removes any deleted
421 /// nodes from the worklist.
422 class WorklistRemover : public SelectionDAG::DAGUpdateListener {
423   DAGCombiner &DC;
424 public:
425   explicit WorklistRemover(DAGCombiner &dc)
426     : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
427
428   void NodeDeleted(SDNode *N, SDNode *E) override {
429     DC.removeFromWorklist(N);
430   }
431 };
432 }
433
434 //===----------------------------------------------------------------------===//
435 //  TargetLowering::DAGCombinerInfo implementation
436 //===----------------------------------------------------------------------===//
437
438 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
439   ((DAGCombiner*)DC)->AddToWorklist(N);
440 }
441
442 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
443   ((DAGCombiner*)DC)->removeFromWorklist(N);
444 }
445
446 SDValue TargetLowering::DAGCombinerInfo::
447 CombineTo(SDNode *N, const std::vector<SDValue> &To, bool AddTo) {
448   return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
449 }
450
451 SDValue TargetLowering::DAGCombinerInfo::
452 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
453   return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
454 }
455
456
457 SDValue TargetLowering::DAGCombinerInfo::
458 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
459   return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
460 }
461
462 void TargetLowering::DAGCombinerInfo::
463 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
464   return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
465 }
466
467 //===----------------------------------------------------------------------===//
468 // Helper Functions
469 //===----------------------------------------------------------------------===//
470
471 void DAGCombiner::deleteAndRecombine(SDNode *N) {
472   removeFromWorklist(N);
473
474   // If the operands of this node are only used by the node, they will now be
475   // dead. Make sure to re-visit them and recursively delete dead nodes.
476   for (const SDValue &Op : N->ops())
477     // For an operand generating multiple values, one of the values may
478     // become dead allowing further simplification (e.g. split index
479     // arithmetic from an indexed load).
480     if (Op->hasOneUse() || Op->getNumValues() > 1)
481       AddToWorklist(Op.getNode());
482
483   DAG.DeleteNode(N);
484 }
485
486 /// Return 1 if we can compute the negated form of the specified expression for
487 /// the same cost as the expression itself, or 2 if we can compute the negated
488 /// form more cheaply than the expression itself.
489 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
490                                const TargetLowering &TLI,
491                                const TargetOptions *Options,
492                                unsigned Depth = 0) {
493   // fneg is removable even if it has multiple uses.
494   if (Op.getOpcode() == ISD::FNEG) return 2;
495
496   // Don't allow anything with multiple uses.
497   if (!Op.hasOneUse()) return 0;
498
499   // Don't recurse exponentially.
500   if (Depth > 6) return 0;
501
502   switch (Op.getOpcode()) {
503   default: return false;
504   case ISD::ConstantFP:
505     // Don't invert constant FP values after legalize.  The negated constant
506     // isn't necessarily legal.
507     return LegalOperations ? 0 : 1;
508   case ISD::FADD:
509     // FIXME: determine better conditions for this xform.
510     if (!Options->UnsafeFPMath) return 0;
511
512     // After operation legalization, it might not be legal to create new FSUBs.
513     if (LegalOperations &&
514         !TLI.isOperationLegalOrCustom(ISD::FSUB,  Op.getValueType()))
515       return 0;
516
517     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
518     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
519                                     Options, Depth + 1))
520       return V;
521     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
522     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
523                               Depth + 1);
524   case ISD::FSUB:
525     // We can't turn -(A-B) into B-A when we honor signed zeros.
526     if (!Options->UnsafeFPMath) return 0;
527
528     // fold (fneg (fsub A, B)) -> (fsub B, A)
529     return 1;
530
531   case ISD::FMUL:
532   case ISD::FDIV:
533     if (Options->HonorSignDependentRoundingFPMath()) return 0;
534
535     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
536     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
537                                     Options, Depth + 1))
538       return V;
539
540     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
541                               Depth + 1);
542
543   case ISD::FP_EXTEND:
544   case ISD::FP_ROUND:
545   case ISD::FSIN:
546     return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
547                               Depth + 1);
548   }
549 }
550
551 /// If isNegatibleForFree returns true, return the newly negated expression.
552 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
553                                     bool LegalOperations, unsigned Depth = 0) {
554   const TargetOptions &Options = DAG.getTarget().Options;
555   // fneg is removable even if it has multiple uses.
556   if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
557
558   // Don't allow anything with multiple uses.
559   assert(Op.hasOneUse() && "Unknown reuse!");
560
561   assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
562   switch (Op.getOpcode()) {
563   default: llvm_unreachable("Unknown code");
564   case ISD::ConstantFP: {
565     APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
566     V.changeSign();
567     return DAG.getConstantFP(V, Op.getValueType());
568   }
569   case ISD::FADD:
570     // FIXME: determine better conditions for this xform.
571     assert(Options.UnsafeFPMath);
572
573     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
574     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
575                            DAG.getTargetLoweringInfo(), &Options, Depth+1))
576       return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
577                          GetNegatedExpression(Op.getOperand(0), DAG,
578                                               LegalOperations, Depth+1),
579                          Op.getOperand(1));
580     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
581     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
582                        GetNegatedExpression(Op.getOperand(1), DAG,
583                                             LegalOperations, Depth+1),
584                        Op.getOperand(0));
585   case ISD::FSUB:
586     // We can't turn -(A-B) into B-A when we honor signed zeros.
587     assert(Options.UnsafeFPMath);
588
589     // fold (fneg (fsub 0, B)) -> B
590     if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
591       if (N0CFP->getValueAPF().isZero())
592         return Op.getOperand(1);
593
594     // fold (fneg (fsub A, B)) -> (fsub B, A)
595     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
596                        Op.getOperand(1), Op.getOperand(0));
597
598   case ISD::FMUL:
599   case ISD::FDIV:
600     assert(!Options.HonorSignDependentRoundingFPMath());
601
602     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
603     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
604                            DAG.getTargetLoweringInfo(), &Options, Depth+1))
605       return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
606                          GetNegatedExpression(Op.getOperand(0), DAG,
607                                               LegalOperations, Depth+1),
608                          Op.getOperand(1));
609
610     // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
611     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
612                        Op.getOperand(0),
613                        GetNegatedExpression(Op.getOperand(1), DAG,
614                                             LegalOperations, Depth+1));
615
616   case ISD::FP_EXTEND:
617   case ISD::FSIN:
618     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
619                        GetNegatedExpression(Op.getOperand(0), DAG,
620                                             LegalOperations, Depth+1));
621   case ISD::FP_ROUND:
622       return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
623                          GetNegatedExpression(Op.getOperand(0), DAG,
624                                               LegalOperations, Depth+1),
625                          Op.getOperand(1));
626   }
627 }
628
629 // Return true if this node is a setcc, or is a select_cc
630 // that selects between the target values used for true and false, making it
631 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
632 // the appropriate nodes based on the type of node we are checking. This
633 // simplifies life a bit for the callers.
634 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
635                                     SDValue &CC) const {
636   if (N.getOpcode() == ISD::SETCC) {
637     LHS = N.getOperand(0);
638     RHS = N.getOperand(1);
639     CC  = N.getOperand(2);
640     return true;
641   }
642
643   if (N.getOpcode() != ISD::SELECT_CC ||
644       !TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
645       !TLI.isConstFalseVal(N.getOperand(3).getNode()))
646     return false;
647
648   if (TLI.getBooleanContents(N.getValueType()) ==
649       TargetLowering::UndefinedBooleanContent)
650     return false;
651
652   LHS = N.getOperand(0);
653   RHS = N.getOperand(1);
654   CC  = N.getOperand(4);
655   return true;
656 }
657
658 /// Return true if this is a SetCC-equivalent operation with only one use.
659 /// If this is true, it allows the users to invert the operation for free when
660 /// it is profitable to do so.
661 bool DAGCombiner::isOneUseSetCC(SDValue N) const {
662   SDValue N0, N1, N2;
663   if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
664     return true;
665   return false;
666 }
667
668 /// Returns true if N is a BUILD_VECTOR node whose
669 /// elements are all the same constant or undefined.
670 static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
671   BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
672   if (!C)
673     return false;
674
675   APInt SplatUndef;
676   unsigned SplatBitSize;
677   bool HasAnyUndefs;
678   EVT EltVT = N->getValueType(0).getVectorElementType();
679   return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
680                              HasAnyUndefs) &&
681           EltVT.getSizeInBits() >= SplatBitSize);
682 }
683
684 // \brief Returns the SDNode if it is a constant BuildVector or constant.
685 static SDNode *isConstantBuildVectorOrConstantInt(SDValue N) {
686   if (isa<ConstantSDNode>(N))
687     return N.getNode();
688   BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N);
689   if (BV && BV->isConstant())
690     return BV;
691   return nullptr;
692 }
693
694 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
695 // int.
696 static ConstantSDNode *isConstOrConstSplat(SDValue N) {
697   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
698     return CN;
699
700   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
701     BitVector UndefElements;
702     ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
703
704     // BuildVectors can truncate their operands. Ignore that case here.
705     // FIXME: We blindly ignore splats which include undef which is overly
706     // pessimistic.
707     if (CN && UndefElements.none() &&
708         CN->getValueType(0) == N.getValueType().getScalarType())
709       return CN;
710   }
711
712   return nullptr;
713 }
714
715 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
716 // float.
717 static ConstantFPSDNode *isConstOrConstSplatFP(SDValue N) {
718   if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
719     return CN;
720
721   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
722     BitVector UndefElements;
723     ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements);
724
725     if (CN && UndefElements.none())
726       return CN;
727   }
728
729   return nullptr;
730 }
731
732 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
733                                     SDValue N0, SDValue N1) {
734   EVT VT = N0.getValueType();
735   if (N0.getOpcode() == Opc) {
736     if (SDNode *L = isConstantBuildVectorOrConstantInt(N0.getOperand(1))) {
737       if (SDNode *R = isConstantBuildVectorOrConstantInt(N1)) {
738         // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
739         SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, L, R);
740         if (!OpNode.getNode())
741           return SDValue();
742         return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
743       }
744       if (N0.hasOneUse()) {
745         // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
746         // use
747         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
748         if (!OpNode.getNode())
749           return SDValue();
750         AddToWorklist(OpNode.getNode());
751         return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
752       }
753     }
754   }
755
756   if (N1.getOpcode() == Opc) {
757     if (SDNode *R = isConstantBuildVectorOrConstantInt(N1.getOperand(1))) {
758       if (SDNode *L = isConstantBuildVectorOrConstantInt(N0)) {
759         // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
760         SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, R, L);
761         if (!OpNode.getNode())
762           return SDValue();
763         return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
764       }
765       if (N1.hasOneUse()) {
766         // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one
767         // use
768         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0);
769         if (!OpNode.getNode())
770           return SDValue();
771         AddToWorklist(OpNode.getNode());
772         return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
773       }
774     }
775   }
776
777   return SDValue();
778 }
779
780 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
781                                bool AddTo) {
782   assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
783   ++NodesCombined;
784   DEBUG(dbgs() << "\nReplacing.1 ";
785         N->dump(&DAG);
786         dbgs() << "\nWith: ";
787         To[0].getNode()->dump(&DAG);
788         dbgs() << " and " << NumTo-1 << " other values\n";
789         for (unsigned i = 0, e = NumTo; i != e; ++i)
790           assert((!To[i].getNode() ||
791                   N->getValueType(i) == To[i].getValueType()) &&
792                  "Cannot combine value to value of different type!"));
793   WorklistRemover DeadNodes(*this);
794   DAG.ReplaceAllUsesWith(N, To);
795   if (AddTo) {
796     // Push the new nodes and any users onto the worklist
797     for (unsigned i = 0, e = NumTo; i != e; ++i) {
798       if (To[i].getNode()) {
799         AddToWorklist(To[i].getNode());
800         AddUsersToWorklist(To[i].getNode());
801       }
802     }
803   }
804
805   // Finally, if the node is now dead, remove it from the graph.  The node
806   // may not be dead if the replacement process recursively simplified to
807   // something else needing this node.
808   if (N->use_empty())
809     deleteAndRecombine(N);
810   return SDValue(N, 0);
811 }
812
813 void DAGCombiner::
814 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
815   // Replace all uses.  If any nodes become isomorphic to other nodes and
816   // are deleted, make sure to remove them from our worklist.
817   WorklistRemover DeadNodes(*this);
818   DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
819
820   // Push the new node and any (possibly new) users onto the worklist.
821   AddToWorklist(TLO.New.getNode());
822   AddUsersToWorklist(TLO.New.getNode());
823
824   // Finally, if the node is now dead, remove it from the graph.  The node
825   // may not be dead if the replacement process recursively simplified to
826   // something else needing this node.
827   if (TLO.Old.getNode()->use_empty())
828     deleteAndRecombine(TLO.Old.getNode());
829 }
830
831 /// Check the specified integer node value to see if it can be simplified or if
832 /// things it uses can be simplified by bit propagation. If so, return true.
833 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
834   TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
835   APInt KnownZero, KnownOne;
836   if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
837     return false;
838
839   // Revisit the node.
840   AddToWorklist(Op.getNode());
841
842   // Replace the old value with the new one.
843   ++NodesCombined;
844   DEBUG(dbgs() << "\nReplacing.2 ";
845         TLO.Old.getNode()->dump(&DAG);
846         dbgs() << "\nWith: ";
847         TLO.New.getNode()->dump(&DAG);
848         dbgs() << '\n');
849
850   CommitTargetLoweringOpt(TLO);
851   return true;
852 }
853
854 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
855   SDLoc dl(Load);
856   EVT VT = Load->getValueType(0);
857   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
858
859   DEBUG(dbgs() << "\nReplacing.9 ";
860         Load->dump(&DAG);
861         dbgs() << "\nWith: ";
862         Trunc.getNode()->dump(&DAG);
863         dbgs() << '\n');
864   WorklistRemover DeadNodes(*this);
865   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
866   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
867   deleteAndRecombine(Load);
868   AddToWorklist(Trunc.getNode());
869 }
870
871 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
872   Replace = false;
873   SDLoc dl(Op);
874   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
875     EVT MemVT = LD->getMemoryVT();
876     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
877       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
878                                                   : ISD::EXTLOAD)
879       : LD->getExtensionType();
880     Replace = true;
881     return DAG.getExtLoad(ExtType, dl, PVT,
882                           LD->getChain(), LD->getBasePtr(),
883                           MemVT, LD->getMemOperand());
884   }
885
886   unsigned Opc = Op.getOpcode();
887   switch (Opc) {
888   default: break;
889   case ISD::AssertSext:
890     return DAG.getNode(ISD::AssertSext, dl, PVT,
891                        SExtPromoteOperand(Op.getOperand(0), PVT),
892                        Op.getOperand(1));
893   case ISD::AssertZext:
894     return DAG.getNode(ISD::AssertZext, dl, PVT,
895                        ZExtPromoteOperand(Op.getOperand(0), PVT),
896                        Op.getOperand(1));
897   case ISD::Constant: {
898     unsigned ExtOpc =
899       Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
900     return DAG.getNode(ExtOpc, dl, PVT, Op);
901   }
902   }
903
904   if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
905     return SDValue();
906   return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
907 }
908
909 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
910   if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
911     return SDValue();
912   EVT OldVT = Op.getValueType();
913   SDLoc dl(Op);
914   bool Replace = false;
915   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
916   if (!NewOp.getNode())
917     return SDValue();
918   AddToWorklist(NewOp.getNode());
919
920   if (Replace)
921     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
922   return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
923                      DAG.getValueType(OldVT));
924 }
925
926 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
927   EVT OldVT = Op.getValueType();
928   SDLoc dl(Op);
929   bool Replace = false;
930   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
931   if (!NewOp.getNode())
932     return SDValue();
933   AddToWorklist(NewOp.getNode());
934
935   if (Replace)
936     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
937   return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
938 }
939
940 /// Promote the specified integer binary operation if the target indicates it is
941 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
942 /// i32 since i16 instructions are longer.
943 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
944   if (!LegalOperations)
945     return SDValue();
946
947   EVT VT = Op.getValueType();
948   if (VT.isVector() || !VT.isInteger())
949     return SDValue();
950
951   // If operation type is 'undesirable', e.g. i16 on x86, consider
952   // promoting it.
953   unsigned Opc = Op.getOpcode();
954   if (TLI.isTypeDesirableForOp(Opc, VT))
955     return SDValue();
956
957   EVT PVT = VT;
958   // Consult target whether it is a good idea to promote this operation and
959   // what's the right type to promote it to.
960   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
961     assert(PVT != VT && "Don't know what type to promote to!");
962
963     bool Replace0 = false;
964     SDValue N0 = Op.getOperand(0);
965     SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
966     if (!NN0.getNode())
967       return SDValue();
968
969     bool Replace1 = false;
970     SDValue N1 = Op.getOperand(1);
971     SDValue NN1;
972     if (N0 == N1)
973       NN1 = NN0;
974     else {
975       NN1 = PromoteOperand(N1, PVT, Replace1);
976       if (!NN1.getNode())
977         return SDValue();
978     }
979
980     AddToWorklist(NN0.getNode());
981     if (NN1.getNode())
982       AddToWorklist(NN1.getNode());
983
984     if (Replace0)
985       ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
986     if (Replace1)
987       ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
988
989     DEBUG(dbgs() << "\nPromoting ";
990           Op.getNode()->dump(&DAG));
991     SDLoc dl(Op);
992     return DAG.getNode(ISD::TRUNCATE, dl, VT,
993                        DAG.getNode(Opc, dl, PVT, NN0, NN1));
994   }
995   return SDValue();
996 }
997
998 /// Promote the specified integer shift operation if the target indicates it is
999 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1000 /// i32 since i16 instructions are longer.
1001 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
1002   if (!LegalOperations)
1003     return SDValue();
1004
1005   EVT VT = Op.getValueType();
1006   if (VT.isVector() || !VT.isInteger())
1007     return SDValue();
1008
1009   // If operation type is 'undesirable', e.g. i16 on x86, consider
1010   // promoting it.
1011   unsigned Opc = Op.getOpcode();
1012   if (TLI.isTypeDesirableForOp(Opc, VT))
1013     return SDValue();
1014
1015   EVT PVT = VT;
1016   // Consult target whether it is a good idea to promote this operation and
1017   // what's the right type to promote it to.
1018   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1019     assert(PVT != VT && "Don't know what type to promote to!");
1020
1021     bool Replace = false;
1022     SDValue N0 = Op.getOperand(0);
1023     if (Opc == ISD::SRA)
1024       N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
1025     else if (Opc == ISD::SRL)
1026       N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
1027     else
1028       N0 = PromoteOperand(N0, PVT, Replace);
1029     if (!N0.getNode())
1030       return SDValue();
1031
1032     AddToWorklist(N0.getNode());
1033     if (Replace)
1034       ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
1035
1036     DEBUG(dbgs() << "\nPromoting ";
1037           Op.getNode()->dump(&DAG));
1038     SDLoc dl(Op);
1039     return DAG.getNode(ISD::TRUNCATE, dl, VT,
1040                        DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
1041   }
1042   return SDValue();
1043 }
1044
1045 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
1046   if (!LegalOperations)
1047     return SDValue();
1048
1049   EVT VT = Op.getValueType();
1050   if (VT.isVector() || !VT.isInteger())
1051     return SDValue();
1052
1053   // If operation type is 'undesirable', e.g. i16 on x86, consider
1054   // promoting it.
1055   unsigned Opc = Op.getOpcode();
1056   if (TLI.isTypeDesirableForOp(Opc, VT))
1057     return SDValue();
1058
1059   EVT PVT = VT;
1060   // Consult target whether it is a good idea to promote this operation and
1061   // what's the right type to promote it to.
1062   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1063     assert(PVT != VT && "Don't know what type to promote to!");
1064     // fold (aext (aext x)) -> (aext x)
1065     // fold (aext (zext x)) -> (zext x)
1066     // fold (aext (sext x)) -> (sext x)
1067     DEBUG(dbgs() << "\nPromoting ";
1068           Op.getNode()->dump(&DAG));
1069     return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1070   }
1071   return SDValue();
1072 }
1073
1074 bool DAGCombiner::PromoteLoad(SDValue Op) {
1075   if (!LegalOperations)
1076     return false;
1077
1078   EVT VT = Op.getValueType();
1079   if (VT.isVector() || !VT.isInteger())
1080     return false;
1081
1082   // If operation type is 'undesirable', e.g. i16 on x86, consider
1083   // promoting it.
1084   unsigned Opc = Op.getOpcode();
1085   if (TLI.isTypeDesirableForOp(Opc, VT))
1086     return false;
1087
1088   EVT PVT = VT;
1089   // Consult target whether it is a good idea to promote this operation and
1090   // what's the right type to promote it to.
1091   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1092     assert(PVT != VT && "Don't know what type to promote to!");
1093
1094     SDLoc dl(Op);
1095     SDNode *N = Op.getNode();
1096     LoadSDNode *LD = cast<LoadSDNode>(N);
1097     EVT MemVT = LD->getMemoryVT();
1098     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1099       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
1100                                                   : ISD::EXTLOAD)
1101       : LD->getExtensionType();
1102     SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
1103                                    LD->getChain(), LD->getBasePtr(),
1104                                    MemVT, LD->getMemOperand());
1105     SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
1106
1107     DEBUG(dbgs() << "\nPromoting ";
1108           N->dump(&DAG);
1109           dbgs() << "\nTo: ";
1110           Result.getNode()->dump(&DAG);
1111           dbgs() << '\n');
1112     WorklistRemover DeadNodes(*this);
1113     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1114     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1115     deleteAndRecombine(N);
1116     AddToWorklist(Result.getNode());
1117     return true;
1118   }
1119   return false;
1120 }
1121
1122 /// \brief Recursively delete a node which has no uses and any operands for
1123 /// which it is the only use.
1124 ///
1125 /// Note that this both deletes the nodes and removes them from the worklist.
1126 /// It also adds any nodes who have had a user deleted to the worklist as they
1127 /// may now have only one use and subject to other combines.
1128 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) {
1129   if (!N->use_empty())
1130     return false;
1131
1132   SmallSetVector<SDNode *, 16> Nodes;
1133   Nodes.insert(N);
1134   do {
1135     N = Nodes.pop_back_val();
1136     if (!N)
1137       continue;
1138
1139     if (N->use_empty()) {
1140       for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1141         Nodes.insert(N->getOperand(i).getNode());
1142
1143       removeFromWorklist(N);
1144       DAG.DeleteNode(N);
1145     } else {
1146       AddToWorklist(N);
1147     }
1148   } while (!Nodes.empty());
1149   return true;
1150 }
1151
1152 //===----------------------------------------------------------------------===//
1153 //  Main DAG Combiner implementation
1154 //===----------------------------------------------------------------------===//
1155
1156 void DAGCombiner::Run(CombineLevel AtLevel) {
1157   // set the instance variables, so that the various visit routines may use it.
1158   Level = AtLevel;
1159   LegalOperations = Level >= AfterLegalizeVectorOps;
1160   LegalTypes = Level >= AfterLegalizeTypes;
1161
1162   // Early exit if this basic block is in an optnone function.
1163   AttributeSet FnAttrs =
1164     DAG.getMachineFunction().getFunction()->getAttributes();
1165   if (FnAttrs.hasAttribute(AttributeSet::FunctionIndex,
1166                            Attribute::OptimizeNone))
1167     return;
1168
1169   // Add all the dag nodes to the worklist.
1170   for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
1171        E = DAG.allnodes_end(); I != E; ++I)
1172     AddToWorklist(I);
1173
1174   // Create a dummy node (which is not added to allnodes), that adds a reference
1175   // to the root node, preventing it from being deleted, and tracking any
1176   // changes of the root.
1177   HandleSDNode Dummy(DAG.getRoot());
1178
1179   // while the worklist isn't empty, find a node and
1180   // try and combine it.
1181   while (!WorklistMap.empty()) {
1182     SDNode *N;
1183     // The Worklist holds the SDNodes in order, but it may contain null entries.
1184     do {
1185       N = Worklist.pop_back_val();
1186     } while (!N);
1187
1188     bool GoodWorklistEntry = WorklistMap.erase(N);
1189     (void)GoodWorklistEntry;
1190     assert(GoodWorklistEntry &&
1191            "Found a worklist entry without a corresponding map entry!");
1192
1193     // If N has no uses, it is dead.  Make sure to revisit all N's operands once
1194     // N is deleted from the DAG, since they too may now be dead or may have a
1195     // reduced number of uses, allowing other xforms.
1196     if (recursivelyDeleteUnusedNodes(N))
1197       continue;
1198
1199     WorklistRemover DeadNodes(*this);
1200
1201     // If this combine is running after legalizing the DAG, re-legalize any
1202     // nodes pulled off the worklist.
1203     if (Level == AfterLegalizeDAG) {
1204       SmallSetVector<SDNode *, 16> UpdatedNodes;
1205       bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes);
1206
1207       for (SDNode *LN : UpdatedNodes) {
1208         AddToWorklist(LN);
1209         AddUsersToWorklist(LN);
1210       }
1211       if (!NIsValid)
1212         continue;
1213     }
1214
1215     DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG));
1216
1217     // Add any operands of the new node which have not yet been combined to the
1218     // worklist as well. Because the worklist uniques things already, this
1219     // won't repeatedly process the same operand.
1220     CombinedNodes.insert(N);
1221     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1222       if (!CombinedNodes.count(N->getOperand(i).getNode()))
1223         AddToWorklist(N->getOperand(i).getNode());
1224
1225     SDValue RV = combine(N);
1226
1227     if (!RV.getNode())
1228       continue;
1229
1230     ++NodesCombined;
1231
1232     // If we get back the same node we passed in, rather than a new node or
1233     // zero, we know that the node must have defined multiple values and
1234     // CombineTo was used.  Since CombineTo takes care of the worklist
1235     // mechanics for us, we have no work to do in this case.
1236     if (RV.getNode() == N)
1237       continue;
1238
1239     assert(N->getOpcode() != ISD::DELETED_NODE &&
1240            RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1241            "Node was deleted but visit returned new node!");
1242
1243     DEBUG(dbgs() << " ... into: ";
1244           RV.getNode()->dump(&DAG));
1245
1246     // Transfer debug value.
1247     DAG.TransferDbgValues(SDValue(N, 0), RV);
1248     if (N->getNumValues() == RV.getNode()->getNumValues())
1249       DAG.ReplaceAllUsesWith(N, RV.getNode());
1250     else {
1251       assert(N->getValueType(0) == RV.getValueType() &&
1252              N->getNumValues() == 1 && "Type mismatch");
1253       SDValue OpV = RV;
1254       DAG.ReplaceAllUsesWith(N, &OpV);
1255     }
1256
1257     // Push the new node and any users onto the worklist
1258     AddToWorklist(RV.getNode());
1259     AddUsersToWorklist(RV.getNode());
1260
1261     // Finally, if the node is now dead, remove it from the graph.  The node
1262     // may not be dead if the replacement process recursively simplified to
1263     // something else needing this node. This will also take care of adding any
1264     // operands which have lost a user to the worklist.
1265     recursivelyDeleteUnusedNodes(N);
1266   }
1267
1268   // If the root changed (e.g. it was a dead load, update the root).
1269   DAG.setRoot(Dummy.getValue());
1270   DAG.RemoveDeadNodes();
1271 }
1272
1273 SDValue DAGCombiner::visit(SDNode *N) {
1274   switch (N->getOpcode()) {
1275   default: break;
1276   case ISD::TokenFactor:        return visitTokenFactor(N);
1277   case ISD::MERGE_VALUES:       return visitMERGE_VALUES(N);
1278   case ISD::ADD:                return visitADD(N);
1279   case ISD::SUB:                return visitSUB(N);
1280   case ISD::ADDC:               return visitADDC(N);
1281   case ISD::SUBC:               return visitSUBC(N);
1282   case ISD::ADDE:               return visitADDE(N);
1283   case ISD::SUBE:               return visitSUBE(N);
1284   case ISD::MUL:                return visitMUL(N);
1285   case ISD::SDIV:               return visitSDIV(N);
1286   case ISD::UDIV:               return visitUDIV(N);
1287   case ISD::SREM:               return visitSREM(N);
1288   case ISD::UREM:               return visitUREM(N);
1289   case ISD::MULHU:              return visitMULHU(N);
1290   case ISD::MULHS:              return visitMULHS(N);
1291   case ISD::SMUL_LOHI:          return visitSMUL_LOHI(N);
1292   case ISD::UMUL_LOHI:          return visitUMUL_LOHI(N);
1293   case ISD::SMULO:              return visitSMULO(N);
1294   case ISD::UMULO:              return visitUMULO(N);
1295   case ISD::SDIVREM:            return visitSDIVREM(N);
1296   case ISD::UDIVREM:            return visitUDIVREM(N);
1297   case ISD::AND:                return visitAND(N);
1298   case ISD::OR:                 return visitOR(N);
1299   case ISD::XOR:                return visitXOR(N);
1300   case ISD::SHL:                return visitSHL(N);
1301   case ISD::SRA:                return visitSRA(N);
1302   case ISD::SRL:                return visitSRL(N);
1303   case ISD::ROTR:
1304   case ISD::ROTL:               return visitRotate(N);
1305   case ISD::CTLZ:               return visitCTLZ(N);
1306   case ISD::CTLZ_ZERO_UNDEF:    return visitCTLZ_ZERO_UNDEF(N);
1307   case ISD::CTTZ:               return visitCTTZ(N);
1308   case ISD::CTTZ_ZERO_UNDEF:    return visitCTTZ_ZERO_UNDEF(N);
1309   case ISD::CTPOP:              return visitCTPOP(N);
1310   case ISD::SELECT:             return visitSELECT(N);
1311   case ISD::VSELECT:            return visitVSELECT(N);
1312   case ISD::SELECT_CC:          return visitSELECT_CC(N);
1313   case ISD::SETCC:              return visitSETCC(N);
1314   case ISD::SIGN_EXTEND:        return visitSIGN_EXTEND(N);
1315   case ISD::ZERO_EXTEND:        return visitZERO_EXTEND(N);
1316   case ISD::ANY_EXTEND:         return visitANY_EXTEND(N);
1317   case ISD::SIGN_EXTEND_INREG:  return visitSIGN_EXTEND_INREG(N);
1318   case ISD::TRUNCATE:           return visitTRUNCATE(N);
1319   case ISD::BITCAST:            return visitBITCAST(N);
1320   case ISD::BUILD_PAIR:         return visitBUILD_PAIR(N);
1321   case ISD::FADD:               return visitFADD(N);
1322   case ISD::FSUB:               return visitFSUB(N);
1323   case ISD::FMUL:               return visitFMUL(N);
1324   case ISD::FMA:                return visitFMA(N);
1325   case ISD::FDIV:               return visitFDIV(N);
1326   case ISD::FREM:               return visitFREM(N);
1327   case ISD::FSQRT:              return visitFSQRT(N);
1328   case ISD::FCOPYSIGN:          return visitFCOPYSIGN(N);
1329   case ISD::SINT_TO_FP:         return visitSINT_TO_FP(N);
1330   case ISD::UINT_TO_FP:         return visitUINT_TO_FP(N);
1331   case ISD::FP_TO_SINT:         return visitFP_TO_SINT(N);
1332   case ISD::FP_TO_UINT:         return visitFP_TO_UINT(N);
1333   case ISD::FP_ROUND:           return visitFP_ROUND(N);
1334   case ISD::FP_ROUND_INREG:     return visitFP_ROUND_INREG(N);
1335   case ISD::FP_EXTEND:          return visitFP_EXTEND(N);
1336   case ISD::FNEG:               return visitFNEG(N);
1337   case ISD::FABS:               return visitFABS(N);
1338   case ISD::FFLOOR:             return visitFFLOOR(N);
1339   case ISD::FMINNUM:            return visitFMINNUM(N);
1340   case ISD::FMAXNUM:            return visitFMAXNUM(N);
1341   case ISD::FCEIL:              return visitFCEIL(N);
1342   case ISD::FTRUNC:             return visitFTRUNC(N);
1343   case ISD::BRCOND:             return visitBRCOND(N);
1344   case ISD::BR_CC:              return visitBR_CC(N);
1345   case ISD::LOAD:               return visitLOAD(N);
1346   case ISD::STORE:              return visitSTORE(N);
1347   case ISD::INSERT_VECTOR_ELT:  return visitINSERT_VECTOR_ELT(N);
1348   case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1349   case ISD::BUILD_VECTOR:       return visitBUILD_VECTOR(N);
1350   case ISD::CONCAT_VECTORS:     return visitCONCAT_VECTORS(N);
1351   case ISD::EXTRACT_SUBVECTOR:  return visitEXTRACT_SUBVECTOR(N);
1352   case ISD::VECTOR_SHUFFLE:     return visitVECTOR_SHUFFLE(N);
1353   case ISD::INSERT_SUBVECTOR:   return visitINSERT_SUBVECTOR(N);
1354   }
1355   return SDValue();
1356 }
1357
1358 SDValue DAGCombiner::combine(SDNode *N) {
1359   SDValue RV = visit(N);
1360
1361   // If nothing happened, try a target-specific DAG combine.
1362   if (!RV.getNode()) {
1363     assert(N->getOpcode() != ISD::DELETED_NODE &&
1364            "Node was deleted but visit returned NULL!");
1365
1366     if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1367         TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1368
1369       // Expose the DAG combiner to the target combiner impls.
1370       TargetLowering::DAGCombinerInfo
1371         DagCombineInfo(DAG, Level, false, this);
1372
1373       RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1374     }
1375   }
1376
1377   // If nothing happened still, try promoting the operation.
1378   if (!RV.getNode()) {
1379     switch (N->getOpcode()) {
1380     default: break;
1381     case ISD::ADD:
1382     case ISD::SUB:
1383     case ISD::MUL:
1384     case ISD::AND:
1385     case ISD::OR:
1386     case ISD::XOR:
1387       RV = PromoteIntBinOp(SDValue(N, 0));
1388       break;
1389     case ISD::SHL:
1390     case ISD::SRA:
1391     case ISD::SRL:
1392       RV = PromoteIntShiftOp(SDValue(N, 0));
1393       break;
1394     case ISD::SIGN_EXTEND:
1395     case ISD::ZERO_EXTEND:
1396     case ISD::ANY_EXTEND:
1397       RV = PromoteExtend(SDValue(N, 0));
1398       break;
1399     case ISD::LOAD:
1400       if (PromoteLoad(SDValue(N, 0)))
1401         RV = SDValue(N, 0);
1402       break;
1403     }
1404   }
1405
1406   // If N is a commutative binary node, try commuting it to enable more
1407   // sdisel CSE.
1408   if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1409       N->getNumValues() == 1) {
1410     SDValue N0 = N->getOperand(0);
1411     SDValue N1 = N->getOperand(1);
1412
1413     // Constant operands are canonicalized to RHS.
1414     if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1415       SDValue Ops[] = {N1, N0};
1416       SDNode *CSENode;
1417       if (const BinaryWithFlagsSDNode *BinNode =
1418               dyn_cast<BinaryWithFlagsSDNode>(N)) {
1419         CSENode = DAG.getNodeIfExists(
1420             N->getOpcode(), N->getVTList(), Ops, BinNode->hasNoUnsignedWrap(),
1421             BinNode->hasNoSignedWrap(), BinNode->isExact());
1422       } else {
1423         CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops);
1424       }
1425       if (CSENode)
1426         return SDValue(CSENode, 0);
1427     }
1428   }
1429
1430   return RV;
1431 }
1432
1433 /// Given a node, return its input chain if it has one, otherwise return a null
1434 /// sd operand.
1435 static SDValue getInputChainForNode(SDNode *N) {
1436   if (unsigned NumOps = N->getNumOperands()) {
1437     if (N->getOperand(0).getValueType() == MVT::Other)
1438       return N->getOperand(0);
1439     if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1440       return N->getOperand(NumOps-1);
1441     for (unsigned i = 1; i < NumOps-1; ++i)
1442       if (N->getOperand(i).getValueType() == MVT::Other)
1443         return N->getOperand(i);
1444   }
1445   return SDValue();
1446 }
1447
1448 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1449   // If N has two operands, where one has an input chain equal to the other,
1450   // the 'other' chain is redundant.
1451   if (N->getNumOperands() == 2) {
1452     if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1453       return N->getOperand(0);
1454     if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1455       return N->getOperand(1);
1456   }
1457
1458   SmallVector<SDNode *, 8> TFs;     // List of token factors to visit.
1459   SmallVector<SDValue, 8> Ops;    // Ops for replacing token factor.
1460   SmallPtrSet<SDNode*, 16> SeenOps;
1461   bool Changed = false;             // If we should replace this token factor.
1462
1463   // Start out with this token factor.
1464   TFs.push_back(N);
1465
1466   // Iterate through token factors.  The TFs grows when new token factors are
1467   // encountered.
1468   for (unsigned i = 0; i < TFs.size(); ++i) {
1469     SDNode *TF = TFs[i];
1470
1471     // Check each of the operands.
1472     for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
1473       SDValue Op = TF->getOperand(i);
1474
1475       switch (Op.getOpcode()) {
1476       case ISD::EntryToken:
1477         // Entry tokens don't need to be added to the list. They are
1478         // rededundant.
1479         Changed = true;
1480         break;
1481
1482       case ISD::TokenFactor:
1483         if (Op.hasOneUse() &&
1484             std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1485           // Queue up for processing.
1486           TFs.push_back(Op.getNode());
1487           // Clean up in case the token factor is removed.
1488           AddToWorklist(Op.getNode());
1489           Changed = true;
1490           break;
1491         }
1492         // Fall thru
1493
1494       default:
1495         // Only add if it isn't already in the list.
1496         if (SeenOps.insert(Op.getNode()).second)
1497           Ops.push_back(Op);
1498         else
1499           Changed = true;
1500         break;
1501       }
1502     }
1503   }
1504
1505   SDValue Result;
1506
1507   // If we've change things around then replace token factor.
1508   if (Changed) {
1509     if (Ops.empty()) {
1510       // The entry token is the only possible outcome.
1511       Result = DAG.getEntryNode();
1512     } else {
1513       // New and improved token factor.
1514       Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
1515     }
1516
1517     // Don't add users to work list.
1518     return CombineTo(N, Result, false);
1519   }
1520
1521   return Result;
1522 }
1523
1524 /// MERGE_VALUES can always be eliminated.
1525 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1526   WorklistRemover DeadNodes(*this);
1527   // Replacing results may cause a different MERGE_VALUES to suddenly
1528   // be CSE'd with N, and carry its uses with it. Iterate until no
1529   // uses remain, to ensure that the node can be safely deleted.
1530   // First add the users of this node to the work list so that they
1531   // can be tried again once they have new operands.
1532   AddUsersToWorklist(N);
1533   do {
1534     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1535       DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1536   } while (!N->use_empty());
1537   deleteAndRecombine(N);
1538   return SDValue(N, 0);   // Return N so it doesn't get rechecked!
1539 }
1540
1541 SDValue DAGCombiner::visitADD(SDNode *N) {
1542   SDValue N0 = N->getOperand(0);
1543   SDValue N1 = N->getOperand(1);
1544   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1545   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1546   EVT VT = N0.getValueType();
1547
1548   // fold vector ops
1549   if (VT.isVector()) {
1550     SDValue FoldedVOp = SimplifyVBinOp(N);
1551     if (FoldedVOp.getNode()) return FoldedVOp;
1552
1553     // fold (add x, 0) -> x, vector edition
1554     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1555       return N0;
1556     if (ISD::isBuildVectorAllZeros(N0.getNode()))
1557       return N1;
1558   }
1559
1560   // fold (add x, undef) -> undef
1561   if (N0.getOpcode() == ISD::UNDEF)
1562     return N0;
1563   if (N1.getOpcode() == ISD::UNDEF)
1564     return N1;
1565   // fold (add c1, c2) -> c1+c2
1566   if (N0C && N1C)
1567     return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C);
1568   // canonicalize constant to RHS
1569   if (N0C && !N1C)
1570     return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
1571   // fold (add x, 0) -> x
1572   if (N1C && N1C->isNullValue())
1573     return N0;
1574   // fold (add Sym, c) -> Sym+c
1575   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1576     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1577         GA->getOpcode() == ISD::GlobalAddress)
1578       return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1579                                   GA->getOffset() +
1580                                     (uint64_t)N1C->getSExtValue());
1581   // fold ((c1-A)+c2) -> (c1+c2)-A
1582   if (N1C && N0.getOpcode() == ISD::SUB)
1583     if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
1584       return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1585                          DAG.getConstant(N1C->getAPIntValue()+
1586                                          N0C->getAPIntValue(), VT),
1587                          N0.getOperand(1));
1588   // reassociate add
1589   SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1);
1590   if (RADD.getNode())
1591     return RADD;
1592   // fold ((0-A) + B) -> B-A
1593   if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
1594       cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
1595     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
1596   // fold (A + (0-B)) -> A-B
1597   if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1598       cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
1599     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
1600   // fold (A+(B-A)) -> B
1601   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1602     return N1.getOperand(0);
1603   // fold ((B-A)+A) -> B
1604   if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1605     return N0.getOperand(0);
1606   // fold (A+(B-(A+C))) to (B-C)
1607   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1608       N0 == N1.getOperand(1).getOperand(0))
1609     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1610                        N1.getOperand(1).getOperand(1));
1611   // fold (A+(B-(C+A))) to (B-C)
1612   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1613       N0 == N1.getOperand(1).getOperand(1))
1614     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1615                        N1.getOperand(1).getOperand(0));
1616   // fold (A+((B-A)+or-C)) to (B+or-C)
1617   if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1618       N1.getOperand(0).getOpcode() == ISD::SUB &&
1619       N0 == N1.getOperand(0).getOperand(1))
1620     return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
1621                        N1.getOperand(0).getOperand(0), N1.getOperand(1));
1622
1623   // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1624   if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1625     SDValue N00 = N0.getOperand(0);
1626     SDValue N01 = N0.getOperand(1);
1627     SDValue N10 = N1.getOperand(0);
1628     SDValue N11 = N1.getOperand(1);
1629
1630     if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1631       return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1632                          DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1633                          DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1634   }
1635
1636   if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1637     return SDValue(N, 0);
1638
1639   // fold (a+b) -> (a|b) iff a and b share no bits.
1640   if (VT.isInteger() && !VT.isVector()) {
1641     APInt LHSZero, LHSOne;
1642     APInt RHSZero, RHSOne;
1643     DAG.computeKnownBits(N0, LHSZero, LHSOne);
1644
1645     if (LHSZero.getBoolValue()) {
1646       DAG.computeKnownBits(N1, RHSZero, RHSOne);
1647
1648       // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1649       // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1650       if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){
1651         if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT))
1652           return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1653       }
1654     }
1655   }
1656
1657   // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1658   if (N1.getOpcode() == ISD::SHL &&
1659       N1.getOperand(0).getOpcode() == ISD::SUB)
1660     if (ConstantSDNode *C =
1661           dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
1662       if (C->getAPIntValue() == 0)
1663         return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1664                            DAG.getNode(ISD::SHL, SDLoc(N), VT,
1665                                        N1.getOperand(0).getOperand(1),
1666                                        N1.getOperand(1)));
1667   if (N0.getOpcode() == ISD::SHL &&
1668       N0.getOperand(0).getOpcode() == ISD::SUB)
1669     if (ConstantSDNode *C =
1670           dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
1671       if (C->getAPIntValue() == 0)
1672         return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1673                            DAG.getNode(ISD::SHL, SDLoc(N), VT,
1674                                        N0.getOperand(0).getOperand(1),
1675                                        N0.getOperand(1)));
1676
1677   if (N1.getOpcode() == ISD::AND) {
1678     SDValue AndOp0 = N1.getOperand(0);
1679     ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1));
1680     unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1681     unsigned DestBits = VT.getScalarType().getSizeInBits();
1682
1683     // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1684     // and similar xforms where the inner op is either ~0 or 0.
1685     if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) {
1686       SDLoc DL(N);
1687       return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1688     }
1689   }
1690
1691   // add (sext i1), X -> sub X, (zext i1)
1692   if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1693       N0.getOperand(0).getValueType() == MVT::i1 &&
1694       !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1695     SDLoc DL(N);
1696     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1697     return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1698   }
1699
1700   // add X, (sextinreg Y i1) -> sub X, (and Y 1)
1701   if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1702     VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1703     if (TN->getVT() == MVT::i1) {
1704       SDLoc DL(N);
1705       SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1706                                  DAG.getConstant(1, VT));
1707       return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt);
1708     }
1709   }
1710
1711   return SDValue();
1712 }
1713
1714 SDValue DAGCombiner::visitADDC(SDNode *N) {
1715   SDValue N0 = N->getOperand(0);
1716   SDValue N1 = N->getOperand(1);
1717   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1718   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1719   EVT VT = N0.getValueType();
1720
1721   // If the flag result is dead, turn this into an ADD.
1722   if (!N->hasAnyUseOfValue(1))
1723     return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1724                      DAG.getNode(ISD::CARRY_FALSE,
1725                                  SDLoc(N), MVT::Glue));
1726
1727   // canonicalize constant to RHS.
1728   if (N0C && !N1C)
1729     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1730
1731   // fold (addc x, 0) -> x + no carry out
1732   if (N1C && N1C->isNullValue())
1733     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1734                                         SDLoc(N), MVT::Glue));
1735
1736   // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1737   APInt LHSZero, LHSOne;
1738   APInt RHSZero, RHSOne;
1739   DAG.computeKnownBits(N0, LHSZero, LHSOne);
1740
1741   if (LHSZero.getBoolValue()) {
1742     DAG.computeKnownBits(N1, RHSZero, RHSOne);
1743
1744     // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1745     // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1746     if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1747       return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1748                        DAG.getNode(ISD::CARRY_FALSE,
1749                                    SDLoc(N), MVT::Glue));
1750   }
1751
1752   return SDValue();
1753 }
1754
1755 SDValue DAGCombiner::visitADDE(SDNode *N) {
1756   SDValue N0 = N->getOperand(0);
1757   SDValue N1 = N->getOperand(1);
1758   SDValue CarryIn = N->getOperand(2);
1759   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1760   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1761
1762   // canonicalize constant to RHS
1763   if (N0C && !N1C)
1764     return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1765                        N1, N0, CarryIn);
1766
1767   // fold (adde x, y, false) -> (addc x, y)
1768   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1769     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1770
1771   return SDValue();
1772 }
1773
1774 // Since it may not be valid to emit a fold to zero for vector initializers
1775 // check if we can before folding.
1776 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
1777                              SelectionDAG &DAG,
1778                              bool LegalOperations, bool LegalTypes) {
1779   if (!VT.isVector())
1780     return DAG.getConstant(0, VT);
1781   if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1782     return DAG.getConstant(0, VT);
1783   return SDValue();
1784 }
1785
1786 SDValue DAGCombiner::visitSUB(SDNode *N) {
1787   SDValue N0 = N->getOperand(0);
1788   SDValue N1 = N->getOperand(1);
1789   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1790   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1791   ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr :
1792     dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1793   EVT VT = N0.getValueType();
1794
1795   // fold vector ops
1796   if (VT.isVector()) {
1797     SDValue FoldedVOp = SimplifyVBinOp(N);
1798     if (FoldedVOp.getNode()) return FoldedVOp;
1799
1800     // fold (sub x, 0) -> x, vector edition
1801     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1802       return N0;
1803   }
1804
1805   // fold (sub x, x) -> 0
1806   // FIXME: Refactor this and xor and other similar operations together.
1807   if (N0 == N1)
1808     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
1809   // fold (sub c1, c2) -> c1-c2
1810   if (N0C && N1C)
1811     return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C);
1812   // fold (sub x, c) -> (add x, -c)
1813   if (N1C)
1814     return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0,
1815                        DAG.getConstant(-N1C->getAPIntValue(), VT));
1816   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1817   if (N0C && N0C->isAllOnesValue())
1818     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
1819   // fold A-(A-B) -> B
1820   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1821     return N1.getOperand(1);
1822   // fold (A+B)-A -> B
1823   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1824     return N0.getOperand(1);
1825   // fold (A+B)-B -> A
1826   if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1827     return N0.getOperand(0);
1828   // fold C2-(A+C1) -> (C2-C1)-A
1829   if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1830     SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1831                                    VT);
1832     return DAG.getNode(ISD::SUB, SDLoc(N), VT, NewC,
1833                        N1.getOperand(0));
1834   }
1835   // fold ((A+(B+or-C))-B) -> A+or-C
1836   if (N0.getOpcode() == ISD::ADD &&
1837       (N0.getOperand(1).getOpcode() == ISD::SUB ||
1838        N0.getOperand(1).getOpcode() == ISD::ADD) &&
1839       N0.getOperand(1).getOperand(0) == N1)
1840     return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
1841                        N0.getOperand(0), N0.getOperand(1).getOperand(1));
1842   // fold ((A+(C+B))-B) -> A+C
1843   if (N0.getOpcode() == ISD::ADD &&
1844       N0.getOperand(1).getOpcode() == ISD::ADD &&
1845       N0.getOperand(1).getOperand(1) == N1)
1846     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1847                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1848   // fold ((A-(B-C))-C) -> A-B
1849   if (N0.getOpcode() == ISD::SUB &&
1850       N0.getOperand(1).getOpcode() == ISD::SUB &&
1851       N0.getOperand(1).getOperand(1) == N1)
1852     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1853                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1854
1855   // If either operand of a sub is undef, the result is undef
1856   if (N0.getOpcode() == ISD::UNDEF)
1857     return N0;
1858   if (N1.getOpcode() == ISD::UNDEF)
1859     return N1;
1860
1861   // If the relocation model supports it, consider symbol offsets.
1862   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1863     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1864       // fold (sub Sym, c) -> Sym-c
1865       if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1866         return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1867                                     GA->getOffset() -
1868                                       (uint64_t)N1C->getSExtValue());
1869       // fold (sub Sym+c1, Sym+c2) -> c1-c2
1870       if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1871         if (GA->getGlobal() == GB->getGlobal())
1872           return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1873                                  VT);
1874     }
1875
1876   // sub X, (sextinreg Y i1) -> add X, (and Y 1)
1877   if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1878     VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1879     if (TN->getVT() == MVT::i1) {
1880       SDLoc DL(N);
1881       SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1882                                  DAG.getConstant(1, VT));
1883       return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt);
1884     }
1885   }
1886
1887   return SDValue();
1888 }
1889
1890 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1891   SDValue N0 = N->getOperand(0);
1892   SDValue N1 = N->getOperand(1);
1893   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1894   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1895   EVT VT = N0.getValueType();
1896
1897   // If the flag result is dead, turn this into an SUB.
1898   if (!N->hasAnyUseOfValue(1))
1899     return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1900                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1901                                  MVT::Glue));
1902
1903   // fold (subc x, x) -> 0 + no borrow
1904   if (N0 == N1)
1905     return CombineTo(N, DAG.getConstant(0, VT),
1906                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1907                                  MVT::Glue));
1908
1909   // fold (subc x, 0) -> x + no borrow
1910   if (N1C && N1C->isNullValue())
1911     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1912                                         MVT::Glue));
1913
1914   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1915   if (N0C && N0C->isAllOnesValue())
1916     return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
1917                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1918                                  MVT::Glue));
1919
1920   return SDValue();
1921 }
1922
1923 SDValue DAGCombiner::visitSUBE(SDNode *N) {
1924   SDValue N0 = N->getOperand(0);
1925   SDValue N1 = N->getOperand(1);
1926   SDValue CarryIn = N->getOperand(2);
1927
1928   // fold (sube x, y, false) -> (subc x, y)
1929   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1930     return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
1931
1932   return SDValue();
1933 }
1934
1935 SDValue DAGCombiner::visitMUL(SDNode *N) {
1936   SDValue N0 = N->getOperand(0);
1937   SDValue N1 = N->getOperand(1);
1938   EVT VT = N0.getValueType();
1939
1940   // fold (mul x, undef) -> 0
1941   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1942     return DAG.getConstant(0, VT);
1943
1944   bool N0IsConst = false;
1945   bool N1IsConst = false;
1946   APInt ConstValue0, ConstValue1;
1947   // fold vector ops
1948   if (VT.isVector()) {
1949     SDValue FoldedVOp = SimplifyVBinOp(N);
1950     if (FoldedVOp.getNode()) return FoldedVOp;
1951
1952     N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
1953     N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
1954   } else {
1955     N0IsConst = dyn_cast<ConstantSDNode>(N0) != nullptr;
1956     ConstValue0 = N0IsConst ? (dyn_cast<ConstantSDNode>(N0))->getAPIntValue()
1957                             : APInt();
1958     N1IsConst = dyn_cast<ConstantSDNode>(N1) != nullptr;
1959     ConstValue1 = N1IsConst ? (dyn_cast<ConstantSDNode>(N1))->getAPIntValue()
1960                             : APInt();
1961   }
1962
1963   // fold (mul c1, c2) -> c1*c2
1964   if (N0IsConst && N1IsConst)
1965     return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0.getNode(), N1.getNode());
1966
1967   // canonicalize constant to RHS
1968   if (N0IsConst && !N1IsConst)
1969     return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
1970   // fold (mul x, 0) -> 0
1971   if (N1IsConst && ConstValue1 == 0)
1972     return N1;
1973   // We require a splat of the entire scalar bit width for non-contiguous
1974   // bit patterns.
1975   bool IsFullSplat =
1976     ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
1977   // fold (mul x, 1) -> x
1978   if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
1979     return N0;
1980   // fold (mul x, -1) -> 0-x
1981   if (N1IsConst && ConstValue1.isAllOnesValue())
1982     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1983                        DAG.getConstant(0, VT), N0);
1984   // fold (mul x, (1 << c)) -> x << c
1985   if (N1IsConst && ConstValue1.isPowerOf2() && IsFullSplat)
1986     return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1987                        DAG.getConstant(ConstValue1.logBase2(),
1988                                        getShiftAmountTy(N0.getValueType())));
1989   // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
1990   if (N1IsConst && (-ConstValue1).isPowerOf2() && IsFullSplat) {
1991     unsigned Log2Val = (-ConstValue1).logBase2();
1992     // FIXME: If the input is something that is easily negated (e.g. a
1993     // single-use add), we should put the negate there.
1994     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1995                        DAG.getConstant(0, VT),
1996                        DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1997                             DAG.getConstant(Log2Val,
1998                                       getShiftAmountTy(N0.getValueType()))));
1999   }
2000
2001   APInt Val;
2002   // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
2003   if (N1IsConst && N0.getOpcode() == ISD::SHL &&
2004       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2005                      isa<ConstantSDNode>(N0.getOperand(1)))) {
2006     SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
2007                              N1, N0.getOperand(1));
2008     AddToWorklist(C3.getNode());
2009     return DAG.getNode(ISD::MUL, SDLoc(N), VT,
2010                        N0.getOperand(0), C3);
2011   }
2012
2013   // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
2014   // use.
2015   {
2016     SDValue Sh(nullptr,0), Y(nullptr,0);
2017     // Check for both (mul (shl X, C), Y)  and  (mul Y, (shl X, C)).
2018     if (N0.getOpcode() == ISD::SHL &&
2019         (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2020                        isa<ConstantSDNode>(N0.getOperand(1))) &&
2021         N0.getNode()->hasOneUse()) {
2022       Sh = N0; Y = N1;
2023     } else if (N1.getOpcode() == ISD::SHL &&
2024                isa<ConstantSDNode>(N1.getOperand(1)) &&
2025                N1.getNode()->hasOneUse()) {
2026       Sh = N1; Y = N0;
2027     }
2028
2029     if (Sh.getNode()) {
2030       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2031                                 Sh.getOperand(0), Y);
2032       return DAG.getNode(ISD::SHL, SDLoc(N), VT,
2033                          Mul, Sh.getOperand(1));
2034     }
2035   }
2036
2037   // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
2038   if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
2039       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2040                      isa<ConstantSDNode>(N0.getOperand(1))))
2041     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
2042                        DAG.getNode(ISD::MUL, SDLoc(N0), VT,
2043                                    N0.getOperand(0), N1),
2044                        DAG.getNode(ISD::MUL, SDLoc(N1), VT,
2045                                    N0.getOperand(1), N1));
2046
2047   // reassociate mul
2048   SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1);
2049   if (RMUL.getNode())
2050     return RMUL;
2051
2052   return SDValue();
2053 }
2054
2055 SDValue DAGCombiner::visitSDIV(SDNode *N) {
2056   SDValue N0 = N->getOperand(0);
2057   SDValue N1 = N->getOperand(1);
2058   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2059   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2060   EVT VT = N->getValueType(0);
2061
2062   // fold vector ops
2063   if (VT.isVector()) {
2064     SDValue FoldedVOp = SimplifyVBinOp(N);
2065     if (FoldedVOp.getNode()) return FoldedVOp;
2066   }
2067
2068   // fold (sdiv c1, c2) -> c1/c2
2069   if (N0C && N1C && !N1C->isNullValue())
2070     return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C);
2071   // fold (sdiv X, 1) -> X
2072   if (N1C && N1C->getAPIntValue() == 1LL)
2073     return N0;
2074   // fold (sdiv X, -1) -> 0-X
2075   if (N1C && N1C->isAllOnesValue())
2076     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
2077                        DAG.getConstant(0, VT), N0);
2078   // If we know the sign bits of both operands are zero, strength reduce to a
2079   // udiv instead.  Handles (X&15) /s 4 -> X&15 >> 2
2080   if (!VT.isVector()) {
2081     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2082       return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
2083                          N0, N1);
2084   }
2085
2086   // fold (sdiv X, pow2) -> simple ops after legalize
2087   if (N1C && !N1C->isNullValue() && (N1C->getAPIntValue().isPowerOf2() ||
2088                                      (-N1C->getAPIntValue()).isPowerOf2())) {
2089     // If dividing by powers of two is cheap, then don't perform the following
2090     // fold.
2091     if (TLI.isPow2SDivCheap())
2092       return SDValue();
2093
2094     // Target-specific implementation of sdiv x, pow2.
2095     SDValue Res = BuildSDIVPow2(N);
2096     if (Res.getNode())
2097       return Res;
2098
2099     unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
2100
2101     // Splat the sign bit into the register
2102     SDValue SGN =
2103         DAG.getNode(ISD::SRA, SDLoc(N), VT, N0,
2104                     DAG.getConstant(VT.getScalarSizeInBits() - 1,
2105                                     getShiftAmountTy(N0.getValueType())));
2106     AddToWorklist(SGN.getNode());
2107
2108     // Add (N0 < 0) ? abs2 - 1 : 0;
2109     SDValue SRL =
2110         DAG.getNode(ISD::SRL, SDLoc(N), VT, SGN,
2111                     DAG.getConstant(VT.getScalarSizeInBits() - lg2,
2112                                     getShiftAmountTy(SGN.getValueType())));
2113     SDValue ADD = DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, SRL);
2114     AddToWorklist(SRL.getNode());
2115     AddToWorklist(ADD.getNode());    // Divide by pow2
2116     SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), VT, ADD,
2117                   DAG.getConstant(lg2, getShiftAmountTy(ADD.getValueType())));
2118
2119     // If we're dividing by a positive value, we're done.  Otherwise, we must
2120     // negate the result.
2121     if (N1C->getAPIntValue().isNonNegative())
2122       return SRA;
2123
2124     AddToWorklist(SRA.getNode());
2125     return DAG.getNode(ISD::SUB, SDLoc(N), VT, DAG.getConstant(0, VT), SRA);
2126   }
2127
2128   // if integer divide is expensive and we satisfy the requirements, emit an
2129   // alternate sequence.
2130   if (N1C && !TLI.isIntDivCheap()) {
2131     SDValue Op = BuildSDIV(N);
2132     if (Op.getNode()) return Op;
2133   }
2134
2135   // undef / X -> 0
2136   if (N0.getOpcode() == ISD::UNDEF)
2137     return DAG.getConstant(0, VT);
2138   // X / undef -> undef
2139   if (N1.getOpcode() == ISD::UNDEF)
2140     return N1;
2141
2142   return SDValue();
2143 }
2144
2145 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2146   SDValue N0 = N->getOperand(0);
2147   SDValue N1 = N->getOperand(1);
2148   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2149   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2150   EVT VT = N->getValueType(0);
2151
2152   // fold vector ops
2153   if (VT.isVector()) {
2154     SDValue FoldedVOp = SimplifyVBinOp(N);
2155     if (FoldedVOp.getNode()) return FoldedVOp;
2156   }
2157
2158   // fold (udiv c1, c2) -> c1/c2
2159   if (N0C && N1C && !N1C->isNullValue())
2160     return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C);
2161   // fold (udiv x, (1 << c)) -> x >>u c
2162   if (N1C && N1C->getAPIntValue().isPowerOf2())
2163     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0,
2164                        DAG.getConstant(N1C->getAPIntValue().logBase2(),
2165                                        getShiftAmountTy(N0.getValueType())));
2166   // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2167   if (N1.getOpcode() == ISD::SHL) {
2168     if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2169       if (SHC->getAPIntValue().isPowerOf2()) {
2170         EVT ADDVT = N1.getOperand(1).getValueType();
2171         SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N), ADDVT,
2172                                   N1.getOperand(1),
2173                                   DAG.getConstant(SHC->getAPIntValue()
2174                                                                   .logBase2(),
2175                                                   ADDVT));
2176         AddToWorklist(Add.getNode());
2177         return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, Add);
2178       }
2179     }
2180   }
2181   // fold (udiv x, c) -> alternate
2182   if (N1C && !TLI.isIntDivCheap()) {
2183     SDValue Op = BuildUDIV(N);
2184     if (Op.getNode()) return Op;
2185   }
2186
2187   // undef / X -> 0
2188   if (N0.getOpcode() == ISD::UNDEF)
2189     return DAG.getConstant(0, VT);
2190   // X / undef -> undef
2191   if (N1.getOpcode() == ISD::UNDEF)
2192     return N1;
2193
2194   return SDValue();
2195 }
2196
2197 SDValue DAGCombiner::visitSREM(SDNode *N) {
2198   SDValue N0 = N->getOperand(0);
2199   SDValue N1 = N->getOperand(1);
2200   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2201   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2202   EVT VT = N->getValueType(0);
2203
2204   // fold (srem c1, c2) -> c1%c2
2205   if (N0C && N1C && !N1C->isNullValue())
2206     return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C);
2207   // If we know the sign bits of both operands are zero, strength reduce to a
2208   // urem instead.  Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2209   if (!VT.isVector()) {
2210     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2211       return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
2212   }
2213
2214   // If X/C can be simplified by the division-by-constant logic, lower
2215   // X%C to the equivalent of X-X/C*C.
2216   if (N1C && !N1C->isNullValue()) {
2217     SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
2218     AddToWorklist(Div.getNode());
2219     SDValue OptimizedDiv = combine(Div.getNode());
2220     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2221       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2222                                 OptimizedDiv, N1);
2223       SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2224       AddToWorklist(Mul.getNode());
2225       return Sub;
2226     }
2227   }
2228
2229   // undef % X -> 0
2230   if (N0.getOpcode() == ISD::UNDEF)
2231     return DAG.getConstant(0, VT);
2232   // X % undef -> undef
2233   if (N1.getOpcode() == ISD::UNDEF)
2234     return N1;
2235
2236   return SDValue();
2237 }
2238
2239 SDValue DAGCombiner::visitUREM(SDNode *N) {
2240   SDValue N0 = N->getOperand(0);
2241   SDValue N1 = N->getOperand(1);
2242   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2243   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2244   EVT VT = N->getValueType(0);
2245
2246   // fold (urem c1, c2) -> c1%c2
2247   if (N0C && N1C && !N1C->isNullValue())
2248     return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C);
2249   // fold (urem x, pow2) -> (and x, pow2-1)
2250   if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
2251     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0,
2252                        DAG.getConstant(N1C->getAPIntValue()-1,VT));
2253   // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2254   if (N1.getOpcode() == ISD::SHL) {
2255     if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2256       if (SHC->getAPIntValue().isPowerOf2()) {
2257         SDValue Add =
2258           DAG.getNode(ISD::ADD, SDLoc(N), VT, N1,
2259                  DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
2260                                  VT));
2261         AddToWorklist(Add.getNode());
2262         return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, Add);
2263       }
2264     }
2265   }
2266
2267   // If X/C can be simplified by the division-by-constant logic, lower
2268   // X%C to the equivalent of X-X/C*C.
2269   if (N1C && !N1C->isNullValue()) {
2270     SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
2271     AddToWorklist(Div.getNode());
2272     SDValue OptimizedDiv = combine(Div.getNode());
2273     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2274       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2275                                 OptimizedDiv, N1);
2276       SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2277       AddToWorklist(Mul.getNode());
2278       return Sub;
2279     }
2280   }
2281
2282   // undef % X -> 0
2283   if (N0.getOpcode() == ISD::UNDEF)
2284     return DAG.getConstant(0, VT);
2285   // X % undef -> undef
2286   if (N1.getOpcode() == ISD::UNDEF)
2287     return N1;
2288
2289   return SDValue();
2290 }
2291
2292 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2293   SDValue N0 = N->getOperand(0);
2294   SDValue N1 = N->getOperand(1);
2295   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2296   EVT VT = N->getValueType(0);
2297   SDLoc DL(N);
2298
2299   // fold (mulhs x, 0) -> 0
2300   if (N1C && N1C->isNullValue())
2301     return N1;
2302   // fold (mulhs x, 1) -> (sra x, size(x)-1)
2303   if (N1C && N1C->getAPIntValue() == 1)
2304     return DAG.getNode(ISD::SRA, SDLoc(N), N0.getValueType(), N0,
2305                        DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2306                                        getShiftAmountTy(N0.getValueType())));
2307   // fold (mulhs x, undef) -> 0
2308   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2309     return DAG.getConstant(0, VT);
2310
2311   // If the type twice as wide is legal, transform the mulhs to a wider multiply
2312   // plus a shift.
2313   if (VT.isSimple() && !VT.isVector()) {
2314     MVT Simple = VT.getSimpleVT();
2315     unsigned SimpleSize = Simple.getSizeInBits();
2316     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2317     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2318       N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2319       N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2320       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2321       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2322             DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2323       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2324     }
2325   }
2326
2327   return SDValue();
2328 }
2329
2330 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2331   SDValue N0 = N->getOperand(0);
2332   SDValue N1 = N->getOperand(1);
2333   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2334   EVT VT = N->getValueType(0);
2335   SDLoc DL(N);
2336
2337   // fold (mulhu x, 0) -> 0
2338   if (N1C && N1C->isNullValue())
2339     return N1;
2340   // fold (mulhu x, 1) -> 0
2341   if (N1C && N1C->getAPIntValue() == 1)
2342     return DAG.getConstant(0, N0.getValueType());
2343   // fold (mulhu x, undef) -> 0
2344   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2345     return DAG.getConstant(0, VT);
2346
2347   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2348   // plus a shift.
2349   if (VT.isSimple() && !VT.isVector()) {
2350     MVT Simple = VT.getSimpleVT();
2351     unsigned SimpleSize = Simple.getSizeInBits();
2352     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2353     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2354       N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2355       N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2356       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2357       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2358             DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2359       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2360     }
2361   }
2362
2363   return SDValue();
2364 }
2365
2366 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp
2367 /// give the opcodes for the two computations that are being performed. Return
2368 /// true if a simplification was made.
2369 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2370                                                 unsigned HiOp) {
2371   // If the high half is not needed, just compute the low half.
2372   bool HiExists = N->hasAnyUseOfValue(1);
2373   if (!HiExists &&
2374       (!LegalOperations ||
2375        TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
2376     SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2377     return CombineTo(N, Res, Res);
2378   }
2379
2380   // If the low half is not needed, just compute the high half.
2381   bool LoExists = N->hasAnyUseOfValue(0);
2382   if (!LoExists &&
2383       (!LegalOperations ||
2384        TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2385     SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2386     return CombineTo(N, Res, Res);
2387   }
2388
2389   // If both halves are used, return as it is.
2390   if (LoExists && HiExists)
2391     return SDValue();
2392
2393   // If the two computed results can be simplified separately, separate them.
2394   if (LoExists) {
2395     SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2396     AddToWorklist(Lo.getNode());
2397     SDValue LoOpt = combine(Lo.getNode());
2398     if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2399         (!LegalOperations ||
2400          TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2401       return CombineTo(N, LoOpt, LoOpt);
2402   }
2403
2404   if (HiExists) {
2405     SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2406     AddToWorklist(Hi.getNode());
2407     SDValue HiOpt = combine(Hi.getNode());
2408     if (HiOpt.getNode() && HiOpt != Hi &&
2409         (!LegalOperations ||
2410          TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2411       return CombineTo(N, HiOpt, HiOpt);
2412   }
2413
2414   return SDValue();
2415 }
2416
2417 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2418   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
2419   if (Res.getNode()) return Res;
2420
2421   EVT VT = N->getValueType(0);
2422   SDLoc DL(N);
2423
2424   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2425   // plus a shift.
2426   if (VT.isSimple() && !VT.isVector()) {
2427     MVT Simple = VT.getSimpleVT();
2428     unsigned SimpleSize = Simple.getSizeInBits();
2429     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2430     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2431       SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2432       SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2433       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2434       // Compute the high part as N1.
2435       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2436             DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2437       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2438       // Compute the low part as N0.
2439       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2440       return CombineTo(N, Lo, Hi);
2441     }
2442   }
2443
2444   return SDValue();
2445 }
2446
2447 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2448   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
2449   if (Res.getNode()) return Res;
2450
2451   EVT VT = N->getValueType(0);
2452   SDLoc DL(N);
2453
2454   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2455   // plus a shift.
2456   if (VT.isSimple() && !VT.isVector()) {
2457     MVT Simple = VT.getSimpleVT();
2458     unsigned SimpleSize = Simple.getSizeInBits();
2459     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2460     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2461       SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2462       SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2463       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2464       // Compute the high part as N1.
2465       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2466             DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2467       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2468       // Compute the low part as N0.
2469       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2470       return CombineTo(N, Lo, Hi);
2471     }
2472   }
2473
2474   return SDValue();
2475 }
2476
2477 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2478   // (smulo x, 2) -> (saddo x, x)
2479   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2480     if (C2->getAPIntValue() == 2)
2481       return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2482                          N->getOperand(0), N->getOperand(0));
2483
2484   return SDValue();
2485 }
2486
2487 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2488   // (umulo x, 2) -> (uaddo x, x)
2489   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2490     if (C2->getAPIntValue() == 2)
2491       return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2492                          N->getOperand(0), N->getOperand(0));
2493
2494   return SDValue();
2495 }
2496
2497 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2498   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
2499   if (Res.getNode()) return Res;
2500
2501   return SDValue();
2502 }
2503
2504 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2505   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
2506   if (Res.getNode()) return Res;
2507
2508   return SDValue();
2509 }
2510
2511 /// If this is a binary operator with two operands of the same opcode, try to
2512 /// simplify it.
2513 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2514   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2515   EVT VT = N0.getValueType();
2516   assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2517
2518   // Bail early if none of these transforms apply.
2519   if (N0.getNode()->getNumOperands() == 0) return SDValue();
2520
2521   // For each of OP in AND/OR/XOR:
2522   // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2523   // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2524   // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2525   // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2526   //
2527   // do not sink logical op inside of a vector extend, since it may combine
2528   // into a vsetcc.
2529   EVT Op0VT = N0.getOperand(0).getValueType();
2530   if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2531        N0.getOpcode() == ISD::SIGN_EXTEND ||
2532        // Avoid infinite looping with PromoteIntBinOp.
2533        (N0.getOpcode() == ISD::ANY_EXTEND &&
2534         (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2535        (N0.getOpcode() == ISD::TRUNCATE &&
2536         (!TLI.isZExtFree(VT, Op0VT) ||
2537          !TLI.isTruncateFree(Op0VT, VT)) &&
2538         TLI.isTypeLegal(Op0VT))) &&
2539       !VT.isVector() &&
2540       Op0VT == N1.getOperand(0).getValueType() &&
2541       (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2542     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2543                                  N0.getOperand(0).getValueType(),
2544                                  N0.getOperand(0), N1.getOperand(0));
2545     AddToWorklist(ORNode.getNode());
2546     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2547   }
2548
2549   // For each of OP in SHL/SRL/SRA/AND...
2550   //   fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2551   //   fold (or  (OP x, z), (OP y, z)) -> (OP (or  x, y), z)
2552   //   fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2553   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2554        N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2555       N0.getOperand(1) == N1.getOperand(1)) {
2556     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2557                                  N0.getOperand(0).getValueType(),
2558                                  N0.getOperand(0), N1.getOperand(0));
2559     AddToWorklist(ORNode.getNode());
2560     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2561                        ORNode, N0.getOperand(1));
2562   }
2563
2564   // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2565   // Only perform this optimization after type legalization and before
2566   // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2567   // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2568   // we don't want to undo this promotion.
2569   // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2570   // on scalars.
2571   if ((N0.getOpcode() == ISD::BITCAST ||
2572        N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2573       Level == AfterLegalizeTypes) {
2574     SDValue In0 = N0.getOperand(0);
2575     SDValue In1 = N1.getOperand(0);
2576     EVT In0Ty = In0.getValueType();
2577     EVT In1Ty = In1.getValueType();
2578     SDLoc DL(N);
2579     // If both incoming values are integers, and the original types are the
2580     // same.
2581     if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2582       SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2583       SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2584       AddToWorklist(Op.getNode());
2585       return BC;
2586     }
2587   }
2588
2589   // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2590   // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2591   // If both shuffles use the same mask, and both shuffle within a single
2592   // vector, then it is worthwhile to move the swizzle after the operation.
2593   // The type-legalizer generates this pattern when loading illegal
2594   // vector types from memory. In many cases this allows additional shuffle
2595   // optimizations.
2596   // There are other cases where moving the shuffle after the xor/and/or
2597   // is profitable even if shuffles don't perform a swizzle.
2598   // If both shuffles use the same mask, and both shuffles have the same first
2599   // or second operand, then it might still be profitable to move the shuffle
2600   // after the xor/and/or operation.
2601   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
2602     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2603     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2604
2605     assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
2606            "Inputs to shuffles are not the same type");
2607
2608     // Check that both shuffles use the same mask. The masks are known to be of
2609     // the same length because the result vector type is the same.
2610     // Check also that shuffles have only one use to avoid introducing extra
2611     // instructions.
2612     if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2613         SVN0->getMask().equals(SVN1->getMask())) {
2614       SDValue ShOp = N0->getOperand(1);
2615
2616       // Don't try to fold this node if it requires introducing a
2617       // build vector of all zeros that might be illegal at this stage.
2618       if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2619         if (!LegalTypes)
2620           ShOp = DAG.getConstant(0, VT);
2621         else
2622           ShOp = SDValue();
2623       }
2624
2625       // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2626       // (OR  (shuf (A, C), shuf (B, C)) -> shuf (OR  (A, B), C)
2627       // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2628       if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2629         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2630                                       N0->getOperand(0), N1->getOperand(0));
2631         AddToWorklist(NewNode.getNode());
2632         return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2633                                     &SVN0->getMask()[0]);
2634       }
2635
2636       // Don't try to fold this node if it requires introducing a
2637       // build vector of all zeros that might be illegal at this stage.
2638       ShOp = N0->getOperand(0);
2639       if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2640         if (!LegalTypes)
2641           ShOp = DAG.getConstant(0, VT);
2642         else
2643           ShOp = SDValue();
2644       }
2645
2646       // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2647       // (OR  (shuf (C, A), shuf (C, B)) -> shuf (C, OR  (A, B))
2648       // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2649       if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2650         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2651                                       N0->getOperand(1), N1->getOperand(1));
2652         AddToWorklist(NewNode.getNode());
2653         return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2654                                     &SVN0->getMask()[0]);
2655       }
2656     }
2657   }
2658
2659   return SDValue();
2660 }
2661
2662 SDValue DAGCombiner::visitAND(SDNode *N) {
2663   SDValue N0 = N->getOperand(0);
2664   SDValue N1 = N->getOperand(1);
2665   SDValue LL, LR, RL, RR, CC0, CC1;
2666   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2667   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2668   EVT VT = N1.getValueType();
2669   unsigned BitWidth = VT.getScalarType().getSizeInBits();
2670
2671   // fold vector ops
2672   if (VT.isVector()) {
2673     SDValue FoldedVOp = SimplifyVBinOp(N);
2674     if (FoldedVOp.getNode()) return FoldedVOp;
2675
2676     // fold (and x, 0) -> 0, vector edition
2677     if (ISD::isBuildVectorAllZeros(N0.getNode()))
2678       // do not return N0, because undef node may exist in N0
2679       return DAG.getConstant(
2680           APInt::getNullValue(
2681               N0.getValueType().getScalarType().getSizeInBits()),
2682           N0.getValueType());
2683     if (ISD::isBuildVectorAllZeros(N1.getNode()))
2684       // do not return N1, because undef node may exist in N1
2685       return DAG.getConstant(
2686           APInt::getNullValue(
2687               N1.getValueType().getScalarType().getSizeInBits()),
2688           N1.getValueType());
2689
2690     // fold (and x, -1) -> x, vector edition
2691     if (ISD::isBuildVectorAllOnes(N0.getNode()))
2692       return N1;
2693     if (ISD::isBuildVectorAllOnes(N1.getNode()))
2694       return N0;
2695   }
2696
2697   // fold (and x, undef) -> 0
2698   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2699     return DAG.getConstant(0, VT);
2700   // fold (and c1, c2) -> c1&c2
2701   if (N0C && N1C)
2702     return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C);
2703   // canonicalize constant to RHS
2704   if (N0C && !N1C)
2705     return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
2706   // fold (and x, -1) -> x
2707   if (N1C && N1C->isAllOnesValue())
2708     return N0;
2709   // if (and x, c) is known to be zero, return 0
2710   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2711                                    APInt::getAllOnesValue(BitWidth)))
2712     return DAG.getConstant(0, VT);
2713   // reassociate and
2714   SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1);
2715   if (RAND.getNode())
2716     return RAND;
2717   // fold (and (or x, C), D) -> D if (C & D) == D
2718   if (N1C && N0.getOpcode() == ISD::OR)
2719     if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2720       if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2721         return N1;
2722   // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2723   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2724     SDValue N0Op0 = N0.getOperand(0);
2725     APInt Mask = ~N1C->getAPIntValue();
2726     Mask = Mask.trunc(N0Op0.getValueSizeInBits());
2727     if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2728       SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
2729                                  N0.getValueType(), N0Op0);
2730
2731       // Replace uses of the AND with uses of the Zero extend node.
2732       CombineTo(N, Zext);
2733
2734       // We actually want to replace all uses of the any_extend with the
2735       // zero_extend, to avoid duplicating things.  This will later cause this
2736       // AND to be folded.
2737       CombineTo(N0.getNode(), Zext);
2738       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2739     }
2740   }
2741   // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
2742   // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2743   // already be zero by virtue of the width of the base type of the load.
2744   //
2745   // the 'X' node here can either be nothing or an extract_vector_elt to catch
2746   // more cases.
2747   if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2748        N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2749       N0.getOpcode() == ISD::LOAD) {
2750     LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2751                                          N0 : N0.getOperand(0) );
2752
2753     // Get the constant (if applicable) the zero'th operand is being ANDed with.
2754     // This can be a pure constant or a vector splat, in which case we treat the
2755     // vector as a scalar and use the splat value.
2756     APInt Constant = APInt::getNullValue(1);
2757     if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2758       Constant = C->getAPIntValue();
2759     } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2760       APInt SplatValue, SplatUndef;
2761       unsigned SplatBitSize;
2762       bool HasAnyUndefs;
2763       bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2764                                              SplatBitSize, HasAnyUndefs);
2765       if (IsSplat) {
2766         // Undef bits can contribute to a possible optimisation if set, so
2767         // set them.
2768         SplatValue |= SplatUndef;
2769
2770         // The splat value may be something like "0x00FFFFFF", which means 0 for
2771         // the first vector value and FF for the rest, repeating. We need a mask
2772         // that will apply equally to all members of the vector, so AND all the
2773         // lanes of the constant together.
2774         EVT VT = Vector->getValueType(0);
2775         unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
2776
2777         // If the splat value has been compressed to a bitlength lower
2778         // than the size of the vector lane, we need to re-expand it to
2779         // the lane size.
2780         if (BitWidth > SplatBitSize)
2781           for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
2782                SplatBitSize < BitWidth;
2783                SplatBitSize = SplatBitSize * 2)
2784             SplatValue |= SplatValue.shl(SplatBitSize);
2785
2786         Constant = APInt::getAllOnesValue(BitWidth);
2787         for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
2788           Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
2789       }
2790     }
2791
2792     // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
2793     // actually legal and isn't going to get expanded, else this is a false
2794     // optimisation.
2795     bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
2796                                                     Load->getMemoryVT());
2797
2798     // Resize the constant to the same size as the original memory access before
2799     // extension. If it is still the AllOnesValue then this AND is completely
2800     // unneeded.
2801     Constant =
2802       Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
2803
2804     bool B;
2805     switch (Load->getExtensionType()) {
2806     default: B = false; break;
2807     case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
2808     case ISD::ZEXTLOAD:
2809     case ISD::NON_EXTLOAD: B = true; break;
2810     }
2811
2812     if (B && Constant.isAllOnesValue()) {
2813       // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
2814       // preserve semantics once we get rid of the AND.
2815       SDValue NewLoad(Load, 0);
2816       if (Load->getExtensionType() == ISD::EXTLOAD) {
2817         NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
2818                               Load->getValueType(0), SDLoc(Load),
2819                               Load->getChain(), Load->getBasePtr(),
2820                               Load->getOffset(), Load->getMemoryVT(),
2821                               Load->getMemOperand());
2822         // Replace uses of the EXTLOAD with the new ZEXTLOAD.
2823         if (Load->getNumValues() == 3) {
2824           // PRE/POST_INC loads have 3 values.
2825           SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
2826                            NewLoad.getValue(2) };
2827           CombineTo(Load, To, 3, true);
2828         } else {
2829           CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
2830         }
2831       }
2832
2833       // Fold the AND away, taking care not to fold to the old load node if we
2834       // replaced it.
2835       CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
2836
2837       return SDValue(N, 0); // Return N so it doesn't get rechecked!
2838     }
2839   }
2840   // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2841   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2842     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2843     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2844
2845     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2846         LL.getValueType().isInteger()) {
2847       // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2848       if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
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       // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2855       if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
2856         SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2857                                       LR.getValueType(), LL, RL);
2858         AddToWorklist(ANDNode.getNode());
2859         return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
2860       }
2861       // fold (and (setgt X,  -1), (setgt Y,  -1)) -> (setgt (or X, Y), -1)
2862       if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
2863         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2864                                      LR.getValueType(), LL, RL);
2865         AddToWorklist(ORNode.getNode());
2866         return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2867       }
2868     }
2869     // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2870     if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2871         Op0 == Op1 && LL.getValueType().isInteger() &&
2872       Op0 == ISD::SETNE && ((cast<ConstantSDNode>(LR)->isNullValue() &&
2873                                  cast<ConstantSDNode>(RR)->isAllOnesValue()) ||
2874                                 (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
2875                                  cast<ConstantSDNode>(RR)->isNullValue()))) {
2876       SDValue ADDNode = DAG.getNode(ISD::ADD, SDLoc(N0), LL.getValueType(),
2877                                     LL, DAG.getConstant(1, LL.getValueType()));
2878       AddToWorklist(ADDNode.getNode());
2879       return DAG.getSetCC(SDLoc(N), VT, ADDNode,
2880                           DAG.getConstant(2, LL.getValueType()), ISD::SETUGE);
2881     }
2882     // canonicalize equivalent to ll == rl
2883     if (LL == RR && LR == RL) {
2884       Op1 = ISD::getSetCCSwappedOperands(Op1);
2885       std::swap(RL, RR);
2886     }
2887     if (LL == RL && LR == RR) {
2888       bool isInteger = LL.getValueType().isInteger();
2889       ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2890       if (Result != ISD::SETCC_INVALID &&
2891           (!LegalOperations ||
2892            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2893             TLI.isOperationLegal(ISD::SETCC,
2894                             getSetCCResultType(N0.getSimpleValueType())))))
2895         return DAG.getSetCC(SDLoc(N), N0.getValueType(),
2896                             LL, LR, Result);
2897     }
2898   }
2899
2900   // Simplify: (and (op x...), (op y...))  -> (op (and x, y))
2901   if (N0.getOpcode() == N1.getOpcode()) {
2902     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
2903     if (Tmp.getNode()) return Tmp;
2904   }
2905
2906   // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
2907   // fold (and (sra)) -> (and (srl)) when possible.
2908   if (!VT.isVector() &&
2909       SimplifyDemandedBits(SDValue(N, 0)))
2910     return SDValue(N, 0);
2911
2912   // fold (zext_inreg (extload x)) -> (zextload x)
2913   if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
2914     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2915     EVT MemVT = LN0->getMemoryVT();
2916     // If we zero all the possible extended bits, then we can turn this into
2917     // a zextload if we are running before legalize or the operation is legal.
2918     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2919     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2920                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2921         ((!LegalOperations && !LN0->isVolatile()) ||
2922          TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2923       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2924                                        LN0->getChain(), LN0->getBasePtr(),
2925                                        MemVT, LN0->getMemOperand());
2926       AddToWorklist(N);
2927       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2928       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2929     }
2930   }
2931   // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
2932   if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
2933       N0.hasOneUse()) {
2934     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2935     EVT MemVT = LN0->getMemoryVT();
2936     // If we zero all the possible extended bits, then we can turn this into
2937     // a zextload if we are running before legalize or the operation is legal.
2938     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2939     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2940                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2941         ((!LegalOperations && !LN0->isVolatile()) ||
2942          TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2943       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2944                                        LN0->getChain(), LN0->getBasePtr(),
2945                                        MemVT, LN0->getMemOperand());
2946       AddToWorklist(N);
2947       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2948       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2949     }
2950   }
2951
2952   // fold (and (load x), 255) -> (zextload x, i8)
2953   // fold (and (extload x, i16), 255) -> (zextload x, i8)
2954   // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
2955   if (N1C && (N0.getOpcode() == ISD::LOAD ||
2956               (N0.getOpcode() == ISD::ANY_EXTEND &&
2957                N0.getOperand(0).getOpcode() == ISD::LOAD))) {
2958     bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
2959     LoadSDNode *LN0 = HasAnyExt
2960       ? cast<LoadSDNode>(N0.getOperand(0))
2961       : cast<LoadSDNode>(N0);
2962     if (LN0->getExtensionType() != ISD::SEXTLOAD &&
2963         LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
2964       uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
2965       if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
2966         EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
2967         EVT LoadedVT = LN0->getMemoryVT();
2968
2969         if (ExtVT == LoadedVT &&
2970             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2971           EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2972
2973           SDValue NewLoad =
2974             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2975                            LN0->getChain(), LN0->getBasePtr(), ExtVT,
2976                            LN0->getMemOperand());
2977           AddToWorklist(N);
2978           CombineTo(LN0, NewLoad, NewLoad.getValue(1));
2979           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2980         }
2981
2982         // Do not change the width of a volatile load.
2983         // Do not generate loads of non-round integer types since these can
2984         // be expensive (and would be wrong if the type is not byte sized).
2985         if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
2986             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2987           EVT PtrType = LN0->getOperand(1).getValueType();
2988
2989           unsigned Alignment = LN0->getAlignment();
2990           SDValue NewPtr = LN0->getBasePtr();
2991
2992           // For big endian targets, we need to add an offset to the pointer
2993           // to load the correct bytes.  For little endian systems, we merely
2994           // need to read fewer bytes from the same pointer.
2995           if (TLI.isBigEndian()) {
2996             unsigned LVTStoreBytes = LoadedVT.getStoreSize();
2997             unsigned EVTStoreBytes = ExtVT.getStoreSize();
2998             unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
2999             NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0), PtrType,
3000                                  NewPtr, DAG.getConstant(PtrOff, PtrType));
3001             Alignment = MinAlign(Alignment, PtrOff);
3002           }
3003
3004           AddToWorklist(NewPtr.getNode());
3005
3006           EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
3007           SDValue Load =
3008             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3009                            LN0->getChain(), NewPtr,
3010                            LN0->getPointerInfo(),
3011                            ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
3012                            LN0->isInvariant(), Alignment, LN0->getAAInfo());
3013           AddToWorklist(N);
3014           CombineTo(LN0, Load, Load.getValue(1));
3015           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3016         }
3017       }
3018     }
3019   }
3020
3021   if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
3022       VT.getSizeInBits() <= 64) {
3023     if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3024       APInt ADDC = ADDI->getAPIntValue();
3025       if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
3026         // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
3027         // immediate for an add, but it is legal if its top c2 bits are set,
3028         // transform the ADD so the immediate doesn't need to be materialized
3029         // in a register.
3030         if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
3031           APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
3032                                              SRLI->getZExtValue());
3033           if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
3034             ADDC |= Mask;
3035             if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
3036               SDValue NewAdd =
3037                 DAG.getNode(ISD::ADD, SDLoc(N0), VT,
3038                             N0.getOperand(0), DAG.getConstant(ADDC, VT));
3039               CombineTo(N0.getNode(), NewAdd);
3040               return SDValue(N, 0); // Return N so it doesn't get rechecked!
3041             }
3042           }
3043         }
3044       }
3045     }
3046   }
3047
3048   // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
3049   if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
3050     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
3051                                        N0.getOperand(1), false);
3052     if (BSwap.getNode())
3053       return BSwap;
3054   }
3055
3056   return SDValue();
3057 }
3058
3059 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16.
3060 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
3061                                         bool DemandHighBits) {
3062   if (!LegalOperations)
3063     return SDValue();
3064
3065   EVT VT = N->getValueType(0);
3066   if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
3067     return SDValue();
3068   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3069     return SDValue();
3070
3071   // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
3072   bool LookPassAnd0 = false;
3073   bool LookPassAnd1 = false;
3074   if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
3075       std::swap(N0, N1);
3076   if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
3077       std::swap(N0, N1);
3078   if (N0.getOpcode() == ISD::AND) {
3079     if (!N0.getNode()->hasOneUse())
3080       return SDValue();
3081     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3082     if (!N01C || N01C->getZExtValue() != 0xFF00)
3083       return SDValue();
3084     N0 = N0.getOperand(0);
3085     LookPassAnd0 = true;
3086   }
3087
3088   if (N1.getOpcode() == ISD::AND) {
3089     if (!N1.getNode()->hasOneUse())
3090       return SDValue();
3091     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3092     if (!N11C || N11C->getZExtValue() != 0xFF)
3093       return SDValue();
3094     N1 = N1.getOperand(0);
3095     LookPassAnd1 = true;
3096   }
3097
3098   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3099     std::swap(N0, N1);
3100   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3101     return SDValue();
3102   if (!N0.getNode()->hasOneUse() ||
3103       !N1.getNode()->hasOneUse())
3104     return SDValue();
3105
3106   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3107   ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3108   if (!N01C || !N11C)
3109     return SDValue();
3110   if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3111     return SDValue();
3112
3113   // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3114   SDValue N00 = N0->getOperand(0);
3115   if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3116     if (!N00.getNode()->hasOneUse())
3117       return SDValue();
3118     ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3119     if (!N001C || N001C->getZExtValue() != 0xFF)
3120       return SDValue();
3121     N00 = N00.getOperand(0);
3122     LookPassAnd0 = true;
3123   }
3124
3125   SDValue N10 = N1->getOperand(0);
3126   if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3127     if (!N10.getNode()->hasOneUse())
3128       return SDValue();
3129     ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3130     if (!N101C || N101C->getZExtValue() != 0xFF00)
3131       return SDValue();
3132     N10 = N10.getOperand(0);
3133     LookPassAnd1 = true;
3134   }
3135
3136   if (N00 != N10)
3137     return SDValue();
3138
3139   // Make sure everything beyond the low halfword gets set to zero since the SRL
3140   // 16 will clear the top bits.
3141   unsigned OpSizeInBits = VT.getSizeInBits();
3142   if (DemandHighBits && OpSizeInBits > 16) {
3143     // If the left-shift isn't masked out then the only way this is a bswap is
3144     // if all bits beyond the low 8 are 0. In that case the entire pattern
3145     // reduces to a left shift anyway: leave it for other parts of the combiner.
3146     if (!LookPassAnd0)
3147       return SDValue();
3148
3149     // However, if the right shift isn't masked out then it might be because
3150     // it's not needed. See if we can spot that too.
3151     if (!LookPassAnd1 &&
3152         !DAG.MaskedValueIsZero(
3153             N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3154       return SDValue();
3155   }
3156
3157   SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
3158   if (OpSizeInBits > 16)
3159     Res = DAG.getNode(ISD::SRL, SDLoc(N), VT, Res,
3160                       DAG.getConstant(OpSizeInBits-16, getShiftAmountTy(VT)));
3161   return Res;
3162 }
3163
3164 /// Return true if the specified node is an element that makes up a 32-bit
3165 /// packed halfword byteswap.
3166 /// ((x & 0x000000ff) << 8) |
3167 /// ((x & 0x0000ff00) >> 8) |
3168 /// ((x & 0x00ff0000) << 8) |
3169 /// ((x & 0xff000000) >> 8)
3170 static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) {
3171   if (!N.getNode()->hasOneUse())
3172     return false;
3173
3174   unsigned Opc = N.getOpcode();
3175   if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3176     return false;
3177
3178   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3179   if (!N1C)
3180     return false;
3181
3182   unsigned Num;
3183   switch (N1C->getZExtValue()) {
3184   default:
3185     return false;
3186   case 0xFF:       Num = 0; break;
3187   case 0xFF00:     Num = 1; break;
3188   case 0xFF0000:   Num = 2; break;
3189   case 0xFF000000: Num = 3; break;
3190   }
3191
3192   // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3193   SDValue N0 = N.getOperand(0);
3194   if (Opc == ISD::AND) {
3195     if (Num == 0 || Num == 2) {
3196       // (x >> 8) & 0xff
3197       // (x >> 8) & 0xff0000
3198       if (N0.getOpcode() != ISD::SRL)
3199         return false;
3200       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3201       if (!C || C->getZExtValue() != 8)
3202         return false;
3203     } else {
3204       // (x << 8) & 0xff00
3205       // (x << 8) & 0xff000000
3206       if (N0.getOpcode() != ISD::SHL)
3207         return false;
3208       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3209       if (!C || C->getZExtValue() != 8)
3210         return false;
3211     }
3212   } else if (Opc == ISD::SHL) {
3213     // (x & 0xff) << 8
3214     // (x & 0xff0000) << 8
3215     if (Num != 0 && Num != 2)
3216       return false;
3217     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3218     if (!C || C->getZExtValue() != 8)
3219       return false;
3220   } else { // Opc == ISD::SRL
3221     // (x & 0xff00) >> 8
3222     // (x & 0xff000000) >> 8
3223     if (Num != 1 && Num != 3)
3224       return false;
3225     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3226     if (!C || C->getZExtValue() != 8)
3227       return false;
3228   }
3229
3230   if (Parts[Num])
3231     return false;
3232
3233   Parts[Num] = N0.getOperand(0).getNode();
3234   return true;
3235 }
3236
3237 /// Match a 32-bit packed halfword bswap. That is
3238 /// ((x & 0x000000ff) << 8) |
3239 /// ((x & 0x0000ff00) >> 8) |
3240 /// ((x & 0x00ff0000) << 8) |
3241 /// ((x & 0xff000000) >> 8)
3242 /// => (rotl (bswap x), 16)
3243 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3244   if (!LegalOperations)
3245     return SDValue();
3246
3247   EVT VT = N->getValueType(0);
3248   if (VT != MVT::i32)
3249     return SDValue();
3250   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3251     return SDValue();
3252
3253   // Look for either
3254   // (or (or (and), (and)), (or (and), (and)))
3255   // (or (or (or (and), (and)), (and)), (and))
3256   if (N0.getOpcode() != ISD::OR)
3257     return SDValue();
3258   SDValue N00 = N0.getOperand(0);
3259   SDValue N01 = N0.getOperand(1);
3260   SDNode *Parts[4] = {};
3261
3262   if (N1.getOpcode() == ISD::OR &&
3263       N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3264     // (or (or (and), (and)), (or (and), (and)))
3265     SDValue N000 = N00.getOperand(0);
3266     if (!isBSwapHWordElement(N000, Parts))
3267       return SDValue();
3268
3269     SDValue N001 = N00.getOperand(1);
3270     if (!isBSwapHWordElement(N001, Parts))
3271       return SDValue();
3272     SDValue N010 = N01.getOperand(0);
3273     if (!isBSwapHWordElement(N010, Parts))
3274       return SDValue();
3275     SDValue N011 = N01.getOperand(1);
3276     if (!isBSwapHWordElement(N011, Parts))
3277       return SDValue();
3278   } else {
3279     // (or (or (or (and), (and)), (and)), (and))
3280     if (!isBSwapHWordElement(N1, Parts))
3281       return SDValue();
3282     if (!isBSwapHWordElement(N01, Parts))
3283       return SDValue();
3284     if (N00.getOpcode() != ISD::OR)
3285       return SDValue();
3286     SDValue N000 = N00.getOperand(0);
3287     if (!isBSwapHWordElement(N000, Parts))
3288       return SDValue();
3289     SDValue N001 = N00.getOperand(1);
3290     if (!isBSwapHWordElement(N001, Parts))
3291       return SDValue();
3292   }
3293
3294   // Make sure the parts are all coming from the same node.
3295   if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3296     return SDValue();
3297
3298   SDValue BSwap = DAG.getNode(ISD::BSWAP, SDLoc(N), VT,
3299                               SDValue(Parts[0],0));
3300
3301   // Result of the bswap should be rotated by 16. If it's not legal, then
3302   // do  (x << 16) | (x >> 16).
3303   SDValue ShAmt = DAG.getConstant(16, getShiftAmountTy(VT));
3304   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3305     return DAG.getNode(ISD::ROTL, SDLoc(N), VT, BSwap, ShAmt);
3306   if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3307     return DAG.getNode(ISD::ROTR, SDLoc(N), VT, BSwap, ShAmt);
3308   return DAG.getNode(ISD::OR, SDLoc(N), VT,
3309                      DAG.getNode(ISD::SHL, SDLoc(N), VT, BSwap, ShAmt),
3310                      DAG.getNode(ISD::SRL, SDLoc(N), VT, BSwap, ShAmt));
3311 }
3312
3313 SDValue DAGCombiner::visitOR(SDNode *N) {
3314   SDValue N0 = N->getOperand(0);
3315   SDValue N1 = N->getOperand(1);
3316   SDValue LL, LR, RL, RR, CC0, CC1;
3317   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3318   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3319   EVT VT = N1.getValueType();
3320
3321   // fold vector ops
3322   if (VT.isVector()) {
3323     SDValue FoldedVOp = SimplifyVBinOp(N);
3324     if (FoldedVOp.getNode()) return FoldedVOp;
3325
3326     // fold (or x, 0) -> x, vector edition
3327     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3328       return N1;
3329     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3330       return N0;
3331
3332     // fold (or x, -1) -> -1, vector edition
3333     if (ISD::isBuildVectorAllOnes(N0.getNode()))
3334       // do not return N0, because undef node may exist in N0
3335       return DAG.getConstant(
3336           APInt::getAllOnesValue(
3337               N0.getValueType().getScalarType().getSizeInBits()),
3338           N0.getValueType());
3339     if (ISD::isBuildVectorAllOnes(N1.getNode()))
3340       // do not return N1, because undef node may exist in N1
3341       return DAG.getConstant(
3342           APInt::getAllOnesValue(
3343               N1.getValueType().getScalarType().getSizeInBits()),
3344           N1.getValueType());
3345
3346     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
3347     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
3348     // Do this only if the resulting shuffle is legal.
3349     if (isa<ShuffleVectorSDNode>(N0) &&
3350         isa<ShuffleVectorSDNode>(N1) &&
3351         // Avoid folding a node with illegal type.
3352         TLI.isTypeLegal(VT) &&
3353         N0->getOperand(1) == N1->getOperand(1) &&
3354         ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
3355       bool CanFold = true;
3356       unsigned NumElts = VT.getVectorNumElements();
3357       const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3358       const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3359       // We construct two shuffle masks:
3360       // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
3361       // and N1 as the second operand.
3362       // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
3363       // and N0 as the second operand.
3364       // We do this because OR is commutable and therefore there might be
3365       // two ways to fold this node into a shuffle.
3366       SmallVector<int,4> Mask1;
3367       SmallVector<int,4> Mask2;
3368
3369       for (unsigned i = 0; i != NumElts && CanFold; ++i) {
3370         int M0 = SV0->getMaskElt(i);
3371         int M1 = SV1->getMaskElt(i);
3372
3373         // Both shuffle indexes are undef. Propagate Undef.
3374         if (M0 < 0 && M1 < 0) {
3375           Mask1.push_back(M0);
3376           Mask2.push_back(M0);
3377           continue;
3378         }
3379
3380         if (M0 < 0 || M1 < 0 ||
3381             (M0 < (int)NumElts && M1 < (int)NumElts) ||
3382             (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
3383           CanFold = false;
3384           break;
3385         }
3386
3387         Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
3388         Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
3389       }
3390
3391       if (CanFold) {
3392         // Fold this sequence only if the resulting shuffle is 'legal'.
3393         if (TLI.isShuffleMaskLegal(Mask1, VT))
3394           return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
3395                                       N1->getOperand(0), &Mask1[0]);
3396         if (TLI.isShuffleMaskLegal(Mask2, VT))
3397           return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
3398                                       N0->getOperand(0), &Mask2[0]);
3399       }
3400     }
3401   }
3402
3403   // fold (or x, undef) -> -1
3404   if (!LegalOperations &&
3405       (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3406     EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3407     return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
3408   }
3409   // fold (or c1, c2) -> c1|c2
3410   if (N0C && N1C)
3411     return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C);
3412   // canonicalize constant to RHS
3413   if (N0C && !N1C)
3414     return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3415   // fold (or x, 0) -> x
3416   if (N1C && N1C->isNullValue())
3417     return N0;
3418   // fold (or x, -1) -> -1
3419   if (N1C && N1C->isAllOnesValue())
3420     return N1;
3421   // fold (or x, c) -> c iff (x & ~c) == 0
3422   if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3423     return N1;
3424
3425   // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3426   SDValue BSwap = MatchBSwapHWord(N, N0, N1);
3427   if (BSwap.getNode())
3428     return BSwap;
3429   BSwap = MatchBSwapHWordLow(N, N0, N1);
3430   if (BSwap.getNode())
3431     return BSwap;
3432
3433   // reassociate or
3434   SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1);
3435   if (ROR.getNode())
3436     return ROR;
3437   // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3438   // iff (c1 & c2) == 0.
3439   if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3440              isa<ConstantSDNode>(N0.getOperand(1))) {
3441     ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3442     if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3443       SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1);
3444       if (!COR.getNode())
3445         return SDValue();
3446       return DAG.getNode(ISD::AND, SDLoc(N), VT,
3447                          DAG.getNode(ISD::OR, SDLoc(N0), VT,
3448                                      N0.getOperand(0), N1), COR);
3449     }
3450   }
3451   // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3452   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3453     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3454     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3455
3456     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
3457         LL.getValueType().isInteger()) {
3458       // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3459       // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3460       if (cast<ConstantSDNode>(LR)->isNullValue() &&
3461           (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3462         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3463                                      LR.getValueType(), LL, RL);
3464         AddToWorklist(ORNode.getNode());
3465         return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
3466       }
3467       // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3468       // fold (or (setgt X, -1), (setgt Y  -1)) -> (setgt (and X, Y), -1)
3469       if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
3470           (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3471         SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3472                                       LR.getValueType(), LL, RL);
3473         AddToWorklist(ANDNode.getNode());
3474         return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
3475       }
3476     }
3477     // canonicalize equivalent to ll == rl
3478     if (LL == RR && LR == RL) {
3479       Op1 = ISD::getSetCCSwappedOperands(Op1);
3480       std::swap(RL, RR);
3481     }
3482     if (LL == RL && LR == RR) {
3483       bool isInteger = LL.getValueType().isInteger();
3484       ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3485       if (Result != ISD::SETCC_INVALID &&
3486           (!LegalOperations ||
3487            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3488             TLI.isOperationLegal(ISD::SETCC,
3489               getSetCCResultType(N0.getValueType())))))
3490         return DAG.getSetCC(SDLoc(N), N0.getValueType(),
3491                             LL, LR, Result);
3492     }
3493   }
3494
3495   // Simplify: (or (op x...), (op y...))  -> (op (or x, y))
3496   if (N0.getOpcode() == N1.getOpcode()) {
3497     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3498     if (Tmp.getNode()) return Tmp;
3499   }
3500
3501   // (or (and X, C1), (and Y, C2))  -> (and (or X, Y), C3) if possible.
3502   if (N0.getOpcode() == ISD::AND &&
3503       N1.getOpcode() == ISD::AND &&
3504       N0.getOperand(1).getOpcode() == ISD::Constant &&
3505       N1.getOperand(1).getOpcode() == ISD::Constant &&
3506       // Don't increase # computations.
3507       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3508     // We can only do this xform if we know that bits from X that are set in C2
3509     // but not in C1 are already zero.  Likewise for Y.
3510     const APInt &LHSMask =
3511       cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3512     const APInt &RHSMask =
3513       cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
3514
3515     if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3516         DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3517       SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3518                               N0.getOperand(0), N1.getOperand(0));
3519       return DAG.getNode(ISD::AND, SDLoc(N), VT, X,
3520                          DAG.getConstant(LHSMask | RHSMask, VT));
3521     }
3522   }
3523
3524   // See if this is some rotate idiom.
3525   if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3526     return SDValue(Rot, 0);
3527
3528   // Simplify the operands using demanded-bits information.
3529   if (!VT.isVector() &&
3530       SimplifyDemandedBits(SDValue(N, 0)))
3531     return SDValue(N, 0);
3532
3533   return SDValue();
3534 }
3535
3536 /// Match "(X shl/srl V1) & V2" where V2 may not be present.
3537 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3538   if (Op.getOpcode() == ISD::AND) {
3539     if (isa<ConstantSDNode>(Op.getOperand(1))) {
3540       Mask = Op.getOperand(1);
3541       Op = Op.getOperand(0);
3542     } else {
3543       return false;
3544     }
3545   }
3546
3547   if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3548     Shift = Op;
3549     return true;
3550   }
3551
3552   return false;
3553 }
3554
3555 // Return true if we can prove that, whenever Neg and Pos are both in the
3556 // range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos).  This means that
3557 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3558 //
3559 //     (or (shift1 X, Neg), (shift2 X, Pos))
3560 //
3561 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3562 // in direction shift1 by Neg.  The range [0, OpSize) means that we only need
3563 // to consider shift amounts with defined behavior.
3564 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) {
3565   // If OpSize is a power of 2 then:
3566   //
3567   //  (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1)
3568   //  (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize).
3569   //
3570   // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check
3571   // for the stronger condition:
3572   //
3573   //     Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1)    [A]
3574   //
3575   // for all Neg and Pos.  Since Neg & (OpSize - 1) == Neg' & (OpSize - 1)
3576   // we can just replace Neg with Neg' for the rest of the function.
3577   //
3578   // In other cases we check for the even stronger condition:
3579   //
3580   //     Neg == OpSize - Pos                                    [B]
3581   //
3582   // for all Neg and Pos.  Note that the (or ...) then invokes undefined
3583   // behavior if Pos == 0 (and consequently Neg == OpSize).
3584   //
3585   // We could actually use [A] whenever OpSize is a power of 2, but the
3586   // only extra cases that it would match are those uninteresting ones
3587   // where Neg and Pos are never in range at the same time.  E.g. for
3588   // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3589   // as well as (sub 32, Pos), but:
3590   //
3591   //     (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3592   //
3593   // always invokes undefined behavior for 32-bit X.
3594   //
3595   // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise.
3596   unsigned MaskLoBits = 0;
3597   if (Neg.getOpcode() == ISD::AND &&
3598       isPowerOf2_64(OpSize) &&
3599       Neg.getOperand(1).getOpcode() == ISD::Constant &&
3600       cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) {
3601     Neg = Neg.getOperand(0);
3602     MaskLoBits = Log2_64(OpSize);
3603   }
3604
3605   // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3606   if (Neg.getOpcode() != ISD::SUB)
3607     return 0;
3608   ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0));
3609   if (!NegC)
3610     return 0;
3611   SDValue NegOp1 = Neg.getOperand(1);
3612
3613   // On the RHS of [A], if Pos is Pos' & (OpSize - 1), just replace Pos with
3614   // Pos'.  The truncation is redundant for the purpose of the equality.
3615   if (MaskLoBits &&
3616       Pos.getOpcode() == ISD::AND &&
3617       Pos.getOperand(1).getOpcode() == ISD::Constant &&
3618       cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() == OpSize - 1)
3619     Pos = Pos.getOperand(0);
3620
3621   // The condition we need is now:
3622   //
3623   //     (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask
3624   //
3625   // If NegOp1 == Pos then we need:
3626   //
3627   //              OpSize & Mask == NegC & Mask
3628   //
3629   // (because "x & Mask" is a truncation and distributes through subtraction).
3630   APInt Width;
3631   if (Pos == NegOp1)
3632     Width = NegC->getAPIntValue();
3633   // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3634   // Then the condition we want to prove becomes:
3635   //
3636   //     (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask
3637   //
3638   // which, again because "x & Mask" is a truncation, becomes:
3639   //
3640   //                NegC & Mask == (OpSize - PosC) & Mask
3641   //              OpSize & Mask == (NegC + PosC) & Mask
3642   else if (Pos.getOpcode() == ISD::ADD &&
3643            Pos.getOperand(0) == NegOp1 &&
3644            Pos.getOperand(1).getOpcode() == ISD::Constant)
3645     Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() +
3646              NegC->getAPIntValue());
3647   else
3648     return false;
3649
3650   // Now we just need to check that OpSize & Mask == Width & Mask.
3651   if (MaskLoBits)
3652     // Opsize & Mask is 0 since Mask is Opsize - 1.
3653     return Width.getLoBits(MaskLoBits) == 0;
3654   return Width == OpSize;
3655 }
3656
3657 // A subroutine of MatchRotate used once we have found an OR of two opposite
3658 // shifts of Shifted.  If Neg == <operand size> - Pos then the OR reduces
3659 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3660 // former being preferred if supported.  InnerPos and InnerNeg are Pos and
3661 // Neg with outer conversions stripped away.
3662 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3663                                        SDValue Neg, SDValue InnerPos,
3664                                        SDValue InnerNeg, unsigned PosOpcode,
3665                                        unsigned NegOpcode, SDLoc DL) {
3666   // fold (or (shl x, (*ext y)),
3667   //          (srl x, (*ext (sub 32, y)))) ->
3668   //   (rotl x, y) or (rotr x, (sub 32, y))
3669   //
3670   // fold (or (shl x, (*ext (sub 32, y))),
3671   //          (srl x, (*ext y))) ->
3672   //   (rotr x, y) or (rotl x, (sub 32, y))
3673   EVT VT = Shifted.getValueType();
3674   if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) {
3675     bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3676     return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3677                        HasPos ? Pos : Neg).getNode();
3678   }
3679
3680   return nullptr;
3681 }
3682
3683 // MatchRotate - Handle an 'or' of two operands.  If this is one of the many
3684 // idioms for rotate, and if the target supports rotation instructions, generate
3685 // a rot[lr].
3686 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
3687   // Must be a legal type.  Expanded 'n promoted things won't work with rotates.
3688   EVT VT = LHS.getValueType();
3689   if (!TLI.isTypeLegal(VT)) return nullptr;
3690
3691   // The target must have at least one rotate flavor.
3692   bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3693   bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3694   if (!HasROTL && !HasROTR) return nullptr;
3695
3696   // Match "(X shl/srl V1) & V2" where V2 may not be present.
3697   SDValue LHSShift;   // The shift.
3698   SDValue LHSMask;    // AND value if any.
3699   if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3700     return nullptr; // Not part of a rotate.
3701
3702   SDValue RHSShift;   // The shift.
3703   SDValue RHSMask;    // AND value if any.
3704   if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3705     return nullptr; // Not part of a rotate.
3706
3707   if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3708     return nullptr;   // Not shifting the same value.
3709
3710   if (LHSShift.getOpcode() == RHSShift.getOpcode())
3711     return nullptr;   // Shifts must disagree.
3712
3713   // Canonicalize shl to left side in a shl/srl pair.
3714   if (RHSShift.getOpcode() == ISD::SHL) {
3715     std::swap(LHS, RHS);
3716     std::swap(LHSShift, RHSShift);
3717     std::swap(LHSMask , RHSMask );
3718   }
3719
3720   unsigned OpSizeInBits = VT.getSizeInBits();
3721   SDValue LHSShiftArg = LHSShift.getOperand(0);
3722   SDValue LHSShiftAmt = LHSShift.getOperand(1);
3723   SDValue RHSShiftArg = RHSShift.getOperand(0);
3724   SDValue RHSShiftAmt = RHSShift.getOperand(1);
3725
3726   // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3727   // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
3728   if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3729       RHSShiftAmt.getOpcode() == ISD::Constant) {
3730     uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3731     uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
3732     if ((LShVal + RShVal) != OpSizeInBits)
3733       return nullptr;
3734
3735     SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3736                               LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3737
3738     // If there is an AND of either shifted operand, apply it to the result.
3739     if (LHSMask.getNode() || RHSMask.getNode()) {
3740       APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
3741
3742       if (LHSMask.getNode()) {
3743         APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3744         Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
3745       }
3746       if (RHSMask.getNode()) {
3747         APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3748         Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
3749       }
3750
3751       Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT));
3752     }
3753
3754     return Rot.getNode();
3755   }
3756
3757   // If there is a mask here, and we have a variable shift, we can't be sure
3758   // that we're masking out the right stuff.
3759   if (LHSMask.getNode() || RHSMask.getNode())
3760     return nullptr;
3761
3762   // If the shift amount is sign/zext/any-extended just peel it off.
3763   SDValue LExtOp0 = LHSShiftAmt;
3764   SDValue RExtOp0 = RHSShiftAmt;
3765   if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3766        LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3767        LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3768        LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3769       (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3770        RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3771        RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3772        RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
3773     LExtOp0 = LHSShiftAmt.getOperand(0);
3774     RExtOp0 = RHSShiftAmt.getOperand(0);
3775   }
3776
3777   SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
3778                                    LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
3779   if (TryL)
3780     return TryL;
3781
3782   SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
3783                                    RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
3784   if (TryR)
3785     return TryR;
3786
3787   return nullptr;
3788 }
3789
3790 SDValue DAGCombiner::visitXOR(SDNode *N) {
3791   SDValue N0 = N->getOperand(0);
3792   SDValue N1 = N->getOperand(1);
3793   SDValue LHS, RHS, CC;
3794   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3795   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3796   EVT VT = N0.getValueType();
3797
3798   // fold vector ops
3799   if (VT.isVector()) {
3800     SDValue FoldedVOp = SimplifyVBinOp(N);
3801     if (FoldedVOp.getNode()) return FoldedVOp;
3802
3803     // fold (xor x, 0) -> x, vector edition
3804     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3805       return N1;
3806     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3807       return N0;
3808   }
3809
3810   // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3811   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3812     return DAG.getConstant(0, VT);
3813   // fold (xor x, undef) -> undef
3814   if (N0.getOpcode() == ISD::UNDEF)
3815     return N0;
3816   if (N1.getOpcode() == ISD::UNDEF)
3817     return N1;
3818   // fold (xor c1, c2) -> c1^c2
3819   if (N0C && N1C)
3820     return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
3821   // canonicalize constant to RHS
3822   if (N0C && !N1C)
3823     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
3824   // fold (xor x, 0) -> x
3825   if (N1C && N1C->isNullValue())
3826     return N0;
3827   // reassociate xor
3828   SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1);
3829   if (RXOR.getNode())
3830     return RXOR;
3831
3832   // fold !(x cc y) -> (x !cc y)
3833   if (TLI.isConstTrueVal(N1.getNode()) && isSetCCEquivalent(N0, LHS, RHS, CC)) {
3834     bool isInt = LHS.getValueType().isInteger();
3835     ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3836                                                isInt);
3837
3838     if (!LegalOperations ||
3839         TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
3840       switch (N0.getOpcode()) {
3841       default:
3842         llvm_unreachable("Unhandled SetCC Equivalent!");
3843       case ISD::SETCC:
3844         return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
3845       case ISD::SELECT_CC:
3846         return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
3847                                N0.getOperand(3), NotCC);
3848       }
3849     }
3850   }
3851
3852   // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
3853   if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
3854       N0.getNode()->hasOneUse() &&
3855       isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
3856     SDValue V = N0.getOperand(0);
3857     V = DAG.getNode(ISD::XOR, SDLoc(N0), V.getValueType(), V,
3858                     DAG.getConstant(1, V.getValueType()));
3859     AddToWorklist(V.getNode());
3860     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
3861   }
3862
3863   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
3864   if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
3865       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3866     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3867     if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
3868       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3869       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3870       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3871       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
3872       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3873     }
3874   }
3875   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
3876   if (N1C && N1C->isAllOnesValue() &&
3877       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3878     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3879     if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
3880       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3881       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3882       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3883       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
3884       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3885     }
3886   }
3887   // fold (xor (and x, y), y) -> (and (not x), y)
3888   if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3889       N0->getOperand(1) == N1) {
3890     SDValue X = N0->getOperand(0);
3891     SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
3892     AddToWorklist(NotX.getNode());
3893     return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
3894   }
3895   // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
3896   if (N1C && N0.getOpcode() == ISD::XOR) {
3897     ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
3898     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3899     if (N00C)
3900       return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(1),
3901                          DAG.getConstant(N1C->getAPIntValue() ^
3902                                          N00C->getAPIntValue(), VT));
3903     if (N01C)
3904       return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(0),
3905                          DAG.getConstant(N1C->getAPIntValue() ^
3906                                          N01C->getAPIntValue(), VT));
3907   }
3908   // fold (xor x, x) -> 0
3909   if (N0 == N1)
3910     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
3911
3912   // Simplify: xor (op x...), (op y...)  -> (op (xor x, y))
3913   if (N0.getOpcode() == N1.getOpcode()) {
3914     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3915     if (Tmp.getNode()) return Tmp;
3916   }
3917
3918   // Simplify the expression using non-local knowledge.
3919   if (!VT.isVector() &&
3920       SimplifyDemandedBits(SDValue(N, 0)))
3921     return SDValue(N, 0);
3922
3923   return SDValue();
3924 }
3925
3926 /// Handle transforms common to the three shifts, when the shift amount is a
3927 /// constant.
3928 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
3929   // We can't and shouldn't fold opaque constants.
3930   if (Amt->isOpaque())
3931     return SDValue();
3932
3933   SDNode *LHS = N->getOperand(0).getNode();
3934   if (!LHS->hasOneUse()) return SDValue();
3935
3936   // We want to pull some binops through shifts, so that we have (and (shift))
3937   // instead of (shift (and)), likewise for add, or, xor, etc.  This sort of
3938   // thing happens with address calculations, so it's important to canonicalize
3939   // it.
3940   bool HighBitSet = false;  // Can we transform this if the high bit is set?
3941
3942   switch (LHS->getOpcode()) {
3943   default: return SDValue();
3944   case ISD::OR:
3945   case ISD::XOR:
3946     HighBitSet = false; // We can only transform sra if the high bit is clear.
3947     break;
3948   case ISD::AND:
3949     HighBitSet = true;  // We can only transform sra if the high bit is set.
3950     break;
3951   case ISD::ADD:
3952     if (N->getOpcode() != ISD::SHL)
3953       return SDValue(); // only shl(add) not sr[al](add).
3954     HighBitSet = false; // We can only transform sra if the high bit is clear.
3955     break;
3956   }
3957
3958   // We require the RHS of the binop to be a constant and not opaque as well.
3959   ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
3960   if (!BinOpCst || BinOpCst->isOpaque()) return SDValue();
3961
3962   // FIXME: disable this unless the input to the binop is a shift by a constant.
3963   // If it is not a shift, it pessimizes some common cases like:
3964   //
3965   //    void foo(int *X, int i) { X[i & 1235] = 1; }
3966   //    int bar(int *X, int i) { return X[i & 255]; }
3967   SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
3968   if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
3969        BinOpLHSVal->getOpcode() != ISD::SRA &&
3970        BinOpLHSVal->getOpcode() != ISD::SRL) ||
3971       !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
3972     return SDValue();
3973
3974   EVT VT = N->getValueType(0);
3975
3976   // If this is a signed shift right, and the high bit is modified by the
3977   // logical operation, do not perform the transformation. The highBitSet
3978   // boolean indicates the value of the high bit of the constant which would
3979   // cause it to be modified for this operation.
3980   if (N->getOpcode() == ISD::SRA) {
3981     bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
3982     if (BinOpRHSSignSet != HighBitSet)
3983       return SDValue();
3984   }
3985
3986   if (!TLI.isDesirableToCommuteWithShift(LHS))
3987     return SDValue();
3988
3989   // Fold the constants, shifting the binop RHS by the shift amount.
3990   SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
3991                                N->getValueType(0),
3992                                LHS->getOperand(1), N->getOperand(1));
3993   assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
3994
3995   // Create the new shift.
3996   SDValue NewShift = DAG.getNode(N->getOpcode(),
3997                                  SDLoc(LHS->getOperand(0)),
3998                                  VT, LHS->getOperand(0), N->getOperand(1));
3999
4000   // Create the new binop.
4001   return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
4002 }
4003
4004 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
4005   assert(N->getOpcode() == ISD::TRUNCATE);
4006   assert(N->getOperand(0).getOpcode() == ISD::AND);
4007
4008   // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
4009   if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
4010     SDValue N01 = N->getOperand(0).getOperand(1);
4011
4012     if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
4013       EVT TruncVT = N->getValueType(0);
4014       SDValue N00 = N->getOperand(0).getOperand(0);
4015       APInt TruncC = N01C->getAPIntValue();
4016       TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
4017
4018       return DAG.getNode(ISD::AND, SDLoc(N), TruncVT,
4019                          DAG.getNode(ISD::TRUNCATE, SDLoc(N), TruncVT, N00),
4020                          DAG.getConstant(TruncC, TruncVT));
4021     }
4022   }
4023
4024   return SDValue();
4025 }
4026
4027 SDValue DAGCombiner::visitRotate(SDNode *N) {
4028   // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
4029   if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
4030       N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
4031     SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode());
4032     if (NewOp1.getNode())
4033       return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
4034                          N->getOperand(0), NewOp1);
4035   }
4036   return SDValue();
4037 }
4038
4039 SDValue DAGCombiner::visitSHL(SDNode *N) {
4040   SDValue N0 = N->getOperand(0);
4041   SDValue N1 = N->getOperand(1);
4042   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4043   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4044   EVT VT = N0.getValueType();
4045   unsigned OpSizeInBits = VT.getScalarSizeInBits();
4046
4047   // fold vector ops
4048   if (VT.isVector()) {
4049     SDValue FoldedVOp = SimplifyVBinOp(N);
4050     if (FoldedVOp.getNode()) return FoldedVOp;
4051
4052     BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
4053     // If setcc produces all-one true value then:
4054     // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
4055     if (N1CV && N1CV->isConstant()) {
4056       if (N0.getOpcode() == ISD::AND) {
4057         SDValue N00 = N0->getOperand(0);
4058         SDValue N01 = N0->getOperand(1);
4059         BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
4060
4061         if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
4062             TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
4063                 TargetLowering::ZeroOrNegativeOneBooleanContent) {
4064           SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, VT, N01CV, N1CV);
4065           if (C.getNode())
4066             return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
4067         }
4068       } else {
4069         N1C = isConstOrConstSplat(N1);
4070       }
4071     }
4072   }
4073
4074   // fold (shl c1, c2) -> c1<<c2
4075   if (N0C && N1C)
4076     return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
4077   // fold (shl 0, x) -> 0
4078   if (N0C && N0C->isNullValue())
4079     return N0;
4080   // fold (shl x, c >= size(x)) -> undef
4081   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4082     return DAG.getUNDEF(VT);
4083   // fold (shl x, 0) -> x
4084   if (N1C && N1C->isNullValue())
4085     return N0;
4086   // fold (shl undef, x) -> 0
4087   if (N0.getOpcode() == ISD::UNDEF)
4088     return DAG.getConstant(0, VT);
4089   // if (shl x, c) is known to be zero, return 0
4090   if (DAG.MaskedValueIsZero(SDValue(N, 0),
4091                             APInt::getAllOnesValue(OpSizeInBits)))
4092     return DAG.getConstant(0, VT);
4093   // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
4094   if (N1.getOpcode() == ISD::TRUNCATE &&
4095       N1.getOperand(0).getOpcode() == ISD::AND) {
4096     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4097     if (NewOp1.getNode())
4098       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
4099   }
4100
4101   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4102     return SDValue(N, 0);
4103
4104   // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
4105   if (N1C && N0.getOpcode() == ISD::SHL) {
4106     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4107       uint64_t c1 = N0C1->getZExtValue();
4108       uint64_t c2 = N1C->getZExtValue();
4109       if (c1 + c2 >= OpSizeInBits)
4110         return DAG.getConstant(0, VT);
4111       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4112                          DAG.getConstant(c1 + c2, N1.getValueType()));
4113     }
4114   }
4115
4116   // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4117   // For this to be valid, the second form must not preserve any of the bits
4118   // that are shifted out by the inner shift in the first form.  This means
4119   // the outer shift size must be >= the number of bits added by the ext.
4120   // As a corollary, we don't care what kind of ext it is.
4121   if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4122               N0.getOpcode() == ISD::ANY_EXTEND ||
4123               N0.getOpcode() == ISD::SIGN_EXTEND) &&
4124       N0.getOperand(0).getOpcode() == ISD::SHL) {
4125     SDValue N0Op0 = N0.getOperand(0);
4126     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4127       uint64_t c1 = N0Op0C1->getZExtValue();
4128       uint64_t c2 = N1C->getZExtValue();
4129       EVT InnerShiftVT = N0Op0.getValueType();
4130       uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4131       if (c2 >= OpSizeInBits - InnerShiftSize) {
4132         if (c1 + c2 >= OpSizeInBits)
4133           return DAG.getConstant(0, VT);
4134         return DAG.getNode(ISD::SHL, SDLoc(N0), VT,
4135                            DAG.getNode(N0.getOpcode(), SDLoc(N0), VT,
4136                                        N0Op0->getOperand(0)),
4137                            DAG.getConstant(c1 + c2, N1.getValueType()));
4138       }
4139     }
4140   }
4141
4142   // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4143   // Only fold this if the inner zext has no other uses to avoid increasing
4144   // the total number of instructions.
4145   if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
4146       N0.getOperand(0).getOpcode() == ISD::SRL) {
4147     SDValue N0Op0 = N0.getOperand(0);
4148     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4149       uint64_t c1 = N0Op0C1->getZExtValue();
4150       if (c1 < VT.getScalarSizeInBits()) {
4151         uint64_t c2 = N1C->getZExtValue();
4152         if (c1 == c2) {
4153           SDValue NewOp0 = N0.getOperand(0);
4154           EVT CountVT = NewOp0.getOperand(1).getValueType();
4155           SDValue NewSHL = DAG.getNode(ISD::SHL, SDLoc(N), NewOp0.getValueType(),
4156                                        NewOp0, DAG.getConstant(c2, CountVT));
4157           AddToWorklist(NewSHL.getNode());
4158           return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4159         }
4160       }
4161     }
4162   }
4163
4164   // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4165   //                               (and (srl x, (sub c1, c2), MASK)
4166   // Only fold this if the inner shift has no other uses -- if it does, folding
4167   // this will increase the total number of instructions.
4168   if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4169     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4170       uint64_t c1 = N0C1->getZExtValue();
4171       if (c1 < OpSizeInBits) {
4172         uint64_t c2 = N1C->getZExtValue();
4173         APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4174         SDValue Shift;
4175         if (c2 > c1) {
4176           Mask = Mask.shl(c2 - c1);
4177           Shift = DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4178                               DAG.getConstant(c2 - c1, N1.getValueType()));
4179         } else {
4180           Mask = Mask.lshr(c1 - c2);
4181           Shift = DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4182                               DAG.getConstant(c1 - c2, N1.getValueType()));
4183         }
4184         return DAG.getNode(ISD::AND, SDLoc(N0), VT, Shift,
4185                            DAG.getConstant(Mask, VT));
4186       }
4187     }
4188   }
4189   // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
4190   if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
4191     unsigned BitSize = VT.getScalarSizeInBits();
4192     SDValue HiBitsMask =
4193       DAG.getConstant(APInt::getHighBitsSet(BitSize,
4194                                             BitSize - N1C->getZExtValue()), VT);
4195     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4196                        HiBitsMask);
4197   }
4198
4199   // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
4200   // Variant of version done on multiply, except mul by a power of 2 is turned
4201   // into a shift.
4202   APInt Val;
4203   if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
4204       (isa<ConstantSDNode>(N0.getOperand(1)) ||
4205        isConstantSplatVector(N0.getOperand(1).getNode(), Val))) {
4206     SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1);
4207     SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
4208     return DAG.getNode(ISD::ADD, SDLoc(N), VT, Shl0, Shl1);
4209   }
4210
4211   if (N1C) {
4212     SDValue NewSHL = visitShiftByConstant(N, N1C);
4213     if (NewSHL.getNode())
4214       return NewSHL;
4215   }
4216
4217   return SDValue();
4218 }
4219
4220 SDValue DAGCombiner::visitSRA(SDNode *N) {
4221   SDValue N0 = N->getOperand(0);
4222   SDValue N1 = N->getOperand(1);
4223   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4224   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4225   EVT VT = N0.getValueType();
4226   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4227
4228   // fold vector ops
4229   if (VT.isVector()) {
4230     SDValue FoldedVOp = SimplifyVBinOp(N);
4231     if (FoldedVOp.getNode()) return FoldedVOp;
4232
4233     N1C = isConstOrConstSplat(N1);
4234   }
4235
4236   // fold (sra c1, c2) -> (sra c1, c2)
4237   if (N0C && N1C)
4238     return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
4239   // fold (sra 0, x) -> 0
4240   if (N0C && N0C->isNullValue())
4241     return N0;
4242   // fold (sra -1, x) -> -1
4243   if (N0C && N0C->isAllOnesValue())
4244     return N0;
4245   // fold (sra x, (setge c, size(x))) -> undef
4246   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4247     return DAG.getUNDEF(VT);
4248   // fold (sra x, 0) -> x
4249   if (N1C && N1C->isNullValue())
4250     return N0;
4251   // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4252   // sext_inreg.
4253   if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
4254     unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
4255     EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4256     if (VT.isVector())
4257       ExtVT = EVT::getVectorVT(*DAG.getContext(),
4258                                ExtVT, VT.getVectorNumElements());
4259     if ((!LegalOperations ||
4260          TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
4261       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
4262                          N0.getOperand(0), DAG.getValueType(ExtVT));
4263   }
4264
4265   // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
4266   if (N1C && N0.getOpcode() == ISD::SRA) {
4267     if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
4268       unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
4269       if (Sum >= OpSizeInBits)
4270         Sum = OpSizeInBits - 1;
4271       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0.getOperand(0),
4272                          DAG.getConstant(Sum, N1.getValueType()));
4273     }
4274   }
4275
4276   // fold (sra (shl X, m), (sub result_size, n))
4277   // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
4278   // result_size - n != m.
4279   // If truncate is free for the target sext(shl) is likely to result in better
4280   // code.
4281   if (N0.getOpcode() == ISD::SHL && N1C) {
4282     // Get the two constanst of the shifts, CN0 = m, CN = n.
4283     const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4284     if (N01C) {
4285       LLVMContext &Ctx = *DAG.getContext();
4286       // Determine what the truncate's result bitsize and type would be.
4287       EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4288
4289       if (VT.isVector())
4290         TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4291
4292       // Determine the residual right-shift amount.
4293       signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
4294
4295       // If the shift is not a no-op (in which case this should be just a sign
4296       // extend already), the truncated to type is legal, sign_extend is legal
4297       // on that type, and the truncate to that type is both legal and free,
4298       // perform the transform.
4299       if ((ShiftAmt > 0) &&
4300           TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4301           TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
4302           TLI.isTruncateFree(VT, TruncVT)) {
4303
4304           SDValue Amt = DAG.getConstant(ShiftAmt,
4305               getShiftAmountTy(N0.getOperand(0).getValueType()));
4306           SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), VT,
4307                                       N0.getOperand(0), Amt);
4308           SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), TruncVT,
4309                                       Shift);
4310           return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N),
4311                              N->getValueType(0), Trunc);
4312       }
4313     }
4314   }
4315
4316   // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
4317   if (N1.getOpcode() == ISD::TRUNCATE &&
4318       N1.getOperand(0).getOpcode() == ISD::AND) {
4319     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4320     if (NewOp1.getNode())
4321       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
4322   }
4323
4324   // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
4325   //      if c1 is equal to the number of bits the trunc removes
4326   if (N0.getOpcode() == ISD::TRUNCATE &&
4327       (N0.getOperand(0).getOpcode() == ISD::SRL ||
4328        N0.getOperand(0).getOpcode() == ISD::SRA) &&
4329       N0.getOperand(0).hasOneUse() &&
4330       N0.getOperand(0).getOperand(1).hasOneUse() &&
4331       N1C) {
4332     SDValue N0Op0 = N0.getOperand(0);
4333     if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4334       unsigned LargeShiftVal = LargeShift->getZExtValue();
4335       EVT LargeVT = N0Op0.getValueType();
4336
4337       if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4338         SDValue Amt =
4339           DAG.getConstant(LargeShiftVal + N1C->getZExtValue(),
4340                           getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4341         SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), LargeVT,
4342                                   N0Op0.getOperand(0), Amt);
4343         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, SRA);
4344       }
4345     }
4346   }
4347
4348   // Simplify, based on bits shifted out of the LHS.
4349   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4350     return SDValue(N, 0);
4351
4352
4353   // If the sign bit is known to be zero, switch this to a SRL.
4354   if (DAG.SignBitIsZero(N0))
4355     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
4356
4357   if (N1C) {
4358     SDValue NewSRA = visitShiftByConstant(N, N1C);
4359     if (NewSRA.getNode())
4360       return NewSRA;
4361   }
4362
4363   return SDValue();
4364 }
4365
4366 SDValue DAGCombiner::visitSRL(SDNode *N) {
4367   SDValue N0 = N->getOperand(0);
4368   SDValue N1 = N->getOperand(1);
4369   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4370   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4371   EVT VT = N0.getValueType();
4372   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4373
4374   // fold vector ops
4375   if (VT.isVector()) {
4376     SDValue FoldedVOp = SimplifyVBinOp(N);
4377     if (FoldedVOp.getNode()) return FoldedVOp;
4378
4379     N1C = isConstOrConstSplat(N1);
4380   }
4381
4382   // fold (srl c1, c2) -> c1 >>u c2
4383   if (N0C && N1C)
4384     return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C);
4385   // fold (srl 0, x) -> 0
4386   if (N0C && N0C->isNullValue())
4387     return N0;
4388   // fold (srl x, c >= size(x)) -> undef
4389   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4390     return DAG.getUNDEF(VT);
4391   // fold (srl x, 0) -> x
4392   if (N1C && N1C->isNullValue())
4393     return N0;
4394   // if (srl x, c) is known to be zero, return 0
4395   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4396                                    APInt::getAllOnesValue(OpSizeInBits)))
4397     return DAG.getConstant(0, VT);
4398
4399   // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
4400   if (N1C && N0.getOpcode() == ISD::SRL) {
4401     if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
4402       uint64_t c1 = N01C->getZExtValue();
4403       uint64_t c2 = N1C->getZExtValue();
4404       if (c1 + c2 >= OpSizeInBits)
4405         return DAG.getConstant(0, VT);
4406       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4407                          DAG.getConstant(c1 + c2, N1.getValueType()));
4408     }
4409   }
4410
4411   // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4412   if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4413       N0.getOperand(0).getOpcode() == ISD::SRL &&
4414       isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4415     uint64_t c1 =
4416       cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4417     uint64_t c2 = N1C->getZExtValue();
4418     EVT InnerShiftVT = N0.getOperand(0).getValueType();
4419     EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4420     uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
4421     // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4422     if (c1 + OpSizeInBits == InnerShiftSize) {
4423       if (c1 + c2 >= InnerShiftSize)
4424         return DAG.getConstant(0, VT);
4425       return DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT,
4426                          DAG.getNode(ISD::SRL, SDLoc(N0), InnerShiftVT,
4427                                      N0.getOperand(0)->getOperand(0),
4428                                      DAG.getConstant(c1 + c2, ShiftCountVT)));
4429     }
4430   }
4431
4432   // fold (srl (shl x, c), c) -> (and x, cst2)
4433   if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4434     unsigned BitSize = N0.getScalarValueSizeInBits();
4435     if (BitSize <= 64) {
4436       uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4437       return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4438                          DAG.getConstant(~0ULL >> ShAmt, VT));
4439     }
4440   }
4441
4442   // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4443   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4444     // Shifting in all undef bits?
4445     EVT SmallVT = N0.getOperand(0).getValueType();
4446     unsigned BitSize = SmallVT.getScalarSizeInBits();
4447     if (N1C->getZExtValue() >= BitSize)
4448       return DAG.getUNDEF(VT);
4449
4450     if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4451       uint64_t ShiftAmt = N1C->getZExtValue();
4452       SDValue SmallShift = DAG.getNode(ISD::SRL, SDLoc(N0), SmallVT,
4453                                        N0.getOperand(0),
4454                           DAG.getConstant(ShiftAmt, getShiftAmountTy(SmallVT)));
4455       AddToWorklist(SmallShift.getNode());
4456       APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
4457       return DAG.getNode(ISD::AND, SDLoc(N), VT,
4458                          DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, SmallShift),
4459                          DAG.getConstant(Mask, VT));
4460     }
4461   }
4462
4463   // fold (srl (sra X, Y), 31) -> (srl X, 31).  This srl only looks at the sign
4464   // bit, which is unmodified by sra.
4465   if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
4466     if (N0.getOpcode() == ISD::SRA)
4467       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4468   }
4469
4470   // fold (srl (ctlz x), "5") -> x  iff x has one bit set (the low bit).
4471   if (N1C && N0.getOpcode() == ISD::CTLZ &&
4472       N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
4473     APInt KnownZero, KnownOne;
4474     DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne);
4475
4476     // If any of the input bits are KnownOne, then the input couldn't be all
4477     // zeros, thus the result of the srl will always be zero.
4478     if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
4479
4480     // If all of the bits input the to ctlz node are known to be zero, then
4481     // the result of the ctlz is "32" and the result of the shift is one.
4482     APInt UnknownBits = ~KnownZero;
4483     if (UnknownBits == 0) return DAG.getConstant(1, VT);
4484
4485     // Otherwise, check to see if there is exactly one bit input to the ctlz.
4486     if ((UnknownBits & (UnknownBits - 1)) == 0) {
4487       // Okay, we know that only that the single bit specified by UnknownBits
4488       // could be set on input to the CTLZ node. If this bit is set, the SRL
4489       // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4490       // to an SRL/XOR pair, which is likely to simplify more.
4491       unsigned ShAmt = UnknownBits.countTrailingZeros();
4492       SDValue Op = N0.getOperand(0);
4493
4494       if (ShAmt) {
4495         Op = DAG.getNode(ISD::SRL, SDLoc(N0), VT, Op,
4496                   DAG.getConstant(ShAmt, getShiftAmountTy(Op.getValueType())));
4497         AddToWorklist(Op.getNode());
4498       }
4499
4500       return DAG.getNode(ISD::XOR, SDLoc(N), VT,
4501                          Op, DAG.getConstant(1, VT));
4502     }
4503   }
4504
4505   // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4506   if (N1.getOpcode() == ISD::TRUNCATE &&
4507       N1.getOperand(0).getOpcode() == ISD::AND) {
4508     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4509     if (NewOp1.getNode())
4510       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
4511   }
4512
4513   // fold operands of srl based on knowledge that the low bits are not
4514   // demanded.
4515   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4516     return SDValue(N, 0);
4517
4518   if (N1C) {
4519     SDValue NewSRL = visitShiftByConstant(N, N1C);
4520     if (NewSRL.getNode())
4521       return NewSRL;
4522   }
4523
4524   // Attempt to convert a srl of a load into a narrower zero-extending load.
4525   SDValue NarrowLoad = ReduceLoadWidth(N);
4526   if (NarrowLoad.getNode())
4527     return NarrowLoad;
4528
4529   // Here is a common situation. We want to optimize:
4530   //
4531   //   %a = ...
4532   //   %b = and i32 %a, 2
4533   //   %c = srl i32 %b, 1
4534   //   brcond i32 %c ...
4535   //
4536   // into
4537   //
4538   //   %a = ...
4539   //   %b = and %a, 2
4540   //   %c = setcc eq %b, 0
4541   //   brcond %c ...
4542   //
4543   // However when after the source operand of SRL is optimized into AND, the SRL
4544   // itself may not be optimized further. Look for it and add the BRCOND into
4545   // the worklist.
4546   if (N->hasOneUse()) {
4547     SDNode *Use = *N->use_begin();
4548     if (Use->getOpcode() == ISD::BRCOND)
4549       AddToWorklist(Use);
4550     else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4551       // Also look pass the truncate.
4552       Use = *Use->use_begin();
4553       if (Use->getOpcode() == ISD::BRCOND)
4554         AddToWorklist(Use);
4555     }
4556   }
4557
4558   return SDValue();
4559 }
4560
4561 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4562   SDValue N0 = N->getOperand(0);
4563   EVT VT = N->getValueType(0);
4564
4565   // fold (ctlz c1) -> c2
4566   if (isa<ConstantSDNode>(N0))
4567     return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
4568   return SDValue();
4569 }
4570
4571 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4572   SDValue N0 = N->getOperand(0);
4573   EVT VT = N->getValueType(0);
4574
4575   // fold (ctlz_zero_undef c1) -> c2
4576   if (isa<ConstantSDNode>(N0))
4577     return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4578   return SDValue();
4579 }
4580
4581 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4582   SDValue N0 = N->getOperand(0);
4583   EVT VT = N->getValueType(0);
4584
4585   // fold (cttz c1) -> c2
4586   if (isa<ConstantSDNode>(N0))
4587     return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
4588   return SDValue();
4589 }
4590
4591 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4592   SDValue N0 = N->getOperand(0);
4593   EVT VT = N->getValueType(0);
4594
4595   // fold (cttz_zero_undef c1) -> c2
4596   if (isa<ConstantSDNode>(N0))
4597     return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4598   return SDValue();
4599 }
4600
4601 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4602   SDValue N0 = N->getOperand(0);
4603   EVT VT = N->getValueType(0);
4604
4605   // fold (ctpop c1) -> c2
4606   if (isa<ConstantSDNode>(N0))
4607     return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
4608   return SDValue();
4609 }
4610
4611 SDValue DAGCombiner::visitSELECT(SDNode *N) {
4612   SDValue N0 = N->getOperand(0);
4613   SDValue N1 = N->getOperand(1);
4614   SDValue N2 = N->getOperand(2);
4615   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4616   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4617   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
4618   EVT VT = N->getValueType(0);
4619   EVT VT0 = N0.getValueType();
4620
4621   // fold (select C, X, X) -> X
4622   if (N1 == N2)
4623     return N1;
4624   // fold (select true, X, Y) -> X
4625   if (N0C && !N0C->isNullValue())
4626     return N1;
4627   // fold (select false, X, Y) -> Y
4628   if (N0C && N0C->isNullValue())
4629     return N2;
4630   // fold (select C, 1, X) -> (or C, X)
4631   if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
4632     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4633   // fold (select C, 0, 1) -> (xor C, 1)
4634   // We can't do this reliably if integer based booleans have different contents
4635   // to floating point based booleans. This is because we can't tell whether we
4636   // have an integer-based boolean or a floating-point-based boolean unless we
4637   // can find the SETCC that produced it and inspect its operands. This is
4638   // fairly easy if C is the SETCC node, but it can potentially be
4639   // undiscoverable (or not reasonably discoverable). For example, it could be
4640   // in another basic block or it could require searching a complicated
4641   // expression.
4642   if (VT.isInteger() &&
4643       (VT0 == MVT::i1 || (VT0.isInteger() &&
4644                           TLI.getBooleanContents(false, false) ==
4645                               TLI.getBooleanContents(false, true) &&
4646                           TLI.getBooleanContents(false, false) ==
4647                               TargetLowering::ZeroOrOneBooleanContent)) &&
4648       N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
4649     SDValue XORNode;
4650     if (VT == VT0)
4651       return DAG.getNode(ISD::XOR, SDLoc(N), VT0,
4652                          N0, DAG.getConstant(1, VT0));
4653     XORNode = DAG.getNode(ISD::XOR, SDLoc(N0), VT0,
4654                           N0, DAG.getConstant(1, VT0));
4655     AddToWorklist(XORNode.getNode());
4656     if (VT.bitsGT(VT0))
4657       return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4658     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
4659   }
4660   // fold (select C, 0, X) -> (and (not C), X)
4661   if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
4662     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4663     AddToWorklist(NOTNode.getNode());
4664     return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
4665   }
4666   // fold (select C, X, 1) -> (or (not C), X)
4667   if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
4668     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4669     AddToWorklist(NOTNode.getNode());
4670     return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
4671   }
4672   // fold (select C, X, 0) -> (and C, X)
4673   if (VT == MVT::i1 && N2C && N2C->isNullValue())
4674     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4675   // fold (select X, X, Y) -> (or X, Y)
4676   // fold (select X, 1, Y) -> (or X, Y)
4677   if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
4678     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4679   // fold (select X, Y, X) -> (and X, Y)
4680   // fold (select X, Y, 0) -> (and X, Y)
4681   if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
4682     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4683
4684   // If we can fold this based on the true/false value, do so.
4685   if (SimplifySelectOps(N, N1, N2))
4686     return SDValue(N, 0);  // Don't revisit N.
4687
4688   // fold selects based on a setcc into other things, such as min/max/abs
4689   if (N0.getOpcode() == ISD::SETCC) {
4690     if ((!LegalOperations &&
4691          TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
4692         TLI.isOperationLegal(ISD::SELECT_CC, VT))
4693       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
4694                          N0.getOperand(0), N0.getOperand(1),
4695                          N1, N2, N0.getOperand(2));
4696     return SimplifySelect(SDLoc(N), N0, N1, N2);
4697   }
4698
4699   return SDValue();
4700 }
4701
4702 static
4703 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
4704   SDLoc DL(N);
4705   EVT LoVT, HiVT;
4706   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
4707
4708   // Split the inputs.
4709   SDValue Lo, Hi, LL, LH, RL, RH;
4710   std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
4711   std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
4712
4713   Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
4714   Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
4715
4716   return std::make_pair(Lo, Hi);
4717 }
4718
4719 // This function assumes all the vselect's arguments are CONCAT_VECTOR
4720 // nodes and that the condition is a BV of ConstantSDNodes (or undefs).
4721 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
4722   SDLoc dl(N);
4723   SDValue Cond = N->getOperand(0);
4724   SDValue LHS = N->getOperand(1);
4725   SDValue RHS = N->getOperand(2);
4726   EVT VT = N->getValueType(0);
4727   int NumElems = VT.getVectorNumElements();
4728   assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
4729          RHS.getOpcode() == ISD::CONCAT_VECTORS &&
4730          Cond.getOpcode() == ISD::BUILD_VECTOR);
4731
4732   // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about
4733   // binary ones here.
4734   if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2)
4735     return SDValue();
4736
4737   // We're sure we have an even number of elements due to the
4738   // concat_vectors we have as arguments to vselect.
4739   // Skip BV elements until we find one that's not an UNDEF
4740   // After we find an UNDEF element, keep looping until we get to half the
4741   // length of the BV and see if all the non-undef nodes are the same.
4742   ConstantSDNode *BottomHalf = nullptr;
4743   for (int i = 0; i < NumElems / 2; ++i) {
4744     if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
4745       continue;
4746
4747     if (BottomHalf == nullptr)
4748       BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
4749     else if (Cond->getOperand(i).getNode() != BottomHalf)
4750       return SDValue();
4751   }
4752
4753   // Do the same for the second half of the BuildVector
4754   ConstantSDNode *TopHalf = nullptr;
4755   for (int i = NumElems / 2; i < NumElems; ++i) {
4756     if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
4757       continue;
4758
4759     if (TopHalf == nullptr)
4760       TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
4761     else if (Cond->getOperand(i).getNode() != TopHalf)
4762       return SDValue();
4763   }
4764
4765   assert(TopHalf && BottomHalf &&
4766          "One half of the selector was all UNDEFs and the other was all the "
4767          "same value. This should have been addressed before this function.");
4768   return DAG.getNode(
4769       ISD::CONCAT_VECTORS, dl, VT,
4770       BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
4771       TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
4772 }
4773
4774 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
4775   SDValue N0 = N->getOperand(0);
4776   SDValue N1 = N->getOperand(1);
4777   SDValue N2 = N->getOperand(2);
4778   SDLoc DL(N);
4779
4780   // Canonicalize integer abs.
4781   // vselect (setg[te] X,  0),  X, -X ->
4782   // vselect (setgt    X, -1),  X, -X ->
4783   // vselect (setl[te] X,  0), -X,  X ->
4784   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
4785   if (N0.getOpcode() == ISD::SETCC) {
4786     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4787     ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4788     bool isAbs = false;
4789     bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
4790
4791     if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
4792          (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
4793         N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
4794       isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
4795     else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
4796              N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
4797       isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
4798
4799     if (isAbs) {
4800       EVT VT = LHS.getValueType();
4801       SDValue Shift = DAG.getNode(
4802           ISD::SRA, DL, VT, LHS,
4803           DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, VT));
4804       SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
4805       AddToWorklist(Shift.getNode());
4806       AddToWorklist(Add.getNode());
4807       return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
4808     }
4809   }
4810
4811   // If the VSELECT result requires splitting and the mask is provided by a
4812   // SETCC, then split both nodes and its operands before legalization. This
4813   // prevents the type legalizer from unrolling SETCC into scalar comparisons
4814   // and enables future optimizations (e.g. min/max pattern matching on X86).
4815   if (N0.getOpcode() == ISD::SETCC) {
4816     EVT VT = N->getValueType(0);
4817
4818     // Check if any splitting is required.
4819     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
4820         TargetLowering::TypeSplitVector)
4821       return SDValue();
4822
4823     SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
4824     std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
4825     std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
4826     std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
4827
4828     Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
4829     Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
4830
4831     // Add the new VSELECT nodes to the work list in case they need to be split
4832     // again.
4833     AddToWorklist(Lo.getNode());
4834     AddToWorklist(Hi.getNode());
4835
4836     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
4837   }
4838
4839   // Fold (vselect (build_vector all_ones), N1, N2) -> N1
4840   if (ISD::isBuildVectorAllOnes(N0.getNode()))
4841     return N1;
4842   // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
4843   if (ISD::isBuildVectorAllZeros(N0.getNode()))
4844     return N2;
4845
4846   // The ConvertSelectToConcatVector function is assuming both the above
4847   // checks for (vselect (build_vector all{ones,zeros) ...) have been made
4848   // and addressed.
4849   if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
4850       N2.getOpcode() == ISD::CONCAT_VECTORS &&
4851       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
4852     SDValue CV = ConvertSelectToConcatVector(N, DAG);
4853     if (CV.getNode())
4854       return CV;
4855   }
4856
4857   return SDValue();
4858 }
4859
4860 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
4861   SDValue N0 = N->getOperand(0);
4862   SDValue N1 = N->getOperand(1);
4863   SDValue N2 = N->getOperand(2);
4864   SDValue N3 = N->getOperand(3);
4865   SDValue N4 = N->getOperand(4);
4866   ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
4867
4868   // fold select_cc lhs, rhs, x, x, cc -> x
4869   if (N2 == N3)
4870     return N2;
4871
4872   // Determine if the condition we're dealing with is constant
4873   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
4874                               N0, N1, CC, SDLoc(N), false);
4875   if (SCC.getNode()) {
4876     AddToWorklist(SCC.getNode());
4877
4878     if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
4879       if (!SCCC->isNullValue())
4880         return N2;    // cond always true -> true val
4881       else
4882         return N3;    // cond always false -> false val
4883     }
4884
4885     // Fold to a simpler select_cc
4886     if (SCC.getOpcode() == ISD::SETCC)
4887       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
4888                          SCC.getOperand(0), SCC.getOperand(1), N2, N3,
4889                          SCC.getOperand(2));
4890   }
4891
4892   // If we can fold this based on the true/false value, do so.
4893   if (SimplifySelectOps(N, N2, N3))
4894     return SDValue(N, 0);  // Don't revisit N.
4895
4896   // fold select_cc into other things, such as min/max/abs
4897   return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
4898 }
4899
4900 SDValue DAGCombiner::visitSETCC(SDNode *N) {
4901   return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
4902                        cast<CondCodeSDNode>(N->getOperand(2))->get(),
4903                        SDLoc(N));
4904 }
4905
4906 // tryToFoldExtendOfConstant - Try to fold a sext/zext/aext
4907 // dag node into a ConstantSDNode or a build_vector of constants.
4908 // This function is called by the DAGCombiner when visiting sext/zext/aext
4909 // dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
4910 // Vector extends are not folded if operations are legal; this is to
4911 // avoid introducing illegal build_vector dag nodes.
4912 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
4913                                          SelectionDAG &DAG, bool LegalTypes,
4914                                          bool LegalOperations) {
4915   unsigned Opcode = N->getOpcode();
4916   SDValue N0 = N->getOperand(0);
4917   EVT VT = N->getValueType(0);
4918
4919   assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
4920          Opcode == ISD::ANY_EXTEND) && "Expected EXTEND dag node in input!");
4921
4922   // fold (sext c1) -> c1
4923   // fold (zext c1) -> c1
4924   // fold (aext c1) -> c1
4925   if (isa<ConstantSDNode>(N0))
4926     return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
4927
4928   // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
4929   // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
4930   // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
4931   EVT SVT = VT.getScalarType();
4932   if (!(VT.isVector() &&
4933       (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
4934       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
4935     return nullptr;
4936
4937   // We can fold this node into a build_vector.
4938   unsigned VTBits = SVT.getSizeInBits();
4939   unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
4940   unsigned ShAmt = VTBits - EVTBits;
4941   SmallVector<SDValue, 8> Elts;
4942   unsigned NumElts = N0->getNumOperands();
4943   SDLoc DL(N);
4944
4945   for (unsigned i=0; i != NumElts; ++i) {
4946     SDValue Op = N0->getOperand(i);
4947     if (Op->getOpcode() == ISD::UNDEF) {
4948       Elts.push_back(DAG.getUNDEF(SVT));
4949       continue;
4950     }
4951
4952     ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
4953     const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
4954     if (Opcode == ISD::SIGN_EXTEND)
4955       Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
4956                                      SVT));
4957     else
4958       Elts.push_back(DAG.getConstant(C.shl(ShAmt).lshr(ShAmt).getZExtValue(),
4959                                      SVT));
4960   }
4961
4962   return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts).getNode();
4963 }
4964
4965 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
4966 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
4967 // transformation. Returns true if extension are possible and the above
4968 // mentioned transformation is profitable.
4969 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
4970                                     unsigned ExtOpc,
4971                                     SmallVectorImpl<SDNode *> &ExtendNodes,
4972                                     const TargetLowering &TLI) {
4973   bool HasCopyToRegUses = false;
4974   bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
4975   for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
4976                             UE = N0.getNode()->use_end();
4977        UI != UE; ++UI) {
4978     SDNode *User = *UI;
4979     if (User == N)
4980       continue;
4981     if (UI.getUse().getResNo() != N0.getResNo())
4982       continue;
4983     // FIXME: Only extend SETCC N, N and SETCC N, c for now.
4984     if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
4985       ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
4986       if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
4987         // Sign bits will be lost after a zext.
4988         return false;
4989       bool Add = false;
4990       for (unsigned i = 0; i != 2; ++i) {
4991         SDValue UseOp = User->getOperand(i);
4992         if (UseOp == N0)
4993           continue;
4994         if (!isa<ConstantSDNode>(UseOp))
4995           return false;
4996         Add = true;
4997       }
4998       if (Add)
4999         ExtendNodes.push_back(User);
5000       continue;
5001     }
5002     // If truncates aren't free and there are users we can't
5003     // extend, it isn't worthwhile.
5004     if (!isTruncFree)
5005       return false;
5006     // Remember if this value is live-out.
5007     if (User->getOpcode() == ISD::CopyToReg)
5008       HasCopyToRegUses = true;
5009   }
5010
5011   if (HasCopyToRegUses) {
5012     bool BothLiveOut = false;
5013     for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
5014          UI != UE; ++UI) {
5015       SDUse &Use = UI.getUse();
5016       if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
5017         BothLiveOut = true;
5018         break;
5019       }
5020     }
5021     if (BothLiveOut)
5022       // Both unextended and extended values are live out. There had better be
5023       // a good reason for the transformation.
5024       return ExtendNodes.size();
5025   }
5026   return true;
5027 }
5028
5029 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
5030                                   SDValue Trunc, SDValue ExtLoad, SDLoc DL,
5031                                   ISD::NodeType ExtType) {
5032   // Extend SetCC uses if necessary.
5033   for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
5034     SDNode *SetCC = SetCCs[i];
5035     SmallVector<SDValue, 4> Ops;
5036
5037     for (unsigned j = 0; j != 2; ++j) {
5038       SDValue SOp = SetCC->getOperand(j);
5039       if (SOp == Trunc)
5040         Ops.push_back(ExtLoad);
5041       else
5042         Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
5043     }
5044
5045     Ops.push_back(SetCC->getOperand(2));
5046     CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
5047   }
5048 }
5049
5050 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
5051   SDValue N0 = N->getOperand(0);
5052   EVT VT = N->getValueType(0);
5053
5054   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5055                                               LegalOperations))
5056     return SDValue(Res, 0);
5057
5058   // fold (sext (sext x)) -> (sext x)
5059   // fold (sext (aext x)) -> (sext x)
5060   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5061     return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
5062                        N0.getOperand(0));
5063
5064   if (N0.getOpcode() == ISD::TRUNCATE) {
5065     // fold (sext (truncate (load x))) -> (sext (smaller load x))
5066     // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
5067     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5068     if (NarrowLoad.getNode()) {
5069       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5070       if (NarrowLoad.getNode() != N0.getNode()) {
5071         CombineTo(N0.getNode(), NarrowLoad);
5072         // CombineTo deleted the truncate, if needed, but not what's under it.
5073         AddToWorklist(oye);
5074       }
5075       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5076     }
5077
5078     // See if the value being truncated is already sign extended.  If so, just
5079     // eliminate the trunc/sext pair.
5080     SDValue Op = N0.getOperand(0);
5081     unsigned OpBits   = Op.getValueType().getScalarType().getSizeInBits();
5082     unsigned MidBits  = N0.getValueType().getScalarType().getSizeInBits();
5083     unsigned DestBits = VT.getScalarType().getSizeInBits();
5084     unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
5085
5086     if (OpBits == DestBits) {
5087       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
5088       // bits, it is already ready.
5089       if (NumSignBits > DestBits-MidBits)
5090         return Op;
5091     } else if (OpBits < DestBits) {
5092       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
5093       // bits, just sext from i32.
5094       if (NumSignBits > OpBits-MidBits)
5095         return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
5096     } else {
5097       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
5098       // bits, just truncate to i32.
5099       if (NumSignBits > OpBits-MidBits)
5100         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5101     }
5102
5103     // fold (sext (truncate x)) -> (sextinreg x).
5104     if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
5105                                                  N0.getValueType())) {
5106       if (OpBits < DestBits)
5107         Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
5108       else if (OpBits > DestBits)
5109         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
5110       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
5111                          DAG.getValueType(N0.getValueType()));
5112     }
5113   }
5114
5115   // fold (sext (load x)) -> (sext (truncate (sextload x)))
5116   // None of the supported targets knows how to perform load and sign extend
5117   // on vectors in one instruction.  We only perform this transformation on
5118   // scalars.
5119   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5120       ISD::isUNINDEXEDLoad(N0.getNode()) &&
5121       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5122        TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()))) {
5123     bool DoXform = true;
5124     SmallVector<SDNode*, 4> SetCCs;
5125     if (!N0.hasOneUse())
5126       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
5127     if (DoXform) {
5128       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5129       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5130                                        LN0->getChain(),
5131                                        LN0->getBasePtr(), N0.getValueType(),
5132                                        LN0->getMemOperand());
5133       CombineTo(N, ExtLoad);
5134       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5135                                   N0.getValueType(), ExtLoad);
5136       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5137       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5138                       ISD::SIGN_EXTEND);
5139       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5140     }
5141   }
5142
5143   // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
5144   // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
5145   if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5146       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5147     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5148     EVT MemVT = LN0->getMemoryVT();
5149     if ((!LegalOperations && !LN0->isVolatile()) ||
5150         TLI.isLoadExtLegal(ISD::SEXTLOAD, MemVT)) {
5151       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5152                                        LN0->getChain(),
5153                                        LN0->getBasePtr(), MemVT,
5154                                        LN0->getMemOperand());
5155       CombineTo(N, ExtLoad);
5156       CombineTo(N0.getNode(),
5157                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5158                             N0.getValueType(), ExtLoad),
5159                 ExtLoad.getValue(1));
5160       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5161     }
5162   }
5163
5164   // fold (sext (and/or/xor (load x), cst)) ->
5165   //      (and/or/xor (sextload x), (sext cst))
5166   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5167        N0.getOpcode() == ISD::XOR) &&
5168       isa<LoadSDNode>(N0.getOperand(0)) &&
5169       N0.getOperand(1).getOpcode() == ISD::Constant &&
5170       TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()) &&
5171       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5172     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5173     if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
5174       bool DoXform = true;
5175       SmallVector<SDNode*, 4> SetCCs;
5176       if (!N0.hasOneUse())
5177         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
5178                                           SetCCs, TLI);
5179       if (DoXform) {
5180         SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
5181                                          LN0->getChain(), LN0->getBasePtr(),
5182                                          LN0->getMemoryVT(),
5183                                          LN0->getMemOperand());
5184         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5185         Mask = Mask.sext(VT.getSizeInBits());
5186         SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5187                                   ExtLoad, DAG.getConstant(Mask, VT));
5188         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5189                                     SDLoc(N0.getOperand(0)),
5190                                     N0.getOperand(0).getValueType(), ExtLoad);
5191         CombineTo(N, And);
5192         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5193         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5194                         ISD::SIGN_EXTEND);
5195         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5196       }
5197     }
5198   }
5199
5200   if (N0.getOpcode() == ISD::SETCC) {
5201     EVT N0VT = N0.getOperand(0).getValueType();
5202     // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
5203     // Only do this before legalize for now.
5204     if (VT.isVector() && !LegalOperations &&
5205         TLI.getBooleanContents(N0VT) ==
5206             TargetLowering::ZeroOrNegativeOneBooleanContent) {
5207       // On some architectures (such as SSE/NEON/etc) the SETCC result type is
5208       // of the same size as the compared operands. Only optimize sext(setcc())
5209       // if this is the case.
5210       EVT SVT = getSetCCResultType(N0VT);
5211
5212       // We know that the # elements of the results is the same as the
5213       // # elements of the compare (and the # elements of the compare result
5214       // for that matter).  Check to see that they are the same size.  If so,
5215       // we know that the element size of the sext'd result matches the
5216       // element size of the compare operands.
5217       if (VT.getSizeInBits() == SVT.getSizeInBits())
5218         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5219                              N0.getOperand(1),
5220                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
5221
5222       // If the desired elements are smaller or larger than the source
5223       // elements we can use a matching integer vector type and then
5224       // truncate/sign extend
5225       EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5226       if (SVT == MatchingVectorType) {
5227         SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
5228                                N0.getOperand(0), N0.getOperand(1),
5229                                cast<CondCodeSDNode>(N0.getOperand(2))->get());
5230         return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
5231       }
5232     }
5233
5234     // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
5235     unsigned ElementWidth = VT.getScalarType().getSizeInBits();
5236     SDValue NegOne =
5237       DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT);
5238     SDValue SCC =
5239       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5240                        NegOne, DAG.getConstant(0, VT),
5241                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5242     if (SCC.getNode()) return SCC;
5243
5244     if (!VT.isVector()) {
5245       EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
5246       if (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, SetCCVT)) {
5247         SDLoc DL(N);
5248         ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5249         SDValue SetCC = DAG.getSetCC(DL, SetCCVT,
5250                                      N0.getOperand(0), N0.getOperand(1), CC);
5251         return DAG.getSelect(DL, VT, SetCC,
5252                              NegOne, DAG.getConstant(0, VT));
5253       }
5254     }
5255   }
5256
5257   // fold (sext x) -> (zext x) if the sign bit is known zero.
5258   if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
5259       DAG.SignBitIsZero(N0))
5260     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
5261
5262   return SDValue();
5263 }
5264
5265 // isTruncateOf - If N is a truncate of some other value, return true, record
5266 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
5267 // This function computes KnownZero to avoid a duplicated call to
5268 // computeKnownBits in the caller.
5269 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
5270                          APInt &KnownZero) {
5271   APInt KnownOne;
5272   if (N->getOpcode() == ISD::TRUNCATE) {
5273     Op = N->getOperand(0);
5274     DAG.computeKnownBits(Op, KnownZero, KnownOne);
5275     return true;
5276   }
5277
5278   if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
5279       cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
5280     return false;
5281
5282   SDValue Op0 = N->getOperand(0);
5283   SDValue Op1 = N->getOperand(1);
5284   assert(Op0.getValueType() == Op1.getValueType());
5285
5286   ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0);
5287   ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
5288   if (COp0 && COp0->isNullValue())
5289     Op = Op1;
5290   else if (COp1 && COp1->isNullValue())
5291     Op = Op0;
5292   else
5293     return false;
5294
5295   DAG.computeKnownBits(Op, KnownZero, KnownOne);
5296
5297   if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
5298     return false;
5299
5300   return true;
5301 }
5302
5303 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
5304   SDValue N0 = N->getOperand(0);
5305   EVT VT = N->getValueType(0);
5306
5307   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5308                                               LegalOperations))
5309     return SDValue(Res, 0);
5310
5311   // fold (zext (zext x)) -> (zext x)
5312   // fold (zext (aext x)) -> (zext x)
5313   if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5314     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
5315                        N0.getOperand(0));
5316
5317   // fold (zext (truncate x)) -> (zext x) or
5318   //      (zext (truncate x)) -> (truncate x)
5319   // This is valid when the truncated bits of x are already zero.
5320   // FIXME: We should extend this to work for vectors too.
5321   SDValue Op;
5322   APInt KnownZero;
5323   if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
5324     APInt TruncatedBits =
5325       (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
5326       APInt(Op.getValueSizeInBits(), 0) :
5327       APInt::getBitsSet(Op.getValueSizeInBits(),
5328                         N0.getValueSizeInBits(),
5329                         std::min(Op.getValueSizeInBits(),
5330                                  VT.getSizeInBits()));
5331     if (TruncatedBits == (KnownZero & TruncatedBits)) {
5332       if (VT.bitsGT(Op.getValueType()))
5333         return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
5334       if (VT.bitsLT(Op.getValueType()))
5335         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5336
5337       return Op;
5338     }
5339   }
5340
5341   // fold (zext (truncate (load x))) -> (zext (smaller load x))
5342   // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
5343   if (N0.getOpcode() == ISD::TRUNCATE) {
5344     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5345     if (NarrowLoad.getNode()) {
5346       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5347       if (NarrowLoad.getNode() != N0.getNode()) {
5348         CombineTo(N0.getNode(), NarrowLoad);
5349         // CombineTo deleted the truncate, if needed, but not what's under it.
5350         AddToWorklist(oye);
5351       }
5352       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5353     }
5354   }
5355
5356   // fold (zext (truncate x)) -> (and x, mask)
5357   if (N0.getOpcode() == ISD::TRUNCATE &&
5358       (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
5359
5360     // fold (zext (truncate (load x))) -> (zext (smaller load x))
5361     // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
5362     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5363     if (NarrowLoad.getNode()) {
5364       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5365       if (NarrowLoad.getNode() != N0.getNode()) {
5366         CombineTo(N0.getNode(), NarrowLoad);
5367         // CombineTo deleted the truncate, if needed, but not what's under it.
5368         AddToWorklist(oye);
5369       }
5370       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5371     }
5372
5373     SDValue Op = N0.getOperand(0);
5374     if (Op.getValueType().bitsLT(VT)) {
5375       Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
5376       AddToWorklist(Op.getNode());
5377     } else if (Op.getValueType().bitsGT(VT)) {
5378       Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5379       AddToWorklist(Op.getNode());
5380     }
5381     return DAG.getZeroExtendInReg(Op, SDLoc(N),
5382                                   N0.getValueType().getScalarType());
5383   }
5384
5385   // Fold (zext (and (trunc x), cst)) -> (and x, cst),
5386   // if either of the casts is not free.
5387   if (N0.getOpcode() == ISD::AND &&
5388       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5389       N0.getOperand(1).getOpcode() == ISD::Constant &&
5390       (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5391                            N0.getValueType()) ||
5392        !TLI.isZExtFree(N0.getValueType(), VT))) {
5393     SDValue X = N0.getOperand(0).getOperand(0);
5394     if (X.getValueType().bitsLT(VT)) {
5395       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
5396     } else if (X.getValueType().bitsGT(VT)) {
5397       X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
5398     }
5399     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5400     Mask = Mask.zext(VT.getSizeInBits());
5401     return DAG.getNode(ISD::AND, SDLoc(N), VT,
5402                        X, DAG.getConstant(Mask, VT));
5403   }
5404
5405   // fold (zext (load x)) -> (zext (truncate (zextload x)))
5406   // None of the supported targets knows how to perform load and vector_zext
5407   // on vectors in one instruction.  We only perform this transformation on
5408   // scalars.
5409   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5410       ISD::isUNINDEXEDLoad(N0.getNode()) &&
5411       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5412        TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()))) {
5413     bool DoXform = true;
5414     SmallVector<SDNode*, 4> SetCCs;
5415     if (!N0.hasOneUse())
5416       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
5417     if (DoXform) {
5418       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5419       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5420                                        LN0->getChain(),
5421                                        LN0->getBasePtr(), N0.getValueType(),
5422                                        LN0->getMemOperand());
5423       CombineTo(N, ExtLoad);
5424       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5425                                   N0.getValueType(), ExtLoad);
5426       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5427
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   // fold (zext (and/or/xor (load x), cst)) ->
5435   //      (and/or/xor (zextload x), (zext cst))
5436   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5437        N0.getOpcode() == ISD::XOR) &&
5438       isa<LoadSDNode>(N0.getOperand(0)) &&
5439       N0.getOperand(1).getOpcode() == ISD::Constant &&
5440       TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()) &&
5441       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5442     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5443     if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
5444       bool DoXform = true;
5445       SmallVector<SDNode*, 4> SetCCs;
5446       if (!N0.hasOneUse())
5447         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
5448                                           SetCCs, TLI);
5449       if (DoXform) {
5450         SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
5451                                          LN0->getChain(), LN0->getBasePtr(),
5452                                          LN0->getMemoryVT(),
5453                                          LN0->getMemOperand());
5454         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5455         Mask = Mask.zext(VT.getSizeInBits());
5456         SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5457                                   ExtLoad, DAG.getConstant(Mask, VT));
5458         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5459                                     SDLoc(N0.getOperand(0)),
5460                                     N0.getOperand(0).getValueType(), ExtLoad);
5461         CombineTo(N, And);
5462         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5463         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5464                         ISD::ZERO_EXTEND);
5465         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5466       }
5467     }
5468   }
5469
5470   // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
5471   // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
5472   if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5473       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5474     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5475     EVT MemVT = LN0->getMemoryVT();
5476     if ((!LegalOperations && !LN0->isVolatile()) ||
5477         TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT)) {
5478       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5479                                        LN0->getChain(),
5480                                        LN0->getBasePtr(), MemVT,
5481                                        LN0->getMemOperand());
5482       CombineTo(N, ExtLoad);
5483       CombineTo(N0.getNode(),
5484                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
5485                             ExtLoad),
5486                 ExtLoad.getValue(1));
5487       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5488     }
5489   }
5490
5491   if (N0.getOpcode() == ISD::SETCC) {
5492     if (!LegalOperations && VT.isVector() &&
5493         N0.getValueType().getVectorElementType() == MVT::i1) {
5494       EVT N0VT = N0.getOperand(0).getValueType();
5495       if (getSetCCResultType(N0VT) == N0.getValueType())
5496         return SDValue();
5497
5498       // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
5499       // Only do this before legalize for now.
5500       EVT EltVT = VT.getVectorElementType();
5501       SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
5502                                     DAG.getConstant(1, EltVT));
5503       if (VT.getSizeInBits() == N0VT.getSizeInBits())
5504         // We know that the # elements of the results is the same as the
5505         // # elements of the compare (and the # elements of the compare result
5506         // for that matter).  Check to see that they are the same size.  If so,
5507         // we know that the element size of the sext'd result matches the
5508         // element size of the compare operands.
5509         return DAG.getNode(ISD::AND, SDLoc(N), VT,
5510                            DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5511                                          N0.getOperand(1),
5512                                  cast<CondCodeSDNode>(N0.getOperand(2))->get()),
5513                            DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
5514                                        OneOps));
5515
5516       // If the desired elements are smaller or larger than the source
5517       // elements we can use a matching integer vector type and then
5518       // truncate/sign extend
5519       EVT MatchingElementType =
5520         EVT::getIntegerVT(*DAG.getContext(),
5521                           N0VT.getScalarType().getSizeInBits());
5522       EVT MatchingVectorType =
5523         EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
5524                          N0VT.getVectorNumElements());
5525       SDValue VsetCC =
5526         DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5527                       N0.getOperand(1),
5528                       cast<CondCodeSDNode>(N0.getOperand(2))->get());
5529       return DAG.getNode(ISD::AND, SDLoc(N), VT,
5530                          DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT),
5531                          DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, OneOps));
5532     }
5533
5534     // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5535     SDValue SCC =
5536       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5537                        DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5538                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5539     if (SCC.getNode()) return SCC;
5540   }
5541
5542   // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
5543   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
5544       isa<ConstantSDNode>(N0.getOperand(1)) &&
5545       N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
5546       N0.hasOneUse()) {
5547     SDValue ShAmt = N0.getOperand(1);
5548     unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
5549     if (N0.getOpcode() == ISD::SHL) {
5550       SDValue InnerZExt = N0.getOperand(0);
5551       // If the original shl may be shifting out bits, do not perform this
5552       // transformation.
5553       unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
5554         InnerZExt.getOperand(0).getValueType().getSizeInBits();
5555       if (ShAmtVal > KnownZeroBits)
5556         return SDValue();
5557     }
5558
5559     SDLoc DL(N);
5560
5561     // Ensure that the shift amount is wide enough for the shifted value.
5562     if (VT.getSizeInBits() >= 256)
5563       ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
5564
5565     return DAG.getNode(N0.getOpcode(), DL, VT,
5566                        DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
5567                        ShAmt);
5568   }
5569
5570   return SDValue();
5571 }
5572
5573 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
5574   SDValue N0 = N->getOperand(0);
5575   EVT VT = N->getValueType(0);
5576
5577   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5578                                               LegalOperations))
5579     return SDValue(Res, 0);
5580
5581   // fold (aext (aext x)) -> (aext x)
5582   // fold (aext (zext x)) -> (zext x)
5583   // fold (aext (sext x)) -> (sext x)
5584   if (N0.getOpcode() == ISD::ANY_EXTEND  ||
5585       N0.getOpcode() == ISD::ZERO_EXTEND ||
5586       N0.getOpcode() == ISD::SIGN_EXTEND)
5587     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
5588
5589   // fold (aext (truncate (load x))) -> (aext (smaller load x))
5590   // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
5591   if (N0.getOpcode() == ISD::TRUNCATE) {
5592     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5593     if (NarrowLoad.getNode()) {
5594       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5595       if (NarrowLoad.getNode() != N0.getNode()) {
5596         CombineTo(N0.getNode(), NarrowLoad);
5597         // CombineTo deleted the truncate, if needed, but not what's under it.
5598         AddToWorklist(oye);
5599       }
5600       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5601     }
5602   }
5603
5604   // fold (aext (truncate x))
5605   if (N0.getOpcode() == ISD::TRUNCATE) {
5606     SDValue TruncOp = N0.getOperand(0);
5607     if (TruncOp.getValueType() == VT)
5608       return TruncOp; // x iff x size == zext size.
5609     if (TruncOp.getValueType().bitsGT(VT))
5610       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
5611     return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
5612   }
5613
5614   // Fold (aext (and (trunc x), cst)) -> (and x, cst)
5615   // if the trunc is not free.
5616   if (N0.getOpcode() == ISD::AND &&
5617       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5618       N0.getOperand(1).getOpcode() == ISD::Constant &&
5619       !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5620                           N0.getValueType())) {
5621     SDValue X = N0.getOperand(0).getOperand(0);
5622     if (X.getValueType().bitsLT(VT)) {
5623       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
5624     } else if (X.getValueType().bitsGT(VT)) {
5625       X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
5626     }
5627     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5628     Mask = Mask.zext(VT.getSizeInBits());
5629     return DAG.getNode(ISD::AND, SDLoc(N), VT,
5630                        X, DAG.getConstant(Mask, VT));
5631   }
5632
5633   // fold (aext (load x)) -> (aext (truncate (extload x)))
5634   // None of the supported targets knows how to perform load and any_ext
5635   // on vectors in one instruction.  We only perform this transformation on
5636   // scalars.
5637   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5638       ISD::isUNINDEXEDLoad(N0.getNode()) &&
5639       TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType())) {
5640     bool DoXform = true;
5641     SmallVector<SDNode*, 4> SetCCs;
5642     if (!N0.hasOneUse())
5643       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
5644     if (DoXform) {
5645       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5646       SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
5647                                        LN0->getChain(),
5648                                        LN0->getBasePtr(), N0.getValueType(),
5649                                        LN0->getMemOperand());
5650       CombineTo(N, ExtLoad);
5651       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5652                                   N0.getValueType(), ExtLoad);
5653       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5654       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5655                       ISD::ANY_EXTEND);
5656       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5657     }
5658   }
5659
5660   // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
5661   // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
5662   // fold (aext ( extload x)) -> (aext (truncate (extload  x)))
5663   if (N0.getOpcode() == ISD::LOAD &&
5664       !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5665       N0.hasOneUse()) {
5666     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5667     ISD::LoadExtType ExtType = LN0->getExtensionType();
5668     EVT MemVT = LN0->getMemoryVT();
5669     if (!LegalOperations || TLI.isLoadExtLegal(ExtType, MemVT)) {
5670       SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
5671                                        VT, LN0->getChain(), LN0->getBasePtr(),
5672                                        MemVT, LN0->getMemOperand());
5673       CombineTo(N, ExtLoad);
5674       CombineTo(N0.getNode(),
5675                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5676                             N0.getValueType(), ExtLoad),
5677                 ExtLoad.getValue(1));
5678       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5679     }
5680   }
5681
5682   if (N0.getOpcode() == ISD::SETCC) {
5683     // For vectors:
5684     // aext(setcc) -> vsetcc
5685     // aext(setcc) -> truncate(vsetcc)
5686     // aext(setcc) -> aext(vsetcc)
5687     // Only do this before legalize for now.
5688     if (VT.isVector() && !LegalOperations) {
5689       EVT N0VT = N0.getOperand(0).getValueType();
5690         // We know that the # elements of the results is the same as the
5691         // # elements of the compare (and the # elements of the compare result
5692         // for that matter).  Check to see that they are the same size.  If so,
5693         // we know that the element size of the sext'd result matches the
5694         // element size of the compare operands.
5695       if (VT.getSizeInBits() == N0VT.getSizeInBits())
5696         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5697                              N0.getOperand(1),
5698                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
5699       // If the desired elements are smaller or larger than the source
5700       // elements we can use a matching integer vector type and then
5701       // truncate/any extend
5702       else {
5703         EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5704         SDValue VsetCC =
5705           DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5706                         N0.getOperand(1),
5707                         cast<CondCodeSDNode>(N0.getOperand(2))->get());
5708         return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
5709       }
5710     }
5711
5712     // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5713     SDValue SCC =
5714       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5715                        DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5716                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5717     if (SCC.getNode())
5718       return SCC;
5719   }
5720
5721   return SDValue();
5722 }
5723
5724 /// See if the specified operand can be simplified with the knowledge that only
5725 /// the bits specified by Mask are used.  If so, return the simpler operand,
5726 /// otherwise return a null SDValue.
5727 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
5728   switch (V.getOpcode()) {
5729   default: break;
5730   case ISD::Constant: {
5731     const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
5732     assert(CV && "Const value should be ConstSDNode.");
5733     const APInt &CVal = CV->getAPIntValue();
5734     APInt NewVal = CVal & Mask;
5735     if (NewVal != CVal)
5736       return DAG.getConstant(NewVal, V.getValueType());
5737     break;
5738   }
5739   case ISD::OR:
5740   case ISD::XOR:
5741     // If the LHS or RHS don't contribute bits to the or, drop them.
5742     if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
5743       return V.getOperand(1);
5744     if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
5745       return V.getOperand(0);
5746     break;
5747   case ISD::SRL:
5748     // Only look at single-use SRLs.
5749     if (!V.getNode()->hasOneUse())
5750       break;
5751     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
5752       // See if we can recursively simplify the LHS.
5753       unsigned Amt = RHSC->getZExtValue();
5754
5755       // Watch out for shift count overflow though.
5756       if (Amt >= Mask.getBitWidth()) break;
5757       APInt NewMask = Mask << Amt;
5758       SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
5759       if (SimplifyLHS.getNode())
5760         return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
5761                            SimplifyLHS, V.getOperand(1));
5762     }
5763   }
5764   return SDValue();
5765 }
5766
5767 /// If the result of a wider load is shifted to right of N  bits and then
5768 /// truncated to a narrower type and where N is a multiple of number of bits of
5769 /// the narrower type, transform it to a narrower load from address + N / num of
5770 /// bits of new type. If the result is to be extended, also fold the extension
5771 /// to form a extending load.
5772 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
5773   unsigned Opc = N->getOpcode();
5774
5775   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
5776   SDValue N0 = N->getOperand(0);
5777   EVT VT = N->getValueType(0);
5778   EVT ExtVT = VT;
5779
5780   // This transformation isn't valid for vector loads.
5781   if (VT.isVector())
5782     return SDValue();
5783
5784   // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
5785   // extended to VT.
5786   if (Opc == ISD::SIGN_EXTEND_INREG) {
5787     ExtType = ISD::SEXTLOAD;
5788     ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
5789   } else if (Opc == ISD::SRL) {
5790     // Another special-case: SRL is basically zero-extending a narrower value.
5791     ExtType = ISD::ZEXTLOAD;
5792     N0 = SDValue(N, 0);
5793     ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
5794     if (!N01) return SDValue();
5795     ExtVT = EVT::getIntegerVT(*DAG.getContext(),
5796                               VT.getSizeInBits() - N01->getZExtValue());
5797   }
5798   if (LegalOperations && !TLI.isLoadExtLegal(ExtType, ExtVT))
5799     return SDValue();
5800
5801   unsigned EVTBits = ExtVT.getSizeInBits();
5802
5803   // Do not generate loads of non-round integer types since these can
5804   // be expensive (and would be wrong if the type is not byte sized).
5805   if (!ExtVT.isRound())
5806     return SDValue();
5807
5808   unsigned ShAmt = 0;
5809   if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
5810     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5811       ShAmt = N01->getZExtValue();
5812       // Is the shift amount a multiple of size of VT?
5813       if ((ShAmt & (EVTBits-1)) == 0) {
5814         N0 = N0.getOperand(0);
5815         // Is the load width a multiple of size of VT?
5816         if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
5817           return SDValue();
5818       }
5819
5820       // At this point, we must have a load or else we can't do the transform.
5821       if (!isa<LoadSDNode>(N0)) return SDValue();
5822
5823       // Because a SRL must be assumed to *need* to zero-extend the high bits
5824       // (as opposed to anyext the high bits), we can't combine the zextload
5825       // lowering of SRL and an sextload.
5826       if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
5827         return SDValue();
5828
5829       // If the shift amount is larger than the input type then we're not
5830       // accessing any of the loaded bytes.  If the load was a zextload/extload
5831       // then the result of the shift+trunc is zero/undef (handled elsewhere).
5832       if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
5833         return SDValue();
5834     }
5835   }
5836
5837   // If the load is shifted left (and the result isn't shifted back right),
5838   // we can fold the truncate through the shift.
5839   unsigned ShLeftAmt = 0;
5840   if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
5841       ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
5842     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5843       ShLeftAmt = N01->getZExtValue();
5844       N0 = N0.getOperand(0);
5845     }
5846   }
5847
5848   // If we haven't found a load, we can't narrow it.  Don't transform one with
5849   // multiple uses, this would require adding a new load.
5850   if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
5851     return SDValue();
5852
5853   // Don't change the width of a volatile load.
5854   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5855   if (LN0->isVolatile())
5856     return SDValue();
5857
5858   // Verify that we are actually reducing a load width here.
5859   if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
5860     return SDValue();
5861
5862   // For the transform to be legal, the load must produce only two values
5863   // (the value loaded and the chain).  Don't transform a pre-increment
5864   // load, for example, which produces an extra value.  Otherwise the
5865   // transformation is not equivalent, and the downstream logic to replace
5866   // uses gets things wrong.
5867   if (LN0->getNumValues() > 2)
5868     return SDValue();
5869
5870   // If the load that we're shrinking is an extload and we're not just
5871   // discarding the extension we can't simply shrink the load. Bail.
5872   // TODO: It would be possible to merge the extensions in some cases.
5873   if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
5874       LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
5875     return SDValue();
5876
5877   EVT PtrType = N0.getOperand(1).getValueType();
5878
5879   if (PtrType == MVT::Untyped || PtrType.isExtended())
5880     // It's not possible to generate a constant of extended or untyped type.
5881     return SDValue();
5882
5883   // For big endian targets, we need to adjust the offset to the pointer to
5884   // load the correct bytes.
5885   if (TLI.isBigEndian()) {
5886     unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
5887     unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
5888     ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
5889   }
5890
5891   uint64_t PtrOff = ShAmt / 8;
5892   unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
5893   SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0),
5894                                PtrType, LN0->getBasePtr(),
5895                                DAG.getConstant(PtrOff, PtrType));
5896   AddToWorklist(NewPtr.getNode());
5897
5898   SDValue Load;
5899   if (ExtType == ISD::NON_EXTLOAD)
5900     Load =  DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
5901                         LN0->getPointerInfo().getWithOffset(PtrOff),
5902                         LN0->isVolatile(), LN0->isNonTemporal(),
5903                         LN0->isInvariant(), NewAlign, LN0->getAAInfo());
5904   else
5905     Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
5906                           LN0->getPointerInfo().getWithOffset(PtrOff),
5907                           ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
5908                           LN0->isInvariant(), NewAlign, LN0->getAAInfo());
5909
5910   // Replace the old load's chain with the new load's chain.
5911   WorklistRemover DeadNodes(*this);
5912   DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
5913
5914   // Shift the result left, if we've swallowed a left shift.
5915   SDValue Result = Load;
5916   if (ShLeftAmt != 0) {
5917     EVT ShImmTy = getShiftAmountTy(Result.getValueType());
5918     if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
5919       ShImmTy = VT;
5920     // If the shift amount is as large as the result size (but, presumably,
5921     // no larger than the source) then the useful bits of the result are
5922     // zero; we can't simply return the shortened shift, because the result
5923     // of that operation is undefined.
5924     if (ShLeftAmt >= VT.getSizeInBits())
5925       Result = DAG.getConstant(0, VT);
5926     else
5927       Result = DAG.getNode(ISD::SHL, SDLoc(N0), VT,
5928                           Result, DAG.getConstant(ShLeftAmt, ShImmTy));
5929   }
5930
5931   // Return the new loaded value.
5932   return Result;
5933 }
5934
5935 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
5936   SDValue N0 = N->getOperand(0);
5937   SDValue N1 = N->getOperand(1);
5938   EVT VT = N->getValueType(0);
5939   EVT EVT = cast<VTSDNode>(N1)->getVT();
5940   unsigned VTBits = VT.getScalarType().getSizeInBits();
5941   unsigned EVTBits = EVT.getScalarType().getSizeInBits();
5942
5943   // fold (sext_in_reg c1) -> c1
5944   if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
5945     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
5946
5947   // If the input is already sign extended, just drop the extension.
5948   if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
5949     return N0;
5950
5951   // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
5952   if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
5953       EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
5954     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5955                        N0.getOperand(0), N1);
5956
5957   // fold (sext_in_reg (sext x)) -> (sext x)
5958   // fold (sext_in_reg (aext x)) -> (sext x)
5959   // if x is small enough.
5960   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
5961     SDValue N00 = N0.getOperand(0);
5962     if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
5963         (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
5964       return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
5965   }
5966
5967   // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
5968   if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
5969     return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
5970
5971   // fold operands of sext_in_reg based on knowledge that the top bits are not
5972   // demanded.
5973   if (SimplifyDemandedBits(SDValue(N, 0)))
5974     return SDValue(N, 0);
5975
5976   // fold (sext_in_reg (load x)) -> (smaller sextload x)
5977   // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
5978   SDValue NarrowLoad = ReduceLoadWidth(N);
5979   if (NarrowLoad.getNode())
5980     return NarrowLoad;
5981
5982   // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
5983   // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
5984   // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
5985   if (N0.getOpcode() == ISD::SRL) {
5986     if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
5987       if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
5988         // We can turn this into an SRA iff the input to the SRL is already sign
5989         // extended enough.
5990         unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
5991         if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
5992           return DAG.getNode(ISD::SRA, SDLoc(N), VT,
5993                              N0.getOperand(0), N0.getOperand(1));
5994       }
5995   }
5996
5997   // fold (sext_inreg (extload x)) -> (sextload x)
5998   if (ISD::isEXTLoad(N0.getNode()) &&
5999       ISD::isUNINDEXEDLoad(N0.getNode()) &&
6000       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6001       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6002        TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
6003     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6004     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6005                                      LN0->getChain(),
6006                                      LN0->getBasePtr(), EVT,
6007                                      LN0->getMemOperand());
6008     CombineTo(N, ExtLoad);
6009     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6010     AddToWorklist(ExtLoad.getNode());
6011     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6012   }
6013   // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
6014   if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6015       N0.hasOneUse() &&
6016       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6017       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6018        TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
6019     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6020     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6021                                      LN0->getChain(),
6022                                      LN0->getBasePtr(), EVT,
6023                                      LN0->getMemOperand());
6024     CombineTo(N, ExtLoad);
6025     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6026     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6027   }
6028
6029   // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
6030   if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
6031     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
6032                                        N0.getOperand(1), false);
6033     if (BSwap.getNode())
6034       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6035                          BSwap, N1);
6036   }
6037
6038   // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs
6039   // into a build_vector.
6040   if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
6041     SmallVector<SDValue, 8> Elts;
6042     unsigned NumElts = N0->getNumOperands();
6043     unsigned ShAmt = VTBits - EVTBits;
6044
6045     for (unsigned i = 0; i != NumElts; ++i) {
6046       SDValue Op = N0->getOperand(i);
6047       if (Op->getOpcode() == ISD::UNDEF) {
6048         Elts.push_back(Op);
6049         continue;
6050       }
6051
6052       ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
6053       const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
6054       Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
6055                                      Op.getValueType()));
6056     }
6057
6058     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Elts);
6059   }
6060
6061   return SDValue();
6062 }
6063
6064 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
6065   SDValue N0 = N->getOperand(0);
6066   EVT VT = N->getValueType(0);
6067   bool isLE = TLI.isLittleEndian();
6068
6069   // noop truncate
6070   if (N0.getValueType() == N->getValueType(0))
6071     return N0;
6072   // fold (truncate c1) -> c1
6073   if (isa<ConstantSDNode>(N0))
6074     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
6075   // fold (truncate (truncate x)) -> (truncate x)
6076   if (N0.getOpcode() == ISD::TRUNCATE)
6077     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6078   // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
6079   if (N0.getOpcode() == ISD::ZERO_EXTEND ||
6080       N0.getOpcode() == ISD::SIGN_EXTEND ||
6081       N0.getOpcode() == ISD::ANY_EXTEND) {
6082     if (N0.getOperand(0).getValueType().bitsLT(VT))
6083       // if the source is smaller than the dest, we still need an extend
6084       return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
6085                          N0.getOperand(0));
6086     if (N0.getOperand(0).getValueType().bitsGT(VT))
6087       // if the source is larger than the dest, than we just need the truncate
6088       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6089     // if the source and dest are the same type, we can drop both the extend
6090     // and the truncate.
6091     return N0.getOperand(0);
6092   }
6093
6094   // Fold extract-and-trunc into a narrow extract. For example:
6095   //   i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
6096   //   i32 y = TRUNCATE(i64 x)
6097   //        -- becomes --
6098   //   v16i8 b = BITCAST (v2i64 val)
6099   //   i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
6100   //
6101   // Note: We only run this optimization after type legalization (which often
6102   // creates this pattern) and before operation legalization after which
6103   // we need to be more careful about the vector instructions that we generate.
6104   if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6105       LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
6106
6107     EVT VecTy = N0.getOperand(0).getValueType();
6108     EVT ExTy = N0.getValueType();
6109     EVT TrTy = N->getValueType(0);
6110
6111     unsigned NumElem = VecTy.getVectorNumElements();
6112     unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
6113
6114     EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
6115     assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
6116
6117     SDValue EltNo = N0->getOperand(1);
6118     if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
6119       int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
6120       EVT IndexTy = TLI.getVectorIdxTy();
6121       int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
6122
6123       SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
6124                               NVT, N0.getOperand(0));
6125
6126       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
6127                          SDLoc(N), TrTy, V,
6128                          DAG.getConstant(Index, IndexTy));
6129     }
6130   }
6131
6132   // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
6133   if (N0.getOpcode() == ISD::SELECT) {
6134     EVT SrcVT = N0.getValueType();
6135     if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
6136         TLI.isTruncateFree(SrcVT, VT)) {
6137       SDLoc SL(N0);
6138       SDValue Cond = N0.getOperand(0);
6139       SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
6140       SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
6141       return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
6142     }
6143   }
6144
6145   // Fold a series of buildvector, bitcast, and truncate if possible.
6146   // For example fold
6147   //   (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
6148   //   (2xi32 (buildvector x, y)).
6149   if (Level == AfterLegalizeVectorOps && VT.isVector() &&
6150       N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
6151       N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
6152       N0.getOperand(0).hasOneUse()) {
6153
6154     SDValue BuildVect = N0.getOperand(0);
6155     EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
6156     EVT TruncVecEltTy = VT.getVectorElementType();
6157
6158     // Check that the element types match.
6159     if (BuildVectEltTy == TruncVecEltTy) {
6160       // Now we only need to compute the offset of the truncated elements.
6161       unsigned BuildVecNumElts =  BuildVect.getNumOperands();
6162       unsigned TruncVecNumElts = VT.getVectorNumElements();
6163       unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
6164
6165       assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
6166              "Invalid number of elements");
6167
6168       SmallVector<SDValue, 8> Opnds;
6169       for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
6170         Opnds.push_back(BuildVect.getOperand(i));
6171
6172       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
6173     }
6174   }
6175
6176   // See if we can simplify the input to this truncate through knowledge that
6177   // only the low bits are being used.
6178   // For example "trunc (or (shl x, 8), y)" // -> trunc y
6179   // Currently we only perform this optimization on scalars because vectors
6180   // may have different active low bits.
6181   if (!VT.isVector()) {
6182     SDValue Shorter =
6183       GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
6184                                                VT.getSizeInBits()));
6185     if (Shorter.getNode())
6186       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
6187   }
6188   // fold (truncate (load x)) -> (smaller load x)
6189   // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
6190   if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
6191     SDValue Reduced = ReduceLoadWidth(N);
6192     if (Reduced.getNode())
6193       return Reduced;
6194     // Handle the case where the load remains an extending load even
6195     // after truncation.
6196     if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
6197       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6198       if (!LN0->isVolatile() &&
6199           LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
6200         SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
6201                                          VT, LN0->getChain(), LN0->getBasePtr(),
6202                                          LN0->getMemoryVT(),
6203                                          LN0->getMemOperand());
6204         DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
6205         return NewLoad;
6206       }
6207     }
6208   }
6209   // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
6210   // where ... are all 'undef'.
6211   if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
6212     SmallVector<EVT, 8> VTs;
6213     SDValue V;
6214     unsigned Idx = 0;
6215     unsigned NumDefs = 0;
6216
6217     for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
6218       SDValue X = N0.getOperand(i);
6219       if (X.getOpcode() != ISD::UNDEF) {
6220         V = X;
6221         Idx = i;
6222         NumDefs++;
6223       }
6224       // Stop if more than one members are non-undef.
6225       if (NumDefs > 1)
6226         break;
6227       VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
6228                                      VT.getVectorElementType(),
6229                                      X.getValueType().getVectorNumElements()));
6230     }
6231
6232     if (NumDefs == 0)
6233       return DAG.getUNDEF(VT);
6234
6235     if (NumDefs == 1) {
6236       assert(V.getNode() && "The single defined operand is empty!");
6237       SmallVector<SDValue, 8> Opnds;
6238       for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
6239         if (i != Idx) {
6240           Opnds.push_back(DAG.getUNDEF(VTs[i]));
6241           continue;
6242         }
6243         SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
6244         AddToWorklist(NV.getNode());
6245         Opnds.push_back(NV);
6246       }
6247       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
6248     }
6249   }
6250
6251   // Simplify the operands using demanded-bits information.
6252   if (!VT.isVector() &&
6253       SimplifyDemandedBits(SDValue(N, 0)))
6254     return SDValue(N, 0);
6255
6256   return SDValue();
6257 }
6258
6259 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
6260   SDValue Elt = N->getOperand(i);
6261   if (Elt.getOpcode() != ISD::MERGE_VALUES)
6262     return Elt.getNode();
6263   return Elt.getOperand(Elt.getResNo()).getNode();
6264 }
6265
6266 /// build_pair (load, load) -> load
6267 /// if load locations are consecutive.
6268 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
6269   assert(N->getOpcode() == ISD::BUILD_PAIR);
6270
6271   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
6272   LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
6273   if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
6274       LD1->getAddressSpace() != LD2->getAddressSpace())
6275     return SDValue();
6276   EVT LD1VT = LD1->getValueType(0);
6277
6278   if (ISD::isNON_EXTLoad(LD2) &&
6279       LD2->hasOneUse() &&
6280       // If both are volatile this would reduce the number of volatile loads.
6281       // If one is volatile it might be ok, but play conservative and bail out.
6282       !LD1->isVolatile() &&
6283       !LD2->isVolatile() &&
6284       DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
6285     unsigned Align = LD1->getAlignment();
6286     unsigned NewAlign = TLI.getDataLayout()->
6287       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6288
6289     if (NewAlign <= Align &&
6290         (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
6291       return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
6292                          LD1->getBasePtr(), LD1->getPointerInfo(),
6293                          false, false, false, Align);
6294   }
6295
6296   return SDValue();
6297 }
6298
6299 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
6300   SDValue N0 = N->getOperand(0);
6301   EVT VT = N->getValueType(0);
6302
6303   // If the input is a BUILD_VECTOR with all constant elements, fold this now.
6304   // Only do this before legalize, since afterward the target may be depending
6305   // on the bitconvert.
6306   // First check to see if this is all constant.
6307   if (!LegalTypes &&
6308       N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
6309       VT.isVector()) {
6310     bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
6311
6312     EVT DestEltVT = N->getValueType(0).getVectorElementType();
6313     assert(!DestEltVT.isVector() &&
6314            "Element type of vector ValueType must not be vector!");
6315     if (isSimple)
6316       return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
6317   }
6318
6319   // If the input is a constant, let getNode fold it.
6320   if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
6321     SDValue Res = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
6322     if (Res.getNode() != N) {
6323       if (!LegalOperations ||
6324           TLI.isOperationLegal(Res.getNode()->getOpcode(), VT))
6325         return Res;
6326
6327       // Folding it resulted in an illegal node, and it's too late to
6328       // do that. Clean up the old node and forego the transformation.
6329       // Ideally this won't happen very often, because instcombine
6330       // and the earlier dagcombine runs (where illegal nodes are
6331       // permitted) should have folded most of them already.
6332       deleteAndRecombine(Res.getNode());
6333     }
6334   }
6335
6336   // (conv (conv x, t1), t2) -> (conv x, t2)
6337   if (N0.getOpcode() == ISD::BITCAST)
6338     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
6339                        N0.getOperand(0));
6340
6341   // fold (conv (load x)) -> (load (conv*)x)
6342   // If the resultant load doesn't need a higher alignment than the original!
6343   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
6344       // Do not change the width of a volatile load.
6345       !cast<LoadSDNode>(N0)->isVolatile() &&
6346       // Do not remove the cast if the types differ in endian layout.
6347       TLI.hasBigEndianPartOrdering(N0.getValueType()) ==
6348       TLI.hasBigEndianPartOrdering(VT) &&
6349       (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
6350       TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
6351     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6352     unsigned Align = TLI.getDataLayout()->
6353       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6354     unsigned OrigAlign = LN0->getAlignment();
6355
6356     if (Align <= OrigAlign) {
6357       SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
6358                                  LN0->getBasePtr(), LN0->getPointerInfo(),
6359                                  LN0->isVolatile(), LN0->isNonTemporal(),
6360                                  LN0->isInvariant(), OrigAlign,
6361                                  LN0->getAAInfo());
6362       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
6363       return Load;
6364     }
6365   }
6366
6367   // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
6368   // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
6369   // This often reduces constant pool loads.
6370   if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
6371        (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
6372       N0.getNode()->hasOneUse() && VT.isInteger() &&
6373       !VT.isVector() && !N0.getValueType().isVector()) {
6374     SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
6375                                   N0.getOperand(0));
6376     AddToWorklist(NewConv.getNode());
6377
6378     APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6379     if (N0.getOpcode() == ISD::FNEG)
6380       return DAG.getNode(ISD::XOR, SDLoc(N), VT,
6381                          NewConv, DAG.getConstant(SignBit, VT));
6382     assert(N0.getOpcode() == ISD::FABS);
6383     return DAG.getNode(ISD::AND, SDLoc(N), VT,
6384                        NewConv, DAG.getConstant(~SignBit, VT));
6385   }
6386
6387   // fold (bitconvert (fcopysign cst, x)) ->
6388   //         (or (and (bitconvert x), sign), (and cst, (not sign)))
6389   // Note that we don't handle (copysign x, cst) because this can always be
6390   // folded to an fneg or fabs.
6391   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
6392       isa<ConstantFPSDNode>(N0.getOperand(0)) &&
6393       VT.isInteger() && !VT.isVector()) {
6394     unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
6395     EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
6396     if (isTypeLegal(IntXVT)) {
6397       SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6398                               IntXVT, N0.getOperand(1));
6399       AddToWorklist(X.getNode());
6400
6401       // If X has a different width than the result/lhs, sext it or truncate it.
6402       unsigned VTWidth = VT.getSizeInBits();
6403       if (OrigXWidth < VTWidth) {
6404         X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
6405         AddToWorklist(X.getNode());
6406       } else if (OrigXWidth > VTWidth) {
6407         // To get the sign bit in the right place, we have to shift it right
6408         // before truncating.
6409         X = DAG.getNode(ISD::SRL, SDLoc(X),
6410                         X.getValueType(), X,
6411                         DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
6412         AddToWorklist(X.getNode());
6413         X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
6414         AddToWorklist(X.getNode());
6415       }
6416
6417       APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6418       X = DAG.getNode(ISD::AND, SDLoc(X), VT,
6419                       X, DAG.getConstant(SignBit, VT));
6420       AddToWorklist(X.getNode());
6421
6422       SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6423                                 VT, N0.getOperand(0));
6424       Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
6425                         Cst, DAG.getConstant(~SignBit, VT));
6426       AddToWorklist(Cst.getNode());
6427
6428       return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
6429     }
6430   }
6431
6432   // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
6433   if (N0.getOpcode() == ISD::BUILD_PAIR) {
6434     SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
6435     if (CombineLD.getNode())
6436       return CombineLD;
6437   }
6438
6439   return SDValue();
6440 }
6441
6442 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
6443   EVT VT = N->getValueType(0);
6444   return CombineConsecutiveLoads(N, VT);
6445 }
6446
6447 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef
6448 /// operands. DstEltVT indicates the destination element value type.
6449 SDValue DAGCombiner::
6450 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
6451   EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
6452
6453   // If this is already the right type, we're done.
6454   if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
6455
6456   unsigned SrcBitSize = SrcEltVT.getSizeInBits();
6457   unsigned DstBitSize = DstEltVT.getSizeInBits();
6458
6459   // If this is a conversion of N elements of one type to N elements of another
6460   // type, convert each element.  This handles FP<->INT cases.
6461   if (SrcBitSize == DstBitSize) {
6462     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6463                               BV->getValueType(0).getVectorNumElements());
6464
6465     // Due to the FP element handling below calling this routine recursively,
6466     // we can end up with a scalar-to-vector node here.
6467     if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
6468       return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6469                          DAG.getNode(ISD::BITCAST, SDLoc(BV),
6470                                      DstEltVT, BV->getOperand(0)));
6471
6472     SmallVector<SDValue, 8> Ops;
6473     for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6474       SDValue Op = BV->getOperand(i);
6475       // If the vector element type is not legal, the BUILD_VECTOR operands
6476       // are promoted and implicitly truncated.  Make that explicit here.
6477       if (Op.getValueType() != SrcEltVT)
6478         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
6479       Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
6480                                 DstEltVT, Op));
6481       AddToWorklist(Ops.back().getNode());
6482     }
6483     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6484   }
6485
6486   // Otherwise, we're growing or shrinking the elements.  To avoid having to
6487   // handle annoying details of growing/shrinking FP values, we convert them to
6488   // int first.
6489   if (SrcEltVT.isFloatingPoint()) {
6490     // Convert the input float vector to a int vector where the elements are the
6491     // same sizes.
6492     assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!");
6493     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
6494     BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
6495     SrcEltVT = IntVT;
6496   }
6497
6498   // Now we know the input is an integer vector.  If the output is a FP type,
6499   // convert to integer first, then to FP of the right size.
6500   if (DstEltVT.isFloatingPoint()) {
6501     assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!");
6502     EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
6503     SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
6504
6505     // Next, convert to FP elements of the same size.
6506     return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
6507   }
6508
6509   // Okay, we know the src/dst types are both integers of differing types.
6510   // Handling growing first.
6511   assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
6512   if (SrcBitSize < DstBitSize) {
6513     unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
6514
6515     SmallVector<SDValue, 8> Ops;
6516     for (unsigned i = 0, e = BV->getNumOperands(); i != e;
6517          i += NumInputsPerOutput) {
6518       bool isLE = TLI.isLittleEndian();
6519       APInt NewBits = APInt(DstBitSize, 0);
6520       bool EltIsUndef = true;
6521       for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
6522         // Shift the previously computed bits over.
6523         NewBits <<= SrcBitSize;
6524         SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
6525         if (Op.getOpcode() == ISD::UNDEF) continue;
6526         EltIsUndef = false;
6527
6528         NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
6529                    zextOrTrunc(SrcBitSize).zext(DstBitSize);
6530       }
6531
6532       if (EltIsUndef)
6533         Ops.push_back(DAG.getUNDEF(DstEltVT));
6534       else
6535         Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
6536     }
6537
6538     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
6539     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6540   }
6541
6542   // Finally, this must be the case where we are shrinking elements: each input
6543   // turns into multiple outputs.
6544   bool isS2V = ISD::isScalarToVector(BV);
6545   unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
6546   EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6547                             NumOutputsPerInput*BV->getNumOperands());
6548   SmallVector<SDValue, 8> Ops;
6549
6550   for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6551     if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
6552       for (unsigned j = 0; j != NumOutputsPerInput; ++j)
6553         Ops.push_back(DAG.getUNDEF(DstEltVT));
6554       continue;
6555     }
6556
6557     APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
6558                   getAPIntValue().zextOrTrunc(SrcBitSize);
6559
6560     for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
6561       APInt ThisVal = OpVal.trunc(DstBitSize);
6562       Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
6563       if (isS2V && i == 0 && j == 0 && ThisVal.zext(SrcBitSize) == OpVal)
6564         // Simply turn this into a SCALAR_TO_VECTOR of the new type.
6565         return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6566                            Ops[0]);
6567       OpVal = OpVal.lshr(DstBitSize);
6568     }
6569
6570     // For big endian targets, swap the order of the pieces of each element.
6571     if (TLI.isBigEndian())
6572       std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
6573   }
6574
6575   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6576 }
6577
6578 SDValue DAGCombiner::visitFADD(SDNode *N) {
6579   SDValue N0 = N->getOperand(0);
6580   SDValue N1 = N->getOperand(1);
6581   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6582   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6583   EVT VT = N->getValueType(0);
6584   const TargetOptions &Options = DAG.getTarget().Options;
6585
6586   // fold vector ops
6587   if (VT.isVector()) {
6588     SDValue FoldedVOp = SimplifyVBinOp(N);
6589     if (FoldedVOp.getNode()) return FoldedVOp;
6590   }
6591
6592   // fold (fadd c1, c2) -> c1 + c2
6593   if (N0CFP && N1CFP)
6594     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N1);
6595
6596   // canonicalize constant to RHS
6597   if (N0CFP && !N1CFP)
6598     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N0);
6599
6600   // fold (fadd A, (fneg B)) -> (fsub A, B)
6601   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6602       isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2)
6603     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0,
6604                        GetNegatedExpression(N1, DAG, LegalOperations));
6605
6606   // fold (fadd (fneg A), B) -> (fsub B, A)
6607   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6608       isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2)
6609     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N1,
6610                        GetNegatedExpression(N0, DAG, LegalOperations));
6611
6612   // If 'unsafe math' is enabled, fold lots of things.
6613   if (Options.UnsafeFPMath) {
6614     // No FP constant should be created after legalization as Instruction
6615     // Selection pass has a hard time dealing with FP constants.
6616     bool AllowNewConst = (Level < AfterLegalizeDAG);
6617
6618     // fold (fadd A, 0) -> A
6619     if (N1CFP && N1CFP->getValueAPF().isZero())
6620       return N0;
6621
6622     // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
6623     if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
6624         isa<ConstantFPSDNode>(N0.getOperand(1)))
6625       return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0.getOperand(0),
6626                          DAG.getNode(ISD::FADD, SDLoc(N), VT,
6627                                      N0.getOperand(1), N1));
6628
6629     // If allowed, fold (fadd (fneg x), x) -> 0.0
6630     if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
6631       return DAG.getConstantFP(0.0, VT);
6632
6633     // If allowed, fold (fadd x, (fneg x)) -> 0.0
6634     if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
6635       return DAG.getConstantFP(0.0, VT);
6636
6637     // We can fold chains of FADD's of the same value into multiplications.
6638     // This transform is not safe in general because we are reducing the number
6639     // of rounding steps.
6640     if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) {
6641       if (N0.getOpcode() == ISD::FMUL) {
6642         ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6643         ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
6644
6645         // (fadd (fmul x, c), x) -> (fmul x, c+1)
6646         if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
6647           SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6648                                        SDValue(CFP01, 0),
6649                                        DAG.getConstantFP(1.0, VT));
6650           return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, NewCFP);
6651         }
6652
6653         // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
6654         if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
6655             N1.getOperand(0) == N1.getOperand(1) &&
6656             N0.getOperand(0) == N1.getOperand(0)) {
6657           SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6658                                        SDValue(CFP01, 0),
6659                                        DAG.getConstantFP(2.0, VT));
6660           return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6661                              N0.getOperand(0), NewCFP);
6662         }
6663       }
6664
6665       if (N1.getOpcode() == ISD::FMUL) {
6666         ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6667         ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
6668
6669         // (fadd x, (fmul x, c)) -> (fmul x, c+1)
6670         if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
6671           SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6672                                        SDValue(CFP11, 0),
6673                                        DAG.getConstantFP(1.0, VT));
6674           return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, NewCFP);
6675         }
6676
6677         // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
6678         if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
6679             N0.getOperand(0) == N0.getOperand(1) &&
6680             N1.getOperand(0) == N0.getOperand(0)) {
6681           SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6682                                        SDValue(CFP11, 0),
6683                                        DAG.getConstantFP(2.0, VT));
6684           return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1.getOperand(0), NewCFP);
6685         }
6686       }
6687
6688       if (N0.getOpcode() == ISD::FADD && AllowNewConst) {
6689         ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6690         // (fadd (fadd x, x), x) -> (fmul x, 3.0)
6691         if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
6692             (N0.getOperand(0) == N1))
6693           return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6694                              N1, DAG.getConstantFP(3.0, VT));
6695       }
6696
6697       if (N1.getOpcode() == ISD::FADD && AllowNewConst) {
6698         ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6699         // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
6700         if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
6701             N1.getOperand(0) == N0)
6702           return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6703                              N0, DAG.getConstantFP(3.0, VT));
6704       }
6705
6706       // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
6707       if (AllowNewConst &&
6708           N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
6709           N0.getOperand(0) == N0.getOperand(1) &&
6710           N1.getOperand(0) == N1.getOperand(1) &&
6711           N0.getOperand(0) == N1.getOperand(0))
6712         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6713                            N0.getOperand(0), DAG.getConstantFP(4.0, VT));
6714     }
6715   } // enable-unsafe-fp-math
6716
6717   // FADD -> FMA combines:
6718   if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath) &&
6719       TLI.isFMAFasterThanFMulAndFAdd(VT) &&
6720       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6721
6722     // fold (fadd (fmul x, y), z) -> (fma x, y, z)
6723     if (N0.getOpcode() == ISD::FMUL &&
6724         (N0->hasOneUse() || TLI.enableAggressiveFMAFusion(VT)))
6725       return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6726                          N0.getOperand(0), N0.getOperand(1), N1);
6727
6728     // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
6729     // Note: Commutes FADD operands.
6730     if (N1.getOpcode() == ISD::FMUL &&
6731         (N1->hasOneUse() || TLI.enableAggressiveFMAFusion(VT)))
6732       return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6733                          N1.getOperand(0), N1.getOperand(1), N0);
6734   }
6735
6736   return SDValue();
6737 }
6738
6739 SDValue DAGCombiner::visitFSUB(SDNode *N) {
6740   SDValue N0 = N->getOperand(0);
6741   SDValue N1 = N->getOperand(1);
6742   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
6743   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
6744   EVT VT = N->getValueType(0);
6745   SDLoc dl(N);
6746   const TargetOptions &Options = DAG.getTarget().Options;
6747
6748   // fold vector ops
6749   if (VT.isVector()) {
6750     SDValue FoldedVOp = SimplifyVBinOp(N);
6751     if (FoldedVOp.getNode()) return FoldedVOp;
6752   }
6753
6754   // fold (fsub c1, c2) -> c1-c2
6755   if (N0CFP && N1CFP)
6756     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0, N1);
6757
6758   // fold (fsub A, (fneg B)) -> (fadd A, B)
6759   if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
6760     return DAG.getNode(ISD::FADD, dl, VT, N0,
6761                        GetNegatedExpression(N1, DAG, LegalOperations));
6762
6763   // If 'unsafe math' is enabled, fold lots of things.
6764   if (Options.UnsafeFPMath) {
6765     // (fsub A, 0) -> A
6766     if (N1CFP && N1CFP->getValueAPF().isZero())
6767       return N0;
6768
6769     // (fsub 0, B) -> -B
6770     if (N0CFP && N0CFP->getValueAPF().isZero()) {
6771       if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
6772         return GetNegatedExpression(N1, DAG, LegalOperations);
6773       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6774         return DAG.getNode(ISD::FNEG, dl, VT, N1);
6775     }
6776
6777     // (fsub x, x) -> 0.0
6778     if (N0 == N1)
6779       return DAG.getConstantFP(0.0f, VT);
6780
6781     // (fsub x, (fadd x, y)) -> (fneg y)
6782     // (fsub x, (fadd y, x)) -> (fneg y)
6783     if (N1.getOpcode() == ISD::FADD) {
6784       SDValue N10 = N1->getOperand(0);
6785       SDValue N11 = N1->getOperand(1);
6786
6787       if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options))
6788         return GetNegatedExpression(N11, DAG, LegalOperations);
6789
6790       if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options))
6791         return GetNegatedExpression(N10, DAG, LegalOperations);
6792     }
6793   }
6794
6795   // FSUB -> FMA combines:
6796   if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath) &&
6797       TLI.isFMAFasterThanFMulAndFAdd(VT) &&
6798       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6799
6800     // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
6801     if (N0.getOpcode() == ISD::FMUL &&
6802         (N0->hasOneUse() || TLI.enableAggressiveFMAFusion(VT)))
6803       return DAG.getNode(ISD::FMA, dl, VT,
6804                          N0.getOperand(0), N0.getOperand(1),
6805                          DAG.getNode(ISD::FNEG, dl, VT, N1));
6806
6807     // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
6808     // Note: Commutes FSUB operands.
6809     if (N1.getOpcode() == ISD::FMUL &&
6810         (N1->hasOneUse() || TLI.enableAggressiveFMAFusion(VT)))
6811       return DAG.getNode(ISD::FMA, dl, VT,
6812                          DAG.getNode(ISD::FNEG, dl, VT,
6813                          N1.getOperand(0)),
6814                          N1.getOperand(1), N0);
6815
6816     // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
6817     if (N0.getOpcode() == ISD::FNEG &&
6818         N0.getOperand(0).getOpcode() == ISD::FMUL &&
6819         ((N0->hasOneUse() && N0.getOperand(0).hasOneUse()) ||
6820             TLI.enableAggressiveFMAFusion(VT))) {
6821       SDValue N00 = N0.getOperand(0).getOperand(0);
6822       SDValue N01 = N0.getOperand(0).getOperand(1);
6823       return DAG.getNode(ISD::FMA, dl, VT,
6824                          DAG.getNode(ISD::FNEG, dl, VT, N00), N01,
6825                          DAG.getNode(ISD::FNEG, dl, VT, N1));
6826     }
6827   }
6828
6829   return SDValue();
6830 }
6831
6832 SDValue DAGCombiner::visitFMUL(SDNode *N) {
6833   SDValue N0 = N->getOperand(0);
6834   SDValue N1 = N->getOperand(1);
6835   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
6836   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
6837   EVT VT = N->getValueType(0);
6838   const TargetOptions &Options = DAG.getTarget().Options;
6839
6840   // fold vector ops
6841   if (VT.isVector()) {
6842     // This just handles C1 * C2 for vectors. Other vector folds are below.
6843     SDValue FoldedVOp = SimplifyVBinOp(N);
6844     if (FoldedVOp.getNode())
6845       return FoldedVOp;
6846     // Canonicalize vector constant to RHS.
6847     if (N0.getOpcode() == ISD::BUILD_VECTOR &&
6848         N1.getOpcode() != ISD::BUILD_VECTOR)
6849       if (auto *BV0 = dyn_cast<BuildVectorSDNode>(N0))
6850         if (BV0->isConstant())
6851           return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N1, N0);
6852   }
6853
6854   // fold (fmul c1, c2) -> c1*c2
6855   if (N0CFP && N1CFP)
6856     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, N1);
6857
6858   // canonicalize constant to RHS
6859   if (N0CFP && !N1CFP)
6860     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, N0);
6861
6862   // fold (fmul A, 1.0) -> A
6863   if (N1CFP && N1CFP->isExactlyValue(1.0))
6864     return N0;
6865
6866   if (Options.UnsafeFPMath) {
6867     // fold (fmul A, 0) -> 0
6868     if (N1CFP && N1CFP->getValueAPF().isZero())
6869       return N1;
6870
6871     // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
6872     if (N0.getOpcode() == ISD::FMUL) {
6873       // Fold scalars or any vector constants (not just splats).
6874       // This fold is done in general by InstCombine, but extra fmul insts
6875       // may have been generated during lowering.
6876       SDValue N01 = N0.getOperand(1);
6877       auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
6878       auto *BV01 = dyn_cast<BuildVectorSDNode>(N01);
6879       if ((N1CFP && isConstOrConstSplatFP(N01)) ||
6880           (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) {
6881         SDLoc SL(N);
6882         SDValue MulConsts = DAG.getNode(ISD::FMUL, SL, VT, N01, N1);
6883         return DAG.getNode(ISD::FMUL, SL, VT, N0.getOperand(0), MulConsts);
6884       }
6885     }
6886
6887     // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c))
6888     // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs
6889     // during an early run of DAGCombiner can prevent folding with fmuls
6890     // inserted during lowering.
6891     if (N0.getOpcode() == ISD::FADD && N0.getOperand(0) == N0.getOperand(1)) {
6892       SDLoc SL(N);
6893       const SDValue Two = DAG.getConstantFP(2.0, VT);
6894       SDValue MulConsts = DAG.getNode(ISD::FMUL, SL, VT, Two, N1);
6895       return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0), MulConsts);
6896     }
6897   }
6898
6899   // fold (fmul X, 2.0) -> (fadd X, X)
6900   if (N1CFP && N1CFP->isExactlyValue(+2.0))
6901     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N0);
6902
6903   // fold (fmul X, -1.0) -> (fneg X)
6904   if (N1CFP && N1CFP->isExactlyValue(-1.0))
6905     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6906       return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
6907
6908   // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
6909   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
6910     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
6911       // Both can be negated for free, check to see if at least one is cheaper
6912       // negated.
6913       if (LHSNeg == 2 || RHSNeg == 2)
6914         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6915                            GetNegatedExpression(N0, DAG, LegalOperations),
6916                            GetNegatedExpression(N1, DAG, LegalOperations));
6917     }
6918   }
6919
6920   return SDValue();
6921 }
6922
6923 SDValue DAGCombiner::visitFMA(SDNode *N) {
6924   SDValue N0 = N->getOperand(0);
6925   SDValue N1 = N->getOperand(1);
6926   SDValue N2 = N->getOperand(2);
6927   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6928   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6929   EVT VT = N->getValueType(0);
6930   SDLoc dl(N);
6931   const TargetOptions &Options = DAG.getTarget().Options;
6932
6933   // Constant fold FMA.
6934   if (isa<ConstantFPSDNode>(N0) &&
6935       isa<ConstantFPSDNode>(N1) &&
6936       isa<ConstantFPSDNode>(N2)) {
6937     return DAG.getNode(ISD::FMA, dl, VT, N0, N1, N2);
6938   }
6939
6940   if (Options.UnsafeFPMath) {
6941     if (N0CFP && N0CFP->isZero())
6942       return N2;
6943     if (N1CFP && N1CFP->isZero())
6944       return N2;
6945   }
6946   if (N0CFP && N0CFP->isExactlyValue(1.0))
6947     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
6948   if (N1CFP && N1CFP->isExactlyValue(1.0))
6949     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
6950
6951   // Canonicalize (fma c, x, y) -> (fma x, c, y)
6952   if (N0CFP && !N1CFP)
6953     return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
6954
6955   // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
6956   if (Options.UnsafeFPMath && N1CFP &&
6957       N2.getOpcode() == ISD::FMUL &&
6958       N0 == N2.getOperand(0) &&
6959       N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
6960     return DAG.getNode(ISD::FMUL, dl, VT, N0,
6961                        DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
6962   }
6963
6964
6965   // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
6966   if (Options.UnsafeFPMath &&
6967       N0.getOpcode() == ISD::FMUL && N1CFP &&
6968       N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
6969     return DAG.getNode(ISD::FMA, dl, VT,
6970                        N0.getOperand(0),
6971                        DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
6972                        N2);
6973   }
6974
6975   // (fma x, 1, y) -> (fadd x, y)
6976   // (fma x, -1, y) -> (fadd (fneg x), y)
6977   if (N1CFP) {
6978     if (N1CFP->isExactlyValue(1.0))
6979       return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
6980
6981     if (N1CFP->isExactlyValue(-1.0) &&
6982         (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
6983       SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
6984       AddToWorklist(RHSNeg.getNode());
6985       return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
6986     }
6987   }
6988
6989   // (fma x, c, x) -> (fmul x, (c+1))
6990   if (Options.UnsafeFPMath && N1CFP && N0 == N2)
6991     return DAG.getNode(ISD::FMUL, dl, VT, N0,
6992                        DAG.getNode(ISD::FADD, dl, VT,
6993                                    N1, DAG.getConstantFP(1.0, VT)));
6994
6995   // (fma x, c, (fneg x)) -> (fmul x, (c-1))
6996   if (Options.UnsafeFPMath && N1CFP &&
6997       N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
6998     return DAG.getNode(ISD::FMUL, dl, VT, N0,
6999                        DAG.getNode(ISD::FADD, dl, VT,
7000                                    N1, DAG.getConstantFP(-1.0, VT)));
7001
7002
7003   return SDValue();
7004 }
7005
7006 SDValue DAGCombiner::visitFDIV(SDNode *N) {
7007   SDValue N0 = N->getOperand(0);
7008   SDValue N1 = N->getOperand(1);
7009   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7010   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7011   EVT VT = N->getValueType(0);
7012   SDLoc DL(N);
7013   const TargetOptions &Options = DAG.getTarget().Options;
7014
7015   // fold vector ops
7016   if (VT.isVector()) {
7017     SDValue FoldedVOp = SimplifyVBinOp(N);
7018     if (FoldedVOp.getNode()) return FoldedVOp;
7019   }
7020
7021   // fold (fdiv c1, c2) -> c1/c2
7022   if (N0CFP && N1CFP)
7023     return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
7024
7025   if (Options.UnsafeFPMath) {
7026     // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
7027     if (N1CFP) {
7028       // Compute the reciprocal 1.0 / c2.
7029       APFloat N1APF = N1CFP->getValueAPF();
7030       APFloat Recip(N1APF.getSemantics(), 1); // 1.0
7031       APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
7032       // Only do the transform if the reciprocal is a legal fp immediate that
7033       // isn't too nasty (eg NaN, denormal, ...).
7034       if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
7035           (!LegalOperations ||
7036            // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
7037            // backend)... we should handle this gracefully after Legalize.
7038            // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
7039            TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
7040            TLI.isFPImmLegal(Recip, VT)))
7041         return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0,
7042                            DAG.getConstantFP(Recip, VT));
7043     }
7044
7045     // If this FDIV is part of a reciprocal square root, it may be folded
7046     // into a target-specific square root estimate instruction.
7047     if (N1.getOpcode() == ISD::FSQRT) {
7048       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0))) {
7049         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7050       }
7051     } else if (N1.getOpcode() == ISD::FP_EXTEND &&
7052                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
7053       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) {
7054         RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV);
7055         AddToWorklist(RV.getNode());
7056         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7057       }
7058     } else if (N1.getOpcode() == ISD::FP_ROUND &&
7059                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
7060       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) {
7061         RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1));
7062         AddToWorklist(RV.getNode());
7063         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7064       }
7065     } else if (N1.getOpcode() == ISD::FMUL) {
7066       // Look through an FMUL. Even though this won't remove the FDIV directly,
7067       // it's still worthwhile to get rid of the FSQRT if possible.
7068       SDValue SqrtOp;
7069       SDValue OtherOp;
7070       if (N1.getOperand(0).getOpcode() == ISD::FSQRT) {
7071         SqrtOp = N1.getOperand(0);
7072         OtherOp = N1.getOperand(1);
7073       } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) {
7074         SqrtOp = N1.getOperand(1);
7075         OtherOp = N1.getOperand(0);
7076       }
7077       if (SqrtOp.getNode()) {
7078         // We found a FSQRT, so try to make this fold:
7079         // x / (y * sqrt(z)) -> x * (rsqrt(z) / y)
7080         if (SDValue RV = BuildRsqrtEstimate(SqrtOp.getOperand(0))) {
7081           RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp);
7082           AddToWorklist(RV.getNode());
7083           return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7084         }
7085       }
7086     }
7087
7088     // Fold into a reciprocal estimate and multiply instead of a real divide.
7089     if (SDValue RV = BuildReciprocalEstimate(N1)) {
7090       AddToWorklist(RV.getNode());
7091       return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7092     }
7093   }
7094
7095   // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
7096   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
7097     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
7098       // Both can be negated for free, check to see if at least one is cheaper
7099       // negated.
7100       if (LHSNeg == 2 || RHSNeg == 2)
7101         return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
7102                            GetNegatedExpression(N0, DAG, LegalOperations),
7103                            GetNegatedExpression(N1, DAG, LegalOperations));
7104     }
7105   }
7106
7107   return SDValue();
7108 }
7109
7110 SDValue DAGCombiner::visitFREM(SDNode *N) {
7111   SDValue N0 = N->getOperand(0);
7112   SDValue N1 = N->getOperand(1);
7113   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7114   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7115   EVT VT = N->getValueType(0);
7116
7117   // fold (frem c1, c2) -> fmod(c1,c2)
7118   if (N0CFP && N1CFP)
7119     return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
7120
7121   return SDValue();
7122 }
7123
7124 SDValue DAGCombiner::visitFSQRT(SDNode *N) {
7125   if (DAG.getTarget().Options.UnsafeFPMath) {
7126     // Compute this as X * (1/sqrt(X)) = X * (X ** -0.5)
7127     if (SDValue RV = BuildRsqrtEstimate(N->getOperand(0))) {
7128       EVT VT = RV.getValueType();
7129       RV = DAG.getNode(ISD::FMUL, SDLoc(N), VT, N->getOperand(0), RV);
7130       AddToWorklist(RV.getNode());
7131
7132       // Unfortunately, RV is now NaN if the input was exactly 0.
7133       // Select out this case and force the answer to 0.
7134       SDValue Zero = DAG.getConstantFP(0.0, VT);
7135       SDValue ZeroCmp =
7136         DAG.getSetCC(SDLoc(N), TLI.getSetCCResultType(*DAG.getContext(), VT),
7137                      N->getOperand(0), Zero, ISD::SETEQ);
7138       AddToWorklist(ZeroCmp.getNode());
7139       AddToWorklist(RV.getNode());
7140
7141       RV = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT,
7142                        SDLoc(N), VT, ZeroCmp, Zero, RV);
7143       return RV;
7144     }
7145   }
7146   return SDValue();
7147 }
7148
7149 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
7150   SDValue N0 = N->getOperand(0);
7151   SDValue N1 = N->getOperand(1);
7152   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7153   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7154   EVT VT = N->getValueType(0);
7155
7156   if (N0CFP && N1CFP)  // Constant fold
7157     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
7158
7159   if (N1CFP) {
7160     const APFloat& V = N1CFP->getValueAPF();
7161     // copysign(x, c1) -> fabs(x)       iff ispos(c1)
7162     // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
7163     if (!V.isNegative()) {
7164       if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
7165         return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7166     } else {
7167       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
7168         return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
7169                            DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
7170     }
7171   }
7172
7173   // copysign(fabs(x), y) -> copysign(x, y)
7174   // copysign(fneg(x), y) -> copysign(x, y)
7175   // copysign(copysign(x,z), y) -> copysign(x, y)
7176   if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
7177       N0.getOpcode() == ISD::FCOPYSIGN)
7178     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7179                        N0.getOperand(0), N1);
7180
7181   // copysign(x, abs(y)) -> abs(x)
7182   if (N1.getOpcode() == ISD::FABS)
7183     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7184
7185   // copysign(x, copysign(y,z)) -> copysign(x, z)
7186   if (N1.getOpcode() == ISD::FCOPYSIGN)
7187     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7188                        N0, N1.getOperand(1));
7189
7190   // copysign(x, fp_extend(y)) -> copysign(x, y)
7191   // copysign(x, fp_round(y)) -> copysign(x, y)
7192   if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
7193     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7194                        N0, N1.getOperand(0));
7195
7196   return SDValue();
7197 }
7198
7199 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
7200   SDValue N0 = N->getOperand(0);
7201   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
7202   EVT VT = N->getValueType(0);
7203   EVT OpVT = N0.getValueType();
7204
7205   // fold (sint_to_fp c1) -> c1fp
7206   if (N0C &&
7207       // ...but only if the target supports immediate floating-point values
7208       (!LegalOperations ||
7209        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
7210     return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
7211
7212   // If the input is a legal type, and SINT_TO_FP is not legal on this target,
7213   // but UINT_TO_FP is legal on this target, try to convert.
7214   if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
7215       TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
7216     // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
7217     if (DAG.SignBitIsZero(N0))
7218       return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
7219   }
7220
7221   // The next optimizations are desirable only if SELECT_CC can be lowered.
7222   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
7223     // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
7224     if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
7225         !VT.isVector() &&
7226         (!LegalOperations ||
7227          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7228       SDValue Ops[] =
7229         { N0.getOperand(0), N0.getOperand(1),
7230           DAG.getConstantFP(-1.0, VT) , DAG.getConstantFP(0.0, VT),
7231           N0.getOperand(2) };
7232       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7233     }
7234
7235     // fold (sint_to_fp (zext (setcc x, y, cc))) ->
7236     //      (select_cc x, y, 1.0, 0.0,, cc)
7237     if (N0.getOpcode() == ISD::ZERO_EXTEND &&
7238         N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
7239         (!LegalOperations ||
7240          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7241       SDValue Ops[] =
7242         { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
7243           DAG.getConstantFP(1.0, VT) , DAG.getConstantFP(0.0, VT),
7244           N0.getOperand(0).getOperand(2) };
7245       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7246     }
7247   }
7248
7249   return SDValue();
7250 }
7251
7252 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
7253   SDValue N0 = N->getOperand(0);
7254   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
7255   EVT VT = N->getValueType(0);
7256   EVT OpVT = N0.getValueType();
7257
7258   // fold (uint_to_fp c1) -> c1fp
7259   if (N0C &&
7260       // ...but only if the target supports immediate floating-point values
7261       (!LegalOperations ||
7262        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
7263     return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
7264
7265   // If the input is a legal type, and UINT_TO_FP is not legal on this target,
7266   // but SINT_TO_FP is legal on this target, try to convert.
7267   if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
7268       TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
7269     // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
7270     if (DAG.SignBitIsZero(N0))
7271       return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
7272   }
7273
7274   // The next optimizations are desirable only if SELECT_CC can be lowered.
7275   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
7276     // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
7277
7278     if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
7279         (!LegalOperations ||
7280          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7281       SDValue Ops[] =
7282         { N0.getOperand(0), N0.getOperand(1),
7283           DAG.getConstantFP(1.0, VT),  DAG.getConstantFP(0.0, VT),
7284           N0.getOperand(2) };
7285       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7286     }
7287   }
7288
7289   return SDValue();
7290 }
7291
7292 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
7293   SDValue N0 = N->getOperand(0);
7294   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7295   EVT VT = N->getValueType(0);
7296
7297   // fold (fp_to_sint c1fp) -> c1
7298   if (N0CFP)
7299     return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
7300
7301   return SDValue();
7302 }
7303
7304 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
7305   SDValue N0 = N->getOperand(0);
7306   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7307   EVT VT = N->getValueType(0);
7308
7309   // fold (fp_to_uint c1fp) -> c1
7310   if (N0CFP)
7311     return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
7312
7313   return SDValue();
7314 }
7315
7316 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
7317   SDValue N0 = N->getOperand(0);
7318   SDValue N1 = N->getOperand(1);
7319   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7320   EVT VT = N->getValueType(0);
7321
7322   // fold (fp_round c1fp) -> c1fp
7323   if (N0CFP)
7324     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
7325
7326   // fold (fp_round (fp_extend x)) -> x
7327   if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
7328     return N0.getOperand(0);
7329
7330   // fold (fp_round (fp_round x)) -> (fp_round x)
7331   if (N0.getOpcode() == ISD::FP_ROUND) {
7332     // This is a value preserving truncation if both round's are.
7333     bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
7334                    N0.getNode()->getConstantOperandVal(1) == 1;
7335     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0.getOperand(0),
7336                        DAG.getIntPtrConstant(IsTrunc));
7337   }
7338
7339   // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
7340   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
7341     SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
7342                               N0.getOperand(0), N1);
7343     AddToWorklist(Tmp.getNode());
7344     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7345                        Tmp, N0.getOperand(1));
7346   }
7347
7348   return SDValue();
7349 }
7350
7351 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
7352   SDValue N0 = N->getOperand(0);
7353   EVT VT = N->getValueType(0);
7354   EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
7355   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7356
7357   // fold (fp_round_inreg c1fp) -> c1fp
7358   if (N0CFP && isTypeLegal(EVT)) {
7359     SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
7360     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, Round);
7361   }
7362
7363   return SDValue();
7364 }
7365
7366 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
7367   SDValue N0 = N->getOperand(0);
7368   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7369   EVT VT = N->getValueType(0);
7370
7371   // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
7372   if (N->hasOneUse() &&
7373       N->use_begin()->getOpcode() == ISD::FP_ROUND)
7374     return SDValue();
7375
7376   // fold (fp_extend c1fp) -> c1fp
7377   if (N0CFP)
7378     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
7379
7380   // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
7381   // value of X.
7382   if (N0.getOpcode() == ISD::FP_ROUND
7383       && N0.getNode()->getConstantOperandVal(1) == 1) {
7384     SDValue In = N0.getOperand(0);
7385     if (In.getValueType() == VT) return In;
7386     if (VT.bitsLT(In.getValueType()))
7387       return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
7388                          In, N0.getOperand(1));
7389     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
7390   }
7391
7392   // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
7393   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7394        TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType())) {
7395     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7396     SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
7397                                      LN0->getChain(),
7398                                      LN0->getBasePtr(), N0.getValueType(),
7399                                      LN0->getMemOperand());
7400     CombineTo(N, ExtLoad);
7401     CombineTo(N0.getNode(),
7402               DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
7403                           N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
7404               ExtLoad.getValue(1));
7405     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7406   }
7407
7408   return SDValue();
7409 }
7410
7411 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
7412   SDValue N0 = N->getOperand(0);
7413   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7414   EVT VT = N->getValueType(0);
7415
7416   // fold (fceil c1) -> fceil(c1)
7417   if (N0CFP)
7418     return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
7419
7420   return SDValue();
7421 }
7422
7423 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
7424   SDValue N0 = N->getOperand(0);
7425   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7426   EVT VT = N->getValueType(0);
7427
7428   // fold (ftrunc c1) -> ftrunc(c1)
7429   if (N0CFP)
7430     return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
7431
7432   return SDValue();
7433 }
7434
7435 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
7436   SDValue N0 = N->getOperand(0);
7437   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7438   EVT VT = N->getValueType(0);
7439
7440   // fold (ffloor c1) -> ffloor(c1)
7441   if (N0CFP)
7442     return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
7443
7444   return SDValue();
7445 }
7446
7447 // FIXME: FNEG and FABS have a lot in common; refactor.
7448 SDValue DAGCombiner::visitFNEG(SDNode *N) {
7449   SDValue N0 = N->getOperand(0);
7450   EVT VT = N->getValueType(0);
7451
7452   if (VT.isVector()) {
7453     SDValue FoldedVOp = SimplifyVUnaryOp(N);
7454     if (FoldedVOp.getNode()) return FoldedVOp;
7455   }
7456
7457   // Constant fold FNEG.
7458   if (isa<ConstantFPSDNode>(N0))
7459     return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N->getOperand(0));
7460
7461   if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
7462                          &DAG.getTarget().Options))
7463     return GetNegatedExpression(N0, DAG, LegalOperations);
7464
7465   // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading
7466   // constant pool values.
7467   if (!TLI.isFNegFree(VT) &&
7468       N0.getOpcode() == ISD::BITCAST &&
7469       N0.getNode()->hasOneUse()) {
7470     SDValue Int = N0.getOperand(0);
7471     EVT IntVT = Int.getValueType();
7472     if (IntVT.isInteger() && !IntVT.isVector()) {
7473       APInt SignMask;
7474       if (N0.getValueType().isVector()) {
7475         // For a vector, get a mask such as 0x80... per scalar element
7476         // and splat it.
7477         SignMask = APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
7478         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
7479       } else {
7480         // For a scalar, just generate 0x80...
7481         SignMask = APInt::getSignBit(IntVT.getSizeInBits());
7482       }
7483       Int = DAG.getNode(ISD::XOR, SDLoc(N0), IntVT, Int,
7484                         DAG.getConstant(SignMask, IntVT));
7485       AddToWorklist(Int.getNode());
7486       return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Int);
7487     }
7488   }
7489
7490   // (fneg (fmul c, x)) -> (fmul -c, x)
7491   if (N0.getOpcode() == ISD::FMUL) {
7492     ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
7493     if (CFP1) {
7494       APFloat CVal = CFP1->getValueAPF();
7495       CVal.changeSign();
7496       if (Level >= AfterLegalizeDAG &&
7497           (TLI.isFPImmLegal(CVal, N->getValueType(0)) ||
7498            TLI.isOperationLegal(ISD::ConstantFP, N->getValueType(0))))
7499         return DAG.getNode(
7500             ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
7501             DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0.getOperand(1)));
7502     }
7503   }
7504
7505   return SDValue();
7506 }
7507
7508 SDValue DAGCombiner::visitFMINNUM(SDNode *N) {
7509   SDValue N0 = N->getOperand(0);
7510   SDValue N1 = N->getOperand(1);
7511   const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7512   const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7513
7514   if (N0CFP && N1CFP) {
7515     const APFloat &C0 = N0CFP->getValueAPF();
7516     const APFloat &C1 = N1CFP->getValueAPF();
7517     return DAG.getConstantFP(minnum(C0, C1), N->getValueType(0));
7518   }
7519
7520   if (N0CFP) {
7521     EVT VT = N->getValueType(0);
7522     // Canonicalize to constant on RHS.
7523     return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0);
7524   }
7525
7526   return SDValue();
7527 }
7528
7529 SDValue DAGCombiner::visitFMAXNUM(SDNode *N) {
7530   SDValue N0 = N->getOperand(0);
7531   SDValue N1 = N->getOperand(1);
7532   const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7533   const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7534
7535   if (N0CFP && N1CFP) {
7536     const APFloat &C0 = N0CFP->getValueAPF();
7537     const APFloat &C1 = N1CFP->getValueAPF();
7538     return DAG.getConstantFP(maxnum(C0, C1), N->getValueType(0));
7539   }
7540
7541   if (N0CFP) {
7542     EVT VT = N->getValueType(0);
7543     // Canonicalize to constant on RHS.
7544     return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0);
7545   }
7546
7547   return SDValue();
7548 }
7549
7550 SDValue DAGCombiner::visitFABS(SDNode *N) {
7551   SDValue N0 = N->getOperand(0);
7552   EVT VT = N->getValueType(0);
7553
7554   if (VT.isVector()) {
7555     SDValue FoldedVOp = SimplifyVUnaryOp(N);
7556     if (FoldedVOp.getNode()) return FoldedVOp;
7557   }
7558
7559   // fold (fabs c1) -> fabs(c1)
7560   if (isa<ConstantFPSDNode>(N0))
7561     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7562
7563   // fold (fabs (fabs x)) -> (fabs x)
7564   if (N0.getOpcode() == ISD::FABS)
7565     return N->getOperand(0);
7566
7567   // fold (fabs (fneg x)) -> (fabs x)
7568   // fold (fabs (fcopysign x, y)) -> (fabs x)
7569   if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
7570     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
7571
7572   // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading
7573   // constant pool values.
7574   if (!TLI.isFAbsFree(VT) &&
7575       N0.getOpcode() == ISD::BITCAST &&
7576       N0.getNode()->hasOneUse()) {
7577     SDValue Int = N0.getOperand(0);
7578     EVT IntVT = Int.getValueType();
7579     if (IntVT.isInteger() && !IntVT.isVector()) {
7580       APInt SignMask;
7581       if (N0.getValueType().isVector()) {
7582         // For a vector, get a mask such as 0x7f... per scalar element
7583         // and splat it.
7584         SignMask = ~APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
7585         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
7586       } else {
7587         // For a scalar, just generate 0x7f...
7588         SignMask = ~APInt::getSignBit(IntVT.getSizeInBits());
7589       }
7590       Int = DAG.getNode(ISD::AND, SDLoc(N0), IntVT, Int,
7591                         DAG.getConstant(SignMask, IntVT));
7592       AddToWorklist(Int.getNode());
7593       return DAG.getNode(ISD::BITCAST, SDLoc(N), N->getValueType(0), Int);
7594     }
7595   }
7596
7597   return SDValue();
7598 }
7599
7600 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
7601   SDValue Chain = N->getOperand(0);
7602   SDValue N1 = N->getOperand(1);
7603   SDValue N2 = N->getOperand(2);
7604
7605   // If N is a constant we could fold this into a fallthrough or unconditional
7606   // branch. However that doesn't happen very often in normal code, because
7607   // Instcombine/SimplifyCFG should have handled the available opportunities.
7608   // If we did this folding here, it would be necessary to update the
7609   // MachineBasicBlock CFG, which is awkward.
7610
7611   // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
7612   // on the target.
7613   if (N1.getOpcode() == ISD::SETCC &&
7614       TLI.isOperationLegalOrCustom(ISD::BR_CC,
7615                                    N1.getOperand(0).getValueType())) {
7616     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7617                        Chain, N1.getOperand(2),
7618                        N1.getOperand(0), N1.getOperand(1), N2);
7619   }
7620
7621   if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
7622       ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
7623        (N1.getOperand(0).hasOneUse() &&
7624         N1.getOperand(0).getOpcode() == ISD::SRL))) {
7625     SDNode *Trunc = nullptr;
7626     if (N1.getOpcode() == ISD::TRUNCATE) {
7627       // Look pass the truncate.
7628       Trunc = N1.getNode();
7629       N1 = N1.getOperand(0);
7630     }
7631
7632     // Match this pattern so that we can generate simpler code:
7633     //
7634     //   %a = ...
7635     //   %b = and i32 %a, 2
7636     //   %c = srl i32 %b, 1
7637     //   brcond i32 %c ...
7638     //
7639     // into
7640     //
7641     //   %a = ...
7642     //   %b = and i32 %a, 2
7643     //   %c = setcc eq %b, 0
7644     //   brcond %c ...
7645     //
7646     // This applies only when the AND constant value has one bit set and the
7647     // SRL constant is equal to the log2 of the AND constant. The back-end is
7648     // smart enough to convert the result into a TEST/JMP sequence.
7649     SDValue Op0 = N1.getOperand(0);
7650     SDValue Op1 = N1.getOperand(1);
7651
7652     if (Op0.getOpcode() == ISD::AND &&
7653         Op1.getOpcode() == ISD::Constant) {
7654       SDValue AndOp1 = Op0.getOperand(1);
7655
7656       if (AndOp1.getOpcode() == ISD::Constant) {
7657         const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
7658
7659         if (AndConst.isPowerOf2() &&
7660             cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
7661           SDValue SetCC =
7662             DAG.getSetCC(SDLoc(N),
7663                          getSetCCResultType(Op0.getValueType()),
7664                          Op0, DAG.getConstant(0, Op0.getValueType()),
7665                          ISD::SETNE);
7666
7667           SDValue NewBRCond = DAG.getNode(ISD::BRCOND, SDLoc(N),
7668                                           MVT::Other, Chain, SetCC, N2);
7669           // Don't add the new BRCond into the worklist or else SimplifySelectCC
7670           // will convert it back to (X & C1) >> C2.
7671           CombineTo(N, NewBRCond, false);
7672           // Truncate is dead.
7673           if (Trunc)
7674             deleteAndRecombine(Trunc);
7675           // Replace the uses of SRL with SETCC
7676           WorklistRemover DeadNodes(*this);
7677           DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
7678           deleteAndRecombine(N1.getNode());
7679           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7680         }
7681       }
7682     }
7683
7684     if (Trunc)
7685       // Restore N1 if the above transformation doesn't match.
7686       N1 = N->getOperand(1);
7687   }
7688
7689   // Transform br(xor(x, y)) -> br(x != y)
7690   // Transform br(xor(xor(x,y), 1)) -> br (x == y)
7691   if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
7692     SDNode *TheXor = N1.getNode();
7693     SDValue Op0 = TheXor->getOperand(0);
7694     SDValue Op1 = TheXor->getOperand(1);
7695     if (Op0.getOpcode() == Op1.getOpcode()) {
7696       // Avoid missing important xor optimizations.
7697       SDValue Tmp = visitXOR(TheXor);
7698       if (Tmp.getNode()) {
7699         if (Tmp.getNode() != TheXor) {
7700           DEBUG(dbgs() << "\nReplacing.8 ";
7701                 TheXor->dump(&DAG);
7702                 dbgs() << "\nWith: ";
7703                 Tmp.getNode()->dump(&DAG);
7704                 dbgs() << '\n');
7705           WorklistRemover DeadNodes(*this);
7706           DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
7707           deleteAndRecombine(TheXor);
7708           return DAG.getNode(ISD::BRCOND, SDLoc(N),
7709                              MVT::Other, Chain, Tmp, N2);
7710         }
7711
7712         // visitXOR has changed XOR's operands or replaced the XOR completely,
7713         // bail out.
7714         return SDValue(N, 0);
7715       }
7716     }
7717
7718     if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
7719       bool Equal = false;
7720       if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
7721         if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
7722             Op0.getOpcode() == ISD::XOR) {
7723           TheXor = Op0.getNode();
7724           Equal = true;
7725         }
7726
7727       EVT SetCCVT = N1.getValueType();
7728       if (LegalTypes)
7729         SetCCVT = getSetCCResultType(SetCCVT);
7730       SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
7731                                    SetCCVT,
7732                                    Op0, Op1,
7733                                    Equal ? ISD::SETEQ : ISD::SETNE);
7734       // Replace the uses of XOR with SETCC
7735       WorklistRemover DeadNodes(*this);
7736       DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
7737       deleteAndRecombine(N1.getNode());
7738       return DAG.getNode(ISD::BRCOND, SDLoc(N),
7739                          MVT::Other, Chain, SetCC, N2);
7740     }
7741   }
7742
7743   return SDValue();
7744 }
7745
7746 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
7747 //
7748 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
7749   CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
7750   SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
7751
7752   // If N is a constant we could fold this into a fallthrough or unconditional
7753   // branch. However that doesn't happen very often in normal code, because
7754   // Instcombine/SimplifyCFG should have handled the available opportunities.
7755   // If we did this folding here, it would be necessary to update the
7756   // MachineBasicBlock CFG, which is awkward.
7757
7758   // Use SimplifySetCC to simplify SETCC's.
7759   SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
7760                                CondLHS, CondRHS, CC->get(), SDLoc(N),
7761                                false);
7762   if (Simp.getNode()) AddToWorklist(Simp.getNode());
7763
7764   // fold to a simpler setcc
7765   if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
7766     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7767                        N->getOperand(0), Simp.getOperand(2),
7768                        Simp.getOperand(0), Simp.getOperand(1),
7769                        N->getOperand(4));
7770
7771   return SDValue();
7772 }
7773
7774 /// Return true if 'Use' is a load or a store that uses N as its base pointer
7775 /// and that N may be folded in the load / store addressing mode.
7776 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
7777                                     SelectionDAG &DAG,
7778                                     const TargetLowering &TLI) {
7779   EVT VT;
7780   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(Use)) {
7781     if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
7782       return false;
7783     VT = Use->getValueType(0);
7784   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(Use)) {
7785     if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
7786       return false;
7787     VT = ST->getValue().getValueType();
7788   } else
7789     return false;
7790
7791   TargetLowering::AddrMode AM;
7792   if (N->getOpcode() == ISD::ADD) {
7793     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7794     if (Offset)
7795       // [reg +/- imm]
7796       AM.BaseOffs = Offset->getSExtValue();
7797     else
7798       // [reg +/- reg]
7799       AM.Scale = 1;
7800   } else if (N->getOpcode() == ISD::SUB) {
7801     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7802     if (Offset)
7803       // [reg +/- imm]
7804       AM.BaseOffs = -Offset->getSExtValue();
7805     else
7806       // [reg +/- reg]
7807       AM.Scale = 1;
7808   } else
7809     return false;
7810
7811   return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
7812 }
7813
7814 /// Try turning a load/store into a pre-indexed load/store when the base
7815 /// pointer is an add or subtract and it has other uses besides the load/store.
7816 /// After the transformation, the new indexed load/store has effectively folded
7817 /// the add/subtract in and all of its other uses are redirected to the
7818 /// new load/store.
7819 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
7820   if (Level < AfterLegalizeDAG)
7821     return false;
7822
7823   bool isLoad = true;
7824   SDValue Ptr;
7825   EVT VT;
7826   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
7827     if (LD->isIndexed())
7828       return false;
7829     VT = LD->getMemoryVT();
7830     if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
7831         !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
7832       return false;
7833     Ptr = LD->getBasePtr();
7834   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
7835     if (ST->isIndexed())
7836       return false;
7837     VT = ST->getMemoryVT();
7838     if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
7839         !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
7840       return false;
7841     Ptr = ST->getBasePtr();
7842     isLoad = false;
7843   } else {
7844     return false;
7845   }
7846
7847   // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
7848   // out.  There is no reason to make this a preinc/predec.
7849   if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
7850       Ptr.getNode()->hasOneUse())
7851     return false;
7852
7853   // Ask the target to do addressing mode selection.
7854   SDValue BasePtr;
7855   SDValue Offset;
7856   ISD::MemIndexedMode AM = ISD::UNINDEXED;
7857   if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
7858     return false;
7859
7860   // Backends without true r+i pre-indexed forms may need to pass a
7861   // constant base with a variable offset so that constant coercion
7862   // will work with the patterns in canonical form.
7863   bool Swapped = false;
7864   if (isa<ConstantSDNode>(BasePtr)) {
7865     std::swap(BasePtr, Offset);
7866     Swapped = true;
7867   }
7868
7869   // Don't create a indexed load / store with zero offset.
7870   if (isa<ConstantSDNode>(Offset) &&
7871       cast<ConstantSDNode>(Offset)->isNullValue())
7872     return false;
7873
7874   // Try turning it into a pre-indexed load / store except when:
7875   // 1) The new base ptr is a frame index.
7876   // 2) If N is a store and the new base ptr is either the same as or is a
7877   //    predecessor of the value being stored.
7878   // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
7879   //    that would create a cycle.
7880   // 4) All uses are load / store ops that use it as old base ptr.
7881
7882   // Check #1.  Preinc'ing a frame index would require copying the stack pointer
7883   // (plus the implicit offset) to a register to preinc anyway.
7884   if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7885     return false;
7886
7887   // Check #2.
7888   if (!isLoad) {
7889     SDValue Val = cast<StoreSDNode>(N)->getValue();
7890     if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
7891       return false;
7892   }
7893
7894   // If the offset is a constant, there may be other adds of constants that
7895   // can be folded with this one. We should do this to avoid having to keep
7896   // a copy of the original base pointer.
7897   SmallVector<SDNode *, 16> OtherUses;
7898   if (isa<ConstantSDNode>(Offset))
7899     for (SDNode *Use : BasePtr.getNode()->uses()) {
7900       if (Use == Ptr.getNode())
7901         continue;
7902
7903       if (Use->isPredecessorOf(N))
7904         continue;
7905
7906       if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) {
7907         OtherUses.clear();
7908         break;
7909       }
7910
7911       SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1);
7912       if (Op1.getNode() == BasePtr.getNode())
7913         std::swap(Op0, Op1);
7914       assert(Op0.getNode() == BasePtr.getNode() &&
7915              "Use of ADD/SUB but not an operand");
7916
7917       if (!isa<ConstantSDNode>(Op1)) {
7918         OtherUses.clear();
7919         break;
7920       }
7921
7922       // FIXME: In some cases, we can be smarter about this.
7923       if (Op1.getValueType() != Offset.getValueType()) {
7924         OtherUses.clear();
7925         break;
7926       }
7927
7928       OtherUses.push_back(Use);
7929     }
7930
7931   if (Swapped)
7932     std::swap(BasePtr, Offset);
7933
7934   // Now check for #3 and #4.
7935   bool RealUse = false;
7936
7937   // Caches for hasPredecessorHelper
7938   SmallPtrSet<const SDNode *, 32> Visited;
7939   SmallVector<const SDNode *, 16> Worklist;
7940
7941   for (SDNode *Use : Ptr.getNode()->uses()) {
7942     if (Use == N)
7943       continue;
7944     if (N->hasPredecessorHelper(Use, Visited, Worklist))
7945       return false;
7946
7947     // If Ptr may be folded in addressing mode of other use, then it's
7948     // not profitable to do this transformation.
7949     if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
7950       RealUse = true;
7951   }
7952
7953   if (!RealUse)
7954     return false;
7955
7956   SDValue Result;
7957   if (isLoad)
7958     Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
7959                                 BasePtr, Offset, AM);
7960   else
7961     Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
7962                                  BasePtr, Offset, AM);
7963   ++PreIndexedNodes;
7964   ++NodesCombined;
7965   DEBUG(dbgs() << "\nReplacing.4 ";
7966         N->dump(&DAG);
7967         dbgs() << "\nWith: ";
7968         Result.getNode()->dump(&DAG);
7969         dbgs() << '\n');
7970   WorklistRemover DeadNodes(*this);
7971   if (isLoad) {
7972     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7973     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
7974   } else {
7975     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
7976   }
7977
7978   // Finally, since the node is now dead, remove it from the graph.
7979   deleteAndRecombine(N);
7980
7981   if (Swapped)
7982     std::swap(BasePtr, Offset);
7983
7984   // Replace other uses of BasePtr that can be updated to use Ptr
7985   for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
7986     unsigned OffsetIdx = 1;
7987     if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
7988       OffsetIdx = 0;
7989     assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
7990            BasePtr.getNode() && "Expected BasePtr operand");
7991
7992     // We need to replace ptr0 in the following expression:
7993     //   x0 * offset0 + y0 * ptr0 = t0
7994     // knowing that
7995     //   x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
7996     //
7997     // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
7998     // indexed load/store and the expresion that needs to be re-written.
7999     //
8000     // Therefore, we have:
8001     //   t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
8002
8003     ConstantSDNode *CN =
8004       cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
8005     int X0, X1, Y0, Y1;
8006     APInt Offset0 = CN->getAPIntValue();
8007     APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
8008
8009     X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
8010     Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
8011     X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
8012     Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
8013
8014     unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
8015
8016     APInt CNV = Offset0;
8017     if (X0 < 0) CNV = -CNV;
8018     if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
8019     else CNV = CNV - Offset1;
8020
8021     // We can now generate the new expression.
8022     SDValue NewOp1 = DAG.getConstant(CNV, CN->getValueType(0));
8023     SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
8024
8025     SDValue NewUse = DAG.getNode(Opcode,
8026                                  SDLoc(OtherUses[i]),
8027                                  OtherUses[i]->getValueType(0), NewOp1, NewOp2);
8028     DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
8029     deleteAndRecombine(OtherUses[i]);
8030   }
8031
8032   // Replace the uses of Ptr with uses of the updated base value.
8033   DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
8034   deleteAndRecombine(Ptr.getNode());
8035
8036   return true;
8037 }
8038
8039 /// Try to combine a load/store with a add/sub of the base pointer node into a
8040 /// post-indexed load/store. The transformation folded the add/subtract into the
8041 /// new indexed load/store effectively and all of its uses are redirected to the
8042 /// new load/store.
8043 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
8044   if (Level < AfterLegalizeDAG)
8045     return false;
8046
8047   bool isLoad = true;
8048   SDValue Ptr;
8049   EVT VT;
8050   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
8051     if (LD->isIndexed())
8052       return false;
8053     VT = LD->getMemoryVT();
8054     if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
8055         !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
8056       return false;
8057     Ptr = LD->getBasePtr();
8058   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
8059     if (ST->isIndexed())
8060       return false;
8061     VT = ST->getMemoryVT();
8062     if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
8063         !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
8064       return false;
8065     Ptr = ST->getBasePtr();
8066     isLoad = false;
8067   } else {
8068     return false;
8069   }
8070
8071   if (Ptr.getNode()->hasOneUse())
8072     return false;
8073
8074   for (SDNode *Op : Ptr.getNode()->uses()) {
8075     if (Op == N ||
8076         (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
8077       continue;
8078
8079     SDValue BasePtr;
8080     SDValue Offset;
8081     ISD::MemIndexedMode AM = ISD::UNINDEXED;
8082     if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
8083       // Don't create a indexed load / store with zero offset.
8084       if (isa<ConstantSDNode>(Offset) &&
8085           cast<ConstantSDNode>(Offset)->isNullValue())
8086         continue;
8087
8088       // Try turning it into a post-indexed load / store except when
8089       // 1) All uses are load / store ops that use it as base ptr (and
8090       //    it may be folded as addressing mmode).
8091       // 2) Op must be independent of N, i.e. Op is neither a predecessor
8092       //    nor a successor of N. Otherwise, if Op is folded that would
8093       //    create a cycle.
8094
8095       if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
8096         continue;
8097
8098       // Check for #1.
8099       bool TryNext = false;
8100       for (SDNode *Use : BasePtr.getNode()->uses()) {
8101         if (Use == Ptr.getNode())
8102           continue;
8103
8104         // If all the uses are load / store addresses, then don't do the
8105         // transformation.
8106         if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
8107           bool RealUse = false;
8108           for (SDNode *UseUse : Use->uses()) {
8109             if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
8110               RealUse = true;
8111           }
8112
8113           if (!RealUse) {
8114             TryNext = true;
8115             break;
8116           }
8117         }
8118       }
8119
8120       if (TryNext)
8121         continue;
8122
8123       // Check for #2
8124       if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
8125         SDValue Result = isLoad
8126           ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
8127                                BasePtr, Offset, AM)
8128           : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
8129                                 BasePtr, Offset, AM);
8130         ++PostIndexedNodes;
8131         ++NodesCombined;
8132         DEBUG(dbgs() << "\nReplacing.5 ";
8133               N->dump(&DAG);
8134               dbgs() << "\nWith: ";
8135               Result.getNode()->dump(&DAG);
8136               dbgs() << '\n');
8137         WorklistRemover DeadNodes(*this);
8138         if (isLoad) {
8139           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
8140           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
8141         } else {
8142           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
8143         }
8144
8145         // Finally, since the node is now dead, remove it from the graph.
8146         deleteAndRecombine(N);
8147
8148         // Replace the uses of Use with uses of the updated base value.
8149         DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
8150                                       Result.getValue(isLoad ? 1 : 0));
8151         deleteAndRecombine(Op);
8152         return true;
8153       }
8154     }
8155   }
8156
8157   return false;
8158 }
8159
8160 /// \brief Return the base-pointer arithmetic from an indexed \p LD.
8161 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) {
8162   ISD::MemIndexedMode AM = LD->getAddressingMode();
8163   assert(AM != ISD::UNINDEXED);
8164   SDValue BP = LD->getOperand(1);
8165   SDValue Inc = LD->getOperand(2);
8166
8167   // Some backends use TargetConstants for load offsets, but don't expect
8168   // TargetConstants in general ADD nodes. We can convert these constants into
8169   // regular Constants (if the constant is not opaque).
8170   assert((Inc.getOpcode() != ISD::TargetConstant ||
8171           !cast<ConstantSDNode>(Inc)->isOpaque()) &&
8172          "Cannot split out indexing using opaque target constants");
8173   if (Inc.getOpcode() == ISD::TargetConstant) {
8174     ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc);
8175     Inc = DAG.getConstant(*ConstInc->getConstantIntValue(),
8176                           ConstInc->getValueType(0));
8177   }
8178
8179   unsigned Opc =
8180       (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB);
8181   return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc);
8182 }
8183
8184 SDValue DAGCombiner::visitLOAD(SDNode *N) {
8185   LoadSDNode *LD  = cast<LoadSDNode>(N);
8186   SDValue Chain = LD->getChain();
8187   SDValue Ptr   = LD->getBasePtr();
8188
8189   // If load is not volatile and there are no uses of the loaded value (and
8190   // the updated indexed value in case of indexed loads), change uses of the
8191   // chain value into uses of the chain input (i.e. delete the dead load).
8192   if (!LD->isVolatile()) {
8193     if (N->getValueType(1) == MVT::Other) {
8194       // Unindexed loads.
8195       if (!N->hasAnyUseOfValue(0)) {
8196         // It's not safe to use the two value CombineTo variant here. e.g.
8197         // v1, chain2 = load chain1, loc
8198         // v2, chain3 = load chain2, loc
8199         // v3         = add v2, c
8200         // Now we replace use of chain2 with chain1.  This makes the second load
8201         // isomorphic to the one we are deleting, and thus makes this load live.
8202         DEBUG(dbgs() << "\nReplacing.6 ";
8203               N->dump(&DAG);
8204               dbgs() << "\nWith chain: ";
8205               Chain.getNode()->dump(&DAG);
8206               dbgs() << "\n");
8207         WorklistRemover DeadNodes(*this);
8208         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
8209
8210         if (N->use_empty())
8211           deleteAndRecombine(N);
8212
8213         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
8214       }
8215     } else {
8216       // Indexed loads.
8217       assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
8218
8219       // If this load has an opaque TargetConstant offset, then we cannot split
8220       // the indexing into an add/sub directly (that TargetConstant may not be
8221       // valid for a different type of node, and we cannot convert an opaque
8222       // target constant into a regular constant).
8223       bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant &&
8224                        cast<ConstantSDNode>(LD->getOperand(2))->isOpaque();
8225
8226       if (!N->hasAnyUseOfValue(0) &&
8227           ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) {
8228         SDValue Undef = DAG.getUNDEF(N->getValueType(0));
8229         SDValue Index;
8230         if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) {
8231           Index = SplitIndexingFromLoad(LD);
8232           // Try to fold the base pointer arithmetic into subsequent loads and
8233           // stores.
8234           AddUsersToWorklist(N);
8235         } else
8236           Index = DAG.getUNDEF(N->getValueType(1));
8237         DEBUG(dbgs() << "\nReplacing.7 ";
8238               N->dump(&DAG);
8239               dbgs() << "\nWith: ";
8240               Undef.getNode()->dump(&DAG);
8241               dbgs() << " and 2 other values\n");
8242         WorklistRemover DeadNodes(*this);
8243         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
8244         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index);
8245         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
8246         deleteAndRecombine(N);
8247         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
8248       }
8249     }
8250   }
8251
8252   // If this load is directly stored, replace the load value with the stored
8253   // value.
8254   // TODO: Handle store large -> read small portion.
8255   // TODO: Handle TRUNCSTORE/LOADEXT
8256   if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
8257     if (ISD::isNON_TRUNCStore(Chain.getNode())) {
8258       StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
8259       if (PrevST->getBasePtr() == Ptr &&
8260           PrevST->getValue().getValueType() == N->getValueType(0))
8261       return CombineTo(N, Chain.getOperand(1), Chain);
8262     }
8263   }
8264
8265   // Try to infer better alignment information than the load already has.
8266   if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
8267     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
8268       if (Align > LD->getMemOperand()->getBaseAlignment()) {
8269         SDValue NewLoad =
8270                DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
8271                               LD->getValueType(0),
8272                               Chain, Ptr, LD->getPointerInfo(),
8273                               LD->getMemoryVT(),
8274                               LD->isVolatile(), LD->isNonTemporal(),
8275                               LD->isInvariant(), Align, LD->getAAInfo());
8276         return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
8277       }
8278     }
8279   }
8280
8281   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
8282                                                   : DAG.getSubtarget().useAA();
8283 #ifndef NDEBUG
8284   if (CombinerAAOnlyFunc.getNumOccurrences() &&
8285       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
8286     UseAA = false;
8287 #endif
8288   if (UseAA && LD->isUnindexed()) {
8289     // Walk up chain skipping non-aliasing memory nodes.
8290     SDValue BetterChain = FindBetterChain(N, Chain);
8291
8292     // If there is a better chain.
8293     if (Chain != BetterChain) {
8294       SDValue ReplLoad;
8295
8296       // Replace the chain to void dependency.
8297       if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
8298         ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
8299                                BetterChain, Ptr, LD->getMemOperand());
8300       } else {
8301         ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
8302                                   LD->getValueType(0),
8303                                   BetterChain, Ptr, LD->getMemoryVT(),
8304                                   LD->getMemOperand());
8305       }
8306
8307       // Create token factor to keep old chain connected.
8308       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
8309                                   MVT::Other, Chain, ReplLoad.getValue(1));
8310
8311       // Make sure the new and old chains are cleaned up.
8312       AddToWorklist(Token.getNode());
8313
8314       // Replace uses with load result and token factor. Don't add users
8315       // to work list.
8316       return CombineTo(N, ReplLoad.getValue(0), Token, false);
8317     }
8318   }
8319
8320   // Try transforming N to an indexed load.
8321   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
8322     return SDValue(N, 0);
8323
8324   // Try to slice up N to more direct loads if the slices are mapped to
8325   // different register banks or pairing can take place.
8326   if (SliceUpLoad(N))
8327     return SDValue(N, 0);
8328
8329   return SDValue();
8330 }
8331
8332 namespace {
8333 /// \brief Helper structure used to slice a load in smaller loads.
8334 /// Basically a slice is obtained from the following sequence:
8335 /// Origin = load Ty1, Base
8336 /// Shift = srl Ty1 Origin, CstTy Amount
8337 /// Inst = trunc Shift to Ty2
8338 ///
8339 /// Then, it will be rewriten into:
8340 /// Slice = load SliceTy, Base + SliceOffset
8341 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
8342 ///
8343 /// SliceTy is deduced from the number of bits that are actually used to
8344 /// build Inst.
8345 struct LoadedSlice {
8346   /// \brief Helper structure used to compute the cost of a slice.
8347   struct Cost {
8348     /// Are we optimizing for code size.
8349     bool ForCodeSize;
8350     /// Various cost.
8351     unsigned Loads;
8352     unsigned Truncates;
8353     unsigned CrossRegisterBanksCopies;
8354     unsigned ZExts;
8355     unsigned Shift;
8356
8357     Cost(bool ForCodeSize = false)
8358         : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
8359           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
8360
8361     /// \brief Get the cost of one isolated slice.
8362     Cost(const LoadedSlice &LS, bool ForCodeSize = false)
8363         : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
8364           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
8365       EVT TruncType = LS.Inst->getValueType(0);
8366       EVT LoadedType = LS.getLoadedType();
8367       if (TruncType != LoadedType &&
8368           !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
8369         ZExts = 1;
8370     }
8371
8372     /// \brief Account for slicing gain in the current cost.
8373     /// Slicing provide a few gains like removing a shift or a
8374     /// truncate. This method allows to grow the cost of the original
8375     /// load with the gain from this slice.
8376     void addSliceGain(const LoadedSlice &LS) {
8377       // Each slice saves a truncate.
8378       const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
8379       if (!TLI.isTruncateFree(LS.Inst->getValueType(0),
8380                               LS.Inst->getOperand(0).getValueType()))
8381         ++Truncates;
8382       // If there is a shift amount, this slice gets rid of it.
8383       if (LS.Shift)
8384         ++Shift;
8385       // If this slice can merge a cross register bank copy, account for it.
8386       if (LS.canMergeExpensiveCrossRegisterBankCopy())
8387         ++CrossRegisterBanksCopies;
8388     }
8389
8390     Cost &operator+=(const Cost &RHS) {
8391       Loads += RHS.Loads;
8392       Truncates += RHS.Truncates;
8393       CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
8394       ZExts += RHS.ZExts;
8395       Shift += RHS.Shift;
8396       return *this;
8397     }
8398
8399     bool operator==(const Cost &RHS) const {
8400       return Loads == RHS.Loads && Truncates == RHS.Truncates &&
8401              CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
8402              ZExts == RHS.ZExts && Shift == RHS.Shift;
8403     }
8404
8405     bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
8406
8407     bool operator<(const Cost &RHS) const {
8408       // Assume cross register banks copies are as expensive as loads.
8409       // FIXME: Do we want some more target hooks?
8410       unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
8411       unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
8412       // Unless we are optimizing for code size, consider the
8413       // expensive operation first.
8414       if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
8415         return ExpensiveOpsLHS < ExpensiveOpsRHS;
8416       return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
8417              (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
8418     }
8419
8420     bool operator>(const Cost &RHS) const { return RHS < *this; }
8421
8422     bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
8423
8424     bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
8425   };
8426   // The last instruction that represent the slice. This should be a
8427   // truncate instruction.
8428   SDNode *Inst;
8429   // The original load instruction.
8430   LoadSDNode *Origin;
8431   // The right shift amount in bits from the original load.
8432   unsigned Shift;
8433   // The DAG from which Origin came from.
8434   // This is used to get some contextual information about legal types, etc.
8435   SelectionDAG *DAG;
8436
8437   LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
8438               unsigned Shift = 0, SelectionDAG *DAG = nullptr)
8439       : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
8440
8441   LoadedSlice(const LoadedSlice &LS)
8442       : Inst(LS.Inst), Origin(LS.Origin), Shift(LS.Shift), DAG(LS.DAG) {}
8443
8444   /// \brief Get the bits used in a chunk of bits \p BitWidth large.
8445   /// \return Result is \p BitWidth and has used bits set to 1 and
8446   ///         not used bits set to 0.
8447   APInt getUsedBits() const {
8448     // Reproduce the trunc(lshr) sequence:
8449     // - Start from the truncated value.
8450     // - Zero extend to the desired bit width.
8451     // - Shift left.
8452     assert(Origin && "No original load to compare against.");
8453     unsigned BitWidth = Origin->getValueSizeInBits(0);
8454     assert(Inst && "This slice is not bound to an instruction");
8455     assert(Inst->getValueSizeInBits(0) <= BitWidth &&
8456            "Extracted slice is bigger than the whole type!");
8457     APInt UsedBits(Inst->getValueSizeInBits(0), 0);
8458     UsedBits.setAllBits();
8459     UsedBits = UsedBits.zext(BitWidth);
8460     UsedBits <<= Shift;
8461     return UsedBits;
8462   }
8463
8464   /// \brief Get the size of the slice to be loaded in bytes.
8465   unsigned getLoadedSize() const {
8466     unsigned SliceSize = getUsedBits().countPopulation();
8467     assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
8468     return SliceSize / 8;
8469   }
8470
8471   /// \brief Get the type that will be loaded for this slice.
8472   /// Note: This may not be the final type for the slice.
8473   EVT getLoadedType() const {
8474     assert(DAG && "Missing context");
8475     LLVMContext &Ctxt = *DAG->getContext();
8476     return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
8477   }
8478
8479   /// \brief Get the alignment of the load used for this slice.
8480   unsigned getAlignment() const {
8481     unsigned Alignment = Origin->getAlignment();
8482     unsigned Offset = getOffsetFromBase();
8483     if (Offset != 0)
8484       Alignment = MinAlign(Alignment, Alignment + Offset);
8485     return Alignment;
8486   }
8487
8488   /// \brief Check if this slice can be rewritten with legal operations.
8489   bool isLegal() const {
8490     // An invalid slice is not legal.
8491     if (!Origin || !Inst || !DAG)
8492       return false;
8493
8494     // Offsets are for indexed load only, we do not handle that.
8495     if (Origin->getOffset().getOpcode() != ISD::UNDEF)
8496       return false;
8497
8498     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8499
8500     // Check that the type is legal.
8501     EVT SliceType = getLoadedType();
8502     if (!TLI.isTypeLegal(SliceType))
8503       return false;
8504
8505     // Check that the load is legal for this type.
8506     if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
8507       return false;
8508
8509     // Check that the offset can be computed.
8510     // 1. Check its type.
8511     EVT PtrType = Origin->getBasePtr().getValueType();
8512     if (PtrType == MVT::Untyped || PtrType.isExtended())
8513       return false;
8514
8515     // 2. Check that it fits in the immediate.
8516     if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
8517       return false;
8518
8519     // 3. Check that the computation is legal.
8520     if (!TLI.isOperationLegal(ISD::ADD, PtrType))
8521       return false;
8522
8523     // Check that the zext is legal if it needs one.
8524     EVT TruncateType = Inst->getValueType(0);
8525     if (TruncateType != SliceType &&
8526         !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
8527       return false;
8528
8529     return true;
8530   }
8531
8532   /// \brief Get the offset in bytes of this slice in the original chunk of
8533   /// bits.
8534   /// \pre DAG != nullptr.
8535   uint64_t getOffsetFromBase() const {
8536     assert(DAG && "Missing context.");
8537     bool IsBigEndian =
8538         DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian();
8539     assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
8540     uint64_t Offset = Shift / 8;
8541     unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
8542     assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
8543            "The size of the original loaded type is not a multiple of a"
8544            " byte.");
8545     // If Offset is bigger than TySizeInBytes, it means we are loading all
8546     // zeros. This should have been optimized before in the process.
8547     assert(TySizeInBytes > Offset &&
8548            "Invalid shift amount for given loaded size");
8549     if (IsBigEndian)
8550       Offset = TySizeInBytes - Offset - getLoadedSize();
8551     return Offset;
8552   }
8553
8554   /// \brief Generate the sequence of instructions to load the slice
8555   /// represented by this object and redirect the uses of this slice to
8556   /// this new sequence of instructions.
8557   /// \pre this->Inst && this->Origin are valid Instructions and this
8558   /// object passed the legal check: LoadedSlice::isLegal returned true.
8559   /// \return The last instruction of the sequence used to load the slice.
8560   SDValue loadSlice() const {
8561     assert(Inst && Origin && "Unable to replace a non-existing slice.");
8562     const SDValue &OldBaseAddr = Origin->getBasePtr();
8563     SDValue BaseAddr = OldBaseAddr;
8564     // Get the offset in that chunk of bytes w.r.t. the endianess.
8565     int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
8566     assert(Offset >= 0 && "Offset too big to fit in int64_t!");
8567     if (Offset) {
8568       // BaseAddr = BaseAddr + Offset.
8569       EVT ArithType = BaseAddr.getValueType();
8570       BaseAddr = DAG->getNode(ISD::ADD, SDLoc(Origin), ArithType, BaseAddr,
8571                               DAG->getConstant(Offset, ArithType));
8572     }
8573
8574     // Create the type of the loaded slice according to its size.
8575     EVT SliceType = getLoadedType();
8576
8577     // Create the load for the slice.
8578     SDValue LastInst = DAG->getLoad(
8579         SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
8580         Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
8581         Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
8582     // If the final type is not the same as the loaded type, this means that
8583     // we have to pad with zero. Create a zero extend for that.
8584     EVT FinalType = Inst->getValueType(0);
8585     if (SliceType != FinalType)
8586       LastInst =
8587           DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
8588     return LastInst;
8589   }
8590
8591   /// \brief Check if this slice can be merged with an expensive cross register
8592   /// bank copy. E.g.,
8593   /// i = load i32
8594   /// f = bitcast i32 i to float
8595   bool canMergeExpensiveCrossRegisterBankCopy() const {
8596     if (!Inst || !Inst->hasOneUse())
8597       return false;
8598     SDNode *Use = *Inst->use_begin();
8599     if (Use->getOpcode() != ISD::BITCAST)
8600       return false;
8601     assert(DAG && "Missing context");
8602     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8603     EVT ResVT = Use->getValueType(0);
8604     const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
8605     const TargetRegisterClass *ArgRC =
8606         TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
8607     if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
8608       return false;
8609
8610     // At this point, we know that we perform a cross-register-bank copy.
8611     // Check if it is expensive.
8612     const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo();
8613     // Assume bitcasts are cheap, unless both register classes do not
8614     // explicitly share a common sub class.
8615     if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
8616       return false;
8617
8618     // Check if it will be merged with the load.
8619     // 1. Check the alignment constraint.
8620     unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment(
8621         ResVT.getTypeForEVT(*DAG->getContext()));
8622
8623     if (RequiredAlignment > getAlignment())
8624       return false;
8625
8626     // 2. Check that the load is a legal operation for that type.
8627     if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
8628       return false;
8629
8630     // 3. Check that we do not have a zext in the way.
8631     if (Inst->getValueType(0) != getLoadedType())
8632       return false;
8633
8634     return true;
8635   }
8636 };
8637 }
8638
8639 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
8640 /// \p UsedBits looks like 0..0 1..1 0..0.
8641 static bool areUsedBitsDense(const APInt &UsedBits) {
8642   // If all the bits are one, this is dense!
8643   if (UsedBits.isAllOnesValue())
8644     return true;
8645
8646   // Get rid of the unused bits on the right.
8647   APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
8648   // Get rid of the unused bits on the left.
8649   if (NarrowedUsedBits.countLeadingZeros())
8650     NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
8651   // Check that the chunk of bits is completely used.
8652   return NarrowedUsedBits.isAllOnesValue();
8653 }
8654
8655 /// \brief Check whether or not \p First and \p Second are next to each other
8656 /// in memory. This means that there is no hole between the bits loaded
8657 /// by \p First and the bits loaded by \p Second.
8658 static bool areSlicesNextToEachOther(const LoadedSlice &First,
8659                                      const LoadedSlice &Second) {
8660   assert(First.Origin == Second.Origin && First.Origin &&
8661          "Unable to match different memory origins.");
8662   APInt UsedBits = First.getUsedBits();
8663   assert((UsedBits & Second.getUsedBits()) == 0 &&
8664          "Slices are not supposed to overlap.");
8665   UsedBits |= Second.getUsedBits();
8666   return areUsedBitsDense(UsedBits);
8667 }
8668
8669 /// \brief Adjust the \p GlobalLSCost according to the target
8670 /// paring capabilities and the layout of the slices.
8671 /// \pre \p GlobalLSCost should account for at least as many loads as
8672 /// there is in the slices in \p LoadedSlices.
8673 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8674                                  LoadedSlice::Cost &GlobalLSCost) {
8675   unsigned NumberOfSlices = LoadedSlices.size();
8676   // If there is less than 2 elements, no pairing is possible.
8677   if (NumberOfSlices < 2)
8678     return;
8679
8680   // Sort the slices so that elements that are likely to be next to each
8681   // other in memory are next to each other in the list.
8682   std::sort(LoadedSlices.begin(), LoadedSlices.end(),
8683             [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
8684     assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
8685     return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
8686   });
8687   const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
8688   // First (resp. Second) is the first (resp. Second) potentially candidate
8689   // to be placed in a paired load.
8690   const LoadedSlice *First = nullptr;
8691   const LoadedSlice *Second = nullptr;
8692   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
8693                 // Set the beginning of the pair.
8694                                                            First = Second) {
8695
8696     Second = &LoadedSlices[CurrSlice];
8697
8698     // If First is NULL, it means we start a new pair.
8699     // Get to the next slice.
8700     if (!First)
8701       continue;
8702
8703     EVT LoadedType = First->getLoadedType();
8704
8705     // If the types of the slices are different, we cannot pair them.
8706     if (LoadedType != Second->getLoadedType())
8707       continue;
8708
8709     // Check if the target supplies paired loads for this type.
8710     unsigned RequiredAlignment = 0;
8711     if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
8712       // move to the next pair, this type is hopeless.
8713       Second = nullptr;
8714       continue;
8715     }
8716     // Check if we meet the alignment requirement.
8717     if (RequiredAlignment > First->getAlignment())
8718       continue;
8719
8720     // Check that both loads are next to each other in memory.
8721     if (!areSlicesNextToEachOther(*First, *Second))
8722       continue;
8723
8724     assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
8725     --GlobalLSCost.Loads;
8726     // Move to the next pair.
8727     Second = nullptr;
8728   }
8729 }
8730
8731 /// \brief Check the profitability of all involved LoadedSlice.
8732 /// Currently, it is considered profitable if there is exactly two
8733 /// involved slices (1) which are (2) next to each other in memory, and
8734 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
8735 ///
8736 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
8737 /// the elements themselves.
8738 ///
8739 /// FIXME: When the cost model will be mature enough, we can relax
8740 /// constraints (1) and (2).
8741 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8742                                 const APInt &UsedBits, bool ForCodeSize) {
8743   unsigned NumberOfSlices = LoadedSlices.size();
8744   if (StressLoadSlicing)
8745     return NumberOfSlices > 1;
8746
8747   // Check (1).
8748   if (NumberOfSlices != 2)
8749     return false;
8750
8751   // Check (2).
8752   if (!areUsedBitsDense(UsedBits))
8753     return false;
8754
8755   // Check (3).
8756   LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
8757   // The original code has one big load.
8758   OrigCost.Loads = 1;
8759   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
8760     const LoadedSlice &LS = LoadedSlices[CurrSlice];
8761     // Accumulate the cost of all the slices.
8762     LoadedSlice::Cost SliceCost(LS, ForCodeSize);
8763     GlobalSlicingCost += SliceCost;
8764
8765     // Account as cost in the original configuration the gain obtained
8766     // with the current slices.
8767     OrigCost.addSliceGain(LS);
8768   }
8769
8770   // If the target supports paired load, adjust the cost accordingly.
8771   adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
8772   return OrigCost > GlobalSlicingCost;
8773 }
8774
8775 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
8776 /// operations, split it in the various pieces being extracted.
8777 ///
8778 /// This sort of thing is introduced by SROA.
8779 /// This slicing takes care not to insert overlapping loads.
8780 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
8781 bool DAGCombiner::SliceUpLoad(SDNode *N) {
8782   if (Level < AfterLegalizeDAG)
8783     return false;
8784
8785   LoadSDNode *LD = cast<LoadSDNode>(N);
8786   if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
8787       !LD->getValueType(0).isInteger())
8788     return false;
8789
8790   // Keep track of already used bits to detect overlapping values.
8791   // In that case, we will just abort the transformation.
8792   APInt UsedBits(LD->getValueSizeInBits(0), 0);
8793
8794   SmallVector<LoadedSlice, 4> LoadedSlices;
8795
8796   // Check if this load is used as several smaller chunks of bits.
8797   // Basically, look for uses in trunc or trunc(lshr) and record a new chain
8798   // of computation for each trunc.
8799   for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
8800        UI != UIEnd; ++UI) {
8801     // Skip the uses of the chain.
8802     if (UI.getUse().getResNo() != 0)
8803       continue;
8804
8805     SDNode *User = *UI;
8806     unsigned Shift = 0;
8807
8808     // Check if this is a trunc(lshr).
8809     if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
8810         isa<ConstantSDNode>(User->getOperand(1))) {
8811       Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
8812       User = *User->use_begin();
8813     }
8814
8815     // At this point, User is a Truncate, iff we encountered, trunc or
8816     // trunc(lshr).
8817     if (User->getOpcode() != ISD::TRUNCATE)
8818       return false;
8819
8820     // The width of the type must be a power of 2 and greater than 8-bits.
8821     // Otherwise the load cannot be represented in LLVM IR.
8822     // Moreover, if we shifted with a non-8-bits multiple, the slice
8823     // will be across several bytes. We do not support that.
8824     unsigned Width = User->getValueSizeInBits(0);
8825     if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
8826       return 0;
8827
8828     // Build the slice for this chain of computations.
8829     LoadedSlice LS(User, LD, Shift, &DAG);
8830     APInt CurrentUsedBits = LS.getUsedBits();
8831
8832     // Check if this slice overlaps with another.
8833     if ((CurrentUsedBits & UsedBits) != 0)
8834       return false;
8835     // Update the bits used globally.
8836     UsedBits |= CurrentUsedBits;
8837
8838     // Check if the new slice would be legal.
8839     if (!LS.isLegal())
8840       return false;
8841
8842     // Record the slice.
8843     LoadedSlices.push_back(LS);
8844   }
8845
8846   // Abort slicing if it does not seem to be profitable.
8847   if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
8848     return false;
8849
8850   ++SlicedLoads;
8851
8852   // Rewrite each chain to use an independent load.
8853   // By construction, each chain can be represented by a unique load.
8854
8855   // Prepare the argument for the new token factor for all the slices.
8856   SmallVector<SDValue, 8> ArgChains;
8857   for (SmallVectorImpl<LoadedSlice>::const_iterator
8858            LSIt = LoadedSlices.begin(),
8859            LSItEnd = LoadedSlices.end();
8860        LSIt != LSItEnd; ++LSIt) {
8861     SDValue SliceInst = LSIt->loadSlice();
8862     CombineTo(LSIt->Inst, SliceInst, true);
8863     if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
8864       SliceInst = SliceInst.getOperand(0);
8865     assert(SliceInst->getOpcode() == ISD::LOAD &&
8866            "It takes more than a zext to get to the loaded slice!!");
8867     ArgChains.push_back(SliceInst.getValue(1));
8868   }
8869
8870   SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
8871                               ArgChains);
8872   DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
8873   return true;
8874 }
8875
8876 /// Check to see if V is (and load (ptr), imm), where the load is having
8877 /// specific bytes cleared out.  If so, return the byte size being masked out
8878 /// and the shift amount.
8879 static std::pair<unsigned, unsigned>
8880 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
8881   std::pair<unsigned, unsigned> Result(0, 0);
8882
8883   // Check for the structure we're looking for.
8884   if (V->getOpcode() != ISD::AND ||
8885       !isa<ConstantSDNode>(V->getOperand(1)) ||
8886       !ISD::isNormalLoad(V->getOperand(0).getNode()))
8887     return Result;
8888
8889   // Check the chain and pointer.
8890   LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
8891   if (LD->getBasePtr() != Ptr) return Result;  // Not from same pointer.
8892
8893   // The store should be chained directly to the load or be an operand of a
8894   // tokenfactor.
8895   if (LD == Chain.getNode())
8896     ; // ok.
8897   else if (Chain->getOpcode() != ISD::TokenFactor)
8898     return Result; // Fail.
8899   else {
8900     bool isOk = false;
8901     for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
8902       if (Chain->getOperand(i).getNode() == LD) {
8903         isOk = true;
8904         break;
8905       }
8906     if (!isOk) return Result;
8907   }
8908
8909   // This only handles simple types.
8910   if (V.getValueType() != MVT::i16 &&
8911       V.getValueType() != MVT::i32 &&
8912       V.getValueType() != MVT::i64)
8913     return Result;
8914
8915   // Check the constant mask.  Invert it so that the bits being masked out are
8916   // 0 and the bits being kept are 1.  Use getSExtValue so that leading bits
8917   // follow the sign bit for uniformity.
8918   uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
8919   unsigned NotMaskLZ = countLeadingZeros(NotMask);
8920   if (NotMaskLZ & 7) return Result;  // Must be multiple of a byte.
8921   unsigned NotMaskTZ = countTrailingZeros(NotMask);
8922   if (NotMaskTZ & 7) return Result;  // Must be multiple of a byte.
8923   if (NotMaskLZ == 64) return Result;  // All zero mask.
8924
8925   // See if we have a continuous run of bits.  If so, we have 0*1+0*
8926   if (CountTrailingOnes_64(NotMask >> NotMaskTZ)+NotMaskTZ+NotMaskLZ != 64)
8927     return Result;
8928
8929   // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
8930   if (V.getValueType() != MVT::i64 && NotMaskLZ)
8931     NotMaskLZ -= 64-V.getValueSizeInBits();
8932
8933   unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
8934   switch (MaskedBytes) {
8935   case 1:
8936   case 2:
8937   case 4: break;
8938   default: return Result; // All one mask, or 5-byte mask.
8939   }
8940
8941   // Verify that the first bit starts at a multiple of mask so that the access
8942   // is aligned the same as the access width.
8943   if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
8944
8945   Result.first = MaskedBytes;
8946   Result.second = NotMaskTZ/8;
8947   return Result;
8948 }
8949
8950
8951 /// Check to see if IVal is something that provides a value as specified by
8952 /// MaskInfo. If so, replace the specified store with a narrower store of
8953 /// truncated IVal.
8954 static SDNode *
8955 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
8956                                 SDValue IVal, StoreSDNode *St,
8957                                 DAGCombiner *DC) {
8958   unsigned NumBytes = MaskInfo.first;
8959   unsigned ByteShift = MaskInfo.second;
8960   SelectionDAG &DAG = DC->getDAG();
8961
8962   // Check to see if IVal is all zeros in the part being masked in by the 'or'
8963   // that uses this.  If not, this is not a replacement.
8964   APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
8965                                   ByteShift*8, (ByteShift+NumBytes)*8);
8966   if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
8967
8968   // Check that it is legal on the target to do this.  It is legal if the new
8969   // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
8970   // legalization.
8971   MVT VT = MVT::getIntegerVT(NumBytes*8);
8972   if (!DC->isTypeLegal(VT))
8973     return nullptr;
8974
8975   // Okay, we can do this!  Replace the 'St' store with a store of IVal that is
8976   // shifted by ByteShift and truncated down to NumBytes.
8977   if (ByteShift)
8978     IVal = DAG.getNode(ISD::SRL, SDLoc(IVal), IVal.getValueType(), IVal,
8979                        DAG.getConstant(ByteShift*8,
8980                                     DC->getShiftAmountTy(IVal.getValueType())));
8981
8982   // Figure out the offset for the store and the alignment of the access.
8983   unsigned StOffset;
8984   unsigned NewAlign = St->getAlignment();
8985
8986   if (DAG.getTargetLoweringInfo().isLittleEndian())
8987     StOffset = ByteShift;
8988   else
8989     StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
8990
8991   SDValue Ptr = St->getBasePtr();
8992   if (StOffset) {
8993     Ptr = DAG.getNode(ISD::ADD, SDLoc(IVal), Ptr.getValueType(),
8994                       Ptr, DAG.getConstant(StOffset, Ptr.getValueType()));
8995     NewAlign = MinAlign(NewAlign, StOffset);
8996   }
8997
8998   // Truncate down to the new size.
8999   IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
9000
9001   ++OpsNarrowed;
9002   return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
9003                       St->getPointerInfo().getWithOffset(StOffset),
9004                       false, false, NewAlign).getNode();
9005 }
9006
9007
9008 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and
9009 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try
9010 /// narrowing the load and store if it would end up being a win for performance
9011 /// or code size.
9012 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
9013   StoreSDNode *ST  = cast<StoreSDNode>(N);
9014   if (ST->isVolatile())
9015     return SDValue();
9016
9017   SDValue Chain = ST->getChain();
9018   SDValue Value = ST->getValue();
9019   SDValue Ptr   = ST->getBasePtr();
9020   EVT VT = Value.getValueType();
9021
9022   if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
9023     return SDValue();
9024
9025   unsigned Opc = Value.getOpcode();
9026
9027   // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
9028   // is a byte mask indicating a consecutive number of bytes, check to see if
9029   // Y is known to provide just those bytes.  If so, we try to replace the
9030   // load + replace + store sequence with a single (narrower) store, which makes
9031   // the load dead.
9032   if (Opc == ISD::OR) {
9033     std::pair<unsigned, unsigned> MaskedLoad;
9034     MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
9035     if (MaskedLoad.first)
9036       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
9037                                                   Value.getOperand(1), ST,this))
9038         return SDValue(NewST, 0);
9039
9040     // Or is commutative, so try swapping X and Y.
9041     MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
9042     if (MaskedLoad.first)
9043       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
9044                                                   Value.getOperand(0), ST,this))
9045         return SDValue(NewST, 0);
9046   }
9047
9048   if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
9049       Value.getOperand(1).getOpcode() != ISD::Constant)
9050     return SDValue();
9051
9052   SDValue N0 = Value.getOperand(0);
9053   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
9054       Chain == SDValue(N0.getNode(), 1)) {
9055     LoadSDNode *LD = cast<LoadSDNode>(N0);
9056     if (LD->getBasePtr() != Ptr ||
9057         LD->getPointerInfo().getAddrSpace() !=
9058         ST->getPointerInfo().getAddrSpace())
9059       return SDValue();
9060
9061     // Find the type to narrow it the load / op / store to.
9062     SDValue N1 = Value.getOperand(1);
9063     unsigned BitWidth = N1.getValueSizeInBits();
9064     APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
9065     if (Opc == ISD::AND)
9066       Imm ^= APInt::getAllOnesValue(BitWidth);
9067     if (Imm == 0 || Imm.isAllOnesValue())
9068       return SDValue();
9069     unsigned ShAmt = Imm.countTrailingZeros();
9070     unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
9071     unsigned NewBW = NextPowerOf2(MSB - ShAmt);
9072     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
9073     while (NewBW < BitWidth &&
9074            !(TLI.isOperationLegalOrCustom(Opc, NewVT) &&
9075              TLI.isNarrowingProfitable(VT, NewVT))) {
9076       NewBW = NextPowerOf2(NewBW);
9077       NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
9078     }
9079     if (NewBW >= BitWidth)
9080       return SDValue();
9081
9082     // If the lsb changed does not start at the type bitwidth boundary,
9083     // start at the previous one.
9084     if (ShAmt % NewBW)
9085       ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
9086     APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
9087                                    std::min(BitWidth, ShAmt + NewBW));
9088     if ((Imm & Mask) == Imm) {
9089       APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
9090       if (Opc == ISD::AND)
9091         NewImm ^= APInt::getAllOnesValue(NewBW);
9092       uint64_t PtrOff = ShAmt / 8;
9093       // For big endian targets, we need to adjust the offset to the pointer to
9094       // load the correct bytes.
9095       if (TLI.isBigEndian())
9096         PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
9097
9098       unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
9099       Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
9100       if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
9101         return SDValue();
9102
9103       SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
9104                                    Ptr.getValueType(), Ptr,
9105                                    DAG.getConstant(PtrOff, Ptr.getValueType()));
9106       SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
9107                                   LD->getChain(), NewPtr,
9108                                   LD->getPointerInfo().getWithOffset(PtrOff),
9109                                   LD->isVolatile(), LD->isNonTemporal(),
9110                                   LD->isInvariant(), NewAlign,
9111                                   LD->getAAInfo());
9112       SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
9113                                    DAG.getConstant(NewImm, NewVT));
9114       SDValue NewST = DAG.getStore(Chain, SDLoc(N),
9115                                    NewVal, NewPtr,
9116                                    ST->getPointerInfo().getWithOffset(PtrOff),
9117                                    false, false, NewAlign);
9118
9119       AddToWorklist(NewPtr.getNode());
9120       AddToWorklist(NewLD.getNode());
9121       AddToWorklist(NewVal.getNode());
9122       WorklistRemover DeadNodes(*this);
9123       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
9124       ++OpsNarrowed;
9125       return NewST;
9126     }
9127   }
9128
9129   return SDValue();
9130 }
9131
9132 /// For a given floating point load / store pair, if the load value isn't used
9133 /// by any other operations, then consider transforming the pair to integer
9134 /// load / store operations if the target deems the transformation profitable.
9135 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
9136   StoreSDNode *ST  = cast<StoreSDNode>(N);
9137   SDValue Chain = ST->getChain();
9138   SDValue Value = ST->getValue();
9139   if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
9140       Value.hasOneUse() &&
9141       Chain == SDValue(Value.getNode(), 1)) {
9142     LoadSDNode *LD = cast<LoadSDNode>(Value);
9143     EVT VT = LD->getMemoryVT();
9144     if (!VT.isFloatingPoint() ||
9145         VT != ST->getMemoryVT() ||
9146         LD->isNonTemporal() ||
9147         ST->isNonTemporal() ||
9148         LD->getPointerInfo().getAddrSpace() != 0 ||
9149         ST->getPointerInfo().getAddrSpace() != 0)
9150       return SDValue();
9151
9152     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
9153     if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
9154         !TLI.isOperationLegal(ISD::STORE, IntVT) ||
9155         !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
9156         !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
9157       return SDValue();
9158
9159     unsigned LDAlign = LD->getAlignment();
9160     unsigned STAlign = ST->getAlignment();
9161     Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
9162     unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
9163     if (LDAlign < ABIAlign || STAlign < ABIAlign)
9164       return SDValue();
9165
9166     SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
9167                                 LD->getChain(), LD->getBasePtr(),
9168                                 LD->getPointerInfo(),
9169                                 false, false, false, LDAlign);
9170
9171     SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
9172                                  NewLD, ST->getBasePtr(),
9173                                  ST->getPointerInfo(),
9174                                  false, false, STAlign);
9175
9176     AddToWorklist(NewLD.getNode());
9177     AddToWorklist(NewST.getNode());
9178     WorklistRemover DeadNodes(*this);
9179     DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
9180     ++LdStFP2Int;
9181     return NewST;
9182   }
9183
9184   return SDValue();
9185 }
9186
9187 /// Helper struct to parse and store a memory address as base + index + offset.
9188 /// We ignore sign extensions when it is safe to do so.
9189 /// The following two expressions are not equivalent. To differentiate we need
9190 /// to store whether there was a sign extension involved in the index
9191 /// computation.
9192 ///  (load (i64 add (i64 copyfromreg %c)
9193 ///                 (i64 signextend (add (i8 load %index)
9194 ///                                      (i8 1))))
9195 /// vs
9196 ///
9197 /// (load (i64 add (i64 copyfromreg %c)
9198 ///                (i64 signextend (i32 add (i32 signextend (i8 load %index))
9199 ///                                         (i32 1)))))
9200 struct BaseIndexOffset {
9201   SDValue Base;
9202   SDValue Index;
9203   int64_t Offset;
9204   bool IsIndexSignExt;
9205
9206   BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
9207
9208   BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
9209                   bool IsIndexSignExt) :
9210     Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
9211
9212   bool equalBaseIndex(const BaseIndexOffset &Other) {
9213     return Other.Base == Base && Other.Index == Index &&
9214       Other.IsIndexSignExt == IsIndexSignExt;
9215   }
9216
9217   /// Parses tree in Ptr for base, index, offset addresses.
9218   static BaseIndexOffset match(SDValue Ptr) {
9219     bool IsIndexSignExt = false;
9220
9221     // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
9222     // instruction, then it could be just the BASE or everything else we don't
9223     // know how to handle. Just use Ptr as BASE and give up.
9224     if (Ptr->getOpcode() != ISD::ADD)
9225       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9226
9227     // We know that we have at least an ADD instruction. Try to pattern match
9228     // the simple case of BASE + OFFSET.
9229     if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
9230       int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
9231       return  BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
9232                               IsIndexSignExt);
9233     }
9234
9235     // Inside a loop the current BASE pointer is calculated using an ADD and a
9236     // MUL instruction. In this case Ptr is the actual BASE pointer.
9237     // (i64 add (i64 %array_ptr)
9238     //          (i64 mul (i64 %induction_var)
9239     //                   (i64 %element_size)))
9240     if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
9241       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9242
9243     // Look at Base + Index + Offset cases.
9244     SDValue Base = Ptr->getOperand(0);
9245     SDValue IndexOffset = Ptr->getOperand(1);
9246
9247     // Skip signextends.
9248     if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
9249       IndexOffset = IndexOffset->getOperand(0);
9250       IsIndexSignExt = true;
9251     }
9252
9253     // Either the case of Base + Index (no offset) or something else.
9254     if (IndexOffset->getOpcode() != ISD::ADD)
9255       return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
9256
9257     // Now we have the case of Base + Index + offset.
9258     SDValue Index = IndexOffset->getOperand(0);
9259     SDValue Offset = IndexOffset->getOperand(1);
9260
9261     if (!isa<ConstantSDNode>(Offset))
9262       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9263
9264     // Ignore signextends.
9265     if (Index->getOpcode() == ISD::SIGN_EXTEND) {
9266       Index = Index->getOperand(0);
9267       IsIndexSignExt = true;
9268     } else IsIndexSignExt = false;
9269
9270     int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
9271     return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
9272   }
9273 };
9274
9275 /// Holds a pointer to an LSBaseSDNode as well as information on where it
9276 /// is located in a sequence of memory operations connected by a chain.
9277 struct MemOpLink {
9278   MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
9279     MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
9280   // Ptr to the mem node.
9281   LSBaseSDNode *MemNode;
9282   // Offset from the base ptr.
9283   int64_t OffsetFromBase;
9284   // What is the sequence number of this mem node.
9285   // Lowest mem operand in the DAG starts at zero.
9286   unsigned SequenceNum;
9287 };
9288
9289 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
9290   EVT MemVT = St->getMemoryVT();
9291   int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
9292   bool NoVectors = DAG.getMachineFunction().getFunction()->getAttributes().
9293     hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
9294
9295   // Don't merge vectors into wider inputs.
9296   if (MemVT.isVector() || !MemVT.isSimple())
9297     return false;
9298
9299   // Perform an early exit check. Do not bother looking at stored values that
9300   // are not constants or loads.
9301   SDValue StoredVal = St->getValue();
9302   bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
9303   if (!isa<ConstantSDNode>(StoredVal) && !isa<ConstantFPSDNode>(StoredVal) &&
9304       !IsLoadSrc)
9305     return false;
9306
9307   // Only look at ends of store sequences.
9308   SDValue Chain = SDValue(St, 0);
9309   if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
9310     return false;
9311
9312   // This holds the base pointer, index, and the offset in bytes from the base
9313   // pointer.
9314   BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
9315
9316   // We must have a base and an offset.
9317   if (!BasePtr.Base.getNode())
9318     return false;
9319
9320   // Do not handle stores to undef base pointers.
9321   if (BasePtr.Base.getOpcode() == ISD::UNDEF)
9322     return false;
9323
9324   // Save the LoadSDNodes that we find in the chain.
9325   // We need to make sure that these nodes do not interfere with
9326   // any of the store nodes.
9327   SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
9328
9329   // Save the StoreSDNodes that we find in the chain.
9330   SmallVector<MemOpLink, 8> StoreNodes;
9331
9332   // Walk up the chain and look for nodes with offsets from the same
9333   // base pointer. Stop when reaching an instruction with a different kind
9334   // or instruction which has a different base pointer.
9335   unsigned Seq = 0;
9336   StoreSDNode *Index = St;
9337   while (Index) {
9338     // If the chain has more than one use, then we can't reorder the mem ops.
9339     if (Index != St && !SDValue(Index, 0)->hasOneUse())
9340       break;
9341
9342     // Find the base pointer and offset for this memory node.
9343     BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
9344
9345     // Check that the base pointer is the same as the original one.
9346     if (!Ptr.equalBaseIndex(BasePtr))
9347       break;
9348
9349     // Check that the alignment is the same.
9350     if (Index->getAlignment() != St->getAlignment())
9351       break;
9352
9353     // The memory operands must not be volatile.
9354     if (Index->isVolatile() || Index->isIndexed())
9355       break;
9356
9357     // No truncation.
9358     if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
9359       if (St->isTruncatingStore())
9360         break;
9361
9362     // The stored memory type must be the same.
9363     if (Index->getMemoryVT() != MemVT)
9364       break;
9365
9366     // We do not allow unaligned stores because we want to prevent overriding
9367     // stores.
9368     if (Index->getAlignment()*8 != MemVT.getSizeInBits())
9369       break;
9370
9371     // We found a potential memory operand to merge.
9372     StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
9373
9374     // Find the next memory operand in the chain. If the next operand in the
9375     // chain is a store then move up and continue the scan with the next
9376     // memory operand. If the next operand is a load save it and use alias
9377     // information to check if it interferes with anything.
9378     SDNode *NextInChain = Index->getChain().getNode();
9379     while (1) {
9380       if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
9381         // We found a store node. Use it for the next iteration.
9382         Index = STn;
9383         break;
9384       } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
9385         if (Ldn->isVolatile()) {
9386           Index = nullptr;
9387           break;
9388         }
9389
9390         // Save the load node for later. Continue the scan.
9391         AliasLoadNodes.push_back(Ldn);
9392         NextInChain = Ldn->getChain().getNode();
9393         continue;
9394       } else {
9395         Index = nullptr;
9396         break;
9397       }
9398     }
9399   }
9400
9401   // Check if there is anything to merge.
9402   if (StoreNodes.size() < 2)
9403     return false;
9404
9405   // Sort the memory operands according to their distance from the base pointer.
9406   std::sort(StoreNodes.begin(), StoreNodes.end(),
9407             [](MemOpLink LHS, MemOpLink RHS) {
9408     return LHS.OffsetFromBase < RHS.OffsetFromBase ||
9409            (LHS.OffsetFromBase == RHS.OffsetFromBase &&
9410             LHS.SequenceNum > RHS.SequenceNum);
9411   });
9412
9413   // Scan the memory operations on the chain and find the first non-consecutive
9414   // store memory address.
9415   unsigned LastConsecutiveStore = 0;
9416   int64_t StartAddress = StoreNodes[0].OffsetFromBase;
9417   for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
9418
9419     // Check that the addresses are consecutive starting from the second
9420     // element in the list of stores.
9421     if (i > 0) {
9422       int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
9423       if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9424         break;
9425     }
9426
9427     bool Alias = false;
9428     // Check if this store interferes with any of the loads that we found.
9429     for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
9430       if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
9431         Alias = true;
9432         break;
9433       }
9434     // We found a load that alias with this store. Stop the sequence.
9435     if (Alias)
9436       break;
9437
9438     // Mark this node as useful.
9439     LastConsecutiveStore = i;
9440   }
9441
9442   // The node with the lowest store address.
9443   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
9444
9445   // Store the constants into memory as one consecutive store.
9446   if (!IsLoadSrc) {
9447     unsigned LastLegalType = 0;
9448     unsigned LastLegalVectorType = 0;
9449     bool NonZero = false;
9450     for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9451       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
9452       SDValue StoredVal = St->getValue();
9453
9454       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
9455         NonZero |= !C->isNullValue();
9456       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
9457         NonZero |= !C->getConstantFPValue()->isNullValue();
9458       } else {
9459         // Non-constant.
9460         break;
9461       }
9462
9463       // Find a legal type for the constant store.
9464       unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9465       EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9466       if (TLI.isTypeLegal(StoreTy))
9467         LastLegalType = i+1;
9468       // Or check whether a truncstore is legal.
9469       else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9470                TargetLowering::TypePromoteInteger) {
9471         EVT LegalizedStoredValueTy =
9472           TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
9473         if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy))
9474           LastLegalType = i+1;
9475       }
9476
9477       // Find a legal type for the vector store.
9478       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9479       if (TLI.isTypeLegal(Ty))
9480         LastLegalVectorType = i + 1;
9481     }
9482
9483     // We only use vectors if the constant is known to be zero and the
9484     // function is not marked with the noimplicitfloat attribute.
9485     if (NonZero || NoVectors)
9486       LastLegalVectorType = 0;
9487
9488     // Check if we found a legal integer type to store.
9489     if (LastLegalType == 0 && LastLegalVectorType == 0)
9490       return false;
9491
9492     bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
9493     unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
9494
9495     // Make sure we have something to merge.
9496     if (NumElem < 2)
9497       return false;
9498
9499     unsigned EarliestNodeUsed = 0;
9500     for (unsigned i=0; i < NumElem; ++i) {
9501       // Find a chain for the new wide-store operand. Notice that some
9502       // of the store nodes that we found may not be selected for inclusion
9503       // in the wide store. The chain we use needs to be the chain of the
9504       // earliest store node which is *used* and replaced by the wide store.
9505       if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9506         EarliestNodeUsed = i;
9507     }
9508
9509     // The earliest Node in the DAG.
9510     LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9511     SDLoc DL(StoreNodes[0].MemNode);
9512
9513     SDValue StoredVal;
9514     if (UseVector) {
9515       // Find a legal type for the vector store.
9516       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9517       assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
9518       StoredVal = DAG.getConstant(0, Ty);
9519     } else {
9520       unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9521       APInt StoreInt(StoreBW, 0);
9522
9523       // Construct a single integer constant which is made of the smaller
9524       // constant inputs.
9525       bool IsLE = TLI.isLittleEndian();
9526       for (unsigned i = 0; i < NumElem ; ++i) {
9527         unsigned Idx = IsLE ?(NumElem - 1 - i) : i;
9528         StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
9529         SDValue Val = St->getValue();
9530         StoreInt<<=ElementSizeBytes*8;
9531         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
9532           StoreInt|=C->getAPIntValue().zext(StoreBW);
9533         } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
9534           StoreInt|= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
9535         } else {
9536           assert(false && "Invalid constant element type");
9537         }
9538       }
9539
9540       // Create the new Load and Store operations.
9541       EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9542       StoredVal = DAG.getConstant(StoreInt, StoreTy);
9543     }
9544
9545     SDValue NewStore = DAG.getStore(EarliestOp->getChain(), DL, StoredVal,
9546                                     FirstInChain->getBasePtr(),
9547                                     FirstInChain->getPointerInfo(),
9548                                     false, false,
9549                                     FirstInChain->getAlignment());
9550
9551     // Replace the first store with the new store
9552     CombineTo(EarliestOp, NewStore);
9553     // Erase all other stores.
9554     for (unsigned i = 0; i < NumElem ; ++i) {
9555       if (StoreNodes[i].MemNode == EarliestOp)
9556         continue;
9557       StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9558       // ReplaceAllUsesWith will replace all uses that existed when it was
9559       // called, but graph optimizations may cause new ones to appear. For
9560       // example, the case in pr14333 looks like
9561       //
9562       //  St's chain -> St -> another store -> X
9563       //
9564       // And the only difference from St to the other store is the chain.
9565       // When we change it's chain to be St's chain they become identical,
9566       // get CSEed and the net result is that X is now a use of St.
9567       // Since we know that St is redundant, just iterate.
9568       while (!St->use_empty())
9569         DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
9570       deleteAndRecombine(St);
9571     }
9572
9573     return true;
9574   }
9575
9576   // Below we handle the case of multiple consecutive stores that
9577   // come from multiple consecutive loads. We merge them into a single
9578   // wide load and a single wide store.
9579
9580   // Look for load nodes which are used by the stored values.
9581   SmallVector<MemOpLink, 8> LoadNodes;
9582
9583   // Find acceptable loads. Loads need to have the same chain (token factor),
9584   // must not be zext, volatile, indexed, and they must be consecutive.
9585   BaseIndexOffset LdBasePtr;
9586   for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9587     StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
9588     LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
9589     if (!Ld) break;
9590
9591     // Loads must only have one use.
9592     if (!Ld->hasNUsesOfValue(1, 0))
9593       break;
9594
9595     // Check that the alignment is the same as the stores.
9596     if (Ld->getAlignment() != St->getAlignment())
9597       break;
9598
9599     // The memory operands must not be volatile.
9600     if (Ld->isVolatile() || Ld->isIndexed())
9601       break;
9602
9603     // We do not accept ext loads.
9604     if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
9605       break;
9606
9607     // The stored memory type must be the same.
9608     if (Ld->getMemoryVT() != MemVT)
9609       break;
9610
9611     BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
9612     // If this is not the first ptr that we check.
9613     if (LdBasePtr.Base.getNode()) {
9614       // The base ptr must be the same.
9615       if (!LdPtr.equalBaseIndex(LdBasePtr))
9616         break;
9617     } else {
9618       // Check that all other base pointers are the same as this one.
9619       LdBasePtr = LdPtr;
9620     }
9621
9622     // We found a potential memory operand to merge.
9623     LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
9624   }
9625
9626   if (LoadNodes.size() < 2)
9627     return false;
9628
9629   // If we have load/store pair instructions and we only have two values,
9630   // don't bother.
9631   unsigned RequiredAlignment;
9632   if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) &&
9633       St->getAlignment() >= RequiredAlignment)
9634     return false;
9635
9636   // Scan the memory operations on the chain and find the first non-consecutive
9637   // load memory address. These variables hold the index in the store node
9638   // array.
9639   unsigned LastConsecutiveLoad = 0;
9640   // This variable refers to the size and not index in the array.
9641   unsigned LastLegalVectorType = 0;
9642   unsigned LastLegalIntegerType = 0;
9643   StartAddress = LoadNodes[0].OffsetFromBase;
9644   SDValue FirstChain = LoadNodes[0].MemNode->getChain();
9645   for (unsigned i = 1; i < LoadNodes.size(); ++i) {
9646     // All loads much share the same chain.
9647     if (LoadNodes[i].MemNode->getChain() != FirstChain)
9648       break;
9649
9650     int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
9651     if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9652       break;
9653     LastConsecutiveLoad = i;
9654
9655     // Find a legal type for the vector store.
9656     EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9657     if (TLI.isTypeLegal(StoreTy))
9658       LastLegalVectorType = i + 1;
9659
9660     // Find a legal type for the integer store.
9661     unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9662     StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9663     if (TLI.isTypeLegal(StoreTy))
9664       LastLegalIntegerType = i + 1;
9665     // Or check whether a truncstore and extload is legal.
9666     else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9667              TargetLowering::TypePromoteInteger) {
9668       EVT LegalizedStoredValueTy =
9669         TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
9670       if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
9671           TLI.isLoadExtLegal(ISD::ZEXTLOAD, StoreTy) &&
9672           TLI.isLoadExtLegal(ISD::SEXTLOAD, StoreTy) &&
9673           TLI.isLoadExtLegal(ISD::EXTLOAD, StoreTy))
9674         LastLegalIntegerType = i+1;
9675     }
9676   }
9677
9678   // Only use vector types if the vector type is larger than the integer type.
9679   // If they are the same, use integers.
9680   bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
9681   unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
9682
9683   // We add +1 here because the LastXXX variables refer to location while
9684   // the NumElem refers to array/index size.
9685   unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
9686   NumElem = std::min(LastLegalType, NumElem);
9687
9688   if (NumElem < 2)
9689     return false;
9690
9691   // The earliest Node in the DAG.
9692   unsigned EarliestNodeUsed = 0;
9693   LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9694   for (unsigned i=1; i<NumElem; ++i) {
9695     // Find a chain for the new wide-store operand. Notice that some
9696     // of the store nodes that we found may not be selected for inclusion
9697     // in the wide store. The chain we use needs to be the chain of the
9698     // earliest store node which is *used* and replaced by the wide store.
9699     if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9700       EarliestNodeUsed = i;
9701   }
9702
9703   // Find if it is better to use vectors or integers to load and store
9704   // to memory.
9705   EVT JointMemOpVT;
9706   if (UseVectorTy) {
9707     JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9708   } else {
9709     unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9710     JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9711   }
9712
9713   SDLoc LoadDL(LoadNodes[0].MemNode);
9714   SDLoc StoreDL(StoreNodes[0].MemNode);
9715
9716   LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
9717   SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL,
9718                                 FirstLoad->getChain(),
9719                                 FirstLoad->getBasePtr(),
9720                                 FirstLoad->getPointerInfo(),
9721                                 false, false, false,
9722                                 FirstLoad->getAlignment());
9723
9724   SDValue NewStore = DAG.getStore(EarliestOp->getChain(), StoreDL, NewLoad,
9725                                   FirstInChain->getBasePtr(),
9726                                   FirstInChain->getPointerInfo(), false, false,
9727                                   FirstInChain->getAlignment());
9728
9729   // Replace one of the loads with the new load.
9730   LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
9731   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
9732                                 SDValue(NewLoad.getNode(), 1));
9733
9734   // Remove the rest of the load chains.
9735   for (unsigned i = 1; i < NumElem ; ++i) {
9736     // Replace all chain users of the old load nodes with the chain of the new
9737     // load node.
9738     LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
9739     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
9740   }
9741
9742   // Replace the first store with the new store.
9743   CombineTo(EarliestOp, NewStore);
9744   // Erase all other stores.
9745   for (unsigned i = 0; i < NumElem ; ++i) {
9746     // Remove all Store nodes.
9747     if (StoreNodes[i].MemNode == EarliestOp)
9748       continue;
9749     StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9750     DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
9751     deleteAndRecombine(St);
9752   }
9753
9754   return true;
9755 }
9756
9757 SDValue DAGCombiner::visitSTORE(SDNode *N) {
9758   StoreSDNode *ST  = cast<StoreSDNode>(N);
9759   SDValue Chain = ST->getChain();
9760   SDValue Value = ST->getValue();
9761   SDValue Ptr   = ST->getBasePtr();
9762
9763   // If this is a store of a bit convert, store the input value if the
9764   // resultant store does not need a higher alignment than the original.
9765   if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
9766       ST->isUnindexed()) {
9767     unsigned OrigAlign = ST->getAlignment();
9768     EVT SVT = Value.getOperand(0).getValueType();
9769     unsigned Align = TLI.getDataLayout()->
9770       getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
9771     if (Align <= OrigAlign &&
9772         ((!LegalOperations && !ST->isVolatile()) ||
9773          TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
9774       return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
9775                           Ptr, ST->getPointerInfo(), ST->isVolatile(),
9776                           ST->isNonTemporal(), OrigAlign,
9777                           ST->getAAInfo());
9778   }
9779
9780   // Turn 'store undef, Ptr' -> nothing.
9781   if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
9782     return Chain;
9783
9784   // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
9785   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
9786     // NOTE: If the original store is volatile, this transform must not increase
9787     // the number of stores.  For example, on x86-32 an f64 can be stored in one
9788     // processor operation but an i64 (which is not legal) requires two.  So the
9789     // transform should not be done in this case.
9790     if (Value.getOpcode() != ISD::TargetConstantFP) {
9791       SDValue Tmp;
9792       switch (CFP->getSimpleValueType(0).SimpleTy) {
9793       default: llvm_unreachable("Unknown FP type");
9794       case MVT::f16:    // We don't do this for these yet.
9795       case MVT::f80:
9796       case MVT::f128:
9797       case MVT::ppcf128:
9798         break;
9799       case MVT::f32:
9800         if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
9801             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
9802           Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
9803                               bitcastToAPInt().getZExtValue(), MVT::i32);
9804           return DAG.getStore(Chain, SDLoc(N), Tmp,
9805                               Ptr, ST->getMemOperand());
9806         }
9807         break;
9808       case MVT::f64:
9809         if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
9810              !ST->isVolatile()) ||
9811             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
9812           Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
9813                                 getZExtValue(), MVT::i64);
9814           return DAG.getStore(Chain, SDLoc(N), Tmp,
9815                               Ptr, ST->getMemOperand());
9816         }
9817
9818         if (!ST->isVolatile() &&
9819             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
9820           // Many FP stores are not made apparent until after legalize, e.g. for
9821           // argument passing.  Since this is so common, custom legalize the
9822           // 64-bit integer store into two 32-bit stores.
9823           uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
9824           SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
9825           SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
9826           if (TLI.isBigEndian()) std::swap(Lo, Hi);
9827
9828           unsigned Alignment = ST->getAlignment();
9829           bool isVolatile = ST->isVolatile();
9830           bool isNonTemporal = ST->isNonTemporal();
9831           AAMDNodes AAInfo = ST->getAAInfo();
9832
9833           SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
9834                                      Ptr, ST->getPointerInfo(),
9835                                      isVolatile, isNonTemporal,
9836                                      ST->getAlignment(), AAInfo);
9837           Ptr = DAG.getNode(ISD::ADD, SDLoc(N), Ptr.getValueType(), Ptr,
9838                             DAG.getConstant(4, Ptr.getValueType()));
9839           Alignment = MinAlign(Alignment, 4U);
9840           SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
9841                                      Ptr, ST->getPointerInfo().getWithOffset(4),
9842                                      isVolatile, isNonTemporal,
9843                                      Alignment, AAInfo);
9844           return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
9845                              St0, St1);
9846         }
9847
9848         break;
9849       }
9850     }
9851   }
9852
9853   // Try to infer better alignment information than the store already has.
9854   if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
9855     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
9856       if (Align > ST->getAlignment())
9857         return DAG.getTruncStore(Chain, SDLoc(N), Value,
9858                                  Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
9859                                  ST->isVolatile(), ST->isNonTemporal(), Align,
9860                                  ST->getAAInfo());
9861     }
9862   }
9863
9864   // Try transforming a pair floating point load / store ops to integer
9865   // load / store ops.
9866   SDValue NewST = TransformFPLoadStorePair(N);
9867   if (NewST.getNode())
9868     return NewST;
9869
9870   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
9871                                                   : DAG.getSubtarget().useAA();
9872 #ifndef NDEBUG
9873   if (CombinerAAOnlyFunc.getNumOccurrences() &&
9874       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
9875     UseAA = false;
9876 #endif
9877   if (UseAA && ST->isUnindexed()) {
9878     // Walk up chain skipping non-aliasing memory nodes.
9879     SDValue BetterChain = FindBetterChain(N, Chain);
9880
9881     // If there is a better chain.
9882     if (Chain != BetterChain) {
9883       SDValue ReplStore;
9884
9885       // Replace the chain to avoid dependency.
9886       if (ST->isTruncatingStore()) {
9887         ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
9888                                       ST->getMemoryVT(), ST->getMemOperand());
9889       } else {
9890         ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
9891                                  ST->getMemOperand());
9892       }
9893
9894       // Create token to keep both nodes around.
9895       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
9896                                   MVT::Other, Chain, ReplStore);
9897
9898       // Make sure the new and old chains are cleaned up.
9899       AddToWorklist(Token.getNode());
9900
9901       // Don't add users to work list.
9902       return CombineTo(N, Token, false);
9903     }
9904   }
9905
9906   // Try transforming N to an indexed store.
9907   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
9908     return SDValue(N, 0);
9909
9910   // FIXME: is there such a thing as a truncating indexed store?
9911   if (ST->isTruncatingStore() && ST->isUnindexed() &&
9912       Value.getValueType().isInteger()) {
9913     // See if we can simplify the input to this truncstore with knowledge that
9914     // only the low bits are being used.  For example:
9915     // "truncstore (or (shl x, 8), y), i8"  -> "truncstore y, i8"
9916     SDValue Shorter =
9917       GetDemandedBits(Value,
9918                       APInt::getLowBitsSet(
9919                         Value.getValueType().getScalarType().getSizeInBits(),
9920                         ST->getMemoryVT().getScalarType().getSizeInBits()));
9921     AddToWorklist(Value.getNode());
9922     if (Shorter.getNode())
9923       return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
9924                                Ptr, ST->getMemoryVT(), ST->getMemOperand());
9925
9926     // Otherwise, see if we can simplify the operation with
9927     // SimplifyDemandedBits, which only works if the value has a single use.
9928     if (SimplifyDemandedBits(Value,
9929                         APInt::getLowBitsSet(
9930                           Value.getValueType().getScalarType().getSizeInBits(),
9931                           ST->getMemoryVT().getScalarType().getSizeInBits())))
9932       return SDValue(N, 0);
9933   }
9934
9935   // If this is a load followed by a store to the same location, then the store
9936   // is dead/noop.
9937   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
9938     if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
9939         ST->isUnindexed() && !ST->isVolatile() &&
9940         // There can't be any side effects between the load and store, such as
9941         // a call or store.
9942         Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
9943       // The store is dead, remove it.
9944       return Chain;
9945     }
9946   }
9947
9948   // If this is a store followed by a store with the same value to the same
9949   // location, then the store is dead/noop.
9950   if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) {
9951     if (ST1->getBasePtr() == Ptr && ST->getMemoryVT() == ST1->getMemoryVT() &&
9952         ST1->getValue() == Value && ST->isUnindexed() && !ST->isVolatile() &&
9953         ST1->isUnindexed() && !ST1->isVolatile()) {
9954       // The store is dead, remove it.
9955       return Chain;
9956     }
9957   }
9958
9959   // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
9960   // truncating store.  We can do this even if this is already a truncstore.
9961   if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
9962       && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
9963       TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
9964                             ST->getMemoryVT())) {
9965     return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
9966                              Ptr, ST->getMemoryVT(), ST->getMemOperand());
9967   }
9968
9969   // Only perform this optimization before the types are legal, because we
9970   // don't want to perform this optimization on every DAGCombine invocation.
9971   if (!LegalTypes) {
9972     bool EverChanged = false;
9973
9974     do {
9975       // There can be multiple store sequences on the same chain.
9976       // Keep trying to merge store sequences until we are unable to do so
9977       // or until we merge the last store on the chain.
9978       bool Changed = MergeConsecutiveStores(ST);
9979       EverChanged |= Changed;
9980       if (!Changed) break;
9981     } while (ST->getOpcode() != ISD::DELETED_NODE);
9982
9983     if (EverChanged)
9984       return SDValue(N, 0);
9985   }
9986
9987   return ReduceLoadOpStoreWidth(N);
9988 }
9989
9990 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
9991   SDValue InVec = N->getOperand(0);
9992   SDValue InVal = N->getOperand(1);
9993   SDValue EltNo = N->getOperand(2);
9994   SDLoc dl(N);
9995
9996   // If the inserted element is an UNDEF, just use the input vector.
9997   if (InVal.getOpcode() == ISD::UNDEF)
9998     return InVec;
9999
10000   EVT VT = InVec.getValueType();
10001
10002   // If we can't generate a legal BUILD_VECTOR, exit
10003   if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
10004     return SDValue();
10005
10006   // Check that we know which element is being inserted
10007   if (!isa<ConstantSDNode>(EltNo))
10008     return SDValue();
10009   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
10010
10011   // Canonicalize insert_vector_elt dag nodes.
10012   // Example:
10013   // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
10014   // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
10015   //
10016   // Do this only if the child insert_vector node has one use; also
10017   // do this only if indices are both constants and Idx1 < Idx0.
10018   if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
10019       && isa<ConstantSDNode>(InVec.getOperand(2))) {
10020     unsigned OtherElt =
10021       cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue();
10022     if (Elt < OtherElt) {
10023       // Swap nodes.
10024       SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT,
10025                                   InVec.getOperand(0), InVal, EltNo);
10026       AddToWorklist(NewOp.getNode());
10027       return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
10028                          VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
10029     }
10030   }
10031
10032   // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
10033   // be converted to a BUILD_VECTOR).  Fill in the Ops vector with the
10034   // vector elements.
10035   SmallVector<SDValue, 8> Ops;
10036   // Do not combine these two vectors if the output vector will not replace
10037   // the input vector.
10038   if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
10039     Ops.append(InVec.getNode()->op_begin(),
10040                InVec.getNode()->op_end());
10041   } else if (InVec.getOpcode() == ISD::UNDEF) {
10042     unsigned NElts = VT.getVectorNumElements();
10043     Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
10044   } else {
10045     return SDValue();
10046   }
10047
10048   // Insert the element
10049   if (Elt < Ops.size()) {
10050     // All the operands of BUILD_VECTOR must have the same type;
10051     // we enforce that here.
10052     EVT OpVT = Ops[0].getValueType();
10053     if (InVal.getValueType() != OpVT)
10054       InVal = OpVT.bitsGT(InVal.getValueType()) ?
10055                 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
10056                 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
10057     Ops[Elt] = InVal;
10058   }
10059
10060   // Return the new vector
10061   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
10062 }
10063
10064 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
10065     SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) {
10066   EVT ResultVT = EVE->getValueType(0);
10067   EVT VecEltVT = InVecVT.getVectorElementType();
10068   unsigned Align = OriginalLoad->getAlignment();
10069   unsigned NewAlign = TLI.getDataLayout()->getABITypeAlignment(
10070       VecEltVT.getTypeForEVT(*DAG.getContext()));
10071
10072   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
10073     return SDValue();
10074
10075   Align = NewAlign;
10076
10077   SDValue NewPtr = OriginalLoad->getBasePtr();
10078   SDValue Offset;
10079   EVT PtrType = NewPtr.getValueType();
10080   MachinePointerInfo MPI;
10081   if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
10082     int Elt = ConstEltNo->getZExtValue();
10083     unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
10084     if (TLI.isBigEndian())
10085       PtrOff = InVecVT.getSizeInBits() / 8 - PtrOff;
10086     Offset = DAG.getConstant(PtrOff, PtrType);
10087     MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
10088   } else {
10089     Offset = DAG.getNode(
10090         ISD::MUL, SDLoc(EVE), EltNo.getValueType(), EltNo,
10091         DAG.getConstant(VecEltVT.getStoreSize(), EltNo.getValueType()));
10092     if (TLI.isBigEndian())
10093       Offset = DAG.getNode(
10094           ISD::SUB, SDLoc(EVE), EltNo.getValueType(),
10095           DAG.getConstant(InVecVT.getStoreSize(), EltNo.getValueType()), Offset);
10096     MPI = OriginalLoad->getPointerInfo();
10097   }
10098   NewPtr = DAG.getNode(ISD::ADD, SDLoc(EVE), PtrType, NewPtr, Offset);
10099
10100   // The replacement we need to do here is a little tricky: we need to
10101   // replace an extractelement of a load with a load.
10102   // Use ReplaceAllUsesOfValuesWith to do the replacement.
10103   // Note that this replacement assumes that the extractvalue is the only
10104   // use of the load; that's okay because we don't want to perform this
10105   // transformation in other cases anyway.
10106   SDValue Load;
10107   SDValue Chain;
10108   if (ResultVT.bitsGT(VecEltVT)) {
10109     // If the result type of vextract is wider than the load, then issue an
10110     // extending load instead.
10111     ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, VecEltVT)
10112                                    ? ISD::ZEXTLOAD
10113                                    : ISD::EXTLOAD;
10114     Load = DAG.getExtLoad(
10115         ExtType, SDLoc(EVE), ResultVT, OriginalLoad->getChain(), NewPtr, MPI,
10116         VecEltVT, OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
10117         OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
10118     Chain = Load.getValue(1);
10119   } else {
10120     Load = DAG.getLoad(
10121         VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, MPI,
10122         OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
10123         OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
10124     Chain = Load.getValue(1);
10125     if (ResultVT.bitsLT(VecEltVT))
10126       Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
10127     else
10128       Load = DAG.getNode(ISD::BITCAST, SDLoc(EVE), ResultVT, Load);
10129   }
10130   WorklistRemover DeadNodes(*this);
10131   SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
10132   SDValue To[] = { Load, Chain };
10133   DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
10134   // Since we're explicitly calling ReplaceAllUses, add the new node to the
10135   // worklist explicitly as well.
10136   AddToWorklist(Load.getNode());
10137   AddUsersToWorklist(Load.getNode()); // Add users too
10138   // Make sure to revisit this node to clean it up; it will usually be dead.
10139   AddToWorklist(EVE);
10140   ++OpsNarrowed;
10141   return SDValue(EVE, 0);
10142 }
10143
10144 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
10145   // (vextract (scalar_to_vector val, 0) -> val
10146   SDValue InVec = N->getOperand(0);
10147   EVT VT = InVec.getValueType();
10148   EVT NVT = N->getValueType(0);
10149
10150   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
10151     // Check if the result type doesn't match the inserted element type. A
10152     // SCALAR_TO_VECTOR may truncate the inserted element and the
10153     // EXTRACT_VECTOR_ELT may widen the extracted vector.
10154     SDValue InOp = InVec.getOperand(0);
10155     if (InOp.getValueType() != NVT) {
10156       assert(InOp.getValueType().isInteger() && NVT.isInteger());
10157       return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
10158     }
10159     return InOp;
10160   }
10161
10162   SDValue EltNo = N->getOperand(1);
10163   bool ConstEltNo = isa<ConstantSDNode>(EltNo);
10164
10165   // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
10166   // We only perform this optimization before the op legalization phase because
10167   // we may introduce new vector instructions which are not backed by TD
10168   // patterns. For example on AVX, extracting elements from a wide vector
10169   // without using extract_subvector. However, if we can find an underlying
10170   // scalar value, then we can always use that.
10171   if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
10172       && ConstEltNo) {
10173     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
10174     int NumElem = VT.getVectorNumElements();
10175     ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
10176     // Find the new index to extract from.
10177     int OrigElt = SVOp->getMaskElt(Elt);
10178
10179     // Extracting an undef index is undef.
10180     if (OrigElt == -1)
10181       return DAG.getUNDEF(NVT);
10182
10183     // Select the right vector half to extract from.
10184     SDValue SVInVec;
10185     if (OrigElt < NumElem) {
10186       SVInVec = InVec->getOperand(0);
10187     } else {
10188       SVInVec = InVec->getOperand(1);
10189       OrigElt -= NumElem;
10190     }
10191
10192     if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
10193       SDValue InOp = SVInVec.getOperand(OrigElt);
10194       if (InOp.getValueType() != NVT) {
10195         assert(InOp.getValueType().isInteger() && NVT.isInteger());
10196         InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
10197       }
10198
10199       return InOp;
10200     }
10201
10202     // FIXME: We should handle recursing on other vector shuffles and
10203     // scalar_to_vector here as well.
10204
10205     if (!LegalOperations) {
10206       EVT IndexTy = TLI.getVectorIdxTy();
10207       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT,
10208                          SVInVec, DAG.getConstant(OrigElt, IndexTy));
10209     }
10210   }
10211
10212   bool BCNumEltsChanged = false;
10213   EVT ExtVT = VT.getVectorElementType();
10214   EVT LVT = ExtVT;
10215
10216   // If the result of load has to be truncated, then it's not necessarily
10217   // profitable.
10218   if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
10219     return SDValue();
10220
10221   if (InVec.getOpcode() == ISD::BITCAST) {
10222     // Don't duplicate a load with other uses.
10223     if (!InVec.hasOneUse())
10224       return SDValue();
10225
10226     EVT BCVT = InVec.getOperand(0).getValueType();
10227     if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
10228       return SDValue();
10229     if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
10230       BCNumEltsChanged = true;
10231     InVec = InVec.getOperand(0);
10232     ExtVT = BCVT.getVectorElementType();
10233   }
10234
10235   // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size)
10236   if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() &&
10237       ISD::isNormalLoad(InVec.getNode()) &&
10238       !N->getOperand(1)->hasPredecessor(InVec.getNode())) {
10239     SDValue Index = N->getOperand(1);
10240     if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec))
10241       return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index,
10242                                                            OrigLoad);
10243   }
10244
10245   // Perform only after legalization to ensure build_vector / vector_shuffle
10246   // optimizations have already been done.
10247   if (!LegalOperations) return SDValue();
10248
10249   // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
10250   // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
10251   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
10252
10253   if (ConstEltNo) {
10254     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
10255
10256     LoadSDNode *LN0 = nullptr;
10257     const ShuffleVectorSDNode *SVN = nullptr;
10258     if (ISD::isNormalLoad(InVec.getNode())) {
10259       LN0 = cast<LoadSDNode>(InVec);
10260     } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
10261                InVec.getOperand(0).getValueType() == ExtVT &&
10262                ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
10263       // Don't duplicate a load with other uses.
10264       if (!InVec.hasOneUse())
10265         return SDValue();
10266
10267       LN0 = cast<LoadSDNode>(InVec.getOperand(0));
10268     } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
10269       // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
10270       // =>
10271       // (load $addr+1*size)
10272
10273       // Don't duplicate a load with other uses.
10274       if (!InVec.hasOneUse())
10275         return SDValue();
10276
10277       // If the bit convert changed the number of elements, it is unsafe
10278       // to examine the mask.
10279       if (BCNumEltsChanged)
10280         return SDValue();
10281
10282       // Select the input vector, guarding against out of range extract vector.
10283       unsigned NumElems = VT.getVectorNumElements();
10284       int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
10285       InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
10286
10287       if (InVec.getOpcode() == ISD::BITCAST) {
10288         // Don't duplicate a load with other uses.
10289         if (!InVec.hasOneUse())
10290           return SDValue();
10291
10292         InVec = InVec.getOperand(0);
10293       }
10294       if (ISD::isNormalLoad(InVec.getNode())) {
10295         LN0 = cast<LoadSDNode>(InVec);
10296         Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
10297         EltNo = DAG.getConstant(Elt, EltNo.getValueType());
10298       }
10299     }
10300
10301     // Make sure we found a non-volatile load and the extractelement is
10302     // the only use.
10303     if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
10304       return SDValue();
10305
10306     // If Idx was -1 above, Elt is going to be -1, so just return undef.
10307     if (Elt == -1)
10308       return DAG.getUNDEF(LVT);
10309
10310     return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0);
10311   }
10312
10313   return SDValue();
10314 }
10315
10316 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
10317 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
10318   // We perform this optimization post type-legalization because
10319   // the type-legalizer often scalarizes integer-promoted vectors.
10320   // Performing this optimization before may create bit-casts which
10321   // will be type-legalized to complex code sequences.
10322   // We perform this optimization only before the operation legalizer because we
10323   // may introduce illegal operations.
10324   if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
10325     return SDValue();
10326
10327   unsigned NumInScalars = N->getNumOperands();
10328   SDLoc dl(N);
10329   EVT VT = N->getValueType(0);
10330
10331   // Check to see if this is a BUILD_VECTOR of a bunch of values
10332   // which come from any_extend or zero_extend nodes. If so, we can create
10333   // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
10334   // optimizations. We do not handle sign-extend because we can't fill the sign
10335   // using shuffles.
10336   EVT SourceType = MVT::Other;
10337   bool AllAnyExt = true;
10338
10339   for (unsigned i = 0; i != NumInScalars; ++i) {
10340     SDValue In = N->getOperand(i);
10341     // Ignore undef inputs.
10342     if (In.getOpcode() == ISD::UNDEF) continue;
10343
10344     bool AnyExt  = In.getOpcode() == ISD::ANY_EXTEND;
10345     bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
10346
10347     // Abort if the element is not an extension.
10348     if (!ZeroExt && !AnyExt) {
10349       SourceType = MVT::Other;
10350       break;
10351     }
10352
10353     // The input is a ZeroExt or AnyExt. Check the original type.
10354     EVT InTy = In.getOperand(0).getValueType();
10355
10356     // Check that all of the widened source types are the same.
10357     if (SourceType == MVT::Other)
10358       // First time.
10359       SourceType = InTy;
10360     else if (InTy != SourceType) {
10361       // Multiple income types. Abort.
10362       SourceType = MVT::Other;
10363       break;
10364     }
10365
10366     // Check if all of the extends are ANY_EXTENDs.
10367     AllAnyExt &= AnyExt;
10368   }
10369
10370   // In order to have valid types, all of the inputs must be extended from the
10371   // same source type and all of the inputs must be any or zero extend.
10372   // Scalar sizes must be a power of two.
10373   EVT OutScalarTy = VT.getScalarType();
10374   bool ValidTypes = SourceType != MVT::Other &&
10375                  isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
10376                  isPowerOf2_32(SourceType.getSizeInBits());
10377
10378   // Create a new simpler BUILD_VECTOR sequence which other optimizations can
10379   // turn into a single shuffle instruction.
10380   if (!ValidTypes)
10381     return SDValue();
10382
10383   bool isLE = TLI.isLittleEndian();
10384   unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
10385   assert(ElemRatio > 1 && "Invalid element size ratio");
10386   SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
10387                                DAG.getConstant(0, SourceType);
10388
10389   unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
10390   SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
10391
10392   // Populate the new build_vector
10393   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
10394     SDValue Cast = N->getOperand(i);
10395     assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
10396             Cast.getOpcode() == ISD::ZERO_EXTEND ||
10397             Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
10398     SDValue In;
10399     if (Cast.getOpcode() == ISD::UNDEF)
10400       In = DAG.getUNDEF(SourceType);
10401     else
10402       In = Cast->getOperand(0);
10403     unsigned Index = isLE ? (i * ElemRatio) :
10404                             (i * ElemRatio + (ElemRatio - 1));
10405
10406     assert(Index < Ops.size() && "Invalid index");
10407     Ops[Index] = In;
10408   }
10409
10410   // The type of the new BUILD_VECTOR node.
10411   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
10412   assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
10413          "Invalid vector size");
10414   // Check if the new vector type is legal.
10415   if (!isTypeLegal(VecVT)) return SDValue();
10416
10417   // Make the new BUILD_VECTOR.
10418   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
10419
10420   // The new BUILD_VECTOR node has the potential to be further optimized.
10421   AddToWorklist(BV.getNode());
10422   // Bitcast to the desired type.
10423   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
10424 }
10425
10426 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
10427   EVT VT = N->getValueType(0);
10428
10429   unsigned NumInScalars = N->getNumOperands();
10430   SDLoc dl(N);
10431
10432   EVT SrcVT = MVT::Other;
10433   unsigned Opcode = ISD::DELETED_NODE;
10434   unsigned NumDefs = 0;
10435
10436   for (unsigned i = 0; i != NumInScalars; ++i) {
10437     SDValue In = N->getOperand(i);
10438     unsigned Opc = In.getOpcode();
10439
10440     if (Opc == ISD::UNDEF)
10441       continue;
10442
10443     // If all scalar values are floats and converted from integers.
10444     if (Opcode == ISD::DELETED_NODE &&
10445         (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
10446       Opcode = Opc;
10447     }
10448
10449     if (Opc != Opcode)
10450       return SDValue();
10451
10452     EVT InVT = In.getOperand(0).getValueType();
10453
10454     // If all scalar values are typed differently, bail out. It's chosen to
10455     // simplify BUILD_VECTOR of integer types.
10456     if (SrcVT == MVT::Other)
10457       SrcVT = InVT;
10458     if (SrcVT != InVT)
10459       return SDValue();
10460     NumDefs++;
10461   }
10462
10463   // If the vector has just one element defined, it's not worth to fold it into
10464   // a vectorized one.
10465   if (NumDefs < 2)
10466     return SDValue();
10467
10468   assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
10469          && "Should only handle conversion from integer to float.");
10470   assert(SrcVT != MVT::Other && "Cannot determine source type!");
10471
10472   EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
10473
10474   if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
10475     return SDValue();
10476
10477   SmallVector<SDValue, 8> Opnds;
10478   for (unsigned i = 0; i != NumInScalars; ++i) {
10479     SDValue In = N->getOperand(i);
10480
10481     if (In.getOpcode() == ISD::UNDEF)
10482       Opnds.push_back(DAG.getUNDEF(SrcVT));
10483     else
10484       Opnds.push_back(In.getOperand(0));
10485   }
10486   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds);
10487   AddToWorklist(BV.getNode());
10488
10489   return DAG.getNode(Opcode, dl, VT, BV);
10490 }
10491
10492 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
10493   unsigned NumInScalars = N->getNumOperands();
10494   SDLoc dl(N);
10495   EVT VT = N->getValueType(0);
10496
10497   // A vector built entirely of undefs is undef.
10498   if (ISD::allOperandsUndef(N))
10499     return DAG.getUNDEF(VT);
10500
10501   SDValue V = reduceBuildVecExtToExtBuildVec(N);
10502   if (V.getNode())
10503     return V;
10504
10505   V = reduceBuildVecConvertToConvertBuildVec(N);
10506   if (V.getNode())
10507     return V;
10508
10509   // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
10510   // operations.  If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
10511   // at most two distinct vectors, turn this into a shuffle node.
10512
10513   // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
10514   if (!isTypeLegal(VT))
10515     return SDValue();
10516
10517   // May only combine to shuffle after legalize if shuffle is legal.
10518   if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT))
10519     return SDValue();
10520
10521   SDValue VecIn1, VecIn2;
10522   for (unsigned i = 0; i != NumInScalars; ++i) {
10523     // Ignore undef inputs.
10524     if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
10525
10526     // If this input is something other than a EXTRACT_VECTOR_ELT with a
10527     // constant index, bail out.
10528     if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10529         !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) {
10530       VecIn1 = VecIn2 = SDValue(nullptr, 0);
10531       break;
10532     }
10533
10534     // We allow up to two distinct input vectors.
10535     SDValue ExtractedFromVec = N->getOperand(i).getOperand(0);
10536     if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
10537       continue;
10538
10539     if (!VecIn1.getNode()) {
10540       VecIn1 = ExtractedFromVec;
10541     } else if (!VecIn2.getNode()) {
10542       VecIn2 = ExtractedFromVec;
10543     } else {
10544       // Too many inputs.
10545       VecIn1 = VecIn2 = SDValue(nullptr, 0);
10546       break;
10547     }
10548   }
10549
10550   // If everything is good, we can make a shuffle operation.
10551   if (VecIn1.getNode()) {
10552     SmallVector<int, 8> Mask;
10553     for (unsigned i = 0; i != NumInScalars; ++i) {
10554       if (N->getOperand(i).getOpcode() == ISD::UNDEF) {
10555         Mask.push_back(-1);
10556         continue;
10557       }
10558
10559       // If extracting from the first vector, just use the index directly.
10560       SDValue Extract = N->getOperand(i);
10561       SDValue ExtVal = Extract.getOperand(1);
10562       if (Extract.getOperand(0) == VecIn1) {
10563         unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
10564         if (ExtIndex > VT.getVectorNumElements())
10565           return SDValue();
10566
10567         Mask.push_back(ExtIndex);
10568         continue;
10569       }
10570
10571       // Otherwise, use InIdx + VecSize
10572       unsigned Idx = cast<ConstantSDNode>(ExtVal)->getZExtValue();
10573       Mask.push_back(Idx+NumInScalars);
10574     }
10575
10576     // We can't generate a shuffle node with mismatched input and output types.
10577     // Attempt to transform a single input vector to the correct type.
10578     if ((VT != VecIn1.getValueType())) {
10579       // We don't support shuffeling between TWO values of different types.
10580       if (VecIn2.getNode())
10581         return SDValue();
10582
10583       // We only support widening of vectors which are half the size of the
10584       // output registers. For example XMM->YMM widening on X86 with AVX.
10585       if (VecIn1.getValueType().getSizeInBits()*2 != VT.getSizeInBits())
10586         return SDValue();
10587
10588       // If the input vector type has a different base type to the output
10589       // vector type, bail out.
10590       if (VecIn1.getValueType().getVectorElementType() !=
10591           VT.getVectorElementType())
10592         return SDValue();
10593
10594       // Widen the input vector by adding undef values.
10595       VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10596                            VecIn1, DAG.getUNDEF(VecIn1.getValueType()));
10597     }
10598
10599     // If VecIn2 is unused then change it to undef.
10600     VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
10601
10602     // Check that we were able to transform all incoming values to the same
10603     // type.
10604     if (VecIn2.getValueType() != VecIn1.getValueType() ||
10605         VecIn1.getValueType() != VT)
10606           return SDValue();
10607
10608     // Return the new VECTOR_SHUFFLE node.
10609     SDValue Ops[2];
10610     Ops[0] = VecIn1;
10611     Ops[1] = VecIn2;
10612     return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
10613   }
10614
10615   return SDValue();
10616 }
10617
10618 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
10619   // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
10620   // EXTRACT_SUBVECTOR operations.  If so, and if the EXTRACT_SUBVECTOR vector
10621   // inputs come from at most two distinct vectors, turn this into a shuffle
10622   // node.
10623
10624   // If we only have one input vector, we don't need to do any concatenation.
10625   if (N->getNumOperands() == 1)
10626     return N->getOperand(0);
10627
10628   // Check if all of the operands are undefs.
10629   EVT VT = N->getValueType(0);
10630   if (ISD::allOperandsUndef(N))
10631     return DAG.getUNDEF(VT);
10632
10633   // Optimize concat_vectors where one of the vectors is undef.
10634   if (N->getNumOperands() == 2 &&
10635       N->getOperand(1)->getOpcode() == ISD::UNDEF) {
10636     SDValue In = N->getOperand(0);
10637     assert(In.getValueType().isVector() && "Must concat vectors");
10638
10639     // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
10640     if (In->getOpcode() == ISD::BITCAST &&
10641         !In->getOperand(0)->getValueType(0).isVector()) {
10642       SDValue Scalar = In->getOperand(0);
10643       EVT SclTy = Scalar->getValueType(0);
10644
10645       if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
10646         return SDValue();
10647
10648       EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
10649                                  VT.getSizeInBits() / SclTy.getSizeInBits());
10650       if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
10651         return SDValue();
10652
10653       SDLoc dl = SDLoc(N);
10654       SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
10655       return DAG.getNode(ISD::BITCAST, dl, VT, Res);
10656     }
10657   }
10658
10659   // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
10660   // -> (BUILD_VECTOR A, B, ..., C, D, ...)
10661   if (N->getNumOperands() == 2 &&
10662       N->getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
10663       N->getOperand(1).getOpcode() == ISD::BUILD_VECTOR) {
10664     EVT VT = N->getValueType(0);
10665     SDValue N0 = N->getOperand(0);
10666     SDValue N1 = N->getOperand(1);
10667     SmallVector<SDValue, 8> Opnds;
10668     unsigned BuildVecNumElts =  N0.getNumOperands();
10669
10670     EVT SclTy0 = N0.getOperand(0)->getValueType(0);
10671     EVT SclTy1 = N1.getOperand(0)->getValueType(0);
10672     if (SclTy0.isFloatingPoint()) {
10673       for (unsigned i = 0; i != BuildVecNumElts; ++i)
10674         Opnds.push_back(N0.getOperand(i));
10675       for (unsigned i = 0; i != BuildVecNumElts; ++i)
10676         Opnds.push_back(N1.getOperand(i));
10677     } else {
10678       // If BUILD_VECTOR are from built from integer, they may have different
10679       // operand types. Get the smaller type and truncate all operands to it.
10680       EVT MinTy = SclTy0.bitsLE(SclTy1) ? SclTy0 : SclTy1;
10681       for (unsigned i = 0; i != BuildVecNumElts; ++i)
10682         Opnds.push_back(DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinTy,
10683                         N0.getOperand(i)));
10684       for (unsigned i = 0; i != BuildVecNumElts; ++i)
10685         Opnds.push_back(DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinTy,
10686                         N1.getOperand(i)));
10687     }
10688
10689     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
10690   }
10691
10692   // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
10693   // nodes often generate nop CONCAT_VECTOR nodes.
10694   // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
10695   // place the incoming vectors at the exact same location.
10696   SDValue SingleSource = SDValue();
10697   unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
10698
10699   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
10700     SDValue Op = N->getOperand(i);
10701
10702     if (Op.getOpcode() == ISD::UNDEF)
10703       continue;
10704
10705     // Check if this is the identity extract:
10706     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
10707       return SDValue();
10708
10709     // Find the single incoming vector for the extract_subvector.
10710     if (SingleSource.getNode()) {
10711       if (Op.getOperand(0) != SingleSource)
10712         return SDValue();
10713     } else {
10714       SingleSource = Op.getOperand(0);
10715
10716       // Check the source type is the same as the type of the result.
10717       // If not, this concat may extend the vector, so we can not
10718       // optimize it away.
10719       if (SingleSource.getValueType() != N->getValueType(0))
10720         return SDValue();
10721     }
10722
10723     unsigned IdentityIndex = i * PartNumElem;
10724     ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
10725     // The extract index must be constant.
10726     if (!CS)
10727       return SDValue();
10728
10729     // Check that we are reading from the identity index.
10730     if (CS->getZExtValue() != IdentityIndex)
10731       return SDValue();
10732   }
10733
10734   if (SingleSource.getNode())
10735     return SingleSource;
10736
10737   return SDValue();
10738 }
10739
10740 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
10741   EVT NVT = N->getValueType(0);
10742   SDValue V = N->getOperand(0);
10743
10744   if (V->getOpcode() == ISD::CONCAT_VECTORS) {
10745     // Combine:
10746     //    (extract_subvec (concat V1, V2, ...), i)
10747     // Into:
10748     //    Vi if possible
10749     // Only operand 0 is checked as 'concat' assumes all inputs of the same
10750     // type.
10751     if (V->getOperand(0).getValueType() != NVT)
10752       return SDValue();
10753     unsigned Idx = dyn_cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
10754     unsigned NumElems = NVT.getVectorNumElements();
10755     assert((Idx % NumElems) == 0 &&
10756            "IDX in concat is not a multiple of the result vector length.");
10757     return V->getOperand(Idx / NumElems);
10758   }
10759
10760   // Skip bitcasting
10761   if (V->getOpcode() == ISD::BITCAST)
10762     V = V.getOperand(0);
10763
10764   if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
10765     SDLoc dl(N);
10766     // Handle only simple case where vector being inserted and vector
10767     // being extracted are of same type, and are half size of larger vectors.
10768     EVT BigVT = V->getOperand(0).getValueType();
10769     EVT SmallVT = V->getOperand(1).getValueType();
10770     if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
10771       return SDValue();
10772
10773     // Only handle cases where both indexes are constants with the same type.
10774     ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
10775     ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
10776
10777     if (InsIdx && ExtIdx &&
10778         InsIdx->getValueType(0).getSizeInBits() <= 64 &&
10779         ExtIdx->getValueType(0).getSizeInBits() <= 64) {
10780       // Combine:
10781       //    (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
10782       // Into:
10783       //    indices are equal or bit offsets are equal => V1
10784       //    otherwise => (extract_subvec V1, ExtIdx)
10785       if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
10786           ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
10787         return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
10788       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
10789                          DAG.getNode(ISD::BITCAST, dl,
10790                                      N->getOperand(0).getValueType(),
10791                                      V->getOperand(0)), N->getOperand(1));
10792     }
10793   }
10794
10795   return SDValue();
10796 }
10797
10798 static SDValue simplifyShuffleOperandRecursively(SmallBitVector &UsedElements,
10799                                                  SDValue V, SelectionDAG &DAG) {
10800   SDLoc DL(V);
10801   EVT VT = V.getValueType();
10802
10803   switch (V.getOpcode()) {
10804   default:
10805     return V;
10806
10807   case ISD::CONCAT_VECTORS: {
10808     EVT OpVT = V->getOperand(0).getValueType();
10809     int OpSize = OpVT.getVectorNumElements();
10810     SmallBitVector OpUsedElements(OpSize, false);
10811     bool FoundSimplification = false;
10812     SmallVector<SDValue, 4> NewOps;
10813     NewOps.reserve(V->getNumOperands());
10814     for (int i = 0, NumOps = V->getNumOperands(); i < NumOps; ++i) {
10815       SDValue Op = V->getOperand(i);
10816       bool OpUsed = false;
10817       for (int j = 0; j < OpSize; ++j)
10818         if (UsedElements[i * OpSize + j]) {
10819           OpUsedElements[j] = true;
10820           OpUsed = true;
10821         }
10822       NewOps.push_back(
10823           OpUsed ? simplifyShuffleOperandRecursively(OpUsedElements, Op, DAG)
10824                  : DAG.getUNDEF(OpVT));
10825       FoundSimplification |= Op == NewOps.back();
10826       OpUsedElements.reset();
10827     }
10828     if (FoundSimplification)
10829       V = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, NewOps);
10830     return V;
10831   }
10832
10833   case ISD::INSERT_SUBVECTOR: {
10834     SDValue BaseV = V->getOperand(0);
10835     SDValue SubV = V->getOperand(1);
10836     auto *IdxN = dyn_cast<ConstantSDNode>(V->getOperand(2));
10837     if (!IdxN)
10838       return V;
10839
10840     int SubSize = SubV.getValueType().getVectorNumElements();
10841     int Idx = IdxN->getZExtValue();
10842     bool SubVectorUsed = false;
10843     SmallBitVector SubUsedElements(SubSize, false);
10844     for (int i = 0; i < SubSize; ++i)
10845       if (UsedElements[i + Idx]) {
10846         SubVectorUsed = true;
10847         SubUsedElements[i] = true;
10848         UsedElements[i + Idx] = false;
10849       }
10850
10851     // Now recurse on both the base and sub vectors.
10852     SDValue SimplifiedSubV =
10853         SubVectorUsed
10854             ? simplifyShuffleOperandRecursively(SubUsedElements, SubV, DAG)
10855             : DAG.getUNDEF(SubV.getValueType());
10856     SDValue SimplifiedBaseV = simplifyShuffleOperandRecursively(UsedElements, BaseV, DAG);
10857     if (SimplifiedSubV != SubV || SimplifiedBaseV != BaseV)
10858       V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
10859                       SimplifiedBaseV, SimplifiedSubV, V->getOperand(2));
10860     return V;
10861   }
10862   }
10863 }
10864
10865 static SDValue simplifyShuffleOperands(ShuffleVectorSDNode *SVN, SDValue N0,
10866                                        SDValue N1, SelectionDAG &DAG) {
10867   EVT VT = SVN->getValueType(0);
10868   int NumElts = VT.getVectorNumElements();
10869   SmallBitVector N0UsedElements(NumElts, false), N1UsedElements(NumElts, false);
10870   for (int M : SVN->getMask())
10871     if (M >= 0 && M < NumElts)
10872       N0UsedElements[M] = true;
10873     else if (M >= NumElts)
10874       N1UsedElements[M - NumElts] = true;
10875
10876   SDValue S0 = simplifyShuffleOperandRecursively(N0UsedElements, N0, DAG);
10877   SDValue S1 = simplifyShuffleOperandRecursively(N1UsedElements, N1, DAG);
10878   if (S0 == N0 && S1 == N1)
10879     return SDValue();
10880
10881   return DAG.getVectorShuffle(VT, SDLoc(SVN), S0, S1, SVN->getMask());
10882 }
10883
10884 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat.
10885 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
10886   EVT VT = N->getValueType(0);
10887   unsigned NumElts = VT.getVectorNumElements();
10888
10889   SDValue N0 = N->getOperand(0);
10890   SDValue N1 = N->getOperand(1);
10891   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10892
10893   SmallVector<SDValue, 4> Ops;
10894   EVT ConcatVT = N0.getOperand(0).getValueType();
10895   unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
10896   unsigned NumConcats = NumElts / NumElemsPerConcat;
10897
10898   // Look at every vector that's inserted. We're looking for exact
10899   // subvector-sized copies from a concatenated vector
10900   for (unsigned I = 0; I != NumConcats; ++I) {
10901     // Make sure we're dealing with a copy.
10902     unsigned Begin = I * NumElemsPerConcat;
10903     bool AllUndef = true, NoUndef = true;
10904     for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
10905       if (SVN->getMaskElt(J) >= 0)
10906         AllUndef = false;
10907       else
10908         NoUndef = false;
10909     }
10910
10911     if (NoUndef) {
10912       if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
10913         return SDValue();
10914
10915       for (unsigned J = 1; J != NumElemsPerConcat; ++J)
10916         if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
10917           return SDValue();
10918
10919       unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
10920       if (FirstElt < N0.getNumOperands())
10921         Ops.push_back(N0.getOperand(FirstElt));
10922       else
10923         Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
10924
10925     } else if (AllUndef) {
10926       Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
10927     } else { // Mixed with general masks and undefs, can't do optimization.
10928       return SDValue();
10929     }
10930   }
10931
10932   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
10933 }
10934
10935 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
10936   EVT VT = N->getValueType(0);
10937   unsigned NumElts = VT.getVectorNumElements();
10938
10939   SDValue N0 = N->getOperand(0);
10940   SDValue N1 = N->getOperand(1);
10941
10942   assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
10943
10944   // Canonicalize shuffle undef, undef -> undef
10945   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
10946     return DAG.getUNDEF(VT);
10947
10948   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10949
10950   // Canonicalize shuffle v, v -> v, undef
10951   if (N0 == N1) {
10952     SmallVector<int, 8> NewMask;
10953     for (unsigned i = 0; i != NumElts; ++i) {
10954       int Idx = SVN->getMaskElt(i);
10955       if (Idx >= (int)NumElts) Idx -= NumElts;
10956       NewMask.push_back(Idx);
10957     }
10958     return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
10959                                 &NewMask[0]);
10960   }
10961
10962   // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
10963   if (N0.getOpcode() == ISD::UNDEF) {
10964     SmallVector<int, 8> NewMask;
10965     for (unsigned i = 0; i != NumElts; ++i) {
10966       int Idx = SVN->getMaskElt(i);
10967       if (Idx >= 0) {
10968         if (Idx >= (int)NumElts)
10969           Idx -= NumElts;
10970         else
10971           Idx = -1; // remove reference to lhs
10972       }
10973       NewMask.push_back(Idx);
10974     }
10975     return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
10976                                 &NewMask[0]);
10977   }
10978
10979   // Remove references to rhs if it is undef
10980   if (N1.getOpcode() == ISD::UNDEF) {
10981     bool Changed = false;
10982     SmallVector<int, 8> NewMask;
10983     for (unsigned i = 0; i != NumElts; ++i) {
10984       int Idx = SVN->getMaskElt(i);
10985       if (Idx >= (int)NumElts) {
10986         Idx = -1;
10987         Changed = true;
10988       }
10989       NewMask.push_back(Idx);
10990     }
10991     if (Changed)
10992       return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
10993   }
10994
10995   // If it is a splat, check if the argument vector is another splat or a
10996   // build_vector with all scalar elements the same.
10997   if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
10998     SDNode *V = N0.getNode();
10999
11000     // If this is a bit convert that changes the element type of the vector but
11001     // not the number of vector elements, look through it.  Be careful not to
11002     // look though conversions that change things like v4f32 to v2f64.
11003     if (V->getOpcode() == ISD::BITCAST) {
11004       SDValue ConvInput = V->getOperand(0);
11005       if (ConvInput.getValueType().isVector() &&
11006           ConvInput.getValueType().getVectorNumElements() == NumElts)
11007         V = ConvInput.getNode();
11008     }
11009
11010     if (V->getOpcode() == ISD::BUILD_VECTOR) {
11011       assert(V->getNumOperands() == NumElts &&
11012              "BUILD_VECTOR has wrong number of operands");
11013       SDValue Base;
11014       bool AllSame = true;
11015       for (unsigned i = 0; i != NumElts; ++i) {
11016         if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
11017           Base = V->getOperand(i);
11018           break;
11019         }
11020       }
11021       // Splat of <u, u, u, u>, return <u, u, u, u>
11022       if (!Base.getNode())
11023         return N0;
11024       for (unsigned i = 0; i != NumElts; ++i) {
11025         if (V->getOperand(i) != Base) {
11026           AllSame = false;
11027           break;
11028         }
11029       }
11030       // Splat of <x, x, x, x>, return <x, x, x, x>
11031       if (AllSame)
11032         return N0;
11033     }
11034   }
11035
11036   // There are various patterns used to build up a vector from smaller vectors,
11037   // subvectors, or elements. Scan chains of these and replace unused insertions
11038   // or components with undef.
11039   if (SDValue S = simplifyShuffleOperands(SVN, N0, N1, DAG))
11040     return S;
11041
11042   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
11043       Level < AfterLegalizeVectorOps &&
11044       (N1.getOpcode() == ISD::UNDEF ||
11045       (N1.getOpcode() == ISD::CONCAT_VECTORS &&
11046        N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
11047     SDValue V = partitionShuffleOfConcats(N, DAG);
11048
11049     if (V.getNode())
11050       return V;
11051   }
11052
11053   // If this shuffle node is simply a swizzle of another shuffle node,
11054   // then try to simplify it.
11055   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
11056       N1.getOpcode() == ISD::UNDEF) {
11057
11058     ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
11059
11060     // The incoming shuffle must be of the same type as the result of the
11061     // current shuffle.
11062     assert(OtherSV->getOperand(0).getValueType() == VT &&
11063            "Shuffle types don't match");
11064
11065     SmallVector<int, 4> Mask;
11066     // Compute the combined shuffle mask.
11067     for (unsigned i = 0; i != NumElts; ++i) {
11068       int Idx = SVN->getMaskElt(i);
11069       assert(Idx < (int)NumElts && "Index references undef operand");
11070       // Next, this index comes from the first value, which is the incoming
11071       // shuffle. Adopt the incoming index.
11072       if (Idx >= 0)
11073         Idx = OtherSV->getMaskElt(Idx);
11074       Mask.push_back(Idx);
11075     }
11076
11077     // Check if all indices in Mask are Undef. In case, propagate Undef.
11078     bool isUndefMask = true;
11079     for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
11080       isUndefMask &= Mask[i] < 0;
11081
11082     if (isUndefMask)
11083       return DAG.getUNDEF(VT);
11084
11085     bool CommuteOperands = false;
11086     if (N0.getOperand(1).getOpcode() != ISD::UNDEF) {
11087       // To be valid, the combine shuffle mask should only reference elements
11088       // from one of the two vectors in input to the inner shufflevector.
11089       bool IsValidMask = true;
11090       for (unsigned i = 0; i != NumElts && IsValidMask; ++i)
11091         // See if the combined mask only reference undefs or elements coming
11092         // from the first shufflevector operand.
11093         IsValidMask = Mask[i] < 0 || (unsigned)Mask[i] < NumElts;
11094
11095       if (!IsValidMask) {
11096         IsValidMask = true;
11097         for (unsigned i = 0; i != NumElts && IsValidMask; ++i)
11098           // Check that all the elements come from the second shuffle operand.
11099           IsValidMask = Mask[i] < 0 || (unsigned)Mask[i] >= NumElts;
11100         CommuteOperands = IsValidMask;
11101       }
11102
11103       // Early exit if the combined shuffle mask is not valid.
11104       if (!IsValidMask)
11105         return SDValue();
11106     }
11107
11108     // See if this pair of shuffles can be safely folded according to either
11109     // of the following rules:
11110     //   shuffle(shuffle(x, y), undef) -> x
11111     //   shuffle(shuffle(x, undef), undef) -> x
11112     //   shuffle(shuffle(x, y), undef) -> y
11113     bool IsIdentityMask = true;
11114     unsigned BaseMaskIndex = CommuteOperands ? NumElts : 0;
11115     for (unsigned i = 0; i != NumElts && IsIdentityMask; ++i) {
11116       // Skip Undefs.
11117       if (Mask[i] < 0)
11118         continue;
11119
11120       // The combined shuffle must map each index to itself.
11121       IsIdentityMask = (unsigned)Mask[i] == i + BaseMaskIndex;
11122     }
11123
11124     if (IsIdentityMask) {
11125       if (CommuteOperands)
11126         // optimize shuffle(shuffle(x, y), undef) -> y.
11127         return OtherSV->getOperand(1);
11128
11129       // optimize shuffle(shuffle(x, undef), undef) -> x
11130       // optimize shuffle(shuffle(x, y), undef) -> x
11131       return OtherSV->getOperand(0);
11132     }
11133
11134     // It may still be beneficial to combine the two shuffles if the
11135     // resulting shuffle is legal.
11136     if (TLI.isTypeLegal(VT)) {
11137       if (!CommuteOperands) {
11138         if (TLI.isShuffleMaskLegal(Mask, VT))
11139           // shuffle(shuffle(x, undef, M1), undef, M2) -> shuffle(x, undef, M3).
11140           // shuffle(shuffle(x, y, M1), undef, M2) -> shuffle(x, undef, M3)
11141           return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0), N1,
11142                                       &Mask[0]);
11143       } else {
11144         // Compute the commuted shuffle mask.
11145         for (unsigned i = 0; i != NumElts; ++i) {
11146           int idx = Mask[i];
11147           if (idx < 0)
11148             continue;
11149           else if (idx < (int)NumElts)
11150             Mask[i] = idx + NumElts;
11151           else
11152             Mask[i] = idx - NumElts;
11153         }
11154
11155         if (TLI.isShuffleMaskLegal(Mask, VT))
11156           //   shuffle(shuffle(x, y, M1), undef, M2) -> shuffle(y, undef, M3)
11157           return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(1), N1,
11158                                       &Mask[0]);
11159       }
11160     }
11161   }
11162
11163   // Canonicalize shuffles according to rules:
11164   //  shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
11165   //  shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
11166   //  shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
11167   if (N1.getOpcode() == ISD::VECTOR_SHUFFLE && N0.getOpcode() != ISD::UNDEF &&
11168       N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
11169       TLI.isTypeLegal(VT)) {
11170     // The incoming shuffle must be of the same type as the result of the
11171     // current shuffle.
11172     assert(N1->getOperand(0).getValueType() == VT &&
11173            "Shuffle types don't match");
11174
11175     SDValue SV0 = N1->getOperand(0);
11176     SDValue SV1 = N1->getOperand(1);
11177     bool HasSameOp0 = N0 == SV0;
11178     bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
11179     if (HasSameOp0 || IsSV1Undef || N0 == SV1)
11180       // Commute the operands of this shuffle so that next rule
11181       // will trigger.
11182       return DAG.getCommutedVectorShuffle(*SVN);
11183   }
11184
11185   // Try to fold according to rules:
11186   //   shuffle(shuffle(A, B, M0), B, M1) -> shuffle(A, B, M2)
11187   //   shuffle(shuffle(A, B, M0), A, M1) -> shuffle(A, B, M2)
11188   //   shuffle(shuffle(A, Undef, M0), B, M1) -> shuffle(A, B, M2)
11189   //   shuffle(shuffle(A, Undef, M0), A, M1) -> shuffle(A, Undef, M2)
11190   // Don't try to fold shuffles with illegal type.
11191   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
11192       N1.getOpcode() != ISD::UNDEF && TLI.isTypeLegal(VT)) {
11193     ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
11194
11195     // The incoming shuffle must be of the same type as the result of the
11196     // current shuffle.
11197     assert(OtherSV->getOperand(0).getValueType() == VT &&
11198            "Shuffle types don't match");
11199
11200     SDValue SV0 = OtherSV->getOperand(0);
11201     SDValue SV1 = OtherSV->getOperand(1);
11202     bool HasSameOp0 = N1 == SV0;
11203     bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
11204     if (!HasSameOp0 && !IsSV1Undef && N1 != SV1)
11205       // Early exit.
11206       return SDValue();
11207
11208     SmallVector<int, 4> Mask;
11209     // Compute the combined shuffle mask for a shuffle with SV0 as the first
11210     // operand, and SV1 as the second operand.
11211     for (unsigned i = 0; i != NumElts; ++i) {
11212       int Idx = SVN->getMaskElt(i);
11213       if (Idx < 0) {
11214         // Propagate Undef.
11215         Mask.push_back(Idx);
11216         continue;
11217       }
11218
11219       if (Idx < (int)NumElts) {
11220         Idx = OtherSV->getMaskElt(Idx);
11221         if (IsSV1Undef && Idx >= (int) NumElts)
11222           Idx = -1;  // Propagate Undef.
11223       } else
11224         Idx = HasSameOp0 ? Idx - NumElts : Idx;
11225
11226       Mask.push_back(Idx);
11227     }
11228
11229     // Check if all indices in Mask are Undef. In case, propagate Undef.
11230     bool isUndefMask = true;
11231     for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
11232       isUndefMask &= Mask[i] < 0;
11233
11234     if (isUndefMask)
11235       return DAG.getUNDEF(VT);
11236
11237     // Avoid introducing shuffles with illegal mask.
11238     if (TLI.isShuffleMaskLegal(Mask, VT)) {
11239       if (IsSV1Undef)
11240         //   shuffle(shuffle(A, Undef, M0), B, M1) -> shuffle(A, B, M2)
11241         //   shuffle(shuffle(A, Undef, M0), A, M1) -> shuffle(A, Undef, M2)
11242         return DAG.getVectorShuffle(VT, SDLoc(N), SV0, N1, &Mask[0]);
11243       return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, &Mask[0]);
11244     }
11245
11246     // Compute the commuted shuffle mask.
11247     for (unsigned i = 0; i != NumElts; ++i) {
11248       int idx = Mask[i];
11249       if (idx < 0)
11250         continue;
11251       else if (idx < (int)NumElts)
11252         Mask[i] = idx + NumElts;
11253       else
11254         Mask[i] = idx - NumElts;
11255     }
11256
11257     if (TLI.isShuffleMaskLegal(Mask, VT)) {
11258       if (IsSV1Undef)
11259         //   shuffle(shuffle(A, Undef, M0), B, M1) -> shuffle(B, A, M2)
11260         return DAG.getVectorShuffle(VT, SDLoc(N), N1, SV0, &Mask[0]);
11261       //   shuffle(shuffle(A, B, M0), B, M1) -> shuffle(B, A, M2)
11262       //   shuffle(shuffle(A, B, M0), A, M1) -> shuffle(B, A, M2)
11263       return DAG.getVectorShuffle(VT, SDLoc(N), SV1, SV0, &Mask[0]);
11264     }
11265   }
11266
11267   return SDValue();
11268 }
11269
11270 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
11271   SDValue N0 = N->getOperand(0);
11272   SDValue N2 = N->getOperand(2);
11273
11274   // If the input vector is a concatenation, and the insert replaces
11275   // one of the halves, we can optimize into a single concat_vectors.
11276   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
11277       N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
11278     APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
11279     EVT VT = N->getValueType(0);
11280
11281     // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
11282     // (concat_vectors Z, Y)
11283     if (InsIdx == 0)
11284       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
11285                          N->getOperand(1), N0.getOperand(1));
11286
11287     // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
11288     // (concat_vectors X, Z)
11289     if (InsIdx == VT.getVectorNumElements()/2)
11290       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
11291                          N0.getOperand(0), N->getOperand(1));
11292   }
11293
11294   return SDValue();
11295 }
11296
11297 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle
11298 /// with the destination vector and a zero vector.
11299 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
11300 ///      vector_shuffle V, Zero, <0, 4, 2, 4>
11301 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
11302   EVT VT = N->getValueType(0);
11303   SDLoc dl(N);
11304   SDValue LHS = N->getOperand(0);
11305   SDValue RHS = N->getOperand(1);
11306   if (N->getOpcode() == ISD::AND) {
11307     if (RHS.getOpcode() == ISD::BITCAST)
11308       RHS = RHS.getOperand(0);
11309     if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
11310       SmallVector<int, 8> Indices;
11311       unsigned NumElts = RHS.getNumOperands();
11312       for (unsigned i = 0; i != NumElts; ++i) {
11313         SDValue Elt = RHS.getOperand(i);
11314         if (!isa<ConstantSDNode>(Elt))
11315           return SDValue();
11316
11317         if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
11318           Indices.push_back(i);
11319         else if (cast<ConstantSDNode>(Elt)->isNullValue())
11320           Indices.push_back(NumElts+i);
11321         else
11322           return SDValue();
11323       }
11324
11325       // Let's see if the target supports this vector_shuffle.
11326       EVT RVT = RHS.getValueType();
11327       if (!TLI.isVectorClearMaskLegal(Indices, RVT))
11328         return SDValue();
11329
11330       // Return the new VECTOR_SHUFFLE node.
11331       EVT EltVT = RVT.getVectorElementType();
11332       SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
11333                                      DAG.getConstant(0, EltVT));
11334       SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), RVT, ZeroOps);
11335       LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
11336       SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
11337       return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
11338     }
11339   }
11340
11341   return SDValue();
11342 }
11343
11344 /// Visit a binary vector operation, like ADD.
11345 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
11346   assert(N->getValueType(0).isVector() &&
11347          "SimplifyVBinOp only works on vectors!");
11348
11349   SDValue LHS = N->getOperand(0);
11350   SDValue RHS = N->getOperand(1);
11351   SDValue Shuffle = XformToShuffleWithZero(N);
11352   if (Shuffle.getNode()) return Shuffle;
11353
11354   // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
11355   // this operation.
11356   if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
11357       RHS.getOpcode() == ISD::BUILD_VECTOR) {
11358     // Check if both vectors are constants. If not bail out.
11359     if (!(cast<BuildVectorSDNode>(LHS)->isConstant() &&
11360           cast<BuildVectorSDNode>(RHS)->isConstant()))
11361       return SDValue();
11362
11363     SmallVector<SDValue, 8> Ops;
11364     for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
11365       SDValue LHSOp = LHS.getOperand(i);
11366       SDValue RHSOp = RHS.getOperand(i);
11367
11368       // Can't fold divide by zero.
11369       if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
11370           N->getOpcode() == ISD::FDIV) {
11371         if ((RHSOp.getOpcode() == ISD::Constant &&
11372              cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
11373             (RHSOp.getOpcode() == ISD::ConstantFP &&
11374              cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
11375           break;
11376       }
11377
11378       EVT VT = LHSOp.getValueType();
11379       EVT RVT = RHSOp.getValueType();
11380       if (RVT != VT) {
11381         // Integer BUILD_VECTOR operands may have types larger than the element
11382         // size (e.g., when the element type is not legal).  Prior to type
11383         // legalization, the types may not match between the two BUILD_VECTORS.
11384         // Truncate one of the operands to make them match.
11385         if (RVT.getSizeInBits() > VT.getSizeInBits()) {
11386           RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
11387         } else {
11388           LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
11389           VT = RVT;
11390         }
11391       }
11392       SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
11393                                    LHSOp, RHSOp);
11394       if (FoldOp.getOpcode() != ISD::UNDEF &&
11395           FoldOp.getOpcode() != ISD::Constant &&
11396           FoldOp.getOpcode() != ISD::ConstantFP)
11397         break;
11398       Ops.push_back(FoldOp);
11399       AddToWorklist(FoldOp.getNode());
11400     }
11401
11402     if (Ops.size() == LHS.getNumOperands())
11403       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), LHS.getValueType(), Ops);
11404   }
11405
11406   // Type legalization might introduce new shuffles in the DAG.
11407   // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
11408   //   -> (shuffle (VBinOp (A, B)), Undef, Mask).
11409   if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
11410       isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
11411       LHS.getOperand(1).getOpcode() == ISD::UNDEF &&
11412       RHS.getOperand(1).getOpcode() == ISD::UNDEF) {
11413     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
11414     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
11415
11416     if (SVN0->getMask().equals(SVN1->getMask())) {
11417       EVT VT = N->getValueType(0);
11418       SDValue UndefVector = LHS.getOperand(1);
11419       SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
11420                                      LHS.getOperand(0), RHS.getOperand(0));
11421       AddUsersToWorklist(N);
11422       return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
11423                                   &SVN0->getMask()[0]);
11424     }
11425   }
11426
11427   return SDValue();
11428 }
11429
11430 /// Visit a binary vector operation, like FABS/FNEG.
11431 SDValue DAGCombiner::SimplifyVUnaryOp(SDNode *N) {
11432   assert(N->getValueType(0).isVector() &&
11433          "SimplifyVUnaryOp only works on vectors!");
11434
11435   SDValue N0 = N->getOperand(0);
11436
11437   if (N0.getOpcode() != ISD::BUILD_VECTOR)
11438     return SDValue();
11439
11440   // Operand is a BUILD_VECTOR node, see if we can constant fold it.
11441   SmallVector<SDValue, 8> Ops;
11442   for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
11443     SDValue Op = N0.getOperand(i);
11444     if (Op.getOpcode() != ISD::UNDEF &&
11445         Op.getOpcode() != ISD::ConstantFP)
11446       break;
11447     EVT EltVT = Op.getValueType();
11448     SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(N0), EltVT, Op);
11449     if (FoldOp.getOpcode() != ISD::UNDEF &&
11450         FoldOp.getOpcode() != ISD::ConstantFP)
11451       break;
11452     Ops.push_back(FoldOp);
11453     AddToWorklist(FoldOp.getNode());
11454   }
11455
11456   if (Ops.size() != N0.getNumOperands())
11457     return SDValue();
11458
11459   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), N0.getValueType(), Ops);
11460 }
11461
11462 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
11463                                     SDValue N1, SDValue N2){
11464   assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
11465
11466   SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
11467                                  cast<CondCodeSDNode>(N0.getOperand(2))->get());
11468
11469   // If we got a simplified select_cc node back from SimplifySelectCC, then
11470   // break it down into a new SETCC node, and a new SELECT node, and then return
11471   // the SELECT node, since we were called with a SELECT node.
11472   if (SCC.getNode()) {
11473     // Check to see if we got a select_cc back (to turn into setcc/select).
11474     // Otherwise, just return whatever node we got back, like fabs.
11475     if (SCC.getOpcode() == ISD::SELECT_CC) {
11476       SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
11477                                   N0.getValueType(),
11478                                   SCC.getOperand(0), SCC.getOperand(1),
11479                                   SCC.getOperand(4));
11480       AddToWorklist(SETCC.getNode());
11481       return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC,
11482                            SCC.getOperand(2), SCC.getOperand(3));
11483     }
11484
11485     return SCC;
11486   }
11487   return SDValue();
11488 }
11489
11490 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values
11491 /// being selected between, see if we can simplify the select.  Callers of this
11492 /// should assume that TheSelect is deleted if this returns true.  As such, they
11493 /// should return the appropriate thing (e.g. the node) back to the top-level of
11494 /// the DAG combiner loop to avoid it being looked at.
11495 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
11496                                     SDValue RHS) {
11497
11498   // Cannot simplify select with vector condition
11499   if (TheSelect->getOperand(0).getValueType().isVector()) return false;
11500
11501   // If this is a select from two identical things, try to pull the operation
11502   // through the select.
11503   if (LHS.getOpcode() != RHS.getOpcode() ||
11504       !LHS.hasOneUse() || !RHS.hasOneUse())
11505     return false;
11506
11507   // If this is a load and the token chain is identical, replace the select
11508   // of two loads with a load through a select of the address to load from.
11509   // This triggers in things like "select bool X, 10.0, 123.0" after the FP
11510   // constants have been dropped into the constant pool.
11511   if (LHS.getOpcode() == ISD::LOAD) {
11512     LoadSDNode *LLD = cast<LoadSDNode>(LHS);
11513     LoadSDNode *RLD = cast<LoadSDNode>(RHS);
11514
11515     // Token chains must be identical.
11516     if (LHS.getOperand(0) != RHS.getOperand(0) ||
11517         // Do not let this transformation reduce the number of volatile loads.
11518         LLD->isVolatile() || RLD->isVolatile() ||
11519         // If this is an EXTLOAD, the VT's must match.
11520         LLD->getMemoryVT() != RLD->getMemoryVT() ||
11521         // If this is an EXTLOAD, the kind of extension must match.
11522         (LLD->getExtensionType() != RLD->getExtensionType() &&
11523          // The only exception is if one of the extensions is anyext.
11524          LLD->getExtensionType() != ISD::EXTLOAD &&
11525          RLD->getExtensionType() != ISD::EXTLOAD) ||
11526         // FIXME: this discards src value information.  This is
11527         // over-conservative. It would be beneficial to be able to remember
11528         // both potential memory locations.  Since we are discarding
11529         // src value info, don't do the transformation if the memory
11530         // locations are not in the default address space.
11531         LLD->getPointerInfo().getAddrSpace() != 0 ||
11532         RLD->getPointerInfo().getAddrSpace() != 0 ||
11533         !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
11534                                       LLD->getBasePtr().getValueType()))
11535       return false;
11536
11537     // Check that the select condition doesn't reach either load.  If so,
11538     // folding this will induce a cycle into the DAG.  If not, this is safe to
11539     // xform, so create a select of the addresses.
11540     SDValue Addr;
11541     if (TheSelect->getOpcode() == ISD::SELECT) {
11542       SDNode *CondNode = TheSelect->getOperand(0).getNode();
11543       if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
11544           (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
11545         return false;
11546       // The loads must not depend on one another.
11547       if (LLD->isPredecessorOf(RLD) ||
11548           RLD->isPredecessorOf(LLD))
11549         return false;
11550       Addr = DAG.getSelect(SDLoc(TheSelect),
11551                            LLD->getBasePtr().getValueType(),
11552                            TheSelect->getOperand(0), LLD->getBasePtr(),
11553                            RLD->getBasePtr());
11554     } else {  // Otherwise SELECT_CC
11555       SDNode *CondLHS = TheSelect->getOperand(0).getNode();
11556       SDNode *CondRHS = TheSelect->getOperand(1).getNode();
11557
11558       if ((LLD->hasAnyUseOfValue(1) &&
11559            (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
11560           (RLD->hasAnyUseOfValue(1) &&
11561            (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
11562         return false;
11563
11564       Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
11565                          LLD->getBasePtr().getValueType(),
11566                          TheSelect->getOperand(0),
11567                          TheSelect->getOperand(1),
11568                          LLD->getBasePtr(), RLD->getBasePtr(),
11569                          TheSelect->getOperand(4));
11570     }
11571
11572     SDValue Load;
11573     // It is safe to replace the two loads if they have different alignments,
11574     // but the new load must be the minimum (most restrictive) alignment of the
11575     // inputs.
11576     bool isInvariant = LLD->isInvariant() & RLD->isInvariant();
11577     unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment());
11578     if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
11579       Load = DAG.getLoad(TheSelect->getValueType(0),
11580                          SDLoc(TheSelect),
11581                          // FIXME: Discards pointer and AA info.
11582                          LLD->getChain(), Addr, MachinePointerInfo(),
11583                          LLD->isVolatile(), LLD->isNonTemporal(),
11584                          isInvariant, Alignment);
11585     } else {
11586       Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
11587                             RLD->getExtensionType() : LLD->getExtensionType(),
11588                             SDLoc(TheSelect),
11589                             TheSelect->getValueType(0),
11590                             // FIXME: Discards pointer and AA info.
11591                             LLD->getChain(), Addr, MachinePointerInfo(),
11592                             LLD->getMemoryVT(), LLD->isVolatile(),
11593                             LLD->isNonTemporal(), isInvariant, Alignment);
11594     }
11595
11596     // Users of the select now use the result of the load.
11597     CombineTo(TheSelect, Load);
11598
11599     // Users of the old loads now use the new load's chain.  We know the
11600     // old-load value is dead now.
11601     CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
11602     CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
11603     return true;
11604   }
11605
11606   return false;
11607 }
11608
11609 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3
11610 /// where 'cond' is the comparison specified by CC.
11611 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
11612                                       SDValue N2, SDValue N3,
11613                                       ISD::CondCode CC, bool NotExtCompare) {
11614   // (x ? y : y) -> y.
11615   if (N2 == N3) return N2;
11616
11617   EVT VT = N2.getValueType();
11618   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
11619   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
11620   ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
11621
11622   // Determine if the condition we're dealing with is constant
11623   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
11624                               N0, N1, CC, DL, false);
11625   if (SCC.getNode()) AddToWorklist(SCC.getNode());
11626   ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
11627
11628   // fold select_cc true, x, y -> x
11629   if (SCCC && !SCCC->isNullValue())
11630     return N2;
11631   // fold select_cc false, x, y -> y
11632   if (SCCC && SCCC->isNullValue())
11633     return N3;
11634
11635   // Check to see if we can simplify the select into an fabs node
11636   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
11637     // Allow either -0.0 or 0.0
11638     if (CFP->getValueAPF().isZero()) {
11639       // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
11640       if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
11641           N0 == N2 && N3.getOpcode() == ISD::FNEG &&
11642           N2 == N3.getOperand(0))
11643         return DAG.getNode(ISD::FABS, DL, VT, N0);
11644
11645       // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
11646       if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
11647           N0 == N3 && N2.getOpcode() == ISD::FNEG &&
11648           N2.getOperand(0) == N3)
11649         return DAG.getNode(ISD::FABS, DL, VT, N3);
11650     }
11651   }
11652
11653   // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
11654   // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
11655   // in it.  This is a win when the constant is not otherwise available because
11656   // it replaces two constant pool loads with one.  We only do this if the FP
11657   // type is known to be legal, because if it isn't, then we are before legalize
11658   // types an we want the other legalization to happen first (e.g. to avoid
11659   // messing with soft float) and if the ConstantFP is not legal, because if
11660   // it is legal, we may not need to store the FP constant in a constant pool.
11661   if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
11662     if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
11663       if (TLI.isTypeLegal(N2.getValueType()) &&
11664           (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
11665                TargetLowering::Legal &&
11666            !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
11667            !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
11668           // If both constants have multiple uses, then we won't need to do an
11669           // extra load, they are likely around in registers for other users.
11670           (TV->hasOneUse() || FV->hasOneUse())) {
11671         Constant *Elts[] = {
11672           const_cast<ConstantFP*>(FV->getConstantFPValue()),
11673           const_cast<ConstantFP*>(TV->getConstantFPValue())
11674         };
11675         Type *FPTy = Elts[0]->getType();
11676         const DataLayout &TD = *TLI.getDataLayout();
11677
11678         // Create a ConstantArray of the two constants.
11679         Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
11680         SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
11681                                             TD.getPrefTypeAlignment(FPTy));
11682         unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
11683
11684         // Get the offsets to the 0 and 1 element of the array so that we can
11685         // select between them.
11686         SDValue Zero = DAG.getIntPtrConstant(0);
11687         unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
11688         SDValue One = DAG.getIntPtrConstant(EltSize);
11689
11690         SDValue Cond = DAG.getSetCC(DL,
11691                                     getSetCCResultType(N0.getValueType()),
11692                                     N0, N1, CC);
11693         AddToWorklist(Cond.getNode());
11694         SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
11695                                           Cond, One, Zero);
11696         AddToWorklist(CstOffset.getNode());
11697         CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
11698                             CstOffset);
11699         AddToWorklist(CPIdx.getNode());
11700         return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
11701                            MachinePointerInfo::getConstantPool(), false,
11702                            false, false, Alignment);
11703
11704       }
11705     }
11706
11707   // Check to see if we can perform the "gzip trick", transforming
11708   // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
11709   if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
11710       (N1C->isNullValue() ||                         // (a < 0) ? b : 0
11711        (N1C->getAPIntValue() == 1 && N0 == N2))) {   // (a < 1) ? a : 0
11712     EVT XType = N0.getValueType();
11713     EVT AType = N2.getValueType();
11714     if (XType.bitsGE(AType)) {
11715       // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
11716       // single-bit constant.
11717       if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
11718         unsigned ShCtV = N2C->getAPIntValue().logBase2();
11719         ShCtV = XType.getSizeInBits()-ShCtV-1;
11720         SDValue ShCt = DAG.getConstant(ShCtV,
11721                                        getShiftAmountTy(N0.getValueType()));
11722         SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
11723                                     XType, N0, ShCt);
11724         AddToWorklist(Shift.getNode());
11725
11726         if (XType.bitsGT(AType)) {
11727           Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
11728           AddToWorklist(Shift.getNode());
11729         }
11730
11731         return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
11732       }
11733
11734       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
11735                                   XType, N0,
11736                                   DAG.getConstant(XType.getSizeInBits()-1,
11737                                          getShiftAmountTy(N0.getValueType())));
11738       AddToWorklist(Shift.getNode());
11739
11740       if (XType.bitsGT(AType)) {
11741         Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
11742         AddToWorklist(Shift.getNode());
11743       }
11744
11745       return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
11746     }
11747   }
11748
11749   // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
11750   // where y is has a single bit set.
11751   // A plaintext description would be, we can turn the SELECT_CC into an AND
11752   // when the condition can be materialized as an all-ones register.  Any
11753   // single bit-test can be materialized as an all-ones register with
11754   // shift-left and shift-right-arith.
11755   if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
11756       N0->getValueType(0) == VT &&
11757       N1C && N1C->isNullValue() &&
11758       N2C && N2C->isNullValue()) {
11759     SDValue AndLHS = N0->getOperand(0);
11760     ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
11761     if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
11762       // Shift the tested bit over the sign bit.
11763       APInt AndMask = ConstAndRHS->getAPIntValue();
11764       SDValue ShlAmt =
11765         DAG.getConstant(AndMask.countLeadingZeros(),
11766                         getShiftAmountTy(AndLHS.getValueType()));
11767       SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
11768
11769       // Now arithmetic right shift it all the way over, so the result is either
11770       // all-ones, or zero.
11771       SDValue ShrAmt =
11772         DAG.getConstant(AndMask.getBitWidth()-1,
11773                         getShiftAmountTy(Shl.getValueType()));
11774       SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
11775
11776       return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
11777     }
11778   }
11779
11780   // fold select C, 16, 0 -> shl C, 4
11781   if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
11782       TLI.getBooleanContents(N0.getValueType()) ==
11783           TargetLowering::ZeroOrOneBooleanContent) {
11784
11785     // If the caller doesn't want us to simplify this into a zext of a compare,
11786     // don't do it.
11787     if (NotExtCompare && N2C->getAPIntValue() == 1)
11788       return SDValue();
11789
11790     // Get a SetCC of the condition
11791     // NOTE: Don't create a SETCC if it's not legal on this target.
11792     if (!LegalOperations ||
11793         TLI.isOperationLegal(ISD::SETCC,
11794           LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
11795       SDValue Temp, SCC;
11796       // cast from setcc result type to select result type
11797       if (LegalTypes) {
11798         SCC  = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
11799                             N0, N1, CC);
11800         if (N2.getValueType().bitsLT(SCC.getValueType()))
11801           Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
11802                                         N2.getValueType());
11803         else
11804           Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
11805                              N2.getValueType(), SCC);
11806       } else {
11807         SCC  = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
11808         Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
11809                            N2.getValueType(), SCC);
11810       }
11811
11812       AddToWorklist(SCC.getNode());
11813       AddToWorklist(Temp.getNode());
11814
11815       if (N2C->getAPIntValue() == 1)
11816         return Temp;
11817
11818       // shl setcc result by log2 n2c
11819       return DAG.getNode(
11820           ISD::SHL, DL, N2.getValueType(), Temp,
11821           DAG.getConstant(N2C->getAPIntValue().logBase2(),
11822                           getShiftAmountTy(Temp.getValueType())));
11823     }
11824   }
11825
11826   // Check to see if this is the equivalent of setcc
11827   // FIXME: Turn all of these into setcc if setcc if setcc is legal
11828   // otherwise, go ahead with the folds.
11829   if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
11830     EVT XType = N0.getValueType();
11831     if (!LegalOperations ||
11832         TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
11833       SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
11834       if (Res.getValueType() != VT)
11835         Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
11836       return Res;
11837     }
11838
11839     // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
11840     if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
11841         (!LegalOperations ||
11842          TLI.isOperationLegal(ISD::CTLZ, XType))) {
11843       SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
11844       return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
11845                          DAG.getConstant(Log2_32(XType.getSizeInBits()),
11846                                        getShiftAmountTy(Ctlz.getValueType())));
11847     }
11848     // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
11849     if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
11850       SDValue NegN0 = DAG.getNode(ISD::SUB, SDLoc(N0),
11851                                   XType, DAG.getConstant(0, XType), N0);
11852       SDValue NotN0 = DAG.getNOT(SDLoc(N0), N0, XType);
11853       return DAG.getNode(ISD::SRL, DL, XType,
11854                          DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
11855                          DAG.getConstant(XType.getSizeInBits()-1,
11856                                          getShiftAmountTy(XType)));
11857     }
11858     // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
11859     if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
11860       SDValue Sign = DAG.getNode(ISD::SRL, SDLoc(N0), XType, N0,
11861                                  DAG.getConstant(XType.getSizeInBits()-1,
11862                                          getShiftAmountTy(N0.getValueType())));
11863       return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
11864     }
11865   }
11866
11867   // Check to see if this is an integer abs.
11868   // select_cc setg[te] X,  0,  X, -X ->
11869   // select_cc setgt    X, -1,  X, -X ->
11870   // select_cc setl[te] X,  0, -X,  X ->
11871   // select_cc setlt    X,  1, -X,  X ->
11872   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
11873   if (N1C) {
11874     ConstantSDNode *SubC = nullptr;
11875     if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
11876          (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
11877         N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
11878       SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
11879     else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
11880               (N1C->isOne() && CC == ISD::SETLT)) &&
11881              N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
11882       SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
11883
11884     EVT XType = N0.getValueType();
11885     if (SubC && SubC->isNullValue() && XType.isInteger()) {
11886       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), XType,
11887                                   N0,
11888                                   DAG.getConstant(XType.getSizeInBits()-1,
11889                                          getShiftAmountTy(N0.getValueType())));
11890       SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0),
11891                                 XType, N0, Shift);
11892       AddToWorklist(Shift.getNode());
11893       AddToWorklist(Add.getNode());
11894       return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
11895     }
11896   }
11897
11898   return SDValue();
11899 }
11900
11901 /// This is a stub for TargetLowering::SimplifySetCC.
11902 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
11903                                    SDValue N1, ISD::CondCode Cond,
11904                                    SDLoc DL, bool foldBooleans) {
11905   TargetLowering::DAGCombinerInfo
11906     DagCombineInfo(DAG, Level, false, this);
11907   return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
11908 }
11909
11910 /// Given an ISD::SDIV node expressing a divide by constant, return
11911 /// a DAG expression to select that will generate the same value by multiplying
11912 /// by a magic number.
11913 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
11914 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
11915   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
11916   if (!C)
11917     return SDValue();
11918
11919   // Avoid division by zero.
11920   if (!C->getAPIntValue())
11921     return SDValue();
11922
11923   std::vector<SDNode*> Built;
11924   SDValue S =
11925       TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
11926
11927   for (SDNode *N : Built)
11928     AddToWorklist(N);
11929   return S;
11930 }
11931
11932 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a
11933 /// DAG expression that will generate the same value by right shifting.
11934 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
11935   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
11936   if (!C)
11937     return SDValue();
11938
11939   // Avoid division by zero.
11940   if (!C->getAPIntValue())
11941     return SDValue();
11942
11943   std::vector<SDNode *> Built;
11944   SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
11945
11946   for (SDNode *N : Built)
11947     AddToWorklist(N);
11948   return S;
11949 }
11950
11951 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG
11952 /// expression that will generate the same value by multiplying by a magic
11953 /// number.
11954 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
11955 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
11956   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
11957   if (!C)
11958     return SDValue();
11959
11960   // Avoid division by zero.
11961   if (!C->getAPIntValue())
11962     return SDValue();
11963
11964   std::vector<SDNode*> Built;
11965   SDValue S =
11966       TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
11967
11968   for (SDNode *N : Built)
11969     AddToWorklist(N);
11970   return S;
11971 }
11972
11973 SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op) {
11974   if (Level >= AfterLegalizeDAG)
11975     return SDValue();
11976
11977   // Expose the DAG combiner to the target combiner implementations.
11978   TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
11979
11980   unsigned Iterations = 0;
11981   if (SDValue Est = TLI.getRecipEstimate(Op, DCI, Iterations)) {
11982     if (Iterations) {
11983       // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
11984       // For the reciprocal, we need to find the zero of the function:
11985       //   F(X) = A X - 1 [which has a zero at X = 1/A]
11986       //     =>
11987       //   X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
11988       //     does not require additional intermediate precision]
11989       EVT VT = Op.getValueType();
11990       SDLoc DL(Op);
11991       SDValue FPOne = DAG.getConstantFP(1.0, VT);
11992
11993       AddToWorklist(Est.getNode());
11994
11995       // Newton iterations: Est = Est + Est (1 - Arg * Est)
11996       for (unsigned i = 0; i < Iterations; ++i) {
11997         SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est);
11998         AddToWorklist(NewEst.getNode());
11999
12000         NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst);
12001         AddToWorklist(NewEst.getNode());
12002
12003         NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst);
12004         AddToWorklist(NewEst.getNode());
12005
12006         Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst);
12007         AddToWorklist(Est.getNode());
12008       }
12009     }
12010     return Est;
12011   }
12012
12013   return SDValue();
12014 }
12015
12016 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
12017 /// For the reciprocal sqrt, we need to find the zero of the function:
12018 ///   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
12019 ///     =>
12020 ///   X_{i+1} = X_i (1.5 - A X_i^2 / 2)
12021 /// As a result, we precompute A/2 prior to the iteration loop.
12022 SDValue DAGCombiner::BuildRsqrtNROneConst(SDValue Arg, SDValue Est,
12023                                           unsigned Iterations) {
12024   EVT VT = Arg.getValueType();
12025   SDLoc DL(Arg);
12026   SDValue ThreeHalves = DAG.getConstantFP(1.5, VT);
12027
12028   // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that
12029   // this entire sequence requires only one FP constant.
12030   SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg);
12031   AddToWorklist(HalfArg.getNode());
12032
12033   HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg);
12034   AddToWorklist(HalfArg.getNode());
12035
12036   // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
12037   for (unsigned i = 0; i < Iterations; ++i) {
12038     SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est);
12039     AddToWorklist(NewEst.getNode());
12040
12041     NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst);
12042     AddToWorklist(NewEst.getNode());
12043
12044     NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst);
12045     AddToWorklist(NewEst.getNode());
12046
12047     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst);
12048     AddToWorklist(Est.getNode());
12049   }
12050   return Est;
12051 }
12052
12053 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
12054 /// For the reciprocal sqrt, we need to find the zero of the function:
12055 ///   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
12056 ///     =>
12057 ///   X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0))
12058 SDValue DAGCombiner::BuildRsqrtNRTwoConst(SDValue Arg, SDValue Est,
12059                                           unsigned Iterations) {
12060   EVT VT = Arg.getValueType();
12061   SDLoc DL(Arg);
12062   SDValue MinusThree = DAG.getConstantFP(-3.0, VT);
12063   SDValue MinusHalf = DAG.getConstantFP(-0.5, VT);
12064
12065   // Newton iterations: Est = -0.5 * Est * (-3.0 + Arg * Est * Est)
12066   for (unsigned i = 0; i < Iterations; ++i) {
12067     SDValue HalfEst = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf);
12068     AddToWorklist(HalfEst.getNode());
12069
12070     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Est);
12071     AddToWorklist(Est.getNode());
12072
12073     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg);
12074     AddToWorklist(Est.getNode());
12075
12076     Est = DAG.getNode(ISD::FADD, DL, VT, Est, MinusThree);
12077     AddToWorklist(Est.getNode());
12078
12079     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, HalfEst);
12080     AddToWorklist(Est.getNode());
12081   }
12082   return Est;
12083 }
12084
12085 SDValue DAGCombiner::BuildRsqrtEstimate(SDValue Op) {
12086   if (Level >= AfterLegalizeDAG)
12087     return SDValue();
12088
12089   // Expose the DAG combiner to the target combiner implementations.
12090   TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
12091   unsigned Iterations = 0;
12092   bool UseOneConstNR = false;
12093   if (SDValue Est = TLI.getRsqrtEstimate(Op, DCI, Iterations, UseOneConstNR)) {
12094     AddToWorklist(Est.getNode());
12095     if (Iterations) {
12096       Est = UseOneConstNR ?
12097         BuildRsqrtNROneConst(Op, Est, Iterations) :
12098         BuildRsqrtNRTwoConst(Op, Est, Iterations);
12099     }
12100     return Est;
12101   }
12102
12103   return SDValue();
12104 }
12105
12106 /// Return true if base is a frame index, which is known not to alias with
12107 /// anything but itself.  Provides base object and offset as results.
12108 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
12109                            const GlobalValue *&GV, const void *&CV) {
12110   // Assume it is a primitive operation.
12111   Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
12112
12113   // If it's an adding a simple constant then integrate the offset.
12114   if (Base.getOpcode() == ISD::ADD) {
12115     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
12116       Base = Base.getOperand(0);
12117       Offset += C->getZExtValue();
12118     }
12119   }
12120
12121   // Return the underlying GlobalValue, and update the Offset.  Return false
12122   // for GlobalAddressSDNode since the same GlobalAddress may be represented
12123   // by multiple nodes with different offsets.
12124   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
12125     GV = G->getGlobal();
12126     Offset += G->getOffset();
12127     return false;
12128   }
12129
12130   // Return the underlying Constant value, and update the Offset.  Return false
12131   // for ConstantSDNodes since the same constant pool entry may be represented
12132   // by multiple nodes with different offsets.
12133   if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
12134     CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
12135                                          : (const void *)C->getConstVal();
12136     Offset += C->getOffset();
12137     return false;
12138   }
12139   // If it's any of the following then it can't alias with anything but itself.
12140   return isa<FrameIndexSDNode>(Base);
12141 }
12142
12143 /// Return true if there is any possibility that the two addresses overlap.
12144 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
12145   // If they are the same then they must be aliases.
12146   if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
12147
12148   // If they are both volatile then they cannot be reordered.
12149   if (Op0->isVolatile() && Op1->isVolatile()) return true;
12150
12151   // Gather base node and offset information.
12152   SDValue Base1, Base2;
12153   int64_t Offset1, Offset2;
12154   const GlobalValue *GV1, *GV2;
12155   const void *CV1, *CV2;
12156   bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
12157                                       Base1, Offset1, GV1, CV1);
12158   bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
12159                                       Base2, Offset2, GV2, CV2);
12160
12161   // If they have a same base address then check to see if they overlap.
12162   if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
12163     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
12164              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
12165
12166   // It is possible for different frame indices to alias each other, mostly
12167   // when tail call optimization reuses return address slots for arguments.
12168   // To catch this case, look up the actual index of frame indices to compute
12169   // the real alias relationship.
12170   if (isFrameIndex1 && isFrameIndex2) {
12171     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12172     Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
12173     Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
12174     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
12175              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
12176   }
12177
12178   // Otherwise, if we know what the bases are, and they aren't identical, then
12179   // we know they cannot alias.
12180   if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
12181     return false;
12182
12183   // If we know required SrcValue1 and SrcValue2 have relatively large alignment
12184   // compared to the size and offset of the access, we may be able to prove they
12185   // do not alias.  This check is conservative for now to catch cases created by
12186   // splitting vector types.
12187   if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
12188       (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
12189       (Op0->getMemoryVT().getSizeInBits() >> 3 ==
12190        Op1->getMemoryVT().getSizeInBits() >> 3) &&
12191       (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) {
12192     int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
12193     int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
12194
12195     // There is no overlap between these relatively aligned accesses of similar
12196     // size, return no alias.
12197     if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
12198         (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
12199       return false;
12200   }
12201
12202   bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0
12203                    ? CombinerGlobalAA
12204                    : DAG.getSubtarget().useAA();
12205 #ifndef NDEBUG
12206   if (CombinerAAOnlyFunc.getNumOccurrences() &&
12207       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
12208     UseAA = false;
12209 #endif
12210   if (UseAA &&
12211       Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
12212     // Use alias analysis information.
12213     int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
12214                                  Op1->getSrcValueOffset());
12215     int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
12216         Op0->getSrcValueOffset() - MinOffset;
12217     int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
12218         Op1->getSrcValueOffset() - MinOffset;
12219     AliasAnalysis::AliasResult AAResult =
12220         AA.alias(AliasAnalysis::Location(Op0->getMemOperand()->getValue(),
12221                                          Overlap1,
12222                                          UseTBAA ? Op0->getAAInfo() : AAMDNodes()),
12223                  AliasAnalysis::Location(Op1->getMemOperand()->getValue(),
12224                                          Overlap2,
12225                                          UseTBAA ? Op1->getAAInfo() : AAMDNodes()));
12226     if (AAResult == AliasAnalysis::NoAlias)
12227       return false;
12228   }
12229
12230   // Otherwise we have to assume they alias.
12231   return true;
12232 }
12233
12234 /// Walk up chain skipping non-aliasing memory nodes,
12235 /// looking for aliasing nodes and adding them to the Aliases vector.
12236 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
12237                                    SmallVectorImpl<SDValue> &Aliases) {
12238   SmallVector<SDValue, 8> Chains;     // List of chains to visit.
12239   SmallPtrSet<SDNode *, 16> Visited;  // Visited node set.
12240
12241   // Get alias information for node.
12242   bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
12243
12244   // Starting off.
12245   Chains.push_back(OriginalChain);
12246   unsigned Depth = 0;
12247
12248   // Look at each chain and determine if it is an alias.  If so, add it to the
12249   // aliases list.  If not, then continue up the chain looking for the next
12250   // candidate.
12251   while (!Chains.empty()) {
12252     SDValue Chain = Chains.back();
12253     Chains.pop_back();
12254
12255     // For TokenFactor nodes, look at each operand and only continue up the
12256     // chain until we find two aliases.  If we've seen two aliases, assume we'll
12257     // find more and revert to original chain since the xform is unlikely to be
12258     // profitable.
12259     //
12260     // FIXME: The depth check could be made to return the last non-aliasing
12261     // chain we found before we hit a tokenfactor rather than the original
12262     // chain.
12263     if (Depth > 6 || Aliases.size() == 2) {
12264       Aliases.clear();
12265       Aliases.push_back(OriginalChain);
12266       return;
12267     }
12268
12269     // Don't bother if we've been before.
12270     if (!Visited.insert(Chain.getNode()).second)
12271       continue;
12272
12273     switch (Chain.getOpcode()) {
12274     case ISD::EntryToken:
12275       // Entry token is ideal chain operand, but handled in FindBetterChain.
12276       break;
12277
12278     case ISD::LOAD:
12279     case ISD::STORE: {
12280       // Get alias information for Chain.
12281       bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
12282           !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
12283
12284       // If chain is alias then stop here.
12285       if (!(IsLoad && IsOpLoad) &&
12286           isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
12287         Aliases.push_back(Chain);
12288       } else {
12289         // Look further up the chain.
12290         Chains.push_back(Chain.getOperand(0));
12291         ++Depth;
12292       }
12293       break;
12294     }
12295
12296     case ISD::TokenFactor:
12297       // We have to check each of the operands of the token factor for "small"
12298       // token factors, so we queue them up.  Adding the operands to the queue
12299       // (stack) in reverse order maintains the original order and increases the
12300       // likelihood that getNode will find a matching token factor (CSE.)
12301       if (Chain.getNumOperands() > 16) {
12302         Aliases.push_back(Chain);
12303         break;
12304       }
12305       for (unsigned n = Chain.getNumOperands(); n;)
12306         Chains.push_back(Chain.getOperand(--n));
12307       ++Depth;
12308       break;
12309
12310     default:
12311       // For all other instructions we will just have to take what we can get.
12312       Aliases.push_back(Chain);
12313       break;
12314     }
12315   }
12316
12317   // We need to be careful here to also search for aliases through the
12318   // value operand of a store, etc. Consider the following situation:
12319   //   Token1 = ...
12320   //   L1 = load Token1, %52
12321   //   S1 = store Token1, L1, %51
12322   //   L2 = load Token1, %52+8
12323   //   S2 = store Token1, L2, %51+8
12324   //   Token2 = Token(S1, S2)
12325   //   L3 = load Token2, %53
12326   //   S3 = store Token2, L3, %52
12327   //   L4 = load Token2, %53+8
12328   //   S4 = store Token2, L4, %52+8
12329   // If we search for aliases of S3 (which loads address %52), and we look
12330   // only through the chain, then we'll miss the trivial dependence on L1
12331   // (which also loads from %52). We then might change all loads and
12332   // stores to use Token1 as their chain operand, which could result in
12333   // copying %53 into %52 before copying %52 into %51 (which should
12334   // happen first).
12335   //
12336   // The problem is, however, that searching for such data dependencies
12337   // can become expensive, and the cost is not directly related to the
12338   // chain depth. Instead, we'll rule out such configurations here by
12339   // insisting that we've visited all chain users (except for users
12340   // of the original chain, which is not necessary). When doing this,
12341   // we need to look through nodes we don't care about (otherwise, things
12342   // like register copies will interfere with trivial cases).
12343
12344   SmallVector<const SDNode *, 16> Worklist;
12345   for (const SDNode *N : Visited)
12346     if (N != OriginalChain.getNode())
12347       Worklist.push_back(N);
12348
12349   while (!Worklist.empty()) {
12350     const SDNode *M = Worklist.pop_back_val();
12351
12352     // We have already visited M, and want to make sure we've visited any uses
12353     // of M that we care about. For uses that we've not visisted, and don't
12354     // care about, queue them to the worklist.
12355
12356     for (SDNode::use_iterator UI = M->use_begin(),
12357          UIE = M->use_end(); UI != UIE; ++UI)
12358       if (UI.getUse().getValueType() == MVT::Other &&
12359           Visited.insert(*UI).second) {
12360         if (isa<MemIntrinsicSDNode>(*UI) || isa<MemSDNode>(*UI)) {
12361           // We've not visited this use, and we care about it (it could have an
12362           // ordering dependency with the original node).
12363           Aliases.clear();
12364           Aliases.push_back(OriginalChain);
12365           return;
12366         }
12367
12368         // We've not visited this use, but we don't care about it. Mark it as
12369         // visited and enqueue it to the worklist.
12370         Worklist.push_back(*UI);
12371       }
12372   }
12373 }
12374
12375 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain
12376 /// (aliasing node.)
12377 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
12378   SmallVector<SDValue, 8> Aliases;  // Ops for replacing token factor.
12379
12380   // Accumulate all the aliases to this node.
12381   GatherAllAliases(N, OldChain, Aliases);
12382
12383   // If no operands then chain to entry token.
12384   if (Aliases.size() == 0)
12385     return DAG.getEntryNode();
12386
12387   // If a single operand then chain to it.  We don't need to revisit it.
12388   if (Aliases.size() == 1)
12389     return Aliases[0];
12390
12391   // Construct a custom tailored token factor.
12392   return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
12393 }
12394
12395 /// This is the entry point for the file.
12396 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
12397                            CodeGenOpt::Level OptLevel) {
12398   /// This is the main entry point to this class.
12399   DAGCombiner(*this, AA, OptLevel).Run(Level);
12400 }