Revert "[x86] Fold extract_vector_elt of a load into the Load's address computation."
[oota-llvm.git] / lib / CodeGen / SelectionDAG / DAGCombiner.cpp
1 //===-- DAGCombiner.cpp - Implement a DAG node combiner -------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This pass combines dag nodes to form fewer, simpler DAG nodes.  It can be run
11 // both before and after the DAG is legalized.
12 //
13 // This pass is not a substitute for the LLVM IR instcombine pass. This pass is
14 // primarily intended to handle simplification opportunities that are implicit
15 // in the LLVM IR and exposed by the various codegen lowering phases.
16 //
17 //===----------------------------------------------------------------------===//
18
19 #include "llvm/CodeGen/SelectionDAG.h"
20 #include "llvm/ADT/SmallPtrSet.h"
21 #include "llvm/ADT/Statistic.h"
22 #include "llvm/Analysis/AliasAnalysis.h"
23 #include "llvm/CodeGen/MachineFrameInfo.h"
24 #include "llvm/CodeGen/MachineFunction.h"
25 #include "llvm/IR/DataLayout.h"
26 #include "llvm/IR/DerivedTypes.h"
27 #include "llvm/IR/Function.h"
28 #include "llvm/IR/LLVMContext.h"
29 #include "llvm/Support/CommandLine.h"
30 #include "llvm/Support/Debug.h"
31 #include "llvm/Support/ErrorHandling.h"
32 #include "llvm/Support/MathExtras.h"
33 #include "llvm/Support/raw_ostream.h"
34 #include "llvm/Target/TargetLowering.h"
35 #include "llvm/Target/TargetMachine.h"
36 #include "llvm/Target/TargetOptions.h"
37 #include "llvm/Target/TargetRegisterInfo.h"
38 #include "llvm/Target/TargetSubtargetInfo.h"
39 #include <algorithm>
40 using namespace llvm;
41
42 #define DEBUG_TYPE "dagcombine"
43
44 STATISTIC(NodesCombined   , "Number of dag nodes combined");
45 STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created");
46 STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created");
47 STATISTIC(OpsNarrowed     , "Number of load/op/store narrowed");
48 STATISTIC(LdStFP2Int      , "Number of fp load/store pairs transformed to int");
49 STATISTIC(SlicedLoads, "Number of load sliced");
50
51 namespace {
52   static cl::opt<bool>
53     CombinerAA("combiner-alias-analysis", cl::Hidden,
54                cl::desc("Enable DAG combiner alias-analysis heuristics"));
55
56   static cl::opt<bool>
57     CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
58                cl::desc("Enable DAG combiner's use of IR alias analysis"));
59
60   static cl::opt<bool>
61     UseTBAA("combiner-use-tbaa", cl::Hidden, cl::init(true),
62                cl::desc("Enable DAG combiner's use of TBAA"));
63
64 #ifndef NDEBUG
65   static cl::opt<std::string>
66     CombinerAAOnlyFunc("combiner-aa-only-func", cl::Hidden,
67                cl::desc("Only use DAG-combiner alias analysis in this"
68                         " function"));
69 #endif
70
71   /// Hidden option to stress test load slicing, i.e., when this option
72   /// is enabled, load slicing bypasses most of its profitability guards.
73   static cl::opt<bool>
74   StressLoadSlicing("combiner-stress-load-slicing", cl::Hidden,
75                     cl::desc("Bypass the profitability model of load "
76                              "slicing"),
77                     cl::init(false));
78
79 //------------------------------ DAGCombiner ---------------------------------//
80
81   class DAGCombiner {
82     SelectionDAG &DAG;
83     const TargetLowering &TLI;
84     CombineLevel Level;
85     CodeGenOpt::Level OptLevel;
86     bool LegalOperations;
87     bool LegalTypes;
88     bool ForCodeSize;
89
90     // Worklist of all of the nodes that need to be simplified.
91     //
92     // This has the semantics that when adding to the worklist,
93     // the item added must be next to be processed. It should
94     // also only appear once. The naive approach to this takes
95     // linear time.
96     //
97     // To reduce the insert/remove time to logarithmic, we use
98     // a set and a vector to maintain our worklist.
99     //
100     // The set contains the items on the worklist, but does not
101     // maintain the order they should be visited.
102     //
103     // The vector maintains the order nodes should be visited, but may
104     // contain duplicate or removed nodes. When choosing a node to
105     // visit, we pop off the order stack until we find an item that is
106     // also in the contents set. All operations are O(log N).
107     SmallPtrSet<SDNode*, 64> WorkListContents;
108     SmallVector<SDNode*, 64> WorkListOrder;
109
110     // AA - Used for DAG load/store alias analysis.
111     AliasAnalysis &AA;
112
113     /// AddUsersToWorkList - When an instruction is simplified, add all users of
114     /// the instruction to the work lists because they might get more simplified
115     /// now.
116     ///
117     void AddUsersToWorkList(SDNode *N) {
118       for (SDNode *Node : N->uses())
119         AddToWorkList(Node);
120     }
121
122     /// visit - call the node-specific routine that knows how to fold each
123     /// particular type of node.
124     SDValue visit(SDNode *N);
125
126   public:
127     /// AddToWorkList - Add to the work list making sure its instance is at the
128     /// back (next to be processed.)
129     void AddToWorkList(SDNode *N) {
130       WorkListContents.insert(N);
131       WorkListOrder.push_back(N);
132     }
133
134     /// removeFromWorkList - remove all instances of N from the worklist.
135     ///
136     void removeFromWorkList(SDNode *N) {
137       WorkListContents.erase(N);
138     }
139
140     SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
141                       bool AddTo = true);
142
143     SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
144       return CombineTo(N, &Res, 1, AddTo);
145     }
146
147     SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
148                       bool AddTo = true) {
149       SDValue To[] = { Res0, Res1 };
150       return CombineTo(N, To, 2, AddTo);
151     }
152
153     void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
154
155   private:
156
157     /// SimplifyDemandedBits - Check the specified integer node value to see if
158     /// it can be simplified or if things it uses can be simplified by bit
159     /// propagation.  If so, return true.
160     bool SimplifyDemandedBits(SDValue Op) {
161       unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits();
162       APInt Demanded = APInt::getAllOnesValue(BitWidth);
163       return SimplifyDemandedBits(Op, Demanded);
164     }
165
166     bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded);
167
168     bool CombineToPreIndexedLoadStore(SDNode *N);
169     bool CombineToPostIndexedLoadStore(SDNode *N);
170     bool SliceUpLoad(SDNode *N);
171
172     void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
173     SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
174     SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
175     SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
176     SDValue PromoteIntBinOp(SDValue Op);
177     SDValue PromoteIntShiftOp(SDValue Op);
178     SDValue PromoteExtend(SDValue Op);
179     bool PromoteLoad(SDValue Op);
180
181     void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
182                          SDValue Trunc, SDValue ExtLoad, SDLoc DL,
183                          ISD::NodeType ExtType);
184
185     /// combine - call the node-specific routine that knows how to fold each
186     /// particular type of node. If that doesn't do anything, try the
187     /// target-specific DAG combines.
188     SDValue combine(SDNode *N);
189
190     // Visitation implementation - Implement dag node combining for different
191     // node types.  The semantics are as follows:
192     // Return Value:
193     //   SDValue.getNode() == 0 - No change was made
194     //   SDValue.getNode() == N - N was replaced, is dead and has been handled.
195     //   otherwise              - N should be replaced by the returned Operand.
196     //
197     SDValue visitTokenFactor(SDNode *N);
198     SDValue visitMERGE_VALUES(SDNode *N);
199     SDValue visitADD(SDNode *N);
200     SDValue visitSUB(SDNode *N);
201     SDValue visitADDC(SDNode *N);
202     SDValue visitSUBC(SDNode *N);
203     SDValue visitADDE(SDNode *N);
204     SDValue visitSUBE(SDNode *N);
205     SDValue visitMUL(SDNode *N);
206     SDValue visitSDIV(SDNode *N);
207     SDValue visitUDIV(SDNode *N);
208     SDValue visitSREM(SDNode *N);
209     SDValue visitUREM(SDNode *N);
210     SDValue visitMULHU(SDNode *N);
211     SDValue visitMULHS(SDNode *N);
212     SDValue visitSMUL_LOHI(SDNode *N);
213     SDValue visitUMUL_LOHI(SDNode *N);
214     SDValue visitSMULO(SDNode *N);
215     SDValue visitUMULO(SDNode *N);
216     SDValue visitSDIVREM(SDNode *N);
217     SDValue visitUDIVREM(SDNode *N);
218     SDValue visitAND(SDNode *N);
219     SDValue visitOR(SDNode *N);
220     SDValue visitXOR(SDNode *N);
221     SDValue SimplifyVBinOp(SDNode *N);
222     SDValue SimplifyVUnaryOp(SDNode *N);
223     SDValue visitSHL(SDNode *N);
224     SDValue visitSRA(SDNode *N);
225     SDValue visitSRL(SDNode *N);
226     SDValue visitRotate(SDNode *N);
227     SDValue visitCTLZ(SDNode *N);
228     SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
229     SDValue visitCTTZ(SDNode *N);
230     SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
231     SDValue visitCTPOP(SDNode *N);
232     SDValue visitSELECT(SDNode *N);
233     SDValue visitVSELECT(SDNode *N);
234     SDValue visitSELECT_CC(SDNode *N);
235     SDValue visitSETCC(SDNode *N);
236     SDValue visitSIGN_EXTEND(SDNode *N);
237     SDValue visitZERO_EXTEND(SDNode *N);
238     SDValue visitANY_EXTEND(SDNode *N);
239     SDValue visitSIGN_EXTEND_INREG(SDNode *N);
240     SDValue visitTRUNCATE(SDNode *N);
241     SDValue visitBITCAST(SDNode *N);
242     SDValue visitBUILD_PAIR(SDNode *N);
243     SDValue visitFADD(SDNode *N);
244     SDValue visitFSUB(SDNode *N);
245     SDValue visitFMUL(SDNode *N);
246     SDValue visitFMA(SDNode *N);
247     SDValue visitFDIV(SDNode *N);
248     SDValue visitFREM(SDNode *N);
249     SDValue visitFCOPYSIGN(SDNode *N);
250     SDValue visitSINT_TO_FP(SDNode *N);
251     SDValue visitUINT_TO_FP(SDNode *N);
252     SDValue visitFP_TO_SINT(SDNode *N);
253     SDValue visitFP_TO_UINT(SDNode *N);
254     SDValue visitFP_ROUND(SDNode *N);
255     SDValue visitFP_ROUND_INREG(SDNode *N);
256     SDValue visitFP_EXTEND(SDNode *N);
257     SDValue visitFNEG(SDNode *N);
258     SDValue visitFABS(SDNode *N);
259     SDValue visitFCEIL(SDNode *N);
260     SDValue visitFTRUNC(SDNode *N);
261     SDValue visitFFLOOR(SDNode *N);
262     SDValue visitBRCOND(SDNode *N);
263     SDValue visitBR_CC(SDNode *N);
264     SDValue visitLOAD(SDNode *N);
265     SDValue visitSTORE(SDNode *N);
266     SDValue visitINSERT_VECTOR_ELT(SDNode *N);
267     SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
268     SDValue visitBUILD_VECTOR(SDNode *N);
269     SDValue visitCONCAT_VECTORS(SDNode *N);
270     SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
271     SDValue visitVECTOR_SHUFFLE(SDNode *N);
272     SDValue visitINSERT_SUBVECTOR(SDNode *N);
273
274     SDValue XformToShuffleWithZero(SDNode *N);
275     SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS);
276
277     SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt);
278
279     bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
280     SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
281     SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2);
282     SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2,
283                              SDValue N3, ISD::CondCode CC,
284                              bool NotExtCompare = false);
285     SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
286                           SDLoc DL, bool foldBooleans = true);
287
288     bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
289                            SDValue &CC) const;
290     bool isOneUseSetCC(SDValue N) const;
291
292     SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
293                                          unsigned HiOp);
294     SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
295     SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
296     SDValue BuildSDIV(SDNode *N);
297     SDValue BuildUDIV(SDNode *N);
298     SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
299                                bool DemandHighBits = true);
300     SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
301     SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
302                               SDValue InnerPos, SDValue InnerNeg,
303                               unsigned PosOpcode, unsigned NegOpcode,
304                               SDLoc DL);
305     SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL);
306     SDValue ReduceLoadWidth(SDNode *N);
307     SDValue ReduceLoadOpStoreWidth(SDNode *N);
308     SDValue TransformFPLoadStorePair(SDNode *N);
309     SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
310     SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
311
312     SDValue GetDemandedBits(SDValue V, const APInt &Mask);
313
314     /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
315     /// looking for aliasing nodes and adding them to the Aliases vector.
316     void GatherAllAliases(SDNode *N, SDValue OriginalChain,
317                           SmallVectorImpl<SDValue> &Aliases);
318
319     /// isAlias - Return true if there is any possibility that the two addresses
320     /// overlap.
321     bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const;
322
323     /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes,
324     /// looking for a better chain (aliasing node.)
325     SDValue FindBetterChain(SDNode *N, SDValue Chain);
326
327     /// Merge consecutive store operations into a wide store.
328     /// This optimization uses wide integers or vectors when possible.
329     /// \return True if some memory operations were changed.
330     bool MergeConsecutiveStores(StoreSDNode *N);
331
332     /// \brief Try to transform a truncation where C is a constant:
333     ///     (trunc (and X, C)) -> (and (trunc X), (trunc C))
334     ///
335     /// \p N needs to be a truncation and its first operand an AND. Other
336     /// requirements are checked by the function (e.g. that trunc is
337     /// single-use) and if missed an empty SDValue is returned.
338     SDValue distributeTruncateThroughAnd(SDNode *N);
339
340   public:
341     DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
342         : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
343           OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
344       AttributeSet FnAttrs =
345           DAG.getMachineFunction().getFunction()->getAttributes();
346       ForCodeSize =
347           FnAttrs.hasAttribute(AttributeSet::FunctionIndex,
348                                Attribute::OptimizeForSize) ||
349           FnAttrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::MinSize);
350     }
351
352     /// Run - runs the dag combiner on all nodes in the work list
353     void Run(CombineLevel AtLevel);
354
355     SelectionDAG &getDAG() const { return DAG; }
356
357     /// getShiftAmountTy - Returns a type large enough to hold any valid
358     /// shift amount - before type legalization these can be huge.
359     EVT getShiftAmountTy(EVT LHSTy) {
360       assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
361       if (LHSTy.isVector())
362         return LHSTy;
363       return LegalTypes ? TLI.getScalarShiftAmountTy(LHSTy)
364                         : TLI.getPointerTy();
365     }
366
367     /// isTypeLegal - This method returns true if we are running before type
368     /// legalization or if the specified VT is legal.
369     bool isTypeLegal(const EVT &VT) {
370       if (!LegalTypes) return true;
371       return TLI.isTypeLegal(VT);
372     }
373
374     /// getSetCCResultType - Convenience wrapper around
375     /// TargetLowering::getSetCCResultType
376     EVT getSetCCResultType(EVT VT) const {
377       return TLI.getSetCCResultType(*DAG.getContext(), VT);
378     }
379   };
380 }
381
382
383 namespace {
384 /// WorkListRemover - This class is a DAGUpdateListener that removes any deleted
385 /// nodes from the worklist.
386 class WorkListRemover : public SelectionDAG::DAGUpdateListener {
387   DAGCombiner &DC;
388 public:
389   explicit WorkListRemover(DAGCombiner &dc)
390     : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
391
392   void NodeDeleted(SDNode *N, SDNode *E) override {
393     DC.removeFromWorkList(N);
394   }
395 };
396 }
397
398 //===----------------------------------------------------------------------===//
399 //  TargetLowering::DAGCombinerInfo implementation
400 //===----------------------------------------------------------------------===//
401
402 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
403   ((DAGCombiner*)DC)->AddToWorkList(N);
404 }
405
406 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
407   ((DAGCombiner*)DC)->removeFromWorkList(N);
408 }
409
410 SDValue TargetLowering::DAGCombinerInfo::
411 CombineTo(SDNode *N, const std::vector<SDValue> &To, bool AddTo) {
412   return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
413 }
414
415 SDValue TargetLowering::DAGCombinerInfo::
416 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
417   return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
418 }
419
420
421 SDValue TargetLowering::DAGCombinerInfo::
422 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
423   return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
424 }
425
426 void TargetLowering::DAGCombinerInfo::
427 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
428   return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
429 }
430
431 //===----------------------------------------------------------------------===//
432 // Helper Functions
433 //===----------------------------------------------------------------------===//
434
435 /// isNegatibleForFree - Return 1 if we can compute the negated form of the
436 /// specified expression for the same cost as the expression itself, or 2 if we
437 /// can compute the negated form more cheaply than the expression itself.
438 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
439                                const TargetLowering &TLI,
440                                const TargetOptions *Options,
441                                unsigned Depth = 0) {
442   // fneg is removable even if it has multiple uses.
443   if (Op.getOpcode() == ISD::FNEG) return 2;
444
445   // Don't allow anything with multiple uses.
446   if (!Op.hasOneUse()) return 0;
447
448   // Don't recurse exponentially.
449   if (Depth > 6) return 0;
450
451   switch (Op.getOpcode()) {
452   default: return false;
453   case ISD::ConstantFP:
454     // Don't invert constant FP values after legalize.  The negated constant
455     // isn't necessarily legal.
456     return LegalOperations ? 0 : 1;
457   case ISD::FADD:
458     // FIXME: determine better conditions for this xform.
459     if (!Options->UnsafeFPMath) return 0;
460
461     // After operation legalization, it might not be legal to create new FSUBs.
462     if (LegalOperations &&
463         !TLI.isOperationLegalOrCustom(ISD::FSUB,  Op.getValueType()))
464       return 0;
465
466     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
467     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
468                                     Options, Depth + 1))
469       return V;
470     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
471     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
472                               Depth + 1);
473   case ISD::FSUB:
474     // We can't turn -(A-B) into B-A when we honor signed zeros.
475     if (!Options->UnsafeFPMath) return 0;
476
477     // fold (fneg (fsub A, B)) -> (fsub B, A)
478     return 1;
479
480   case ISD::FMUL:
481   case ISD::FDIV:
482     if (Options->HonorSignDependentRoundingFPMath()) return 0;
483
484     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
485     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
486                                     Options, Depth + 1))
487       return V;
488
489     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
490                               Depth + 1);
491
492   case ISD::FP_EXTEND:
493   case ISD::FP_ROUND:
494   case ISD::FSIN:
495     return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
496                               Depth + 1);
497   }
498 }
499
500 /// GetNegatedExpression - If isNegatibleForFree returns true, this function
501 /// returns the newly negated expression.
502 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
503                                     bool LegalOperations, unsigned Depth = 0) {
504   // fneg is removable even if it has multiple uses.
505   if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
506
507   // Don't allow anything with multiple uses.
508   assert(Op.hasOneUse() && "Unknown reuse!");
509
510   assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
511   switch (Op.getOpcode()) {
512   default: llvm_unreachable("Unknown code");
513   case ISD::ConstantFP: {
514     APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
515     V.changeSign();
516     return DAG.getConstantFP(V, Op.getValueType());
517   }
518   case ISD::FADD:
519     // FIXME: determine better conditions for this xform.
520     assert(DAG.getTarget().Options.UnsafeFPMath);
521
522     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
523     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
524                            DAG.getTargetLoweringInfo(),
525                            &DAG.getTarget().Options, Depth+1))
526       return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
527                          GetNegatedExpression(Op.getOperand(0), DAG,
528                                               LegalOperations, Depth+1),
529                          Op.getOperand(1));
530     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
531     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
532                        GetNegatedExpression(Op.getOperand(1), DAG,
533                                             LegalOperations, Depth+1),
534                        Op.getOperand(0));
535   case ISD::FSUB:
536     // We can't turn -(A-B) into B-A when we honor signed zeros.
537     assert(DAG.getTarget().Options.UnsafeFPMath);
538
539     // fold (fneg (fsub 0, B)) -> B
540     if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
541       if (N0CFP->getValueAPF().isZero())
542         return Op.getOperand(1);
543
544     // fold (fneg (fsub A, B)) -> (fsub B, A)
545     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
546                        Op.getOperand(1), Op.getOperand(0));
547
548   case ISD::FMUL:
549   case ISD::FDIV:
550     assert(!DAG.getTarget().Options.HonorSignDependentRoundingFPMath());
551
552     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
553     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
554                            DAG.getTargetLoweringInfo(),
555                            &DAG.getTarget().Options, Depth+1))
556       return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
557                          GetNegatedExpression(Op.getOperand(0), DAG,
558                                               LegalOperations, Depth+1),
559                          Op.getOperand(1));
560
561     // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
562     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
563                        Op.getOperand(0),
564                        GetNegatedExpression(Op.getOperand(1), DAG,
565                                             LegalOperations, Depth+1));
566
567   case ISD::FP_EXTEND:
568   case ISD::FSIN:
569     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
570                        GetNegatedExpression(Op.getOperand(0), DAG,
571                                             LegalOperations, Depth+1));
572   case ISD::FP_ROUND:
573       return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
574                          GetNegatedExpression(Op.getOperand(0), DAG,
575                                               LegalOperations, Depth+1),
576                          Op.getOperand(1));
577   }
578 }
579
580 // isSetCCEquivalent - Return true if this node is a setcc, or is a select_cc
581 // that selects between the target values used for true and false, making it
582 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
583 // the appropriate nodes based on the type of node we are checking. This
584 // simplifies life a bit for the callers.
585 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
586                                     SDValue &CC) const {
587   if (N.getOpcode() == ISD::SETCC) {
588     LHS = N.getOperand(0);
589     RHS = N.getOperand(1);
590     CC  = N.getOperand(2);
591     return true;
592   }
593
594   if (N.getOpcode() != ISD::SELECT_CC ||
595       !TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
596       !TLI.isConstFalseVal(N.getOperand(3).getNode()))
597     return false;
598
599   LHS = N.getOperand(0);
600   RHS = N.getOperand(1);
601   CC  = N.getOperand(4);
602   return true;
603 }
604
605 // isOneUseSetCC - Return true if this is a SetCC-equivalent operation with only
606 // one use.  If this is true, it allows the users to invert the operation for
607 // free when it is profitable to do so.
608 bool DAGCombiner::isOneUseSetCC(SDValue N) const {
609   SDValue N0, N1, N2;
610   if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
611     return true;
612   return false;
613 }
614
615 /// isConstantSplatVector - Returns true if N is a BUILD_VECTOR node whose
616 /// elements are all the same constant or undefined.
617 static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
618   BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
619   if (!C)
620     return false;
621
622   APInt SplatUndef;
623   unsigned SplatBitSize;
624   bool HasAnyUndefs;
625   EVT EltVT = N->getValueType(0).getVectorElementType();
626   return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
627                              HasAnyUndefs) &&
628           EltVT.getSizeInBits() >= SplatBitSize);
629 }
630
631 // \brief Returns the SDNode if it is a constant BuildVector or constant.
632 static SDNode *isConstantBuildVectorOrConstantInt(SDValue N) {
633   if (isa<ConstantSDNode>(N))
634     return N.getNode();
635   BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N);
636   if(BV && BV->isConstant())
637     return BV;
638   return nullptr;
639 }
640
641 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
642 // int.
643 static ConstantSDNode *isConstOrConstSplat(SDValue N) {
644   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
645     return CN;
646
647   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
648     BitVector UndefElements;
649     ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
650
651     // BuildVectors can truncate their operands. Ignore that case here.
652     // FIXME: We blindly ignore splats which include undef which is overly
653     // pessimistic.
654     if (CN && UndefElements.none() &&
655         CN->getValueType(0) == N.getValueType().getScalarType())
656       return CN;
657   }
658
659   return nullptr;
660 }
661
662 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
663                                     SDValue N0, SDValue N1) {
664   EVT VT = N0.getValueType();
665   if (N0.getOpcode() == Opc) {
666     if (SDNode *L = isConstantBuildVectorOrConstantInt(N0.getOperand(1))) {
667       if (SDNode *R = isConstantBuildVectorOrConstantInt(N1)) {
668         // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
669         SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, L, R);
670         if (!OpNode.getNode())
671           return SDValue();
672         return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
673       }
674       if (N0.hasOneUse()) {
675         // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
676         // use
677         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
678         if (!OpNode.getNode())
679           return SDValue();
680         AddToWorkList(OpNode.getNode());
681         return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
682       }
683     }
684   }
685
686   if (N1.getOpcode() == Opc) {
687     if (SDNode *R = isConstantBuildVectorOrConstantInt(N1.getOperand(1))) {
688       if (SDNode *L = isConstantBuildVectorOrConstantInt(N0)) {
689         // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
690         SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, R, L);
691         if (!OpNode.getNode())
692           return SDValue();
693         return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
694       }
695       if (N1.hasOneUse()) {
696         // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one
697         // use
698         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0);
699         if (!OpNode.getNode())
700           return SDValue();
701         AddToWorkList(OpNode.getNode());
702         return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
703       }
704     }
705   }
706
707   return SDValue();
708 }
709
710 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
711                                bool AddTo) {
712   assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
713   ++NodesCombined;
714   DEBUG(dbgs() << "\nReplacing.1 ";
715         N->dump(&DAG);
716         dbgs() << "\nWith: ";
717         To[0].getNode()->dump(&DAG);
718         dbgs() << " and " << NumTo-1 << " other values\n";
719         for (unsigned i = 0, e = NumTo; i != e; ++i)
720           assert((!To[i].getNode() ||
721                   N->getValueType(i) == To[i].getValueType()) &&
722                  "Cannot combine value to value of different type!"));
723   WorkListRemover DeadNodes(*this);
724   DAG.ReplaceAllUsesWith(N, To);
725   if (AddTo) {
726     // Push the new nodes and any users onto the worklist
727     for (unsigned i = 0, e = NumTo; i != e; ++i) {
728       if (To[i].getNode()) {
729         AddToWorkList(To[i].getNode());
730         AddUsersToWorkList(To[i].getNode());
731       }
732     }
733   }
734
735   // Finally, if the node is now dead, remove it from the graph.  The node
736   // may not be dead if the replacement process recursively simplified to
737   // something else needing this node.
738   if (N->use_empty()) {
739     // Nodes can be reintroduced into the worklist.  Make sure we do not
740     // process a node that has been replaced.
741     removeFromWorkList(N);
742
743     // Finally, since the node is now dead, remove it from the graph.
744     DAG.DeleteNode(N);
745   }
746   return SDValue(N, 0);
747 }
748
749 void DAGCombiner::
750 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
751   // Replace all uses.  If any nodes become isomorphic to other nodes and
752   // are deleted, make sure to remove them from our worklist.
753   WorkListRemover DeadNodes(*this);
754   DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
755
756   // Push the new node and any (possibly new) users onto the worklist.
757   AddToWorkList(TLO.New.getNode());
758   AddUsersToWorkList(TLO.New.getNode());
759
760   // Finally, if the node is now dead, remove it from the graph.  The node
761   // may not be dead if the replacement process recursively simplified to
762   // something else needing this node.
763   if (TLO.Old.getNode()->use_empty()) {
764     removeFromWorkList(TLO.Old.getNode());
765
766     // If the operands of this node are only used by the node, they will now
767     // be dead.  Make sure to visit them first to delete dead nodes early.
768     for (unsigned i = 0, e = TLO.Old.getNode()->getNumOperands(); i != e; ++i)
769       if (TLO.Old.getNode()->getOperand(i).getNode()->hasOneUse())
770         AddToWorkList(TLO.Old.getNode()->getOperand(i).getNode());
771
772     DAG.DeleteNode(TLO.Old.getNode());
773   }
774 }
775
776 /// SimplifyDemandedBits - Check the specified integer node value to see if
777 /// it can be simplified or if things it uses can be simplified by bit
778 /// propagation.  If so, return true.
779 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
780   TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
781   APInt KnownZero, KnownOne;
782   if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
783     return false;
784
785   // Revisit the node.
786   AddToWorkList(Op.getNode());
787
788   // Replace the old value with the new one.
789   ++NodesCombined;
790   DEBUG(dbgs() << "\nReplacing.2 ";
791         TLO.Old.getNode()->dump(&DAG);
792         dbgs() << "\nWith: ";
793         TLO.New.getNode()->dump(&DAG);
794         dbgs() << '\n');
795
796   CommitTargetLoweringOpt(TLO);
797   return true;
798 }
799
800 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
801   SDLoc dl(Load);
802   EVT VT = Load->getValueType(0);
803   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
804
805   DEBUG(dbgs() << "\nReplacing.9 ";
806         Load->dump(&DAG);
807         dbgs() << "\nWith: ";
808         Trunc.getNode()->dump(&DAG);
809         dbgs() << '\n');
810   WorkListRemover DeadNodes(*this);
811   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
812   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
813   removeFromWorkList(Load);
814   DAG.DeleteNode(Load);
815   AddToWorkList(Trunc.getNode());
816 }
817
818 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
819   Replace = false;
820   SDLoc dl(Op);
821   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
822     EVT MemVT = LD->getMemoryVT();
823     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
824       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
825                                                   : ISD::EXTLOAD)
826       : LD->getExtensionType();
827     Replace = true;
828     return DAG.getExtLoad(ExtType, dl, PVT,
829                           LD->getChain(), LD->getBasePtr(),
830                           MemVT, LD->getMemOperand());
831   }
832
833   unsigned Opc = Op.getOpcode();
834   switch (Opc) {
835   default: break;
836   case ISD::AssertSext:
837     return DAG.getNode(ISD::AssertSext, dl, PVT,
838                        SExtPromoteOperand(Op.getOperand(0), PVT),
839                        Op.getOperand(1));
840   case ISD::AssertZext:
841     return DAG.getNode(ISD::AssertZext, dl, PVT,
842                        ZExtPromoteOperand(Op.getOperand(0), PVT),
843                        Op.getOperand(1));
844   case ISD::Constant: {
845     unsigned ExtOpc =
846       Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
847     return DAG.getNode(ExtOpc, dl, PVT, Op);
848   }
849   }
850
851   if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
852     return SDValue();
853   return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
854 }
855
856 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
857   if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
858     return SDValue();
859   EVT OldVT = Op.getValueType();
860   SDLoc dl(Op);
861   bool Replace = false;
862   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
863   if (!NewOp.getNode())
864     return SDValue();
865   AddToWorkList(NewOp.getNode());
866
867   if (Replace)
868     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
869   return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
870                      DAG.getValueType(OldVT));
871 }
872
873 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
874   EVT OldVT = Op.getValueType();
875   SDLoc dl(Op);
876   bool Replace = false;
877   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
878   if (!NewOp.getNode())
879     return SDValue();
880   AddToWorkList(NewOp.getNode());
881
882   if (Replace)
883     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
884   return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
885 }
886
887 /// PromoteIntBinOp - Promote the specified integer binary operation if the
888 /// target indicates it is beneficial. e.g. On x86, it's usually better to
889 /// promote i16 operations to i32 since i16 instructions are longer.
890 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
891   if (!LegalOperations)
892     return SDValue();
893
894   EVT VT = Op.getValueType();
895   if (VT.isVector() || !VT.isInteger())
896     return SDValue();
897
898   // If operation type is 'undesirable', e.g. i16 on x86, consider
899   // promoting it.
900   unsigned Opc = Op.getOpcode();
901   if (TLI.isTypeDesirableForOp(Opc, VT))
902     return SDValue();
903
904   EVT PVT = VT;
905   // Consult target whether it is a good idea to promote this operation and
906   // what's the right type to promote it to.
907   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
908     assert(PVT != VT && "Don't know what type to promote to!");
909
910     bool Replace0 = false;
911     SDValue N0 = Op.getOperand(0);
912     SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
913     if (!NN0.getNode())
914       return SDValue();
915
916     bool Replace1 = false;
917     SDValue N1 = Op.getOperand(1);
918     SDValue NN1;
919     if (N0 == N1)
920       NN1 = NN0;
921     else {
922       NN1 = PromoteOperand(N1, PVT, Replace1);
923       if (!NN1.getNode())
924         return SDValue();
925     }
926
927     AddToWorkList(NN0.getNode());
928     if (NN1.getNode())
929       AddToWorkList(NN1.getNode());
930
931     if (Replace0)
932       ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
933     if (Replace1)
934       ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
935
936     DEBUG(dbgs() << "\nPromoting ";
937           Op.getNode()->dump(&DAG));
938     SDLoc dl(Op);
939     return DAG.getNode(ISD::TRUNCATE, dl, VT,
940                        DAG.getNode(Opc, dl, PVT, NN0, NN1));
941   }
942   return SDValue();
943 }
944
945 /// PromoteIntShiftOp - Promote the specified integer shift operation if the
946 /// target indicates it is beneficial. e.g. On x86, it's usually better to
947 /// promote i16 operations to i32 since i16 instructions are longer.
948 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
949   if (!LegalOperations)
950     return SDValue();
951
952   EVT VT = Op.getValueType();
953   if (VT.isVector() || !VT.isInteger())
954     return SDValue();
955
956   // If operation type is 'undesirable', e.g. i16 on x86, consider
957   // promoting it.
958   unsigned Opc = Op.getOpcode();
959   if (TLI.isTypeDesirableForOp(Opc, VT))
960     return SDValue();
961
962   EVT PVT = VT;
963   // Consult target whether it is a good idea to promote this operation and
964   // what's the right type to promote it to.
965   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
966     assert(PVT != VT && "Don't know what type to promote to!");
967
968     bool Replace = false;
969     SDValue N0 = Op.getOperand(0);
970     if (Opc == ISD::SRA)
971       N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
972     else if (Opc == ISD::SRL)
973       N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
974     else
975       N0 = PromoteOperand(N0, PVT, Replace);
976     if (!N0.getNode())
977       return SDValue();
978
979     AddToWorkList(N0.getNode());
980     if (Replace)
981       ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
982
983     DEBUG(dbgs() << "\nPromoting ";
984           Op.getNode()->dump(&DAG));
985     SDLoc dl(Op);
986     return DAG.getNode(ISD::TRUNCATE, dl, VT,
987                        DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
988   }
989   return SDValue();
990 }
991
992 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
993   if (!LegalOperations)
994     return SDValue();
995
996   EVT VT = Op.getValueType();
997   if (VT.isVector() || !VT.isInteger())
998     return SDValue();
999
1000   // If operation type is 'undesirable', e.g. i16 on x86, consider
1001   // promoting it.
1002   unsigned Opc = Op.getOpcode();
1003   if (TLI.isTypeDesirableForOp(Opc, VT))
1004     return SDValue();
1005
1006   EVT PVT = VT;
1007   // Consult target whether it is a good idea to promote this operation and
1008   // what's the right type to promote it to.
1009   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1010     assert(PVT != VT && "Don't know what type to promote to!");
1011     // fold (aext (aext x)) -> (aext x)
1012     // fold (aext (zext x)) -> (zext x)
1013     // fold (aext (sext x)) -> (sext x)
1014     DEBUG(dbgs() << "\nPromoting ";
1015           Op.getNode()->dump(&DAG));
1016     return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1017   }
1018   return SDValue();
1019 }
1020
1021 bool DAGCombiner::PromoteLoad(SDValue Op) {
1022   if (!LegalOperations)
1023     return false;
1024
1025   EVT VT = Op.getValueType();
1026   if (VT.isVector() || !VT.isInteger())
1027     return false;
1028
1029   // If operation type is 'undesirable', e.g. i16 on x86, consider
1030   // promoting it.
1031   unsigned Opc = Op.getOpcode();
1032   if (TLI.isTypeDesirableForOp(Opc, VT))
1033     return false;
1034
1035   EVT PVT = VT;
1036   // Consult target whether it is a good idea to promote this operation and
1037   // what's the right type to promote it to.
1038   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1039     assert(PVT != VT && "Don't know what type to promote to!");
1040
1041     SDLoc dl(Op);
1042     SDNode *N = Op.getNode();
1043     LoadSDNode *LD = cast<LoadSDNode>(N);
1044     EVT MemVT = LD->getMemoryVT();
1045     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1046       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
1047                                                   : ISD::EXTLOAD)
1048       : LD->getExtensionType();
1049     SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
1050                                    LD->getChain(), LD->getBasePtr(),
1051                                    MemVT, LD->getMemOperand());
1052     SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
1053
1054     DEBUG(dbgs() << "\nPromoting ";
1055           N->dump(&DAG);
1056           dbgs() << "\nTo: ";
1057           Result.getNode()->dump(&DAG);
1058           dbgs() << '\n');
1059     WorkListRemover DeadNodes(*this);
1060     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1061     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1062     removeFromWorkList(N);
1063     DAG.DeleteNode(N);
1064     AddToWorkList(Result.getNode());
1065     return true;
1066   }
1067   return false;
1068 }
1069
1070
1071 //===----------------------------------------------------------------------===//
1072 //  Main DAG Combiner implementation
1073 //===----------------------------------------------------------------------===//
1074
1075 void DAGCombiner::Run(CombineLevel AtLevel) {
1076   // set the instance variables, so that the various visit routines may use it.
1077   Level = AtLevel;
1078   LegalOperations = Level >= AfterLegalizeVectorOps;
1079   LegalTypes = Level >= AfterLegalizeTypes;
1080
1081   // Add all the dag nodes to the worklist.
1082   for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
1083        E = DAG.allnodes_end(); I != E; ++I)
1084     AddToWorkList(I);
1085
1086   // Create a dummy node (which is not added to allnodes), that adds a reference
1087   // to the root node, preventing it from being deleted, and tracking any
1088   // changes of the root.
1089   HandleSDNode Dummy(DAG.getRoot());
1090
1091   // The root of the dag may dangle to deleted nodes until the dag combiner is
1092   // done.  Set it to null to avoid confusion.
1093   DAG.setRoot(SDValue());
1094
1095   // while the worklist isn't empty, find a node and
1096   // try and combine it.
1097   while (!WorkListContents.empty()) {
1098     SDNode *N;
1099     // The WorkListOrder holds the SDNodes in order, but it may contain
1100     // duplicates.
1101     // In order to avoid a linear scan, we use a set (O(log N)) to hold what the
1102     // worklist *should* contain, and check the node we want to visit is should
1103     // actually be visited.
1104     do {
1105       N = WorkListOrder.pop_back_val();
1106     } while (!WorkListContents.erase(N));
1107
1108     // If N has no uses, it is dead.  Make sure to revisit all N's operands once
1109     // N is deleted from the DAG, since they too may now be dead or may have a
1110     // reduced number of uses, allowing other xforms.
1111     if (N->use_empty() && N != &Dummy) {
1112       for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1113         AddToWorkList(N->getOperand(i).getNode());
1114
1115       DAG.DeleteNode(N);
1116       continue;
1117     }
1118
1119     SDValue RV = combine(N);
1120
1121     if (!RV.getNode())
1122       continue;
1123
1124     ++NodesCombined;
1125
1126     // If we get back the same node we passed in, rather than a new node or
1127     // zero, we know that the node must have defined multiple values and
1128     // CombineTo was used.  Since CombineTo takes care of the worklist
1129     // mechanics for us, we have no work to do in this case.
1130     if (RV.getNode() == N)
1131       continue;
1132
1133     assert(N->getOpcode() != ISD::DELETED_NODE &&
1134            RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1135            "Node was deleted but visit returned new node!");
1136
1137     DEBUG(dbgs() << "\nReplacing.3 ";
1138           N->dump(&DAG);
1139           dbgs() << "\nWith: ";
1140           RV.getNode()->dump(&DAG);
1141           dbgs() << '\n');
1142
1143     // Transfer debug value.
1144     DAG.TransferDbgValues(SDValue(N, 0), RV);
1145     WorkListRemover DeadNodes(*this);
1146     if (N->getNumValues() == RV.getNode()->getNumValues())
1147       DAG.ReplaceAllUsesWith(N, RV.getNode());
1148     else {
1149       assert(N->getValueType(0) == RV.getValueType() &&
1150              N->getNumValues() == 1 && "Type mismatch");
1151       SDValue OpV = RV;
1152       DAG.ReplaceAllUsesWith(N, &OpV);
1153     }
1154
1155     // Push the new node and any users onto the worklist
1156     AddToWorkList(RV.getNode());
1157     AddUsersToWorkList(RV.getNode());
1158
1159     // Add any uses of the old node to the worklist in case this node is the
1160     // last one that uses them.  They may become dead after this node is
1161     // deleted.
1162     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1163       AddToWorkList(N->getOperand(i).getNode());
1164
1165     // Finally, if the node is now dead, remove it from the graph.  The node
1166     // may not be dead if the replacement process recursively simplified to
1167     // something else needing this node.
1168     if (N->use_empty()) {
1169       // Nodes can be reintroduced into the worklist.  Make sure we do not
1170       // process a node that has been replaced.
1171       removeFromWorkList(N);
1172
1173       // Finally, since the node is now dead, remove it from the graph.
1174       DAG.DeleteNode(N);
1175     }
1176   }
1177
1178   // If the root changed (e.g. it was a dead load, update the root).
1179   DAG.setRoot(Dummy.getValue());
1180   DAG.RemoveDeadNodes();
1181 }
1182
1183 SDValue DAGCombiner::visit(SDNode *N) {
1184   switch (N->getOpcode()) {
1185   default: break;
1186   case ISD::TokenFactor:        return visitTokenFactor(N);
1187   case ISD::MERGE_VALUES:       return visitMERGE_VALUES(N);
1188   case ISD::ADD:                return visitADD(N);
1189   case ISD::SUB:                return visitSUB(N);
1190   case ISD::ADDC:               return visitADDC(N);
1191   case ISD::SUBC:               return visitSUBC(N);
1192   case ISD::ADDE:               return visitADDE(N);
1193   case ISD::SUBE:               return visitSUBE(N);
1194   case ISD::MUL:                return visitMUL(N);
1195   case ISD::SDIV:               return visitSDIV(N);
1196   case ISD::UDIV:               return visitUDIV(N);
1197   case ISD::SREM:               return visitSREM(N);
1198   case ISD::UREM:               return visitUREM(N);
1199   case ISD::MULHU:              return visitMULHU(N);
1200   case ISD::MULHS:              return visitMULHS(N);
1201   case ISD::SMUL_LOHI:          return visitSMUL_LOHI(N);
1202   case ISD::UMUL_LOHI:          return visitUMUL_LOHI(N);
1203   case ISD::SMULO:              return visitSMULO(N);
1204   case ISD::UMULO:              return visitUMULO(N);
1205   case ISD::SDIVREM:            return visitSDIVREM(N);
1206   case ISD::UDIVREM:            return visitUDIVREM(N);
1207   case ISD::AND:                return visitAND(N);
1208   case ISD::OR:                 return visitOR(N);
1209   case ISD::XOR:                return visitXOR(N);
1210   case ISD::SHL:                return visitSHL(N);
1211   case ISD::SRA:                return visitSRA(N);
1212   case ISD::SRL:                return visitSRL(N);
1213   case ISD::ROTR:
1214   case ISD::ROTL:               return visitRotate(N);
1215   case ISD::CTLZ:               return visitCTLZ(N);
1216   case ISD::CTLZ_ZERO_UNDEF:    return visitCTLZ_ZERO_UNDEF(N);
1217   case ISD::CTTZ:               return visitCTTZ(N);
1218   case ISD::CTTZ_ZERO_UNDEF:    return visitCTTZ_ZERO_UNDEF(N);
1219   case ISD::CTPOP:              return visitCTPOP(N);
1220   case ISD::SELECT:             return visitSELECT(N);
1221   case ISD::VSELECT:            return visitVSELECT(N);
1222   case ISD::SELECT_CC:          return visitSELECT_CC(N);
1223   case ISD::SETCC:              return visitSETCC(N);
1224   case ISD::SIGN_EXTEND:        return visitSIGN_EXTEND(N);
1225   case ISD::ZERO_EXTEND:        return visitZERO_EXTEND(N);
1226   case ISD::ANY_EXTEND:         return visitANY_EXTEND(N);
1227   case ISD::SIGN_EXTEND_INREG:  return visitSIGN_EXTEND_INREG(N);
1228   case ISD::TRUNCATE:           return visitTRUNCATE(N);
1229   case ISD::BITCAST:            return visitBITCAST(N);
1230   case ISD::BUILD_PAIR:         return visitBUILD_PAIR(N);
1231   case ISD::FADD:               return visitFADD(N);
1232   case ISD::FSUB:               return visitFSUB(N);
1233   case ISD::FMUL:               return visitFMUL(N);
1234   case ISD::FMA:                return visitFMA(N);
1235   case ISD::FDIV:               return visitFDIV(N);
1236   case ISD::FREM:               return visitFREM(N);
1237   case ISD::FCOPYSIGN:          return visitFCOPYSIGN(N);
1238   case ISD::SINT_TO_FP:         return visitSINT_TO_FP(N);
1239   case ISD::UINT_TO_FP:         return visitUINT_TO_FP(N);
1240   case ISD::FP_TO_SINT:         return visitFP_TO_SINT(N);
1241   case ISD::FP_TO_UINT:         return visitFP_TO_UINT(N);
1242   case ISD::FP_ROUND:           return visitFP_ROUND(N);
1243   case ISD::FP_ROUND_INREG:     return visitFP_ROUND_INREG(N);
1244   case ISD::FP_EXTEND:          return visitFP_EXTEND(N);
1245   case ISD::FNEG:               return visitFNEG(N);
1246   case ISD::FABS:               return visitFABS(N);
1247   case ISD::FFLOOR:             return visitFFLOOR(N);
1248   case ISD::FCEIL:              return visitFCEIL(N);
1249   case ISD::FTRUNC:             return visitFTRUNC(N);
1250   case ISD::BRCOND:             return visitBRCOND(N);
1251   case ISD::BR_CC:              return visitBR_CC(N);
1252   case ISD::LOAD:               return visitLOAD(N);
1253   case ISD::STORE:              return visitSTORE(N);
1254   case ISD::INSERT_VECTOR_ELT:  return visitINSERT_VECTOR_ELT(N);
1255   case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1256   case ISD::BUILD_VECTOR:       return visitBUILD_VECTOR(N);
1257   case ISD::CONCAT_VECTORS:     return visitCONCAT_VECTORS(N);
1258   case ISD::EXTRACT_SUBVECTOR:  return visitEXTRACT_SUBVECTOR(N);
1259   case ISD::VECTOR_SHUFFLE:     return visitVECTOR_SHUFFLE(N);
1260   case ISD::INSERT_SUBVECTOR:   return visitINSERT_SUBVECTOR(N);
1261   }
1262   return SDValue();
1263 }
1264
1265 SDValue DAGCombiner::combine(SDNode *N) {
1266   SDValue RV = visit(N);
1267
1268   // If nothing happened, try a target-specific DAG combine.
1269   if (!RV.getNode()) {
1270     assert(N->getOpcode() != ISD::DELETED_NODE &&
1271            "Node was deleted but visit returned NULL!");
1272
1273     if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1274         TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1275
1276       // Expose the DAG combiner to the target combiner impls.
1277       TargetLowering::DAGCombinerInfo
1278         DagCombineInfo(DAG, Level, false, this);
1279
1280       RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1281     }
1282   }
1283
1284   // If nothing happened still, try promoting the operation.
1285   if (!RV.getNode()) {
1286     switch (N->getOpcode()) {
1287     default: break;
1288     case ISD::ADD:
1289     case ISD::SUB:
1290     case ISD::MUL:
1291     case ISD::AND:
1292     case ISD::OR:
1293     case ISD::XOR:
1294       RV = PromoteIntBinOp(SDValue(N, 0));
1295       break;
1296     case ISD::SHL:
1297     case ISD::SRA:
1298     case ISD::SRL:
1299       RV = PromoteIntShiftOp(SDValue(N, 0));
1300       break;
1301     case ISD::SIGN_EXTEND:
1302     case ISD::ZERO_EXTEND:
1303     case ISD::ANY_EXTEND:
1304       RV = PromoteExtend(SDValue(N, 0));
1305       break;
1306     case ISD::LOAD:
1307       if (PromoteLoad(SDValue(N, 0)))
1308         RV = SDValue(N, 0);
1309       break;
1310     }
1311   }
1312
1313   // If N is a commutative binary node, try commuting it to enable more
1314   // sdisel CSE.
1315   if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1316       N->getNumValues() == 1) {
1317     SDValue N0 = N->getOperand(0);
1318     SDValue N1 = N->getOperand(1);
1319
1320     // Constant operands are canonicalized to RHS.
1321     if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1322       SDValue Ops[] = {N1, N0};
1323       SDNode *CSENode;
1324       if (const BinaryWithFlagsSDNode *BinNode =
1325               dyn_cast<BinaryWithFlagsSDNode>(N)) {
1326         CSENode = DAG.getNodeIfExists(
1327             N->getOpcode(), N->getVTList(), Ops, BinNode->hasNoUnsignedWrap(),
1328             BinNode->hasNoSignedWrap(), BinNode->isExact());
1329       } else {
1330         CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops);
1331       }
1332       if (CSENode)
1333         return SDValue(CSENode, 0);
1334     }
1335   }
1336
1337   return RV;
1338 }
1339
1340 /// getInputChainForNode - Given a node, return its input chain if it has one,
1341 /// otherwise return a null sd operand.
1342 static SDValue getInputChainForNode(SDNode *N) {
1343   if (unsigned NumOps = N->getNumOperands()) {
1344     if (N->getOperand(0).getValueType() == MVT::Other)
1345       return N->getOperand(0);
1346     if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1347       return N->getOperand(NumOps-1);
1348     for (unsigned i = 1; i < NumOps-1; ++i)
1349       if (N->getOperand(i).getValueType() == MVT::Other)
1350         return N->getOperand(i);
1351   }
1352   return SDValue();
1353 }
1354
1355 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1356   // If N has two operands, where one has an input chain equal to the other,
1357   // the 'other' chain is redundant.
1358   if (N->getNumOperands() == 2) {
1359     if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1360       return N->getOperand(0);
1361     if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1362       return N->getOperand(1);
1363   }
1364
1365   SmallVector<SDNode *, 8> TFs;     // List of token factors to visit.
1366   SmallVector<SDValue, 8> Ops;    // Ops for replacing token factor.
1367   SmallPtrSet<SDNode*, 16> SeenOps;
1368   bool Changed = false;             // If we should replace this token factor.
1369
1370   // Start out with this token factor.
1371   TFs.push_back(N);
1372
1373   // Iterate through token factors.  The TFs grows when new token factors are
1374   // encountered.
1375   for (unsigned i = 0; i < TFs.size(); ++i) {
1376     SDNode *TF = TFs[i];
1377
1378     // Check each of the operands.
1379     for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
1380       SDValue Op = TF->getOperand(i);
1381
1382       switch (Op.getOpcode()) {
1383       case ISD::EntryToken:
1384         // Entry tokens don't need to be added to the list. They are
1385         // rededundant.
1386         Changed = true;
1387         break;
1388
1389       case ISD::TokenFactor:
1390         if (Op.hasOneUse() &&
1391             std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1392           // Queue up for processing.
1393           TFs.push_back(Op.getNode());
1394           // Clean up in case the token factor is removed.
1395           AddToWorkList(Op.getNode());
1396           Changed = true;
1397           break;
1398         }
1399         // Fall thru
1400
1401       default:
1402         // Only add if it isn't already in the list.
1403         if (SeenOps.insert(Op.getNode()))
1404           Ops.push_back(Op);
1405         else
1406           Changed = true;
1407         break;
1408       }
1409     }
1410   }
1411
1412   SDValue Result;
1413
1414   // If we've change things around then replace token factor.
1415   if (Changed) {
1416     if (Ops.empty()) {
1417       // The entry token is the only possible outcome.
1418       Result = DAG.getEntryNode();
1419     } else {
1420       // New and improved token factor.
1421       Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
1422     }
1423
1424     // Don't add users to work list.
1425     return CombineTo(N, Result, false);
1426   }
1427
1428   return Result;
1429 }
1430
1431 /// MERGE_VALUES can always be eliminated.
1432 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1433   WorkListRemover DeadNodes(*this);
1434   // Replacing results may cause a different MERGE_VALUES to suddenly
1435   // be CSE'd with N, and carry its uses with it. Iterate until no
1436   // uses remain, to ensure that the node can be safely deleted.
1437   // First add the users of this node to the work list so that they
1438   // can be tried again once they have new operands.
1439   AddUsersToWorkList(N);
1440   do {
1441     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1442       DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1443   } while (!N->use_empty());
1444   removeFromWorkList(N);
1445   DAG.DeleteNode(N);
1446   return SDValue(N, 0);   // Return N so it doesn't get rechecked!
1447 }
1448
1449 static
1450 SDValue combineShlAddConstant(SDLoc DL, SDValue N0, SDValue N1,
1451                               SelectionDAG &DAG) {
1452   EVT VT = N0.getValueType();
1453   SDValue N00 = N0.getOperand(0);
1454   SDValue N01 = N0.getOperand(1);
1455   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N01);
1456
1457   if (N01C && N00.getOpcode() == ISD::ADD && N00.getNode()->hasOneUse() &&
1458       isa<ConstantSDNode>(N00.getOperand(1))) {
1459     // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1460     N0 = DAG.getNode(ISD::ADD, SDLoc(N0), VT,
1461                      DAG.getNode(ISD::SHL, SDLoc(N00), VT,
1462                                  N00.getOperand(0), N01),
1463                      DAG.getNode(ISD::SHL, SDLoc(N01), VT,
1464                                  N00.getOperand(1), N01));
1465     return DAG.getNode(ISD::ADD, DL, VT, N0, N1);
1466   }
1467
1468   return SDValue();
1469 }
1470
1471 SDValue DAGCombiner::visitADD(SDNode *N) {
1472   SDValue N0 = N->getOperand(0);
1473   SDValue N1 = N->getOperand(1);
1474   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1475   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1476   EVT VT = N0.getValueType();
1477
1478   // fold vector ops
1479   if (VT.isVector()) {
1480     SDValue FoldedVOp = SimplifyVBinOp(N);
1481     if (FoldedVOp.getNode()) return FoldedVOp;
1482
1483     // fold (add x, 0) -> x, vector edition
1484     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1485       return N0;
1486     if (ISD::isBuildVectorAllZeros(N0.getNode()))
1487       return N1;
1488   }
1489
1490   // fold (add x, undef) -> undef
1491   if (N0.getOpcode() == ISD::UNDEF)
1492     return N0;
1493   if (N1.getOpcode() == ISD::UNDEF)
1494     return N1;
1495   // fold (add c1, c2) -> c1+c2
1496   if (N0C && N1C)
1497     return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C);
1498   // canonicalize constant to RHS
1499   if (N0C && !N1C)
1500     return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
1501   // fold (add x, 0) -> x
1502   if (N1C && N1C->isNullValue())
1503     return N0;
1504   // fold (add Sym, c) -> Sym+c
1505   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1506     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1507         GA->getOpcode() == ISD::GlobalAddress)
1508       return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1509                                   GA->getOffset() +
1510                                     (uint64_t)N1C->getSExtValue());
1511   // fold ((c1-A)+c2) -> (c1+c2)-A
1512   if (N1C && N0.getOpcode() == ISD::SUB)
1513     if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
1514       return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1515                          DAG.getConstant(N1C->getAPIntValue()+
1516                                          N0C->getAPIntValue(), VT),
1517                          N0.getOperand(1));
1518   // reassociate add
1519   SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1);
1520   if (RADD.getNode())
1521     return RADD;
1522   // fold ((0-A) + B) -> B-A
1523   if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
1524       cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
1525     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
1526   // fold (A + (0-B)) -> A-B
1527   if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1528       cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
1529     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
1530   // fold (A+(B-A)) -> B
1531   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1532     return N1.getOperand(0);
1533   // fold ((B-A)+A) -> B
1534   if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1535     return N0.getOperand(0);
1536   // fold (A+(B-(A+C))) to (B-C)
1537   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1538       N0 == N1.getOperand(1).getOperand(0))
1539     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1540                        N1.getOperand(1).getOperand(1));
1541   // fold (A+(B-(C+A))) to (B-C)
1542   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1543       N0 == N1.getOperand(1).getOperand(1))
1544     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1545                        N1.getOperand(1).getOperand(0));
1546   // fold (A+((B-A)+or-C)) to (B+or-C)
1547   if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1548       N1.getOperand(0).getOpcode() == ISD::SUB &&
1549       N0 == N1.getOperand(0).getOperand(1))
1550     return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
1551                        N1.getOperand(0).getOperand(0), N1.getOperand(1));
1552
1553   // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1554   if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1555     SDValue N00 = N0.getOperand(0);
1556     SDValue N01 = N0.getOperand(1);
1557     SDValue N10 = N1.getOperand(0);
1558     SDValue N11 = N1.getOperand(1);
1559
1560     if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1561       return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1562                          DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1563                          DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1564   }
1565
1566   if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1567     return SDValue(N, 0);
1568
1569   // fold (a+b) -> (a|b) iff a and b share no bits.
1570   if (VT.isInteger() && !VT.isVector()) {
1571     APInt LHSZero, LHSOne;
1572     APInt RHSZero, RHSOne;
1573     DAG.computeKnownBits(N0, LHSZero, LHSOne);
1574
1575     if (LHSZero.getBoolValue()) {
1576       DAG.computeKnownBits(N1, RHSZero, RHSOne);
1577
1578       // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1579       // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1580       if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){
1581         if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT))
1582           return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1583       }
1584     }
1585   }
1586
1587   // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1588   if (N0.getOpcode() == ISD::SHL && N0.getNode()->hasOneUse()) {
1589     SDValue Result = combineShlAddConstant(SDLoc(N), N0, N1, DAG);
1590     if (Result.getNode()) return Result;
1591   }
1592   if (N1.getOpcode() == ISD::SHL && N1.getNode()->hasOneUse()) {
1593     SDValue Result = combineShlAddConstant(SDLoc(N), N1, N0, DAG);
1594     if (Result.getNode()) return Result;
1595   }
1596
1597   // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1598   if (N1.getOpcode() == ISD::SHL &&
1599       N1.getOperand(0).getOpcode() == ISD::SUB)
1600     if (ConstantSDNode *C =
1601           dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
1602       if (C->getAPIntValue() == 0)
1603         return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1604                            DAG.getNode(ISD::SHL, SDLoc(N), VT,
1605                                        N1.getOperand(0).getOperand(1),
1606                                        N1.getOperand(1)));
1607   if (N0.getOpcode() == ISD::SHL &&
1608       N0.getOperand(0).getOpcode() == ISD::SUB)
1609     if (ConstantSDNode *C =
1610           dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
1611       if (C->getAPIntValue() == 0)
1612         return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1613                            DAG.getNode(ISD::SHL, SDLoc(N), VT,
1614                                        N0.getOperand(0).getOperand(1),
1615                                        N0.getOperand(1)));
1616
1617   if (N1.getOpcode() == ISD::AND) {
1618     SDValue AndOp0 = N1.getOperand(0);
1619     ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1));
1620     unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1621     unsigned DestBits = VT.getScalarType().getSizeInBits();
1622
1623     // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1624     // and similar xforms where the inner op is either ~0 or 0.
1625     if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) {
1626       SDLoc DL(N);
1627       return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1628     }
1629   }
1630
1631   // add (sext i1), X -> sub X, (zext i1)
1632   if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1633       N0.getOperand(0).getValueType() == MVT::i1 &&
1634       !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1635     SDLoc DL(N);
1636     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1637     return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1638   }
1639
1640   return SDValue();
1641 }
1642
1643 SDValue DAGCombiner::visitADDC(SDNode *N) {
1644   SDValue N0 = N->getOperand(0);
1645   SDValue N1 = N->getOperand(1);
1646   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1647   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1648   EVT VT = N0.getValueType();
1649
1650   // If the flag result is dead, turn this into an ADD.
1651   if (!N->hasAnyUseOfValue(1))
1652     return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1653                      DAG.getNode(ISD::CARRY_FALSE,
1654                                  SDLoc(N), MVT::Glue));
1655
1656   // canonicalize constant to RHS.
1657   if (N0C && !N1C)
1658     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1659
1660   // fold (addc x, 0) -> x + no carry out
1661   if (N1C && N1C->isNullValue())
1662     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1663                                         SDLoc(N), MVT::Glue));
1664
1665   // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1666   APInt LHSZero, LHSOne;
1667   APInt RHSZero, RHSOne;
1668   DAG.computeKnownBits(N0, LHSZero, LHSOne);
1669
1670   if (LHSZero.getBoolValue()) {
1671     DAG.computeKnownBits(N1, RHSZero, RHSOne);
1672
1673     // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1674     // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1675     if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1676       return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1677                        DAG.getNode(ISD::CARRY_FALSE,
1678                                    SDLoc(N), MVT::Glue));
1679   }
1680
1681   return SDValue();
1682 }
1683
1684 SDValue DAGCombiner::visitADDE(SDNode *N) {
1685   SDValue N0 = N->getOperand(0);
1686   SDValue N1 = N->getOperand(1);
1687   SDValue CarryIn = N->getOperand(2);
1688   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1689   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1690
1691   // canonicalize constant to RHS
1692   if (N0C && !N1C)
1693     return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1694                        N1, N0, CarryIn);
1695
1696   // fold (adde x, y, false) -> (addc x, y)
1697   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1698     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1699
1700   return SDValue();
1701 }
1702
1703 // Since it may not be valid to emit a fold to zero for vector initializers
1704 // check if we can before folding.
1705 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
1706                              SelectionDAG &DAG,
1707                              bool LegalOperations, bool LegalTypes) {
1708   if (!VT.isVector())
1709     return DAG.getConstant(0, VT);
1710   if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1711     return DAG.getConstant(0, VT);
1712   return SDValue();
1713 }
1714
1715 SDValue DAGCombiner::visitSUB(SDNode *N) {
1716   SDValue N0 = N->getOperand(0);
1717   SDValue N1 = N->getOperand(1);
1718   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1719   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1720   ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr :
1721     dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1722   EVT VT = N0.getValueType();
1723
1724   // fold vector ops
1725   if (VT.isVector()) {
1726     SDValue FoldedVOp = SimplifyVBinOp(N);
1727     if (FoldedVOp.getNode()) return FoldedVOp;
1728
1729     // fold (sub x, 0) -> x, vector edition
1730     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1731       return N0;
1732   }
1733
1734   // fold (sub x, x) -> 0
1735   // FIXME: Refactor this and xor and other similar operations together.
1736   if (N0 == N1)
1737     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
1738   // fold (sub c1, c2) -> c1-c2
1739   if (N0C && N1C)
1740     return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C);
1741   // fold (sub x, c) -> (add x, -c)
1742   if (N1C)
1743     return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0,
1744                        DAG.getConstant(-N1C->getAPIntValue(), VT));
1745   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1746   if (N0C && N0C->isAllOnesValue())
1747     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
1748   // fold A-(A-B) -> B
1749   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1750     return N1.getOperand(1);
1751   // fold (A+B)-A -> B
1752   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1753     return N0.getOperand(1);
1754   // fold (A+B)-B -> A
1755   if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1756     return N0.getOperand(0);
1757   // fold C2-(A+C1) -> (C2-C1)-A
1758   if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1759     SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1760                                    VT);
1761     return DAG.getNode(ISD::SUB, SDLoc(N), VT, NewC,
1762                        N1.getOperand(0));
1763   }
1764   // fold ((A+(B+or-C))-B) -> A+or-C
1765   if (N0.getOpcode() == ISD::ADD &&
1766       (N0.getOperand(1).getOpcode() == ISD::SUB ||
1767        N0.getOperand(1).getOpcode() == ISD::ADD) &&
1768       N0.getOperand(1).getOperand(0) == N1)
1769     return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
1770                        N0.getOperand(0), N0.getOperand(1).getOperand(1));
1771   // fold ((A+(C+B))-B) -> A+C
1772   if (N0.getOpcode() == ISD::ADD &&
1773       N0.getOperand(1).getOpcode() == ISD::ADD &&
1774       N0.getOperand(1).getOperand(1) == N1)
1775     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1776                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1777   // fold ((A-(B-C))-C) -> A-B
1778   if (N0.getOpcode() == ISD::SUB &&
1779       N0.getOperand(1).getOpcode() == ISD::SUB &&
1780       N0.getOperand(1).getOperand(1) == N1)
1781     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1782                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1783
1784   // If either operand of a sub is undef, the result is undef
1785   if (N0.getOpcode() == ISD::UNDEF)
1786     return N0;
1787   if (N1.getOpcode() == ISD::UNDEF)
1788     return N1;
1789
1790   // If the relocation model supports it, consider symbol offsets.
1791   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1792     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1793       // fold (sub Sym, c) -> Sym-c
1794       if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1795         return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1796                                     GA->getOffset() -
1797                                       (uint64_t)N1C->getSExtValue());
1798       // fold (sub Sym+c1, Sym+c2) -> c1-c2
1799       if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1800         if (GA->getGlobal() == GB->getGlobal())
1801           return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1802                                  VT);
1803     }
1804
1805   return SDValue();
1806 }
1807
1808 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1809   SDValue N0 = N->getOperand(0);
1810   SDValue N1 = N->getOperand(1);
1811   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1812   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1813   EVT VT = N0.getValueType();
1814
1815   // If the flag result is dead, turn this into an SUB.
1816   if (!N->hasAnyUseOfValue(1))
1817     return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1818                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1819                                  MVT::Glue));
1820
1821   // fold (subc x, x) -> 0 + no borrow
1822   if (N0 == N1)
1823     return CombineTo(N, DAG.getConstant(0, VT),
1824                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1825                                  MVT::Glue));
1826
1827   // fold (subc x, 0) -> x + no borrow
1828   if (N1C && N1C->isNullValue())
1829     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1830                                         MVT::Glue));
1831
1832   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1833   if (N0C && N0C->isAllOnesValue())
1834     return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
1835                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1836                                  MVT::Glue));
1837
1838   return SDValue();
1839 }
1840
1841 SDValue DAGCombiner::visitSUBE(SDNode *N) {
1842   SDValue N0 = N->getOperand(0);
1843   SDValue N1 = N->getOperand(1);
1844   SDValue CarryIn = N->getOperand(2);
1845
1846   // fold (sube x, y, false) -> (subc x, y)
1847   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1848     return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
1849
1850   return SDValue();
1851 }
1852
1853 SDValue DAGCombiner::visitMUL(SDNode *N) {
1854   SDValue N0 = N->getOperand(0);
1855   SDValue N1 = N->getOperand(1);
1856   EVT VT = N0.getValueType();
1857
1858   // fold (mul x, undef) -> 0
1859   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1860     return DAG.getConstant(0, VT);
1861
1862   bool N0IsConst = false;
1863   bool N1IsConst = false;
1864   APInt ConstValue0, ConstValue1;
1865   // fold vector ops
1866   if (VT.isVector()) {
1867     SDValue FoldedVOp = SimplifyVBinOp(N);
1868     if (FoldedVOp.getNode()) return FoldedVOp;
1869
1870     N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
1871     N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
1872   } else {
1873     N0IsConst = dyn_cast<ConstantSDNode>(N0) != nullptr;
1874     ConstValue0 = N0IsConst ? (dyn_cast<ConstantSDNode>(N0))->getAPIntValue()
1875                             : APInt();
1876     N1IsConst = dyn_cast<ConstantSDNode>(N1) != nullptr;
1877     ConstValue1 = N1IsConst ? (dyn_cast<ConstantSDNode>(N1))->getAPIntValue()
1878                             : APInt();
1879   }
1880
1881   // fold (mul c1, c2) -> c1*c2
1882   if (N0IsConst && N1IsConst)
1883     return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0.getNode(), N1.getNode());
1884
1885   // canonicalize constant to RHS
1886   if (N0IsConst && !N1IsConst)
1887     return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
1888   // fold (mul x, 0) -> 0
1889   if (N1IsConst && ConstValue1 == 0)
1890     return N1;
1891   // We require a splat of the entire scalar bit width for non-contiguous
1892   // bit patterns.
1893   bool IsFullSplat =
1894     ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
1895   // fold (mul x, 1) -> x
1896   if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
1897     return N0;
1898   // fold (mul x, -1) -> 0-x
1899   if (N1IsConst && ConstValue1.isAllOnesValue())
1900     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1901                        DAG.getConstant(0, VT), N0);
1902   // fold (mul x, (1 << c)) -> x << c
1903   if (N1IsConst && ConstValue1.isPowerOf2() && IsFullSplat)
1904     return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1905                        DAG.getConstant(ConstValue1.logBase2(),
1906                                        getShiftAmountTy(N0.getValueType())));
1907   // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
1908   if (N1IsConst && (-ConstValue1).isPowerOf2() && IsFullSplat) {
1909     unsigned Log2Val = (-ConstValue1).logBase2();
1910     // FIXME: If the input is something that is easily negated (e.g. a
1911     // single-use add), we should put the negate there.
1912     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1913                        DAG.getConstant(0, VT),
1914                        DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1915                             DAG.getConstant(Log2Val,
1916                                       getShiftAmountTy(N0.getValueType()))));
1917   }
1918
1919   APInt Val;
1920   // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
1921   if (N1IsConst && N0.getOpcode() == ISD::SHL &&
1922       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1923                      isa<ConstantSDNode>(N0.getOperand(1)))) {
1924     SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
1925                              N1, N0.getOperand(1));
1926     AddToWorkList(C3.getNode());
1927     return DAG.getNode(ISD::MUL, SDLoc(N), VT,
1928                        N0.getOperand(0), C3);
1929   }
1930
1931   // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
1932   // use.
1933   {
1934     SDValue Sh(nullptr,0), Y(nullptr,0);
1935     // Check for both (mul (shl X, C), Y)  and  (mul Y, (shl X, C)).
1936     if (N0.getOpcode() == ISD::SHL &&
1937         (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1938                        isa<ConstantSDNode>(N0.getOperand(1))) &&
1939         N0.getNode()->hasOneUse()) {
1940       Sh = N0; Y = N1;
1941     } else if (N1.getOpcode() == ISD::SHL &&
1942                isa<ConstantSDNode>(N1.getOperand(1)) &&
1943                N1.getNode()->hasOneUse()) {
1944       Sh = N1; Y = N0;
1945     }
1946
1947     if (Sh.getNode()) {
1948       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
1949                                 Sh.getOperand(0), Y);
1950       return DAG.getNode(ISD::SHL, SDLoc(N), VT,
1951                          Mul, Sh.getOperand(1));
1952     }
1953   }
1954
1955   // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
1956   if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
1957       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1958                      isa<ConstantSDNode>(N0.getOperand(1))))
1959     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1960                        DAG.getNode(ISD::MUL, SDLoc(N0), VT,
1961                                    N0.getOperand(0), N1),
1962                        DAG.getNode(ISD::MUL, SDLoc(N1), VT,
1963                                    N0.getOperand(1), N1));
1964
1965   // reassociate mul
1966   SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1);
1967   if (RMUL.getNode())
1968     return RMUL;
1969
1970   return SDValue();
1971 }
1972
1973 SDValue DAGCombiner::visitSDIV(SDNode *N) {
1974   SDValue N0 = N->getOperand(0);
1975   SDValue N1 = N->getOperand(1);
1976   ConstantSDNode *N0C = isConstOrConstSplat(N0);
1977   ConstantSDNode *N1C = isConstOrConstSplat(N1);
1978   EVT VT = N->getValueType(0);
1979
1980   // fold vector ops
1981   if (VT.isVector()) {
1982     SDValue FoldedVOp = SimplifyVBinOp(N);
1983     if (FoldedVOp.getNode()) return FoldedVOp;
1984   }
1985
1986   // fold (sdiv c1, c2) -> c1/c2
1987   if (N0C && N1C && !N1C->isNullValue())
1988     return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C);
1989   // fold (sdiv X, 1) -> X
1990   if (N1C && N1C->getAPIntValue() == 1LL)
1991     return N0;
1992   // fold (sdiv X, -1) -> 0-X
1993   if (N1C && N1C->isAllOnesValue())
1994     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1995                        DAG.getConstant(0, VT), N0);
1996   // If we know the sign bits of both operands are zero, strength reduce to a
1997   // udiv instead.  Handles (X&15) /s 4 -> X&15 >> 2
1998   if (!VT.isVector()) {
1999     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2000       return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
2001                          N0, N1);
2002   }
2003
2004   // fold (sdiv X, pow2) -> simple ops after legalize
2005   if (N1C && !N1C->isNullValue() && (N1C->getAPIntValue().isPowerOf2() ||
2006                                      (-N1C->getAPIntValue()).isPowerOf2())) {
2007     // If dividing by powers of two is cheap, then don't perform the following
2008     // fold.
2009     if (TLI.isPow2DivCheap())
2010       return SDValue();
2011
2012     unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
2013
2014     // Splat the sign bit into the register
2015     SDValue SGN =
2016         DAG.getNode(ISD::SRA, SDLoc(N), VT, N0,
2017                     DAG.getConstant(VT.getScalarSizeInBits() - 1,
2018                                     getShiftAmountTy(N0.getValueType())));
2019     AddToWorkList(SGN.getNode());
2020
2021     // Add (N0 < 0) ? abs2 - 1 : 0;
2022     SDValue SRL =
2023         DAG.getNode(ISD::SRL, SDLoc(N), VT, SGN,
2024                     DAG.getConstant(VT.getScalarSizeInBits() - lg2,
2025                                     getShiftAmountTy(SGN.getValueType())));
2026     SDValue ADD = DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, SRL);
2027     AddToWorkList(SRL.getNode());
2028     AddToWorkList(ADD.getNode());    // Divide by pow2
2029     SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), VT, ADD,
2030                   DAG.getConstant(lg2, getShiftAmountTy(ADD.getValueType())));
2031
2032     // If we're dividing by a positive value, we're done.  Otherwise, we must
2033     // negate the result.
2034     if (N1C->getAPIntValue().isNonNegative())
2035       return SRA;
2036
2037     AddToWorkList(SRA.getNode());
2038     return DAG.getNode(ISD::SUB, SDLoc(N), VT, DAG.getConstant(0, VT), SRA);
2039   }
2040
2041   // if integer divide is expensive and we satisfy the requirements, emit an
2042   // alternate sequence.
2043   if (N1C && !TLI.isIntDivCheap()) {
2044     SDValue Op = BuildSDIV(N);
2045     if (Op.getNode()) return Op;
2046   }
2047
2048   // undef / X -> 0
2049   if (N0.getOpcode() == ISD::UNDEF)
2050     return DAG.getConstant(0, VT);
2051   // X / undef -> undef
2052   if (N1.getOpcode() == ISD::UNDEF)
2053     return N1;
2054
2055   return SDValue();
2056 }
2057
2058 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2059   SDValue N0 = N->getOperand(0);
2060   SDValue N1 = N->getOperand(1);
2061   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2062   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2063   EVT VT = N->getValueType(0);
2064
2065   // fold vector ops
2066   if (VT.isVector()) {
2067     SDValue FoldedVOp = SimplifyVBinOp(N);
2068     if (FoldedVOp.getNode()) return FoldedVOp;
2069   }
2070
2071   // fold (udiv c1, c2) -> c1/c2
2072   if (N0C && N1C && !N1C->isNullValue())
2073     return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C);
2074   // fold (udiv x, (1 << c)) -> x >>u c
2075   if (N1C && N1C->getAPIntValue().isPowerOf2())
2076     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0,
2077                        DAG.getConstant(N1C->getAPIntValue().logBase2(),
2078                                        getShiftAmountTy(N0.getValueType())));
2079   // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2080   if (N1.getOpcode() == ISD::SHL) {
2081     if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2082       if (SHC->getAPIntValue().isPowerOf2()) {
2083         EVT ADDVT = N1.getOperand(1).getValueType();
2084         SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N), ADDVT,
2085                                   N1.getOperand(1),
2086                                   DAG.getConstant(SHC->getAPIntValue()
2087                                                                   .logBase2(),
2088                                                   ADDVT));
2089         AddToWorkList(Add.getNode());
2090         return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, Add);
2091       }
2092     }
2093   }
2094   // fold (udiv x, c) -> alternate
2095   if (N1C && !TLI.isIntDivCheap()) {
2096     SDValue Op = BuildUDIV(N);
2097     if (Op.getNode()) return Op;
2098   }
2099
2100   // undef / X -> 0
2101   if (N0.getOpcode() == ISD::UNDEF)
2102     return DAG.getConstant(0, VT);
2103   // X / undef -> undef
2104   if (N1.getOpcode() == ISD::UNDEF)
2105     return N1;
2106
2107   return SDValue();
2108 }
2109
2110 SDValue DAGCombiner::visitSREM(SDNode *N) {
2111   SDValue N0 = N->getOperand(0);
2112   SDValue N1 = N->getOperand(1);
2113   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2114   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2115   EVT VT = N->getValueType(0);
2116
2117   // fold (srem c1, c2) -> c1%c2
2118   if (N0C && N1C && !N1C->isNullValue())
2119     return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C);
2120   // If we know the sign bits of both operands are zero, strength reduce to a
2121   // urem instead.  Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2122   if (!VT.isVector()) {
2123     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2124       return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
2125   }
2126
2127   // If X/C can be simplified by the division-by-constant logic, lower
2128   // X%C to the equivalent of X-X/C*C.
2129   if (N1C && !N1C->isNullValue()) {
2130     SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
2131     AddToWorkList(Div.getNode());
2132     SDValue OptimizedDiv = combine(Div.getNode());
2133     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2134       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2135                                 OptimizedDiv, N1);
2136       SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2137       AddToWorkList(Mul.getNode());
2138       return Sub;
2139     }
2140   }
2141
2142   // undef % X -> 0
2143   if (N0.getOpcode() == ISD::UNDEF)
2144     return DAG.getConstant(0, VT);
2145   // X % undef -> undef
2146   if (N1.getOpcode() == ISD::UNDEF)
2147     return N1;
2148
2149   return SDValue();
2150 }
2151
2152 SDValue DAGCombiner::visitUREM(SDNode *N) {
2153   SDValue N0 = N->getOperand(0);
2154   SDValue N1 = N->getOperand(1);
2155   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2156   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2157   EVT VT = N->getValueType(0);
2158
2159   // fold (urem c1, c2) -> c1%c2
2160   if (N0C && N1C && !N1C->isNullValue())
2161     return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C);
2162   // fold (urem x, pow2) -> (and x, pow2-1)
2163   if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
2164     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0,
2165                        DAG.getConstant(N1C->getAPIntValue()-1,VT));
2166   // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2167   if (N1.getOpcode() == ISD::SHL) {
2168     if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2169       if (SHC->getAPIntValue().isPowerOf2()) {
2170         SDValue Add =
2171           DAG.getNode(ISD::ADD, SDLoc(N), VT, N1,
2172                  DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
2173                                  VT));
2174         AddToWorkList(Add.getNode());
2175         return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, Add);
2176       }
2177     }
2178   }
2179
2180   // If X/C can be simplified by the division-by-constant logic, lower
2181   // X%C to the equivalent of X-X/C*C.
2182   if (N1C && !N1C->isNullValue()) {
2183     SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
2184     AddToWorkList(Div.getNode());
2185     SDValue OptimizedDiv = combine(Div.getNode());
2186     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2187       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2188                                 OptimizedDiv, N1);
2189       SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2190       AddToWorkList(Mul.getNode());
2191       return Sub;
2192     }
2193   }
2194
2195   // undef % X -> 0
2196   if (N0.getOpcode() == ISD::UNDEF)
2197     return DAG.getConstant(0, VT);
2198   // X % undef -> undef
2199   if (N1.getOpcode() == ISD::UNDEF)
2200     return N1;
2201
2202   return SDValue();
2203 }
2204
2205 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2206   SDValue N0 = N->getOperand(0);
2207   SDValue N1 = N->getOperand(1);
2208   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2209   EVT VT = N->getValueType(0);
2210   SDLoc DL(N);
2211
2212   // fold (mulhs x, 0) -> 0
2213   if (N1C && N1C->isNullValue())
2214     return N1;
2215   // fold (mulhs x, 1) -> (sra x, size(x)-1)
2216   if (N1C && N1C->getAPIntValue() == 1)
2217     return DAG.getNode(ISD::SRA, SDLoc(N), N0.getValueType(), N0,
2218                        DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2219                                        getShiftAmountTy(N0.getValueType())));
2220   // fold (mulhs x, undef) -> 0
2221   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2222     return DAG.getConstant(0, VT);
2223
2224   // If the type twice as wide is legal, transform the mulhs to a wider multiply
2225   // plus a shift.
2226   if (VT.isSimple() && !VT.isVector()) {
2227     MVT Simple = VT.getSimpleVT();
2228     unsigned SimpleSize = Simple.getSizeInBits();
2229     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2230     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2231       N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2232       N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2233       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2234       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2235             DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2236       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2237     }
2238   }
2239
2240   return SDValue();
2241 }
2242
2243 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2244   SDValue N0 = N->getOperand(0);
2245   SDValue N1 = N->getOperand(1);
2246   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2247   EVT VT = N->getValueType(0);
2248   SDLoc DL(N);
2249
2250   // fold (mulhu x, 0) -> 0
2251   if (N1C && N1C->isNullValue())
2252     return N1;
2253   // fold (mulhu x, 1) -> 0
2254   if (N1C && N1C->getAPIntValue() == 1)
2255     return DAG.getConstant(0, N0.getValueType());
2256   // fold (mulhu x, undef) -> 0
2257   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2258     return DAG.getConstant(0, VT);
2259
2260   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2261   // plus a shift.
2262   if (VT.isSimple() && !VT.isVector()) {
2263     MVT Simple = VT.getSimpleVT();
2264     unsigned SimpleSize = Simple.getSizeInBits();
2265     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2266     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2267       N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2268       N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2269       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2270       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2271             DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2272       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2273     }
2274   }
2275
2276   return SDValue();
2277 }
2278
2279 /// SimplifyNodeWithTwoResults - Perform optimizations common to nodes that
2280 /// compute two values. LoOp and HiOp give the opcodes for the two computations
2281 /// that are being performed. Return true if a simplification was made.
2282 ///
2283 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2284                                                 unsigned HiOp) {
2285   // If the high half is not needed, just compute the low half.
2286   bool HiExists = N->hasAnyUseOfValue(1);
2287   if (!HiExists &&
2288       (!LegalOperations ||
2289        TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
2290     SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0),
2291                               ArrayRef<SDUse>(N->op_begin(), N->op_end()));
2292     return CombineTo(N, Res, Res);
2293   }
2294
2295   // If the low half is not needed, just compute the high half.
2296   bool LoExists = N->hasAnyUseOfValue(0);
2297   if (!LoExists &&
2298       (!LegalOperations ||
2299        TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2300     SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1),
2301                               ArrayRef<SDUse>(N->op_begin(), N->op_end()));
2302     return CombineTo(N, Res, Res);
2303   }
2304
2305   // If both halves are used, return as it is.
2306   if (LoExists && HiExists)
2307     return SDValue();
2308
2309   // If the two computed results can be simplified separately, separate them.
2310   if (LoExists) {
2311     SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0),
2312                              ArrayRef<SDUse>(N->op_begin(), N->op_end()));
2313     AddToWorkList(Lo.getNode());
2314     SDValue LoOpt = combine(Lo.getNode());
2315     if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2316         (!LegalOperations ||
2317          TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2318       return CombineTo(N, LoOpt, LoOpt);
2319   }
2320
2321   if (HiExists) {
2322     SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1),
2323                              ArrayRef<SDUse>(N->op_begin(), N->op_end()));
2324     AddToWorkList(Hi.getNode());
2325     SDValue HiOpt = combine(Hi.getNode());
2326     if (HiOpt.getNode() && HiOpt != Hi &&
2327         (!LegalOperations ||
2328          TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2329       return CombineTo(N, HiOpt, HiOpt);
2330   }
2331
2332   return SDValue();
2333 }
2334
2335 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2336   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
2337   if (Res.getNode()) return Res;
2338
2339   EVT VT = N->getValueType(0);
2340   SDLoc DL(N);
2341
2342   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2343   // plus a shift.
2344   if (VT.isSimple() && !VT.isVector()) {
2345     MVT Simple = VT.getSimpleVT();
2346     unsigned SimpleSize = Simple.getSizeInBits();
2347     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2348     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2349       SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2350       SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2351       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2352       // Compute the high part as N1.
2353       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2354             DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2355       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2356       // Compute the low part as N0.
2357       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2358       return CombineTo(N, Lo, Hi);
2359     }
2360   }
2361
2362   return SDValue();
2363 }
2364
2365 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2366   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
2367   if (Res.getNode()) return Res;
2368
2369   EVT VT = N->getValueType(0);
2370   SDLoc DL(N);
2371
2372   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2373   // plus a shift.
2374   if (VT.isSimple() && !VT.isVector()) {
2375     MVT Simple = VT.getSimpleVT();
2376     unsigned SimpleSize = Simple.getSizeInBits();
2377     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2378     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2379       SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2380       SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2381       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2382       // Compute the high part as N1.
2383       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2384             DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2385       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2386       // Compute the low part as N0.
2387       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2388       return CombineTo(N, Lo, Hi);
2389     }
2390   }
2391
2392   return SDValue();
2393 }
2394
2395 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2396   // (smulo x, 2) -> (saddo x, x)
2397   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2398     if (C2->getAPIntValue() == 2)
2399       return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2400                          N->getOperand(0), N->getOperand(0));
2401
2402   return SDValue();
2403 }
2404
2405 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2406   // (umulo x, 2) -> (uaddo x, x)
2407   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2408     if (C2->getAPIntValue() == 2)
2409       return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2410                          N->getOperand(0), N->getOperand(0));
2411
2412   return SDValue();
2413 }
2414
2415 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2416   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
2417   if (Res.getNode()) return Res;
2418
2419   return SDValue();
2420 }
2421
2422 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2423   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
2424   if (Res.getNode()) return Res;
2425
2426   return SDValue();
2427 }
2428
2429 /// SimplifyBinOpWithSameOpcodeHands - If this is a binary operator with
2430 /// two operands of the same opcode, try to simplify it.
2431 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2432   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2433   EVT VT = N0.getValueType();
2434   assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2435
2436   // Bail early if none of these transforms apply.
2437   if (N0.getNode()->getNumOperands() == 0) return SDValue();
2438
2439   // For each of OP in AND/OR/XOR:
2440   // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2441   // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2442   // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2443   // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2444   //
2445   // do not sink logical op inside of a vector extend, since it may combine
2446   // into a vsetcc.
2447   EVT Op0VT = N0.getOperand(0).getValueType();
2448   if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2449        N0.getOpcode() == ISD::SIGN_EXTEND ||
2450        // Avoid infinite looping with PromoteIntBinOp.
2451        (N0.getOpcode() == ISD::ANY_EXTEND &&
2452         (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2453        (N0.getOpcode() == ISD::TRUNCATE &&
2454         (!TLI.isZExtFree(VT, Op0VT) ||
2455          !TLI.isTruncateFree(Op0VT, VT)) &&
2456         TLI.isTypeLegal(Op0VT))) &&
2457       !VT.isVector() &&
2458       Op0VT == N1.getOperand(0).getValueType() &&
2459       (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2460     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2461                                  N0.getOperand(0).getValueType(),
2462                                  N0.getOperand(0), N1.getOperand(0));
2463     AddToWorkList(ORNode.getNode());
2464     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2465   }
2466
2467   // For each of OP in SHL/SRL/SRA/AND...
2468   //   fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2469   //   fold (or  (OP x, z), (OP y, z)) -> (OP (or  x, y), z)
2470   //   fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2471   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2472        N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2473       N0.getOperand(1) == N1.getOperand(1)) {
2474     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2475                                  N0.getOperand(0).getValueType(),
2476                                  N0.getOperand(0), N1.getOperand(0));
2477     AddToWorkList(ORNode.getNode());
2478     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2479                        ORNode, N0.getOperand(1));
2480   }
2481
2482   // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2483   // Only perform this optimization after type legalization and before
2484   // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2485   // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2486   // we don't want to undo this promotion.
2487   // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2488   // on scalars.
2489   if ((N0.getOpcode() == ISD::BITCAST ||
2490        N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2491       Level == AfterLegalizeTypes) {
2492     SDValue In0 = N0.getOperand(0);
2493     SDValue In1 = N1.getOperand(0);
2494     EVT In0Ty = In0.getValueType();
2495     EVT In1Ty = In1.getValueType();
2496     SDLoc DL(N);
2497     // If both incoming values are integers, and the original types are the
2498     // same.
2499     if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2500       SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2501       SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2502       AddToWorkList(Op.getNode());
2503       return BC;
2504     }
2505   }
2506
2507   // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2508   // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2509   // If both shuffles use the same mask, and both shuffle within a single
2510   // vector, then it is worthwhile to move the swizzle after the operation.
2511   // The type-legalizer generates this pattern when loading illegal
2512   // vector types from memory. In many cases this allows additional shuffle
2513   // optimizations.
2514   // There are other cases where moving the shuffle after the xor/and/or
2515   // is profitable even if shuffles don't perform a swizzle.
2516   // If both shuffles use the same mask, and both shuffles have the same first
2517   // or second operand, then it might still be profitable to move the shuffle
2518   // after the xor/and/or operation.
2519   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
2520     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2521     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2522
2523     assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
2524            "Inputs to shuffles are not the same type");
2525
2526     // Check that both shuffles use the same mask. The masks are known to be of
2527     // the same length because the result vector type is the same.
2528     // Check also that shuffles have only one use to avoid introducing extra
2529     // instructions.
2530     if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2531         SVN0->getMask().equals(SVN1->getMask())) {
2532       SDValue ShOp = N0->getOperand(1);
2533
2534       // Don't try to fold this node if it requires introducing a
2535       // build vector of all zeros that might be illegal at this stage.
2536       if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2537         if (!LegalTypes)
2538           ShOp = DAG.getConstant(0, VT);
2539         else
2540           ShOp = SDValue();
2541       }
2542
2543       // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2544       // (OR  (shuf (A, C), shuf (B, C)) -> shuf (OR  (A, B), C)
2545       // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2546       if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2547         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2548                                       N0->getOperand(0), N1->getOperand(0));
2549         AddToWorkList(NewNode.getNode());
2550         return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2551                                     &SVN0->getMask()[0]);
2552       }
2553
2554       // Don't try to fold this node if it requires introducing a
2555       // build vector of all zeros that might be illegal at this stage.
2556       ShOp = N0->getOperand(0);
2557       if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2558         if (!LegalTypes)
2559           ShOp = DAG.getConstant(0, VT);
2560         else
2561           ShOp = SDValue();
2562       }
2563
2564       // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2565       // (OR  (shuf (C, A), shuf (C, B)) -> shuf (C, OR  (A, B))
2566       // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2567       if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2568         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2569                                       N0->getOperand(1), N1->getOperand(1));
2570         AddToWorkList(NewNode.getNode());
2571         return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2572                                     &SVN0->getMask()[0]);
2573       }
2574     }
2575   }
2576
2577   return SDValue();
2578 }
2579
2580 SDValue DAGCombiner::visitAND(SDNode *N) {
2581   SDValue N0 = N->getOperand(0);
2582   SDValue N1 = N->getOperand(1);
2583   SDValue LL, LR, RL, RR, CC0, CC1;
2584   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2585   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2586   EVT VT = N1.getValueType();
2587   unsigned BitWidth = VT.getScalarType().getSizeInBits();
2588
2589   // fold vector ops
2590   if (VT.isVector()) {
2591     SDValue FoldedVOp = SimplifyVBinOp(N);
2592     if (FoldedVOp.getNode()) return FoldedVOp;
2593
2594     // fold (and x, 0) -> 0, vector edition
2595     if (ISD::isBuildVectorAllZeros(N0.getNode()))
2596       return N0;
2597     if (ISD::isBuildVectorAllZeros(N1.getNode()))
2598       return N1;
2599
2600     // fold (and x, -1) -> x, vector edition
2601     if (ISD::isBuildVectorAllOnes(N0.getNode()))
2602       return N1;
2603     if (ISD::isBuildVectorAllOnes(N1.getNode()))
2604       return N0;
2605   }
2606
2607   // fold (and x, undef) -> 0
2608   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2609     return DAG.getConstant(0, VT);
2610   // fold (and c1, c2) -> c1&c2
2611   if (N0C && N1C)
2612     return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C);
2613   // canonicalize constant to RHS
2614   if (N0C && !N1C)
2615     return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
2616   // fold (and x, -1) -> x
2617   if (N1C && N1C->isAllOnesValue())
2618     return N0;
2619   // if (and x, c) is known to be zero, return 0
2620   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2621                                    APInt::getAllOnesValue(BitWidth)))
2622     return DAG.getConstant(0, VT);
2623   // reassociate and
2624   SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1);
2625   if (RAND.getNode())
2626     return RAND;
2627   // fold (and (or x, C), D) -> D if (C & D) == D
2628   if (N1C && N0.getOpcode() == ISD::OR)
2629     if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2630       if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2631         return N1;
2632   // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2633   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2634     SDValue N0Op0 = N0.getOperand(0);
2635     APInt Mask = ~N1C->getAPIntValue();
2636     Mask = Mask.trunc(N0Op0.getValueSizeInBits());
2637     if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2638       SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
2639                                  N0.getValueType(), N0Op0);
2640
2641       // Replace uses of the AND with uses of the Zero extend node.
2642       CombineTo(N, Zext);
2643
2644       // We actually want to replace all uses of the any_extend with the
2645       // zero_extend, to avoid duplicating things.  This will later cause this
2646       // AND to be folded.
2647       CombineTo(N0.getNode(), Zext);
2648       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2649     }
2650   }
2651   // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
2652   // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2653   // already be zero by virtue of the width of the base type of the load.
2654   //
2655   // the 'X' node here can either be nothing or an extract_vector_elt to catch
2656   // more cases.
2657   if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2658        N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2659       N0.getOpcode() == ISD::LOAD) {
2660     LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2661                                          N0 : N0.getOperand(0) );
2662
2663     // Get the constant (if applicable) the zero'th operand is being ANDed with.
2664     // This can be a pure constant or a vector splat, in which case we treat the
2665     // vector as a scalar and use the splat value.
2666     APInt Constant = APInt::getNullValue(1);
2667     if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2668       Constant = C->getAPIntValue();
2669     } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2670       APInt SplatValue, SplatUndef;
2671       unsigned SplatBitSize;
2672       bool HasAnyUndefs;
2673       bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2674                                              SplatBitSize, HasAnyUndefs);
2675       if (IsSplat) {
2676         // Undef bits can contribute to a possible optimisation if set, so
2677         // set them.
2678         SplatValue |= SplatUndef;
2679
2680         // The splat value may be something like "0x00FFFFFF", which means 0 for
2681         // the first vector value and FF for the rest, repeating. We need a mask
2682         // that will apply equally to all members of the vector, so AND all the
2683         // lanes of the constant together.
2684         EVT VT = Vector->getValueType(0);
2685         unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
2686
2687         // If the splat value has been compressed to a bitlength lower
2688         // than the size of the vector lane, we need to re-expand it to
2689         // the lane size.
2690         if (BitWidth > SplatBitSize)
2691           for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
2692                SplatBitSize < BitWidth;
2693                SplatBitSize = SplatBitSize * 2)
2694             SplatValue |= SplatValue.shl(SplatBitSize);
2695
2696         Constant = APInt::getAllOnesValue(BitWidth);
2697         for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
2698           Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
2699       }
2700     }
2701
2702     // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
2703     // actually legal and isn't going to get expanded, else this is a false
2704     // optimisation.
2705     bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
2706                                                     Load->getMemoryVT());
2707
2708     // Resize the constant to the same size as the original memory access before
2709     // extension. If it is still the AllOnesValue then this AND is completely
2710     // unneeded.
2711     Constant =
2712       Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
2713
2714     bool B;
2715     switch (Load->getExtensionType()) {
2716     default: B = false; break;
2717     case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
2718     case ISD::ZEXTLOAD:
2719     case ISD::NON_EXTLOAD: B = true; break;
2720     }
2721
2722     if (B && Constant.isAllOnesValue()) {
2723       // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
2724       // preserve semantics once we get rid of the AND.
2725       SDValue NewLoad(Load, 0);
2726       if (Load->getExtensionType() == ISD::EXTLOAD) {
2727         NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
2728                               Load->getValueType(0), SDLoc(Load),
2729                               Load->getChain(), Load->getBasePtr(),
2730                               Load->getOffset(), Load->getMemoryVT(),
2731                               Load->getMemOperand());
2732         // Replace uses of the EXTLOAD with the new ZEXTLOAD.
2733         if (Load->getNumValues() == 3) {
2734           // PRE/POST_INC loads have 3 values.
2735           SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
2736                            NewLoad.getValue(2) };
2737           CombineTo(Load, To, 3, true);
2738         } else {
2739           CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
2740         }
2741       }
2742
2743       // Fold the AND away, taking care not to fold to the old load node if we
2744       // replaced it.
2745       CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
2746
2747       return SDValue(N, 0); // Return N so it doesn't get rechecked!
2748     }
2749   }
2750   // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2751   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2752     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2753     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2754
2755     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2756         LL.getValueType().isInteger()) {
2757       // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2758       if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
2759         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2760                                      LR.getValueType(), LL, RL);
2761         AddToWorkList(ORNode.getNode());
2762         return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2763       }
2764       // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2765       if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
2766         SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2767                                       LR.getValueType(), LL, RL);
2768         AddToWorkList(ANDNode.getNode());
2769         return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
2770       }
2771       // fold (and (setgt X,  -1), (setgt Y,  -1)) -> (setgt (or X, Y), -1)
2772       if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
2773         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2774                                      LR.getValueType(), LL, RL);
2775         AddToWorkList(ORNode.getNode());
2776         return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2777       }
2778     }
2779     // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2780     if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2781         Op0 == Op1 && LL.getValueType().isInteger() &&
2782       Op0 == ISD::SETNE && ((cast<ConstantSDNode>(LR)->isNullValue() &&
2783                                  cast<ConstantSDNode>(RR)->isAllOnesValue()) ||
2784                                 (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
2785                                  cast<ConstantSDNode>(RR)->isNullValue()))) {
2786       SDValue ADDNode = DAG.getNode(ISD::ADD, SDLoc(N0), LL.getValueType(),
2787                                     LL, DAG.getConstant(1, LL.getValueType()));
2788       AddToWorkList(ADDNode.getNode());
2789       return DAG.getSetCC(SDLoc(N), VT, ADDNode,
2790                           DAG.getConstant(2, LL.getValueType()), ISD::SETUGE);
2791     }
2792     // canonicalize equivalent to ll == rl
2793     if (LL == RR && LR == RL) {
2794       Op1 = ISD::getSetCCSwappedOperands(Op1);
2795       std::swap(RL, RR);
2796     }
2797     if (LL == RL && LR == RR) {
2798       bool isInteger = LL.getValueType().isInteger();
2799       ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2800       if (Result != ISD::SETCC_INVALID &&
2801           (!LegalOperations ||
2802            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2803             TLI.isOperationLegal(ISD::SETCC,
2804                             getSetCCResultType(N0.getSimpleValueType())))))
2805         return DAG.getSetCC(SDLoc(N), N0.getValueType(),
2806                             LL, LR, Result);
2807     }
2808   }
2809
2810   // Simplify: (and (op x...), (op y...))  -> (op (and x, y))
2811   if (N0.getOpcode() == N1.getOpcode()) {
2812     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
2813     if (Tmp.getNode()) return Tmp;
2814   }
2815
2816   // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
2817   // fold (and (sra)) -> (and (srl)) when possible.
2818   if (!VT.isVector() &&
2819       SimplifyDemandedBits(SDValue(N, 0)))
2820     return SDValue(N, 0);
2821
2822   // fold (zext_inreg (extload x)) -> (zextload x)
2823   if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
2824     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2825     EVT MemVT = LN0->getMemoryVT();
2826     // If we zero all the possible extended bits, then we can turn this into
2827     // a zextload if we are running before legalize or the operation is legal.
2828     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2829     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2830                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2831         ((!LegalOperations && !LN0->isVolatile()) ||
2832          TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2833       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2834                                        LN0->getChain(), LN0->getBasePtr(),
2835                                        MemVT, LN0->getMemOperand());
2836       AddToWorkList(N);
2837       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2838       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2839     }
2840   }
2841   // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
2842   if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
2843       N0.hasOneUse()) {
2844     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2845     EVT MemVT = LN0->getMemoryVT();
2846     // If we zero all the possible extended bits, then we can turn this into
2847     // a zextload if we are running before legalize or the operation is legal.
2848     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2849     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2850                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2851         ((!LegalOperations && !LN0->isVolatile()) ||
2852          TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2853       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2854                                        LN0->getChain(), LN0->getBasePtr(),
2855                                        MemVT, LN0->getMemOperand());
2856       AddToWorkList(N);
2857       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2858       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2859     }
2860   }
2861
2862   // fold (and (load x), 255) -> (zextload x, i8)
2863   // fold (and (extload x, i16), 255) -> (zextload x, i8)
2864   // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
2865   if (N1C && (N0.getOpcode() == ISD::LOAD ||
2866               (N0.getOpcode() == ISD::ANY_EXTEND &&
2867                N0.getOperand(0).getOpcode() == ISD::LOAD))) {
2868     bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
2869     LoadSDNode *LN0 = HasAnyExt
2870       ? cast<LoadSDNode>(N0.getOperand(0))
2871       : cast<LoadSDNode>(N0);
2872     if (LN0->getExtensionType() != ISD::SEXTLOAD &&
2873         LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
2874       uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
2875       if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
2876         EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
2877         EVT LoadedVT = LN0->getMemoryVT();
2878
2879         if (ExtVT == LoadedVT &&
2880             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2881           EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2882
2883           SDValue NewLoad =
2884             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2885                            LN0->getChain(), LN0->getBasePtr(), ExtVT,
2886                            LN0->getMemOperand());
2887           AddToWorkList(N);
2888           CombineTo(LN0, NewLoad, NewLoad.getValue(1));
2889           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2890         }
2891
2892         // Do not change the width of a volatile load.
2893         // Do not generate loads of non-round integer types since these can
2894         // be expensive (and would be wrong if the type is not byte sized).
2895         if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
2896             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2897           EVT PtrType = LN0->getOperand(1).getValueType();
2898
2899           unsigned Alignment = LN0->getAlignment();
2900           SDValue NewPtr = LN0->getBasePtr();
2901
2902           // For big endian targets, we need to add an offset to the pointer
2903           // to load the correct bytes.  For little endian systems, we merely
2904           // need to read fewer bytes from the same pointer.
2905           if (TLI.isBigEndian()) {
2906             unsigned LVTStoreBytes = LoadedVT.getStoreSize();
2907             unsigned EVTStoreBytes = ExtVT.getStoreSize();
2908             unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
2909             NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0), PtrType,
2910                                  NewPtr, DAG.getConstant(PtrOff, PtrType));
2911             Alignment = MinAlign(Alignment, PtrOff);
2912           }
2913
2914           AddToWorkList(NewPtr.getNode());
2915
2916           EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2917           SDValue Load =
2918             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2919                            LN0->getChain(), NewPtr,
2920                            LN0->getPointerInfo(),
2921                            ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
2922                            Alignment, LN0->getTBAAInfo());
2923           AddToWorkList(N);
2924           CombineTo(LN0, Load, Load.getValue(1));
2925           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2926         }
2927       }
2928     }
2929   }
2930
2931   if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2932       VT.getSizeInBits() <= 64) {
2933     if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2934       APInt ADDC = ADDI->getAPIntValue();
2935       if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2936         // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
2937         // immediate for an add, but it is legal if its top c2 bits are set,
2938         // transform the ADD so the immediate doesn't need to be materialized
2939         // in a register.
2940         if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
2941           APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
2942                                              SRLI->getZExtValue());
2943           if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
2944             ADDC |= Mask;
2945             if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2946               SDValue NewAdd =
2947                 DAG.getNode(ISD::ADD, SDLoc(N0), VT,
2948                             N0.getOperand(0), DAG.getConstant(ADDC, VT));
2949               CombineTo(N0.getNode(), NewAdd);
2950               return SDValue(N, 0); // Return N so it doesn't get rechecked!
2951             }
2952           }
2953         }
2954       }
2955     }
2956   }
2957
2958   // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
2959   if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
2960     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
2961                                        N0.getOperand(1), false);
2962     if (BSwap.getNode())
2963       return BSwap;
2964   }
2965
2966   return SDValue();
2967 }
2968
2969 /// MatchBSwapHWord - Match (a >> 8) | (a << 8) as (bswap a) >> 16
2970 ///
2971 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
2972                                         bool DemandHighBits) {
2973   if (!LegalOperations)
2974     return SDValue();
2975
2976   EVT VT = N->getValueType(0);
2977   if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
2978     return SDValue();
2979   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
2980     return SDValue();
2981
2982   // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
2983   bool LookPassAnd0 = false;
2984   bool LookPassAnd1 = false;
2985   if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
2986       std::swap(N0, N1);
2987   if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
2988       std::swap(N0, N1);
2989   if (N0.getOpcode() == ISD::AND) {
2990     if (!N0.getNode()->hasOneUse())
2991       return SDValue();
2992     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2993     if (!N01C || N01C->getZExtValue() != 0xFF00)
2994       return SDValue();
2995     N0 = N0.getOperand(0);
2996     LookPassAnd0 = true;
2997   }
2998
2999   if (N1.getOpcode() == ISD::AND) {
3000     if (!N1.getNode()->hasOneUse())
3001       return SDValue();
3002     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3003     if (!N11C || N11C->getZExtValue() != 0xFF)
3004       return SDValue();
3005     N1 = N1.getOperand(0);
3006     LookPassAnd1 = true;
3007   }
3008
3009   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3010     std::swap(N0, N1);
3011   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3012     return SDValue();
3013   if (!N0.getNode()->hasOneUse() ||
3014       !N1.getNode()->hasOneUse())
3015     return SDValue();
3016
3017   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3018   ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3019   if (!N01C || !N11C)
3020     return SDValue();
3021   if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3022     return SDValue();
3023
3024   // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3025   SDValue N00 = N0->getOperand(0);
3026   if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3027     if (!N00.getNode()->hasOneUse())
3028       return SDValue();
3029     ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3030     if (!N001C || N001C->getZExtValue() != 0xFF)
3031       return SDValue();
3032     N00 = N00.getOperand(0);
3033     LookPassAnd0 = true;
3034   }
3035
3036   SDValue N10 = N1->getOperand(0);
3037   if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3038     if (!N10.getNode()->hasOneUse())
3039       return SDValue();
3040     ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3041     if (!N101C || N101C->getZExtValue() != 0xFF00)
3042       return SDValue();
3043     N10 = N10.getOperand(0);
3044     LookPassAnd1 = true;
3045   }
3046
3047   if (N00 != N10)
3048     return SDValue();
3049
3050   // Make sure everything beyond the low halfword gets set to zero since the SRL
3051   // 16 will clear the top bits.
3052   unsigned OpSizeInBits = VT.getSizeInBits();
3053   if (DemandHighBits && OpSizeInBits > 16) {
3054     // If the left-shift isn't masked out then the only way this is a bswap is
3055     // if all bits beyond the low 8 are 0. In that case the entire pattern
3056     // reduces to a left shift anyway: leave it for other parts of the combiner.
3057     if (!LookPassAnd0)
3058       return SDValue();
3059
3060     // However, if the right shift isn't masked out then it might be because
3061     // it's not needed. See if we can spot that too.
3062     if (!LookPassAnd1 &&
3063         !DAG.MaskedValueIsZero(
3064             N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3065       return SDValue();
3066   }
3067
3068   SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
3069   if (OpSizeInBits > 16)
3070     Res = DAG.getNode(ISD::SRL, SDLoc(N), VT, Res,
3071                       DAG.getConstant(OpSizeInBits-16, getShiftAmountTy(VT)));
3072   return Res;
3073 }
3074
3075 /// isBSwapHWordElement - Return true if the specified node is an element
3076 /// that makes up a 32-bit packed halfword byteswap. i.e.
3077 /// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
3078 static bool isBSwapHWordElement(SDValue N, SmallVectorImpl<SDNode *> &Parts) {
3079   if (!N.getNode()->hasOneUse())
3080     return false;
3081
3082   unsigned Opc = N.getOpcode();
3083   if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3084     return false;
3085
3086   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3087   if (!N1C)
3088     return false;
3089
3090   unsigned Num;
3091   switch (N1C->getZExtValue()) {
3092   default:
3093     return false;
3094   case 0xFF:       Num = 0; break;
3095   case 0xFF00:     Num = 1; break;
3096   case 0xFF0000:   Num = 2; break;
3097   case 0xFF000000: Num = 3; break;
3098   }
3099
3100   // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3101   SDValue N0 = N.getOperand(0);
3102   if (Opc == ISD::AND) {
3103     if (Num == 0 || Num == 2) {
3104       // (x >> 8) & 0xff
3105       // (x >> 8) & 0xff0000
3106       if (N0.getOpcode() != ISD::SRL)
3107         return false;
3108       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3109       if (!C || C->getZExtValue() != 8)
3110         return false;
3111     } else {
3112       // (x << 8) & 0xff00
3113       // (x << 8) & 0xff000000
3114       if (N0.getOpcode() != ISD::SHL)
3115         return false;
3116       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3117       if (!C || C->getZExtValue() != 8)
3118         return false;
3119     }
3120   } else if (Opc == ISD::SHL) {
3121     // (x & 0xff) << 8
3122     // (x & 0xff0000) << 8
3123     if (Num != 0 && Num != 2)
3124       return false;
3125     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3126     if (!C || C->getZExtValue() != 8)
3127       return false;
3128   } else { // Opc == ISD::SRL
3129     // (x & 0xff00) >> 8
3130     // (x & 0xff000000) >> 8
3131     if (Num != 1 && Num != 3)
3132       return false;
3133     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3134     if (!C || C->getZExtValue() != 8)
3135       return false;
3136   }
3137
3138   if (Parts[Num])
3139     return false;
3140
3141   Parts[Num] = N0.getOperand(0).getNode();
3142   return true;
3143 }
3144
3145 /// MatchBSwapHWord - Match a 32-bit packed halfword bswap. That is
3146 /// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
3147 /// => (rotl (bswap x), 16)
3148 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3149   if (!LegalOperations)
3150     return SDValue();
3151
3152   EVT VT = N->getValueType(0);
3153   if (VT != MVT::i32)
3154     return SDValue();
3155   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3156     return SDValue();
3157
3158   SmallVector<SDNode*,4> Parts(4, (SDNode*)nullptr);
3159   // Look for either
3160   // (or (or (and), (and)), (or (and), (and)))
3161   // (or (or (or (and), (and)), (and)), (and))
3162   if (N0.getOpcode() != ISD::OR)
3163     return SDValue();
3164   SDValue N00 = N0.getOperand(0);
3165   SDValue N01 = N0.getOperand(1);
3166
3167   if (N1.getOpcode() == ISD::OR &&
3168       N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3169     // (or (or (and), (and)), (or (and), (and)))
3170     SDValue N000 = N00.getOperand(0);
3171     if (!isBSwapHWordElement(N000, Parts))
3172       return SDValue();
3173
3174     SDValue N001 = N00.getOperand(1);
3175     if (!isBSwapHWordElement(N001, Parts))
3176       return SDValue();
3177     SDValue N010 = N01.getOperand(0);
3178     if (!isBSwapHWordElement(N010, Parts))
3179       return SDValue();
3180     SDValue N011 = N01.getOperand(1);
3181     if (!isBSwapHWordElement(N011, Parts))
3182       return SDValue();
3183   } else {
3184     // (or (or (or (and), (and)), (and)), (and))
3185     if (!isBSwapHWordElement(N1, Parts))
3186       return SDValue();
3187     if (!isBSwapHWordElement(N01, Parts))
3188       return SDValue();
3189     if (N00.getOpcode() != ISD::OR)
3190       return SDValue();
3191     SDValue N000 = N00.getOperand(0);
3192     if (!isBSwapHWordElement(N000, Parts))
3193       return SDValue();
3194     SDValue N001 = N00.getOperand(1);
3195     if (!isBSwapHWordElement(N001, Parts))
3196       return SDValue();
3197   }
3198
3199   // Make sure the parts are all coming from the same node.
3200   if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3201     return SDValue();
3202
3203   SDValue BSwap = DAG.getNode(ISD::BSWAP, SDLoc(N), VT,
3204                               SDValue(Parts[0],0));
3205
3206   // Result of the bswap should be rotated by 16. If it's not legal, then
3207   // do  (x << 16) | (x >> 16).
3208   SDValue ShAmt = DAG.getConstant(16, getShiftAmountTy(VT));
3209   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3210     return DAG.getNode(ISD::ROTL, SDLoc(N), VT, BSwap, ShAmt);
3211   if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3212     return DAG.getNode(ISD::ROTR, SDLoc(N), VT, BSwap, ShAmt);
3213   return DAG.getNode(ISD::OR, SDLoc(N), VT,
3214                      DAG.getNode(ISD::SHL, SDLoc(N), VT, BSwap, ShAmt),
3215                      DAG.getNode(ISD::SRL, SDLoc(N), VT, BSwap, ShAmt));
3216 }
3217
3218 SDValue DAGCombiner::visitOR(SDNode *N) {
3219   SDValue N0 = N->getOperand(0);
3220   SDValue N1 = N->getOperand(1);
3221   SDValue LL, LR, RL, RR, CC0, CC1;
3222   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3223   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3224   EVT VT = N1.getValueType();
3225
3226   // fold vector ops
3227   if (VT.isVector()) {
3228     SDValue FoldedVOp = SimplifyVBinOp(N);
3229     if (FoldedVOp.getNode()) return FoldedVOp;
3230
3231     // fold (or x, 0) -> x, vector edition
3232     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3233       return N1;
3234     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3235       return N0;
3236
3237     // fold (or x, -1) -> -1, vector edition
3238     if (ISD::isBuildVectorAllOnes(N0.getNode()))
3239       return N0;
3240     if (ISD::isBuildVectorAllOnes(N1.getNode()))
3241       return N1;
3242
3243     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
3244     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
3245     // Do this only if the resulting shuffle is legal.
3246     if (isa<ShuffleVectorSDNode>(N0) &&
3247         isa<ShuffleVectorSDNode>(N1) &&
3248         // Avoid folding a node with illegal type.
3249         TLI.isTypeLegal(VT) &&
3250         N0->getOperand(1) == N1->getOperand(1) &&
3251         ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
3252       bool CanFold = true;
3253       unsigned NumElts = VT.getVectorNumElements();
3254       const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3255       const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3256       // We construct two shuffle masks:
3257       // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
3258       // and N1 as the second operand.
3259       // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
3260       // and N0 as the second operand.
3261       // We do this because OR is commutable and therefore there might be
3262       // two ways to fold this node into a shuffle.
3263       SmallVector<int,4> Mask1;
3264       SmallVector<int,4> Mask2;
3265
3266       for (unsigned i = 0; i != NumElts && CanFold; ++i) {
3267         int M0 = SV0->getMaskElt(i);
3268         int M1 = SV1->getMaskElt(i);
3269
3270         // Both shuffle indexes are undef. Propagate Undef.
3271         if (M0 < 0 && M1 < 0) {
3272           Mask1.push_back(M0);
3273           Mask2.push_back(M0);
3274           continue;
3275         }
3276
3277         if (M0 < 0 || M1 < 0 ||
3278             (M0 < (int)NumElts && M1 < (int)NumElts) ||
3279             (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
3280           CanFold = false;
3281           break;
3282         }
3283
3284         Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
3285         Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
3286       }
3287
3288       if (CanFold) {
3289         // Fold this sequence only if the resulting shuffle is 'legal'.
3290         if (TLI.isShuffleMaskLegal(Mask1, VT))
3291           return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
3292                                       N1->getOperand(0), &Mask1[0]);
3293         if (TLI.isShuffleMaskLegal(Mask2, VT))
3294           return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
3295                                       N0->getOperand(0), &Mask2[0]);
3296       }
3297     }
3298   }
3299
3300   // fold (or x, undef) -> -1
3301   if (!LegalOperations &&
3302       (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3303     EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3304     return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
3305   }
3306   // fold (or c1, c2) -> c1|c2
3307   if (N0C && N1C)
3308     return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C);
3309   // canonicalize constant to RHS
3310   if (N0C && !N1C)
3311     return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3312   // fold (or x, 0) -> x
3313   if (N1C && N1C->isNullValue())
3314     return N0;
3315   // fold (or x, -1) -> -1
3316   if (N1C && N1C->isAllOnesValue())
3317     return N1;
3318   // fold (or x, c) -> c iff (x & ~c) == 0
3319   if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3320     return N1;
3321
3322   // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3323   SDValue BSwap = MatchBSwapHWord(N, N0, N1);
3324   if (BSwap.getNode())
3325     return BSwap;
3326   BSwap = MatchBSwapHWordLow(N, N0, N1);
3327   if (BSwap.getNode())
3328     return BSwap;
3329
3330   // reassociate or
3331   SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1);
3332   if (ROR.getNode())
3333     return ROR;
3334   // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3335   // iff (c1 & c2) == 0.
3336   if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3337              isa<ConstantSDNode>(N0.getOperand(1))) {
3338     ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3339     if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3340       SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1);
3341       if (!COR.getNode())
3342         return SDValue();
3343       return DAG.getNode(ISD::AND, SDLoc(N), VT,
3344                          DAG.getNode(ISD::OR, SDLoc(N0), VT,
3345                                      N0.getOperand(0), N1), COR);
3346     }
3347   }
3348   // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3349   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3350     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3351     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3352
3353     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
3354         LL.getValueType().isInteger()) {
3355       // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3356       // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3357       if (cast<ConstantSDNode>(LR)->isNullValue() &&
3358           (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3359         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3360                                      LR.getValueType(), LL, RL);
3361         AddToWorkList(ORNode.getNode());
3362         return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
3363       }
3364       // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3365       // fold (or (setgt X, -1), (setgt Y  -1)) -> (setgt (and X, Y), -1)
3366       if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
3367           (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3368         SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3369                                       LR.getValueType(), LL, RL);
3370         AddToWorkList(ANDNode.getNode());
3371         return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
3372       }
3373     }
3374     // canonicalize equivalent to ll == rl
3375     if (LL == RR && LR == RL) {
3376       Op1 = ISD::getSetCCSwappedOperands(Op1);
3377       std::swap(RL, RR);
3378     }
3379     if (LL == RL && LR == RR) {
3380       bool isInteger = LL.getValueType().isInteger();
3381       ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3382       if (Result != ISD::SETCC_INVALID &&
3383           (!LegalOperations ||
3384            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3385             TLI.isOperationLegal(ISD::SETCC,
3386               getSetCCResultType(N0.getValueType())))))
3387         return DAG.getSetCC(SDLoc(N), N0.getValueType(),
3388                             LL, LR, Result);
3389     }
3390   }
3391
3392   // Simplify: (or (op x...), (op y...))  -> (op (or x, y))
3393   if (N0.getOpcode() == N1.getOpcode()) {
3394     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3395     if (Tmp.getNode()) return Tmp;
3396   }
3397
3398   // (or (and X, C1), (and Y, C2))  -> (and (or X, Y), C3) if possible.
3399   if (N0.getOpcode() == ISD::AND &&
3400       N1.getOpcode() == ISD::AND &&
3401       N0.getOperand(1).getOpcode() == ISD::Constant &&
3402       N1.getOperand(1).getOpcode() == ISD::Constant &&
3403       // Don't increase # computations.
3404       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3405     // We can only do this xform if we know that bits from X that are set in C2
3406     // but not in C1 are already zero.  Likewise for Y.
3407     const APInt &LHSMask =
3408       cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3409     const APInt &RHSMask =
3410       cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
3411
3412     if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3413         DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3414       SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3415                               N0.getOperand(0), N1.getOperand(0));
3416       return DAG.getNode(ISD::AND, SDLoc(N), VT, X,
3417                          DAG.getConstant(LHSMask | RHSMask, VT));
3418     }
3419   }
3420
3421   // See if this is some rotate idiom.
3422   if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3423     return SDValue(Rot, 0);
3424
3425   // Simplify the operands using demanded-bits information.
3426   if (!VT.isVector() &&
3427       SimplifyDemandedBits(SDValue(N, 0)))
3428     return SDValue(N, 0);
3429
3430   return SDValue();
3431 }
3432
3433 /// MatchRotateHalf - Match "(X shl/srl V1) & V2" where V2 may not be present.
3434 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3435   if (Op.getOpcode() == ISD::AND) {
3436     if (isa<ConstantSDNode>(Op.getOperand(1))) {
3437       Mask = Op.getOperand(1);
3438       Op = Op.getOperand(0);
3439     } else {
3440       return false;
3441     }
3442   }
3443
3444   if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3445     Shift = Op;
3446     return true;
3447   }
3448
3449   return false;
3450 }
3451
3452 // Return true if we can prove that, whenever Neg and Pos are both in the
3453 // range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos).  This means that
3454 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3455 //
3456 //     (or (shift1 X, Neg), (shift2 X, Pos))
3457 //
3458 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3459 // in direction shift1 by Neg.  The range [0, OpSize) means that we only need
3460 // to consider shift amounts with defined behavior.
3461 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) {
3462   // If OpSize is a power of 2 then:
3463   //
3464   //  (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1)
3465   //  (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize).
3466   //
3467   // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check
3468   // for the stronger condition:
3469   //
3470   //     Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1)    [A]
3471   //
3472   // for all Neg and Pos.  Since Neg & (OpSize - 1) == Neg' & (OpSize - 1)
3473   // we can just replace Neg with Neg' for the rest of the function.
3474   //
3475   // In other cases we check for the even stronger condition:
3476   //
3477   //     Neg == OpSize - Pos                                    [B]
3478   //
3479   // for all Neg and Pos.  Note that the (or ...) then invokes undefined
3480   // behavior if Pos == 0 (and consequently Neg == OpSize).
3481   //
3482   // We could actually use [A] whenever OpSize is a power of 2, but the
3483   // only extra cases that it would match are those uninteresting ones
3484   // where Neg and Pos are never in range at the same time.  E.g. for
3485   // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3486   // as well as (sub 32, Pos), but:
3487   //
3488   //     (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3489   //
3490   // always invokes undefined behavior for 32-bit X.
3491   //
3492   // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise.
3493   unsigned MaskLoBits = 0;
3494   if (Neg.getOpcode() == ISD::AND &&
3495       isPowerOf2_64(OpSize) &&
3496       Neg.getOperand(1).getOpcode() == ISD::Constant &&
3497       cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) {
3498     Neg = Neg.getOperand(0);
3499     MaskLoBits = Log2_64(OpSize);
3500   }
3501
3502   // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3503   if (Neg.getOpcode() != ISD::SUB)
3504     return 0;
3505   ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0));
3506   if (!NegC)
3507     return 0;
3508   SDValue NegOp1 = Neg.getOperand(1);
3509
3510   // On the RHS of [A], if Pos is Pos' & (OpSize - 1), just replace Pos with
3511   // Pos'.  The truncation is redundant for the purpose of the equality.
3512   if (MaskLoBits &&
3513       Pos.getOpcode() == ISD::AND &&
3514       Pos.getOperand(1).getOpcode() == ISD::Constant &&
3515       cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() == OpSize - 1)
3516     Pos = Pos.getOperand(0);
3517
3518   // The condition we need is now:
3519   //
3520   //     (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask
3521   //
3522   // If NegOp1 == Pos then we need:
3523   //
3524   //              OpSize & Mask == NegC & Mask
3525   //
3526   // (because "x & Mask" is a truncation and distributes through subtraction).
3527   APInt Width;
3528   if (Pos == NegOp1)
3529     Width = NegC->getAPIntValue();
3530   // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3531   // Then the condition we want to prove becomes:
3532   //
3533   //     (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask
3534   //
3535   // which, again because "x & Mask" is a truncation, becomes:
3536   //
3537   //                NegC & Mask == (OpSize - PosC) & Mask
3538   //              OpSize & Mask == (NegC + PosC) & Mask
3539   else if (Pos.getOpcode() == ISD::ADD &&
3540            Pos.getOperand(0) == NegOp1 &&
3541            Pos.getOperand(1).getOpcode() == ISD::Constant)
3542     Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() +
3543              NegC->getAPIntValue());
3544   else
3545     return false;
3546
3547   // Now we just need to check that OpSize & Mask == Width & Mask.
3548   if (MaskLoBits)
3549     // Opsize & Mask is 0 since Mask is Opsize - 1.
3550     return Width.getLoBits(MaskLoBits) == 0;
3551   return Width == OpSize;
3552 }
3553
3554 // A subroutine of MatchRotate used once we have found an OR of two opposite
3555 // shifts of Shifted.  If Neg == <operand size> - Pos then the OR reduces
3556 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3557 // former being preferred if supported.  InnerPos and InnerNeg are Pos and
3558 // Neg with outer conversions stripped away.
3559 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3560                                        SDValue Neg, SDValue InnerPos,
3561                                        SDValue InnerNeg, unsigned PosOpcode,
3562                                        unsigned NegOpcode, SDLoc DL) {
3563   // fold (or (shl x, (*ext y)),
3564   //          (srl x, (*ext (sub 32, y)))) ->
3565   //   (rotl x, y) or (rotr x, (sub 32, y))
3566   //
3567   // fold (or (shl x, (*ext (sub 32, y))),
3568   //          (srl x, (*ext y))) ->
3569   //   (rotr x, y) or (rotl x, (sub 32, y))
3570   EVT VT = Shifted.getValueType();
3571   if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) {
3572     bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3573     return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3574                        HasPos ? Pos : Neg).getNode();
3575   }
3576
3577   return nullptr;
3578 }
3579
3580 // MatchRotate - Handle an 'or' of two operands.  If this is one of the many
3581 // idioms for rotate, and if the target supports rotation instructions, generate
3582 // a rot[lr].
3583 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
3584   // Must be a legal type.  Expanded 'n promoted things won't work with rotates.
3585   EVT VT = LHS.getValueType();
3586   if (!TLI.isTypeLegal(VT)) return nullptr;
3587
3588   // The target must have at least one rotate flavor.
3589   bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3590   bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3591   if (!HasROTL && !HasROTR) return nullptr;
3592
3593   // Match "(X shl/srl V1) & V2" where V2 may not be present.
3594   SDValue LHSShift;   // The shift.
3595   SDValue LHSMask;    // AND value if any.
3596   if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3597     return nullptr; // Not part of a rotate.
3598
3599   SDValue RHSShift;   // The shift.
3600   SDValue RHSMask;    // AND value if any.
3601   if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3602     return nullptr; // Not part of a rotate.
3603
3604   if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3605     return nullptr;   // Not shifting the same value.
3606
3607   if (LHSShift.getOpcode() == RHSShift.getOpcode())
3608     return nullptr;   // Shifts must disagree.
3609
3610   // Canonicalize shl to left side in a shl/srl pair.
3611   if (RHSShift.getOpcode() == ISD::SHL) {
3612     std::swap(LHS, RHS);
3613     std::swap(LHSShift, RHSShift);
3614     std::swap(LHSMask , RHSMask );
3615   }
3616
3617   unsigned OpSizeInBits = VT.getSizeInBits();
3618   SDValue LHSShiftArg = LHSShift.getOperand(0);
3619   SDValue LHSShiftAmt = LHSShift.getOperand(1);
3620   SDValue RHSShiftArg = RHSShift.getOperand(0);
3621   SDValue RHSShiftAmt = RHSShift.getOperand(1);
3622
3623   // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3624   // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
3625   if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3626       RHSShiftAmt.getOpcode() == ISD::Constant) {
3627     uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3628     uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
3629     if ((LShVal + RShVal) != OpSizeInBits)
3630       return nullptr;
3631
3632     SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3633                               LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3634
3635     // If there is an AND of either shifted operand, apply it to the result.
3636     if (LHSMask.getNode() || RHSMask.getNode()) {
3637       APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
3638
3639       if (LHSMask.getNode()) {
3640         APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3641         Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
3642       }
3643       if (RHSMask.getNode()) {
3644         APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3645         Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
3646       }
3647
3648       Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT));
3649     }
3650
3651     return Rot.getNode();
3652   }
3653
3654   // If there is a mask here, and we have a variable shift, we can't be sure
3655   // that we're masking out the right stuff.
3656   if (LHSMask.getNode() || RHSMask.getNode())
3657     return nullptr;
3658
3659   // If the shift amount is sign/zext/any-extended just peel it off.
3660   SDValue LExtOp0 = LHSShiftAmt;
3661   SDValue RExtOp0 = RHSShiftAmt;
3662   if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3663        LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3664        LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3665        LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3666       (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3667        RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3668        RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3669        RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
3670     LExtOp0 = LHSShiftAmt.getOperand(0);
3671     RExtOp0 = RHSShiftAmt.getOperand(0);
3672   }
3673
3674   SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
3675                                    LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
3676   if (TryL)
3677     return TryL;
3678
3679   SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
3680                                    RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
3681   if (TryR)
3682     return TryR;
3683
3684   return nullptr;
3685 }
3686
3687 SDValue DAGCombiner::visitXOR(SDNode *N) {
3688   SDValue N0 = N->getOperand(0);
3689   SDValue N1 = N->getOperand(1);
3690   SDValue LHS, RHS, CC;
3691   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3692   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3693   EVT VT = N0.getValueType();
3694
3695   // fold vector ops
3696   if (VT.isVector()) {
3697     SDValue FoldedVOp = SimplifyVBinOp(N);
3698     if (FoldedVOp.getNode()) return FoldedVOp;
3699
3700     // fold (xor x, 0) -> x, vector edition
3701     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3702       return N1;
3703     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3704       return N0;
3705   }
3706
3707   // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3708   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3709     return DAG.getConstant(0, VT);
3710   // fold (xor x, undef) -> undef
3711   if (N0.getOpcode() == ISD::UNDEF)
3712     return N0;
3713   if (N1.getOpcode() == ISD::UNDEF)
3714     return N1;
3715   // fold (xor c1, c2) -> c1^c2
3716   if (N0C && N1C)
3717     return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
3718   // canonicalize constant to RHS
3719   if (N0C && !N1C)
3720     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
3721   // fold (xor x, 0) -> x
3722   if (N1C && N1C->isNullValue())
3723     return N0;
3724   // reassociate xor
3725   SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1);
3726   if (RXOR.getNode())
3727     return RXOR;
3728
3729   // fold !(x cc y) -> (x !cc y)
3730   if (N1C && N1C->getAPIntValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) {
3731     bool isInt = LHS.getValueType().isInteger();
3732     ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3733                                                isInt);
3734
3735     if (!LegalOperations ||
3736         TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
3737       switch (N0.getOpcode()) {
3738       default:
3739         llvm_unreachable("Unhandled SetCC Equivalent!");
3740       case ISD::SETCC:
3741         return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
3742       case ISD::SELECT_CC:
3743         return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
3744                                N0.getOperand(3), NotCC);
3745       }
3746     }
3747   }
3748
3749   // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
3750   if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
3751       N0.getNode()->hasOneUse() &&
3752       isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
3753     SDValue V = N0.getOperand(0);
3754     V = DAG.getNode(ISD::XOR, SDLoc(N0), V.getValueType(), V,
3755                     DAG.getConstant(1, V.getValueType()));
3756     AddToWorkList(V.getNode());
3757     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
3758   }
3759
3760   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
3761   if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
3762       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3763     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3764     if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
3765       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3766       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3767       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3768       AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
3769       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3770     }
3771   }
3772   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
3773   if (N1C && N1C->isAllOnesValue() &&
3774       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3775     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3776     if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
3777       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3778       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3779       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3780       AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
3781       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3782     }
3783   }
3784   // fold (xor (and x, y), y) -> (and (not x), y)
3785   if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3786       N0->getOperand(1) == N1) {
3787     SDValue X = N0->getOperand(0);
3788     SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
3789     AddToWorkList(NotX.getNode());
3790     return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
3791   }
3792   // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
3793   if (N1C && N0.getOpcode() == ISD::XOR) {
3794     ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
3795     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3796     if (N00C)
3797       return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(1),
3798                          DAG.getConstant(N1C->getAPIntValue() ^
3799                                          N00C->getAPIntValue(), VT));
3800     if (N01C)
3801       return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(0),
3802                          DAG.getConstant(N1C->getAPIntValue() ^
3803                                          N01C->getAPIntValue(), VT));
3804   }
3805   // fold (xor x, x) -> 0
3806   if (N0 == N1)
3807     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
3808
3809   // Simplify: xor (op x...), (op y...)  -> (op (xor x, y))
3810   if (N0.getOpcode() == N1.getOpcode()) {
3811     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3812     if (Tmp.getNode()) return Tmp;
3813   }
3814
3815   // Simplify the expression using non-local knowledge.
3816   if (!VT.isVector() &&
3817       SimplifyDemandedBits(SDValue(N, 0)))
3818     return SDValue(N, 0);
3819
3820   return SDValue();
3821 }
3822
3823 /// visitShiftByConstant - Handle transforms common to the three shifts, when
3824 /// the shift amount is a constant.
3825 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
3826   // We can't and shouldn't fold opaque constants.
3827   if (Amt->isOpaque())
3828     return SDValue();
3829
3830   SDNode *LHS = N->getOperand(0).getNode();
3831   if (!LHS->hasOneUse()) return SDValue();
3832
3833   // We want to pull some binops through shifts, so that we have (and (shift))
3834   // instead of (shift (and)), likewise for add, or, xor, etc.  This sort of
3835   // thing happens with address calculations, so it's important to canonicalize
3836   // it.
3837   bool HighBitSet = false;  // Can we transform this if the high bit is set?
3838
3839   switch (LHS->getOpcode()) {
3840   default: return SDValue();
3841   case ISD::OR:
3842   case ISD::XOR:
3843     HighBitSet = false; // We can only transform sra if the high bit is clear.
3844     break;
3845   case ISD::AND:
3846     HighBitSet = true;  // We can only transform sra if the high bit is set.
3847     break;
3848   case ISD::ADD:
3849     if (N->getOpcode() != ISD::SHL)
3850       return SDValue(); // only shl(add) not sr[al](add).
3851     HighBitSet = false; // We can only transform sra if the high bit is clear.
3852     break;
3853   }
3854
3855   // We require the RHS of the binop to be a constant and not opaque as well.
3856   ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
3857   if (!BinOpCst || BinOpCst->isOpaque()) return SDValue();
3858
3859   // FIXME: disable this unless the input to the binop is a shift by a constant.
3860   // If it is not a shift, it pessimizes some common cases like:
3861   //
3862   //    void foo(int *X, int i) { X[i & 1235] = 1; }
3863   //    int bar(int *X, int i) { return X[i & 255]; }
3864   SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
3865   if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
3866        BinOpLHSVal->getOpcode() != ISD::SRA &&
3867        BinOpLHSVal->getOpcode() != ISD::SRL) ||
3868       !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
3869     return SDValue();
3870
3871   EVT VT = N->getValueType(0);
3872
3873   // If this is a signed shift right, and the high bit is modified by the
3874   // logical operation, do not perform the transformation. The highBitSet
3875   // boolean indicates the value of the high bit of the constant which would
3876   // cause it to be modified for this operation.
3877   if (N->getOpcode() == ISD::SRA) {
3878     bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
3879     if (BinOpRHSSignSet != HighBitSet)
3880       return SDValue();
3881   }
3882
3883   if (!TLI.isDesirableToCommuteWithShift(LHS))
3884     return SDValue();
3885
3886   // Fold the constants, shifting the binop RHS by the shift amount.
3887   SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
3888                                N->getValueType(0),
3889                                LHS->getOperand(1), N->getOperand(1));
3890   assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
3891
3892   // Create the new shift.
3893   SDValue NewShift = DAG.getNode(N->getOpcode(),
3894                                  SDLoc(LHS->getOperand(0)),
3895                                  VT, LHS->getOperand(0), N->getOperand(1));
3896
3897   // Create the new binop.
3898   return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
3899 }
3900
3901 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
3902   assert(N->getOpcode() == ISD::TRUNCATE);
3903   assert(N->getOperand(0).getOpcode() == ISD::AND);
3904
3905   // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
3906   if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
3907     SDValue N01 = N->getOperand(0).getOperand(1);
3908
3909     if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
3910       EVT TruncVT = N->getValueType(0);
3911       SDValue N00 = N->getOperand(0).getOperand(0);
3912       APInt TruncC = N01C->getAPIntValue();
3913       TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
3914
3915       return DAG.getNode(ISD::AND, SDLoc(N), TruncVT,
3916                          DAG.getNode(ISD::TRUNCATE, SDLoc(N), TruncVT, N00),
3917                          DAG.getConstant(TruncC, TruncVT));
3918     }
3919   }
3920
3921   return SDValue();
3922 }
3923
3924 SDValue DAGCombiner::visitRotate(SDNode *N) {
3925   // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
3926   if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
3927       N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
3928     SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode());
3929     if (NewOp1.getNode())
3930       return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
3931                          N->getOperand(0), NewOp1);
3932   }
3933   return SDValue();
3934 }
3935
3936 SDValue DAGCombiner::visitSHL(SDNode *N) {
3937   SDValue N0 = N->getOperand(0);
3938   SDValue N1 = N->getOperand(1);
3939   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3940   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3941   EVT VT = N0.getValueType();
3942   unsigned OpSizeInBits = VT.getScalarSizeInBits();
3943
3944   // fold vector ops
3945   if (VT.isVector()) {
3946     SDValue FoldedVOp = SimplifyVBinOp(N);
3947     if (FoldedVOp.getNode()) return FoldedVOp;
3948
3949     BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
3950     // If setcc produces all-one true value then:
3951     // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
3952     if (N1CV && N1CV->isConstant()) {
3953       if (N0.getOpcode() == ISD::AND) {
3954         SDValue N00 = N0->getOperand(0);
3955         SDValue N01 = N0->getOperand(1);
3956         BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
3957
3958         if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
3959             TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
3960                 TargetLowering::ZeroOrNegativeOneBooleanContent) {
3961           SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, VT, N01CV, N1CV);
3962           if (C.getNode())
3963             return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
3964         }
3965       } else {
3966         N1C = isConstOrConstSplat(N1);
3967       }
3968     }
3969   }
3970
3971   // fold (shl c1, c2) -> c1<<c2
3972   if (N0C && N1C)
3973     return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
3974   // fold (shl 0, x) -> 0
3975   if (N0C && N0C->isNullValue())
3976     return N0;
3977   // fold (shl x, c >= size(x)) -> undef
3978   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
3979     return DAG.getUNDEF(VT);
3980   // fold (shl x, 0) -> x
3981   if (N1C && N1C->isNullValue())
3982     return N0;
3983   // fold (shl undef, x) -> 0
3984   if (N0.getOpcode() == ISD::UNDEF)
3985     return DAG.getConstant(0, VT);
3986   // if (shl x, c) is known to be zero, return 0
3987   if (DAG.MaskedValueIsZero(SDValue(N, 0),
3988                             APInt::getAllOnesValue(OpSizeInBits)))
3989     return DAG.getConstant(0, VT);
3990   // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
3991   if (N1.getOpcode() == ISD::TRUNCATE &&
3992       N1.getOperand(0).getOpcode() == ISD::AND) {
3993     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
3994     if (NewOp1.getNode())
3995       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
3996   }
3997
3998   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
3999     return SDValue(N, 0);
4000
4001   // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
4002   if (N1C && N0.getOpcode() == ISD::SHL) {
4003     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4004       uint64_t c1 = N0C1->getZExtValue();
4005       uint64_t c2 = N1C->getZExtValue();
4006       if (c1 + c2 >= OpSizeInBits)
4007         return DAG.getConstant(0, VT);
4008       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4009                          DAG.getConstant(c1 + c2, N1.getValueType()));
4010     }
4011   }
4012
4013   // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4014   // For this to be valid, the second form must not preserve any of the bits
4015   // that are shifted out by the inner shift in the first form.  This means
4016   // the outer shift size must be >= the number of bits added by the ext.
4017   // As a corollary, we don't care what kind of ext it is.
4018   if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4019               N0.getOpcode() == ISD::ANY_EXTEND ||
4020               N0.getOpcode() == ISD::SIGN_EXTEND) &&
4021       N0.getOperand(0).getOpcode() == ISD::SHL) {
4022     SDValue N0Op0 = N0.getOperand(0);
4023     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4024       uint64_t c1 = N0Op0C1->getZExtValue();
4025       uint64_t c2 = N1C->getZExtValue();
4026       EVT InnerShiftVT = N0Op0.getValueType();
4027       uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4028       if (c2 >= OpSizeInBits - InnerShiftSize) {
4029         if (c1 + c2 >= OpSizeInBits)
4030           return DAG.getConstant(0, VT);
4031         return DAG.getNode(ISD::SHL, SDLoc(N0), VT,
4032                            DAG.getNode(N0.getOpcode(), SDLoc(N0), VT,
4033                                        N0Op0->getOperand(0)),
4034                            DAG.getConstant(c1 + c2, N1.getValueType()));
4035       }
4036     }
4037   }
4038
4039   // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4040   // Only fold this if the inner zext has no other uses to avoid increasing
4041   // the total number of instructions.
4042   if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
4043       N0.getOperand(0).getOpcode() == ISD::SRL) {
4044     SDValue N0Op0 = N0.getOperand(0);
4045     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4046       uint64_t c1 = N0Op0C1->getZExtValue();
4047       if (c1 < VT.getScalarSizeInBits()) {
4048         uint64_t c2 = N1C->getZExtValue();
4049         if (c1 == c2) {
4050           SDValue NewOp0 = N0.getOperand(0);
4051           EVT CountVT = NewOp0.getOperand(1).getValueType();
4052           SDValue NewSHL = DAG.getNode(ISD::SHL, SDLoc(N), NewOp0.getValueType(),
4053                                        NewOp0, DAG.getConstant(c2, CountVT));
4054           AddToWorkList(NewSHL.getNode());
4055           return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4056         }
4057       }
4058     }
4059   }
4060
4061   // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4062   //                               (and (srl x, (sub c1, c2), MASK)
4063   // Only fold this if the inner shift has no other uses -- if it does, folding
4064   // this will increase the total number of instructions.
4065   if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4066     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4067       uint64_t c1 = N0C1->getZExtValue();
4068       if (c1 < OpSizeInBits) {
4069         uint64_t c2 = N1C->getZExtValue();
4070         APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4071         SDValue Shift;
4072         if (c2 > c1) {
4073           Mask = Mask.shl(c2 - c1);
4074           Shift = DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4075                               DAG.getConstant(c2 - c1, N1.getValueType()));
4076         } else {
4077           Mask = Mask.lshr(c1 - c2);
4078           Shift = DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4079                               DAG.getConstant(c1 - c2, N1.getValueType()));
4080         }
4081         return DAG.getNode(ISD::AND, SDLoc(N0), VT, Shift,
4082                            DAG.getConstant(Mask, VT));
4083       }
4084     }
4085   }
4086   // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
4087   if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
4088     unsigned BitSize = VT.getScalarSizeInBits();
4089     SDValue HiBitsMask =
4090       DAG.getConstant(APInt::getHighBitsSet(BitSize,
4091                                             BitSize - N1C->getZExtValue()), VT);
4092     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4093                        HiBitsMask);
4094   }
4095
4096   if (N1C) {
4097     SDValue NewSHL = visitShiftByConstant(N, N1C);
4098     if (NewSHL.getNode())
4099       return NewSHL;
4100   }
4101
4102   return SDValue();
4103 }
4104
4105 SDValue DAGCombiner::visitSRA(SDNode *N) {
4106   SDValue N0 = N->getOperand(0);
4107   SDValue N1 = N->getOperand(1);
4108   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4109   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4110   EVT VT = N0.getValueType();
4111   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4112
4113   // fold vector ops
4114   if (VT.isVector()) {
4115     SDValue FoldedVOp = SimplifyVBinOp(N);
4116     if (FoldedVOp.getNode()) return FoldedVOp;
4117
4118     N1C = isConstOrConstSplat(N1);
4119   }
4120
4121   // fold (sra c1, c2) -> (sra c1, c2)
4122   if (N0C && N1C)
4123     return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
4124   // fold (sra 0, x) -> 0
4125   if (N0C && N0C->isNullValue())
4126     return N0;
4127   // fold (sra -1, x) -> -1
4128   if (N0C && N0C->isAllOnesValue())
4129     return N0;
4130   // fold (sra x, (setge c, size(x))) -> undef
4131   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4132     return DAG.getUNDEF(VT);
4133   // fold (sra x, 0) -> x
4134   if (N1C && N1C->isNullValue())
4135     return N0;
4136   // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4137   // sext_inreg.
4138   if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
4139     unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
4140     EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4141     if (VT.isVector())
4142       ExtVT = EVT::getVectorVT(*DAG.getContext(),
4143                                ExtVT, VT.getVectorNumElements());
4144     if ((!LegalOperations ||
4145          TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
4146       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
4147                          N0.getOperand(0), DAG.getValueType(ExtVT));
4148   }
4149
4150   // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
4151   if (N1C && N0.getOpcode() == ISD::SRA) {
4152     if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
4153       unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
4154       if (Sum >= OpSizeInBits)
4155         Sum = OpSizeInBits - 1;
4156       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0.getOperand(0),
4157                          DAG.getConstant(Sum, N1.getValueType()));
4158     }
4159   }
4160
4161   // fold (sra (shl X, m), (sub result_size, n))
4162   // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
4163   // result_size - n != m.
4164   // If truncate is free for the target sext(shl) is likely to result in better
4165   // code.
4166   if (N0.getOpcode() == ISD::SHL && N1C) {
4167     // Get the two constanst of the shifts, CN0 = m, CN = n.
4168     const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4169     if (N01C) {
4170       LLVMContext &Ctx = *DAG.getContext();
4171       // Determine what the truncate's result bitsize and type would be.
4172       EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4173
4174       if (VT.isVector())
4175         TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4176
4177       // Determine the residual right-shift amount.
4178       signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
4179
4180       // If the shift is not a no-op (in which case this should be just a sign
4181       // extend already), the truncated to type is legal, sign_extend is legal
4182       // on that type, and the truncate to that type is both legal and free,
4183       // perform the transform.
4184       if ((ShiftAmt > 0) &&
4185           TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4186           TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
4187           TLI.isTruncateFree(VT, TruncVT)) {
4188
4189           SDValue Amt = DAG.getConstant(ShiftAmt,
4190               getShiftAmountTy(N0.getOperand(0).getValueType()));
4191           SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), VT,
4192                                       N0.getOperand(0), Amt);
4193           SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), TruncVT,
4194                                       Shift);
4195           return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N),
4196                              N->getValueType(0), Trunc);
4197       }
4198     }
4199   }
4200
4201   // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
4202   if (N1.getOpcode() == ISD::TRUNCATE &&
4203       N1.getOperand(0).getOpcode() == ISD::AND) {
4204     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4205     if (NewOp1.getNode())
4206       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
4207   }
4208
4209   // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
4210   //      if c1 is equal to the number of bits the trunc removes
4211   if (N0.getOpcode() == ISD::TRUNCATE &&
4212       (N0.getOperand(0).getOpcode() == ISD::SRL ||
4213        N0.getOperand(0).getOpcode() == ISD::SRA) &&
4214       N0.getOperand(0).hasOneUse() &&
4215       N0.getOperand(0).getOperand(1).hasOneUse() &&
4216       N1C) {
4217     SDValue N0Op0 = N0.getOperand(0);
4218     if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4219       unsigned LargeShiftVal = LargeShift->getZExtValue();
4220       EVT LargeVT = N0Op0.getValueType();
4221
4222       if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4223         SDValue Amt =
4224           DAG.getConstant(LargeShiftVal + N1C->getZExtValue(),
4225                           getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4226         SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), LargeVT,
4227                                   N0Op0.getOperand(0), Amt);
4228         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, SRA);
4229       }
4230     }
4231   }
4232
4233   // Simplify, based on bits shifted out of the LHS.
4234   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4235     return SDValue(N, 0);
4236
4237
4238   // If the sign bit is known to be zero, switch this to a SRL.
4239   if (DAG.SignBitIsZero(N0))
4240     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
4241
4242   if (N1C) {
4243     SDValue NewSRA = visitShiftByConstant(N, N1C);
4244     if (NewSRA.getNode())
4245       return NewSRA;
4246   }
4247
4248   return SDValue();
4249 }
4250
4251 SDValue DAGCombiner::visitSRL(SDNode *N) {
4252   SDValue N0 = N->getOperand(0);
4253   SDValue N1 = N->getOperand(1);
4254   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4255   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4256   EVT VT = N0.getValueType();
4257   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4258
4259   // fold vector ops
4260   if (VT.isVector()) {
4261     SDValue FoldedVOp = SimplifyVBinOp(N);
4262     if (FoldedVOp.getNode()) return FoldedVOp;
4263
4264     N1C = isConstOrConstSplat(N1);
4265   }
4266
4267   // fold (srl c1, c2) -> c1 >>u c2
4268   if (N0C && N1C)
4269     return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C);
4270   // fold (srl 0, x) -> 0
4271   if (N0C && N0C->isNullValue())
4272     return N0;
4273   // fold (srl x, c >= size(x)) -> undef
4274   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4275     return DAG.getUNDEF(VT);
4276   // fold (srl x, 0) -> x
4277   if (N1C && N1C->isNullValue())
4278     return N0;
4279   // if (srl x, c) is known to be zero, return 0
4280   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4281                                    APInt::getAllOnesValue(OpSizeInBits)))
4282     return DAG.getConstant(0, VT);
4283
4284   // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
4285   if (N1C && N0.getOpcode() == ISD::SRL) {
4286     if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
4287       uint64_t c1 = N01C->getZExtValue();
4288       uint64_t c2 = N1C->getZExtValue();
4289       if (c1 + c2 >= OpSizeInBits)
4290         return DAG.getConstant(0, VT);
4291       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4292                          DAG.getConstant(c1 + c2, N1.getValueType()));
4293     }
4294   }
4295
4296   // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4297   if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4298       N0.getOperand(0).getOpcode() == ISD::SRL &&
4299       isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4300     uint64_t c1 =
4301       cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4302     uint64_t c2 = N1C->getZExtValue();
4303     EVT InnerShiftVT = N0.getOperand(0).getValueType();
4304     EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4305     uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
4306     // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4307     if (c1 + OpSizeInBits == InnerShiftSize) {
4308       if (c1 + c2 >= InnerShiftSize)
4309         return DAG.getConstant(0, VT);
4310       return DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT,
4311                          DAG.getNode(ISD::SRL, SDLoc(N0), InnerShiftVT,
4312                                      N0.getOperand(0)->getOperand(0),
4313                                      DAG.getConstant(c1 + c2, ShiftCountVT)));
4314     }
4315   }
4316
4317   // fold (srl (shl x, c), c) -> (and x, cst2)
4318   if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4319     unsigned BitSize = N0.getScalarValueSizeInBits();
4320     if (BitSize <= 64) {
4321       uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4322       return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4323                          DAG.getConstant(~0ULL >> ShAmt, VT));
4324     }
4325   }
4326
4327   // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4328   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4329     // Shifting in all undef bits?
4330     EVT SmallVT = N0.getOperand(0).getValueType();
4331     unsigned BitSize = SmallVT.getScalarSizeInBits();
4332     if (N1C->getZExtValue() >= BitSize)
4333       return DAG.getUNDEF(VT);
4334
4335     if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4336       uint64_t ShiftAmt = N1C->getZExtValue();
4337       SDValue SmallShift = DAG.getNode(ISD::SRL, SDLoc(N0), SmallVT,
4338                                        N0.getOperand(0),
4339                           DAG.getConstant(ShiftAmt, getShiftAmountTy(SmallVT)));
4340       AddToWorkList(SmallShift.getNode());
4341       APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
4342       return DAG.getNode(ISD::AND, SDLoc(N), VT,
4343                          DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, SmallShift),
4344                          DAG.getConstant(Mask, VT));
4345     }
4346   }
4347
4348   // fold (srl (sra X, Y), 31) -> (srl X, 31).  This srl only looks at the sign
4349   // bit, which is unmodified by sra.
4350   if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
4351     if (N0.getOpcode() == ISD::SRA)
4352       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4353   }
4354
4355   // fold (srl (ctlz x), "5") -> x  iff x has one bit set (the low bit).
4356   if (N1C && N0.getOpcode() == ISD::CTLZ &&
4357       N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
4358     APInt KnownZero, KnownOne;
4359     DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne);
4360
4361     // If any of the input bits are KnownOne, then the input couldn't be all
4362     // zeros, thus the result of the srl will always be zero.
4363     if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
4364
4365     // If all of the bits input the to ctlz node are known to be zero, then
4366     // the result of the ctlz is "32" and the result of the shift is one.
4367     APInt UnknownBits = ~KnownZero;
4368     if (UnknownBits == 0) return DAG.getConstant(1, VT);
4369
4370     // Otherwise, check to see if there is exactly one bit input to the ctlz.
4371     if ((UnknownBits & (UnknownBits - 1)) == 0) {
4372       // Okay, we know that only that the single bit specified by UnknownBits
4373       // could be set on input to the CTLZ node. If this bit is set, the SRL
4374       // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4375       // to an SRL/XOR pair, which is likely to simplify more.
4376       unsigned ShAmt = UnknownBits.countTrailingZeros();
4377       SDValue Op = N0.getOperand(0);
4378
4379       if (ShAmt) {
4380         Op = DAG.getNode(ISD::SRL, SDLoc(N0), VT, Op,
4381                   DAG.getConstant(ShAmt, getShiftAmountTy(Op.getValueType())));
4382         AddToWorkList(Op.getNode());
4383       }
4384
4385       return DAG.getNode(ISD::XOR, SDLoc(N), VT,
4386                          Op, DAG.getConstant(1, VT));
4387     }
4388   }
4389
4390   // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4391   if (N1.getOpcode() == ISD::TRUNCATE &&
4392       N1.getOperand(0).getOpcode() == ISD::AND) {
4393     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4394     if (NewOp1.getNode())
4395       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
4396   }
4397
4398   // fold operands of srl based on knowledge that the low bits are not
4399   // demanded.
4400   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4401     return SDValue(N, 0);
4402
4403   if (N1C) {
4404     SDValue NewSRL = visitShiftByConstant(N, N1C);
4405     if (NewSRL.getNode())
4406       return NewSRL;
4407   }
4408
4409   // Attempt to convert a srl of a load into a narrower zero-extending load.
4410   SDValue NarrowLoad = ReduceLoadWidth(N);
4411   if (NarrowLoad.getNode())
4412     return NarrowLoad;
4413
4414   // Here is a common situation. We want to optimize:
4415   //
4416   //   %a = ...
4417   //   %b = and i32 %a, 2
4418   //   %c = srl i32 %b, 1
4419   //   brcond i32 %c ...
4420   //
4421   // into
4422   //
4423   //   %a = ...
4424   //   %b = and %a, 2
4425   //   %c = setcc eq %b, 0
4426   //   brcond %c ...
4427   //
4428   // However when after the source operand of SRL is optimized into AND, the SRL
4429   // itself may not be optimized further. Look for it and add the BRCOND into
4430   // the worklist.
4431   if (N->hasOneUse()) {
4432     SDNode *Use = *N->use_begin();
4433     if (Use->getOpcode() == ISD::BRCOND)
4434       AddToWorkList(Use);
4435     else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4436       // Also look pass the truncate.
4437       Use = *Use->use_begin();
4438       if (Use->getOpcode() == ISD::BRCOND)
4439         AddToWorkList(Use);
4440     }
4441   }
4442
4443   return SDValue();
4444 }
4445
4446 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4447   SDValue N0 = N->getOperand(0);
4448   EVT VT = N->getValueType(0);
4449
4450   // fold (ctlz c1) -> c2
4451   if (isa<ConstantSDNode>(N0))
4452     return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
4453   return SDValue();
4454 }
4455
4456 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4457   SDValue N0 = N->getOperand(0);
4458   EVT VT = N->getValueType(0);
4459
4460   // fold (ctlz_zero_undef c1) -> c2
4461   if (isa<ConstantSDNode>(N0))
4462     return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4463   return SDValue();
4464 }
4465
4466 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4467   SDValue N0 = N->getOperand(0);
4468   EVT VT = N->getValueType(0);
4469
4470   // fold (cttz c1) -> c2
4471   if (isa<ConstantSDNode>(N0))
4472     return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
4473   return SDValue();
4474 }
4475
4476 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4477   SDValue N0 = N->getOperand(0);
4478   EVT VT = N->getValueType(0);
4479
4480   // fold (cttz_zero_undef c1) -> c2
4481   if (isa<ConstantSDNode>(N0))
4482     return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4483   return SDValue();
4484 }
4485
4486 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4487   SDValue N0 = N->getOperand(0);
4488   EVT VT = N->getValueType(0);
4489
4490   // fold (ctpop c1) -> c2
4491   if (isa<ConstantSDNode>(N0))
4492     return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
4493   return SDValue();
4494 }
4495
4496 SDValue DAGCombiner::visitSELECT(SDNode *N) {
4497   SDValue N0 = N->getOperand(0);
4498   SDValue N1 = N->getOperand(1);
4499   SDValue N2 = N->getOperand(2);
4500   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4501   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4502   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
4503   EVT VT = N->getValueType(0);
4504   EVT VT0 = N0.getValueType();
4505
4506   // fold (select C, X, X) -> X
4507   if (N1 == N2)
4508     return N1;
4509   // fold (select true, X, Y) -> X
4510   if (N0C && !N0C->isNullValue())
4511     return N1;
4512   // fold (select false, X, Y) -> Y
4513   if (N0C && N0C->isNullValue())
4514     return N2;
4515   // fold (select C, 1, X) -> (or C, X)
4516   if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
4517     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4518   // fold (select C, 0, 1) -> (xor C, 1)
4519   // We can't do this reliably if integer based booleans have different contents
4520   // to floating point based booleans. This is because we can't tell whether we
4521   // have an integer-based boolean or a floating-point-based boolean unless we
4522   // can find the SETCC that produced it and inspect its operands. This is
4523   // fairly easy if C is the SETCC node, but it can potentially be
4524   // undiscoverable (or not reasonably discoverable). For example, it could be
4525   // in another basic block or it could require searching a complicated
4526   // expression.
4527   if (VT.isInteger() &&
4528       (VT0 == MVT::i1 || (VT0.isInteger() &&
4529                           TLI.getBooleanContents(false, false) ==
4530                               TLI.getBooleanContents(false, true) &&
4531                           TLI.getBooleanContents(false, false) ==
4532                               TargetLowering::ZeroOrOneBooleanContent)) &&
4533       N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
4534     SDValue XORNode;
4535     if (VT == VT0)
4536       return DAG.getNode(ISD::XOR, SDLoc(N), VT0,
4537                          N0, DAG.getConstant(1, VT0));
4538     XORNode = DAG.getNode(ISD::XOR, SDLoc(N0), VT0,
4539                           N0, DAG.getConstant(1, VT0));
4540     AddToWorkList(XORNode.getNode());
4541     if (VT.bitsGT(VT0))
4542       return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4543     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
4544   }
4545   // fold (select C, 0, X) -> (and (not C), X)
4546   if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
4547     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4548     AddToWorkList(NOTNode.getNode());
4549     return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
4550   }
4551   // fold (select C, X, 1) -> (or (not C), X)
4552   if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
4553     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4554     AddToWorkList(NOTNode.getNode());
4555     return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
4556   }
4557   // fold (select C, X, 0) -> (and C, X)
4558   if (VT == MVT::i1 && N2C && N2C->isNullValue())
4559     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4560   // fold (select X, X, Y) -> (or X, Y)
4561   // fold (select X, 1, Y) -> (or X, Y)
4562   if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
4563     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4564   // fold (select X, Y, X) -> (and X, Y)
4565   // fold (select X, Y, 0) -> (and X, Y)
4566   if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
4567     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4568
4569   // If we can fold this based on the true/false value, do so.
4570   if (SimplifySelectOps(N, N1, N2))
4571     return SDValue(N, 0);  // Don't revisit N.
4572
4573   // fold selects based on a setcc into other things, such as min/max/abs
4574   if (N0.getOpcode() == ISD::SETCC) {
4575     if ((!LegalOperations &&
4576          TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
4577         TLI.isOperationLegal(ISD::SELECT_CC, VT))
4578       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
4579                          N0.getOperand(0), N0.getOperand(1),
4580                          N1, N2, N0.getOperand(2));
4581     return SimplifySelect(SDLoc(N), N0, N1, N2);
4582   }
4583
4584   return SDValue();
4585 }
4586
4587 static
4588 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
4589   SDLoc DL(N);
4590   EVT LoVT, HiVT;
4591   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
4592
4593   // Split the inputs.
4594   SDValue Lo, Hi, LL, LH, RL, RH;
4595   std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
4596   std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
4597
4598   Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
4599   Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
4600
4601   return std::make_pair(Lo, Hi);
4602 }
4603
4604 // This function assumes all the vselect's arguments are CONCAT_VECTOR
4605 // nodes and that the condition is a BV of ConstantSDNodes (or undefs).
4606 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
4607   SDLoc dl(N);
4608   SDValue Cond = N->getOperand(0);
4609   SDValue LHS = N->getOperand(1);
4610   SDValue RHS = N->getOperand(2);
4611   MVT VT = N->getSimpleValueType(0);
4612   int NumElems = VT.getVectorNumElements();
4613   assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
4614          RHS.getOpcode() == ISD::CONCAT_VECTORS &&
4615          Cond.getOpcode() == ISD::BUILD_VECTOR);
4616
4617   // We're sure we have an even number of elements due to the
4618   // concat_vectors we have as arguments to vselect.
4619   // Skip BV elements until we find one that's not an UNDEF
4620   // After we find an UNDEF element, keep looping until we get to half the
4621   // length of the BV and see if all the non-undef nodes are the same.
4622   ConstantSDNode *BottomHalf = nullptr;
4623   for (int i = 0; i < NumElems / 2; ++i) {
4624     if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
4625       continue;
4626
4627     if (BottomHalf == nullptr)
4628       BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
4629     else if (Cond->getOperand(i).getNode() != BottomHalf)
4630       return SDValue();
4631   }
4632
4633   // Do the same for the second half of the BuildVector
4634   ConstantSDNode *TopHalf = nullptr;
4635   for (int i = NumElems / 2; i < NumElems; ++i) {
4636     if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
4637       continue;
4638
4639     if (TopHalf == nullptr)
4640       TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
4641     else if (Cond->getOperand(i).getNode() != TopHalf)
4642       return SDValue();
4643   }
4644
4645   assert(TopHalf && BottomHalf &&
4646          "One half of the selector was all UNDEFs and the other was all the "
4647          "same value. This should have been addressed before this function.");
4648   return DAG.getNode(
4649       ISD::CONCAT_VECTORS, dl, VT,
4650       BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
4651       TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
4652 }
4653
4654 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
4655   SDValue N0 = N->getOperand(0);
4656   SDValue N1 = N->getOperand(1);
4657   SDValue N2 = N->getOperand(2);
4658   SDLoc DL(N);
4659
4660   // Canonicalize integer abs.
4661   // vselect (setg[te] X,  0),  X, -X ->
4662   // vselect (setgt    X, -1),  X, -X ->
4663   // vselect (setl[te] X,  0), -X,  X ->
4664   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
4665   if (N0.getOpcode() == ISD::SETCC) {
4666     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4667     ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4668     bool isAbs = false;
4669     bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
4670
4671     if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
4672          (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
4673         N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
4674       isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
4675     else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
4676              N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
4677       isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
4678
4679     if (isAbs) {
4680       EVT VT = LHS.getValueType();
4681       SDValue Shift = DAG.getNode(
4682           ISD::SRA, DL, VT, LHS,
4683           DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, VT));
4684       SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
4685       AddToWorkList(Shift.getNode());
4686       AddToWorkList(Add.getNode());
4687       return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
4688     }
4689   }
4690
4691   // If the VSELECT result requires splitting and the mask is provided by a
4692   // SETCC, then split both nodes and its operands before legalization. This
4693   // prevents the type legalizer from unrolling SETCC into scalar comparisons
4694   // and enables future optimizations (e.g. min/max pattern matching on X86).
4695   if (N0.getOpcode() == ISD::SETCC) {
4696     EVT VT = N->getValueType(0);
4697
4698     // Check if any splitting is required.
4699     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
4700         TargetLowering::TypeSplitVector)
4701       return SDValue();
4702
4703     SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
4704     std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
4705     std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
4706     std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
4707
4708     Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
4709     Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
4710
4711     // Add the new VSELECT nodes to the work list in case they need to be split
4712     // again.
4713     AddToWorkList(Lo.getNode());
4714     AddToWorkList(Hi.getNode());
4715
4716     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
4717   }
4718
4719   // Fold (vselect (build_vector all_ones), N1, N2) -> N1
4720   if (ISD::isBuildVectorAllOnes(N0.getNode()))
4721     return N1;
4722   // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
4723   if (ISD::isBuildVectorAllZeros(N0.getNode()))
4724     return N2;
4725
4726   // The ConvertSelectToConcatVector function is assuming both the above
4727   // checks for (vselect (build_vector all{ones,zeros) ...) have been made
4728   // and addressed.
4729   if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
4730       N2.getOpcode() == ISD::CONCAT_VECTORS &&
4731       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
4732     SDValue CV = ConvertSelectToConcatVector(N, DAG);
4733     if (CV.getNode())
4734       return CV;
4735   }
4736
4737   return SDValue();
4738 }
4739
4740 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
4741   SDValue N0 = N->getOperand(0);
4742   SDValue N1 = N->getOperand(1);
4743   SDValue N2 = N->getOperand(2);
4744   SDValue N3 = N->getOperand(3);
4745   SDValue N4 = N->getOperand(4);
4746   ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
4747
4748   // fold select_cc lhs, rhs, x, x, cc -> x
4749   if (N2 == N3)
4750     return N2;
4751
4752   // Determine if the condition we're dealing with is constant
4753   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
4754                               N0, N1, CC, SDLoc(N), false);
4755   if (SCC.getNode()) {
4756     AddToWorkList(SCC.getNode());
4757
4758     if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
4759       if (!SCCC->isNullValue())
4760         return N2;    // cond always true -> true val
4761       else
4762         return N3;    // cond always false -> false val
4763     }
4764
4765     // Fold to a simpler select_cc
4766     if (SCC.getOpcode() == ISD::SETCC)
4767       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
4768                          SCC.getOperand(0), SCC.getOperand(1), N2, N3,
4769                          SCC.getOperand(2));
4770   }
4771
4772   // If we can fold this based on the true/false value, do so.
4773   if (SimplifySelectOps(N, N2, N3))
4774     return SDValue(N, 0);  // Don't revisit N.
4775
4776   // fold select_cc into other things, such as min/max/abs
4777   return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
4778 }
4779
4780 SDValue DAGCombiner::visitSETCC(SDNode *N) {
4781   return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
4782                        cast<CondCodeSDNode>(N->getOperand(2))->get(),
4783                        SDLoc(N));
4784 }
4785
4786 // tryToFoldExtendOfConstant - Try to fold a sext/zext/aext
4787 // dag node into a ConstantSDNode or a build_vector of constants.
4788 // This function is called by the DAGCombiner when visiting sext/zext/aext
4789 // dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
4790 // Vector extends are not folded if operations are legal; this is to
4791 // avoid introducing illegal build_vector dag nodes.
4792 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
4793                                          SelectionDAG &DAG, bool LegalTypes,
4794                                          bool LegalOperations) {
4795   unsigned Opcode = N->getOpcode();
4796   SDValue N0 = N->getOperand(0);
4797   EVT VT = N->getValueType(0);
4798
4799   assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
4800          Opcode == ISD::ANY_EXTEND) && "Expected EXTEND dag node in input!");
4801
4802   // fold (sext c1) -> c1
4803   // fold (zext c1) -> c1
4804   // fold (aext c1) -> c1
4805   if (isa<ConstantSDNode>(N0))
4806     return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
4807
4808   // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
4809   // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
4810   // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
4811   EVT SVT = VT.getScalarType();
4812   if (!(VT.isVector() &&
4813       (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
4814       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
4815     return nullptr;
4816
4817   // We can fold this node into a build_vector.
4818   unsigned VTBits = SVT.getSizeInBits();
4819   unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
4820   unsigned ShAmt = VTBits - EVTBits;
4821   SmallVector<SDValue, 8> Elts;
4822   unsigned NumElts = N0->getNumOperands();
4823   SDLoc DL(N);
4824
4825   for (unsigned i=0; i != NumElts; ++i) {
4826     SDValue Op = N0->getOperand(i);
4827     if (Op->getOpcode() == ISD::UNDEF) {
4828       Elts.push_back(DAG.getUNDEF(SVT));
4829       continue;
4830     }
4831
4832     ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
4833     const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
4834     if (Opcode == ISD::SIGN_EXTEND)
4835       Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
4836                                      SVT));
4837     else
4838       Elts.push_back(DAG.getConstant(C.shl(ShAmt).lshr(ShAmt).getZExtValue(),
4839                                      SVT));
4840   }
4841
4842   return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts).getNode();
4843 }
4844
4845 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
4846 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
4847 // transformation. Returns true if extension are possible and the above
4848 // mentioned transformation is profitable.
4849 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
4850                                     unsigned ExtOpc,
4851                                     SmallVectorImpl<SDNode *> &ExtendNodes,
4852                                     const TargetLowering &TLI) {
4853   bool HasCopyToRegUses = false;
4854   bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
4855   for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
4856                             UE = N0.getNode()->use_end();
4857        UI != UE; ++UI) {
4858     SDNode *User = *UI;
4859     if (User == N)
4860       continue;
4861     if (UI.getUse().getResNo() != N0.getResNo())
4862       continue;
4863     // FIXME: Only extend SETCC N, N and SETCC N, c for now.
4864     if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
4865       ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
4866       if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
4867         // Sign bits will be lost after a zext.
4868         return false;
4869       bool Add = false;
4870       for (unsigned i = 0; i != 2; ++i) {
4871         SDValue UseOp = User->getOperand(i);
4872         if (UseOp == N0)
4873           continue;
4874         if (!isa<ConstantSDNode>(UseOp))
4875           return false;
4876         Add = true;
4877       }
4878       if (Add)
4879         ExtendNodes.push_back(User);
4880       continue;
4881     }
4882     // If truncates aren't free and there are users we can't
4883     // extend, it isn't worthwhile.
4884     if (!isTruncFree)
4885       return false;
4886     // Remember if this value is live-out.
4887     if (User->getOpcode() == ISD::CopyToReg)
4888       HasCopyToRegUses = true;
4889   }
4890
4891   if (HasCopyToRegUses) {
4892     bool BothLiveOut = false;
4893     for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
4894          UI != UE; ++UI) {
4895       SDUse &Use = UI.getUse();
4896       if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
4897         BothLiveOut = true;
4898         break;
4899       }
4900     }
4901     if (BothLiveOut)
4902       // Both unextended and extended values are live out. There had better be
4903       // a good reason for the transformation.
4904       return ExtendNodes.size();
4905   }
4906   return true;
4907 }
4908
4909 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
4910                                   SDValue Trunc, SDValue ExtLoad, SDLoc DL,
4911                                   ISD::NodeType ExtType) {
4912   // Extend SetCC uses if necessary.
4913   for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
4914     SDNode *SetCC = SetCCs[i];
4915     SmallVector<SDValue, 4> Ops;
4916
4917     for (unsigned j = 0; j != 2; ++j) {
4918       SDValue SOp = SetCC->getOperand(j);
4919       if (SOp == Trunc)
4920         Ops.push_back(ExtLoad);
4921       else
4922         Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
4923     }
4924
4925     Ops.push_back(SetCC->getOperand(2));
4926     CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
4927   }
4928 }
4929
4930 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
4931   SDValue N0 = N->getOperand(0);
4932   EVT VT = N->getValueType(0);
4933
4934   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
4935                                               LegalOperations))
4936     return SDValue(Res, 0);
4937
4938   // fold (sext (sext x)) -> (sext x)
4939   // fold (sext (aext x)) -> (sext x)
4940   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
4941     return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
4942                        N0.getOperand(0));
4943
4944   if (N0.getOpcode() == ISD::TRUNCATE) {
4945     // fold (sext (truncate (load x))) -> (sext (smaller load x))
4946     // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
4947     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4948     if (NarrowLoad.getNode()) {
4949       SDNode* oye = N0.getNode()->getOperand(0).getNode();
4950       if (NarrowLoad.getNode() != N0.getNode()) {
4951         CombineTo(N0.getNode(), NarrowLoad);
4952         // CombineTo deleted the truncate, if needed, but not what's under it.
4953         AddToWorkList(oye);
4954       }
4955       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4956     }
4957
4958     // See if the value being truncated is already sign extended.  If so, just
4959     // eliminate the trunc/sext pair.
4960     SDValue Op = N0.getOperand(0);
4961     unsigned OpBits   = Op.getValueType().getScalarType().getSizeInBits();
4962     unsigned MidBits  = N0.getValueType().getScalarType().getSizeInBits();
4963     unsigned DestBits = VT.getScalarType().getSizeInBits();
4964     unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
4965
4966     if (OpBits == DestBits) {
4967       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
4968       // bits, it is already ready.
4969       if (NumSignBits > DestBits-MidBits)
4970         return Op;
4971     } else if (OpBits < DestBits) {
4972       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
4973       // bits, just sext from i32.
4974       if (NumSignBits > OpBits-MidBits)
4975         return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
4976     } else {
4977       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
4978       // bits, just truncate to i32.
4979       if (NumSignBits > OpBits-MidBits)
4980         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
4981     }
4982
4983     // fold (sext (truncate x)) -> (sextinreg x).
4984     if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
4985                                                  N0.getValueType())) {
4986       if (OpBits < DestBits)
4987         Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
4988       else if (OpBits > DestBits)
4989         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
4990       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
4991                          DAG.getValueType(N0.getValueType()));
4992     }
4993   }
4994
4995   // fold (sext (load x)) -> (sext (truncate (sextload x)))
4996   // None of the supported targets knows how to perform load and sign extend
4997   // on vectors in one instruction.  We only perform this transformation on
4998   // scalars.
4999   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5000       ISD::isUNINDEXEDLoad(N0.getNode()) &&
5001       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5002        TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()))) {
5003     bool DoXform = true;
5004     SmallVector<SDNode*, 4> SetCCs;
5005     if (!N0.hasOneUse())
5006       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
5007     if (DoXform) {
5008       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5009       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5010                                        LN0->getChain(),
5011                                        LN0->getBasePtr(), N0.getValueType(),
5012                                        LN0->getMemOperand());
5013       CombineTo(N, ExtLoad);
5014       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5015                                   N0.getValueType(), ExtLoad);
5016       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5017       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5018                       ISD::SIGN_EXTEND);
5019       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5020     }
5021   }
5022
5023   // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
5024   // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
5025   if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5026       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5027     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5028     EVT MemVT = LN0->getMemoryVT();
5029     if ((!LegalOperations && !LN0->isVolatile()) ||
5030         TLI.isLoadExtLegal(ISD::SEXTLOAD, MemVT)) {
5031       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5032                                        LN0->getChain(),
5033                                        LN0->getBasePtr(), MemVT,
5034                                        LN0->getMemOperand());
5035       CombineTo(N, ExtLoad);
5036       CombineTo(N0.getNode(),
5037                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5038                             N0.getValueType(), ExtLoad),
5039                 ExtLoad.getValue(1));
5040       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5041     }
5042   }
5043
5044   // fold (sext (and/or/xor (load x), cst)) ->
5045   //      (and/or/xor (sextload x), (sext cst))
5046   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5047        N0.getOpcode() == ISD::XOR) &&
5048       isa<LoadSDNode>(N0.getOperand(0)) &&
5049       N0.getOperand(1).getOpcode() == ISD::Constant &&
5050       TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()) &&
5051       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5052     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5053     if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
5054       bool DoXform = true;
5055       SmallVector<SDNode*, 4> SetCCs;
5056       if (!N0.hasOneUse())
5057         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
5058                                           SetCCs, TLI);
5059       if (DoXform) {
5060         SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
5061                                          LN0->getChain(), LN0->getBasePtr(),
5062                                          LN0->getMemoryVT(),
5063                                          LN0->getMemOperand());
5064         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5065         Mask = Mask.sext(VT.getSizeInBits());
5066         SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5067                                   ExtLoad, DAG.getConstant(Mask, VT));
5068         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5069                                     SDLoc(N0.getOperand(0)),
5070                                     N0.getOperand(0).getValueType(), ExtLoad);
5071         CombineTo(N, And);
5072         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5073         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5074                         ISD::SIGN_EXTEND);
5075         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5076       }
5077     }
5078   }
5079
5080   if (N0.getOpcode() == ISD::SETCC) {
5081     EVT N0VT = N0.getOperand(0).getValueType();
5082     // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
5083     // Only do this before legalize for now.
5084     if (VT.isVector() && !LegalOperations &&
5085         TLI.getBooleanContents(N0VT) ==
5086             TargetLowering::ZeroOrNegativeOneBooleanContent) {
5087       // On some architectures (such as SSE/NEON/etc) the SETCC result type is
5088       // of the same size as the compared operands. Only optimize sext(setcc())
5089       // if this is the case.
5090       EVT SVT = getSetCCResultType(N0VT);
5091
5092       // We know that the # elements of the results is the same as the
5093       // # elements of the compare (and the # elements of the compare result
5094       // for that matter).  Check to see that they are the same size.  If so,
5095       // we know that the element size of the sext'd result matches the
5096       // element size of the compare operands.
5097       if (VT.getSizeInBits() == SVT.getSizeInBits())
5098         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5099                              N0.getOperand(1),
5100                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
5101
5102       // If the desired elements are smaller or larger than the source
5103       // elements we can use a matching integer vector type and then
5104       // truncate/sign extend
5105       EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5106       if (SVT == MatchingVectorType) {
5107         SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
5108                                N0.getOperand(0), N0.getOperand(1),
5109                                cast<CondCodeSDNode>(N0.getOperand(2))->get());
5110         return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
5111       }
5112     }
5113
5114     // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
5115     unsigned ElementWidth = VT.getScalarType().getSizeInBits();
5116     SDValue NegOne =
5117       DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT);
5118     SDValue SCC =
5119       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5120                        NegOne, DAG.getConstant(0, VT),
5121                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5122     if (SCC.getNode()) return SCC;
5123
5124     if (!VT.isVector()) {
5125       EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
5126       if (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, SetCCVT)) {
5127         SDLoc DL(N);
5128         ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5129         SDValue SetCC = DAG.getSetCC(DL,
5130                                      SetCCVT,
5131                                      N0.getOperand(0), N0.getOperand(1), CC);
5132         EVT SelectVT = getSetCCResultType(VT);
5133         return DAG.getSelect(DL, VT,
5134                              DAG.getSExtOrTrunc(SetCC, DL, SelectVT),
5135                              NegOne, DAG.getConstant(0, VT));
5136
5137       }
5138     }
5139   }
5140
5141   // fold (sext x) -> (zext x) if the sign bit is known zero.
5142   if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
5143       DAG.SignBitIsZero(N0))
5144     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
5145
5146   return SDValue();
5147 }
5148
5149 // isTruncateOf - If N is a truncate of some other value, return true, record
5150 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
5151 // This function computes KnownZero to avoid a duplicated call to
5152 // computeKnownBits in the caller.
5153 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
5154                          APInt &KnownZero) {
5155   APInt KnownOne;
5156   if (N->getOpcode() == ISD::TRUNCATE) {
5157     Op = N->getOperand(0);
5158     DAG.computeKnownBits(Op, KnownZero, KnownOne);
5159     return true;
5160   }
5161
5162   if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
5163       cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
5164     return false;
5165
5166   SDValue Op0 = N->getOperand(0);
5167   SDValue Op1 = N->getOperand(1);
5168   assert(Op0.getValueType() == Op1.getValueType());
5169
5170   ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0);
5171   ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
5172   if (COp0 && COp0->isNullValue())
5173     Op = Op1;
5174   else if (COp1 && COp1->isNullValue())
5175     Op = Op0;
5176   else
5177     return false;
5178
5179   DAG.computeKnownBits(Op, KnownZero, KnownOne);
5180
5181   if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
5182     return false;
5183
5184   return true;
5185 }
5186
5187 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
5188   SDValue N0 = N->getOperand(0);
5189   EVT VT = N->getValueType(0);
5190
5191   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5192                                               LegalOperations))
5193     return SDValue(Res, 0);
5194
5195   // fold (zext (zext x)) -> (zext x)
5196   // fold (zext (aext x)) -> (zext x)
5197   if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5198     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
5199                        N0.getOperand(0));
5200
5201   // fold (zext (truncate x)) -> (zext x) or
5202   //      (zext (truncate x)) -> (truncate x)
5203   // This is valid when the truncated bits of x are already zero.
5204   // FIXME: We should extend this to work for vectors too.
5205   SDValue Op;
5206   APInt KnownZero;
5207   if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
5208     APInt TruncatedBits =
5209       (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
5210       APInt(Op.getValueSizeInBits(), 0) :
5211       APInt::getBitsSet(Op.getValueSizeInBits(),
5212                         N0.getValueSizeInBits(),
5213                         std::min(Op.getValueSizeInBits(),
5214                                  VT.getSizeInBits()));
5215     if (TruncatedBits == (KnownZero & TruncatedBits)) {
5216       if (VT.bitsGT(Op.getValueType()))
5217         return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
5218       if (VT.bitsLT(Op.getValueType()))
5219         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5220
5221       return Op;
5222     }
5223   }
5224
5225   // fold (zext (truncate (load x))) -> (zext (smaller load x))
5226   // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
5227   if (N0.getOpcode() == ISD::TRUNCATE) {
5228     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5229     if (NarrowLoad.getNode()) {
5230       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5231       if (NarrowLoad.getNode() != N0.getNode()) {
5232         CombineTo(N0.getNode(), NarrowLoad);
5233         // CombineTo deleted the truncate, if needed, but not what's under it.
5234         AddToWorkList(oye);
5235       }
5236       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5237     }
5238   }
5239
5240   // fold (zext (truncate x)) -> (and x, mask)
5241   if (N0.getOpcode() == ISD::TRUNCATE &&
5242       (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
5243
5244     // fold (zext (truncate (load x))) -> (zext (smaller load x))
5245     // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
5246     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5247     if (NarrowLoad.getNode()) {
5248       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5249       if (NarrowLoad.getNode() != N0.getNode()) {
5250         CombineTo(N0.getNode(), NarrowLoad);
5251         // CombineTo deleted the truncate, if needed, but not what's under it.
5252         AddToWorkList(oye);
5253       }
5254       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5255     }
5256
5257     SDValue Op = N0.getOperand(0);
5258     if (Op.getValueType().bitsLT(VT)) {
5259       Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
5260       AddToWorkList(Op.getNode());
5261     } else if (Op.getValueType().bitsGT(VT)) {
5262       Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5263       AddToWorkList(Op.getNode());
5264     }
5265     return DAG.getZeroExtendInReg(Op, SDLoc(N),
5266                                   N0.getValueType().getScalarType());
5267   }
5268
5269   // Fold (zext (and (trunc x), cst)) -> (and x, cst),
5270   // if either of the casts is not free.
5271   if (N0.getOpcode() == ISD::AND &&
5272       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5273       N0.getOperand(1).getOpcode() == ISD::Constant &&
5274       (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5275                            N0.getValueType()) ||
5276        !TLI.isZExtFree(N0.getValueType(), VT))) {
5277     SDValue X = N0.getOperand(0).getOperand(0);
5278     if (X.getValueType().bitsLT(VT)) {
5279       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
5280     } else if (X.getValueType().bitsGT(VT)) {
5281       X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
5282     }
5283     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5284     Mask = Mask.zext(VT.getSizeInBits());
5285     return DAG.getNode(ISD::AND, SDLoc(N), VT,
5286                        X, DAG.getConstant(Mask, VT));
5287   }
5288
5289   // fold (zext (load x)) -> (zext (truncate (zextload x)))
5290   // None of the supported targets knows how to perform load and vector_zext
5291   // on vectors in one instruction.  We only perform this transformation on
5292   // scalars.
5293   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5294       ISD::isUNINDEXEDLoad(N0.getNode()) &&
5295       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5296        TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()))) {
5297     bool DoXform = true;
5298     SmallVector<SDNode*, 4> SetCCs;
5299     if (!N0.hasOneUse())
5300       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
5301     if (DoXform) {
5302       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5303       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5304                                        LN0->getChain(),
5305                                        LN0->getBasePtr(), N0.getValueType(),
5306                                        LN0->getMemOperand());
5307       CombineTo(N, ExtLoad);
5308       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5309                                   N0.getValueType(), ExtLoad);
5310       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5311
5312       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5313                       ISD::ZERO_EXTEND);
5314       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5315     }
5316   }
5317
5318   // fold (zext (and/or/xor (load x), cst)) ->
5319   //      (and/or/xor (zextload x), (zext cst))
5320   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5321        N0.getOpcode() == ISD::XOR) &&
5322       isa<LoadSDNode>(N0.getOperand(0)) &&
5323       N0.getOperand(1).getOpcode() == ISD::Constant &&
5324       TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()) &&
5325       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5326     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5327     if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
5328       bool DoXform = true;
5329       SmallVector<SDNode*, 4> SetCCs;
5330       if (!N0.hasOneUse())
5331         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
5332                                           SetCCs, TLI);
5333       if (DoXform) {
5334         SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
5335                                          LN0->getChain(), LN0->getBasePtr(),
5336                                          LN0->getMemoryVT(),
5337                                          LN0->getMemOperand());
5338         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5339         Mask = Mask.zext(VT.getSizeInBits());
5340         SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5341                                   ExtLoad, DAG.getConstant(Mask, VT));
5342         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5343                                     SDLoc(N0.getOperand(0)),
5344                                     N0.getOperand(0).getValueType(), ExtLoad);
5345         CombineTo(N, And);
5346         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5347         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5348                         ISD::ZERO_EXTEND);
5349         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5350       }
5351     }
5352   }
5353
5354   // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
5355   // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
5356   if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5357       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5358     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5359     EVT MemVT = LN0->getMemoryVT();
5360     if ((!LegalOperations && !LN0->isVolatile()) ||
5361         TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT)) {
5362       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5363                                        LN0->getChain(),
5364                                        LN0->getBasePtr(), MemVT,
5365                                        LN0->getMemOperand());
5366       CombineTo(N, ExtLoad);
5367       CombineTo(N0.getNode(),
5368                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
5369                             ExtLoad),
5370                 ExtLoad.getValue(1));
5371       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5372     }
5373   }
5374
5375   if (N0.getOpcode() == ISD::SETCC) {
5376     if (!LegalOperations && VT.isVector() &&
5377         N0.getValueType().getVectorElementType() == MVT::i1) {
5378       EVT N0VT = N0.getOperand(0).getValueType();
5379       if (getSetCCResultType(N0VT) == N0.getValueType())
5380         return SDValue();
5381
5382       // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
5383       // Only do this before legalize for now.
5384       EVT EltVT = VT.getVectorElementType();
5385       SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
5386                                     DAG.getConstant(1, EltVT));
5387       if (VT.getSizeInBits() == N0VT.getSizeInBits())
5388         // We know that the # elements of the results is the same as the
5389         // # elements of the compare (and the # elements of the compare result
5390         // for that matter).  Check to see that they are the same size.  If so,
5391         // we know that the element size of the sext'd result matches the
5392         // element size of the compare operands.
5393         return DAG.getNode(ISD::AND, SDLoc(N), VT,
5394                            DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5395                                          N0.getOperand(1),
5396                                  cast<CondCodeSDNode>(N0.getOperand(2))->get()),
5397                            DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
5398                                        OneOps));
5399
5400       // If the desired elements are smaller or larger than the source
5401       // elements we can use a matching integer vector type and then
5402       // truncate/sign extend
5403       EVT MatchingElementType =
5404         EVT::getIntegerVT(*DAG.getContext(),
5405                           N0VT.getScalarType().getSizeInBits());
5406       EVT MatchingVectorType =
5407         EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
5408                          N0VT.getVectorNumElements());
5409       SDValue VsetCC =
5410         DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5411                       N0.getOperand(1),
5412                       cast<CondCodeSDNode>(N0.getOperand(2))->get());
5413       return DAG.getNode(ISD::AND, SDLoc(N), VT,
5414                          DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT),
5415                          DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, OneOps));
5416     }
5417
5418     // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5419     SDValue SCC =
5420       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5421                        DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5422                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5423     if (SCC.getNode()) return SCC;
5424   }
5425
5426   // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
5427   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
5428       isa<ConstantSDNode>(N0.getOperand(1)) &&
5429       N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
5430       N0.hasOneUse()) {
5431     SDValue ShAmt = N0.getOperand(1);
5432     unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
5433     if (N0.getOpcode() == ISD::SHL) {
5434       SDValue InnerZExt = N0.getOperand(0);
5435       // If the original shl may be shifting out bits, do not perform this
5436       // transformation.
5437       unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
5438         InnerZExt.getOperand(0).getValueType().getSizeInBits();
5439       if (ShAmtVal > KnownZeroBits)
5440         return SDValue();
5441     }
5442
5443     SDLoc DL(N);
5444
5445     // Ensure that the shift amount is wide enough for the shifted value.
5446     if (VT.getSizeInBits() >= 256)
5447       ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
5448
5449     return DAG.getNode(N0.getOpcode(), DL, VT,
5450                        DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
5451                        ShAmt);
5452   }
5453
5454   return SDValue();
5455 }
5456
5457 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
5458   SDValue N0 = N->getOperand(0);
5459   EVT VT = N->getValueType(0);
5460
5461   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5462                                               LegalOperations))
5463     return SDValue(Res, 0);
5464
5465   // fold (aext (aext x)) -> (aext x)
5466   // fold (aext (zext x)) -> (zext x)
5467   // fold (aext (sext x)) -> (sext x)
5468   if (N0.getOpcode() == ISD::ANY_EXTEND  ||
5469       N0.getOpcode() == ISD::ZERO_EXTEND ||
5470       N0.getOpcode() == ISD::SIGN_EXTEND)
5471     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
5472
5473   // fold (aext (truncate (load x))) -> (aext (smaller load x))
5474   // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
5475   if (N0.getOpcode() == ISD::TRUNCATE) {
5476     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5477     if (NarrowLoad.getNode()) {
5478       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5479       if (NarrowLoad.getNode() != N0.getNode()) {
5480         CombineTo(N0.getNode(), NarrowLoad);
5481         // CombineTo deleted the truncate, if needed, but not what's under it.
5482         AddToWorkList(oye);
5483       }
5484       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5485     }
5486   }
5487
5488   // fold (aext (truncate x))
5489   if (N0.getOpcode() == ISD::TRUNCATE) {
5490     SDValue TruncOp = N0.getOperand(0);
5491     if (TruncOp.getValueType() == VT)
5492       return TruncOp; // x iff x size == zext size.
5493     if (TruncOp.getValueType().bitsGT(VT))
5494       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
5495     return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
5496   }
5497
5498   // Fold (aext (and (trunc x), cst)) -> (and x, cst)
5499   // if the trunc is not free.
5500   if (N0.getOpcode() == ISD::AND &&
5501       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5502       N0.getOperand(1).getOpcode() == ISD::Constant &&
5503       !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5504                           N0.getValueType())) {
5505     SDValue X = N0.getOperand(0).getOperand(0);
5506     if (X.getValueType().bitsLT(VT)) {
5507       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
5508     } else if (X.getValueType().bitsGT(VT)) {
5509       X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
5510     }
5511     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5512     Mask = Mask.zext(VT.getSizeInBits());
5513     return DAG.getNode(ISD::AND, SDLoc(N), VT,
5514                        X, DAG.getConstant(Mask, VT));
5515   }
5516
5517   // fold (aext (load x)) -> (aext (truncate (extload x)))
5518   // None of the supported targets knows how to perform load and any_ext
5519   // on vectors in one instruction.  We only perform this transformation on
5520   // scalars.
5521   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5522       ISD::isUNINDEXEDLoad(N0.getNode()) &&
5523       TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType())) {
5524     bool DoXform = true;
5525     SmallVector<SDNode*, 4> SetCCs;
5526     if (!N0.hasOneUse())
5527       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
5528     if (DoXform) {
5529       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5530       SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
5531                                        LN0->getChain(),
5532                                        LN0->getBasePtr(), N0.getValueType(),
5533                                        LN0->getMemOperand());
5534       CombineTo(N, ExtLoad);
5535       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5536                                   N0.getValueType(), ExtLoad);
5537       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5538       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5539                       ISD::ANY_EXTEND);
5540       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5541     }
5542   }
5543
5544   // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
5545   // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
5546   // fold (aext ( extload x)) -> (aext (truncate (extload  x)))
5547   if (N0.getOpcode() == ISD::LOAD &&
5548       !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5549       N0.hasOneUse()) {
5550     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5551     ISD::LoadExtType ExtType = LN0->getExtensionType();
5552     EVT MemVT = LN0->getMemoryVT();
5553     if (!LegalOperations || TLI.isLoadExtLegal(ExtType, MemVT)) {
5554       SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
5555                                        VT, LN0->getChain(), LN0->getBasePtr(),
5556                                        MemVT, LN0->getMemOperand());
5557       CombineTo(N, ExtLoad);
5558       CombineTo(N0.getNode(),
5559                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5560                             N0.getValueType(), ExtLoad),
5561                 ExtLoad.getValue(1));
5562       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5563     }
5564   }
5565
5566   if (N0.getOpcode() == ISD::SETCC) {
5567     // For vectors:
5568     // aext(setcc) -> vsetcc
5569     // aext(setcc) -> truncate(vsetcc)
5570     // aext(setcc) -> aext(vsetcc)
5571     // Only do this before legalize for now.
5572     if (VT.isVector() && !LegalOperations) {
5573       EVT N0VT = N0.getOperand(0).getValueType();
5574         // We know that the # elements of the results is the same as the
5575         // # elements of the compare (and the # elements of the compare result
5576         // for that matter).  Check to see that they are the same size.  If so,
5577         // we know that the element size of the sext'd result matches the
5578         // element size of the compare operands.
5579       if (VT.getSizeInBits() == N0VT.getSizeInBits())
5580         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5581                              N0.getOperand(1),
5582                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
5583       // If the desired elements are smaller or larger than the source
5584       // elements we can use a matching integer vector type and then
5585       // truncate/any extend
5586       else {
5587         EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5588         SDValue VsetCC =
5589           DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5590                         N0.getOperand(1),
5591                         cast<CondCodeSDNode>(N0.getOperand(2))->get());
5592         return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
5593       }
5594     }
5595
5596     // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5597     SDValue SCC =
5598       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5599                        DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5600                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5601     if (SCC.getNode())
5602       return SCC;
5603   }
5604
5605   return SDValue();
5606 }
5607
5608 /// GetDemandedBits - See if the specified operand can be simplified with the
5609 /// knowledge that only the bits specified by Mask are used.  If so, return the
5610 /// simpler operand, otherwise return a null SDValue.
5611 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
5612   switch (V.getOpcode()) {
5613   default: break;
5614   case ISD::Constant: {
5615     const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
5616     assert(CV && "Const value should be ConstSDNode.");
5617     const APInt &CVal = CV->getAPIntValue();
5618     APInt NewVal = CVal & Mask;
5619     if (NewVal != CVal)
5620       return DAG.getConstant(NewVal, V.getValueType());
5621     break;
5622   }
5623   case ISD::OR:
5624   case ISD::XOR:
5625     // If the LHS or RHS don't contribute bits to the or, drop them.
5626     if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
5627       return V.getOperand(1);
5628     if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
5629       return V.getOperand(0);
5630     break;
5631   case ISD::SRL:
5632     // Only look at single-use SRLs.
5633     if (!V.getNode()->hasOneUse())
5634       break;
5635     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
5636       // See if we can recursively simplify the LHS.
5637       unsigned Amt = RHSC->getZExtValue();
5638
5639       // Watch out for shift count overflow though.
5640       if (Amt >= Mask.getBitWidth()) break;
5641       APInt NewMask = Mask << Amt;
5642       SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
5643       if (SimplifyLHS.getNode())
5644         return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
5645                            SimplifyLHS, V.getOperand(1));
5646     }
5647   }
5648   return SDValue();
5649 }
5650
5651 /// ReduceLoadWidth - If the result of a wider load is shifted to right of N
5652 /// bits and then truncated to a narrower type and where N is a multiple
5653 /// of number of bits of the narrower type, transform it to a narrower load
5654 /// from address + N / num of bits of new type. If the result is to be
5655 /// extended, also fold the extension to form a extending load.
5656 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
5657   unsigned Opc = N->getOpcode();
5658
5659   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
5660   SDValue N0 = N->getOperand(0);
5661   EVT VT = N->getValueType(0);
5662   EVT ExtVT = VT;
5663
5664   // This transformation isn't valid for vector loads.
5665   if (VT.isVector())
5666     return SDValue();
5667
5668   // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
5669   // extended to VT.
5670   if (Opc == ISD::SIGN_EXTEND_INREG) {
5671     ExtType = ISD::SEXTLOAD;
5672     ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
5673   } else if (Opc == ISD::SRL) {
5674     // Another special-case: SRL is basically zero-extending a narrower value.
5675     ExtType = ISD::ZEXTLOAD;
5676     N0 = SDValue(N, 0);
5677     ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
5678     if (!N01) return SDValue();
5679     ExtVT = EVT::getIntegerVT(*DAG.getContext(),
5680                               VT.getSizeInBits() - N01->getZExtValue());
5681   }
5682   if (LegalOperations && !TLI.isLoadExtLegal(ExtType, ExtVT))
5683     return SDValue();
5684
5685   unsigned EVTBits = ExtVT.getSizeInBits();
5686
5687   // Do not generate loads of non-round integer types since these can
5688   // be expensive (and would be wrong if the type is not byte sized).
5689   if (!ExtVT.isRound())
5690     return SDValue();
5691
5692   unsigned ShAmt = 0;
5693   if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
5694     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5695       ShAmt = N01->getZExtValue();
5696       // Is the shift amount a multiple of size of VT?
5697       if ((ShAmt & (EVTBits-1)) == 0) {
5698         N0 = N0.getOperand(0);
5699         // Is the load width a multiple of size of VT?
5700         if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
5701           return SDValue();
5702       }
5703
5704       // At this point, we must have a load or else we can't do the transform.
5705       if (!isa<LoadSDNode>(N0)) return SDValue();
5706
5707       // Because a SRL must be assumed to *need* to zero-extend the high bits
5708       // (as opposed to anyext the high bits), we can't combine the zextload
5709       // lowering of SRL and an sextload.
5710       if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
5711         return SDValue();
5712
5713       // If the shift amount is larger than the input type then we're not
5714       // accessing any of the loaded bytes.  If the load was a zextload/extload
5715       // then the result of the shift+trunc is zero/undef (handled elsewhere).
5716       if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
5717         return SDValue();
5718     }
5719   }
5720
5721   // If the load is shifted left (and the result isn't shifted back right),
5722   // we can fold the truncate through the shift.
5723   unsigned ShLeftAmt = 0;
5724   if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
5725       ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
5726     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5727       ShLeftAmt = N01->getZExtValue();
5728       N0 = N0.getOperand(0);
5729     }
5730   }
5731
5732   // If we haven't found a load, we can't narrow it.  Don't transform one with
5733   // multiple uses, this would require adding a new load.
5734   if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
5735     return SDValue();
5736
5737   // Don't change the width of a volatile load.
5738   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5739   if (LN0->isVolatile())
5740     return SDValue();
5741
5742   // Verify that we are actually reducing a load width here.
5743   if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
5744     return SDValue();
5745
5746   // For the transform to be legal, the load must produce only two values
5747   // (the value loaded and the chain).  Don't transform a pre-increment
5748   // load, for example, which produces an extra value.  Otherwise the
5749   // transformation is not equivalent, and the downstream logic to replace
5750   // uses gets things wrong.
5751   if (LN0->getNumValues() > 2)
5752     return SDValue();
5753
5754   // If the load that we're shrinking is an extload and we're not just
5755   // discarding the extension we can't simply shrink the load. Bail.
5756   // TODO: It would be possible to merge the extensions in some cases.
5757   if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
5758       LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
5759     return SDValue();
5760
5761   EVT PtrType = N0.getOperand(1).getValueType();
5762
5763   if (PtrType == MVT::Untyped || PtrType.isExtended())
5764     // It's not possible to generate a constant of extended or untyped type.
5765     return SDValue();
5766
5767   // For big endian targets, we need to adjust the offset to the pointer to
5768   // load the correct bytes.
5769   if (TLI.isBigEndian()) {
5770     unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
5771     unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
5772     ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
5773   }
5774
5775   uint64_t PtrOff = ShAmt / 8;
5776   unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
5777   SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0),
5778                                PtrType, LN0->getBasePtr(),
5779                                DAG.getConstant(PtrOff, PtrType));
5780   AddToWorkList(NewPtr.getNode());
5781
5782   SDValue Load;
5783   if (ExtType == ISD::NON_EXTLOAD)
5784     Load =  DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
5785                         LN0->getPointerInfo().getWithOffset(PtrOff),
5786                         LN0->isVolatile(), LN0->isNonTemporal(),
5787                         LN0->isInvariant(), NewAlign, LN0->getTBAAInfo());
5788   else
5789     Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
5790                           LN0->getPointerInfo().getWithOffset(PtrOff),
5791                           ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
5792                           NewAlign, LN0->getTBAAInfo());
5793
5794   // Replace the old load's chain with the new load's chain.
5795   WorkListRemover DeadNodes(*this);
5796   DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
5797
5798   // Shift the result left, if we've swallowed a left shift.
5799   SDValue Result = Load;
5800   if (ShLeftAmt != 0) {
5801     EVT ShImmTy = getShiftAmountTy(Result.getValueType());
5802     if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
5803       ShImmTy = VT;
5804     // If the shift amount is as large as the result size (but, presumably,
5805     // no larger than the source) then the useful bits of the result are
5806     // zero; we can't simply return the shortened shift, because the result
5807     // of that operation is undefined.
5808     if (ShLeftAmt >= VT.getSizeInBits())
5809       Result = DAG.getConstant(0, VT);
5810     else
5811       Result = DAG.getNode(ISD::SHL, SDLoc(N0), VT,
5812                           Result, DAG.getConstant(ShLeftAmt, ShImmTy));
5813   }
5814
5815   // Return the new loaded value.
5816   return Result;
5817 }
5818
5819 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
5820   SDValue N0 = N->getOperand(0);
5821   SDValue N1 = N->getOperand(1);
5822   EVT VT = N->getValueType(0);
5823   EVT EVT = cast<VTSDNode>(N1)->getVT();
5824   unsigned VTBits = VT.getScalarType().getSizeInBits();
5825   unsigned EVTBits = EVT.getScalarType().getSizeInBits();
5826
5827   // fold (sext_in_reg c1) -> c1
5828   if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
5829     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
5830
5831   // If the input is already sign extended, just drop the extension.
5832   if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
5833     return N0;
5834
5835   // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
5836   if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
5837       EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
5838     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5839                        N0.getOperand(0), N1);
5840
5841   // fold (sext_in_reg (sext x)) -> (sext x)
5842   // fold (sext_in_reg (aext x)) -> (sext x)
5843   // if x is small enough.
5844   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
5845     SDValue N00 = N0.getOperand(0);
5846     if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
5847         (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
5848       return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
5849   }
5850
5851   // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
5852   if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
5853     return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
5854
5855   // fold operands of sext_in_reg based on knowledge that the top bits are not
5856   // demanded.
5857   if (SimplifyDemandedBits(SDValue(N, 0)))
5858     return SDValue(N, 0);
5859
5860   // fold (sext_in_reg (load x)) -> (smaller sextload x)
5861   // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
5862   SDValue NarrowLoad = ReduceLoadWidth(N);
5863   if (NarrowLoad.getNode())
5864     return NarrowLoad;
5865
5866   // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
5867   // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
5868   // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
5869   if (N0.getOpcode() == ISD::SRL) {
5870     if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
5871       if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
5872         // We can turn this into an SRA iff the input to the SRL is already sign
5873         // extended enough.
5874         unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
5875         if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
5876           return DAG.getNode(ISD::SRA, SDLoc(N), VT,
5877                              N0.getOperand(0), N0.getOperand(1));
5878       }
5879   }
5880
5881   // fold (sext_inreg (extload x)) -> (sextload x)
5882   if (ISD::isEXTLoad(N0.getNode()) &&
5883       ISD::isUNINDEXEDLoad(N0.getNode()) &&
5884       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5885       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5886        TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5887     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5888     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5889                                      LN0->getChain(),
5890                                      LN0->getBasePtr(), EVT,
5891                                      LN0->getMemOperand());
5892     CombineTo(N, ExtLoad);
5893     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5894     AddToWorkList(ExtLoad.getNode());
5895     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5896   }
5897   // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
5898   if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5899       N0.hasOneUse() &&
5900       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5901       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5902        TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5903     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5904     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5905                                      LN0->getChain(),
5906                                      LN0->getBasePtr(), EVT,
5907                                      LN0->getMemOperand());
5908     CombineTo(N, ExtLoad);
5909     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5910     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5911   }
5912
5913   // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
5914   if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
5915     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
5916                                        N0.getOperand(1), false);
5917     if (BSwap.getNode())
5918       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5919                          BSwap, N1);
5920   }
5921
5922   // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs
5923   // into a build_vector.
5924   if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5925     SmallVector<SDValue, 8> Elts;
5926     unsigned NumElts = N0->getNumOperands();
5927     unsigned ShAmt = VTBits - EVTBits;
5928
5929     for (unsigned i = 0; i != NumElts; ++i) {
5930       SDValue Op = N0->getOperand(i);
5931       if (Op->getOpcode() == ISD::UNDEF) {
5932         Elts.push_back(Op);
5933         continue;
5934       }
5935
5936       ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
5937       const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
5938       Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
5939                                      Op.getValueType()));
5940     }
5941
5942     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Elts);
5943   }
5944
5945   return SDValue();
5946 }
5947
5948 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
5949   SDValue N0 = N->getOperand(0);
5950   EVT VT = N->getValueType(0);
5951   bool isLE = TLI.isLittleEndian();
5952
5953   // noop truncate
5954   if (N0.getValueType() == N->getValueType(0))
5955     return N0;
5956   // fold (truncate c1) -> c1
5957   if (isa<ConstantSDNode>(N0))
5958     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
5959   // fold (truncate (truncate x)) -> (truncate x)
5960   if (N0.getOpcode() == ISD::TRUNCATE)
5961     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
5962   // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
5963   if (N0.getOpcode() == ISD::ZERO_EXTEND ||
5964       N0.getOpcode() == ISD::SIGN_EXTEND ||
5965       N0.getOpcode() == ISD::ANY_EXTEND) {
5966     if (N0.getOperand(0).getValueType().bitsLT(VT))
5967       // if the source is smaller than the dest, we still need an extend
5968       return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5969                          N0.getOperand(0));
5970     if (N0.getOperand(0).getValueType().bitsGT(VT))
5971       // if the source is larger than the dest, than we just need the truncate
5972       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
5973     // if the source and dest are the same type, we can drop both the extend
5974     // and the truncate.
5975     return N0.getOperand(0);
5976   }
5977
5978   // Fold extract-and-trunc into a narrow extract. For example:
5979   //   i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
5980   //   i32 y = TRUNCATE(i64 x)
5981   //        -- becomes --
5982   //   v16i8 b = BITCAST (v2i64 val)
5983   //   i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
5984   //
5985   // Note: We only run this optimization after type legalization (which often
5986   // creates this pattern) and before operation legalization after which
5987   // we need to be more careful about the vector instructions that we generate.
5988   if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5989       LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
5990
5991     EVT VecTy = N0.getOperand(0).getValueType();
5992     EVT ExTy = N0.getValueType();
5993     EVT TrTy = N->getValueType(0);
5994
5995     unsigned NumElem = VecTy.getVectorNumElements();
5996     unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
5997
5998     EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
5999     assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
6000
6001     SDValue EltNo = N0->getOperand(1);
6002     if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
6003       int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
6004       EVT IndexTy = TLI.getVectorIdxTy();
6005       int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
6006
6007       SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
6008                               NVT, N0.getOperand(0));
6009
6010       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
6011                          SDLoc(N), TrTy, V,
6012                          DAG.getConstant(Index, IndexTy));
6013     }
6014   }
6015
6016   // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
6017   if (N0.getOpcode() == ISD::SELECT) {
6018     EVT SrcVT = N0.getValueType();
6019     if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
6020         TLI.isTruncateFree(SrcVT, VT)) {
6021       SDLoc SL(N0);
6022       SDValue Cond = N0.getOperand(0);
6023       SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
6024       SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
6025       return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
6026     }
6027   }
6028
6029   // Fold a series of buildvector, bitcast, and truncate if possible.
6030   // For example fold
6031   //   (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
6032   //   (2xi32 (buildvector x, y)).
6033   if (Level == AfterLegalizeVectorOps && VT.isVector() &&
6034       N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
6035       N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
6036       N0.getOperand(0).hasOneUse()) {
6037
6038     SDValue BuildVect = N0.getOperand(0);
6039     EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
6040     EVT TruncVecEltTy = VT.getVectorElementType();
6041
6042     // Check that the element types match.
6043     if (BuildVectEltTy == TruncVecEltTy) {
6044       // Now we only need to compute the offset of the truncated elements.
6045       unsigned BuildVecNumElts =  BuildVect.getNumOperands();
6046       unsigned TruncVecNumElts = VT.getVectorNumElements();
6047       unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
6048
6049       assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
6050              "Invalid number of elements");
6051
6052       SmallVector<SDValue, 8> Opnds;
6053       for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
6054         Opnds.push_back(BuildVect.getOperand(i));
6055
6056       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
6057     }
6058   }
6059
6060   // See if we can simplify the input to this truncate through knowledge that
6061   // only the low bits are being used.
6062   // For example "trunc (or (shl x, 8), y)" // -> trunc y
6063   // Currently we only perform this optimization on scalars because vectors
6064   // may have different active low bits.
6065   if (!VT.isVector()) {
6066     SDValue Shorter =
6067       GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
6068                                                VT.getSizeInBits()));
6069     if (Shorter.getNode())
6070       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
6071   }
6072   // fold (truncate (load x)) -> (smaller load x)
6073   // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
6074   if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
6075     SDValue Reduced = ReduceLoadWidth(N);
6076     if (Reduced.getNode())
6077       return Reduced;
6078     // Handle the case where the load remains an extending load even
6079     // after truncation.
6080     if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
6081       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6082       if (!LN0->isVolatile() &&
6083           LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
6084         SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
6085                                          VT, LN0->getChain(), LN0->getBasePtr(),
6086                                          LN0->getMemoryVT(),
6087                                          LN0->getMemOperand());
6088         DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
6089         return NewLoad;
6090       }
6091     }
6092   }
6093   // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
6094   // where ... are all 'undef'.
6095   if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
6096     SmallVector<EVT, 8> VTs;
6097     SDValue V;
6098     unsigned Idx = 0;
6099     unsigned NumDefs = 0;
6100
6101     for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
6102       SDValue X = N0.getOperand(i);
6103       if (X.getOpcode() != ISD::UNDEF) {
6104         V = X;
6105         Idx = i;
6106         NumDefs++;
6107       }
6108       // Stop if more than one members are non-undef.
6109       if (NumDefs > 1)
6110         break;
6111       VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
6112                                      VT.getVectorElementType(),
6113                                      X.getValueType().getVectorNumElements()));
6114     }
6115
6116     if (NumDefs == 0)
6117       return DAG.getUNDEF(VT);
6118
6119     if (NumDefs == 1) {
6120       assert(V.getNode() && "The single defined operand is empty!");
6121       SmallVector<SDValue, 8> Opnds;
6122       for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
6123         if (i != Idx) {
6124           Opnds.push_back(DAG.getUNDEF(VTs[i]));
6125           continue;
6126         }
6127         SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
6128         AddToWorkList(NV.getNode());
6129         Opnds.push_back(NV);
6130       }
6131       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
6132     }
6133   }
6134
6135   // Simplify the operands using demanded-bits information.
6136   if (!VT.isVector() &&
6137       SimplifyDemandedBits(SDValue(N, 0)))
6138     return SDValue(N, 0);
6139
6140   return SDValue();
6141 }
6142
6143 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
6144   SDValue Elt = N->getOperand(i);
6145   if (Elt.getOpcode() != ISD::MERGE_VALUES)
6146     return Elt.getNode();
6147   return Elt.getOperand(Elt.getResNo()).getNode();
6148 }
6149
6150 /// CombineConsecutiveLoads - build_pair (load, load) -> load
6151 /// if load locations are consecutive.
6152 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
6153   assert(N->getOpcode() == ISD::BUILD_PAIR);
6154
6155   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
6156   LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
6157   if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
6158       LD1->getAddressSpace() != LD2->getAddressSpace())
6159     return SDValue();
6160   EVT LD1VT = LD1->getValueType(0);
6161
6162   if (ISD::isNON_EXTLoad(LD2) &&
6163       LD2->hasOneUse() &&
6164       // If both are volatile this would reduce the number of volatile loads.
6165       // If one is volatile it might be ok, but play conservative and bail out.
6166       !LD1->isVolatile() &&
6167       !LD2->isVolatile() &&
6168       DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
6169     unsigned Align = LD1->getAlignment();
6170     unsigned NewAlign = TLI.getDataLayout()->
6171       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6172
6173     if (NewAlign <= Align &&
6174         (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
6175       return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
6176                          LD1->getBasePtr(), LD1->getPointerInfo(),
6177                          false, false, false, Align);
6178   }
6179
6180   return SDValue();
6181 }
6182
6183 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
6184   SDValue N0 = N->getOperand(0);
6185   EVT VT = N->getValueType(0);
6186
6187   // If the input is a BUILD_VECTOR with all constant elements, fold this now.
6188   // Only do this before legalize, since afterward the target may be depending
6189   // on the bitconvert.
6190   // First check to see if this is all constant.
6191   if (!LegalTypes &&
6192       N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
6193       VT.isVector()) {
6194     bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
6195
6196     EVT DestEltVT = N->getValueType(0).getVectorElementType();
6197     assert(!DestEltVT.isVector() &&
6198            "Element type of vector ValueType must not be vector!");
6199     if (isSimple)
6200       return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
6201   }
6202
6203   // If the input is a constant, let getNode fold it.
6204   if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
6205     SDValue Res = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
6206     if (Res.getNode() != N) {
6207       if (!LegalOperations ||
6208           TLI.isOperationLegal(Res.getNode()->getOpcode(), VT))
6209         return Res;
6210
6211       // Folding it resulted in an illegal node, and it's too late to
6212       // do that. Clean up the old node and forego the transformation.
6213       // Ideally this won't happen very often, because instcombine
6214       // and the earlier dagcombine runs (where illegal nodes are
6215       // permitted) should have folded most of them already.
6216       DAG.DeleteNode(Res.getNode());
6217     }
6218   }
6219
6220   // (conv (conv x, t1), t2) -> (conv x, t2)
6221   if (N0.getOpcode() == ISD::BITCAST)
6222     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
6223                        N0.getOperand(0));
6224
6225   // fold (conv (load x)) -> (load (conv*)x)
6226   // If the resultant load doesn't need a higher alignment than the original!
6227   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
6228       // Do not change the width of a volatile load.
6229       !cast<LoadSDNode>(N0)->isVolatile() &&
6230       // Do not remove the cast if the types differ in endian layout.
6231       TLI.hasBigEndianPartOrdering(N0.getValueType()) ==
6232       TLI.hasBigEndianPartOrdering(VT) &&
6233       (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
6234       TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
6235     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6236     unsigned Align = TLI.getDataLayout()->
6237       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6238     unsigned OrigAlign = LN0->getAlignment();
6239
6240     if (Align <= OrigAlign) {
6241       SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
6242                                  LN0->getBasePtr(), LN0->getPointerInfo(),
6243                                  LN0->isVolatile(), LN0->isNonTemporal(),
6244                                  LN0->isInvariant(), OrigAlign,
6245                                  LN0->getTBAAInfo());
6246       AddToWorkList(N);
6247       CombineTo(N0.getNode(),
6248                 DAG.getNode(ISD::BITCAST, SDLoc(N0),
6249                             N0.getValueType(), Load),
6250                 Load.getValue(1));
6251       return Load;
6252     }
6253   }
6254
6255   // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
6256   // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
6257   // This often reduces constant pool loads.
6258   if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
6259        (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
6260       N0.getNode()->hasOneUse() && VT.isInteger() &&
6261       !VT.isVector() && !N0.getValueType().isVector()) {
6262     SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
6263                                   N0.getOperand(0));
6264     AddToWorkList(NewConv.getNode());
6265
6266     APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6267     if (N0.getOpcode() == ISD::FNEG)
6268       return DAG.getNode(ISD::XOR, SDLoc(N), VT,
6269                          NewConv, DAG.getConstant(SignBit, VT));
6270     assert(N0.getOpcode() == ISD::FABS);
6271     return DAG.getNode(ISD::AND, SDLoc(N), VT,
6272                        NewConv, DAG.getConstant(~SignBit, VT));
6273   }
6274
6275   // fold (bitconvert (fcopysign cst, x)) ->
6276   //         (or (and (bitconvert x), sign), (and cst, (not sign)))
6277   // Note that we don't handle (copysign x, cst) because this can always be
6278   // folded to an fneg or fabs.
6279   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
6280       isa<ConstantFPSDNode>(N0.getOperand(0)) &&
6281       VT.isInteger() && !VT.isVector()) {
6282     unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
6283     EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
6284     if (isTypeLegal(IntXVT)) {
6285       SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6286                               IntXVT, N0.getOperand(1));
6287       AddToWorkList(X.getNode());
6288
6289       // If X has a different width than the result/lhs, sext it or truncate it.
6290       unsigned VTWidth = VT.getSizeInBits();
6291       if (OrigXWidth < VTWidth) {
6292         X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
6293         AddToWorkList(X.getNode());
6294       } else if (OrigXWidth > VTWidth) {
6295         // To get the sign bit in the right place, we have to shift it right
6296         // before truncating.
6297         X = DAG.getNode(ISD::SRL, SDLoc(X),
6298                         X.getValueType(), X,
6299                         DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
6300         AddToWorkList(X.getNode());
6301         X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
6302         AddToWorkList(X.getNode());
6303       }
6304
6305       APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6306       X = DAG.getNode(ISD::AND, SDLoc(X), VT,
6307                       X, DAG.getConstant(SignBit, VT));
6308       AddToWorkList(X.getNode());
6309
6310       SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6311                                 VT, N0.getOperand(0));
6312       Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
6313                         Cst, DAG.getConstant(~SignBit, VT));
6314       AddToWorkList(Cst.getNode());
6315
6316       return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
6317     }
6318   }
6319
6320   // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
6321   if (N0.getOpcode() == ISD::BUILD_PAIR) {
6322     SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
6323     if (CombineLD.getNode())
6324       return CombineLD;
6325   }
6326
6327   return SDValue();
6328 }
6329
6330 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
6331   EVT VT = N->getValueType(0);
6332   return CombineConsecutiveLoads(N, VT);
6333 }
6334
6335 /// ConstantFoldBITCASTofBUILD_VECTOR - We know that BV is a build_vector
6336 /// node with Constant, ConstantFP or Undef operands.  DstEltVT indicates the
6337 /// destination element value type.
6338 SDValue DAGCombiner::
6339 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
6340   EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
6341
6342   // If this is already the right type, we're done.
6343   if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
6344
6345   unsigned SrcBitSize = SrcEltVT.getSizeInBits();
6346   unsigned DstBitSize = DstEltVT.getSizeInBits();
6347
6348   // If this is a conversion of N elements of one type to N elements of another
6349   // type, convert each element.  This handles FP<->INT cases.
6350   if (SrcBitSize == DstBitSize) {
6351     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6352                               BV->getValueType(0).getVectorNumElements());
6353
6354     // Due to the FP element handling below calling this routine recursively,
6355     // we can end up with a scalar-to-vector node here.
6356     if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
6357       return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6358                          DAG.getNode(ISD::BITCAST, SDLoc(BV),
6359                                      DstEltVT, BV->getOperand(0)));
6360
6361     SmallVector<SDValue, 8> Ops;
6362     for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6363       SDValue Op = BV->getOperand(i);
6364       // If the vector element type is not legal, the BUILD_VECTOR operands
6365       // are promoted and implicitly truncated.  Make that explicit here.
6366       if (Op.getValueType() != SrcEltVT)
6367         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
6368       Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
6369                                 DstEltVT, Op));
6370       AddToWorkList(Ops.back().getNode());
6371     }
6372     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6373   }
6374
6375   // Otherwise, we're growing or shrinking the elements.  To avoid having to
6376   // handle annoying details of growing/shrinking FP values, we convert them to
6377   // int first.
6378   if (SrcEltVT.isFloatingPoint()) {
6379     // Convert the input float vector to a int vector where the elements are the
6380     // same sizes.
6381     assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!");
6382     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
6383     BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
6384     SrcEltVT = IntVT;
6385   }
6386
6387   // Now we know the input is an integer vector.  If the output is a FP type,
6388   // convert to integer first, then to FP of the right size.
6389   if (DstEltVT.isFloatingPoint()) {
6390     assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!");
6391     EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
6392     SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
6393
6394     // Next, convert to FP elements of the same size.
6395     return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
6396   }
6397
6398   // Okay, we know the src/dst types are both integers of differing types.
6399   // Handling growing first.
6400   assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
6401   if (SrcBitSize < DstBitSize) {
6402     unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
6403
6404     SmallVector<SDValue, 8> Ops;
6405     for (unsigned i = 0, e = BV->getNumOperands(); i != e;
6406          i += NumInputsPerOutput) {
6407       bool isLE = TLI.isLittleEndian();
6408       APInt NewBits = APInt(DstBitSize, 0);
6409       bool EltIsUndef = true;
6410       for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
6411         // Shift the previously computed bits over.
6412         NewBits <<= SrcBitSize;
6413         SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
6414         if (Op.getOpcode() == ISD::UNDEF) continue;
6415         EltIsUndef = false;
6416
6417         NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
6418                    zextOrTrunc(SrcBitSize).zext(DstBitSize);
6419       }
6420
6421       if (EltIsUndef)
6422         Ops.push_back(DAG.getUNDEF(DstEltVT));
6423       else
6424         Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
6425     }
6426
6427     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
6428     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6429   }
6430
6431   // Finally, this must be the case where we are shrinking elements: each input
6432   // turns into multiple outputs.
6433   bool isS2V = ISD::isScalarToVector(BV);
6434   unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
6435   EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6436                             NumOutputsPerInput*BV->getNumOperands());
6437   SmallVector<SDValue, 8> Ops;
6438
6439   for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6440     if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
6441       for (unsigned j = 0; j != NumOutputsPerInput; ++j)
6442         Ops.push_back(DAG.getUNDEF(DstEltVT));
6443       continue;
6444     }
6445
6446     APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
6447                   getAPIntValue().zextOrTrunc(SrcBitSize);
6448
6449     for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
6450       APInt ThisVal = OpVal.trunc(DstBitSize);
6451       Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
6452       if (isS2V && i == 0 && j == 0 && ThisVal.zext(SrcBitSize) == OpVal)
6453         // Simply turn this into a SCALAR_TO_VECTOR of the new type.
6454         return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6455                            Ops[0]);
6456       OpVal = OpVal.lshr(DstBitSize);
6457     }
6458
6459     // For big endian targets, swap the order of the pieces of each element.
6460     if (TLI.isBigEndian())
6461       std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
6462   }
6463
6464   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6465 }
6466
6467 SDValue DAGCombiner::visitFADD(SDNode *N) {
6468   SDValue N0 = N->getOperand(0);
6469   SDValue N1 = N->getOperand(1);
6470   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6471   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6472   EVT VT = N->getValueType(0);
6473
6474   // fold vector ops
6475   if (VT.isVector()) {
6476     SDValue FoldedVOp = SimplifyVBinOp(N);
6477     if (FoldedVOp.getNode()) return FoldedVOp;
6478   }
6479
6480   // fold (fadd c1, c2) -> c1 + c2
6481   if (N0CFP && N1CFP)
6482     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N1);
6483   // canonicalize constant to RHS
6484   if (N0CFP && !N1CFP)
6485     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N0);
6486   // fold (fadd A, 0) -> A
6487   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6488       N1CFP->getValueAPF().isZero())
6489     return N0;
6490   // fold (fadd A, (fneg B)) -> (fsub A, B)
6491   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6492     isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
6493     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0,
6494                        GetNegatedExpression(N1, DAG, LegalOperations));
6495   // fold (fadd (fneg A), B) -> (fsub B, A)
6496   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6497     isNegatibleForFree(N0, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
6498     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N1,
6499                        GetNegatedExpression(N0, DAG, LegalOperations));
6500
6501   // If allowed, fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
6502   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6503       N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
6504       isa<ConstantFPSDNode>(N0.getOperand(1)))
6505     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0.getOperand(0),
6506                        DAG.getNode(ISD::FADD, SDLoc(N), VT,
6507                                    N0.getOperand(1), N1));
6508
6509   // No FP constant should be created after legalization as Instruction
6510   // Selection pass has hard time in dealing with FP constant.
6511   //
6512   // We don't need test this condition for transformation like following, as
6513   // the DAG being transformed implies it is legal to take FP constant as
6514   // operand.
6515   //
6516   //  (fadd (fmul c, x), x) -> (fmul c+1, x)
6517   //
6518   bool AllowNewFpConst = (Level < AfterLegalizeDAG);
6519
6520   // If allow, fold (fadd (fneg x), x) -> 0.0
6521   if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
6522       N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
6523     return DAG.getConstantFP(0.0, VT);
6524
6525     // If allow, fold (fadd x, (fneg x)) -> 0.0
6526   if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
6527       N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
6528     return DAG.getConstantFP(0.0, VT);
6529
6530   // In unsafe math mode, we can fold chains of FADD's of the same value
6531   // into multiplications.  This transform is not safe in general because
6532   // we are reducing the number of rounding steps.
6533   if (DAG.getTarget().Options.UnsafeFPMath &&
6534       TLI.isOperationLegalOrCustom(ISD::FMUL, VT) &&
6535       !N0CFP && !N1CFP) {
6536     if (N0.getOpcode() == ISD::FMUL) {
6537       ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6538       ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
6539
6540       // (fadd (fmul c, x), x) -> (fmul x, c+1)
6541       if (CFP00 && !CFP01 && N0.getOperand(1) == N1) {
6542         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6543                                      SDValue(CFP00, 0),
6544                                      DAG.getConstantFP(1.0, VT));
6545         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6546                            N1, NewCFP);
6547       }
6548
6549       // (fadd (fmul x, c), x) -> (fmul x, c+1)
6550       if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
6551         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6552                                      SDValue(CFP01, 0),
6553                                      DAG.getConstantFP(1.0, VT));
6554         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6555                            N1, NewCFP);
6556       }
6557
6558       // (fadd (fmul c, x), (fadd x, x)) -> (fmul x, c+2)
6559       if (CFP00 && !CFP01 && N1.getOpcode() == ISD::FADD &&
6560           N1.getOperand(0) == N1.getOperand(1) &&
6561           N0.getOperand(1) == N1.getOperand(0)) {
6562         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6563                                      SDValue(CFP00, 0),
6564                                      DAG.getConstantFP(2.0, VT));
6565         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6566                            N0.getOperand(1), NewCFP);
6567       }
6568
6569       // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
6570       if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
6571           N1.getOperand(0) == N1.getOperand(1) &&
6572           N0.getOperand(0) == N1.getOperand(0)) {
6573         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6574                                      SDValue(CFP01, 0),
6575                                      DAG.getConstantFP(2.0, VT));
6576         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6577                            N0.getOperand(0), NewCFP);
6578       }
6579     }
6580
6581     if (N1.getOpcode() == ISD::FMUL) {
6582       ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6583       ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
6584
6585       // (fadd x, (fmul c, x)) -> (fmul x, c+1)
6586       if (CFP10 && !CFP11 && N1.getOperand(1) == N0) {
6587         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6588                                      SDValue(CFP10, 0),
6589                                      DAG.getConstantFP(1.0, VT));
6590         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6591                            N0, NewCFP);
6592       }
6593
6594       // (fadd x, (fmul x, c)) -> (fmul x, c+1)
6595       if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
6596         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6597                                      SDValue(CFP11, 0),
6598                                      DAG.getConstantFP(1.0, VT));
6599         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6600                            N0, NewCFP);
6601       }
6602
6603
6604       // (fadd (fadd x, x), (fmul c, x)) -> (fmul x, c+2)
6605       if (CFP10 && !CFP11 && N0.getOpcode() == ISD::FADD &&
6606           N0.getOperand(0) == N0.getOperand(1) &&
6607           N1.getOperand(1) == N0.getOperand(0)) {
6608         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6609                                      SDValue(CFP10, 0),
6610                                      DAG.getConstantFP(2.0, VT));
6611         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6612                            N1.getOperand(1), NewCFP);
6613       }
6614
6615       // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
6616       if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
6617           N0.getOperand(0) == N0.getOperand(1) &&
6618           N1.getOperand(0) == N0.getOperand(0)) {
6619         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6620                                      SDValue(CFP11, 0),
6621                                      DAG.getConstantFP(2.0, VT));
6622         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6623                            N1.getOperand(0), NewCFP);
6624       }
6625     }
6626
6627     if (N0.getOpcode() == ISD::FADD && AllowNewFpConst) {
6628       ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6629       // (fadd (fadd x, x), x) -> (fmul x, 3.0)
6630       if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
6631           (N0.getOperand(0) == N1))
6632         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6633                            N1, DAG.getConstantFP(3.0, VT));
6634     }
6635
6636     if (N1.getOpcode() == ISD::FADD && AllowNewFpConst) {
6637       ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6638       // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
6639       if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
6640           N1.getOperand(0) == N0)
6641         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6642                            N0, DAG.getConstantFP(3.0, VT));
6643     }
6644
6645     // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
6646     if (AllowNewFpConst &&
6647         N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
6648         N0.getOperand(0) == N0.getOperand(1) &&
6649         N1.getOperand(0) == N1.getOperand(1) &&
6650         N0.getOperand(0) == N1.getOperand(0))
6651       return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6652                          N0.getOperand(0),
6653                          DAG.getConstantFP(4.0, VT));
6654   }
6655
6656   // FADD -> FMA combines:
6657   if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
6658        DAG.getTarget().Options.UnsafeFPMath) &&
6659       DAG.getTarget().getTargetLowering()->isFMAFasterThanFMulAndFAdd(VT) &&
6660       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6661
6662     // fold (fadd (fmul x, y), z) -> (fma x, y, z)
6663     if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
6664       return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6665                          N0.getOperand(0), N0.getOperand(1), N1);
6666
6667     // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
6668     // Note: Commutes FADD operands.
6669     if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
6670       return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6671                          N1.getOperand(0), N1.getOperand(1), N0);
6672   }
6673
6674   return SDValue();
6675 }
6676
6677 SDValue DAGCombiner::visitFSUB(SDNode *N) {
6678   SDValue N0 = N->getOperand(0);
6679   SDValue N1 = N->getOperand(1);
6680   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6681   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6682   EVT VT = N->getValueType(0);
6683   SDLoc dl(N);
6684
6685   // fold vector ops
6686   if (VT.isVector()) {
6687     SDValue FoldedVOp = SimplifyVBinOp(N);
6688     if (FoldedVOp.getNode()) return FoldedVOp;
6689   }
6690
6691   // fold (fsub c1, c2) -> c1-c2
6692   if (N0CFP && N1CFP)
6693     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0, N1);
6694   // fold (fsub A, 0) -> A
6695   if (DAG.getTarget().Options.UnsafeFPMath &&
6696       N1CFP && N1CFP->getValueAPF().isZero())
6697     return N0;
6698   // fold (fsub 0, B) -> -B
6699   if (DAG.getTarget().Options.UnsafeFPMath &&
6700       N0CFP && N0CFP->getValueAPF().isZero()) {
6701     if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
6702       return GetNegatedExpression(N1, DAG, LegalOperations);
6703     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6704       return DAG.getNode(ISD::FNEG, dl, VT, N1);
6705   }
6706   // fold (fsub A, (fneg B)) -> (fadd A, B)
6707   if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
6708     return DAG.getNode(ISD::FADD, dl, VT, N0,
6709                        GetNegatedExpression(N1, DAG, LegalOperations));
6710
6711   // If 'unsafe math' is enabled, fold
6712   //    (fsub x, x) -> 0.0 &
6713   //    (fsub x, (fadd x, y)) -> (fneg y) &
6714   //    (fsub x, (fadd y, x)) -> (fneg y)
6715   if (DAG.getTarget().Options.UnsafeFPMath) {
6716     if (N0 == N1)
6717       return DAG.getConstantFP(0.0f, VT);
6718
6719     if (N1.getOpcode() == ISD::FADD) {
6720       SDValue N10 = N1->getOperand(0);
6721       SDValue N11 = N1->getOperand(1);
6722
6723       if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI,
6724                                           &DAG.getTarget().Options))
6725         return GetNegatedExpression(N11, DAG, LegalOperations);
6726
6727       if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI,
6728                                           &DAG.getTarget().Options))
6729         return GetNegatedExpression(N10, DAG, LegalOperations);
6730     }
6731   }
6732
6733   // FSUB -> FMA combines:
6734   if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
6735        DAG.getTarget().Options.UnsafeFPMath) &&
6736       DAG.getTarget().getTargetLowering()->isFMAFasterThanFMulAndFAdd(VT) &&
6737       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6738
6739     // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
6740     if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
6741       return DAG.getNode(ISD::FMA, dl, VT,
6742                          N0.getOperand(0), N0.getOperand(1),
6743                          DAG.getNode(ISD::FNEG, dl, VT, N1));
6744
6745     // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
6746     // Note: Commutes FSUB operands.
6747     if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
6748       return DAG.getNode(ISD::FMA, dl, VT,
6749                          DAG.getNode(ISD::FNEG, dl, VT,
6750                          N1.getOperand(0)),
6751                          N1.getOperand(1), N0);
6752
6753     // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
6754     if (N0.getOpcode() == ISD::FNEG &&
6755         N0.getOperand(0).getOpcode() == ISD::FMUL &&
6756         N0->hasOneUse() && N0.getOperand(0).hasOneUse()) {
6757       SDValue N00 = N0.getOperand(0).getOperand(0);
6758       SDValue N01 = N0.getOperand(0).getOperand(1);
6759       return DAG.getNode(ISD::FMA, dl, VT,
6760                          DAG.getNode(ISD::FNEG, dl, VT, N00), N01,
6761                          DAG.getNode(ISD::FNEG, dl, VT, N1));
6762     }
6763   }
6764
6765   return SDValue();
6766 }
6767
6768 SDValue DAGCombiner::visitFMUL(SDNode *N) {
6769   SDValue N0 = N->getOperand(0);
6770   SDValue N1 = N->getOperand(1);
6771   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6772   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6773   EVT VT = N->getValueType(0);
6774   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6775
6776   // fold vector ops
6777   if (VT.isVector()) {
6778     SDValue FoldedVOp = SimplifyVBinOp(N);
6779     if (FoldedVOp.getNode()) return FoldedVOp;
6780   }
6781
6782   // fold (fmul c1, c2) -> c1*c2
6783   if (N0CFP && N1CFP)
6784     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, N1);
6785   // canonicalize constant to RHS
6786   if (N0CFP && !N1CFP)
6787     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, N0);
6788   // fold (fmul A, 0) -> 0
6789   if (DAG.getTarget().Options.UnsafeFPMath &&
6790       N1CFP && N1CFP->getValueAPF().isZero())
6791     return N1;
6792   // fold (fmul A, 0) -> 0, vector edition.
6793   if (DAG.getTarget().Options.UnsafeFPMath &&
6794       ISD::isBuildVectorAllZeros(N1.getNode()))
6795     return N1;
6796   // fold (fmul A, 1.0) -> A
6797   if (N1CFP && N1CFP->isExactlyValue(1.0))
6798     return N0;
6799   // fold (fmul X, 2.0) -> (fadd X, X)
6800   if (N1CFP && N1CFP->isExactlyValue(+2.0))
6801     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N0);
6802   // fold (fmul X, -1.0) -> (fneg X)
6803   if (N1CFP && N1CFP->isExactlyValue(-1.0))
6804     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6805       return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
6806
6807   // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
6808   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
6809                                        &DAG.getTarget().Options)) {
6810     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
6811                                          &DAG.getTarget().Options)) {
6812       // Both can be negated for free, check to see if at least one is cheaper
6813       // negated.
6814       if (LHSNeg == 2 || RHSNeg == 2)
6815         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6816                            GetNegatedExpression(N0, DAG, LegalOperations),
6817                            GetNegatedExpression(N1, DAG, LegalOperations));
6818     }
6819   }
6820
6821   // If allowed, fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
6822   if (DAG.getTarget().Options.UnsafeFPMath &&
6823       N1CFP && N0.getOpcode() == ISD::FMUL &&
6824       N0.getNode()->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
6825     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
6826                        DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6827                                    N0.getOperand(1), N1));
6828
6829   return SDValue();
6830 }
6831
6832 SDValue DAGCombiner::visitFMA(SDNode *N) {
6833   SDValue N0 = N->getOperand(0);
6834   SDValue N1 = N->getOperand(1);
6835   SDValue N2 = N->getOperand(2);
6836   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6837   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6838   EVT VT = N->getValueType(0);
6839   SDLoc dl(N);
6840
6841   if (DAG.getTarget().Options.UnsafeFPMath) {
6842     if (N0CFP && N0CFP->isZero())
6843       return N2;
6844     if (N1CFP && N1CFP->isZero())
6845       return N2;
6846   }
6847   if (N0CFP && N0CFP->isExactlyValue(1.0))
6848     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
6849   if (N1CFP && N1CFP->isExactlyValue(1.0))
6850     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
6851
6852   // Canonicalize (fma c, x, y) -> (fma x, c, y)
6853   if (N0CFP && !N1CFP)
6854     return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
6855
6856   // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
6857   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6858       N2.getOpcode() == ISD::FMUL &&
6859       N0 == N2.getOperand(0) &&
6860       N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
6861     return DAG.getNode(ISD::FMUL, dl, VT, N0,
6862                        DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
6863   }
6864
6865
6866   // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
6867   if (DAG.getTarget().Options.UnsafeFPMath &&
6868       N0.getOpcode() == ISD::FMUL && N1CFP &&
6869       N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
6870     return DAG.getNode(ISD::FMA, dl, VT,
6871                        N0.getOperand(0),
6872                        DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
6873                        N2);
6874   }
6875
6876   // (fma x, 1, y) -> (fadd x, y)
6877   // (fma x, -1, y) -> (fadd (fneg x), y)
6878   if (N1CFP) {
6879     if (N1CFP->isExactlyValue(1.0))
6880       return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
6881
6882     if (N1CFP->isExactlyValue(-1.0) &&
6883         (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
6884       SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
6885       AddToWorkList(RHSNeg.getNode());
6886       return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
6887     }
6888   }
6889
6890   // (fma x, c, x) -> (fmul x, (c+1))
6891   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP && N0 == N2)
6892     return DAG.getNode(ISD::FMUL, dl, VT, N0,
6893                        DAG.getNode(ISD::FADD, dl, VT,
6894                                    N1, DAG.getConstantFP(1.0, VT)));
6895
6896   // (fma x, c, (fneg x)) -> (fmul x, (c-1))
6897   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6898       N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
6899     return DAG.getNode(ISD::FMUL, dl, VT, N0,
6900                        DAG.getNode(ISD::FADD, dl, VT,
6901                                    N1, DAG.getConstantFP(-1.0, VT)));
6902
6903
6904   return SDValue();
6905 }
6906
6907 SDValue DAGCombiner::visitFDIV(SDNode *N) {
6908   SDValue N0 = N->getOperand(0);
6909   SDValue N1 = N->getOperand(1);
6910   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6911   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6912   EVT VT = N->getValueType(0);
6913   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6914
6915   // fold vector ops
6916   if (VT.isVector()) {
6917     SDValue FoldedVOp = SimplifyVBinOp(N);
6918     if (FoldedVOp.getNode()) return FoldedVOp;
6919   }
6920
6921   // fold (fdiv c1, c2) -> c1/c2
6922   if (N0CFP && N1CFP)
6923     return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
6924
6925   // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
6926   if (N1CFP && DAG.getTarget().Options.UnsafeFPMath) {
6927     // Compute the reciprocal 1.0 / c2.
6928     APFloat N1APF = N1CFP->getValueAPF();
6929     APFloat Recip(N1APF.getSemantics(), 1); // 1.0
6930     APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
6931     // Only do the transform if the reciprocal is a legal fp immediate that
6932     // isn't too nasty (eg NaN, denormal, ...).
6933     if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
6934         (!LegalOperations ||
6935          // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
6936          // backend)... we should handle this gracefully after Legalize.
6937          // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
6938          TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
6939          TLI.isFPImmLegal(Recip, VT)))
6940       return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0,
6941                          DAG.getConstantFP(Recip, VT));
6942   }
6943
6944   // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
6945   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
6946                                        &DAG.getTarget().Options)) {
6947     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
6948                                          &DAG.getTarget().Options)) {
6949       // Both can be negated for free, check to see if at least one is cheaper
6950       // negated.
6951       if (LHSNeg == 2 || RHSNeg == 2)
6952         return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
6953                            GetNegatedExpression(N0, DAG, LegalOperations),
6954                            GetNegatedExpression(N1, DAG, LegalOperations));
6955     }
6956   }
6957
6958   return SDValue();
6959 }
6960
6961 SDValue DAGCombiner::visitFREM(SDNode *N) {
6962   SDValue N0 = N->getOperand(0);
6963   SDValue N1 = N->getOperand(1);
6964   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6965   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6966   EVT VT = N->getValueType(0);
6967
6968   // fold (frem c1, c2) -> fmod(c1,c2)
6969   if (N0CFP && N1CFP)
6970     return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
6971
6972   return SDValue();
6973 }
6974
6975 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
6976   SDValue N0 = N->getOperand(0);
6977   SDValue N1 = N->getOperand(1);
6978   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6979   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6980   EVT VT = N->getValueType(0);
6981
6982   if (N0CFP && N1CFP)  // Constant fold
6983     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
6984
6985   if (N1CFP) {
6986     const APFloat& V = N1CFP->getValueAPF();
6987     // copysign(x, c1) -> fabs(x)       iff ispos(c1)
6988     // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
6989     if (!V.isNegative()) {
6990       if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
6991         return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
6992     } else {
6993       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6994         return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
6995                            DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
6996     }
6997   }
6998
6999   // copysign(fabs(x), y) -> copysign(x, y)
7000   // copysign(fneg(x), y) -> copysign(x, y)
7001   // copysign(copysign(x,z), y) -> copysign(x, y)
7002   if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
7003       N0.getOpcode() == ISD::FCOPYSIGN)
7004     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7005                        N0.getOperand(0), N1);
7006
7007   // copysign(x, abs(y)) -> abs(x)
7008   if (N1.getOpcode() == ISD::FABS)
7009     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7010
7011   // copysign(x, copysign(y,z)) -> copysign(x, z)
7012   if (N1.getOpcode() == ISD::FCOPYSIGN)
7013     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7014                        N0, N1.getOperand(1));
7015
7016   // copysign(x, fp_extend(y)) -> copysign(x, y)
7017   // copysign(x, fp_round(y)) -> copysign(x, y)
7018   if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
7019     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7020                        N0, N1.getOperand(0));
7021
7022   return SDValue();
7023 }
7024
7025 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
7026   SDValue N0 = N->getOperand(0);
7027   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
7028   EVT VT = N->getValueType(0);
7029   EVT OpVT = N0.getValueType();
7030
7031   // fold (sint_to_fp c1) -> c1fp
7032   if (N0C &&
7033       // ...but only if the target supports immediate floating-point values
7034       (!LegalOperations ||
7035        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
7036     return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
7037
7038   // If the input is a legal type, and SINT_TO_FP is not legal on this target,
7039   // but UINT_TO_FP is legal on this target, try to convert.
7040   if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
7041       TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
7042     // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
7043     if (DAG.SignBitIsZero(N0))
7044       return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
7045   }
7046
7047   // The next optimizations are desirable only if SELECT_CC can be lowered.
7048   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
7049     // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
7050     if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
7051         !VT.isVector() &&
7052         (!LegalOperations ||
7053          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7054       SDValue Ops[] =
7055         { N0.getOperand(0), N0.getOperand(1),
7056           DAG.getConstantFP(-1.0, VT) , DAG.getConstantFP(0.0, VT),
7057           N0.getOperand(2) };
7058       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7059     }
7060
7061     // fold (sint_to_fp (zext (setcc x, y, cc))) ->
7062     //      (select_cc x, y, 1.0, 0.0,, cc)
7063     if (N0.getOpcode() == ISD::ZERO_EXTEND &&
7064         N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
7065         (!LegalOperations ||
7066          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7067       SDValue Ops[] =
7068         { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
7069           DAG.getConstantFP(1.0, VT) , DAG.getConstantFP(0.0, VT),
7070           N0.getOperand(0).getOperand(2) };
7071       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7072     }
7073   }
7074
7075   return SDValue();
7076 }
7077
7078 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
7079   SDValue N0 = N->getOperand(0);
7080   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
7081   EVT VT = N->getValueType(0);
7082   EVT OpVT = N0.getValueType();
7083
7084   // fold (uint_to_fp c1) -> c1fp
7085   if (N0C &&
7086       // ...but only if the target supports immediate floating-point values
7087       (!LegalOperations ||
7088        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
7089     return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
7090
7091   // If the input is a legal type, and UINT_TO_FP is not legal on this target,
7092   // but SINT_TO_FP is legal on this target, try to convert.
7093   if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
7094       TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
7095     // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
7096     if (DAG.SignBitIsZero(N0))
7097       return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
7098   }
7099
7100   // The next optimizations are desirable only if SELECT_CC can be lowered.
7101   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
7102     // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
7103
7104     if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
7105         (!LegalOperations ||
7106          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7107       SDValue Ops[] =
7108         { N0.getOperand(0), N0.getOperand(1),
7109           DAG.getConstantFP(1.0, VT),  DAG.getConstantFP(0.0, VT),
7110           N0.getOperand(2) };
7111       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7112     }
7113   }
7114
7115   return SDValue();
7116 }
7117
7118 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
7119   SDValue N0 = N->getOperand(0);
7120   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7121   EVT VT = N->getValueType(0);
7122
7123   // fold (fp_to_sint c1fp) -> c1
7124   if (N0CFP)
7125     return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
7126
7127   return SDValue();
7128 }
7129
7130 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
7131   SDValue N0 = N->getOperand(0);
7132   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7133   EVT VT = N->getValueType(0);
7134
7135   // fold (fp_to_uint c1fp) -> c1
7136   if (N0CFP)
7137     return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
7138
7139   return SDValue();
7140 }
7141
7142 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
7143   SDValue N0 = N->getOperand(0);
7144   SDValue N1 = N->getOperand(1);
7145   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7146   EVT VT = N->getValueType(0);
7147
7148   // fold (fp_round c1fp) -> c1fp
7149   if (N0CFP)
7150     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
7151
7152   // fold (fp_round (fp_extend x)) -> x
7153   if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
7154     return N0.getOperand(0);
7155
7156   // fold (fp_round (fp_round x)) -> (fp_round x)
7157   if (N0.getOpcode() == ISD::FP_ROUND) {
7158     // This is a value preserving truncation if both round's are.
7159     bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
7160                    N0.getNode()->getConstantOperandVal(1) == 1;
7161     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0.getOperand(0),
7162                        DAG.getIntPtrConstant(IsTrunc));
7163   }
7164
7165   // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
7166   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
7167     SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
7168                               N0.getOperand(0), N1);
7169     AddToWorkList(Tmp.getNode());
7170     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7171                        Tmp, N0.getOperand(1));
7172   }
7173
7174   return SDValue();
7175 }
7176
7177 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
7178   SDValue N0 = N->getOperand(0);
7179   EVT VT = N->getValueType(0);
7180   EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
7181   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7182
7183   // fold (fp_round_inreg c1fp) -> c1fp
7184   if (N0CFP && isTypeLegal(EVT)) {
7185     SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
7186     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, Round);
7187   }
7188
7189   return SDValue();
7190 }
7191
7192 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
7193   SDValue N0 = N->getOperand(0);
7194   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7195   EVT VT = N->getValueType(0);
7196
7197   // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
7198   if (N->hasOneUse() &&
7199       N->use_begin()->getOpcode() == ISD::FP_ROUND)
7200     return SDValue();
7201
7202   // fold (fp_extend c1fp) -> c1fp
7203   if (N0CFP)
7204     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
7205
7206   // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
7207   // value of X.
7208   if (N0.getOpcode() == ISD::FP_ROUND
7209       && N0.getNode()->getConstantOperandVal(1) == 1) {
7210     SDValue In = N0.getOperand(0);
7211     if (In.getValueType() == VT) return In;
7212     if (VT.bitsLT(In.getValueType()))
7213       return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
7214                          In, N0.getOperand(1));
7215     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
7216   }
7217
7218   // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
7219   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7220        TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType())) {
7221     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7222     SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
7223                                      LN0->getChain(),
7224                                      LN0->getBasePtr(), N0.getValueType(),
7225                                      LN0->getMemOperand());
7226     CombineTo(N, ExtLoad);
7227     CombineTo(N0.getNode(),
7228               DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
7229                           N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
7230               ExtLoad.getValue(1));
7231     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7232   }
7233
7234   return SDValue();
7235 }
7236
7237 SDValue DAGCombiner::visitFNEG(SDNode *N) {
7238   SDValue N0 = N->getOperand(0);
7239   EVT VT = N->getValueType(0);
7240
7241   if (VT.isVector()) {
7242     SDValue FoldedVOp = SimplifyVUnaryOp(N);
7243     if (FoldedVOp.getNode()) return FoldedVOp;
7244   }
7245
7246   if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
7247                          &DAG.getTarget().Options))
7248     return GetNegatedExpression(N0, DAG, LegalOperations);
7249
7250   // Transform fneg(bitconvert(x)) -> bitconvert(x^sign) to avoid loading
7251   // constant pool values.
7252   if (!TLI.isFNegFree(VT) && N0.getOpcode() == ISD::BITCAST &&
7253       !VT.isVector() &&
7254       N0.getNode()->hasOneUse() &&
7255       N0.getOperand(0).getValueType().isInteger()) {
7256     SDValue Int = N0.getOperand(0);
7257     EVT IntVT = Int.getValueType();
7258     if (IntVT.isInteger() && !IntVT.isVector()) {
7259       Int = DAG.getNode(ISD::XOR, SDLoc(N0), IntVT, Int,
7260               DAG.getConstant(APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
7261       AddToWorkList(Int.getNode());
7262       return DAG.getNode(ISD::BITCAST, SDLoc(N),
7263                          VT, Int);
7264     }
7265   }
7266
7267   // (fneg (fmul c, x)) -> (fmul -c, x)
7268   if (N0.getOpcode() == ISD::FMUL) {
7269     ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
7270     if (CFP1) {
7271       APFloat CVal = CFP1->getValueAPF();
7272       CVal.changeSign();
7273       if (Level >= AfterLegalizeDAG &&
7274           (TLI.isFPImmLegal(CVal, N->getValueType(0)) ||
7275            TLI.isOperationLegal(ISD::ConstantFP, N->getValueType(0))))
7276         return DAG.getNode(
7277             ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
7278             DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0.getOperand(1)));
7279     }
7280   }
7281
7282   return SDValue();
7283 }
7284
7285 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
7286   SDValue N0 = N->getOperand(0);
7287   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7288   EVT VT = N->getValueType(0);
7289
7290   // fold (fceil c1) -> fceil(c1)
7291   if (N0CFP)
7292     return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
7293
7294   return SDValue();
7295 }
7296
7297 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
7298   SDValue N0 = N->getOperand(0);
7299   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7300   EVT VT = N->getValueType(0);
7301
7302   // fold (ftrunc c1) -> ftrunc(c1)
7303   if (N0CFP)
7304     return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
7305
7306   return SDValue();
7307 }
7308
7309 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
7310   SDValue N0 = N->getOperand(0);
7311   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7312   EVT VT = N->getValueType(0);
7313
7314   // fold (ffloor c1) -> ffloor(c1)
7315   if (N0CFP)
7316     return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
7317
7318   return SDValue();
7319 }
7320
7321 SDValue DAGCombiner::visitFABS(SDNode *N) {
7322   SDValue N0 = N->getOperand(0);
7323   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7324   EVT VT = N->getValueType(0);
7325
7326   if (VT.isVector()) {
7327     SDValue FoldedVOp = SimplifyVUnaryOp(N);
7328     if (FoldedVOp.getNode()) return FoldedVOp;
7329   }
7330
7331   // fold (fabs c1) -> fabs(c1)
7332   if (N0CFP)
7333     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7334   // fold (fabs (fabs x)) -> (fabs x)
7335   if (N0.getOpcode() == ISD::FABS)
7336     return N->getOperand(0);
7337   // fold (fabs (fneg x)) -> (fabs x)
7338   // fold (fabs (fcopysign x, y)) -> (fabs x)
7339   if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
7340     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
7341
7342   // Transform fabs(bitconvert(x)) -> bitconvert(x&~sign) to avoid loading
7343   // constant pool values.
7344   if (!TLI.isFAbsFree(VT) &&
7345       N0.getOpcode() == ISD::BITCAST && N0.getNode()->hasOneUse() &&
7346       N0.getOperand(0).getValueType().isInteger() &&
7347       !N0.getOperand(0).getValueType().isVector()) {
7348     SDValue Int = N0.getOperand(0);
7349     EVT IntVT = Int.getValueType();
7350     if (IntVT.isInteger() && !IntVT.isVector()) {
7351       Int = DAG.getNode(ISD::AND, SDLoc(N0), IntVT, Int,
7352              DAG.getConstant(~APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
7353       AddToWorkList(Int.getNode());
7354       return DAG.getNode(ISD::BITCAST, SDLoc(N),
7355                          N->getValueType(0), Int);
7356     }
7357   }
7358
7359   return SDValue();
7360 }
7361
7362 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
7363   SDValue Chain = N->getOperand(0);
7364   SDValue N1 = N->getOperand(1);
7365   SDValue N2 = N->getOperand(2);
7366
7367   // If N is a constant we could fold this into a fallthrough or unconditional
7368   // branch. However that doesn't happen very often in normal code, because
7369   // Instcombine/SimplifyCFG should have handled the available opportunities.
7370   // If we did this folding here, it would be necessary to update the
7371   // MachineBasicBlock CFG, which is awkward.
7372
7373   // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
7374   // on the target.
7375   if (N1.getOpcode() == ISD::SETCC &&
7376       TLI.isOperationLegalOrCustom(ISD::BR_CC,
7377                                    N1.getOperand(0).getValueType())) {
7378     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7379                        Chain, N1.getOperand(2),
7380                        N1.getOperand(0), N1.getOperand(1), N2);
7381   }
7382
7383   if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
7384       ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
7385        (N1.getOperand(0).hasOneUse() &&
7386         N1.getOperand(0).getOpcode() == ISD::SRL))) {
7387     SDNode *Trunc = nullptr;
7388     if (N1.getOpcode() == ISD::TRUNCATE) {
7389       // Look pass the truncate.
7390       Trunc = N1.getNode();
7391       N1 = N1.getOperand(0);
7392     }
7393
7394     // Match this pattern so that we can generate simpler code:
7395     //
7396     //   %a = ...
7397     //   %b = and i32 %a, 2
7398     //   %c = srl i32 %b, 1
7399     //   brcond i32 %c ...
7400     //
7401     // into
7402     //
7403     //   %a = ...
7404     //   %b = and i32 %a, 2
7405     //   %c = setcc eq %b, 0
7406     //   brcond %c ...
7407     //
7408     // This applies only when the AND constant value has one bit set and the
7409     // SRL constant is equal to the log2 of the AND constant. The back-end is
7410     // smart enough to convert the result into a TEST/JMP sequence.
7411     SDValue Op0 = N1.getOperand(0);
7412     SDValue Op1 = N1.getOperand(1);
7413
7414     if (Op0.getOpcode() == ISD::AND &&
7415         Op1.getOpcode() == ISD::Constant) {
7416       SDValue AndOp1 = Op0.getOperand(1);
7417
7418       if (AndOp1.getOpcode() == ISD::Constant) {
7419         const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
7420
7421         if (AndConst.isPowerOf2() &&
7422             cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
7423           SDValue SetCC =
7424             DAG.getSetCC(SDLoc(N),
7425                          getSetCCResultType(Op0.getValueType()),
7426                          Op0, DAG.getConstant(0, Op0.getValueType()),
7427                          ISD::SETNE);
7428
7429           SDValue NewBRCond = DAG.getNode(ISD::BRCOND, SDLoc(N),
7430                                           MVT::Other, Chain, SetCC, N2);
7431           // Don't add the new BRCond into the worklist or else SimplifySelectCC
7432           // will convert it back to (X & C1) >> C2.
7433           CombineTo(N, NewBRCond, false);
7434           // Truncate is dead.
7435           if (Trunc) {
7436             removeFromWorkList(Trunc);
7437             DAG.DeleteNode(Trunc);
7438           }
7439           // Replace the uses of SRL with SETCC
7440           WorkListRemover DeadNodes(*this);
7441           DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
7442           removeFromWorkList(N1.getNode());
7443           DAG.DeleteNode(N1.getNode());
7444           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7445         }
7446       }
7447     }
7448
7449     if (Trunc)
7450       // Restore N1 if the above transformation doesn't match.
7451       N1 = N->getOperand(1);
7452   }
7453
7454   // Transform br(xor(x, y)) -> br(x != y)
7455   // Transform br(xor(xor(x,y), 1)) -> br (x == y)
7456   if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
7457     SDNode *TheXor = N1.getNode();
7458     SDValue Op0 = TheXor->getOperand(0);
7459     SDValue Op1 = TheXor->getOperand(1);
7460     if (Op0.getOpcode() == Op1.getOpcode()) {
7461       // Avoid missing important xor optimizations.
7462       SDValue Tmp = visitXOR(TheXor);
7463       if (Tmp.getNode()) {
7464         if (Tmp.getNode() != TheXor) {
7465           DEBUG(dbgs() << "\nReplacing.8 ";
7466                 TheXor->dump(&DAG);
7467                 dbgs() << "\nWith: ";
7468                 Tmp.getNode()->dump(&DAG);
7469                 dbgs() << '\n');
7470           WorkListRemover DeadNodes(*this);
7471           DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
7472           removeFromWorkList(TheXor);
7473           DAG.DeleteNode(TheXor);
7474           return DAG.getNode(ISD::BRCOND, SDLoc(N),
7475                              MVT::Other, Chain, Tmp, N2);
7476         }
7477
7478         // visitXOR has changed XOR's operands or replaced the XOR completely,
7479         // bail out.
7480         return SDValue(N, 0);
7481       }
7482     }
7483
7484     if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
7485       bool Equal = false;
7486       if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
7487         if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
7488             Op0.getOpcode() == ISD::XOR) {
7489           TheXor = Op0.getNode();
7490           Equal = true;
7491         }
7492
7493       EVT SetCCVT = N1.getValueType();
7494       if (LegalTypes)
7495         SetCCVT = getSetCCResultType(SetCCVT);
7496       SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
7497                                    SetCCVT,
7498                                    Op0, Op1,
7499                                    Equal ? ISD::SETEQ : ISD::SETNE);
7500       // Replace the uses of XOR with SETCC
7501       WorkListRemover DeadNodes(*this);
7502       DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
7503       removeFromWorkList(N1.getNode());
7504       DAG.DeleteNode(N1.getNode());
7505       return DAG.getNode(ISD::BRCOND, SDLoc(N),
7506                          MVT::Other, Chain, SetCC, N2);
7507     }
7508   }
7509
7510   return SDValue();
7511 }
7512
7513 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
7514 //
7515 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
7516   CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
7517   SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
7518
7519   // If N is a constant we could fold this into a fallthrough or unconditional
7520   // branch. However that doesn't happen very often in normal code, because
7521   // Instcombine/SimplifyCFG should have handled the available opportunities.
7522   // If we did this folding here, it would be necessary to update the
7523   // MachineBasicBlock CFG, which is awkward.
7524
7525   // Use SimplifySetCC to simplify SETCC's.
7526   SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
7527                                CondLHS, CondRHS, CC->get(), SDLoc(N),
7528                                false);
7529   if (Simp.getNode()) AddToWorkList(Simp.getNode());
7530
7531   // fold to a simpler setcc
7532   if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
7533     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7534                        N->getOperand(0), Simp.getOperand(2),
7535                        Simp.getOperand(0), Simp.getOperand(1),
7536                        N->getOperand(4));
7537
7538   return SDValue();
7539 }
7540
7541 /// canFoldInAddressingMode - Return true if 'Use' is a load or a store that
7542 /// uses N as its base pointer and that N may be folded in the load / store
7543 /// addressing mode.
7544 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
7545                                     SelectionDAG &DAG,
7546                                     const TargetLowering &TLI) {
7547   EVT VT;
7548   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(Use)) {
7549     if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
7550       return false;
7551     VT = Use->getValueType(0);
7552   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(Use)) {
7553     if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
7554       return false;
7555     VT = ST->getValue().getValueType();
7556   } else
7557     return false;
7558
7559   TargetLowering::AddrMode AM;
7560   if (N->getOpcode() == ISD::ADD) {
7561     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7562     if (Offset)
7563       // [reg +/- imm]
7564       AM.BaseOffs = Offset->getSExtValue();
7565     else
7566       // [reg +/- reg]
7567       AM.Scale = 1;
7568   } else if (N->getOpcode() == ISD::SUB) {
7569     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7570     if (Offset)
7571       // [reg +/- imm]
7572       AM.BaseOffs = -Offset->getSExtValue();
7573     else
7574       // [reg +/- reg]
7575       AM.Scale = 1;
7576   } else
7577     return false;
7578
7579   return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
7580 }
7581
7582 /// CombineToPreIndexedLoadStore - Try turning a load / store into a
7583 /// pre-indexed load / store when the base pointer is an add or subtract
7584 /// and it has other uses besides the load / store. After the
7585 /// transformation, the new indexed load / store has effectively folded
7586 /// the add / subtract in and all of its other uses are redirected to the
7587 /// new load / store.
7588 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
7589   if (Level < AfterLegalizeDAG)
7590     return false;
7591
7592   bool isLoad = true;
7593   SDValue Ptr;
7594   EVT VT;
7595   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
7596     if (LD->isIndexed())
7597       return false;
7598     VT = LD->getMemoryVT();
7599     if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
7600         !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
7601       return false;
7602     Ptr = LD->getBasePtr();
7603   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
7604     if (ST->isIndexed())
7605       return false;
7606     VT = ST->getMemoryVT();
7607     if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
7608         !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
7609       return false;
7610     Ptr = ST->getBasePtr();
7611     isLoad = false;
7612   } else {
7613     return false;
7614   }
7615
7616   // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
7617   // out.  There is no reason to make this a preinc/predec.
7618   if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
7619       Ptr.getNode()->hasOneUse())
7620     return false;
7621
7622   // Ask the target to do addressing mode selection.
7623   SDValue BasePtr;
7624   SDValue Offset;
7625   ISD::MemIndexedMode AM = ISD::UNINDEXED;
7626   if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
7627     return false;
7628
7629   // Backends without true r+i pre-indexed forms may need to pass a
7630   // constant base with a variable offset so that constant coercion
7631   // will work with the patterns in canonical form.
7632   bool Swapped = false;
7633   if (isa<ConstantSDNode>(BasePtr)) {
7634     std::swap(BasePtr, Offset);
7635     Swapped = true;
7636   }
7637
7638   // Don't create a indexed load / store with zero offset.
7639   if (isa<ConstantSDNode>(Offset) &&
7640       cast<ConstantSDNode>(Offset)->isNullValue())
7641     return false;
7642
7643   // Try turning it into a pre-indexed load / store except when:
7644   // 1) The new base ptr is a frame index.
7645   // 2) If N is a store and the new base ptr is either the same as or is a
7646   //    predecessor of the value being stored.
7647   // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
7648   //    that would create a cycle.
7649   // 4) All uses are load / store ops that use it as old base ptr.
7650
7651   // Check #1.  Preinc'ing a frame index would require copying the stack pointer
7652   // (plus the implicit offset) to a register to preinc anyway.
7653   if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7654     return false;
7655
7656   // Check #2.
7657   if (!isLoad) {
7658     SDValue Val = cast<StoreSDNode>(N)->getValue();
7659     if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
7660       return false;
7661   }
7662
7663   // If the offset is a constant, there may be other adds of constants that
7664   // can be folded with this one. We should do this to avoid having to keep
7665   // a copy of the original base pointer.
7666   SmallVector<SDNode *, 16> OtherUses;
7667   if (isa<ConstantSDNode>(Offset))
7668     for (SDNode *Use : BasePtr.getNode()->uses()) {
7669       if (Use == Ptr.getNode())
7670         continue;
7671
7672       if (Use->isPredecessorOf(N))
7673         continue;
7674
7675       if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) {
7676         OtherUses.clear();
7677         break;
7678       }
7679
7680       SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1);
7681       if (Op1.getNode() == BasePtr.getNode())
7682         std::swap(Op0, Op1);
7683       assert(Op0.getNode() == BasePtr.getNode() &&
7684              "Use of ADD/SUB but not an operand");
7685
7686       if (!isa<ConstantSDNode>(Op1)) {
7687         OtherUses.clear();
7688         break;
7689       }
7690
7691       // FIXME: In some cases, we can be smarter about this.
7692       if (Op1.getValueType() != Offset.getValueType()) {
7693         OtherUses.clear();
7694         break;
7695       }
7696
7697       OtherUses.push_back(Use);
7698     }
7699
7700   if (Swapped)
7701     std::swap(BasePtr, Offset);
7702
7703   // Now check for #3 and #4.
7704   bool RealUse = false;
7705
7706   // Caches for hasPredecessorHelper
7707   SmallPtrSet<const SDNode *, 32> Visited;
7708   SmallVector<const SDNode *, 16> Worklist;
7709
7710   for (SDNode *Use : Ptr.getNode()->uses()) {
7711     if (Use == N)
7712       continue;
7713     if (N->hasPredecessorHelper(Use, Visited, Worklist))
7714       return false;
7715
7716     // If Ptr may be folded in addressing mode of other use, then it's
7717     // not profitable to do this transformation.
7718     if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
7719       RealUse = true;
7720   }
7721
7722   if (!RealUse)
7723     return false;
7724
7725   SDValue Result;
7726   if (isLoad)
7727     Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
7728                                 BasePtr, Offset, AM);
7729   else
7730     Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
7731                                  BasePtr, Offset, AM);
7732   ++PreIndexedNodes;
7733   ++NodesCombined;
7734   DEBUG(dbgs() << "\nReplacing.4 ";
7735         N->dump(&DAG);
7736         dbgs() << "\nWith: ";
7737         Result.getNode()->dump(&DAG);
7738         dbgs() << '\n');
7739   WorkListRemover DeadNodes(*this);
7740   if (isLoad) {
7741     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7742     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
7743   } else {
7744     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
7745   }
7746
7747   // Finally, since the node is now dead, remove it from the graph.
7748   DAG.DeleteNode(N);
7749
7750   if (Swapped)
7751     std::swap(BasePtr, Offset);
7752
7753   // Replace other uses of BasePtr that can be updated to use Ptr
7754   for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
7755     unsigned OffsetIdx = 1;
7756     if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
7757       OffsetIdx = 0;
7758     assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
7759            BasePtr.getNode() && "Expected BasePtr operand");
7760
7761     // We need to replace ptr0 in the following expression:
7762     //   x0 * offset0 + y0 * ptr0 = t0
7763     // knowing that
7764     //   x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
7765     //
7766     // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
7767     // indexed load/store and the expresion that needs to be re-written.
7768     //
7769     // Therefore, we have:
7770     //   t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
7771
7772     ConstantSDNode *CN =
7773       cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
7774     int X0, X1, Y0, Y1;
7775     APInt Offset0 = CN->getAPIntValue();
7776     APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
7777
7778     X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
7779     Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
7780     X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
7781     Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
7782
7783     unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
7784
7785     APInt CNV = Offset0;
7786     if (X0 < 0) CNV = -CNV;
7787     if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
7788     else CNV = CNV - Offset1;
7789
7790     // We can now generate the new expression.
7791     SDValue NewOp1 = DAG.getConstant(CNV, CN->getValueType(0));
7792     SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
7793
7794     SDValue NewUse = DAG.getNode(Opcode,
7795                                  SDLoc(OtherUses[i]),
7796                                  OtherUses[i]->getValueType(0), NewOp1, NewOp2);
7797     DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
7798     removeFromWorkList(OtherUses[i]);
7799     DAG.DeleteNode(OtherUses[i]);
7800   }
7801
7802   // Replace the uses of Ptr with uses of the updated base value.
7803   DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
7804   removeFromWorkList(Ptr.getNode());
7805   DAG.DeleteNode(Ptr.getNode());
7806
7807   return true;
7808 }
7809
7810 /// CombineToPostIndexedLoadStore - Try to combine a load / store with a
7811 /// add / sub of the base pointer node into a post-indexed load / store.
7812 /// The transformation folded the add / subtract into the new indexed
7813 /// load / store effectively and all of its uses are redirected to the
7814 /// new load / store.
7815 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
7816   if (Level < AfterLegalizeDAG)
7817     return false;
7818
7819   bool isLoad = true;
7820   SDValue Ptr;
7821   EVT VT;
7822   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
7823     if (LD->isIndexed())
7824       return false;
7825     VT = LD->getMemoryVT();
7826     if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
7827         !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
7828       return false;
7829     Ptr = LD->getBasePtr();
7830   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
7831     if (ST->isIndexed())
7832       return false;
7833     VT = ST->getMemoryVT();
7834     if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
7835         !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
7836       return false;
7837     Ptr = ST->getBasePtr();
7838     isLoad = false;
7839   } else {
7840     return false;
7841   }
7842
7843   if (Ptr.getNode()->hasOneUse())
7844     return false;
7845
7846   for (SDNode *Op : Ptr.getNode()->uses()) {
7847     if (Op == N ||
7848         (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
7849       continue;
7850
7851     SDValue BasePtr;
7852     SDValue Offset;
7853     ISD::MemIndexedMode AM = ISD::UNINDEXED;
7854     if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
7855       // Don't create a indexed load / store with zero offset.
7856       if (isa<ConstantSDNode>(Offset) &&
7857           cast<ConstantSDNode>(Offset)->isNullValue())
7858         continue;
7859
7860       // Try turning it into a post-indexed load / store except when
7861       // 1) All uses are load / store ops that use it as base ptr (and
7862       //    it may be folded as addressing mmode).
7863       // 2) Op must be independent of N, i.e. Op is neither a predecessor
7864       //    nor a successor of N. Otherwise, if Op is folded that would
7865       //    create a cycle.
7866
7867       if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7868         continue;
7869
7870       // Check for #1.
7871       bool TryNext = false;
7872       for (SDNode *Use : BasePtr.getNode()->uses()) {
7873         if (Use == Ptr.getNode())
7874           continue;
7875
7876         // If all the uses are load / store addresses, then don't do the
7877         // transformation.
7878         if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
7879           bool RealUse = false;
7880           for (SDNode *UseUse : Use->uses()) {
7881             if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
7882               RealUse = true;
7883           }
7884
7885           if (!RealUse) {
7886             TryNext = true;
7887             break;
7888           }
7889         }
7890       }
7891
7892       if (TryNext)
7893         continue;
7894
7895       // Check for #2
7896       if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
7897         SDValue Result = isLoad
7898           ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
7899                                BasePtr, Offset, AM)
7900           : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
7901                                 BasePtr, Offset, AM);
7902         ++PostIndexedNodes;
7903         ++NodesCombined;
7904         DEBUG(dbgs() << "\nReplacing.5 ";
7905               N->dump(&DAG);
7906               dbgs() << "\nWith: ";
7907               Result.getNode()->dump(&DAG);
7908               dbgs() << '\n');
7909         WorkListRemover DeadNodes(*this);
7910         if (isLoad) {
7911           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7912           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
7913         } else {
7914           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
7915         }
7916
7917         // Finally, since the node is now dead, remove it from the graph.
7918         DAG.DeleteNode(N);
7919
7920         // Replace the uses of Use with uses of the updated base value.
7921         DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
7922                                       Result.getValue(isLoad ? 1 : 0));
7923         removeFromWorkList(Op);
7924         DAG.DeleteNode(Op);
7925         return true;
7926       }
7927     }
7928   }
7929
7930   return false;
7931 }
7932
7933 SDValue DAGCombiner::visitLOAD(SDNode *N) {
7934   LoadSDNode *LD  = cast<LoadSDNode>(N);
7935   SDValue Chain = LD->getChain();
7936   SDValue Ptr   = LD->getBasePtr();
7937
7938   // If load is not volatile and there are no uses of the loaded value (and
7939   // the updated indexed value in case of indexed loads), change uses of the
7940   // chain value into uses of the chain input (i.e. delete the dead load).
7941   if (!LD->isVolatile()) {
7942     if (N->getValueType(1) == MVT::Other) {
7943       // Unindexed loads.
7944       if (!N->hasAnyUseOfValue(0)) {
7945         // It's not safe to use the two value CombineTo variant here. e.g.
7946         // v1, chain2 = load chain1, loc
7947         // v2, chain3 = load chain2, loc
7948         // v3         = add v2, c
7949         // Now we replace use of chain2 with chain1.  This makes the second load
7950         // isomorphic to the one we are deleting, and thus makes this load live.
7951         DEBUG(dbgs() << "\nReplacing.6 ";
7952               N->dump(&DAG);
7953               dbgs() << "\nWith chain: ";
7954               Chain.getNode()->dump(&DAG);
7955               dbgs() << "\n");
7956         WorkListRemover DeadNodes(*this);
7957         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
7958
7959         if (N->use_empty()) {
7960           removeFromWorkList(N);
7961           DAG.DeleteNode(N);
7962         }
7963
7964         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7965       }
7966     } else {
7967       // Indexed loads.
7968       assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
7969       if (!N->hasAnyUseOfValue(0) && !N->hasAnyUseOfValue(1)) {
7970         SDValue Undef = DAG.getUNDEF(N->getValueType(0));
7971         DEBUG(dbgs() << "\nReplacing.7 ";
7972               N->dump(&DAG);
7973               dbgs() << "\nWith: ";
7974               Undef.getNode()->dump(&DAG);
7975               dbgs() << " and 2 other values\n");
7976         WorkListRemover DeadNodes(*this);
7977         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
7978         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1),
7979                                       DAG.getUNDEF(N->getValueType(1)));
7980         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
7981         removeFromWorkList(N);
7982         DAG.DeleteNode(N);
7983         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7984       }
7985     }
7986   }
7987
7988   // If this load is directly stored, replace the load value with the stored
7989   // value.
7990   // TODO: Handle store large -> read small portion.
7991   // TODO: Handle TRUNCSTORE/LOADEXT
7992   if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
7993     if (ISD::isNON_TRUNCStore(Chain.getNode())) {
7994       StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
7995       if (PrevST->getBasePtr() == Ptr &&
7996           PrevST->getValue().getValueType() == N->getValueType(0))
7997       return CombineTo(N, Chain.getOperand(1), Chain);
7998     }
7999   }
8000
8001   // Try to infer better alignment information than the load already has.
8002   if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
8003     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
8004       if (Align > LD->getMemOperand()->getBaseAlignment()) {
8005         SDValue NewLoad =
8006                DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
8007                               LD->getValueType(0),
8008                               Chain, Ptr, LD->getPointerInfo(),
8009                               LD->getMemoryVT(),
8010                               LD->isVolatile(), LD->isNonTemporal(), Align,
8011                               LD->getTBAAInfo());
8012         return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
8013       }
8014     }
8015   }
8016
8017   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
8018     TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
8019 #ifndef NDEBUG
8020   if (CombinerAAOnlyFunc.getNumOccurrences() &&
8021       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
8022     UseAA = false;
8023 #endif
8024   if (UseAA && LD->isUnindexed()) {
8025     // Walk up chain skipping non-aliasing memory nodes.
8026     SDValue BetterChain = FindBetterChain(N, Chain);
8027
8028     // If there is a better chain.
8029     if (Chain != BetterChain) {
8030       SDValue ReplLoad;
8031
8032       // Replace the chain to void dependency.
8033       if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
8034         ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
8035                                BetterChain, Ptr, LD->getMemOperand());
8036       } else {
8037         ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
8038                                   LD->getValueType(0),
8039                                   BetterChain, Ptr, LD->getMemoryVT(),
8040                                   LD->getMemOperand());
8041       }
8042
8043       // Create token factor to keep old chain connected.
8044       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
8045                                   MVT::Other, Chain, ReplLoad.getValue(1));
8046
8047       // Make sure the new and old chains are cleaned up.
8048       AddToWorkList(Token.getNode());
8049
8050       // Replace uses with load result and token factor. Don't add users
8051       // to work list.
8052       return CombineTo(N, ReplLoad.getValue(0), Token, false);
8053     }
8054   }
8055
8056   // Try transforming N to an indexed load.
8057   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
8058     return SDValue(N, 0);
8059
8060   // Try to slice up N to more direct loads if the slices are mapped to
8061   // different register banks or pairing can take place.
8062   if (SliceUpLoad(N))
8063     return SDValue(N, 0);
8064
8065   return SDValue();
8066 }
8067
8068 namespace {
8069 /// \brief Helper structure used to slice a load in smaller loads.
8070 /// Basically a slice is obtained from the following sequence:
8071 /// Origin = load Ty1, Base
8072 /// Shift = srl Ty1 Origin, CstTy Amount
8073 /// Inst = trunc Shift to Ty2
8074 ///
8075 /// Then, it will be rewriten into:
8076 /// Slice = load SliceTy, Base + SliceOffset
8077 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
8078 ///
8079 /// SliceTy is deduced from the number of bits that are actually used to
8080 /// build Inst.
8081 struct LoadedSlice {
8082   /// \brief Helper structure used to compute the cost of a slice.
8083   struct Cost {
8084     /// Are we optimizing for code size.
8085     bool ForCodeSize;
8086     /// Various cost.
8087     unsigned Loads;
8088     unsigned Truncates;
8089     unsigned CrossRegisterBanksCopies;
8090     unsigned ZExts;
8091     unsigned Shift;
8092
8093     Cost(bool ForCodeSize = false)
8094         : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
8095           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
8096
8097     /// \brief Get the cost of one isolated slice.
8098     Cost(const LoadedSlice &LS, bool ForCodeSize = false)
8099         : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
8100           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
8101       EVT TruncType = LS.Inst->getValueType(0);
8102       EVT LoadedType = LS.getLoadedType();
8103       if (TruncType != LoadedType &&
8104           !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
8105         ZExts = 1;
8106     }
8107
8108     /// \brief Account for slicing gain in the current cost.
8109     /// Slicing provide a few gains like removing a shift or a
8110     /// truncate. This method allows to grow the cost of the original
8111     /// load with the gain from this slice.
8112     void addSliceGain(const LoadedSlice &LS) {
8113       // Each slice saves a truncate.
8114       const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
8115       if (!TLI.isTruncateFree(LS.Inst->getValueType(0),
8116                               LS.Inst->getOperand(0).getValueType()))
8117         ++Truncates;
8118       // If there is a shift amount, this slice gets rid of it.
8119       if (LS.Shift)
8120         ++Shift;
8121       // If this slice can merge a cross register bank copy, account for it.
8122       if (LS.canMergeExpensiveCrossRegisterBankCopy())
8123         ++CrossRegisterBanksCopies;
8124     }
8125
8126     Cost &operator+=(const Cost &RHS) {
8127       Loads += RHS.Loads;
8128       Truncates += RHS.Truncates;
8129       CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
8130       ZExts += RHS.ZExts;
8131       Shift += RHS.Shift;
8132       return *this;
8133     }
8134
8135     bool operator==(const Cost &RHS) const {
8136       return Loads == RHS.Loads && Truncates == RHS.Truncates &&
8137              CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
8138              ZExts == RHS.ZExts && Shift == RHS.Shift;
8139     }
8140
8141     bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
8142
8143     bool operator<(const Cost &RHS) const {
8144       // Assume cross register banks copies are as expensive as loads.
8145       // FIXME: Do we want some more target hooks?
8146       unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
8147       unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
8148       // Unless we are optimizing for code size, consider the
8149       // expensive operation first.
8150       if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
8151         return ExpensiveOpsLHS < ExpensiveOpsRHS;
8152       return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
8153              (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
8154     }
8155
8156     bool operator>(const Cost &RHS) const { return RHS < *this; }
8157
8158     bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
8159
8160     bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
8161   };
8162   // The last instruction that represent the slice. This should be a
8163   // truncate instruction.
8164   SDNode *Inst;
8165   // The original load instruction.
8166   LoadSDNode *Origin;
8167   // The right shift amount in bits from the original load.
8168   unsigned Shift;
8169   // The DAG from which Origin came from.
8170   // This is used to get some contextual information about legal types, etc.
8171   SelectionDAG *DAG;
8172
8173   LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
8174               unsigned Shift = 0, SelectionDAG *DAG = nullptr)
8175       : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
8176
8177   LoadedSlice(const LoadedSlice &LS)
8178       : Inst(LS.Inst), Origin(LS.Origin), Shift(LS.Shift), DAG(LS.DAG) {}
8179
8180   /// \brief Get the bits used in a chunk of bits \p BitWidth large.
8181   /// \return Result is \p BitWidth and has used bits set to 1 and
8182   ///         not used bits set to 0.
8183   APInt getUsedBits() const {
8184     // Reproduce the trunc(lshr) sequence:
8185     // - Start from the truncated value.
8186     // - Zero extend to the desired bit width.
8187     // - Shift left.
8188     assert(Origin && "No original load to compare against.");
8189     unsigned BitWidth = Origin->getValueSizeInBits(0);
8190     assert(Inst && "This slice is not bound to an instruction");
8191     assert(Inst->getValueSizeInBits(0) <= BitWidth &&
8192            "Extracted slice is bigger than the whole type!");
8193     APInt UsedBits(Inst->getValueSizeInBits(0), 0);
8194     UsedBits.setAllBits();
8195     UsedBits = UsedBits.zext(BitWidth);
8196     UsedBits <<= Shift;
8197     return UsedBits;
8198   }
8199
8200   /// \brief Get the size of the slice to be loaded in bytes.
8201   unsigned getLoadedSize() const {
8202     unsigned SliceSize = getUsedBits().countPopulation();
8203     assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
8204     return SliceSize / 8;
8205   }
8206
8207   /// \brief Get the type that will be loaded for this slice.
8208   /// Note: This may not be the final type for the slice.
8209   EVT getLoadedType() const {
8210     assert(DAG && "Missing context");
8211     LLVMContext &Ctxt = *DAG->getContext();
8212     return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
8213   }
8214
8215   /// \brief Get the alignment of the load used for this slice.
8216   unsigned getAlignment() const {
8217     unsigned Alignment = Origin->getAlignment();
8218     unsigned Offset = getOffsetFromBase();
8219     if (Offset != 0)
8220       Alignment = MinAlign(Alignment, Alignment + Offset);
8221     return Alignment;
8222   }
8223
8224   /// \brief Check if this slice can be rewritten with legal operations.
8225   bool isLegal() const {
8226     // An invalid slice is not legal.
8227     if (!Origin || !Inst || !DAG)
8228       return false;
8229
8230     // Offsets are for indexed load only, we do not handle that.
8231     if (Origin->getOffset().getOpcode() != ISD::UNDEF)
8232       return false;
8233
8234     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8235
8236     // Check that the type is legal.
8237     EVT SliceType = getLoadedType();
8238     if (!TLI.isTypeLegal(SliceType))
8239       return false;
8240
8241     // Check that the load is legal for this type.
8242     if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
8243       return false;
8244
8245     // Check that the offset can be computed.
8246     // 1. Check its type.
8247     EVT PtrType = Origin->getBasePtr().getValueType();
8248     if (PtrType == MVT::Untyped || PtrType.isExtended())
8249       return false;
8250
8251     // 2. Check that it fits in the immediate.
8252     if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
8253       return false;
8254
8255     // 3. Check that the computation is legal.
8256     if (!TLI.isOperationLegal(ISD::ADD, PtrType))
8257       return false;
8258
8259     // Check that the zext is legal if it needs one.
8260     EVT TruncateType = Inst->getValueType(0);
8261     if (TruncateType != SliceType &&
8262         !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
8263       return false;
8264
8265     return true;
8266   }
8267
8268   /// \brief Get the offset in bytes of this slice in the original chunk of
8269   /// bits.
8270   /// \pre DAG != nullptr.
8271   uint64_t getOffsetFromBase() const {
8272     assert(DAG && "Missing context.");
8273     bool IsBigEndian =
8274         DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian();
8275     assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
8276     uint64_t Offset = Shift / 8;
8277     unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
8278     assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
8279            "The size of the original loaded type is not a multiple of a"
8280            " byte.");
8281     // If Offset is bigger than TySizeInBytes, it means we are loading all
8282     // zeros. This should have been optimized before in the process.
8283     assert(TySizeInBytes > Offset &&
8284            "Invalid shift amount for given loaded size");
8285     if (IsBigEndian)
8286       Offset = TySizeInBytes - Offset - getLoadedSize();
8287     return Offset;
8288   }
8289
8290   /// \brief Generate the sequence of instructions to load the slice
8291   /// represented by this object and redirect the uses of this slice to
8292   /// this new sequence of instructions.
8293   /// \pre this->Inst && this->Origin are valid Instructions and this
8294   /// object passed the legal check: LoadedSlice::isLegal returned true.
8295   /// \return The last instruction of the sequence used to load the slice.
8296   SDValue loadSlice() const {
8297     assert(Inst && Origin && "Unable to replace a non-existing slice.");
8298     const SDValue &OldBaseAddr = Origin->getBasePtr();
8299     SDValue BaseAddr = OldBaseAddr;
8300     // Get the offset in that chunk of bytes w.r.t. the endianess.
8301     int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
8302     assert(Offset >= 0 && "Offset too big to fit in int64_t!");
8303     if (Offset) {
8304       // BaseAddr = BaseAddr + Offset.
8305       EVT ArithType = BaseAddr.getValueType();
8306       BaseAddr = DAG->getNode(ISD::ADD, SDLoc(Origin), ArithType, BaseAddr,
8307                               DAG->getConstant(Offset, ArithType));
8308     }
8309
8310     // Create the type of the loaded slice according to its size.
8311     EVT SliceType = getLoadedType();
8312
8313     // Create the load for the slice.
8314     SDValue LastInst = DAG->getLoad(
8315         SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
8316         Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
8317         Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
8318     // If the final type is not the same as the loaded type, this means that
8319     // we have to pad with zero. Create a zero extend for that.
8320     EVT FinalType = Inst->getValueType(0);
8321     if (SliceType != FinalType)
8322       LastInst =
8323           DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
8324     return LastInst;
8325   }
8326
8327   /// \brief Check if this slice can be merged with an expensive cross register
8328   /// bank copy. E.g.,
8329   /// i = load i32
8330   /// f = bitcast i32 i to float
8331   bool canMergeExpensiveCrossRegisterBankCopy() const {
8332     if (!Inst || !Inst->hasOneUse())
8333       return false;
8334     SDNode *Use = *Inst->use_begin();
8335     if (Use->getOpcode() != ISD::BITCAST)
8336       return false;
8337     assert(DAG && "Missing context");
8338     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8339     EVT ResVT = Use->getValueType(0);
8340     const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
8341     const TargetRegisterClass *ArgRC =
8342         TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
8343     if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
8344       return false;
8345
8346     // At this point, we know that we perform a cross-register-bank copy.
8347     // Check if it is expensive.
8348     const TargetRegisterInfo *TRI = TLI.getTargetMachine().getRegisterInfo();
8349     // Assume bitcasts are cheap, unless both register classes do not
8350     // explicitly share a common sub class.
8351     if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
8352       return false;
8353
8354     // Check if it will be merged with the load.
8355     // 1. Check the alignment constraint.
8356     unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment(
8357         ResVT.getTypeForEVT(*DAG->getContext()));
8358
8359     if (RequiredAlignment > getAlignment())
8360       return false;
8361
8362     // 2. Check that the load is a legal operation for that type.
8363     if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
8364       return false;
8365
8366     // 3. Check that we do not have a zext in the way.
8367     if (Inst->getValueType(0) != getLoadedType())
8368       return false;
8369
8370     return true;
8371   }
8372 };
8373 }
8374
8375 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
8376 /// \p UsedBits looks like 0..0 1..1 0..0.
8377 static bool areUsedBitsDense(const APInt &UsedBits) {
8378   // If all the bits are one, this is dense!
8379   if (UsedBits.isAllOnesValue())
8380     return true;
8381
8382   // Get rid of the unused bits on the right.
8383   APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
8384   // Get rid of the unused bits on the left.
8385   if (NarrowedUsedBits.countLeadingZeros())
8386     NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
8387   // Check that the chunk of bits is completely used.
8388   return NarrowedUsedBits.isAllOnesValue();
8389 }
8390
8391 /// \brief Check whether or not \p First and \p Second are next to each other
8392 /// in memory. This means that there is no hole between the bits loaded
8393 /// by \p First and the bits loaded by \p Second.
8394 static bool areSlicesNextToEachOther(const LoadedSlice &First,
8395                                      const LoadedSlice &Second) {
8396   assert(First.Origin == Second.Origin && First.Origin &&
8397          "Unable to match different memory origins.");
8398   APInt UsedBits = First.getUsedBits();
8399   assert((UsedBits & Second.getUsedBits()) == 0 &&
8400          "Slices are not supposed to overlap.");
8401   UsedBits |= Second.getUsedBits();
8402   return areUsedBitsDense(UsedBits);
8403 }
8404
8405 /// \brief Adjust the \p GlobalLSCost according to the target
8406 /// paring capabilities and the layout of the slices.
8407 /// \pre \p GlobalLSCost should account for at least as many loads as
8408 /// there is in the slices in \p LoadedSlices.
8409 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8410                                  LoadedSlice::Cost &GlobalLSCost) {
8411   unsigned NumberOfSlices = LoadedSlices.size();
8412   // If there is less than 2 elements, no pairing is possible.
8413   if (NumberOfSlices < 2)
8414     return;
8415
8416   // Sort the slices so that elements that are likely to be next to each
8417   // other in memory are next to each other in the list.
8418   std::sort(LoadedSlices.begin(), LoadedSlices.end(),
8419             [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
8420     assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
8421     return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
8422   });
8423   const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
8424   // First (resp. Second) is the first (resp. Second) potentially candidate
8425   // to be placed in a paired load.
8426   const LoadedSlice *First = nullptr;
8427   const LoadedSlice *Second = nullptr;
8428   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
8429                 // Set the beginning of the pair.
8430                                                            First = Second) {
8431
8432     Second = &LoadedSlices[CurrSlice];
8433
8434     // If First is NULL, it means we start a new pair.
8435     // Get to the next slice.
8436     if (!First)
8437       continue;
8438
8439     EVT LoadedType = First->getLoadedType();
8440
8441     // If the types of the slices are different, we cannot pair them.
8442     if (LoadedType != Second->getLoadedType())
8443       continue;
8444
8445     // Check if the target supplies paired loads for this type.
8446     unsigned RequiredAlignment = 0;
8447     if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
8448       // move to the next pair, this type is hopeless.
8449       Second = nullptr;
8450       continue;
8451     }
8452     // Check if we meet the alignment requirement.
8453     if (RequiredAlignment > First->getAlignment())
8454       continue;
8455
8456     // Check that both loads are next to each other in memory.
8457     if (!areSlicesNextToEachOther(*First, *Second))
8458       continue;
8459
8460     assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
8461     --GlobalLSCost.Loads;
8462     // Move to the next pair.
8463     Second = nullptr;
8464   }
8465 }
8466
8467 /// \brief Check the profitability of all involved LoadedSlice.
8468 /// Currently, it is considered profitable if there is exactly two
8469 /// involved slices (1) which are (2) next to each other in memory, and
8470 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
8471 ///
8472 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
8473 /// the elements themselves.
8474 ///
8475 /// FIXME: When the cost model will be mature enough, we can relax
8476 /// constraints (1) and (2).
8477 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8478                                 const APInt &UsedBits, bool ForCodeSize) {
8479   unsigned NumberOfSlices = LoadedSlices.size();
8480   if (StressLoadSlicing)
8481     return NumberOfSlices > 1;
8482
8483   // Check (1).
8484   if (NumberOfSlices != 2)
8485     return false;
8486
8487   // Check (2).
8488   if (!areUsedBitsDense(UsedBits))
8489     return false;
8490
8491   // Check (3).
8492   LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
8493   // The original code has one big load.
8494   OrigCost.Loads = 1;
8495   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
8496     const LoadedSlice &LS = LoadedSlices[CurrSlice];
8497     // Accumulate the cost of all the slices.
8498     LoadedSlice::Cost SliceCost(LS, ForCodeSize);
8499     GlobalSlicingCost += SliceCost;
8500
8501     // Account as cost in the original configuration the gain obtained
8502     // with the current slices.
8503     OrigCost.addSliceGain(LS);
8504   }
8505
8506   // If the target supports paired load, adjust the cost accordingly.
8507   adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
8508   return OrigCost > GlobalSlicingCost;
8509 }
8510
8511 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
8512 /// operations, split it in the various pieces being extracted.
8513 ///
8514 /// This sort of thing is introduced by SROA.
8515 /// This slicing takes care not to insert overlapping loads.
8516 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
8517 bool DAGCombiner::SliceUpLoad(SDNode *N) {
8518   if (Level < AfterLegalizeDAG)
8519     return false;
8520
8521   LoadSDNode *LD = cast<LoadSDNode>(N);
8522   if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
8523       !LD->getValueType(0).isInteger())
8524     return false;
8525
8526   // Keep track of already used bits to detect overlapping values.
8527   // In that case, we will just abort the transformation.
8528   APInt UsedBits(LD->getValueSizeInBits(0), 0);
8529
8530   SmallVector<LoadedSlice, 4> LoadedSlices;
8531
8532   // Check if this load is used as several smaller chunks of bits.
8533   // Basically, look for uses in trunc or trunc(lshr) and record a new chain
8534   // of computation for each trunc.
8535   for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
8536        UI != UIEnd; ++UI) {
8537     // Skip the uses of the chain.
8538     if (UI.getUse().getResNo() != 0)
8539       continue;
8540
8541     SDNode *User = *UI;
8542     unsigned Shift = 0;
8543
8544     // Check if this is a trunc(lshr).
8545     if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
8546         isa<ConstantSDNode>(User->getOperand(1))) {
8547       Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
8548       User = *User->use_begin();
8549     }
8550
8551     // At this point, User is a Truncate, iff we encountered, trunc or
8552     // trunc(lshr).
8553     if (User->getOpcode() != ISD::TRUNCATE)
8554       return false;
8555
8556     // The width of the type must be a power of 2 and greater than 8-bits.
8557     // Otherwise the load cannot be represented in LLVM IR.
8558     // Moreover, if we shifted with a non-8-bits multiple, the slice
8559     // will be across several bytes. We do not support that.
8560     unsigned Width = User->getValueSizeInBits(0);
8561     if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
8562       return 0;
8563
8564     // Build the slice for this chain of computations.
8565     LoadedSlice LS(User, LD, Shift, &DAG);
8566     APInt CurrentUsedBits = LS.getUsedBits();
8567
8568     // Check if this slice overlaps with another.
8569     if ((CurrentUsedBits & UsedBits) != 0)
8570       return false;
8571     // Update the bits used globally.
8572     UsedBits |= CurrentUsedBits;
8573
8574     // Check if the new slice would be legal.
8575     if (!LS.isLegal())
8576       return false;
8577
8578     // Record the slice.
8579     LoadedSlices.push_back(LS);
8580   }
8581
8582   // Abort slicing if it does not seem to be profitable.
8583   if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
8584     return false;
8585
8586   ++SlicedLoads;
8587
8588   // Rewrite each chain to use an independent load.
8589   // By construction, each chain can be represented by a unique load.
8590
8591   // Prepare the argument for the new token factor for all the slices.
8592   SmallVector<SDValue, 8> ArgChains;
8593   for (SmallVectorImpl<LoadedSlice>::const_iterator
8594            LSIt = LoadedSlices.begin(),
8595            LSItEnd = LoadedSlices.end();
8596        LSIt != LSItEnd; ++LSIt) {
8597     SDValue SliceInst = LSIt->loadSlice();
8598     CombineTo(LSIt->Inst, SliceInst, true);
8599     if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
8600       SliceInst = SliceInst.getOperand(0);
8601     assert(SliceInst->getOpcode() == ISD::LOAD &&
8602            "It takes more than a zext to get to the loaded slice!!");
8603     ArgChains.push_back(SliceInst.getValue(1));
8604   }
8605
8606   SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
8607                               ArgChains);
8608   DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
8609   return true;
8610 }
8611
8612 /// CheckForMaskedLoad - Check to see if V is (and load (ptr), imm), where the
8613 /// load is having specific bytes cleared out.  If so, return the byte size
8614 /// being masked out and the shift amount.
8615 static std::pair<unsigned, unsigned>
8616 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
8617   std::pair<unsigned, unsigned> Result(0, 0);
8618
8619   // Check for the structure we're looking for.
8620   if (V->getOpcode() != ISD::AND ||
8621       !isa<ConstantSDNode>(V->getOperand(1)) ||
8622       !ISD::isNormalLoad(V->getOperand(0).getNode()))
8623     return Result;
8624
8625   // Check the chain and pointer.
8626   LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
8627   if (LD->getBasePtr() != Ptr) return Result;  // Not from same pointer.
8628
8629   // The store should be chained directly to the load or be an operand of a
8630   // tokenfactor.
8631   if (LD == Chain.getNode())
8632     ; // ok.
8633   else if (Chain->getOpcode() != ISD::TokenFactor)
8634     return Result; // Fail.
8635   else {
8636     bool isOk = false;
8637     for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
8638       if (Chain->getOperand(i).getNode() == LD) {
8639         isOk = true;
8640         break;
8641       }
8642     if (!isOk) return Result;
8643   }
8644
8645   // This only handles simple types.
8646   if (V.getValueType() != MVT::i16 &&
8647       V.getValueType() != MVT::i32 &&
8648       V.getValueType() != MVT::i64)
8649     return Result;
8650
8651   // Check the constant mask.  Invert it so that the bits being masked out are
8652   // 0 and the bits being kept are 1.  Use getSExtValue so that leading bits
8653   // follow the sign bit for uniformity.
8654   uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
8655   unsigned NotMaskLZ = countLeadingZeros(NotMask);
8656   if (NotMaskLZ & 7) return Result;  // Must be multiple of a byte.
8657   unsigned NotMaskTZ = countTrailingZeros(NotMask);
8658   if (NotMaskTZ & 7) return Result;  // Must be multiple of a byte.
8659   if (NotMaskLZ == 64) return Result;  // All zero mask.
8660
8661   // See if we have a continuous run of bits.  If so, we have 0*1+0*
8662   if (CountTrailingOnes_64(NotMask >> NotMaskTZ)+NotMaskTZ+NotMaskLZ != 64)
8663     return Result;
8664
8665   // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
8666   if (V.getValueType() != MVT::i64 && NotMaskLZ)
8667     NotMaskLZ -= 64-V.getValueSizeInBits();
8668
8669   unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
8670   switch (MaskedBytes) {
8671   case 1:
8672   case 2:
8673   case 4: break;
8674   default: return Result; // All one mask, or 5-byte mask.
8675   }
8676
8677   // Verify that the first bit starts at a multiple of mask so that the access
8678   // is aligned the same as the access width.
8679   if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
8680
8681   Result.first = MaskedBytes;
8682   Result.second = NotMaskTZ/8;
8683   return Result;
8684 }
8685
8686
8687 /// ShrinkLoadReplaceStoreWithStore - Check to see if IVal is something that
8688 /// provides a value as specified by MaskInfo.  If so, replace the specified
8689 /// store with a narrower store of truncated IVal.
8690 static SDNode *
8691 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
8692                                 SDValue IVal, StoreSDNode *St,
8693                                 DAGCombiner *DC) {
8694   unsigned NumBytes = MaskInfo.first;
8695   unsigned ByteShift = MaskInfo.second;
8696   SelectionDAG &DAG = DC->getDAG();
8697
8698   // Check to see if IVal is all zeros in the part being masked in by the 'or'
8699   // that uses this.  If not, this is not a replacement.
8700   APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
8701                                   ByteShift*8, (ByteShift+NumBytes)*8);
8702   if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
8703
8704   // Check that it is legal on the target to do this.  It is legal if the new
8705   // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
8706   // legalization.
8707   MVT VT = MVT::getIntegerVT(NumBytes*8);
8708   if (!DC->isTypeLegal(VT))
8709     return nullptr;
8710
8711   // Okay, we can do this!  Replace the 'St' store with a store of IVal that is
8712   // shifted by ByteShift and truncated down to NumBytes.
8713   if (ByteShift)
8714     IVal = DAG.getNode(ISD::SRL, SDLoc(IVal), IVal.getValueType(), IVal,
8715                        DAG.getConstant(ByteShift*8,
8716                                     DC->getShiftAmountTy(IVal.getValueType())));
8717
8718   // Figure out the offset for the store and the alignment of the access.
8719   unsigned StOffset;
8720   unsigned NewAlign = St->getAlignment();
8721
8722   if (DAG.getTargetLoweringInfo().isLittleEndian())
8723     StOffset = ByteShift;
8724   else
8725     StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
8726
8727   SDValue Ptr = St->getBasePtr();
8728   if (StOffset) {
8729     Ptr = DAG.getNode(ISD::ADD, SDLoc(IVal), Ptr.getValueType(),
8730                       Ptr, DAG.getConstant(StOffset, Ptr.getValueType()));
8731     NewAlign = MinAlign(NewAlign, StOffset);
8732   }
8733
8734   // Truncate down to the new size.
8735   IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
8736
8737   ++OpsNarrowed;
8738   return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
8739                       St->getPointerInfo().getWithOffset(StOffset),
8740                       false, false, NewAlign).getNode();
8741 }
8742
8743
8744 /// ReduceLoadOpStoreWidth - Look for sequence of load / op / store where op is
8745 /// one of 'or', 'xor', and 'and' of immediates. If 'op' is only touching some
8746 /// of the loaded bits, try narrowing the load and store if it would end up
8747 /// being a win for performance or code size.
8748 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
8749   StoreSDNode *ST  = cast<StoreSDNode>(N);
8750   if (ST->isVolatile())
8751     return SDValue();
8752
8753   SDValue Chain = ST->getChain();
8754   SDValue Value = ST->getValue();
8755   SDValue Ptr   = ST->getBasePtr();
8756   EVT VT = Value.getValueType();
8757
8758   if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
8759     return SDValue();
8760
8761   unsigned Opc = Value.getOpcode();
8762
8763   // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
8764   // is a byte mask indicating a consecutive number of bytes, check to see if
8765   // Y is known to provide just those bytes.  If so, we try to replace the
8766   // load + replace + store sequence with a single (narrower) store, which makes
8767   // the load dead.
8768   if (Opc == ISD::OR) {
8769     std::pair<unsigned, unsigned> MaskedLoad;
8770     MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
8771     if (MaskedLoad.first)
8772       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8773                                                   Value.getOperand(1), ST,this))
8774         return SDValue(NewST, 0);
8775
8776     // Or is commutative, so try swapping X and Y.
8777     MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
8778     if (MaskedLoad.first)
8779       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8780                                                   Value.getOperand(0), ST,this))
8781         return SDValue(NewST, 0);
8782   }
8783
8784   if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
8785       Value.getOperand(1).getOpcode() != ISD::Constant)
8786     return SDValue();
8787
8788   SDValue N0 = Value.getOperand(0);
8789   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8790       Chain == SDValue(N0.getNode(), 1)) {
8791     LoadSDNode *LD = cast<LoadSDNode>(N0);
8792     if (LD->getBasePtr() != Ptr ||
8793         LD->getPointerInfo().getAddrSpace() !=
8794         ST->getPointerInfo().getAddrSpace())
8795       return SDValue();
8796
8797     // Find the type to narrow it the load / op / store to.
8798     SDValue N1 = Value.getOperand(1);
8799     unsigned BitWidth = N1.getValueSizeInBits();
8800     APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
8801     if (Opc == ISD::AND)
8802       Imm ^= APInt::getAllOnesValue(BitWidth);
8803     if (Imm == 0 || Imm.isAllOnesValue())
8804       return SDValue();
8805     unsigned ShAmt = Imm.countTrailingZeros();
8806     unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
8807     unsigned NewBW = NextPowerOf2(MSB - ShAmt);
8808     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
8809     while (NewBW < BitWidth &&
8810            !(TLI.isOperationLegalOrCustom(Opc, NewVT) &&
8811              TLI.isNarrowingProfitable(VT, NewVT))) {
8812       NewBW = NextPowerOf2(NewBW);
8813       NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
8814     }
8815     if (NewBW >= BitWidth)
8816       return SDValue();
8817
8818     // If the lsb changed does not start at the type bitwidth boundary,
8819     // start at the previous one.
8820     if (ShAmt % NewBW)
8821       ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
8822     APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
8823                                    std::min(BitWidth, ShAmt + NewBW));
8824     if ((Imm & Mask) == Imm) {
8825       APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
8826       if (Opc == ISD::AND)
8827         NewImm ^= APInt::getAllOnesValue(NewBW);
8828       uint64_t PtrOff = ShAmt / 8;
8829       // For big endian targets, we need to adjust the offset to the pointer to
8830       // load the correct bytes.
8831       if (TLI.isBigEndian())
8832         PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
8833
8834       unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
8835       Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
8836       if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
8837         return SDValue();
8838
8839       SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
8840                                    Ptr.getValueType(), Ptr,
8841                                    DAG.getConstant(PtrOff, Ptr.getValueType()));
8842       SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
8843                                   LD->getChain(), NewPtr,
8844                                   LD->getPointerInfo().getWithOffset(PtrOff),
8845                                   LD->isVolatile(), LD->isNonTemporal(),
8846                                   LD->isInvariant(), NewAlign,
8847                                   LD->getTBAAInfo());
8848       SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
8849                                    DAG.getConstant(NewImm, NewVT));
8850       SDValue NewST = DAG.getStore(Chain, SDLoc(N),
8851                                    NewVal, NewPtr,
8852                                    ST->getPointerInfo().getWithOffset(PtrOff),
8853                                    false, false, NewAlign);
8854
8855       AddToWorkList(NewPtr.getNode());
8856       AddToWorkList(NewLD.getNode());
8857       AddToWorkList(NewVal.getNode());
8858       WorkListRemover DeadNodes(*this);
8859       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
8860       ++OpsNarrowed;
8861       return NewST;
8862     }
8863   }
8864
8865   return SDValue();
8866 }
8867
8868 /// TransformFPLoadStorePair - For a given floating point load / store pair,
8869 /// if the load value isn't used by any other operations, then consider
8870 /// transforming the pair to integer load / store operations if the target
8871 /// deems the transformation profitable.
8872 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
8873   StoreSDNode *ST  = cast<StoreSDNode>(N);
8874   SDValue Chain = ST->getChain();
8875   SDValue Value = ST->getValue();
8876   if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
8877       Value.hasOneUse() &&
8878       Chain == SDValue(Value.getNode(), 1)) {
8879     LoadSDNode *LD = cast<LoadSDNode>(Value);
8880     EVT VT = LD->getMemoryVT();
8881     if (!VT.isFloatingPoint() ||
8882         VT != ST->getMemoryVT() ||
8883         LD->isNonTemporal() ||
8884         ST->isNonTemporal() ||
8885         LD->getPointerInfo().getAddrSpace() != 0 ||
8886         ST->getPointerInfo().getAddrSpace() != 0)
8887       return SDValue();
8888
8889     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
8890     if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
8891         !TLI.isOperationLegal(ISD::STORE, IntVT) ||
8892         !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
8893         !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
8894       return SDValue();
8895
8896     unsigned LDAlign = LD->getAlignment();
8897     unsigned STAlign = ST->getAlignment();
8898     Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
8899     unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
8900     if (LDAlign < ABIAlign || STAlign < ABIAlign)
8901       return SDValue();
8902
8903     SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
8904                                 LD->getChain(), LD->getBasePtr(),
8905                                 LD->getPointerInfo(),
8906                                 false, false, false, LDAlign);
8907
8908     SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
8909                                  NewLD, ST->getBasePtr(),
8910                                  ST->getPointerInfo(),
8911                                  false, false, STAlign);
8912
8913     AddToWorkList(NewLD.getNode());
8914     AddToWorkList(NewST.getNode());
8915     WorkListRemover DeadNodes(*this);
8916     DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
8917     ++LdStFP2Int;
8918     return NewST;
8919   }
8920
8921   return SDValue();
8922 }
8923
8924 /// Helper struct to parse and store a memory address as base + index + offset.
8925 /// We ignore sign extensions when it is safe to do so.
8926 /// The following two expressions are not equivalent. To differentiate we need
8927 /// to store whether there was a sign extension involved in the index
8928 /// computation.
8929 ///  (load (i64 add (i64 copyfromreg %c)
8930 ///                 (i64 signextend (add (i8 load %index)
8931 ///                                      (i8 1))))
8932 /// vs
8933 ///
8934 /// (load (i64 add (i64 copyfromreg %c)
8935 ///                (i64 signextend (i32 add (i32 signextend (i8 load %index))
8936 ///                                         (i32 1)))))
8937 struct BaseIndexOffset {
8938   SDValue Base;
8939   SDValue Index;
8940   int64_t Offset;
8941   bool IsIndexSignExt;
8942
8943   BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
8944
8945   BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
8946                   bool IsIndexSignExt) :
8947     Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
8948
8949   bool equalBaseIndex(const BaseIndexOffset &Other) {
8950     return Other.Base == Base && Other.Index == Index &&
8951       Other.IsIndexSignExt == IsIndexSignExt;
8952   }
8953
8954   /// Parses tree in Ptr for base, index, offset addresses.
8955   static BaseIndexOffset match(SDValue Ptr) {
8956     bool IsIndexSignExt = false;
8957
8958     // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
8959     // instruction, then it could be just the BASE or everything else we don't
8960     // know how to handle. Just use Ptr as BASE and give up.
8961     if (Ptr->getOpcode() != ISD::ADD)
8962       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
8963
8964     // We know that we have at least an ADD instruction. Try to pattern match
8965     // the simple case of BASE + OFFSET.
8966     if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
8967       int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
8968       return  BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
8969                               IsIndexSignExt);
8970     }
8971
8972     // Inside a loop the current BASE pointer is calculated using an ADD and a
8973     // MUL instruction. In this case Ptr is the actual BASE pointer.
8974     // (i64 add (i64 %array_ptr)
8975     //          (i64 mul (i64 %induction_var)
8976     //                   (i64 %element_size)))
8977     if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
8978       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
8979
8980     // Look at Base + Index + Offset cases.
8981     SDValue Base = Ptr->getOperand(0);
8982     SDValue IndexOffset = Ptr->getOperand(1);
8983
8984     // Skip signextends.
8985     if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
8986       IndexOffset = IndexOffset->getOperand(0);
8987       IsIndexSignExt = true;
8988     }
8989
8990     // Either the case of Base + Index (no offset) or something else.
8991     if (IndexOffset->getOpcode() != ISD::ADD)
8992       return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
8993
8994     // Now we have the case of Base + Index + offset.
8995     SDValue Index = IndexOffset->getOperand(0);
8996     SDValue Offset = IndexOffset->getOperand(1);
8997
8998     if (!isa<ConstantSDNode>(Offset))
8999       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9000
9001     // Ignore signextends.
9002     if (Index->getOpcode() == ISD::SIGN_EXTEND) {
9003       Index = Index->getOperand(0);
9004       IsIndexSignExt = true;
9005     } else IsIndexSignExt = false;
9006
9007     int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
9008     return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
9009   }
9010 };
9011
9012 /// Holds a pointer to an LSBaseSDNode as well as information on where it
9013 /// is located in a sequence of memory operations connected by a chain.
9014 struct MemOpLink {
9015   MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
9016     MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
9017   // Ptr to the mem node.
9018   LSBaseSDNode *MemNode;
9019   // Offset from the base ptr.
9020   int64_t OffsetFromBase;
9021   // What is the sequence number of this mem node.
9022   // Lowest mem operand in the DAG starts at zero.
9023   unsigned SequenceNum;
9024 };
9025
9026 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
9027   EVT MemVT = St->getMemoryVT();
9028   int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
9029   bool NoVectors = DAG.getMachineFunction().getFunction()->getAttributes().
9030     hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
9031
9032   // Don't merge vectors into wider inputs.
9033   if (MemVT.isVector() || !MemVT.isSimple())
9034     return false;
9035
9036   // Perform an early exit check. Do not bother looking at stored values that
9037   // are not constants or loads.
9038   SDValue StoredVal = St->getValue();
9039   bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
9040   if (!isa<ConstantSDNode>(StoredVal) && !isa<ConstantFPSDNode>(StoredVal) &&
9041       !IsLoadSrc)
9042     return false;
9043
9044   // Only look at ends of store sequences.
9045   SDValue Chain = SDValue(St, 1);
9046   if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
9047     return false;
9048
9049   // This holds the base pointer, index, and the offset in bytes from the base
9050   // pointer.
9051   BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
9052
9053   // We must have a base and an offset.
9054   if (!BasePtr.Base.getNode())
9055     return false;
9056
9057   // Do not handle stores to undef base pointers.
9058   if (BasePtr.Base.getOpcode() == ISD::UNDEF)
9059     return false;
9060
9061   // Save the LoadSDNodes that we find in the chain.
9062   // We need to make sure that these nodes do not interfere with
9063   // any of the store nodes.
9064   SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
9065
9066   // Save the StoreSDNodes that we find in the chain.
9067   SmallVector<MemOpLink, 8> StoreNodes;
9068
9069   // Walk up the chain and look for nodes with offsets from the same
9070   // base pointer. Stop when reaching an instruction with a different kind
9071   // or instruction which has a different base pointer.
9072   unsigned Seq = 0;
9073   StoreSDNode *Index = St;
9074   while (Index) {
9075     // If the chain has more than one use, then we can't reorder the mem ops.
9076     if (Index != St && !SDValue(Index, 1)->hasOneUse())
9077       break;
9078
9079     // Find the base pointer and offset for this memory node.
9080     BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
9081
9082     // Check that the base pointer is the same as the original one.
9083     if (!Ptr.equalBaseIndex(BasePtr))
9084       break;
9085
9086     // Check that the alignment is the same.
9087     if (Index->getAlignment() != St->getAlignment())
9088       break;
9089
9090     // The memory operands must not be volatile.
9091     if (Index->isVolatile() || Index->isIndexed())
9092       break;
9093
9094     // No truncation.
9095     if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
9096       if (St->isTruncatingStore())
9097         break;
9098
9099     // The stored memory type must be the same.
9100     if (Index->getMemoryVT() != MemVT)
9101       break;
9102
9103     // We do not allow unaligned stores because we want to prevent overriding
9104     // stores.
9105     if (Index->getAlignment()*8 != MemVT.getSizeInBits())
9106       break;
9107
9108     // We found a potential memory operand to merge.
9109     StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
9110
9111     // Find the next memory operand in the chain. If the next operand in the
9112     // chain is a store then move up and continue the scan with the next
9113     // memory operand. If the next operand is a load save it and use alias
9114     // information to check if it interferes with anything.
9115     SDNode *NextInChain = Index->getChain().getNode();
9116     while (1) {
9117       if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
9118         // We found a store node. Use it for the next iteration.
9119         Index = STn;
9120         break;
9121       } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
9122         if (Ldn->isVolatile()) {
9123           Index = nullptr;
9124           break;
9125         }
9126
9127         // Save the load node for later. Continue the scan.
9128         AliasLoadNodes.push_back(Ldn);
9129         NextInChain = Ldn->getChain().getNode();
9130         continue;
9131       } else {
9132         Index = nullptr;
9133         break;
9134       }
9135     }
9136   }
9137
9138   // Check if there is anything to merge.
9139   if (StoreNodes.size() < 2)
9140     return false;
9141
9142   // Sort the memory operands according to their distance from the base pointer.
9143   std::sort(StoreNodes.begin(), StoreNodes.end(),
9144             [](MemOpLink LHS, MemOpLink RHS) {
9145     return LHS.OffsetFromBase < RHS.OffsetFromBase ||
9146            (LHS.OffsetFromBase == RHS.OffsetFromBase &&
9147             LHS.SequenceNum > RHS.SequenceNum);
9148   });
9149
9150   // Scan the memory operations on the chain and find the first non-consecutive
9151   // store memory address.
9152   unsigned LastConsecutiveStore = 0;
9153   int64_t StartAddress = StoreNodes[0].OffsetFromBase;
9154   for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
9155
9156     // Check that the addresses are consecutive starting from the second
9157     // element in the list of stores.
9158     if (i > 0) {
9159       int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
9160       if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9161         break;
9162     }
9163
9164     bool Alias = false;
9165     // Check if this store interferes with any of the loads that we found.
9166     for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
9167       if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
9168         Alias = true;
9169         break;
9170       }
9171     // We found a load that alias with this store. Stop the sequence.
9172     if (Alias)
9173       break;
9174
9175     // Mark this node as useful.
9176     LastConsecutiveStore = i;
9177   }
9178
9179   // The node with the lowest store address.
9180   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
9181
9182   // Store the constants into memory as one consecutive store.
9183   if (!IsLoadSrc) {
9184     unsigned LastLegalType = 0;
9185     unsigned LastLegalVectorType = 0;
9186     bool NonZero = false;
9187     for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9188       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
9189       SDValue StoredVal = St->getValue();
9190
9191       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
9192         NonZero |= !C->isNullValue();
9193       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
9194         NonZero |= !C->getConstantFPValue()->isNullValue();
9195       } else {
9196         // Non-constant.
9197         break;
9198       }
9199
9200       // Find a legal type for the constant store.
9201       unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9202       EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9203       if (TLI.isTypeLegal(StoreTy))
9204         LastLegalType = i+1;
9205       // Or check whether a truncstore is legal.
9206       else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9207                TargetLowering::TypePromoteInteger) {
9208         EVT LegalizedStoredValueTy =
9209           TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
9210         if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy))
9211           LastLegalType = i+1;
9212       }
9213
9214       // Find a legal type for the vector store.
9215       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9216       if (TLI.isTypeLegal(Ty))
9217         LastLegalVectorType = i + 1;
9218     }
9219
9220     // We only use vectors if the constant is known to be zero and the
9221     // function is not marked with the noimplicitfloat attribute.
9222     if (NonZero || NoVectors)
9223       LastLegalVectorType = 0;
9224
9225     // Check if we found a legal integer type to store.
9226     if (LastLegalType == 0 && LastLegalVectorType == 0)
9227       return false;
9228
9229     bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
9230     unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
9231
9232     // Make sure we have something to merge.
9233     if (NumElem < 2)
9234       return false;
9235
9236     unsigned EarliestNodeUsed = 0;
9237     for (unsigned i=0; i < NumElem; ++i) {
9238       // Find a chain for the new wide-store operand. Notice that some
9239       // of the store nodes that we found may not be selected for inclusion
9240       // in the wide store. The chain we use needs to be the chain of the
9241       // earliest store node which is *used* and replaced by the wide store.
9242       if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9243         EarliestNodeUsed = i;
9244     }
9245
9246     // The earliest Node in the DAG.
9247     LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9248     SDLoc DL(StoreNodes[0].MemNode);
9249
9250     SDValue StoredVal;
9251     if (UseVector) {
9252       // Find a legal type for the vector store.
9253       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9254       assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
9255       StoredVal = DAG.getConstant(0, Ty);
9256     } else {
9257       unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9258       APInt StoreInt(StoreBW, 0);
9259
9260       // Construct a single integer constant which is made of the smaller
9261       // constant inputs.
9262       bool IsLE = TLI.isLittleEndian();
9263       for (unsigned i = 0; i < NumElem ; ++i) {
9264         unsigned Idx = IsLE ?(NumElem - 1 - i) : i;
9265         StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
9266         SDValue Val = St->getValue();
9267         StoreInt<<=ElementSizeBytes*8;
9268         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
9269           StoreInt|=C->getAPIntValue().zext(StoreBW);
9270         } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
9271           StoreInt|= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
9272         } else {
9273           assert(false && "Invalid constant element type");
9274         }
9275       }
9276
9277       // Create the new Load and Store operations.
9278       EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9279       StoredVal = DAG.getConstant(StoreInt, StoreTy);
9280     }
9281
9282     SDValue NewStore = DAG.getStore(EarliestOp->getChain(), DL, StoredVal,
9283                                     FirstInChain->getBasePtr(),
9284                                     FirstInChain->getPointerInfo(),
9285                                     false, false,
9286                                     FirstInChain->getAlignment());
9287
9288     // Replace the first store with the new store
9289     CombineTo(EarliestOp, NewStore);
9290     // Erase all other stores.
9291     for (unsigned i = 0; i < NumElem ; ++i) {
9292       if (StoreNodes[i].MemNode == EarliestOp)
9293         continue;
9294       StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9295       // ReplaceAllUsesWith will replace all uses that existed when it was
9296       // called, but graph optimizations may cause new ones to appear. For
9297       // example, the case in pr14333 looks like
9298       //
9299       //  St's chain -> St -> another store -> X
9300       //
9301       // And the only difference from St to the other store is the chain.
9302       // When we change it's chain to be St's chain they become identical,
9303       // get CSEed and the net result is that X is now a use of St.
9304       // Since we know that St is redundant, just iterate.
9305       while (!St->use_empty())
9306         DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
9307       removeFromWorkList(St);
9308       DAG.DeleteNode(St);
9309     }
9310
9311     return true;
9312   }
9313
9314   // Below we handle the case of multiple consecutive stores that
9315   // come from multiple consecutive loads. We merge them into a single
9316   // wide load and a single wide store.
9317
9318   // Look for load nodes which are used by the stored values.
9319   SmallVector<MemOpLink, 8> LoadNodes;
9320
9321   // Find acceptable loads. Loads need to have the same chain (token factor),
9322   // must not be zext, volatile, indexed, and they must be consecutive.
9323   BaseIndexOffset LdBasePtr;
9324   for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9325     StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
9326     LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
9327     if (!Ld) break;
9328
9329     // Loads must only have one use.
9330     if (!Ld->hasNUsesOfValue(1, 0))
9331       break;
9332
9333     // Check that the alignment is the same as the stores.
9334     if (Ld->getAlignment() != St->getAlignment())
9335       break;
9336
9337     // The memory operands must not be volatile.
9338     if (Ld->isVolatile() || Ld->isIndexed())
9339       break;
9340
9341     // We do not accept ext loads.
9342     if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
9343       break;
9344
9345     // The stored memory type must be the same.
9346     if (Ld->getMemoryVT() != MemVT)
9347       break;
9348
9349     BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
9350     // If this is not the first ptr that we check.
9351     if (LdBasePtr.Base.getNode()) {
9352       // The base ptr must be the same.
9353       if (!LdPtr.equalBaseIndex(LdBasePtr))
9354         break;
9355     } else {
9356       // Check that all other base pointers are the same as this one.
9357       LdBasePtr = LdPtr;
9358     }
9359
9360     // We found a potential memory operand to merge.
9361     LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
9362   }
9363
9364   if (LoadNodes.size() < 2)
9365     return false;
9366
9367   // Scan the memory operations on the chain and find the first non-consecutive
9368   // load memory address. These variables hold the index in the store node
9369   // array.
9370   unsigned LastConsecutiveLoad = 0;
9371   // This variable refers to the size and not index in the array.
9372   unsigned LastLegalVectorType = 0;
9373   unsigned LastLegalIntegerType = 0;
9374   StartAddress = LoadNodes[0].OffsetFromBase;
9375   SDValue FirstChain = LoadNodes[0].MemNode->getChain();
9376   for (unsigned i = 1; i < LoadNodes.size(); ++i) {
9377     // All loads much share the same chain.
9378     if (LoadNodes[i].MemNode->getChain() != FirstChain)
9379       break;
9380
9381     int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
9382     if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9383       break;
9384     LastConsecutiveLoad = i;
9385
9386     // Find a legal type for the vector store.
9387     EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9388     if (TLI.isTypeLegal(StoreTy))
9389       LastLegalVectorType = i + 1;
9390
9391     // Find a legal type for the integer store.
9392     unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9393     StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9394     if (TLI.isTypeLegal(StoreTy))
9395       LastLegalIntegerType = i + 1;
9396     // Or check whether a truncstore and extload is legal.
9397     else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9398              TargetLowering::TypePromoteInteger) {
9399       EVT LegalizedStoredValueTy =
9400         TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
9401       if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
9402           TLI.isLoadExtLegal(ISD::ZEXTLOAD, StoreTy) &&
9403           TLI.isLoadExtLegal(ISD::SEXTLOAD, StoreTy) &&
9404           TLI.isLoadExtLegal(ISD::EXTLOAD, StoreTy))
9405         LastLegalIntegerType = i+1;
9406     }
9407   }
9408
9409   // Only use vector types if the vector type is larger than the integer type.
9410   // If they are the same, use integers.
9411   bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
9412   unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
9413
9414   // We add +1 here because the LastXXX variables refer to location while
9415   // the NumElem refers to array/index size.
9416   unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
9417   NumElem = std::min(LastLegalType, NumElem);
9418
9419   if (NumElem < 2)
9420     return false;
9421
9422   // The earliest Node in the DAG.
9423   unsigned EarliestNodeUsed = 0;
9424   LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9425   for (unsigned i=1; i<NumElem; ++i) {
9426     // Find a chain for the new wide-store operand. Notice that some
9427     // of the store nodes that we found may not be selected for inclusion
9428     // in the wide store. The chain we use needs to be the chain of the
9429     // earliest store node which is *used* and replaced by the wide store.
9430     if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9431       EarliestNodeUsed = i;
9432   }
9433
9434   // Find if it is better to use vectors or integers to load and store
9435   // to memory.
9436   EVT JointMemOpVT;
9437   if (UseVectorTy) {
9438     JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9439   } else {
9440     unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9441     JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9442   }
9443
9444   SDLoc LoadDL(LoadNodes[0].MemNode);
9445   SDLoc StoreDL(StoreNodes[0].MemNode);
9446
9447   LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
9448   SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL,
9449                                 FirstLoad->getChain(),
9450                                 FirstLoad->getBasePtr(),
9451                                 FirstLoad->getPointerInfo(),
9452                                 false, false, false,
9453                                 FirstLoad->getAlignment());
9454
9455   SDValue NewStore = DAG.getStore(EarliestOp->getChain(), StoreDL, NewLoad,
9456                                   FirstInChain->getBasePtr(),
9457                                   FirstInChain->getPointerInfo(), false, false,
9458                                   FirstInChain->getAlignment());
9459
9460   // Replace one of the loads with the new load.
9461   LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
9462   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
9463                                 SDValue(NewLoad.getNode(), 1));
9464
9465   // Remove the rest of the load chains.
9466   for (unsigned i = 1; i < NumElem ; ++i) {
9467     // Replace all chain users of the old load nodes with the chain of the new
9468     // load node.
9469     LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
9470     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
9471   }
9472
9473   // Replace the first store with the new store.
9474   CombineTo(EarliestOp, NewStore);
9475   // Erase all other stores.
9476   for (unsigned i = 0; i < NumElem ; ++i) {
9477     // Remove all Store nodes.
9478     if (StoreNodes[i].MemNode == EarliestOp)
9479       continue;
9480     StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9481     DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
9482     removeFromWorkList(St);
9483     DAG.DeleteNode(St);
9484   }
9485
9486   return true;
9487 }
9488
9489 SDValue DAGCombiner::visitSTORE(SDNode *N) {
9490   StoreSDNode *ST  = cast<StoreSDNode>(N);
9491   SDValue Chain = ST->getChain();
9492   SDValue Value = ST->getValue();
9493   SDValue Ptr   = ST->getBasePtr();
9494
9495   // If this is a store of a bit convert, store the input value if the
9496   // resultant store does not need a higher alignment than the original.
9497   if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
9498       ST->isUnindexed()) {
9499     unsigned OrigAlign = ST->getAlignment();
9500     EVT SVT = Value.getOperand(0).getValueType();
9501     unsigned Align = TLI.getDataLayout()->
9502       getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
9503     if (Align <= OrigAlign &&
9504         ((!LegalOperations && !ST->isVolatile()) ||
9505          TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
9506       return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
9507                           Ptr, ST->getPointerInfo(), ST->isVolatile(),
9508                           ST->isNonTemporal(), OrigAlign,
9509                           ST->getTBAAInfo());
9510   }
9511
9512   // Turn 'store undef, Ptr' -> nothing.
9513   if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
9514     return Chain;
9515
9516   // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
9517   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
9518     // NOTE: If the original store is volatile, this transform must not increase
9519     // the number of stores.  For example, on x86-32 an f64 can be stored in one
9520     // processor operation but an i64 (which is not legal) requires two.  So the
9521     // transform should not be done in this case.
9522     if (Value.getOpcode() != ISD::TargetConstantFP) {
9523       SDValue Tmp;
9524       switch (CFP->getSimpleValueType(0).SimpleTy) {
9525       default: llvm_unreachable("Unknown FP type");
9526       case MVT::f16:    // We don't do this for these yet.
9527       case MVT::f80:
9528       case MVT::f128:
9529       case MVT::ppcf128:
9530         break;
9531       case MVT::f32:
9532         if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
9533             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
9534           Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
9535                               bitcastToAPInt().getZExtValue(), MVT::i32);
9536           return DAG.getStore(Chain, SDLoc(N), Tmp,
9537                               Ptr, ST->getMemOperand());
9538         }
9539         break;
9540       case MVT::f64:
9541         if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
9542              !ST->isVolatile()) ||
9543             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
9544           Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
9545                                 getZExtValue(), MVT::i64);
9546           return DAG.getStore(Chain, SDLoc(N), Tmp,
9547                               Ptr, ST->getMemOperand());
9548         }
9549
9550         if (!ST->isVolatile() &&
9551             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
9552           // Many FP stores are not made apparent until after legalize, e.g. for
9553           // argument passing.  Since this is so common, custom legalize the
9554           // 64-bit integer store into two 32-bit stores.
9555           uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
9556           SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
9557           SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
9558           if (TLI.isBigEndian()) std::swap(Lo, Hi);
9559
9560           unsigned Alignment = ST->getAlignment();
9561           bool isVolatile = ST->isVolatile();
9562           bool isNonTemporal = ST->isNonTemporal();
9563           const MDNode *TBAAInfo = ST->getTBAAInfo();
9564
9565           SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
9566                                      Ptr, ST->getPointerInfo(),
9567                                      isVolatile, isNonTemporal,
9568                                      ST->getAlignment(), TBAAInfo);
9569           Ptr = DAG.getNode(ISD::ADD, SDLoc(N), Ptr.getValueType(), Ptr,
9570                             DAG.getConstant(4, Ptr.getValueType()));
9571           Alignment = MinAlign(Alignment, 4U);
9572           SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
9573                                      Ptr, ST->getPointerInfo().getWithOffset(4),
9574                                      isVolatile, isNonTemporal,
9575                                      Alignment, TBAAInfo);
9576           return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
9577                              St0, St1);
9578         }
9579
9580         break;
9581       }
9582     }
9583   }
9584
9585   // Try to infer better alignment information than the store already has.
9586   if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
9587     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
9588       if (Align > ST->getAlignment())
9589         return DAG.getTruncStore(Chain, SDLoc(N), Value,
9590                                  Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
9591                                  ST->isVolatile(), ST->isNonTemporal(), Align,
9592                                  ST->getTBAAInfo());
9593     }
9594   }
9595
9596   // Try transforming a pair floating point load / store ops to integer
9597   // load / store ops.
9598   SDValue NewST = TransformFPLoadStorePair(N);
9599   if (NewST.getNode())
9600     return NewST;
9601
9602   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
9603     TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
9604 #ifndef NDEBUG
9605   if (CombinerAAOnlyFunc.getNumOccurrences() &&
9606       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
9607     UseAA = false;
9608 #endif
9609   if (UseAA && ST->isUnindexed()) {
9610     // Walk up chain skipping non-aliasing memory nodes.
9611     SDValue BetterChain = FindBetterChain(N, Chain);
9612
9613     // If there is a better chain.
9614     if (Chain != BetterChain) {
9615       SDValue ReplStore;
9616
9617       // Replace the chain to avoid dependency.
9618       if (ST->isTruncatingStore()) {
9619         ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
9620                                       ST->getMemoryVT(), ST->getMemOperand());
9621       } else {
9622         ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
9623                                  ST->getMemOperand());
9624       }
9625
9626       // Create token to keep both nodes around.
9627       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
9628                                   MVT::Other, Chain, ReplStore);
9629
9630       // Make sure the new and old chains are cleaned up.
9631       AddToWorkList(Token.getNode());
9632
9633       // Don't add users to work list.
9634       return CombineTo(N, Token, false);
9635     }
9636   }
9637
9638   // Try transforming N to an indexed store.
9639   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
9640     return SDValue(N, 0);
9641
9642   // FIXME: is there such a thing as a truncating indexed store?
9643   if (ST->isTruncatingStore() && ST->isUnindexed() &&
9644       Value.getValueType().isInteger()) {
9645     // See if we can simplify the input to this truncstore with knowledge that
9646     // only the low bits are being used.  For example:
9647     // "truncstore (or (shl x, 8), y), i8"  -> "truncstore y, i8"
9648     SDValue Shorter =
9649       GetDemandedBits(Value,
9650                       APInt::getLowBitsSet(
9651                         Value.getValueType().getScalarType().getSizeInBits(),
9652                         ST->getMemoryVT().getScalarType().getSizeInBits()));
9653     AddToWorkList(Value.getNode());
9654     if (Shorter.getNode())
9655       return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
9656                                Ptr, ST->getMemoryVT(), ST->getMemOperand());
9657
9658     // Otherwise, see if we can simplify the operation with
9659     // SimplifyDemandedBits, which only works if the value has a single use.
9660     if (SimplifyDemandedBits(Value,
9661                         APInt::getLowBitsSet(
9662                           Value.getValueType().getScalarType().getSizeInBits(),
9663                           ST->getMemoryVT().getScalarType().getSizeInBits())))
9664       return SDValue(N, 0);
9665   }
9666
9667   // If this is a load followed by a store to the same location, then the store
9668   // is dead/noop.
9669   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
9670     if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
9671         ST->isUnindexed() && !ST->isVolatile() &&
9672         // There can't be any side effects between the load and store, such as
9673         // a call or store.
9674         Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
9675       // The store is dead, remove it.
9676       return Chain;
9677     }
9678   }
9679
9680   // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
9681   // truncating store.  We can do this even if this is already a truncstore.
9682   if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
9683       && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
9684       TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
9685                             ST->getMemoryVT())) {
9686     return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
9687                              Ptr, ST->getMemoryVT(), ST->getMemOperand());
9688   }
9689
9690   // Only perform this optimization before the types are legal, because we
9691   // don't want to perform this optimization on every DAGCombine invocation.
9692   if (!LegalTypes) {
9693     bool EverChanged = false;
9694
9695     do {
9696       // There can be multiple store sequences on the same chain.
9697       // Keep trying to merge store sequences until we are unable to do so
9698       // or until we merge the last store on the chain.
9699       bool Changed = MergeConsecutiveStores(ST);
9700       EverChanged |= Changed;
9701       if (!Changed) break;
9702     } while (ST->getOpcode() != ISD::DELETED_NODE);
9703
9704     if (EverChanged)
9705       return SDValue(N, 0);
9706   }
9707
9708   return ReduceLoadOpStoreWidth(N);
9709 }
9710
9711 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
9712   SDValue InVec = N->getOperand(0);
9713   SDValue InVal = N->getOperand(1);
9714   SDValue EltNo = N->getOperand(2);
9715   SDLoc dl(N);
9716
9717   // If the inserted element is an UNDEF, just use the input vector.
9718   if (InVal.getOpcode() == ISD::UNDEF)
9719     return InVec;
9720
9721   EVT VT = InVec.getValueType();
9722
9723   // If we can't generate a legal BUILD_VECTOR, exit
9724   if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
9725     return SDValue();
9726
9727   // Check that we know which element is being inserted
9728   if (!isa<ConstantSDNode>(EltNo))
9729     return SDValue();
9730   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9731
9732   // Canonicalize insert_vector_elt dag nodes.
9733   // Example:
9734   // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
9735   // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
9736   //
9737   // Do this only if the child insert_vector node has one use; also
9738   // do this only if indices are both constants and Idx1 < Idx0.
9739   if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
9740       && isa<ConstantSDNode>(InVec.getOperand(2))) {
9741     unsigned OtherElt =
9742       cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue();
9743     if (Elt < OtherElt) {
9744       // Swap nodes.
9745       SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT,
9746                                   InVec.getOperand(0), InVal, EltNo);
9747       AddToWorkList(NewOp.getNode());
9748       return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
9749                          VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
9750     }
9751   }
9752
9753   // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
9754   // be converted to a BUILD_VECTOR).  Fill in the Ops vector with the
9755   // vector elements.
9756   SmallVector<SDValue, 8> Ops;
9757   // Do not combine these two vectors if the output vector will not replace
9758   // the input vector.
9759   if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
9760     Ops.append(InVec.getNode()->op_begin(),
9761                InVec.getNode()->op_end());
9762   } else if (InVec.getOpcode() == ISD::UNDEF) {
9763     unsigned NElts = VT.getVectorNumElements();
9764     Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
9765   } else {
9766     return SDValue();
9767   }
9768
9769   // Insert the element
9770   if (Elt < Ops.size()) {
9771     // All the operands of BUILD_VECTOR must have the same type;
9772     // we enforce that here.
9773     EVT OpVT = Ops[0].getValueType();
9774     if (InVal.getValueType() != OpVT)
9775       InVal = OpVT.bitsGT(InVal.getValueType()) ?
9776                 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
9777                 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
9778     Ops[Elt] = InVal;
9779   }
9780
9781   // Return the new vector
9782   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
9783 }
9784
9785 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
9786   // (vextract (scalar_to_vector val, 0) -> val
9787   SDValue InVec = N->getOperand(0);
9788   EVT VT = InVec.getValueType();
9789   EVT NVT = N->getValueType(0);
9790
9791   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
9792     // Check if the result type doesn't match the inserted element type. A
9793     // SCALAR_TO_VECTOR may truncate the inserted element and the
9794     // EXTRACT_VECTOR_ELT may widen the extracted vector.
9795     SDValue InOp = InVec.getOperand(0);
9796     if (InOp.getValueType() != NVT) {
9797       assert(InOp.getValueType().isInteger() && NVT.isInteger());
9798       return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
9799     }
9800     return InOp;
9801   }
9802
9803   SDValue EltNo = N->getOperand(1);
9804   bool ConstEltNo = isa<ConstantSDNode>(EltNo);
9805
9806   // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
9807   // We only perform this optimization before the op legalization phase because
9808   // we may introduce new vector instructions which are not backed by TD
9809   // patterns. For example on AVX, extracting elements from a wide vector
9810   // without using extract_subvector. However, if we can find an underlying
9811   // scalar value, then we can always use that.
9812   if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
9813       && ConstEltNo) {
9814     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9815     int NumElem = VT.getVectorNumElements();
9816     ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
9817     // Find the new index to extract from.
9818     int OrigElt = SVOp->getMaskElt(Elt);
9819
9820     // Extracting an undef index is undef.
9821     if (OrigElt == -1)
9822       return DAG.getUNDEF(NVT);
9823
9824     // Select the right vector half to extract from.
9825     SDValue SVInVec;
9826     if (OrigElt < NumElem) {
9827       SVInVec = InVec->getOperand(0);
9828     } else {
9829       SVInVec = InVec->getOperand(1);
9830       OrigElt -= NumElem;
9831     }
9832
9833     if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
9834       SDValue InOp = SVInVec.getOperand(OrigElt);
9835       if (InOp.getValueType() != NVT) {
9836         assert(InOp.getValueType().isInteger() && NVT.isInteger());
9837         InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
9838       }
9839
9840       return InOp;
9841     }
9842
9843     // FIXME: We should handle recursing on other vector shuffles and
9844     // scalar_to_vector here as well.
9845
9846     if (!LegalOperations) {
9847       EVT IndexTy = TLI.getVectorIdxTy();
9848       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT,
9849                          SVInVec, DAG.getConstant(OrigElt, IndexTy));
9850     }
9851   }
9852
9853   // Perform only after legalization to ensure build_vector / vector_shuffle
9854   // optimizations have already been done.
9855   if (!LegalOperations) return SDValue();
9856
9857   // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
9858   // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
9859   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
9860
9861   if (ConstEltNo) {
9862     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9863     bool NewLoad = false;
9864     bool BCNumEltsChanged = false;
9865     EVT ExtVT = VT.getVectorElementType();
9866     EVT LVT = ExtVT;
9867
9868     // If the result of load has to be truncated, then it's not necessarily
9869     // profitable.
9870     if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
9871       return SDValue();
9872
9873     if (InVec.getOpcode() == ISD::BITCAST) {
9874       // Don't duplicate a load with other uses.
9875       if (!InVec.hasOneUse())
9876         return SDValue();
9877
9878       EVT BCVT = InVec.getOperand(0).getValueType();
9879       if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
9880         return SDValue();
9881       if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
9882         BCNumEltsChanged = true;
9883       InVec = InVec.getOperand(0);
9884       ExtVT = BCVT.getVectorElementType();
9885       NewLoad = true;
9886     }
9887
9888     LoadSDNode *LN0 = nullptr;
9889     const ShuffleVectorSDNode *SVN = nullptr;
9890     if (ISD::isNormalLoad(InVec.getNode())) {
9891       LN0 = cast<LoadSDNode>(InVec);
9892     } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
9893                InVec.getOperand(0).getValueType() == ExtVT &&
9894                ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
9895       // Don't duplicate a load with other uses.
9896       if (!InVec.hasOneUse())
9897         return SDValue();
9898
9899       LN0 = cast<LoadSDNode>(InVec.getOperand(0));
9900     } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
9901       // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
9902       // =>
9903       // (load $addr+1*size)
9904
9905       // Don't duplicate a load with other uses.
9906       if (!InVec.hasOneUse())
9907         return SDValue();
9908
9909       // If the bit convert changed the number of elements, it is unsafe
9910       // to examine the mask.
9911       if (BCNumEltsChanged)
9912         return SDValue();
9913
9914       // Select the input vector, guarding against out of range extract vector.
9915       unsigned NumElems = VT.getVectorNumElements();
9916       int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
9917       InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
9918
9919       if (InVec.getOpcode() == ISD::BITCAST) {
9920         // Don't duplicate a load with other uses.
9921         if (!InVec.hasOneUse())
9922           return SDValue();
9923
9924         InVec = InVec.getOperand(0);
9925       }
9926       if (ISD::isNormalLoad(InVec.getNode())) {
9927         LN0 = cast<LoadSDNode>(InVec);
9928         Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
9929       }
9930     }
9931
9932     // Make sure we found a non-volatile load and the extractelement is
9933     // the only use.
9934     if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
9935       return SDValue();
9936
9937     // If Idx was -1 above, Elt is going to be -1, so just return undef.
9938     if (Elt == -1)
9939       return DAG.getUNDEF(LVT);
9940
9941     unsigned Align = LN0->getAlignment();
9942     if (NewLoad) {
9943       // Check the resultant load doesn't need a higher alignment than the
9944       // original load.
9945       unsigned NewAlign =
9946         TLI.getDataLayout()
9947             ->getABITypeAlignment(LVT.getTypeForEVT(*DAG.getContext()));
9948
9949       if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, LVT))
9950         return SDValue();
9951
9952       Align = NewAlign;
9953     }
9954
9955     SDValue NewPtr = LN0->getBasePtr();
9956     unsigned PtrOff = 0;
9957
9958     if (Elt) {
9959       PtrOff = LVT.getSizeInBits() * Elt / 8;
9960       EVT PtrType = NewPtr.getValueType();
9961       if (TLI.isBigEndian())
9962         PtrOff = VT.getSizeInBits() / 8 - PtrOff;
9963       NewPtr = DAG.getNode(ISD::ADD, SDLoc(N), PtrType, NewPtr,
9964                            DAG.getConstant(PtrOff, PtrType));
9965     }
9966
9967     // The replacement we need to do here is a little tricky: we need to
9968     // replace an extractelement of a load with a load.
9969     // Use ReplaceAllUsesOfValuesWith to do the replacement.
9970     // Note that this replacement assumes that the extractvalue is the only
9971     // use of the load; that's okay because we don't want to perform this
9972     // transformation in other cases anyway.
9973     SDValue Load;
9974     SDValue Chain;
9975     if (NVT.bitsGT(LVT)) {
9976       // If the result type of vextract is wider than the load, then issue an
9977       // extending load instead.
9978       ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, LVT)
9979         ? ISD::ZEXTLOAD : ISD::EXTLOAD;
9980       Load = DAG.getExtLoad(ExtType, SDLoc(N), NVT, LN0->getChain(),
9981                             NewPtr, LN0->getPointerInfo().getWithOffset(PtrOff),
9982                             LVT, LN0->isVolatile(), LN0->isNonTemporal(),
9983                             Align, LN0->getTBAAInfo());
9984       Chain = Load.getValue(1);
9985     } else {
9986       Load = DAG.getLoad(LVT, SDLoc(N), LN0->getChain(), NewPtr,
9987                          LN0->getPointerInfo().getWithOffset(PtrOff),
9988                          LN0->isVolatile(), LN0->isNonTemporal(),
9989                          LN0->isInvariant(), Align, LN0->getTBAAInfo());
9990       Chain = Load.getValue(1);
9991       if (NVT.bitsLT(LVT))
9992         Load = DAG.getNode(ISD::TRUNCATE, SDLoc(N), NVT, Load);
9993       else
9994         Load = DAG.getNode(ISD::BITCAST, SDLoc(N), NVT, Load);
9995     }
9996     WorkListRemover DeadNodes(*this);
9997     SDValue From[] = { SDValue(N, 0), SDValue(LN0,1) };
9998     SDValue To[] = { Load, Chain };
9999     DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
10000     // Since we're explcitly calling ReplaceAllUses, add the new node to the
10001     // worklist explicitly as well.
10002     AddToWorkList(Load.getNode());
10003     AddUsersToWorkList(Load.getNode()); // Add users too
10004     // Make sure to revisit this node to clean it up; it will usually be dead.
10005     AddToWorkList(N);
10006     return SDValue(N, 0);
10007   }
10008
10009   return SDValue();
10010 }
10011
10012 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
10013 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
10014   // We perform this optimization post type-legalization because
10015   // the type-legalizer often scalarizes integer-promoted vectors.
10016   // Performing this optimization before may create bit-casts which
10017   // will be type-legalized to complex code sequences.
10018   // We perform this optimization only before the operation legalizer because we
10019   // may introduce illegal operations.
10020   if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
10021     return SDValue();
10022
10023   unsigned NumInScalars = N->getNumOperands();
10024   SDLoc dl(N);
10025   EVT VT = N->getValueType(0);
10026
10027   // Check to see if this is a BUILD_VECTOR of a bunch of values
10028   // which come from any_extend or zero_extend nodes. If so, we can create
10029   // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
10030   // optimizations. We do not handle sign-extend because we can't fill the sign
10031   // using shuffles.
10032   EVT SourceType = MVT::Other;
10033   bool AllAnyExt = true;
10034
10035   for (unsigned i = 0; i != NumInScalars; ++i) {
10036     SDValue In = N->getOperand(i);
10037     // Ignore undef inputs.
10038     if (In.getOpcode() == ISD::UNDEF) continue;
10039
10040     bool AnyExt  = In.getOpcode() == ISD::ANY_EXTEND;
10041     bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
10042
10043     // Abort if the element is not an extension.
10044     if (!ZeroExt && !AnyExt) {
10045       SourceType = MVT::Other;
10046       break;
10047     }
10048
10049     // The input is a ZeroExt or AnyExt. Check the original type.
10050     EVT InTy = In.getOperand(0).getValueType();
10051
10052     // Check that all of the widened source types are the same.
10053     if (SourceType == MVT::Other)
10054       // First time.
10055       SourceType = InTy;
10056     else if (InTy != SourceType) {
10057       // Multiple income types. Abort.
10058       SourceType = MVT::Other;
10059       break;
10060     }
10061
10062     // Check if all of the extends are ANY_EXTENDs.
10063     AllAnyExt &= AnyExt;
10064   }
10065
10066   // In order to have valid types, all of the inputs must be extended from the
10067   // same source type and all of the inputs must be any or zero extend.
10068   // Scalar sizes must be a power of two.
10069   EVT OutScalarTy = VT.getScalarType();
10070   bool ValidTypes = SourceType != MVT::Other &&
10071                  isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
10072                  isPowerOf2_32(SourceType.getSizeInBits());
10073
10074   // Create a new simpler BUILD_VECTOR sequence which other optimizations can
10075   // turn into a single shuffle instruction.
10076   if (!ValidTypes)
10077     return SDValue();
10078
10079   bool isLE = TLI.isLittleEndian();
10080   unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
10081   assert(ElemRatio > 1 && "Invalid element size ratio");
10082   SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
10083                                DAG.getConstant(0, SourceType);
10084
10085   unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
10086   SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
10087
10088   // Populate the new build_vector
10089   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
10090     SDValue Cast = N->getOperand(i);
10091     assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
10092             Cast.getOpcode() == ISD::ZERO_EXTEND ||
10093             Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
10094     SDValue In;
10095     if (Cast.getOpcode() == ISD::UNDEF)
10096       In = DAG.getUNDEF(SourceType);
10097     else
10098       In = Cast->getOperand(0);
10099     unsigned Index = isLE ? (i * ElemRatio) :
10100                             (i * ElemRatio + (ElemRatio - 1));
10101
10102     assert(Index < Ops.size() && "Invalid index");
10103     Ops[Index] = In;
10104   }
10105
10106   // The type of the new BUILD_VECTOR node.
10107   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
10108   assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
10109          "Invalid vector size");
10110   // Check if the new vector type is legal.
10111   if (!isTypeLegal(VecVT)) return SDValue();
10112
10113   // Make the new BUILD_VECTOR.
10114   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
10115
10116   // The new BUILD_VECTOR node has the potential to be further optimized.
10117   AddToWorkList(BV.getNode());
10118   // Bitcast to the desired type.
10119   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
10120 }
10121
10122 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
10123   EVT VT = N->getValueType(0);
10124
10125   unsigned NumInScalars = N->getNumOperands();
10126   SDLoc dl(N);
10127
10128   EVT SrcVT = MVT::Other;
10129   unsigned Opcode = ISD::DELETED_NODE;
10130   unsigned NumDefs = 0;
10131
10132   for (unsigned i = 0; i != NumInScalars; ++i) {
10133     SDValue In = N->getOperand(i);
10134     unsigned Opc = In.getOpcode();
10135
10136     if (Opc == ISD::UNDEF)
10137       continue;
10138
10139     // If all scalar values are floats and converted from integers.
10140     if (Opcode == ISD::DELETED_NODE &&
10141         (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
10142       Opcode = Opc;
10143     }
10144
10145     if (Opc != Opcode)
10146       return SDValue();
10147
10148     EVT InVT = In.getOperand(0).getValueType();
10149
10150     // If all scalar values are typed differently, bail out. It's chosen to
10151     // simplify BUILD_VECTOR of integer types.
10152     if (SrcVT == MVT::Other)
10153       SrcVT = InVT;
10154     if (SrcVT != InVT)
10155       return SDValue();
10156     NumDefs++;
10157   }
10158
10159   // If the vector has just one element defined, it's not worth to fold it into
10160   // a vectorized one.
10161   if (NumDefs < 2)
10162     return SDValue();
10163
10164   assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
10165          && "Should only handle conversion from integer to float.");
10166   assert(SrcVT != MVT::Other && "Cannot determine source type!");
10167
10168   EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
10169
10170   if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
10171     return SDValue();
10172
10173   SmallVector<SDValue, 8> Opnds;
10174   for (unsigned i = 0; i != NumInScalars; ++i) {
10175     SDValue In = N->getOperand(i);
10176
10177     if (In.getOpcode() == ISD::UNDEF)
10178       Opnds.push_back(DAG.getUNDEF(SrcVT));
10179     else
10180       Opnds.push_back(In.getOperand(0));
10181   }
10182   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds);
10183   AddToWorkList(BV.getNode());
10184
10185   return DAG.getNode(Opcode, dl, VT, BV);
10186 }
10187
10188 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
10189   unsigned NumInScalars = N->getNumOperands();
10190   SDLoc dl(N);
10191   EVT VT = N->getValueType(0);
10192
10193   // A vector built entirely of undefs is undef.
10194   if (ISD::allOperandsUndef(N))
10195     return DAG.getUNDEF(VT);
10196
10197   SDValue V = reduceBuildVecExtToExtBuildVec(N);
10198   if (V.getNode())
10199     return V;
10200
10201   V = reduceBuildVecConvertToConvertBuildVec(N);
10202   if (V.getNode())
10203     return V;
10204
10205   // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
10206   // operations.  If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
10207   // at most two distinct vectors, turn this into a shuffle node.
10208
10209   // May only combine to shuffle after legalize if shuffle is legal.
10210   if (LegalOperations &&
10211       !TLI.isOperationLegalOrCustom(ISD::VECTOR_SHUFFLE, VT))
10212     return SDValue();
10213
10214   SDValue VecIn1, VecIn2;
10215   for (unsigned i = 0; i != NumInScalars; ++i) {
10216     // Ignore undef inputs.
10217     if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
10218
10219     // If this input is something other than a EXTRACT_VECTOR_ELT with a
10220     // constant index, bail out.
10221     if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10222         !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) {
10223       VecIn1 = VecIn2 = SDValue(nullptr, 0);
10224       break;
10225     }
10226
10227     // We allow up to two distinct input vectors.
10228     SDValue ExtractedFromVec = N->getOperand(i).getOperand(0);
10229     if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
10230       continue;
10231
10232     if (!VecIn1.getNode()) {
10233       VecIn1 = ExtractedFromVec;
10234     } else if (!VecIn2.getNode()) {
10235       VecIn2 = ExtractedFromVec;
10236     } else {
10237       // Too many inputs.
10238       VecIn1 = VecIn2 = SDValue(nullptr, 0);
10239       break;
10240     }
10241   }
10242
10243   // If everything is good, we can make a shuffle operation.
10244   if (VecIn1.getNode()) {
10245     SmallVector<int, 8> Mask;
10246     for (unsigned i = 0; i != NumInScalars; ++i) {
10247       if (N->getOperand(i).getOpcode() == ISD::UNDEF) {
10248         Mask.push_back(-1);
10249         continue;
10250       }
10251
10252       // If extracting from the first vector, just use the index directly.
10253       SDValue Extract = N->getOperand(i);
10254       SDValue ExtVal = Extract.getOperand(1);
10255       if (Extract.getOperand(0) == VecIn1) {
10256         unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
10257         if (ExtIndex > VT.getVectorNumElements())
10258           return SDValue();
10259
10260         Mask.push_back(ExtIndex);
10261         continue;
10262       }
10263
10264       // Otherwise, use InIdx + VecSize
10265       unsigned Idx = cast<ConstantSDNode>(ExtVal)->getZExtValue();
10266       Mask.push_back(Idx+NumInScalars);
10267     }
10268
10269     // We can't generate a shuffle node with mismatched input and output types.
10270     // Attempt to transform a single input vector to the correct type.
10271     if ((VT != VecIn1.getValueType())) {
10272       // We don't support shuffeling between TWO values of different types.
10273       if (VecIn2.getNode())
10274         return SDValue();
10275
10276       // We only support widening of vectors which are half the size of the
10277       // output registers. For example XMM->YMM widening on X86 with AVX.
10278       if (VecIn1.getValueType().getSizeInBits()*2 != VT.getSizeInBits())
10279         return SDValue();
10280
10281       // If the input vector type has a different base type to the output
10282       // vector type, bail out.
10283       if (VecIn1.getValueType().getVectorElementType() !=
10284           VT.getVectorElementType())
10285         return SDValue();
10286
10287       // Widen the input vector by adding undef values.
10288       VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10289                            VecIn1, DAG.getUNDEF(VecIn1.getValueType()));
10290     }
10291
10292     // If VecIn2 is unused then change it to undef.
10293     VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
10294
10295     // Check that we were able to transform all incoming values to the same
10296     // type.
10297     if (VecIn2.getValueType() != VecIn1.getValueType() ||
10298         VecIn1.getValueType() != VT)
10299           return SDValue();
10300
10301     // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
10302     if (!isTypeLegal(VT))
10303       return SDValue();
10304
10305     // Return the new VECTOR_SHUFFLE node.
10306     SDValue Ops[2];
10307     Ops[0] = VecIn1;
10308     Ops[1] = VecIn2;
10309     return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
10310   }
10311
10312   return SDValue();
10313 }
10314
10315 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
10316   // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
10317   // EXTRACT_SUBVECTOR operations.  If so, and if the EXTRACT_SUBVECTOR vector
10318   // inputs come from at most two distinct vectors, turn this into a shuffle
10319   // node.
10320
10321   // If we only have one input vector, we don't need to do any concatenation.
10322   if (N->getNumOperands() == 1)
10323     return N->getOperand(0);
10324
10325   // Check if all of the operands are undefs.
10326   EVT VT = N->getValueType(0);
10327   if (ISD::allOperandsUndef(N))
10328     return DAG.getUNDEF(VT);
10329
10330   // Optimize concat_vectors where one of the vectors is undef.
10331   if (N->getNumOperands() == 2 &&
10332       N->getOperand(1)->getOpcode() == ISD::UNDEF) {
10333     SDValue In = N->getOperand(0);
10334     assert(In.getValueType().isVector() && "Must concat vectors");
10335
10336     // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
10337     if (In->getOpcode() == ISD::BITCAST &&
10338         !In->getOperand(0)->getValueType(0).isVector()) {
10339       SDValue Scalar = In->getOperand(0);
10340       EVT SclTy = Scalar->getValueType(0);
10341
10342       if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
10343         return SDValue();
10344
10345       EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
10346                                  VT.getSizeInBits() / SclTy.getSizeInBits());
10347       if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
10348         return SDValue();
10349
10350       SDLoc dl = SDLoc(N);
10351       SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
10352       return DAG.getNode(ISD::BITCAST, dl, VT, Res);
10353     }
10354   }
10355
10356   // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
10357   // -> (BUILD_VECTOR A, B, ..., C, D, ...)
10358   if (N->getNumOperands() == 2 &&
10359       N->getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
10360       N->getOperand(1).getOpcode() == ISD::BUILD_VECTOR) {
10361     EVT VT = N->getValueType(0);
10362     SDValue N0 = N->getOperand(0);
10363     SDValue N1 = N->getOperand(1);
10364     SmallVector<SDValue, 8> Opnds;
10365     unsigned BuildVecNumElts =  N0.getNumOperands();
10366
10367     EVT SclTy0 = N0.getOperand(0)->getValueType(0);
10368     EVT SclTy1 = N1.getOperand(0)->getValueType(0);
10369     if (SclTy0.isFloatingPoint()) {
10370       for (unsigned i = 0; i != BuildVecNumElts; ++i)
10371         Opnds.push_back(N0.getOperand(i));
10372       for (unsigned i = 0; i != BuildVecNumElts; ++i)
10373         Opnds.push_back(N1.getOperand(i));
10374     } else {
10375       // If BUILD_VECTOR are from built from integer, they may have different
10376       // operand types. Get the smaller type and truncate all operands to it.
10377       EVT MinTy = SclTy0.bitsLE(SclTy1) ? SclTy0 : SclTy1;
10378       for (unsigned i = 0; i != BuildVecNumElts; ++i)
10379         Opnds.push_back(DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinTy,
10380                         N0.getOperand(i)));
10381       for (unsigned i = 0; i != BuildVecNumElts; ++i)
10382         Opnds.push_back(DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinTy,
10383                         N1.getOperand(i)));
10384     }
10385
10386     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
10387   }
10388
10389   // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
10390   // nodes often generate nop CONCAT_VECTOR nodes.
10391   // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
10392   // place the incoming vectors at the exact same location.
10393   SDValue SingleSource = SDValue();
10394   unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
10395
10396   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
10397     SDValue Op = N->getOperand(i);
10398
10399     if (Op.getOpcode() == ISD::UNDEF)
10400       continue;
10401
10402     // Check if this is the identity extract:
10403     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
10404       return SDValue();
10405
10406     // Find the single incoming vector for the extract_subvector.
10407     if (SingleSource.getNode()) {
10408       if (Op.getOperand(0) != SingleSource)
10409         return SDValue();
10410     } else {
10411       SingleSource = Op.getOperand(0);
10412
10413       // Check the source type is the same as the type of the result.
10414       // If not, this concat may extend the vector, so we can not
10415       // optimize it away.
10416       if (SingleSource.getValueType() != N->getValueType(0))
10417         return SDValue();
10418     }
10419
10420     unsigned IdentityIndex = i * PartNumElem;
10421     ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
10422     // The extract index must be constant.
10423     if (!CS)
10424       return SDValue();
10425
10426     // Check that we are reading from the identity index.
10427     if (CS->getZExtValue() != IdentityIndex)
10428       return SDValue();
10429   }
10430
10431   if (SingleSource.getNode())
10432     return SingleSource;
10433
10434   return SDValue();
10435 }
10436
10437 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
10438   EVT NVT = N->getValueType(0);
10439   SDValue V = N->getOperand(0);
10440
10441   if (V->getOpcode() == ISD::CONCAT_VECTORS) {
10442     // Combine:
10443     //    (extract_subvec (concat V1, V2, ...), i)
10444     // Into:
10445     //    Vi if possible
10446     // Only operand 0 is checked as 'concat' assumes all inputs of the same
10447     // type.
10448     if (V->getOperand(0).getValueType() != NVT)
10449       return SDValue();
10450     unsigned Idx = dyn_cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
10451     unsigned NumElems = NVT.getVectorNumElements();
10452     assert((Idx % NumElems) == 0 &&
10453            "IDX in concat is not a multiple of the result vector length.");
10454     return V->getOperand(Idx / NumElems);
10455   }
10456
10457   // Skip bitcasting
10458   if (V->getOpcode() == ISD::BITCAST)
10459     V = V.getOperand(0);
10460
10461   if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
10462     SDLoc dl(N);
10463     // Handle only simple case where vector being inserted and vector
10464     // being extracted are of same type, and are half size of larger vectors.
10465     EVT BigVT = V->getOperand(0).getValueType();
10466     EVT SmallVT = V->getOperand(1).getValueType();
10467     if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
10468       return SDValue();
10469
10470     // Only handle cases where both indexes are constants with the same type.
10471     ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
10472     ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
10473
10474     if (InsIdx && ExtIdx &&
10475         InsIdx->getValueType(0).getSizeInBits() <= 64 &&
10476         ExtIdx->getValueType(0).getSizeInBits() <= 64) {
10477       // Combine:
10478       //    (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
10479       // Into:
10480       //    indices are equal or bit offsets are equal => V1
10481       //    otherwise => (extract_subvec V1, ExtIdx)
10482       if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
10483           ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
10484         return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
10485       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
10486                          DAG.getNode(ISD::BITCAST, dl,
10487                                      N->getOperand(0).getValueType(),
10488                                      V->getOperand(0)), N->getOperand(1));
10489     }
10490   }
10491
10492   return SDValue();
10493 }
10494
10495 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat.
10496 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
10497   EVT VT = N->getValueType(0);
10498   unsigned NumElts = VT.getVectorNumElements();
10499
10500   SDValue N0 = N->getOperand(0);
10501   SDValue N1 = N->getOperand(1);
10502   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10503
10504   SmallVector<SDValue, 4> Ops;
10505   EVT ConcatVT = N0.getOperand(0).getValueType();
10506   unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
10507   unsigned NumConcats = NumElts / NumElemsPerConcat;
10508
10509   // Look at every vector that's inserted. We're looking for exact
10510   // subvector-sized copies from a concatenated vector
10511   for (unsigned I = 0; I != NumConcats; ++I) {
10512     // Make sure we're dealing with a copy.
10513     unsigned Begin = I * NumElemsPerConcat;
10514     bool AllUndef = true, NoUndef = true;
10515     for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
10516       if (SVN->getMaskElt(J) >= 0)
10517         AllUndef = false;
10518       else
10519         NoUndef = false;
10520     }
10521
10522     if (NoUndef) {
10523       if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
10524         return SDValue();
10525
10526       for (unsigned J = 1; J != NumElemsPerConcat; ++J)
10527         if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
10528           return SDValue();
10529
10530       unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
10531       if (FirstElt < N0.getNumOperands())
10532         Ops.push_back(N0.getOperand(FirstElt));
10533       else
10534         Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
10535
10536     } else if (AllUndef) {
10537       Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
10538     } else { // Mixed with general masks and undefs, can't do optimization.
10539       return SDValue();
10540     }
10541   }
10542
10543   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
10544 }
10545
10546 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
10547   EVT VT = N->getValueType(0);
10548   unsigned NumElts = VT.getVectorNumElements();
10549
10550   SDValue N0 = N->getOperand(0);
10551   SDValue N1 = N->getOperand(1);
10552
10553   assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
10554
10555   // Canonicalize shuffle undef, undef -> undef
10556   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
10557     return DAG.getUNDEF(VT);
10558
10559   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10560
10561   // Canonicalize shuffle v, v -> v, undef
10562   if (N0 == N1) {
10563     SmallVector<int, 8> NewMask;
10564     for (unsigned i = 0; i != NumElts; ++i) {
10565       int Idx = SVN->getMaskElt(i);
10566       if (Idx >= (int)NumElts) Idx -= NumElts;
10567       NewMask.push_back(Idx);
10568     }
10569     return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
10570                                 &NewMask[0]);
10571   }
10572
10573   // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
10574   if (N0.getOpcode() == ISD::UNDEF) {
10575     SmallVector<int, 8> NewMask;
10576     for (unsigned i = 0; i != NumElts; ++i) {
10577       int Idx = SVN->getMaskElt(i);
10578       if (Idx >= 0) {
10579         if (Idx >= (int)NumElts)
10580           Idx -= NumElts;
10581         else
10582           Idx = -1; // remove reference to lhs
10583       }
10584       NewMask.push_back(Idx);
10585     }
10586     return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
10587                                 &NewMask[0]);
10588   }
10589
10590   // Remove references to rhs if it is undef
10591   if (N1.getOpcode() == ISD::UNDEF) {
10592     bool Changed = false;
10593     SmallVector<int, 8> NewMask;
10594     for (unsigned i = 0; i != NumElts; ++i) {
10595       int Idx = SVN->getMaskElt(i);
10596       if (Idx >= (int)NumElts) {
10597         Idx = -1;
10598         Changed = true;
10599       }
10600       NewMask.push_back(Idx);
10601     }
10602     if (Changed)
10603       return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
10604   }
10605
10606   // If it is a splat, check if the argument vector is another splat or a
10607   // build_vector with all scalar elements the same.
10608   if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
10609     SDNode *V = N0.getNode();
10610
10611     // If this is a bit convert that changes the element type of the vector but
10612     // not the number of vector elements, look through it.  Be careful not to
10613     // look though conversions that change things like v4f32 to v2f64.
10614     if (V->getOpcode() == ISD::BITCAST) {
10615       SDValue ConvInput = V->getOperand(0);
10616       if (ConvInput.getValueType().isVector() &&
10617           ConvInput.getValueType().getVectorNumElements() == NumElts)
10618         V = ConvInput.getNode();
10619     }
10620
10621     if (V->getOpcode() == ISD::BUILD_VECTOR) {
10622       assert(V->getNumOperands() == NumElts &&
10623              "BUILD_VECTOR has wrong number of operands");
10624       SDValue Base;
10625       bool AllSame = true;
10626       for (unsigned i = 0; i != NumElts; ++i) {
10627         if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
10628           Base = V->getOperand(i);
10629           break;
10630         }
10631       }
10632       // Splat of <u, u, u, u>, return <u, u, u, u>
10633       if (!Base.getNode())
10634         return N0;
10635       for (unsigned i = 0; i != NumElts; ++i) {
10636         if (V->getOperand(i) != Base) {
10637           AllSame = false;
10638           break;
10639         }
10640       }
10641       // Splat of <x, x, x, x>, return <x, x, x, x>
10642       if (AllSame)
10643         return N0;
10644     }
10645   }
10646
10647   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
10648       Level < AfterLegalizeVectorOps &&
10649       (N1.getOpcode() == ISD::UNDEF ||
10650       (N1.getOpcode() == ISD::CONCAT_VECTORS &&
10651        N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
10652     SDValue V = partitionShuffleOfConcats(N, DAG);
10653
10654     if (V.getNode())
10655       return V;
10656   }
10657
10658   // If this shuffle node is simply a swizzle of another shuffle node,
10659   // then try to simplify it.
10660   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
10661       N1.getOpcode() == ISD::UNDEF) {
10662
10663     ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
10664
10665     // The incoming shuffle must be of the same type as the result of the
10666     // current shuffle.
10667     assert(OtherSV->getOperand(0).getValueType() == VT &&
10668            "Shuffle types don't match");
10669
10670     SmallVector<int, 4> Mask;
10671     // Compute the combined shuffle mask.
10672     for (unsigned i = 0; i != NumElts; ++i) {
10673       int Idx = SVN->getMaskElt(i);
10674       assert(Idx < (int)NumElts && "Index references undef operand");
10675       // Next, this index comes from the first value, which is the incoming
10676       // shuffle. Adopt the incoming index.
10677       if (Idx >= 0)
10678         Idx = OtherSV->getMaskElt(Idx);
10679       Mask.push_back(Idx);
10680     }
10681     
10682     bool CommuteOperands = false;
10683     if (N0.getOperand(1).getOpcode() != ISD::UNDEF) {
10684       // To be valid, the combine shuffle mask should only reference elements
10685       // from one of the two vectors in input to the inner shufflevector.
10686       bool IsValidMask = true;
10687       for (unsigned i = 0; i != NumElts && IsValidMask; ++i)
10688         // See if the combined mask only reference undefs or elements coming
10689         // from the first shufflevector operand.
10690         IsValidMask = Mask[i] < 0 || (unsigned)Mask[i] < NumElts;
10691
10692       if (!IsValidMask) {
10693         IsValidMask = true;
10694         for (unsigned i = 0; i != NumElts && IsValidMask; ++i)
10695           // Check that all the elements come from the second shuffle operand.
10696           IsValidMask = Mask[i] < 0 || (unsigned)Mask[i] >= NumElts;
10697         CommuteOperands = IsValidMask;
10698       }
10699
10700       // Early exit if the combined shuffle mask is not valid.
10701       if (!IsValidMask)
10702         return SDValue();
10703     }
10704
10705     // See if this pair of shuffles can be safely folded according to either
10706     // of the following rules:
10707     //   shuffle(shuffle(x, y), undef) -> x
10708     //   shuffle(shuffle(x, undef), undef) -> x
10709     //   shuffle(shuffle(x, y), undef) -> y
10710     bool IsIdentityMask = true;
10711     unsigned BaseMaskIndex = CommuteOperands ? NumElts : 0;
10712     for (unsigned i = 0; i != NumElts && IsIdentityMask; ++i) {
10713       // Skip Undefs.
10714       if (Mask[i] < 0)
10715         continue;
10716
10717       // The combined shuffle must map each index to itself.
10718       IsIdentityMask = (unsigned)Mask[i] == i + BaseMaskIndex;
10719     }
10720     
10721     if (IsIdentityMask) {
10722       if (CommuteOperands)
10723         // optimize shuffle(shuffle(x, y), undef) -> y.
10724         return OtherSV->getOperand(1);
10725       
10726       // optimize shuffle(shuffle(x, undef), undef) -> x
10727       // optimize shuffle(shuffle(x, y), undef) -> x
10728       return OtherSV->getOperand(0);
10729     }
10730
10731     // It may still be beneficial to combine the two shuffles if the
10732     // resulting shuffle is legal.
10733     if (TLI.isTypeLegal(VT) && TLI.isShuffleMaskLegal(Mask, VT)) {
10734       if (!CommuteOperands)
10735         // shuffle(shuffle(x, undef, M1), undef, M2) -> shuffle(x, undef, M3).
10736         // shuffle(shuffle(x, y, M1), undef, M2) -> shuffle(x, undef, M3)
10737         return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0), N1,
10738                                     &Mask[0]);
10739       
10740       //   shuffle(shuffle(x, y, M1), undef, M2) -> shuffle(undef, y, M3)
10741       return DAG.getVectorShuffle(VT, SDLoc(N), N1, N0->getOperand(1),
10742                                   &Mask[0]);
10743     }
10744   }
10745
10746   // Try to fold according to rules:
10747   //   shuffle(shuffle(A, B, M0), B, M1) -> shuffle(A, B, M2)
10748   //   shuffle(shuffle(A, B, M0), A, M1) -> shuffle(A, B, M2)
10749   //   shuffle(shuffle(A, Undef, M0), B, M1) -> shuffle(A, B, M2)
10750   //   shuffle(shuffle(A, Undef, M0), A, M1) -> shuffle(A, Undef, M2)
10751   // Don't try to fold shuffles with illegal type.
10752   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
10753       N1.getOpcode() != ISD::UNDEF && TLI.isTypeLegal(VT)) {
10754     ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
10755
10756     // The incoming shuffle must be of the same type as the result of the
10757     // current shuffle.
10758     assert(OtherSV->getOperand(0).getValueType() == VT &&
10759            "Shuffle types don't match");
10760
10761     SDValue SV0 = OtherSV->getOperand(0);
10762     SDValue SV1 = OtherSV->getOperand(1);
10763     bool HasSameOp0 = N1 == SV0;
10764     bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
10765     if (!HasSameOp0 && !IsSV1Undef && N1 != SV1)
10766       // Early exit.
10767       return SDValue();
10768
10769     SmallVector<int, 4> Mask;
10770     // Compute the combined shuffle mask for a shuffle with SV0 as the first
10771     // operand, and SV1 as the second operand.
10772     for (unsigned i = 0; i != NumElts; ++i) {
10773       int Idx = SVN->getMaskElt(i);
10774       if (Idx < 0) {
10775         // Propagate Undef.
10776         Mask.push_back(Idx);
10777         continue;
10778       }
10779
10780       if (Idx < (int)NumElts) {
10781         Idx = OtherSV->getMaskElt(Idx);
10782         if (IsSV1Undef && Idx >= (int) NumElts)
10783           Idx = -1;  // Propagate Undef.
10784       } else
10785         Idx = HasSameOp0 ? Idx - NumElts : Idx;
10786
10787       Mask.push_back(Idx);
10788     }
10789
10790     // Avoid introducing shuffles with illegal mask.
10791     if (TLI.isShuffleMaskLegal(Mask, VT)) {
10792       if (IsSV1Undef)
10793         //   shuffle(shuffle(A, Undef, M0), B, M1) -> shuffle(A, B, M2)
10794         //   shuffle(shuffle(A, Undef, M0), A, M1) -> shuffle(A, Undef, M2)
10795         return DAG.getVectorShuffle(VT, SDLoc(N), SV0, N1, &Mask[0]);
10796       return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, &Mask[0]);
10797     }
10798   }
10799
10800   return SDValue();
10801 }
10802
10803 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
10804   SDValue N0 = N->getOperand(0);
10805   SDValue N2 = N->getOperand(2);
10806
10807   // If the input vector is a concatenation, and the insert replaces
10808   // one of the halves, we can optimize into a single concat_vectors.
10809   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
10810       N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
10811     APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
10812     EVT VT = N->getValueType(0);
10813
10814     // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
10815     // (concat_vectors Z, Y)
10816     if (InsIdx == 0)
10817       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
10818                          N->getOperand(1), N0.getOperand(1));
10819
10820     // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
10821     // (concat_vectors X, Z)
10822     if (InsIdx == VT.getVectorNumElements()/2)
10823       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
10824                          N0.getOperand(0), N->getOperand(1));
10825   }
10826
10827   return SDValue();
10828 }
10829
10830 /// XformToShuffleWithZero - Returns a vector_shuffle if it able to transform
10831 /// an AND to a vector_shuffle with the destination vector and a zero vector.
10832 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
10833 ///      vector_shuffle V, Zero, <0, 4, 2, 4>
10834 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
10835   EVT VT = N->getValueType(0);
10836   SDLoc dl(N);
10837   SDValue LHS = N->getOperand(0);
10838   SDValue RHS = N->getOperand(1);
10839   if (N->getOpcode() == ISD::AND) {
10840     if (RHS.getOpcode() == ISD::BITCAST)
10841       RHS = RHS.getOperand(0);
10842     if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
10843       SmallVector<int, 8> Indices;
10844       unsigned NumElts = RHS.getNumOperands();
10845       for (unsigned i = 0; i != NumElts; ++i) {
10846         SDValue Elt = RHS.getOperand(i);
10847         if (!isa<ConstantSDNode>(Elt))
10848           return SDValue();
10849
10850         if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
10851           Indices.push_back(i);
10852         else if (cast<ConstantSDNode>(Elt)->isNullValue())
10853           Indices.push_back(NumElts);
10854         else
10855           return SDValue();
10856       }
10857
10858       // Let's see if the target supports this vector_shuffle.
10859       EVT RVT = RHS.getValueType();
10860       if (!TLI.isVectorClearMaskLegal(Indices, RVT))
10861         return SDValue();
10862
10863       // Return the new VECTOR_SHUFFLE node.
10864       EVT EltVT = RVT.getVectorElementType();
10865       SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
10866                                      DAG.getConstant(0, EltVT));
10867       SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), RVT, ZeroOps);
10868       LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
10869       SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
10870       return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
10871     }
10872   }
10873
10874   return SDValue();
10875 }
10876
10877 /// SimplifyVBinOp - Visit a binary vector operation, like ADD.
10878 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
10879   assert(N->getValueType(0).isVector() &&
10880          "SimplifyVBinOp only works on vectors!");
10881
10882   SDValue LHS = N->getOperand(0);
10883   SDValue RHS = N->getOperand(1);
10884   SDValue Shuffle = XformToShuffleWithZero(N);
10885   if (Shuffle.getNode()) return Shuffle;
10886
10887   // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
10888   // this operation.
10889   if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
10890       RHS.getOpcode() == ISD::BUILD_VECTOR) {
10891     // Check if both vectors are constants. If not bail out.
10892     if (!(cast<BuildVectorSDNode>(LHS)->isConstant() &&
10893           cast<BuildVectorSDNode>(RHS)->isConstant()))
10894       return SDValue();
10895
10896     SmallVector<SDValue, 8> Ops;
10897     for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
10898       SDValue LHSOp = LHS.getOperand(i);
10899       SDValue RHSOp = RHS.getOperand(i);
10900
10901       // Can't fold divide by zero.
10902       if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
10903           N->getOpcode() == ISD::FDIV) {
10904         if ((RHSOp.getOpcode() == ISD::Constant &&
10905              cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
10906             (RHSOp.getOpcode() == ISD::ConstantFP &&
10907              cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
10908           break;
10909       }
10910
10911       EVT VT = LHSOp.getValueType();
10912       EVT RVT = RHSOp.getValueType();
10913       if (RVT != VT) {
10914         // Integer BUILD_VECTOR operands may have types larger than the element
10915         // size (e.g., when the element type is not legal).  Prior to type
10916         // legalization, the types may not match between the two BUILD_VECTORS.
10917         // Truncate one of the operands to make them match.
10918         if (RVT.getSizeInBits() > VT.getSizeInBits()) {
10919           RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
10920         } else {
10921           LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
10922           VT = RVT;
10923         }
10924       }
10925       SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
10926                                    LHSOp, RHSOp);
10927       if (FoldOp.getOpcode() != ISD::UNDEF &&
10928           FoldOp.getOpcode() != ISD::Constant &&
10929           FoldOp.getOpcode() != ISD::ConstantFP)
10930         break;
10931       Ops.push_back(FoldOp);
10932       AddToWorkList(FoldOp.getNode());
10933     }
10934
10935     if (Ops.size() == LHS.getNumOperands())
10936       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), LHS.getValueType(), Ops);
10937   }
10938
10939   // Type legalization might introduce new shuffles in the DAG.
10940   // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
10941   //   -> (shuffle (VBinOp (A, B)), Undef, Mask).
10942   if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
10943       isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
10944       LHS.getOperand(1).getOpcode() == ISD::UNDEF &&
10945       RHS.getOperand(1).getOpcode() == ISD::UNDEF) {
10946     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
10947     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
10948
10949     if (SVN0->getMask().equals(SVN1->getMask())) {
10950       EVT VT = N->getValueType(0);
10951       SDValue UndefVector = LHS.getOperand(1);
10952       SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
10953                                      LHS.getOperand(0), RHS.getOperand(0));
10954       AddUsersToWorkList(N);
10955       return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
10956                                   &SVN0->getMask()[0]);
10957     }
10958   }
10959
10960   return SDValue();
10961 }
10962
10963 /// SimplifyVUnaryOp - Visit a binary vector operation, like FABS/FNEG.
10964 SDValue DAGCombiner::SimplifyVUnaryOp(SDNode *N) {
10965   assert(N->getValueType(0).isVector() &&
10966          "SimplifyVUnaryOp only works on vectors!");
10967
10968   SDValue N0 = N->getOperand(0);
10969
10970   if (N0.getOpcode() != ISD::BUILD_VECTOR)
10971     return SDValue();
10972
10973   // Operand is a BUILD_VECTOR node, see if we can constant fold it.
10974   SmallVector<SDValue, 8> Ops;
10975   for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
10976     SDValue Op = N0.getOperand(i);
10977     if (Op.getOpcode() != ISD::UNDEF &&
10978         Op.getOpcode() != ISD::ConstantFP)
10979       break;
10980     EVT EltVT = Op.getValueType();
10981     SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(N0), EltVT, Op);
10982     if (FoldOp.getOpcode() != ISD::UNDEF &&
10983         FoldOp.getOpcode() != ISD::ConstantFP)
10984       break;
10985     Ops.push_back(FoldOp);
10986     AddToWorkList(FoldOp.getNode());
10987   }
10988
10989   if (Ops.size() != N0.getNumOperands())
10990     return SDValue();
10991
10992   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), N0.getValueType(), Ops);
10993 }
10994
10995 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
10996                                     SDValue N1, SDValue N2){
10997   assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
10998
10999   SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
11000                                  cast<CondCodeSDNode>(N0.getOperand(2))->get());
11001
11002   // If we got a simplified select_cc node back from SimplifySelectCC, then
11003   // break it down into a new SETCC node, and a new SELECT node, and then return
11004   // the SELECT node, since we were called with a SELECT node.
11005   if (SCC.getNode()) {
11006     // Check to see if we got a select_cc back (to turn into setcc/select).
11007     // Otherwise, just return whatever node we got back, like fabs.
11008     if (SCC.getOpcode() == ISD::SELECT_CC) {
11009       SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
11010                                   N0.getValueType(),
11011                                   SCC.getOperand(0), SCC.getOperand(1),
11012                                   SCC.getOperand(4));
11013       AddToWorkList(SETCC.getNode());
11014       return DAG.getSelect(SDLoc(SCC), SCC.getValueType(),
11015                            SCC.getOperand(2), SCC.getOperand(3), SETCC);
11016     }
11017
11018     return SCC;
11019   }
11020   return SDValue();
11021 }
11022
11023 /// SimplifySelectOps - Given a SELECT or a SELECT_CC node, where LHS and RHS
11024 /// are the two values being selected between, see if we can simplify the
11025 /// select.  Callers of this should assume that TheSelect is deleted if this
11026 /// returns true.  As such, they should return the appropriate thing (e.g. the
11027 /// node) back to the top-level of the DAG combiner loop to avoid it being
11028 /// looked at.
11029 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
11030                                     SDValue RHS) {
11031
11032   // Cannot simplify select with vector condition
11033   if (TheSelect->getOperand(0).getValueType().isVector()) return false;
11034
11035   // If this is a select from two identical things, try to pull the operation
11036   // through the select.
11037   if (LHS.getOpcode() != RHS.getOpcode() ||
11038       !LHS.hasOneUse() || !RHS.hasOneUse())
11039     return false;
11040
11041   // If this is a load and the token chain is identical, replace the select
11042   // of two loads with a load through a select of the address to load from.
11043   // This triggers in things like "select bool X, 10.0, 123.0" after the FP
11044   // constants have been dropped into the constant pool.
11045   if (LHS.getOpcode() == ISD::LOAD) {
11046     LoadSDNode *LLD = cast<LoadSDNode>(LHS);
11047     LoadSDNode *RLD = cast<LoadSDNode>(RHS);
11048
11049     // Token chains must be identical.
11050     if (LHS.getOperand(0) != RHS.getOperand(0) ||
11051         // Do not let this transformation reduce the number of volatile loads.
11052         LLD->isVolatile() || RLD->isVolatile() ||
11053         // If this is an EXTLOAD, the VT's must match.
11054         LLD->getMemoryVT() != RLD->getMemoryVT() ||
11055         // If this is an EXTLOAD, the kind of extension must match.
11056         (LLD->getExtensionType() != RLD->getExtensionType() &&
11057          // The only exception is if one of the extensions is anyext.
11058          LLD->getExtensionType() != ISD::EXTLOAD &&
11059          RLD->getExtensionType() != ISD::EXTLOAD) ||
11060         // FIXME: this discards src value information.  This is
11061         // over-conservative. It would be beneficial to be able to remember
11062         // both potential memory locations.  Since we are discarding
11063         // src value info, don't do the transformation if the memory
11064         // locations are not in the default address space.
11065         LLD->getPointerInfo().getAddrSpace() != 0 ||
11066         RLD->getPointerInfo().getAddrSpace() != 0 ||
11067         !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
11068                                       LLD->getBasePtr().getValueType()))
11069       return false;
11070
11071     // Check that the select condition doesn't reach either load.  If so,
11072     // folding this will induce a cycle into the DAG.  If not, this is safe to
11073     // xform, so create a select of the addresses.
11074     SDValue Addr;
11075     if (TheSelect->getOpcode() == ISD::SELECT) {
11076       SDNode *CondNode = TheSelect->getOperand(0).getNode();
11077       if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
11078           (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
11079         return false;
11080       // The loads must not depend on one another.
11081       if (LLD->isPredecessorOf(RLD) ||
11082           RLD->isPredecessorOf(LLD))
11083         return false;
11084       Addr = DAG.getSelect(SDLoc(TheSelect),
11085                            LLD->getBasePtr().getValueType(),
11086                            TheSelect->getOperand(0), LLD->getBasePtr(),
11087                            RLD->getBasePtr());
11088     } else {  // Otherwise SELECT_CC
11089       SDNode *CondLHS = TheSelect->getOperand(0).getNode();
11090       SDNode *CondRHS = TheSelect->getOperand(1).getNode();
11091
11092       if ((LLD->hasAnyUseOfValue(1) &&
11093            (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
11094           (RLD->hasAnyUseOfValue(1) &&
11095            (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
11096         return false;
11097
11098       Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
11099                          LLD->getBasePtr().getValueType(),
11100                          TheSelect->getOperand(0),
11101                          TheSelect->getOperand(1),
11102                          LLD->getBasePtr(), RLD->getBasePtr(),
11103                          TheSelect->getOperand(4));
11104     }
11105
11106     SDValue Load;
11107     if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
11108       Load = DAG.getLoad(TheSelect->getValueType(0),
11109                          SDLoc(TheSelect),
11110                          // FIXME: Discards pointer and TBAA info.
11111                          LLD->getChain(), Addr, MachinePointerInfo(),
11112                          LLD->isVolatile(), LLD->isNonTemporal(),
11113                          LLD->isInvariant(), LLD->getAlignment());
11114     } else {
11115       Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
11116                             RLD->getExtensionType() : LLD->getExtensionType(),
11117                             SDLoc(TheSelect),
11118                             TheSelect->getValueType(0),
11119                             // FIXME: Discards pointer and TBAA info.
11120                             LLD->getChain(), Addr, MachinePointerInfo(),
11121                             LLD->getMemoryVT(), LLD->isVolatile(),
11122                             LLD->isNonTemporal(), LLD->getAlignment());
11123     }
11124
11125     // Users of the select now use the result of the load.
11126     CombineTo(TheSelect, Load);
11127
11128     // Users of the old loads now use the new load's chain.  We know the
11129     // old-load value is dead now.
11130     CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
11131     CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
11132     return true;
11133   }
11134
11135   return false;
11136 }
11137
11138 /// SimplifySelectCC - Simplify an expression of the form (N0 cond N1) ? N2 : N3
11139 /// where 'cond' is the comparison specified by CC.
11140 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
11141                                       SDValue N2, SDValue N3,
11142                                       ISD::CondCode CC, bool NotExtCompare) {
11143   // (x ? y : y) -> y.
11144   if (N2 == N3) return N2;
11145
11146   EVT VT = N2.getValueType();
11147   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
11148   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
11149   ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
11150
11151   // Determine if the condition we're dealing with is constant
11152   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
11153                               N0, N1, CC, DL, false);
11154   if (SCC.getNode()) AddToWorkList(SCC.getNode());
11155   ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
11156
11157   // fold select_cc true, x, y -> x
11158   if (SCCC && !SCCC->isNullValue())
11159     return N2;
11160   // fold select_cc false, x, y -> y
11161   if (SCCC && SCCC->isNullValue())
11162     return N3;
11163
11164   // Check to see if we can simplify the select into an fabs node
11165   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
11166     // Allow either -0.0 or 0.0
11167     if (CFP->getValueAPF().isZero()) {
11168       // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
11169       if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
11170           N0 == N2 && N3.getOpcode() == ISD::FNEG &&
11171           N2 == N3.getOperand(0))
11172         return DAG.getNode(ISD::FABS, DL, VT, N0);
11173
11174       // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
11175       if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
11176           N0 == N3 && N2.getOpcode() == ISD::FNEG &&
11177           N2.getOperand(0) == N3)
11178         return DAG.getNode(ISD::FABS, DL, VT, N3);
11179     }
11180   }
11181
11182   // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
11183   // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
11184   // in it.  This is a win when the constant is not otherwise available because
11185   // it replaces two constant pool loads with one.  We only do this if the FP
11186   // type is known to be legal, because if it isn't, then we are before legalize
11187   // types an we want the other legalization to happen first (e.g. to avoid
11188   // messing with soft float) and if the ConstantFP is not legal, because if
11189   // it is legal, we may not need to store the FP constant in a constant pool.
11190   if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
11191     if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
11192       if (TLI.isTypeLegal(N2.getValueType()) &&
11193           (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
11194                TargetLowering::Legal &&
11195            !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
11196            !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
11197           // If both constants have multiple uses, then we won't need to do an
11198           // extra load, they are likely around in registers for other users.
11199           (TV->hasOneUse() || FV->hasOneUse())) {
11200         Constant *Elts[] = {
11201           const_cast<ConstantFP*>(FV->getConstantFPValue()),
11202           const_cast<ConstantFP*>(TV->getConstantFPValue())
11203         };
11204         Type *FPTy = Elts[0]->getType();
11205         const DataLayout &TD = *TLI.getDataLayout();
11206
11207         // Create a ConstantArray of the two constants.
11208         Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
11209         SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
11210                                             TD.getPrefTypeAlignment(FPTy));
11211         unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
11212
11213         // Get the offsets to the 0 and 1 element of the array so that we can
11214         // select between them.
11215         SDValue Zero = DAG.getIntPtrConstant(0);
11216         unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
11217         SDValue One = DAG.getIntPtrConstant(EltSize);
11218
11219         SDValue Cond = DAG.getSetCC(DL,
11220                                     getSetCCResultType(N0.getValueType()),
11221                                     N0, N1, CC);
11222         AddToWorkList(Cond.getNode());
11223         SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
11224                                           Cond, One, Zero);
11225         AddToWorkList(CstOffset.getNode());
11226         CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
11227                             CstOffset);
11228         AddToWorkList(CPIdx.getNode());
11229         return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
11230                            MachinePointerInfo::getConstantPool(), false,
11231                            false, false, Alignment);
11232
11233       }
11234     }
11235
11236   // Check to see if we can perform the "gzip trick", transforming
11237   // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
11238   if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
11239       (N1C->isNullValue() ||                         // (a < 0) ? b : 0
11240        (N1C->getAPIntValue() == 1 && N0 == N2))) {   // (a < 1) ? a : 0
11241     EVT XType = N0.getValueType();
11242     EVT AType = N2.getValueType();
11243     if (XType.bitsGE(AType)) {
11244       // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
11245       // single-bit constant.
11246       if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
11247         unsigned ShCtV = N2C->getAPIntValue().logBase2();
11248         ShCtV = XType.getSizeInBits()-ShCtV-1;
11249         SDValue ShCt = DAG.getConstant(ShCtV,
11250                                        getShiftAmountTy(N0.getValueType()));
11251         SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
11252                                     XType, N0, ShCt);
11253         AddToWorkList(Shift.getNode());
11254
11255         if (XType.bitsGT(AType)) {
11256           Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
11257           AddToWorkList(Shift.getNode());
11258         }
11259
11260         return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
11261       }
11262
11263       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
11264                                   XType, N0,
11265                                   DAG.getConstant(XType.getSizeInBits()-1,
11266                                          getShiftAmountTy(N0.getValueType())));
11267       AddToWorkList(Shift.getNode());
11268
11269       if (XType.bitsGT(AType)) {
11270         Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
11271         AddToWorkList(Shift.getNode());
11272       }
11273
11274       return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
11275     }
11276   }
11277
11278   // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
11279   // where y is has a single bit set.
11280   // A plaintext description would be, we can turn the SELECT_CC into an AND
11281   // when the condition can be materialized as an all-ones register.  Any
11282   // single bit-test can be materialized as an all-ones register with
11283   // shift-left and shift-right-arith.
11284   if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
11285       N0->getValueType(0) == VT &&
11286       N1C && N1C->isNullValue() &&
11287       N2C && N2C->isNullValue()) {
11288     SDValue AndLHS = N0->getOperand(0);
11289     ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
11290     if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
11291       // Shift the tested bit over the sign bit.
11292       APInt AndMask = ConstAndRHS->getAPIntValue();
11293       SDValue ShlAmt =
11294         DAG.getConstant(AndMask.countLeadingZeros(),
11295                         getShiftAmountTy(AndLHS.getValueType()));
11296       SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
11297
11298       // Now arithmetic right shift it all the way over, so the result is either
11299       // all-ones, or zero.
11300       SDValue ShrAmt =
11301         DAG.getConstant(AndMask.getBitWidth()-1,
11302                         getShiftAmountTy(Shl.getValueType()));
11303       SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
11304
11305       return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
11306     }
11307   }
11308
11309   // fold select C, 16, 0 -> shl C, 4
11310   if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
11311       TLI.getBooleanContents(N0.getValueType()) ==
11312           TargetLowering::ZeroOrOneBooleanContent) {
11313
11314     // If the caller doesn't want us to simplify this into a zext of a compare,
11315     // don't do it.
11316     if (NotExtCompare && N2C->getAPIntValue() == 1)
11317       return SDValue();
11318
11319     // Get a SetCC of the condition
11320     // NOTE: Don't create a SETCC if it's not legal on this target.
11321     if (!LegalOperations ||
11322         TLI.isOperationLegal(ISD::SETCC,
11323           LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
11324       SDValue Temp, SCC;
11325       // cast from setcc result type to select result type
11326       if (LegalTypes) {
11327         SCC  = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
11328                             N0, N1, CC);
11329         if (N2.getValueType().bitsLT(SCC.getValueType()))
11330           Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
11331                                         N2.getValueType());
11332         else
11333           Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
11334                              N2.getValueType(), SCC);
11335       } else {
11336         SCC  = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
11337         Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
11338                            N2.getValueType(), SCC);
11339       }
11340
11341       AddToWorkList(SCC.getNode());
11342       AddToWorkList(Temp.getNode());
11343
11344       if (N2C->getAPIntValue() == 1)
11345         return Temp;
11346
11347       // shl setcc result by log2 n2c
11348       return DAG.getNode(
11349           ISD::SHL, DL, N2.getValueType(), Temp,
11350           DAG.getConstant(N2C->getAPIntValue().logBase2(),
11351                           getShiftAmountTy(Temp.getValueType())));
11352     }
11353   }
11354
11355   // Check to see if this is the equivalent of setcc
11356   // FIXME: Turn all of these into setcc if setcc if setcc is legal
11357   // otherwise, go ahead with the folds.
11358   if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
11359     EVT XType = N0.getValueType();
11360     if (!LegalOperations ||
11361         TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
11362       SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
11363       if (Res.getValueType() != VT)
11364         Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
11365       return Res;
11366     }
11367
11368     // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
11369     if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
11370         (!LegalOperations ||
11371          TLI.isOperationLegal(ISD::CTLZ, XType))) {
11372       SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
11373       return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
11374                          DAG.getConstant(Log2_32(XType.getSizeInBits()),
11375                                        getShiftAmountTy(Ctlz.getValueType())));
11376     }
11377     // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
11378     if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
11379       SDValue NegN0 = DAG.getNode(ISD::SUB, SDLoc(N0),
11380                                   XType, DAG.getConstant(0, XType), N0);
11381       SDValue NotN0 = DAG.getNOT(SDLoc(N0), N0, XType);
11382       return DAG.getNode(ISD::SRL, DL, XType,
11383                          DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
11384                          DAG.getConstant(XType.getSizeInBits()-1,
11385                                          getShiftAmountTy(XType)));
11386     }
11387     // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
11388     if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
11389       SDValue Sign = DAG.getNode(ISD::SRL, SDLoc(N0), XType, N0,
11390                                  DAG.getConstant(XType.getSizeInBits()-1,
11391                                          getShiftAmountTy(N0.getValueType())));
11392       return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
11393     }
11394   }
11395
11396   // Check to see if this is an integer abs.
11397   // select_cc setg[te] X,  0,  X, -X ->
11398   // select_cc setgt    X, -1,  X, -X ->
11399   // select_cc setl[te] X,  0, -X,  X ->
11400   // select_cc setlt    X,  1, -X,  X ->
11401   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
11402   if (N1C) {
11403     ConstantSDNode *SubC = nullptr;
11404     if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
11405          (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
11406         N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
11407       SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
11408     else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
11409               (N1C->isOne() && CC == ISD::SETLT)) &&
11410              N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
11411       SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
11412
11413     EVT XType = N0.getValueType();
11414     if (SubC && SubC->isNullValue() && XType.isInteger()) {
11415       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), XType,
11416                                   N0,
11417                                   DAG.getConstant(XType.getSizeInBits()-1,
11418                                          getShiftAmountTy(N0.getValueType())));
11419       SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0),
11420                                 XType, N0, Shift);
11421       AddToWorkList(Shift.getNode());
11422       AddToWorkList(Add.getNode());
11423       return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
11424     }
11425   }
11426
11427   return SDValue();
11428 }
11429
11430 /// SimplifySetCC - This is a stub for TargetLowering::SimplifySetCC.
11431 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
11432                                    SDValue N1, ISD::CondCode Cond,
11433                                    SDLoc DL, bool foldBooleans) {
11434   TargetLowering::DAGCombinerInfo
11435     DagCombineInfo(DAG, Level, false, this);
11436   return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
11437 }
11438
11439 /// BuildSDIVSequence - Given an ISD::SDIV node expressing a divide by constant,
11440 /// return a DAG expression to select that will generate the same value by
11441 /// multiplying by a magic number.  See:
11442 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
11443 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
11444   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
11445   if (!C)
11446     return SDValue();
11447
11448   // Avoid division by zero.
11449   if (!C->getAPIntValue())
11450     return SDValue();
11451
11452   std::vector<SDNode*> Built;
11453   SDValue S =
11454       TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
11455
11456   for (SDNode *N : Built)
11457     AddToWorkList(N);
11458   return S;
11459 }
11460
11461 /// BuildUDIV - Given an ISD::UDIV node expressing a divide by constant,
11462 /// return a DAG expression to select that will generate the same value by
11463 /// multiplying by a magic number.  See:
11464 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
11465 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
11466   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
11467   if (!C)
11468     return SDValue();
11469
11470   // Avoid division by zero.
11471   if (!C->getAPIntValue())
11472     return SDValue();
11473
11474   std::vector<SDNode*> Built;
11475   SDValue S =
11476       TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
11477
11478   for (SDNode *N : Built)
11479     AddToWorkList(N);
11480   return S;
11481 }
11482
11483 /// FindBaseOffset - Return true if base is a frame index, which is known not
11484 // to alias with anything but itself.  Provides base object and offset as
11485 // results.
11486 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
11487                            const GlobalValue *&GV, const void *&CV) {
11488   // Assume it is a primitive operation.
11489   Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
11490
11491   // If it's an adding a simple constant then integrate the offset.
11492   if (Base.getOpcode() == ISD::ADD) {
11493     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
11494       Base = Base.getOperand(0);
11495       Offset += C->getZExtValue();
11496     }
11497   }
11498
11499   // Return the underlying GlobalValue, and update the Offset.  Return false
11500   // for GlobalAddressSDNode since the same GlobalAddress may be represented
11501   // by multiple nodes with different offsets.
11502   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
11503     GV = G->getGlobal();
11504     Offset += G->getOffset();
11505     return false;
11506   }
11507
11508   // Return the underlying Constant value, and update the Offset.  Return false
11509   // for ConstantSDNodes since the same constant pool entry may be represented
11510   // by multiple nodes with different offsets.
11511   if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
11512     CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
11513                                          : (const void *)C->getConstVal();
11514     Offset += C->getOffset();
11515     return false;
11516   }
11517   // If it's any of the following then it can't alias with anything but itself.
11518   return isa<FrameIndexSDNode>(Base);
11519 }
11520
11521 /// isAlias - Return true if there is any possibility that the two addresses
11522 /// overlap.
11523 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
11524   // If they are the same then they must be aliases.
11525   if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
11526
11527   // If they are both volatile then they cannot be reordered.
11528   if (Op0->isVolatile() && Op1->isVolatile()) return true;
11529
11530   // Gather base node and offset information.
11531   SDValue Base1, Base2;
11532   int64_t Offset1, Offset2;
11533   const GlobalValue *GV1, *GV2;
11534   const void *CV1, *CV2;
11535   bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
11536                                       Base1, Offset1, GV1, CV1);
11537   bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
11538                                       Base2, Offset2, GV2, CV2);
11539
11540   // If they have a same base address then check to see if they overlap.
11541   if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
11542     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
11543              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
11544
11545   // It is possible for different frame indices to alias each other, mostly
11546   // when tail call optimization reuses return address slots for arguments.
11547   // To catch this case, look up the actual index of frame indices to compute
11548   // the real alias relationship.
11549   if (isFrameIndex1 && isFrameIndex2) {
11550     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11551     Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
11552     Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
11553     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
11554              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
11555   }
11556
11557   // Otherwise, if we know what the bases are, and they aren't identical, then
11558   // we know they cannot alias.
11559   if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
11560     return false;
11561
11562   // If we know required SrcValue1 and SrcValue2 have relatively large alignment
11563   // compared to the size and offset of the access, we may be able to prove they
11564   // do not alias.  This check is conservative for now to catch cases created by
11565   // splitting vector types.
11566   if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
11567       (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
11568       (Op0->getMemoryVT().getSizeInBits() >> 3 ==
11569        Op1->getMemoryVT().getSizeInBits() >> 3) &&
11570       (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) {
11571     int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
11572     int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
11573
11574     // There is no overlap between these relatively aligned accesses of similar
11575     // size, return no alias.
11576     if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
11577         (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
11578       return false;
11579   }
11580
11581   bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0 ? CombinerGlobalAA :
11582     TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
11583 #ifndef NDEBUG
11584   if (CombinerAAOnlyFunc.getNumOccurrences() &&
11585       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
11586     UseAA = false;
11587 #endif
11588   if (UseAA &&
11589       Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
11590     // Use alias analysis information.
11591     int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
11592                                  Op1->getSrcValueOffset());
11593     int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
11594         Op0->getSrcValueOffset() - MinOffset;
11595     int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
11596         Op1->getSrcValueOffset() - MinOffset;
11597     AliasAnalysis::AliasResult AAResult =
11598         AA.alias(AliasAnalysis::Location(Op0->getMemOperand()->getValue(),
11599                                          Overlap1,
11600                                          UseTBAA ? Op0->getTBAAInfo() : nullptr),
11601                  AliasAnalysis::Location(Op1->getMemOperand()->getValue(),
11602                                          Overlap2,
11603                                          UseTBAA ? Op1->getTBAAInfo() : nullptr));
11604     if (AAResult == AliasAnalysis::NoAlias)
11605       return false;
11606   }
11607
11608   // Otherwise we have to assume they alias.
11609   return true;
11610 }
11611
11612 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
11613 /// looking for aliasing nodes and adding them to the Aliases vector.
11614 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
11615                                    SmallVectorImpl<SDValue> &Aliases) {
11616   SmallVector<SDValue, 8> Chains;     // List of chains to visit.
11617   SmallPtrSet<SDNode *, 16> Visited;  // Visited node set.
11618
11619   // Get alias information for node.
11620   bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
11621
11622   // Starting off.
11623   Chains.push_back(OriginalChain);
11624   unsigned Depth = 0;
11625
11626   // Look at each chain and determine if it is an alias.  If so, add it to the
11627   // aliases list.  If not, then continue up the chain looking for the next
11628   // candidate.
11629   while (!Chains.empty()) {
11630     SDValue Chain = Chains.back();
11631     Chains.pop_back();
11632
11633     // For TokenFactor nodes, look at each operand and only continue up the
11634     // chain until we find two aliases.  If we've seen two aliases, assume we'll
11635     // find more and revert to original chain since the xform is unlikely to be
11636     // profitable.
11637     //
11638     // FIXME: The depth check could be made to return the last non-aliasing
11639     // chain we found before we hit a tokenfactor rather than the original
11640     // chain.
11641     if (Depth > 6 || Aliases.size() == 2) {
11642       Aliases.clear();
11643       Aliases.push_back(OriginalChain);
11644       return;
11645     }
11646
11647     // Don't bother if we've been before.
11648     if (!Visited.insert(Chain.getNode()))
11649       continue;
11650
11651     switch (Chain.getOpcode()) {
11652     case ISD::EntryToken:
11653       // Entry token is ideal chain operand, but handled in FindBetterChain.
11654       break;
11655
11656     case ISD::LOAD:
11657     case ISD::STORE: {
11658       // Get alias information for Chain.
11659       bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
11660           !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
11661
11662       // If chain is alias then stop here.
11663       if (!(IsLoad && IsOpLoad) &&
11664           isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
11665         Aliases.push_back(Chain);
11666       } else {
11667         // Look further up the chain.
11668         Chains.push_back(Chain.getOperand(0));
11669         ++Depth;
11670       }
11671       break;
11672     }
11673
11674     case ISD::TokenFactor:
11675       // We have to check each of the operands of the token factor for "small"
11676       // token factors, so we queue them up.  Adding the operands to the queue
11677       // (stack) in reverse order maintains the original order and increases the
11678       // likelihood that getNode will find a matching token factor (CSE.)
11679       if (Chain.getNumOperands() > 16) {
11680         Aliases.push_back(Chain);
11681         break;
11682       }
11683       for (unsigned n = Chain.getNumOperands(); n;)
11684         Chains.push_back(Chain.getOperand(--n));
11685       ++Depth;
11686       break;
11687
11688     default:
11689       // For all other instructions we will just have to take what we can get.
11690       Aliases.push_back(Chain);
11691       break;
11692     }
11693   }
11694
11695   // We need to be careful here to also search for aliases through the
11696   // value operand of a store, etc. Consider the following situation:
11697   //   Token1 = ...
11698   //   L1 = load Token1, %52
11699   //   S1 = store Token1, L1, %51
11700   //   L2 = load Token1, %52+8
11701   //   S2 = store Token1, L2, %51+8
11702   //   Token2 = Token(S1, S2)
11703   //   L3 = load Token2, %53
11704   //   S3 = store Token2, L3, %52
11705   //   L4 = load Token2, %53+8
11706   //   S4 = store Token2, L4, %52+8
11707   // If we search for aliases of S3 (which loads address %52), and we look
11708   // only through the chain, then we'll miss the trivial dependence on L1
11709   // (which also loads from %52). We then might change all loads and
11710   // stores to use Token1 as their chain operand, which could result in
11711   // copying %53 into %52 before copying %52 into %51 (which should
11712   // happen first).
11713   //
11714   // The problem is, however, that searching for such data dependencies
11715   // can become expensive, and the cost is not directly related to the
11716   // chain depth. Instead, we'll rule out such configurations here by
11717   // insisting that we've visited all chain users (except for users
11718   // of the original chain, which is not necessary). When doing this,
11719   // we need to look through nodes we don't care about (otherwise, things
11720   // like register copies will interfere with trivial cases).
11721
11722   SmallVector<const SDNode *, 16> Worklist;
11723   for (SmallPtrSet<SDNode *, 16>::iterator I = Visited.begin(),
11724        IE = Visited.end(); I != IE; ++I)
11725     if (*I != OriginalChain.getNode())
11726       Worklist.push_back(*I);
11727
11728   while (!Worklist.empty()) {
11729     const SDNode *M = Worklist.pop_back_val();
11730
11731     // We have already visited M, and want to make sure we've visited any uses
11732     // of M that we care about. For uses that we've not visisted, and don't
11733     // care about, queue them to the worklist.
11734
11735     for (SDNode::use_iterator UI = M->use_begin(),
11736          UIE = M->use_end(); UI != UIE; ++UI)
11737       if (UI.getUse().getValueType() == MVT::Other && Visited.insert(*UI)) {
11738         if (isa<MemIntrinsicSDNode>(*UI) || isa<MemSDNode>(*UI)) {
11739           // We've not visited this use, and we care about it (it could have an
11740           // ordering dependency with the original node).
11741           Aliases.clear();
11742           Aliases.push_back(OriginalChain);
11743           return;
11744         }
11745
11746         // We've not visited this use, but we don't care about it. Mark it as
11747         // visited and enqueue it to the worklist.
11748         Worklist.push_back(*UI);
11749       }
11750   }
11751 }
11752
11753 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes, looking
11754 /// for a better chain (aliasing node.)
11755 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
11756   SmallVector<SDValue, 8> Aliases;  // Ops for replacing token factor.
11757
11758   // Accumulate all the aliases to this node.
11759   GatherAllAliases(N, OldChain, Aliases);
11760
11761   // If no operands then chain to entry token.
11762   if (Aliases.size() == 0)
11763     return DAG.getEntryNode();
11764
11765   // If a single operand then chain to it.  We don't need to revisit it.
11766   if (Aliases.size() == 1)
11767     return Aliases[0];
11768
11769   // Construct a custom tailored token factor.
11770   return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
11771 }
11772
11773 // SelectionDAG::Combine - This is the entry point for the file.
11774 //
11775 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
11776                            CodeGenOpt::Level OptLevel) {
11777   /// run - This is the main entry point to this class.
11778   ///
11779   DAGCombiner(*this, AA, OptLevel).Run(Level);
11780 }