cb9e13c331da56361682650c0e9095baa4e02a00
[oota-llvm.git] / lib / CodeGen / SelectionDAG / DAGCombiner.cpp
1 //===-- DAGCombiner.cpp - Implement a DAG node combiner -------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This pass combines dag nodes to form fewer, simpler DAG nodes.  It can be run
11 // both before and after the DAG is legalized.
12 //
13 // This pass is not a substitute for the LLVM IR instcombine pass. This pass is
14 // primarily intended to handle simplification opportunities that are implicit
15 // in the LLVM IR and exposed by the various codegen lowering phases.
16 //
17 //===----------------------------------------------------------------------===//
18
19 #include "llvm/CodeGen/SelectionDAG.h"
20 #include "llvm/ADT/SmallPtrSet.h"
21 #include "llvm/ADT/SetVector.h"
22 #include "llvm/ADT/Statistic.h"
23 #include "llvm/Analysis/AliasAnalysis.h"
24 #include "llvm/CodeGen/MachineFrameInfo.h"
25 #include "llvm/CodeGen/MachineFunction.h"
26 #include "llvm/IR/DataLayout.h"
27 #include "llvm/IR/DerivedTypes.h"
28 #include "llvm/IR/Function.h"
29 #include "llvm/IR/LLVMContext.h"
30 #include "llvm/Support/CommandLine.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/Support/ErrorHandling.h"
33 #include "llvm/Support/MathExtras.h"
34 #include "llvm/Support/raw_ostream.h"
35 #include "llvm/Target/TargetLowering.h"
36 #include "llvm/Target/TargetMachine.h"
37 #include "llvm/Target/TargetOptions.h"
38 #include "llvm/Target/TargetRegisterInfo.h"
39 #include "llvm/Target/TargetSubtargetInfo.h"
40 #include <algorithm>
41 using namespace llvm;
42
43 #define DEBUG_TYPE "dagcombine"
44
45 STATISTIC(NodesCombined   , "Number of dag nodes combined");
46 STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created");
47 STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created");
48 STATISTIC(OpsNarrowed     , "Number of load/op/store narrowed");
49 STATISTIC(LdStFP2Int      , "Number of fp load/store pairs transformed to int");
50 STATISTIC(SlicedLoads, "Number of load sliced");
51
52 namespace {
53   static cl::opt<bool>
54     CombinerAA("combiner-alias-analysis", cl::Hidden,
55                cl::desc("Enable DAG combiner alias-analysis heuristics"));
56
57   static cl::opt<bool>
58     CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
59                cl::desc("Enable DAG combiner's use of IR alias analysis"));
60
61   static cl::opt<bool>
62     UseTBAA("combiner-use-tbaa", cl::Hidden, cl::init(true),
63                cl::desc("Enable DAG combiner's use of TBAA"));
64
65 #ifndef NDEBUG
66   static cl::opt<std::string>
67     CombinerAAOnlyFunc("combiner-aa-only-func", cl::Hidden,
68                cl::desc("Only use DAG-combiner alias analysis in this"
69                         " function"));
70 #endif
71
72   /// Hidden option to stress test load slicing, i.e., when this option
73   /// is enabled, load slicing bypasses most of its profitability guards.
74   static cl::opt<bool>
75   StressLoadSlicing("combiner-stress-load-slicing", cl::Hidden,
76                     cl::desc("Bypass the profitability model of load "
77                              "slicing"),
78                     cl::init(false));
79
80 //------------------------------ DAGCombiner ---------------------------------//
81
82   class DAGCombiner {
83     SelectionDAG &DAG;
84     const TargetLowering &TLI;
85     CombineLevel Level;
86     CodeGenOpt::Level OptLevel;
87     bool LegalOperations;
88     bool LegalTypes;
89     bool ForCodeSize;
90
91     /// \brief Worklist of all of the nodes that need to be simplified.
92     ///
93     /// This must behave as a stack -- new nodes to process are pushed onto the
94     /// back and when processing we pop off of the back.
95     ///
96     /// The worklist will not contain duplicates but may contain null entries
97     /// due to nodes being deleted from the underlying DAG.
98     SmallVector<SDNode *, 64> Worklist;
99
100     /// \brief Mapping from an SDNode to its position on the worklist.
101     ///
102     /// This is used to find and remove nodes from the worklist (by nulling
103     /// them) when they are deleted from the underlying DAG. It relies on
104     /// stable indices of nodes within the worklist.
105     DenseMap<SDNode *, unsigned> WorklistMap;
106
107     /// \brief Set of nodes which have been combined (at least once).
108     ///
109     /// This is used to allow us to reliably add any operands of a DAG node
110     /// which have not yet been combined to the worklist.
111     SmallPtrSet<SDNode *, 64> CombinedNodes;
112
113     // AA - Used for DAG load/store alias analysis.
114     AliasAnalysis &AA;
115
116     /// AddUsersToWorklist - When an instruction is simplified, add all users of
117     /// the instruction to the work lists because they might get more simplified
118     /// now.
119     ///
120     void AddUsersToWorklist(SDNode *N) {
121       for (SDNode *Node : N->uses())
122         AddToWorklist(Node);
123     }
124
125     /// visit - call the node-specific routine that knows how to fold each
126     /// particular type of node.
127     SDValue visit(SDNode *N);
128
129   public:
130     /// AddToWorklist - Add to the work list making sure its instance is at the
131     /// back (next to be processed.)
132     void AddToWorklist(SDNode *N) {
133       // Skip handle nodes as they can't usefully be combined and confuse the
134       // zero-use deletion strategy.
135       if (N->getOpcode() == ISD::HANDLENODE)
136         return;
137
138       if (WorklistMap.insert(std::make_pair(N, Worklist.size())).second)
139         Worklist.push_back(N);
140     }
141
142     /// removeFromWorklist - remove all instances of N from the worklist.
143     ///
144     void removeFromWorklist(SDNode *N) {
145       CombinedNodes.erase(N);
146
147       auto It = WorklistMap.find(N);
148       if (It == WorklistMap.end())
149         return; // Not in the worklist.
150
151       // Null out the entry rather than erasing it to avoid a linear operation.
152       Worklist[It->second] = nullptr;
153       WorklistMap.erase(It);
154     }
155
156     void deleteAndRecombine(SDNode *N);
157     bool recursivelyDeleteUnusedNodes(SDNode *N);
158
159     SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
160                       bool AddTo = true);
161
162     SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
163       return CombineTo(N, &Res, 1, AddTo);
164     }
165
166     SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
167                       bool AddTo = true) {
168       SDValue To[] = { Res0, Res1 };
169       return CombineTo(N, To, 2, AddTo);
170     }
171
172     void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
173
174   private:
175
176     /// SimplifyDemandedBits - Check the specified integer node value to see if
177     /// it can be simplified or if things it uses can be simplified by bit
178     /// propagation.  If so, return true.
179     bool SimplifyDemandedBits(SDValue Op) {
180       unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits();
181       APInt Demanded = APInt::getAllOnesValue(BitWidth);
182       return SimplifyDemandedBits(Op, Demanded);
183     }
184
185     bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded);
186
187     bool CombineToPreIndexedLoadStore(SDNode *N);
188     bool CombineToPostIndexedLoadStore(SDNode *N);
189     bool SliceUpLoad(SDNode *N);
190
191     void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
192     SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
193     SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
194     SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
195     SDValue PromoteIntBinOp(SDValue Op);
196     SDValue PromoteIntShiftOp(SDValue Op);
197     SDValue PromoteExtend(SDValue Op);
198     bool PromoteLoad(SDValue Op);
199
200     void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
201                          SDValue Trunc, SDValue ExtLoad, SDLoc DL,
202                          ISD::NodeType ExtType);
203
204     /// combine - call the node-specific routine that knows how to fold each
205     /// particular type of node. If that doesn't do anything, try the
206     /// target-specific DAG combines.
207     SDValue combine(SDNode *N);
208
209     // Visitation implementation - Implement dag node combining for different
210     // node types.  The semantics are as follows:
211     // Return Value:
212     //   SDValue.getNode() == 0 - No change was made
213     //   SDValue.getNode() == N - N was replaced, is dead and has been handled.
214     //   otherwise              - N should be replaced by the returned Operand.
215     //
216     SDValue visitTokenFactor(SDNode *N);
217     SDValue visitMERGE_VALUES(SDNode *N);
218     SDValue visitADD(SDNode *N);
219     SDValue visitSUB(SDNode *N);
220     SDValue visitADDC(SDNode *N);
221     SDValue visitSUBC(SDNode *N);
222     SDValue visitADDE(SDNode *N);
223     SDValue visitSUBE(SDNode *N);
224     SDValue visitMUL(SDNode *N);
225     SDValue visitSDIV(SDNode *N);
226     SDValue visitUDIV(SDNode *N);
227     SDValue visitSREM(SDNode *N);
228     SDValue visitUREM(SDNode *N);
229     SDValue visitMULHU(SDNode *N);
230     SDValue visitMULHS(SDNode *N);
231     SDValue visitSMUL_LOHI(SDNode *N);
232     SDValue visitUMUL_LOHI(SDNode *N);
233     SDValue visitSMULO(SDNode *N);
234     SDValue visitUMULO(SDNode *N);
235     SDValue visitSDIVREM(SDNode *N);
236     SDValue visitUDIVREM(SDNode *N);
237     SDValue visitAND(SDNode *N);
238     SDValue visitOR(SDNode *N);
239     SDValue visitXOR(SDNode *N);
240     SDValue SimplifyVBinOp(SDNode *N);
241     SDValue SimplifyVUnaryOp(SDNode *N);
242     SDValue visitSHL(SDNode *N);
243     SDValue visitSRA(SDNode *N);
244     SDValue visitSRL(SDNode *N);
245     SDValue visitRotate(SDNode *N);
246     SDValue visitCTLZ(SDNode *N);
247     SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
248     SDValue visitCTTZ(SDNode *N);
249     SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
250     SDValue visitCTPOP(SDNode *N);
251     SDValue visitSELECT(SDNode *N);
252     SDValue visitVSELECT(SDNode *N);
253     SDValue visitSELECT_CC(SDNode *N);
254     SDValue visitSETCC(SDNode *N);
255     SDValue visitSIGN_EXTEND(SDNode *N);
256     SDValue visitZERO_EXTEND(SDNode *N);
257     SDValue visitANY_EXTEND(SDNode *N);
258     SDValue visitSIGN_EXTEND_INREG(SDNode *N);
259     SDValue visitTRUNCATE(SDNode *N);
260     SDValue visitBITCAST(SDNode *N);
261     SDValue visitBUILD_PAIR(SDNode *N);
262     SDValue visitFADD(SDNode *N);
263     SDValue visitFSUB(SDNode *N);
264     SDValue visitFMUL(SDNode *N);
265     SDValue visitFMA(SDNode *N);
266     SDValue visitFDIV(SDNode *N);
267     SDValue visitFREM(SDNode *N);
268     SDValue visitFCOPYSIGN(SDNode *N);
269     SDValue visitSINT_TO_FP(SDNode *N);
270     SDValue visitUINT_TO_FP(SDNode *N);
271     SDValue visitFP_TO_SINT(SDNode *N);
272     SDValue visitFP_TO_UINT(SDNode *N);
273     SDValue visitFP_ROUND(SDNode *N);
274     SDValue visitFP_ROUND_INREG(SDNode *N);
275     SDValue visitFP_EXTEND(SDNode *N);
276     SDValue visitFNEG(SDNode *N);
277     SDValue visitFABS(SDNode *N);
278     SDValue visitFCEIL(SDNode *N);
279     SDValue visitFTRUNC(SDNode *N);
280     SDValue visitFFLOOR(SDNode *N);
281     SDValue visitBRCOND(SDNode *N);
282     SDValue visitBR_CC(SDNode *N);
283     SDValue visitLOAD(SDNode *N);
284     SDValue visitSTORE(SDNode *N);
285     SDValue visitINSERT_VECTOR_ELT(SDNode *N);
286     SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
287     SDValue visitBUILD_VECTOR(SDNode *N);
288     SDValue visitCONCAT_VECTORS(SDNode *N);
289     SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
290     SDValue visitVECTOR_SHUFFLE(SDNode *N);
291     SDValue visitINSERT_SUBVECTOR(SDNode *N);
292
293     SDValue XformToShuffleWithZero(SDNode *N);
294     SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS);
295
296     SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt);
297
298     bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
299     SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
300     SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2);
301     SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2,
302                              SDValue N3, ISD::CondCode CC,
303                              bool NotExtCompare = false);
304     SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
305                           SDLoc DL, bool foldBooleans = true);
306
307     bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
308                            SDValue &CC) const;
309     bool isOneUseSetCC(SDValue N) const;
310
311     SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
312                                          unsigned HiOp);
313     SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
314     SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
315     SDValue BuildSDIV(SDNode *N);
316     SDValue BuildSDIVPow2(SDNode *N);
317     SDValue BuildUDIV(SDNode *N);
318     SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
319                                bool DemandHighBits = true);
320     SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
321     SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
322                               SDValue InnerPos, SDValue InnerNeg,
323                               unsigned PosOpcode, unsigned NegOpcode,
324                               SDLoc DL);
325     SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL);
326     SDValue ReduceLoadWidth(SDNode *N);
327     SDValue ReduceLoadOpStoreWidth(SDNode *N);
328     SDValue TransformFPLoadStorePair(SDNode *N);
329     SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
330     SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
331
332     SDValue GetDemandedBits(SDValue V, const APInt &Mask);
333
334     /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
335     /// looking for aliasing nodes and adding them to the Aliases vector.
336     void GatherAllAliases(SDNode *N, SDValue OriginalChain,
337                           SmallVectorImpl<SDValue> &Aliases);
338
339     /// isAlias - Return true if there is any possibility that the two addresses
340     /// overlap.
341     bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const;
342
343     /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes,
344     /// looking for a better chain (aliasing node.)
345     SDValue FindBetterChain(SDNode *N, SDValue Chain);
346
347     /// Merge consecutive store operations into a wide store.
348     /// This optimization uses wide integers or vectors when possible.
349     /// \return True if some memory operations were changed.
350     bool MergeConsecutiveStores(StoreSDNode *N);
351
352     /// \brief Try to transform a truncation where C is a constant:
353     ///     (trunc (and X, C)) -> (and (trunc X), (trunc C))
354     ///
355     /// \p N needs to be a truncation and its first operand an AND. Other
356     /// requirements are checked by the function (e.g. that trunc is
357     /// single-use) and if missed an empty SDValue is returned.
358     SDValue distributeTruncateThroughAnd(SDNode *N);
359
360   public:
361     DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
362         : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
363           OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
364       AttributeSet FnAttrs =
365           DAG.getMachineFunction().getFunction()->getAttributes();
366       ForCodeSize =
367           FnAttrs.hasAttribute(AttributeSet::FunctionIndex,
368                                Attribute::OptimizeForSize) ||
369           FnAttrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::MinSize);
370     }
371
372     /// Run - runs the dag combiner on all nodes in the work list
373     void Run(CombineLevel AtLevel);
374
375     SelectionDAG &getDAG() const { return DAG; }
376
377     /// getShiftAmountTy - Returns a type large enough to hold any valid
378     /// shift amount - before type legalization these can be huge.
379     EVT getShiftAmountTy(EVT LHSTy) {
380       assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
381       if (LHSTy.isVector())
382         return LHSTy;
383       return LegalTypes ? TLI.getScalarShiftAmountTy(LHSTy)
384                         : TLI.getPointerTy();
385     }
386
387     /// isTypeLegal - This method returns true if we are running before type
388     /// legalization or if the specified VT is legal.
389     bool isTypeLegal(const EVT &VT) {
390       if (!LegalTypes) return true;
391       return TLI.isTypeLegal(VT);
392     }
393
394     /// getSetCCResultType - Convenience wrapper around
395     /// TargetLowering::getSetCCResultType
396     EVT getSetCCResultType(EVT VT) const {
397       return TLI.getSetCCResultType(*DAG.getContext(), VT);
398     }
399   };
400 }
401
402
403 namespace {
404 /// WorklistRemover - This class is a DAGUpdateListener that removes any deleted
405 /// nodes from the worklist.
406 class WorklistRemover : public SelectionDAG::DAGUpdateListener {
407   DAGCombiner &DC;
408 public:
409   explicit WorklistRemover(DAGCombiner &dc)
410     : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
411
412   void NodeDeleted(SDNode *N, SDNode *E) override {
413     DC.removeFromWorklist(N);
414   }
415 };
416 }
417
418 //===----------------------------------------------------------------------===//
419 //  TargetLowering::DAGCombinerInfo implementation
420 //===----------------------------------------------------------------------===//
421
422 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
423   ((DAGCombiner*)DC)->AddToWorklist(N);
424 }
425
426 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
427   ((DAGCombiner*)DC)->removeFromWorklist(N);
428 }
429
430 SDValue TargetLowering::DAGCombinerInfo::
431 CombineTo(SDNode *N, const std::vector<SDValue> &To, bool AddTo) {
432   return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
433 }
434
435 SDValue TargetLowering::DAGCombinerInfo::
436 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
437   return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
438 }
439
440
441 SDValue TargetLowering::DAGCombinerInfo::
442 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
443   return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
444 }
445
446 void TargetLowering::DAGCombinerInfo::
447 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
448   return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
449 }
450
451 //===----------------------------------------------------------------------===//
452 // Helper Functions
453 //===----------------------------------------------------------------------===//
454
455 void DAGCombiner::deleteAndRecombine(SDNode *N) {
456   removeFromWorklist(N);
457
458   // If the operands of this node are only used by the node, they will now be
459   // dead. Make sure to re-visit them and recursively delete dead nodes.
460   for (const SDValue &Op : N->ops())
461     if (Op->hasOneUse())
462       AddToWorklist(Op.getNode());
463
464   DAG.DeleteNode(N);
465 }
466
467 /// isNegatibleForFree - Return 1 if we can compute the negated form of the
468 /// specified expression for the same cost as the expression itself, or 2 if we
469 /// can compute the negated form more cheaply than the expression itself.
470 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
471                                const TargetLowering &TLI,
472                                const TargetOptions *Options,
473                                unsigned Depth = 0) {
474   // fneg is removable even if it has multiple uses.
475   if (Op.getOpcode() == ISD::FNEG) return 2;
476
477   // Don't allow anything with multiple uses.
478   if (!Op.hasOneUse()) return 0;
479
480   // Don't recurse exponentially.
481   if (Depth > 6) return 0;
482
483   switch (Op.getOpcode()) {
484   default: return false;
485   case ISD::ConstantFP:
486     // Don't invert constant FP values after legalize.  The negated constant
487     // isn't necessarily legal.
488     return LegalOperations ? 0 : 1;
489   case ISD::FADD:
490     // FIXME: determine better conditions for this xform.
491     if (!Options->UnsafeFPMath) return 0;
492
493     // After operation legalization, it might not be legal to create new FSUBs.
494     if (LegalOperations &&
495         !TLI.isOperationLegalOrCustom(ISD::FSUB,  Op.getValueType()))
496       return 0;
497
498     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
499     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
500                                     Options, Depth + 1))
501       return V;
502     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
503     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
504                               Depth + 1);
505   case ISD::FSUB:
506     // We can't turn -(A-B) into B-A when we honor signed zeros.
507     if (!Options->UnsafeFPMath) return 0;
508
509     // fold (fneg (fsub A, B)) -> (fsub B, A)
510     return 1;
511
512   case ISD::FMUL:
513   case ISD::FDIV:
514     if (Options->HonorSignDependentRoundingFPMath()) return 0;
515
516     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
517     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
518                                     Options, Depth + 1))
519       return V;
520
521     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
522                               Depth + 1);
523
524   case ISD::FP_EXTEND:
525   case ISD::FP_ROUND:
526   case ISD::FSIN:
527     return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
528                               Depth + 1);
529   }
530 }
531
532 /// GetNegatedExpression - If isNegatibleForFree returns true, this function
533 /// returns the newly negated expression.
534 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
535                                     bool LegalOperations, unsigned Depth = 0) {
536   // fneg is removable even if it has multiple uses.
537   if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
538
539   // Don't allow anything with multiple uses.
540   assert(Op.hasOneUse() && "Unknown reuse!");
541
542   assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
543   switch (Op.getOpcode()) {
544   default: llvm_unreachable("Unknown code");
545   case ISD::ConstantFP: {
546     APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
547     V.changeSign();
548     return DAG.getConstantFP(V, Op.getValueType());
549   }
550   case ISD::FADD:
551     // FIXME: determine better conditions for this xform.
552     assert(DAG.getTarget().Options.UnsafeFPMath);
553
554     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
555     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
556                            DAG.getTargetLoweringInfo(),
557                            &DAG.getTarget().Options, Depth+1))
558       return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
559                          GetNegatedExpression(Op.getOperand(0), DAG,
560                                               LegalOperations, Depth+1),
561                          Op.getOperand(1));
562     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
563     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
564                        GetNegatedExpression(Op.getOperand(1), DAG,
565                                             LegalOperations, Depth+1),
566                        Op.getOperand(0));
567   case ISD::FSUB:
568     // We can't turn -(A-B) into B-A when we honor signed zeros.
569     assert(DAG.getTarget().Options.UnsafeFPMath);
570
571     // fold (fneg (fsub 0, B)) -> B
572     if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
573       if (N0CFP->getValueAPF().isZero())
574         return Op.getOperand(1);
575
576     // fold (fneg (fsub A, B)) -> (fsub B, A)
577     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
578                        Op.getOperand(1), Op.getOperand(0));
579
580   case ISD::FMUL:
581   case ISD::FDIV:
582     assert(!DAG.getTarget().Options.HonorSignDependentRoundingFPMath());
583
584     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
585     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
586                            DAG.getTargetLoweringInfo(),
587                            &DAG.getTarget().Options, Depth+1))
588       return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
589                          GetNegatedExpression(Op.getOperand(0), DAG,
590                                               LegalOperations, Depth+1),
591                          Op.getOperand(1));
592
593     // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
594     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
595                        Op.getOperand(0),
596                        GetNegatedExpression(Op.getOperand(1), DAG,
597                                             LegalOperations, Depth+1));
598
599   case ISD::FP_EXTEND:
600   case ISD::FSIN:
601     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
602                        GetNegatedExpression(Op.getOperand(0), DAG,
603                                             LegalOperations, Depth+1));
604   case ISD::FP_ROUND:
605       return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
606                          GetNegatedExpression(Op.getOperand(0), DAG,
607                                               LegalOperations, Depth+1),
608                          Op.getOperand(1));
609   }
610 }
611
612 // isSetCCEquivalent - Return true if this node is a setcc, or is a select_cc
613 // that selects between the target values used for true and false, making it
614 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
615 // the appropriate nodes based on the type of node we are checking. This
616 // simplifies life a bit for the callers.
617 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
618                                     SDValue &CC) const {
619   if (N.getOpcode() == ISD::SETCC) {
620     LHS = N.getOperand(0);
621     RHS = N.getOperand(1);
622     CC  = N.getOperand(2);
623     return true;
624   }
625
626   if (N.getOpcode() != ISD::SELECT_CC ||
627       !TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
628       !TLI.isConstFalseVal(N.getOperand(3).getNode()))
629     return false;
630
631   LHS = N.getOperand(0);
632   RHS = N.getOperand(1);
633   CC  = N.getOperand(4);
634   return true;
635 }
636
637 // isOneUseSetCC - Return true if this is a SetCC-equivalent operation with only
638 // one use.  If this is true, it allows the users to invert the operation for
639 // free when it is profitable to do so.
640 bool DAGCombiner::isOneUseSetCC(SDValue N) const {
641   SDValue N0, N1, N2;
642   if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
643     return true;
644   return false;
645 }
646
647 /// isConstantSplatVector - Returns true if N is a BUILD_VECTOR node whose
648 /// elements are all the same constant or undefined.
649 static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
650   BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
651   if (!C)
652     return false;
653
654   APInt SplatUndef;
655   unsigned SplatBitSize;
656   bool HasAnyUndefs;
657   EVT EltVT = N->getValueType(0).getVectorElementType();
658   return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
659                              HasAnyUndefs) &&
660           EltVT.getSizeInBits() >= SplatBitSize);
661 }
662
663 // \brief Returns the SDNode if it is a constant BuildVector or constant.
664 static SDNode *isConstantBuildVectorOrConstantInt(SDValue N) {
665   if (isa<ConstantSDNode>(N))
666     return N.getNode();
667   BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N);
668   if(BV && BV->isConstant())
669     return BV;
670   return nullptr;
671 }
672
673 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
674 // int.
675 static ConstantSDNode *isConstOrConstSplat(SDValue N) {
676   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
677     return CN;
678
679   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
680     BitVector UndefElements;
681     ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
682
683     // BuildVectors can truncate their operands. Ignore that case here.
684     // FIXME: We blindly ignore splats which include undef which is overly
685     // pessimistic.
686     if (CN && UndefElements.none() &&
687         CN->getValueType(0) == N.getValueType().getScalarType())
688       return CN;
689   }
690
691   return nullptr;
692 }
693
694 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
695                                     SDValue N0, SDValue N1) {
696   EVT VT = N0.getValueType();
697   if (N0.getOpcode() == Opc) {
698     if (SDNode *L = isConstantBuildVectorOrConstantInt(N0.getOperand(1))) {
699       if (SDNode *R = isConstantBuildVectorOrConstantInt(N1)) {
700         // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
701         SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, L, R);
702         if (!OpNode.getNode())
703           return SDValue();
704         return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
705       }
706       if (N0.hasOneUse()) {
707         // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
708         // use
709         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
710         if (!OpNode.getNode())
711           return SDValue();
712         AddToWorklist(OpNode.getNode());
713         return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
714       }
715     }
716   }
717
718   if (N1.getOpcode() == Opc) {
719     if (SDNode *R = isConstantBuildVectorOrConstantInt(N1.getOperand(1))) {
720       if (SDNode *L = isConstantBuildVectorOrConstantInt(N0)) {
721         // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
722         SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, R, L);
723         if (!OpNode.getNode())
724           return SDValue();
725         return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
726       }
727       if (N1.hasOneUse()) {
728         // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one
729         // use
730         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0);
731         if (!OpNode.getNode())
732           return SDValue();
733         AddToWorklist(OpNode.getNode());
734         return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
735       }
736     }
737   }
738
739   return SDValue();
740 }
741
742 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
743                                bool AddTo) {
744   assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
745   ++NodesCombined;
746   DEBUG(dbgs() << "\nReplacing.1 ";
747         N->dump(&DAG);
748         dbgs() << "\nWith: ";
749         To[0].getNode()->dump(&DAG);
750         dbgs() << " and " << NumTo-1 << " other values\n";
751         for (unsigned i = 0, e = NumTo; i != e; ++i)
752           assert((!To[i].getNode() ||
753                   N->getValueType(i) == To[i].getValueType()) &&
754                  "Cannot combine value to value of different type!"));
755   WorklistRemover DeadNodes(*this);
756   DAG.ReplaceAllUsesWith(N, To);
757   if (AddTo) {
758     // Push the new nodes and any users onto the worklist
759     for (unsigned i = 0, e = NumTo; i != e; ++i) {
760       if (To[i].getNode()) {
761         AddToWorklist(To[i].getNode());
762         AddUsersToWorklist(To[i].getNode());
763       }
764     }
765   }
766
767   // Finally, if the node is now dead, remove it from the graph.  The node
768   // may not be dead if the replacement process recursively simplified to
769   // something else needing this node.
770   if (N->use_empty())
771     deleteAndRecombine(N);
772   return SDValue(N, 0);
773 }
774
775 void DAGCombiner::
776 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
777   // Replace all uses.  If any nodes become isomorphic to other nodes and
778   // are deleted, make sure to remove them from our worklist.
779   WorklistRemover DeadNodes(*this);
780   DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
781
782   // Push the new node and any (possibly new) users onto the worklist.
783   AddToWorklist(TLO.New.getNode());
784   AddUsersToWorklist(TLO.New.getNode());
785
786   // Finally, if the node is now dead, remove it from the graph.  The node
787   // may not be dead if the replacement process recursively simplified to
788   // something else needing this node.
789   if (TLO.Old.getNode()->use_empty())
790     deleteAndRecombine(TLO.Old.getNode());
791 }
792
793 /// SimplifyDemandedBits - Check the specified integer node value to see if
794 /// it can be simplified or if things it uses can be simplified by bit
795 /// propagation.  If so, return true.
796 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
797   TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
798   APInt KnownZero, KnownOne;
799   if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
800     return false;
801
802   // Revisit the node.
803   AddToWorklist(Op.getNode());
804
805   // Replace the old value with the new one.
806   ++NodesCombined;
807   DEBUG(dbgs() << "\nReplacing.2 ";
808         TLO.Old.getNode()->dump(&DAG);
809         dbgs() << "\nWith: ";
810         TLO.New.getNode()->dump(&DAG);
811         dbgs() << '\n');
812
813   CommitTargetLoweringOpt(TLO);
814   return true;
815 }
816
817 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
818   SDLoc dl(Load);
819   EVT VT = Load->getValueType(0);
820   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
821
822   DEBUG(dbgs() << "\nReplacing.9 ";
823         Load->dump(&DAG);
824         dbgs() << "\nWith: ";
825         Trunc.getNode()->dump(&DAG);
826         dbgs() << '\n');
827   WorklistRemover DeadNodes(*this);
828   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
829   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
830   deleteAndRecombine(Load);
831   AddToWorklist(Trunc.getNode());
832 }
833
834 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
835   Replace = false;
836   SDLoc dl(Op);
837   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
838     EVT MemVT = LD->getMemoryVT();
839     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
840       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
841                                                   : ISD::EXTLOAD)
842       : LD->getExtensionType();
843     Replace = true;
844     return DAG.getExtLoad(ExtType, dl, PVT,
845                           LD->getChain(), LD->getBasePtr(),
846                           MemVT, LD->getMemOperand());
847   }
848
849   unsigned Opc = Op.getOpcode();
850   switch (Opc) {
851   default: break;
852   case ISD::AssertSext:
853     return DAG.getNode(ISD::AssertSext, dl, PVT,
854                        SExtPromoteOperand(Op.getOperand(0), PVT),
855                        Op.getOperand(1));
856   case ISD::AssertZext:
857     return DAG.getNode(ISD::AssertZext, dl, PVT,
858                        ZExtPromoteOperand(Op.getOperand(0), PVT),
859                        Op.getOperand(1));
860   case ISD::Constant: {
861     unsigned ExtOpc =
862       Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
863     return DAG.getNode(ExtOpc, dl, PVT, Op);
864   }
865   }
866
867   if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
868     return SDValue();
869   return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
870 }
871
872 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
873   if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
874     return SDValue();
875   EVT OldVT = Op.getValueType();
876   SDLoc dl(Op);
877   bool Replace = false;
878   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
879   if (!NewOp.getNode())
880     return SDValue();
881   AddToWorklist(NewOp.getNode());
882
883   if (Replace)
884     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
885   return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
886                      DAG.getValueType(OldVT));
887 }
888
889 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
890   EVT OldVT = Op.getValueType();
891   SDLoc dl(Op);
892   bool Replace = false;
893   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
894   if (!NewOp.getNode())
895     return SDValue();
896   AddToWorklist(NewOp.getNode());
897
898   if (Replace)
899     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
900   return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
901 }
902
903 /// PromoteIntBinOp - Promote the specified integer binary operation if the
904 /// target indicates it is beneficial. e.g. On x86, it's usually better to
905 /// promote i16 operations to i32 since i16 instructions are longer.
906 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
907   if (!LegalOperations)
908     return SDValue();
909
910   EVT VT = Op.getValueType();
911   if (VT.isVector() || !VT.isInteger())
912     return SDValue();
913
914   // If operation type is 'undesirable', e.g. i16 on x86, consider
915   // promoting it.
916   unsigned Opc = Op.getOpcode();
917   if (TLI.isTypeDesirableForOp(Opc, VT))
918     return SDValue();
919
920   EVT PVT = VT;
921   // Consult target whether it is a good idea to promote this operation and
922   // what's the right type to promote it to.
923   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
924     assert(PVT != VT && "Don't know what type to promote to!");
925
926     bool Replace0 = false;
927     SDValue N0 = Op.getOperand(0);
928     SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
929     if (!NN0.getNode())
930       return SDValue();
931
932     bool Replace1 = false;
933     SDValue N1 = Op.getOperand(1);
934     SDValue NN1;
935     if (N0 == N1)
936       NN1 = NN0;
937     else {
938       NN1 = PromoteOperand(N1, PVT, Replace1);
939       if (!NN1.getNode())
940         return SDValue();
941     }
942
943     AddToWorklist(NN0.getNode());
944     if (NN1.getNode())
945       AddToWorklist(NN1.getNode());
946
947     if (Replace0)
948       ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
949     if (Replace1)
950       ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
951
952     DEBUG(dbgs() << "\nPromoting ";
953           Op.getNode()->dump(&DAG));
954     SDLoc dl(Op);
955     return DAG.getNode(ISD::TRUNCATE, dl, VT,
956                        DAG.getNode(Opc, dl, PVT, NN0, NN1));
957   }
958   return SDValue();
959 }
960
961 /// PromoteIntShiftOp - Promote the specified integer shift operation if the
962 /// target indicates it is beneficial. e.g. On x86, it's usually better to
963 /// promote i16 operations to i32 since i16 instructions are longer.
964 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
965   if (!LegalOperations)
966     return SDValue();
967
968   EVT VT = Op.getValueType();
969   if (VT.isVector() || !VT.isInteger())
970     return SDValue();
971
972   // If operation type is 'undesirable', e.g. i16 on x86, consider
973   // promoting it.
974   unsigned Opc = Op.getOpcode();
975   if (TLI.isTypeDesirableForOp(Opc, VT))
976     return SDValue();
977
978   EVT PVT = VT;
979   // Consult target whether it is a good idea to promote this operation and
980   // what's the right type to promote it to.
981   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
982     assert(PVT != VT && "Don't know what type to promote to!");
983
984     bool Replace = false;
985     SDValue N0 = Op.getOperand(0);
986     if (Opc == ISD::SRA)
987       N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
988     else if (Opc == ISD::SRL)
989       N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
990     else
991       N0 = PromoteOperand(N0, PVT, Replace);
992     if (!N0.getNode())
993       return SDValue();
994
995     AddToWorklist(N0.getNode());
996     if (Replace)
997       ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
998
999     DEBUG(dbgs() << "\nPromoting ";
1000           Op.getNode()->dump(&DAG));
1001     SDLoc dl(Op);
1002     return DAG.getNode(ISD::TRUNCATE, dl, VT,
1003                        DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
1004   }
1005   return SDValue();
1006 }
1007
1008 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
1009   if (!LegalOperations)
1010     return SDValue();
1011
1012   EVT VT = Op.getValueType();
1013   if (VT.isVector() || !VT.isInteger())
1014     return SDValue();
1015
1016   // If operation type is 'undesirable', e.g. i16 on x86, consider
1017   // promoting it.
1018   unsigned Opc = Op.getOpcode();
1019   if (TLI.isTypeDesirableForOp(Opc, VT))
1020     return SDValue();
1021
1022   EVT PVT = VT;
1023   // Consult target whether it is a good idea to promote this operation and
1024   // what's the right type to promote it to.
1025   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1026     assert(PVT != VT && "Don't know what type to promote to!");
1027     // fold (aext (aext x)) -> (aext x)
1028     // fold (aext (zext x)) -> (zext x)
1029     // fold (aext (sext x)) -> (sext x)
1030     DEBUG(dbgs() << "\nPromoting ";
1031           Op.getNode()->dump(&DAG));
1032     return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1033   }
1034   return SDValue();
1035 }
1036
1037 bool DAGCombiner::PromoteLoad(SDValue Op) {
1038   if (!LegalOperations)
1039     return false;
1040
1041   EVT VT = Op.getValueType();
1042   if (VT.isVector() || !VT.isInteger())
1043     return false;
1044
1045   // If operation type is 'undesirable', e.g. i16 on x86, consider
1046   // promoting it.
1047   unsigned Opc = Op.getOpcode();
1048   if (TLI.isTypeDesirableForOp(Opc, VT))
1049     return false;
1050
1051   EVT PVT = VT;
1052   // Consult target whether it is a good idea to promote this operation and
1053   // what's the right type to promote it to.
1054   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1055     assert(PVT != VT && "Don't know what type to promote to!");
1056
1057     SDLoc dl(Op);
1058     SDNode *N = Op.getNode();
1059     LoadSDNode *LD = cast<LoadSDNode>(N);
1060     EVT MemVT = LD->getMemoryVT();
1061     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1062       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
1063                                                   : ISD::EXTLOAD)
1064       : LD->getExtensionType();
1065     SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
1066                                    LD->getChain(), LD->getBasePtr(),
1067                                    MemVT, LD->getMemOperand());
1068     SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
1069
1070     DEBUG(dbgs() << "\nPromoting ";
1071           N->dump(&DAG);
1072           dbgs() << "\nTo: ";
1073           Result.getNode()->dump(&DAG);
1074           dbgs() << '\n');
1075     WorklistRemover DeadNodes(*this);
1076     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1077     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1078     deleteAndRecombine(N);
1079     AddToWorklist(Result.getNode());
1080     return true;
1081   }
1082   return false;
1083 }
1084
1085 /// \brief Recursively delete a node which has no uses and any operands for
1086 /// which it is the only use.
1087 ///
1088 /// Note that this both deletes the nodes and removes them from the worklist.
1089 /// It also adds any nodes who have had a user deleted to the worklist as they
1090 /// may now have only one use and subject to other combines.
1091 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) {
1092   if (!N->use_empty())
1093     return false;
1094
1095   SmallSetVector<SDNode *, 16> Nodes;
1096   Nodes.insert(N);
1097   do {
1098     N = Nodes.pop_back_val();
1099     if (!N)
1100       continue;
1101
1102     if (N->use_empty()) {
1103       for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1104         Nodes.insert(N->getOperand(i).getNode());
1105
1106       removeFromWorklist(N);
1107       DAG.DeleteNode(N);
1108     } else {
1109       AddToWorklist(N);
1110     }
1111   } while (!Nodes.empty());
1112   return true;
1113 }
1114
1115 //===----------------------------------------------------------------------===//
1116 //  Main DAG Combiner implementation
1117 //===----------------------------------------------------------------------===//
1118
1119 void DAGCombiner::Run(CombineLevel AtLevel) {
1120   // set the instance variables, so that the various visit routines may use it.
1121   Level = AtLevel;
1122   LegalOperations = Level >= AfterLegalizeVectorOps;
1123   LegalTypes = Level >= AfterLegalizeTypes;
1124
1125   // Add all the dag nodes to the worklist.
1126   for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
1127        E = DAG.allnodes_end(); I != E; ++I)
1128     AddToWorklist(I);
1129
1130   // Create a dummy node (which is not added to allnodes), that adds a reference
1131   // to the root node, preventing it from being deleted, and tracking any
1132   // changes of the root.
1133   HandleSDNode Dummy(DAG.getRoot());
1134
1135   // while the worklist isn't empty, find a node and
1136   // try and combine it.
1137   while (!WorklistMap.empty()) {
1138     SDNode *N;
1139     // The Worklist holds the SDNodes in order, but it may contain null entries.
1140     do {
1141       N = Worklist.pop_back_val();
1142     } while (!N);
1143
1144     bool GoodWorklistEntry = WorklistMap.erase(N);
1145     (void)GoodWorklistEntry;
1146     assert(GoodWorklistEntry &&
1147            "Found a worklist entry without a corresponding map entry!");
1148
1149     // If N has no uses, it is dead.  Make sure to revisit all N's operands once
1150     // N is deleted from the DAG, since they too may now be dead or may have a
1151     // reduced number of uses, allowing other xforms.
1152     if (recursivelyDeleteUnusedNodes(N))
1153       continue;
1154
1155     WorklistRemover DeadNodes(*this);
1156
1157     // If this combine is running after legalizing the DAG, re-legalize any
1158     // nodes pulled off the worklist.
1159     if (Level == AfterLegalizeDAG) {
1160       SmallSetVector<SDNode *, 16> UpdatedNodes;
1161       bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes);
1162
1163       for (SDNode *LN : UpdatedNodes) {
1164         AddToWorklist(LN);
1165         AddUsersToWorklist(LN);
1166       }
1167       if (!NIsValid)
1168         continue;
1169     }
1170
1171     DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG));
1172
1173     // Add any operands of the new node which have not yet been combined to the
1174     // worklist as well. Because the worklist uniques things already, this
1175     // won't repeatedly process the same operand.
1176     CombinedNodes.insert(N);
1177     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1178       if (!CombinedNodes.count(N->getOperand(i).getNode()))
1179         AddToWorklist(N->getOperand(i).getNode());
1180
1181     SDValue RV = combine(N);
1182
1183     if (!RV.getNode())
1184       continue;
1185
1186     ++NodesCombined;
1187
1188     // If we get back the same node we passed in, rather than a new node or
1189     // zero, we know that the node must have defined multiple values and
1190     // CombineTo was used.  Since CombineTo takes care of the worklist
1191     // mechanics for us, we have no work to do in this case.
1192     if (RV.getNode() == N)
1193       continue;
1194
1195     assert(N->getOpcode() != ISD::DELETED_NODE &&
1196            RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1197            "Node was deleted but visit returned new node!");
1198
1199     DEBUG(dbgs() << " ... into: ";
1200           RV.getNode()->dump(&DAG));
1201
1202     // Transfer debug value.
1203     DAG.TransferDbgValues(SDValue(N, 0), RV);
1204     if (N->getNumValues() == RV.getNode()->getNumValues())
1205       DAG.ReplaceAllUsesWith(N, RV.getNode());
1206     else {
1207       assert(N->getValueType(0) == RV.getValueType() &&
1208              N->getNumValues() == 1 && "Type mismatch");
1209       SDValue OpV = RV;
1210       DAG.ReplaceAllUsesWith(N, &OpV);
1211     }
1212
1213     // Push the new node and any users onto the worklist
1214     AddToWorklist(RV.getNode());
1215     AddUsersToWorklist(RV.getNode());
1216
1217     // Finally, if the node is now dead, remove it from the graph.  The node
1218     // may not be dead if the replacement process recursively simplified to
1219     // something else needing this node. This will also take care of adding any
1220     // operands which have lost a user to the worklist.
1221     recursivelyDeleteUnusedNodes(N);
1222   }
1223
1224   // If the root changed (e.g. it was a dead load, update the root).
1225   DAG.setRoot(Dummy.getValue());
1226   DAG.RemoveDeadNodes();
1227 }
1228
1229 SDValue DAGCombiner::visit(SDNode *N) {
1230   switch (N->getOpcode()) {
1231   default: break;
1232   case ISD::TokenFactor:        return visitTokenFactor(N);
1233   case ISD::MERGE_VALUES:       return visitMERGE_VALUES(N);
1234   case ISD::ADD:                return visitADD(N);
1235   case ISD::SUB:                return visitSUB(N);
1236   case ISD::ADDC:               return visitADDC(N);
1237   case ISD::SUBC:               return visitSUBC(N);
1238   case ISD::ADDE:               return visitADDE(N);
1239   case ISD::SUBE:               return visitSUBE(N);
1240   case ISD::MUL:                return visitMUL(N);
1241   case ISD::SDIV:               return visitSDIV(N);
1242   case ISD::UDIV:               return visitUDIV(N);
1243   case ISD::SREM:               return visitSREM(N);
1244   case ISD::UREM:               return visitUREM(N);
1245   case ISD::MULHU:              return visitMULHU(N);
1246   case ISD::MULHS:              return visitMULHS(N);
1247   case ISD::SMUL_LOHI:          return visitSMUL_LOHI(N);
1248   case ISD::UMUL_LOHI:          return visitUMUL_LOHI(N);
1249   case ISD::SMULO:              return visitSMULO(N);
1250   case ISD::UMULO:              return visitUMULO(N);
1251   case ISD::SDIVREM:            return visitSDIVREM(N);
1252   case ISD::UDIVREM:            return visitUDIVREM(N);
1253   case ISD::AND:                return visitAND(N);
1254   case ISD::OR:                 return visitOR(N);
1255   case ISD::XOR:                return visitXOR(N);
1256   case ISD::SHL:                return visitSHL(N);
1257   case ISD::SRA:                return visitSRA(N);
1258   case ISD::SRL:                return visitSRL(N);
1259   case ISD::ROTR:
1260   case ISD::ROTL:               return visitRotate(N);
1261   case ISD::CTLZ:               return visitCTLZ(N);
1262   case ISD::CTLZ_ZERO_UNDEF:    return visitCTLZ_ZERO_UNDEF(N);
1263   case ISD::CTTZ:               return visitCTTZ(N);
1264   case ISD::CTTZ_ZERO_UNDEF:    return visitCTTZ_ZERO_UNDEF(N);
1265   case ISD::CTPOP:              return visitCTPOP(N);
1266   case ISD::SELECT:             return visitSELECT(N);
1267   case ISD::VSELECT:            return visitVSELECT(N);
1268   case ISD::SELECT_CC:          return visitSELECT_CC(N);
1269   case ISD::SETCC:              return visitSETCC(N);
1270   case ISD::SIGN_EXTEND:        return visitSIGN_EXTEND(N);
1271   case ISD::ZERO_EXTEND:        return visitZERO_EXTEND(N);
1272   case ISD::ANY_EXTEND:         return visitANY_EXTEND(N);
1273   case ISD::SIGN_EXTEND_INREG:  return visitSIGN_EXTEND_INREG(N);
1274   case ISD::TRUNCATE:           return visitTRUNCATE(N);
1275   case ISD::BITCAST:            return visitBITCAST(N);
1276   case ISD::BUILD_PAIR:         return visitBUILD_PAIR(N);
1277   case ISD::FADD:               return visitFADD(N);
1278   case ISD::FSUB:               return visitFSUB(N);
1279   case ISD::FMUL:               return visitFMUL(N);
1280   case ISD::FMA:                return visitFMA(N);
1281   case ISD::FDIV:               return visitFDIV(N);
1282   case ISD::FREM:               return visitFREM(N);
1283   case ISD::FCOPYSIGN:          return visitFCOPYSIGN(N);
1284   case ISD::SINT_TO_FP:         return visitSINT_TO_FP(N);
1285   case ISD::UINT_TO_FP:         return visitUINT_TO_FP(N);
1286   case ISD::FP_TO_SINT:         return visitFP_TO_SINT(N);
1287   case ISD::FP_TO_UINT:         return visitFP_TO_UINT(N);
1288   case ISD::FP_ROUND:           return visitFP_ROUND(N);
1289   case ISD::FP_ROUND_INREG:     return visitFP_ROUND_INREG(N);
1290   case ISD::FP_EXTEND:          return visitFP_EXTEND(N);
1291   case ISD::FNEG:               return visitFNEG(N);
1292   case ISD::FABS:               return visitFABS(N);
1293   case ISD::FFLOOR:             return visitFFLOOR(N);
1294   case ISD::FCEIL:              return visitFCEIL(N);
1295   case ISD::FTRUNC:             return visitFTRUNC(N);
1296   case ISD::BRCOND:             return visitBRCOND(N);
1297   case ISD::BR_CC:              return visitBR_CC(N);
1298   case ISD::LOAD:               return visitLOAD(N);
1299   case ISD::STORE:              return visitSTORE(N);
1300   case ISD::INSERT_VECTOR_ELT:  return visitINSERT_VECTOR_ELT(N);
1301   case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1302   case ISD::BUILD_VECTOR:       return visitBUILD_VECTOR(N);
1303   case ISD::CONCAT_VECTORS:     return visitCONCAT_VECTORS(N);
1304   case ISD::EXTRACT_SUBVECTOR:  return visitEXTRACT_SUBVECTOR(N);
1305   case ISD::VECTOR_SHUFFLE:     return visitVECTOR_SHUFFLE(N);
1306   case ISD::INSERT_SUBVECTOR:   return visitINSERT_SUBVECTOR(N);
1307   }
1308   return SDValue();
1309 }
1310
1311 SDValue DAGCombiner::combine(SDNode *N) {
1312   SDValue RV = visit(N);
1313
1314   // If nothing happened, try a target-specific DAG combine.
1315   if (!RV.getNode()) {
1316     assert(N->getOpcode() != ISD::DELETED_NODE &&
1317            "Node was deleted but visit returned NULL!");
1318
1319     if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1320         TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1321
1322       // Expose the DAG combiner to the target combiner impls.
1323       TargetLowering::DAGCombinerInfo
1324         DagCombineInfo(DAG, Level, false, this);
1325
1326       RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1327     }
1328   }
1329
1330   // If nothing happened still, try promoting the operation.
1331   if (!RV.getNode()) {
1332     switch (N->getOpcode()) {
1333     default: break;
1334     case ISD::ADD:
1335     case ISD::SUB:
1336     case ISD::MUL:
1337     case ISD::AND:
1338     case ISD::OR:
1339     case ISD::XOR:
1340       RV = PromoteIntBinOp(SDValue(N, 0));
1341       break;
1342     case ISD::SHL:
1343     case ISD::SRA:
1344     case ISD::SRL:
1345       RV = PromoteIntShiftOp(SDValue(N, 0));
1346       break;
1347     case ISD::SIGN_EXTEND:
1348     case ISD::ZERO_EXTEND:
1349     case ISD::ANY_EXTEND:
1350       RV = PromoteExtend(SDValue(N, 0));
1351       break;
1352     case ISD::LOAD:
1353       if (PromoteLoad(SDValue(N, 0)))
1354         RV = SDValue(N, 0);
1355       break;
1356     }
1357   }
1358
1359   // If N is a commutative binary node, try commuting it to enable more
1360   // sdisel CSE.
1361   if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1362       N->getNumValues() == 1) {
1363     SDValue N0 = N->getOperand(0);
1364     SDValue N1 = N->getOperand(1);
1365
1366     // Constant operands are canonicalized to RHS.
1367     if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1368       SDValue Ops[] = {N1, N0};
1369       SDNode *CSENode;
1370       if (const BinaryWithFlagsSDNode *BinNode =
1371               dyn_cast<BinaryWithFlagsSDNode>(N)) {
1372         CSENode = DAG.getNodeIfExists(
1373             N->getOpcode(), N->getVTList(), Ops, BinNode->hasNoUnsignedWrap(),
1374             BinNode->hasNoSignedWrap(), BinNode->isExact());
1375       } else {
1376         CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops);
1377       }
1378       if (CSENode)
1379         return SDValue(CSENode, 0);
1380     }
1381   }
1382
1383   return RV;
1384 }
1385
1386 /// getInputChainForNode - Given a node, return its input chain if it has one,
1387 /// otherwise return a null sd operand.
1388 static SDValue getInputChainForNode(SDNode *N) {
1389   if (unsigned NumOps = N->getNumOperands()) {
1390     if (N->getOperand(0).getValueType() == MVT::Other)
1391       return N->getOperand(0);
1392     if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1393       return N->getOperand(NumOps-1);
1394     for (unsigned i = 1; i < NumOps-1; ++i)
1395       if (N->getOperand(i).getValueType() == MVT::Other)
1396         return N->getOperand(i);
1397   }
1398   return SDValue();
1399 }
1400
1401 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1402   // If N has two operands, where one has an input chain equal to the other,
1403   // the 'other' chain is redundant.
1404   if (N->getNumOperands() == 2) {
1405     if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1406       return N->getOperand(0);
1407     if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1408       return N->getOperand(1);
1409   }
1410
1411   SmallVector<SDNode *, 8> TFs;     // List of token factors to visit.
1412   SmallVector<SDValue, 8> Ops;    // Ops for replacing token factor.
1413   SmallPtrSet<SDNode*, 16> SeenOps;
1414   bool Changed = false;             // If we should replace this token factor.
1415
1416   // Start out with this token factor.
1417   TFs.push_back(N);
1418
1419   // Iterate through token factors.  The TFs grows when new token factors are
1420   // encountered.
1421   for (unsigned i = 0; i < TFs.size(); ++i) {
1422     SDNode *TF = TFs[i];
1423
1424     // Check each of the operands.
1425     for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
1426       SDValue Op = TF->getOperand(i);
1427
1428       switch (Op.getOpcode()) {
1429       case ISD::EntryToken:
1430         // Entry tokens don't need to be added to the list. They are
1431         // rededundant.
1432         Changed = true;
1433         break;
1434
1435       case ISD::TokenFactor:
1436         if (Op.hasOneUse() &&
1437             std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1438           // Queue up for processing.
1439           TFs.push_back(Op.getNode());
1440           // Clean up in case the token factor is removed.
1441           AddToWorklist(Op.getNode());
1442           Changed = true;
1443           break;
1444         }
1445         // Fall thru
1446
1447       default:
1448         // Only add if it isn't already in the list.
1449         if (SeenOps.insert(Op.getNode()))
1450           Ops.push_back(Op);
1451         else
1452           Changed = true;
1453         break;
1454       }
1455     }
1456   }
1457
1458   SDValue Result;
1459
1460   // If we've change things around then replace token factor.
1461   if (Changed) {
1462     if (Ops.empty()) {
1463       // The entry token is the only possible outcome.
1464       Result = DAG.getEntryNode();
1465     } else {
1466       // New and improved token factor.
1467       Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
1468     }
1469
1470     // Don't add users to work list.
1471     return CombineTo(N, Result, false);
1472   }
1473
1474   return Result;
1475 }
1476
1477 /// MERGE_VALUES can always be eliminated.
1478 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1479   WorklistRemover DeadNodes(*this);
1480   // Replacing results may cause a different MERGE_VALUES to suddenly
1481   // be CSE'd with N, and carry its uses with it. Iterate until no
1482   // uses remain, to ensure that the node can be safely deleted.
1483   // First add the users of this node to the work list so that they
1484   // can be tried again once they have new operands.
1485   AddUsersToWorklist(N);
1486   do {
1487     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1488       DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1489   } while (!N->use_empty());
1490   deleteAndRecombine(N);
1491   return SDValue(N, 0);   // Return N so it doesn't get rechecked!
1492 }
1493
1494 static
1495 SDValue combineShlAddConstant(SDLoc DL, SDValue N0, SDValue N1,
1496                               SelectionDAG &DAG) {
1497   EVT VT = N0.getValueType();
1498   SDValue N00 = N0.getOperand(0);
1499   SDValue N01 = N0.getOperand(1);
1500   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N01);
1501
1502   if (N01C && N00.getOpcode() == ISD::ADD && N00.getNode()->hasOneUse() &&
1503       isa<ConstantSDNode>(N00.getOperand(1))) {
1504     // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1505     N0 = DAG.getNode(ISD::ADD, SDLoc(N0), VT,
1506                      DAG.getNode(ISD::SHL, SDLoc(N00), VT,
1507                                  N00.getOperand(0), N01),
1508                      DAG.getNode(ISD::SHL, SDLoc(N01), VT,
1509                                  N00.getOperand(1), N01));
1510     return DAG.getNode(ISD::ADD, DL, VT, N0, N1);
1511   }
1512
1513   return SDValue();
1514 }
1515
1516 SDValue DAGCombiner::visitADD(SDNode *N) {
1517   SDValue N0 = N->getOperand(0);
1518   SDValue N1 = N->getOperand(1);
1519   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1520   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1521   EVT VT = N0.getValueType();
1522
1523   // fold vector ops
1524   if (VT.isVector()) {
1525     SDValue FoldedVOp = SimplifyVBinOp(N);
1526     if (FoldedVOp.getNode()) return FoldedVOp;
1527
1528     // fold (add x, 0) -> x, vector edition
1529     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1530       return N0;
1531     if (ISD::isBuildVectorAllZeros(N0.getNode()))
1532       return N1;
1533   }
1534
1535   // fold (add x, undef) -> undef
1536   if (N0.getOpcode() == ISD::UNDEF)
1537     return N0;
1538   if (N1.getOpcode() == ISD::UNDEF)
1539     return N1;
1540   // fold (add c1, c2) -> c1+c2
1541   if (N0C && N1C)
1542     return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C);
1543   // canonicalize constant to RHS
1544   if (N0C && !N1C)
1545     return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
1546   // fold (add x, 0) -> x
1547   if (N1C && N1C->isNullValue())
1548     return N0;
1549   // fold (add Sym, c) -> Sym+c
1550   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1551     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1552         GA->getOpcode() == ISD::GlobalAddress)
1553       return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1554                                   GA->getOffset() +
1555                                     (uint64_t)N1C->getSExtValue());
1556   // fold ((c1-A)+c2) -> (c1+c2)-A
1557   if (N1C && N0.getOpcode() == ISD::SUB)
1558     if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
1559       return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1560                          DAG.getConstant(N1C->getAPIntValue()+
1561                                          N0C->getAPIntValue(), VT),
1562                          N0.getOperand(1));
1563   // reassociate add
1564   SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1);
1565   if (RADD.getNode())
1566     return RADD;
1567   // fold ((0-A) + B) -> B-A
1568   if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
1569       cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
1570     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
1571   // fold (A + (0-B)) -> A-B
1572   if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1573       cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
1574     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
1575   // fold (A+(B-A)) -> B
1576   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1577     return N1.getOperand(0);
1578   // fold ((B-A)+A) -> B
1579   if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1580     return N0.getOperand(0);
1581   // fold (A+(B-(A+C))) to (B-C)
1582   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1583       N0 == N1.getOperand(1).getOperand(0))
1584     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1585                        N1.getOperand(1).getOperand(1));
1586   // fold (A+(B-(C+A))) to (B-C)
1587   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1588       N0 == N1.getOperand(1).getOperand(1))
1589     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1590                        N1.getOperand(1).getOperand(0));
1591   // fold (A+((B-A)+or-C)) to (B+or-C)
1592   if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1593       N1.getOperand(0).getOpcode() == ISD::SUB &&
1594       N0 == N1.getOperand(0).getOperand(1))
1595     return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
1596                        N1.getOperand(0).getOperand(0), N1.getOperand(1));
1597
1598   // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1599   if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1600     SDValue N00 = N0.getOperand(0);
1601     SDValue N01 = N0.getOperand(1);
1602     SDValue N10 = N1.getOperand(0);
1603     SDValue N11 = N1.getOperand(1);
1604
1605     if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1606       return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1607                          DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1608                          DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1609   }
1610
1611   if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1612     return SDValue(N, 0);
1613
1614   // fold (a+b) -> (a|b) iff a and b share no bits.
1615   if (VT.isInteger() && !VT.isVector()) {
1616     APInt LHSZero, LHSOne;
1617     APInt RHSZero, RHSOne;
1618     DAG.computeKnownBits(N0, LHSZero, LHSOne);
1619
1620     if (LHSZero.getBoolValue()) {
1621       DAG.computeKnownBits(N1, RHSZero, RHSOne);
1622
1623       // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1624       // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1625       if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){
1626         if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT))
1627           return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1628       }
1629     }
1630   }
1631
1632   // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1633   if (N0.getOpcode() == ISD::SHL && N0.getNode()->hasOneUse()) {
1634     SDValue Result = combineShlAddConstant(SDLoc(N), N0, N1, DAG);
1635     if (Result.getNode()) return Result;
1636   }
1637   if (N1.getOpcode() == ISD::SHL && N1.getNode()->hasOneUse()) {
1638     SDValue Result = combineShlAddConstant(SDLoc(N), N1, N0, DAG);
1639     if (Result.getNode()) return Result;
1640   }
1641
1642   // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1643   if (N1.getOpcode() == ISD::SHL &&
1644       N1.getOperand(0).getOpcode() == ISD::SUB)
1645     if (ConstantSDNode *C =
1646           dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
1647       if (C->getAPIntValue() == 0)
1648         return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1649                            DAG.getNode(ISD::SHL, SDLoc(N), VT,
1650                                        N1.getOperand(0).getOperand(1),
1651                                        N1.getOperand(1)));
1652   if (N0.getOpcode() == ISD::SHL &&
1653       N0.getOperand(0).getOpcode() == ISD::SUB)
1654     if (ConstantSDNode *C =
1655           dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
1656       if (C->getAPIntValue() == 0)
1657         return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1658                            DAG.getNode(ISD::SHL, SDLoc(N), VT,
1659                                        N0.getOperand(0).getOperand(1),
1660                                        N0.getOperand(1)));
1661
1662   if (N1.getOpcode() == ISD::AND) {
1663     SDValue AndOp0 = N1.getOperand(0);
1664     ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1));
1665     unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1666     unsigned DestBits = VT.getScalarType().getSizeInBits();
1667
1668     // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1669     // and similar xforms where the inner op is either ~0 or 0.
1670     if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) {
1671       SDLoc DL(N);
1672       return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1673     }
1674   }
1675
1676   // add (sext i1), X -> sub X, (zext i1)
1677   if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1678       N0.getOperand(0).getValueType() == MVT::i1 &&
1679       !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1680     SDLoc DL(N);
1681     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1682     return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1683   }
1684
1685   return SDValue();
1686 }
1687
1688 SDValue DAGCombiner::visitADDC(SDNode *N) {
1689   SDValue N0 = N->getOperand(0);
1690   SDValue N1 = N->getOperand(1);
1691   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1692   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1693   EVT VT = N0.getValueType();
1694
1695   // If the flag result is dead, turn this into an ADD.
1696   if (!N->hasAnyUseOfValue(1))
1697     return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1698                      DAG.getNode(ISD::CARRY_FALSE,
1699                                  SDLoc(N), MVT::Glue));
1700
1701   // canonicalize constant to RHS.
1702   if (N0C && !N1C)
1703     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1704
1705   // fold (addc x, 0) -> x + no carry out
1706   if (N1C && N1C->isNullValue())
1707     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1708                                         SDLoc(N), MVT::Glue));
1709
1710   // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1711   APInt LHSZero, LHSOne;
1712   APInt RHSZero, RHSOne;
1713   DAG.computeKnownBits(N0, LHSZero, LHSOne);
1714
1715   if (LHSZero.getBoolValue()) {
1716     DAG.computeKnownBits(N1, RHSZero, RHSOne);
1717
1718     // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1719     // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1720     if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1721       return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1722                        DAG.getNode(ISD::CARRY_FALSE,
1723                                    SDLoc(N), MVT::Glue));
1724   }
1725
1726   return SDValue();
1727 }
1728
1729 SDValue DAGCombiner::visitADDE(SDNode *N) {
1730   SDValue N0 = N->getOperand(0);
1731   SDValue N1 = N->getOperand(1);
1732   SDValue CarryIn = N->getOperand(2);
1733   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1734   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1735
1736   // canonicalize constant to RHS
1737   if (N0C && !N1C)
1738     return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1739                        N1, N0, CarryIn);
1740
1741   // fold (adde x, y, false) -> (addc x, y)
1742   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1743     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1744
1745   return SDValue();
1746 }
1747
1748 // Since it may not be valid to emit a fold to zero for vector initializers
1749 // check if we can before folding.
1750 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
1751                              SelectionDAG &DAG,
1752                              bool LegalOperations, bool LegalTypes) {
1753   if (!VT.isVector())
1754     return DAG.getConstant(0, VT);
1755   if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1756     return DAG.getConstant(0, VT);
1757   return SDValue();
1758 }
1759
1760 SDValue DAGCombiner::visitSUB(SDNode *N) {
1761   SDValue N0 = N->getOperand(0);
1762   SDValue N1 = N->getOperand(1);
1763   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1764   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1765   ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr :
1766     dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1767   EVT VT = N0.getValueType();
1768
1769   // fold vector ops
1770   if (VT.isVector()) {
1771     SDValue FoldedVOp = SimplifyVBinOp(N);
1772     if (FoldedVOp.getNode()) return FoldedVOp;
1773
1774     // fold (sub x, 0) -> x, vector edition
1775     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1776       return N0;
1777   }
1778
1779   // fold (sub x, x) -> 0
1780   // FIXME: Refactor this and xor and other similar operations together.
1781   if (N0 == N1)
1782     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
1783   // fold (sub c1, c2) -> c1-c2
1784   if (N0C && N1C)
1785     return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C);
1786   // fold (sub x, c) -> (add x, -c)
1787   if (N1C)
1788     return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0,
1789                        DAG.getConstant(-N1C->getAPIntValue(), VT));
1790   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1791   if (N0C && N0C->isAllOnesValue())
1792     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
1793   // fold A-(A-B) -> B
1794   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1795     return N1.getOperand(1);
1796   // fold (A+B)-A -> B
1797   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1798     return N0.getOperand(1);
1799   // fold (A+B)-B -> A
1800   if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1801     return N0.getOperand(0);
1802   // fold C2-(A+C1) -> (C2-C1)-A
1803   if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1804     SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1805                                    VT);
1806     return DAG.getNode(ISD::SUB, SDLoc(N), VT, NewC,
1807                        N1.getOperand(0));
1808   }
1809   // fold ((A+(B+or-C))-B) -> A+or-C
1810   if (N0.getOpcode() == ISD::ADD &&
1811       (N0.getOperand(1).getOpcode() == ISD::SUB ||
1812        N0.getOperand(1).getOpcode() == ISD::ADD) &&
1813       N0.getOperand(1).getOperand(0) == N1)
1814     return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
1815                        N0.getOperand(0), N0.getOperand(1).getOperand(1));
1816   // fold ((A+(C+B))-B) -> A+C
1817   if (N0.getOpcode() == ISD::ADD &&
1818       N0.getOperand(1).getOpcode() == ISD::ADD &&
1819       N0.getOperand(1).getOperand(1) == N1)
1820     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1821                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1822   // fold ((A-(B-C))-C) -> A-B
1823   if (N0.getOpcode() == ISD::SUB &&
1824       N0.getOperand(1).getOpcode() == ISD::SUB &&
1825       N0.getOperand(1).getOperand(1) == N1)
1826     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1827                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1828
1829   // If either operand of a sub is undef, the result is undef
1830   if (N0.getOpcode() == ISD::UNDEF)
1831     return N0;
1832   if (N1.getOpcode() == ISD::UNDEF)
1833     return N1;
1834
1835   // If the relocation model supports it, consider symbol offsets.
1836   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1837     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1838       // fold (sub Sym, c) -> Sym-c
1839       if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1840         return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1841                                     GA->getOffset() -
1842                                       (uint64_t)N1C->getSExtValue());
1843       // fold (sub Sym+c1, Sym+c2) -> c1-c2
1844       if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1845         if (GA->getGlobal() == GB->getGlobal())
1846           return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1847                                  VT);
1848     }
1849
1850   return SDValue();
1851 }
1852
1853 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1854   SDValue N0 = N->getOperand(0);
1855   SDValue N1 = N->getOperand(1);
1856   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1857   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1858   EVT VT = N0.getValueType();
1859
1860   // If the flag result is dead, turn this into an SUB.
1861   if (!N->hasAnyUseOfValue(1))
1862     return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1863                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1864                                  MVT::Glue));
1865
1866   // fold (subc x, x) -> 0 + no borrow
1867   if (N0 == N1)
1868     return CombineTo(N, DAG.getConstant(0, VT),
1869                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1870                                  MVT::Glue));
1871
1872   // fold (subc x, 0) -> x + no borrow
1873   if (N1C && N1C->isNullValue())
1874     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1875                                         MVT::Glue));
1876
1877   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1878   if (N0C && N0C->isAllOnesValue())
1879     return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
1880                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1881                                  MVT::Glue));
1882
1883   return SDValue();
1884 }
1885
1886 SDValue DAGCombiner::visitSUBE(SDNode *N) {
1887   SDValue N0 = N->getOperand(0);
1888   SDValue N1 = N->getOperand(1);
1889   SDValue CarryIn = N->getOperand(2);
1890
1891   // fold (sube x, y, false) -> (subc x, y)
1892   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1893     return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
1894
1895   return SDValue();
1896 }
1897
1898 SDValue DAGCombiner::visitMUL(SDNode *N) {
1899   SDValue N0 = N->getOperand(0);
1900   SDValue N1 = N->getOperand(1);
1901   EVT VT = N0.getValueType();
1902
1903   // fold (mul x, undef) -> 0
1904   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1905     return DAG.getConstant(0, VT);
1906
1907   bool N0IsConst = false;
1908   bool N1IsConst = false;
1909   APInt ConstValue0, ConstValue1;
1910   // fold vector ops
1911   if (VT.isVector()) {
1912     SDValue FoldedVOp = SimplifyVBinOp(N);
1913     if (FoldedVOp.getNode()) return FoldedVOp;
1914
1915     N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
1916     N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
1917   } else {
1918     N0IsConst = dyn_cast<ConstantSDNode>(N0) != nullptr;
1919     ConstValue0 = N0IsConst ? (dyn_cast<ConstantSDNode>(N0))->getAPIntValue()
1920                             : APInt();
1921     N1IsConst = dyn_cast<ConstantSDNode>(N1) != nullptr;
1922     ConstValue1 = N1IsConst ? (dyn_cast<ConstantSDNode>(N1))->getAPIntValue()
1923                             : APInt();
1924   }
1925
1926   // fold (mul c1, c2) -> c1*c2
1927   if (N0IsConst && N1IsConst)
1928     return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0.getNode(), N1.getNode());
1929
1930   // canonicalize constant to RHS
1931   if (N0IsConst && !N1IsConst)
1932     return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
1933   // fold (mul x, 0) -> 0
1934   if (N1IsConst && ConstValue1 == 0)
1935     return N1;
1936   // We require a splat of the entire scalar bit width for non-contiguous
1937   // bit patterns.
1938   bool IsFullSplat =
1939     ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
1940   // fold (mul x, 1) -> x
1941   if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
1942     return N0;
1943   // fold (mul x, -1) -> 0-x
1944   if (N1IsConst && ConstValue1.isAllOnesValue())
1945     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1946                        DAG.getConstant(0, VT), N0);
1947   // fold (mul x, (1 << c)) -> x << c
1948   if (N1IsConst && ConstValue1.isPowerOf2() && IsFullSplat)
1949     return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1950                        DAG.getConstant(ConstValue1.logBase2(),
1951                                        getShiftAmountTy(N0.getValueType())));
1952   // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
1953   if (N1IsConst && (-ConstValue1).isPowerOf2() && IsFullSplat) {
1954     unsigned Log2Val = (-ConstValue1).logBase2();
1955     // FIXME: If the input is something that is easily negated (e.g. a
1956     // single-use add), we should put the negate there.
1957     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1958                        DAG.getConstant(0, VT),
1959                        DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1960                             DAG.getConstant(Log2Val,
1961                                       getShiftAmountTy(N0.getValueType()))));
1962   }
1963
1964   APInt Val;
1965   // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
1966   if (N1IsConst && N0.getOpcode() == ISD::SHL &&
1967       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1968                      isa<ConstantSDNode>(N0.getOperand(1)))) {
1969     SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
1970                              N1, N0.getOperand(1));
1971     AddToWorklist(C3.getNode());
1972     return DAG.getNode(ISD::MUL, SDLoc(N), VT,
1973                        N0.getOperand(0), C3);
1974   }
1975
1976   // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
1977   // use.
1978   {
1979     SDValue Sh(nullptr,0), Y(nullptr,0);
1980     // Check for both (mul (shl X, C), Y)  and  (mul Y, (shl X, C)).
1981     if (N0.getOpcode() == ISD::SHL &&
1982         (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1983                        isa<ConstantSDNode>(N0.getOperand(1))) &&
1984         N0.getNode()->hasOneUse()) {
1985       Sh = N0; Y = N1;
1986     } else if (N1.getOpcode() == ISD::SHL &&
1987                isa<ConstantSDNode>(N1.getOperand(1)) &&
1988                N1.getNode()->hasOneUse()) {
1989       Sh = N1; Y = N0;
1990     }
1991
1992     if (Sh.getNode()) {
1993       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
1994                                 Sh.getOperand(0), Y);
1995       return DAG.getNode(ISD::SHL, SDLoc(N), VT,
1996                          Mul, Sh.getOperand(1));
1997     }
1998   }
1999
2000   // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
2001   if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
2002       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2003                      isa<ConstantSDNode>(N0.getOperand(1))))
2004     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
2005                        DAG.getNode(ISD::MUL, SDLoc(N0), VT,
2006                                    N0.getOperand(0), N1),
2007                        DAG.getNode(ISD::MUL, SDLoc(N1), VT,
2008                                    N0.getOperand(1), N1));
2009
2010   // reassociate mul
2011   SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1);
2012   if (RMUL.getNode())
2013     return RMUL;
2014
2015   return SDValue();
2016 }
2017
2018 SDValue DAGCombiner::visitSDIV(SDNode *N) {
2019   SDValue N0 = N->getOperand(0);
2020   SDValue N1 = N->getOperand(1);
2021   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2022   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2023   EVT VT = N->getValueType(0);
2024
2025   // fold vector ops
2026   if (VT.isVector()) {
2027     SDValue FoldedVOp = SimplifyVBinOp(N);
2028     if (FoldedVOp.getNode()) return FoldedVOp;
2029   }
2030
2031   // fold (sdiv c1, c2) -> c1/c2
2032   if (N0C && N1C && !N1C->isNullValue())
2033     return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C);
2034   // fold (sdiv X, 1) -> X
2035   if (N1C && N1C->getAPIntValue() == 1LL)
2036     return N0;
2037   // fold (sdiv X, -1) -> 0-X
2038   if (N1C && N1C->isAllOnesValue())
2039     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
2040                        DAG.getConstant(0, VT), N0);
2041   // If we know the sign bits of both operands are zero, strength reduce to a
2042   // udiv instead.  Handles (X&15) /s 4 -> X&15 >> 2
2043   if (!VT.isVector()) {
2044     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2045       return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
2046                          N0, N1);
2047   }
2048
2049   // fold (sdiv X, pow2) -> simple ops after legalize
2050   if (N1C && !N1C->isNullValue() && (N1C->getAPIntValue().isPowerOf2() ||
2051                                      (-N1C->getAPIntValue()).isPowerOf2())) {
2052     // If dividing by powers of two is cheap, then don't perform the following
2053     // fold.
2054     if (TLI.isPow2DivCheap())
2055       return SDValue();
2056
2057     // Target-specific implementation of sdiv x, pow2.
2058     SDValue Res = BuildSDIVPow2(N);
2059     if (Res.getNode())
2060       return Res;
2061
2062     unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
2063
2064     // Splat the sign bit into the register
2065     SDValue SGN =
2066         DAG.getNode(ISD::SRA, SDLoc(N), VT, N0,
2067                     DAG.getConstant(VT.getScalarSizeInBits() - 1,
2068                                     getShiftAmountTy(N0.getValueType())));
2069     AddToWorklist(SGN.getNode());
2070
2071     // Add (N0 < 0) ? abs2 - 1 : 0;
2072     SDValue SRL =
2073         DAG.getNode(ISD::SRL, SDLoc(N), VT, SGN,
2074                     DAG.getConstant(VT.getScalarSizeInBits() - lg2,
2075                                     getShiftAmountTy(SGN.getValueType())));
2076     SDValue ADD = DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, SRL);
2077     AddToWorklist(SRL.getNode());
2078     AddToWorklist(ADD.getNode());    // Divide by pow2
2079     SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), VT, ADD,
2080                   DAG.getConstant(lg2, getShiftAmountTy(ADD.getValueType())));
2081
2082     // If we're dividing by a positive value, we're done.  Otherwise, we must
2083     // negate the result.
2084     if (N1C->getAPIntValue().isNonNegative())
2085       return SRA;
2086
2087     AddToWorklist(SRA.getNode());
2088     return DAG.getNode(ISD::SUB, SDLoc(N), VT, DAG.getConstant(0, VT), SRA);
2089   }
2090
2091   // if integer divide is expensive and we satisfy the requirements, emit an
2092   // alternate sequence.
2093   if (N1C && !TLI.isIntDivCheap()) {
2094     SDValue Op = BuildSDIV(N);
2095     if (Op.getNode()) return Op;
2096   }
2097
2098   // undef / X -> 0
2099   if (N0.getOpcode() == ISD::UNDEF)
2100     return DAG.getConstant(0, VT);
2101   // X / undef -> undef
2102   if (N1.getOpcode() == ISD::UNDEF)
2103     return N1;
2104
2105   return SDValue();
2106 }
2107
2108 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2109   SDValue N0 = N->getOperand(0);
2110   SDValue N1 = N->getOperand(1);
2111   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2112   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2113   EVT VT = N->getValueType(0);
2114
2115   // fold vector ops
2116   if (VT.isVector()) {
2117     SDValue FoldedVOp = SimplifyVBinOp(N);
2118     if (FoldedVOp.getNode()) return FoldedVOp;
2119   }
2120
2121   // fold (udiv c1, c2) -> c1/c2
2122   if (N0C && N1C && !N1C->isNullValue())
2123     return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C);
2124   // fold (udiv x, (1 << c)) -> x >>u c
2125   if (N1C && N1C->getAPIntValue().isPowerOf2())
2126     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0,
2127                        DAG.getConstant(N1C->getAPIntValue().logBase2(),
2128                                        getShiftAmountTy(N0.getValueType())));
2129   // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2130   if (N1.getOpcode() == ISD::SHL) {
2131     if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2132       if (SHC->getAPIntValue().isPowerOf2()) {
2133         EVT ADDVT = N1.getOperand(1).getValueType();
2134         SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N), ADDVT,
2135                                   N1.getOperand(1),
2136                                   DAG.getConstant(SHC->getAPIntValue()
2137                                                                   .logBase2(),
2138                                                   ADDVT));
2139         AddToWorklist(Add.getNode());
2140         return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, Add);
2141       }
2142     }
2143   }
2144   // fold (udiv x, c) -> alternate
2145   if (N1C && !TLI.isIntDivCheap()) {
2146     SDValue Op = BuildUDIV(N);
2147     if (Op.getNode()) return Op;
2148   }
2149
2150   // undef / X -> 0
2151   if (N0.getOpcode() == ISD::UNDEF)
2152     return DAG.getConstant(0, VT);
2153   // X / undef -> undef
2154   if (N1.getOpcode() == ISD::UNDEF)
2155     return N1;
2156
2157   return SDValue();
2158 }
2159
2160 SDValue DAGCombiner::visitSREM(SDNode *N) {
2161   SDValue N0 = N->getOperand(0);
2162   SDValue N1 = N->getOperand(1);
2163   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2164   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2165   EVT VT = N->getValueType(0);
2166
2167   // fold (srem c1, c2) -> c1%c2
2168   if (N0C && N1C && !N1C->isNullValue())
2169     return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C);
2170   // If we know the sign bits of both operands are zero, strength reduce to a
2171   // urem instead.  Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2172   if (!VT.isVector()) {
2173     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2174       return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
2175   }
2176
2177   // If X/C can be simplified by the division-by-constant logic, lower
2178   // X%C to the equivalent of X-X/C*C.
2179   if (N1C && !N1C->isNullValue()) {
2180     SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
2181     AddToWorklist(Div.getNode());
2182     SDValue OptimizedDiv = combine(Div.getNode());
2183     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2184       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2185                                 OptimizedDiv, N1);
2186       SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2187       AddToWorklist(Mul.getNode());
2188       return Sub;
2189     }
2190   }
2191
2192   // undef % X -> 0
2193   if (N0.getOpcode() == ISD::UNDEF)
2194     return DAG.getConstant(0, VT);
2195   // X % undef -> undef
2196   if (N1.getOpcode() == ISD::UNDEF)
2197     return N1;
2198
2199   return SDValue();
2200 }
2201
2202 SDValue DAGCombiner::visitUREM(SDNode *N) {
2203   SDValue N0 = N->getOperand(0);
2204   SDValue N1 = N->getOperand(1);
2205   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2206   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2207   EVT VT = N->getValueType(0);
2208
2209   // fold (urem c1, c2) -> c1%c2
2210   if (N0C && N1C && !N1C->isNullValue())
2211     return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C);
2212   // fold (urem x, pow2) -> (and x, pow2-1)
2213   if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
2214     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0,
2215                        DAG.getConstant(N1C->getAPIntValue()-1,VT));
2216   // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2217   if (N1.getOpcode() == ISD::SHL) {
2218     if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2219       if (SHC->getAPIntValue().isPowerOf2()) {
2220         SDValue Add =
2221           DAG.getNode(ISD::ADD, SDLoc(N), VT, N1,
2222                  DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
2223                                  VT));
2224         AddToWorklist(Add.getNode());
2225         return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, Add);
2226       }
2227     }
2228   }
2229
2230   // If X/C can be simplified by the division-by-constant logic, lower
2231   // X%C to the equivalent of X-X/C*C.
2232   if (N1C && !N1C->isNullValue()) {
2233     SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
2234     AddToWorklist(Div.getNode());
2235     SDValue OptimizedDiv = combine(Div.getNode());
2236     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2237       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2238                                 OptimizedDiv, N1);
2239       SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2240       AddToWorklist(Mul.getNode());
2241       return Sub;
2242     }
2243   }
2244
2245   // undef % X -> 0
2246   if (N0.getOpcode() == ISD::UNDEF)
2247     return DAG.getConstant(0, VT);
2248   // X % undef -> undef
2249   if (N1.getOpcode() == ISD::UNDEF)
2250     return N1;
2251
2252   return SDValue();
2253 }
2254
2255 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2256   SDValue N0 = N->getOperand(0);
2257   SDValue N1 = N->getOperand(1);
2258   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2259   EVT VT = N->getValueType(0);
2260   SDLoc DL(N);
2261
2262   // fold (mulhs x, 0) -> 0
2263   if (N1C && N1C->isNullValue())
2264     return N1;
2265   // fold (mulhs x, 1) -> (sra x, size(x)-1)
2266   if (N1C && N1C->getAPIntValue() == 1)
2267     return DAG.getNode(ISD::SRA, SDLoc(N), N0.getValueType(), N0,
2268                        DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2269                                        getShiftAmountTy(N0.getValueType())));
2270   // fold (mulhs x, undef) -> 0
2271   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2272     return DAG.getConstant(0, VT);
2273
2274   // If the type twice as wide is legal, transform the mulhs to a wider multiply
2275   // plus a shift.
2276   if (VT.isSimple() && !VT.isVector()) {
2277     MVT Simple = VT.getSimpleVT();
2278     unsigned SimpleSize = Simple.getSizeInBits();
2279     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2280     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2281       N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2282       N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2283       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2284       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2285             DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2286       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2287     }
2288   }
2289
2290   return SDValue();
2291 }
2292
2293 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2294   SDValue N0 = N->getOperand(0);
2295   SDValue N1 = N->getOperand(1);
2296   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2297   EVT VT = N->getValueType(0);
2298   SDLoc DL(N);
2299
2300   // fold (mulhu x, 0) -> 0
2301   if (N1C && N1C->isNullValue())
2302     return N1;
2303   // fold (mulhu x, 1) -> 0
2304   if (N1C && N1C->getAPIntValue() == 1)
2305     return DAG.getConstant(0, N0.getValueType());
2306   // fold (mulhu x, undef) -> 0
2307   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2308     return DAG.getConstant(0, VT);
2309
2310   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2311   // plus a shift.
2312   if (VT.isSimple() && !VT.isVector()) {
2313     MVT Simple = VT.getSimpleVT();
2314     unsigned SimpleSize = Simple.getSizeInBits();
2315     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2316     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2317       N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2318       N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2319       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2320       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2321             DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2322       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2323     }
2324   }
2325
2326   return SDValue();
2327 }
2328
2329 /// SimplifyNodeWithTwoResults - Perform optimizations common to nodes that
2330 /// compute two values. LoOp and HiOp give the opcodes for the two computations
2331 /// that are being performed. Return true if a simplification was made.
2332 ///
2333 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2334                                                 unsigned HiOp) {
2335   // If the high half is not needed, just compute the low half.
2336   bool HiExists = N->hasAnyUseOfValue(1);
2337   if (!HiExists &&
2338       (!LegalOperations ||
2339        TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
2340     SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0),
2341                               ArrayRef<SDUse>(N->op_begin(), N->op_end()));
2342     return CombineTo(N, Res, Res);
2343   }
2344
2345   // If the low half is not needed, just compute the high half.
2346   bool LoExists = N->hasAnyUseOfValue(0);
2347   if (!LoExists &&
2348       (!LegalOperations ||
2349        TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2350     SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1),
2351                               ArrayRef<SDUse>(N->op_begin(), N->op_end()));
2352     return CombineTo(N, Res, Res);
2353   }
2354
2355   // If both halves are used, return as it is.
2356   if (LoExists && HiExists)
2357     return SDValue();
2358
2359   // If the two computed results can be simplified separately, separate them.
2360   if (LoExists) {
2361     SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0),
2362                              ArrayRef<SDUse>(N->op_begin(), N->op_end()));
2363     AddToWorklist(Lo.getNode());
2364     SDValue LoOpt = combine(Lo.getNode());
2365     if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2366         (!LegalOperations ||
2367          TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2368       return CombineTo(N, LoOpt, LoOpt);
2369   }
2370
2371   if (HiExists) {
2372     SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1),
2373                              ArrayRef<SDUse>(N->op_begin(), N->op_end()));
2374     AddToWorklist(Hi.getNode());
2375     SDValue HiOpt = combine(Hi.getNode());
2376     if (HiOpt.getNode() && HiOpt != Hi &&
2377         (!LegalOperations ||
2378          TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2379       return CombineTo(N, HiOpt, HiOpt);
2380   }
2381
2382   return SDValue();
2383 }
2384
2385 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2386   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
2387   if (Res.getNode()) return Res;
2388
2389   EVT VT = N->getValueType(0);
2390   SDLoc DL(N);
2391
2392   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2393   // plus a shift.
2394   if (VT.isSimple() && !VT.isVector()) {
2395     MVT Simple = VT.getSimpleVT();
2396     unsigned SimpleSize = Simple.getSizeInBits();
2397     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2398     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2399       SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2400       SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2401       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2402       // Compute the high part as N1.
2403       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2404             DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2405       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2406       // Compute the low part as N0.
2407       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2408       return CombineTo(N, Lo, Hi);
2409     }
2410   }
2411
2412   return SDValue();
2413 }
2414
2415 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2416   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
2417   if (Res.getNode()) return Res;
2418
2419   EVT VT = N->getValueType(0);
2420   SDLoc DL(N);
2421
2422   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2423   // plus a shift.
2424   if (VT.isSimple() && !VT.isVector()) {
2425     MVT Simple = VT.getSimpleVT();
2426     unsigned SimpleSize = Simple.getSizeInBits();
2427     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2428     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2429       SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2430       SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2431       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2432       // Compute the high part as N1.
2433       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2434             DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2435       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2436       // Compute the low part as N0.
2437       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2438       return CombineTo(N, Lo, Hi);
2439     }
2440   }
2441
2442   return SDValue();
2443 }
2444
2445 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2446   // (smulo x, 2) -> (saddo x, x)
2447   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2448     if (C2->getAPIntValue() == 2)
2449       return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2450                          N->getOperand(0), N->getOperand(0));
2451
2452   return SDValue();
2453 }
2454
2455 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2456   // (umulo x, 2) -> (uaddo x, x)
2457   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2458     if (C2->getAPIntValue() == 2)
2459       return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2460                          N->getOperand(0), N->getOperand(0));
2461
2462   return SDValue();
2463 }
2464
2465 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2466   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
2467   if (Res.getNode()) return Res;
2468
2469   return SDValue();
2470 }
2471
2472 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2473   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
2474   if (Res.getNode()) return Res;
2475
2476   return SDValue();
2477 }
2478
2479 /// SimplifyBinOpWithSameOpcodeHands - If this is a binary operator with
2480 /// two operands of the same opcode, try to simplify it.
2481 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2482   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2483   EVT VT = N0.getValueType();
2484   assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2485
2486   // Bail early if none of these transforms apply.
2487   if (N0.getNode()->getNumOperands() == 0) return SDValue();
2488
2489   // For each of OP in AND/OR/XOR:
2490   // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2491   // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2492   // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2493   // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2494   //
2495   // do not sink logical op inside of a vector extend, since it may combine
2496   // into a vsetcc.
2497   EVT Op0VT = N0.getOperand(0).getValueType();
2498   if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2499        N0.getOpcode() == ISD::SIGN_EXTEND ||
2500        // Avoid infinite looping with PromoteIntBinOp.
2501        (N0.getOpcode() == ISD::ANY_EXTEND &&
2502         (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2503        (N0.getOpcode() == ISD::TRUNCATE &&
2504         (!TLI.isZExtFree(VT, Op0VT) ||
2505          !TLI.isTruncateFree(Op0VT, VT)) &&
2506         TLI.isTypeLegal(Op0VT))) &&
2507       !VT.isVector() &&
2508       Op0VT == N1.getOperand(0).getValueType() &&
2509       (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2510     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2511                                  N0.getOperand(0).getValueType(),
2512                                  N0.getOperand(0), N1.getOperand(0));
2513     AddToWorklist(ORNode.getNode());
2514     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2515   }
2516
2517   // For each of OP in SHL/SRL/SRA/AND...
2518   //   fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2519   //   fold (or  (OP x, z), (OP y, z)) -> (OP (or  x, y), z)
2520   //   fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2521   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2522        N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2523       N0.getOperand(1) == N1.getOperand(1)) {
2524     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2525                                  N0.getOperand(0).getValueType(),
2526                                  N0.getOperand(0), N1.getOperand(0));
2527     AddToWorklist(ORNode.getNode());
2528     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2529                        ORNode, N0.getOperand(1));
2530   }
2531
2532   // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2533   // Only perform this optimization after type legalization and before
2534   // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2535   // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2536   // we don't want to undo this promotion.
2537   // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2538   // on scalars.
2539   if ((N0.getOpcode() == ISD::BITCAST ||
2540        N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2541       Level == AfterLegalizeTypes) {
2542     SDValue In0 = N0.getOperand(0);
2543     SDValue In1 = N1.getOperand(0);
2544     EVT In0Ty = In0.getValueType();
2545     EVT In1Ty = In1.getValueType();
2546     SDLoc DL(N);
2547     // If both incoming values are integers, and the original types are the
2548     // same.
2549     if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2550       SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2551       SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2552       AddToWorklist(Op.getNode());
2553       return BC;
2554     }
2555   }
2556
2557   // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2558   // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2559   // If both shuffles use the same mask, and both shuffle within a single
2560   // vector, then it is worthwhile to move the swizzle after the operation.
2561   // The type-legalizer generates this pattern when loading illegal
2562   // vector types from memory. In many cases this allows additional shuffle
2563   // optimizations.
2564   // There are other cases where moving the shuffle after the xor/and/or
2565   // is profitable even if shuffles don't perform a swizzle.
2566   // If both shuffles use the same mask, and both shuffles have the same first
2567   // or second operand, then it might still be profitable to move the shuffle
2568   // after the xor/and/or operation.
2569   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
2570     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2571     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2572
2573     assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
2574            "Inputs to shuffles are not the same type");
2575
2576     // Check that both shuffles use the same mask. The masks are known to be of
2577     // the same length because the result vector type is the same.
2578     // Check also that shuffles have only one use to avoid introducing extra
2579     // instructions.
2580     if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2581         SVN0->getMask().equals(SVN1->getMask())) {
2582       SDValue ShOp = N0->getOperand(1);
2583
2584       // Don't try to fold this node if it requires introducing a
2585       // build vector of all zeros that might be illegal at this stage.
2586       if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2587         if (!LegalTypes)
2588           ShOp = DAG.getConstant(0, VT);
2589         else
2590           ShOp = SDValue();
2591       }
2592
2593       // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2594       // (OR  (shuf (A, C), shuf (B, C)) -> shuf (OR  (A, B), C)
2595       // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2596       if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2597         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2598                                       N0->getOperand(0), N1->getOperand(0));
2599         AddToWorklist(NewNode.getNode());
2600         return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2601                                     &SVN0->getMask()[0]);
2602       }
2603
2604       // Don't try to fold this node if it requires introducing a
2605       // build vector of all zeros that might be illegal at this stage.
2606       ShOp = N0->getOperand(0);
2607       if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2608         if (!LegalTypes)
2609           ShOp = DAG.getConstant(0, VT);
2610         else
2611           ShOp = SDValue();
2612       }
2613
2614       // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2615       // (OR  (shuf (C, A), shuf (C, B)) -> shuf (C, OR  (A, B))
2616       // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2617       if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2618         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2619                                       N0->getOperand(1), N1->getOperand(1));
2620         AddToWorklist(NewNode.getNode());
2621         return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2622                                     &SVN0->getMask()[0]);
2623       }
2624     }
2625   }
2626
2627   return SDValue();
2628 }
2629
2630 SDValue DAGCombiner::visitAND(SDNode *N) {
2631   SDValue N0 = N->getOperand(0);
2632   SDValue N1 = N->getOperand(1);
2633   SDValue LL, LR, RL, RR, CC0, CC1;
2634   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2635   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2636   EVT VT = N1.getValueType();
2637   unsigned BitWidth = VT.getScalarType().getSizeInBits();
2638
2639   // fold vector ops
2640   if (VT.isVector()) {
2641     SDValue FoldedVOp = SimplifyVBinOp(N);
2642     if (FoldedVOp.getNode()) return FoldedVOp;
2643
2644     // fold (and x, 0) -> 0, vector edition
2645     if (ISD::isBuildVectorAllZeros(N0.getNode()))
2646       return N0;
2647     if (ISD::isBuildVectorAllZeros(N1.getNode()))
2648       return N1;
2649
2650     // fold (and x, -1) -> x, vector edition
2651     if (ISD::isBuildVectorAllOnes(N0.getNode()))
2652       return N1;
2653     if (ISD::isBuildVectorAllOnes(N1.getNode()))
2654       return N0;
2655   }
2656
2657   // fold (and x, undef) -> 0
2658   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2659     return DAG.getConstant(0, VT);
2660   // fold (and c1, c2) -> c1&c2
2661   if (N0C && N1C)
2662     return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C);
2663   // canonicalize constant to RHS
2664   if (N0C && !N1C)
2665     return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
2666   // fold (and x, -1) -> x
2667   if (N1C && N1C->isAllOnesValue())
2668     return N0;
2669   // if (and x, c) is known to be zero, return 0
2670   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2671                                    APInt::getAllOnesValue(BitWidth)))
2672     return DAG.getConstant(0, VT);
2673   // reassociate and
2674   SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1);
2675   if (RAND.getNode())
2676     return RAND;
2677   // fold (and (or x, C), D) -> D if (C & D) == D
2678   if (N1C && N0.getOpcode() == ISD::OR)
2679     if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2680       if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2681         return N1;
2682   // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2683   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2684     SDValue N0Op0 = N0.getOperand(0);
2685     APInt Mask = ~N1C->getAPIntValue();
2686     Mask = Mask.trunc(N0Op0.getValueSizeInBits());
2687     if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2688       SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
2689                                  N0.getValueType(), N0Op0);
2690
2691       // Replace uses of the AND with uses of the Zero extend node.
2692       CombineTo(N, Zext);
2693
2694       // We actually want to replace all uses of the any_extend with the
2695       // zero_extend, to avoid duplicating things.  This will later cause this
2696       // AND to be folded.
2697       CombineTo(N0.getNode(), Zext);
2698       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2699     }
2700   }
2701   // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
2702   // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2703   // already be zero by virtue of the width of the base type of the load.
2704   //
2705   // the 'X' node here can either be nothing or an extract_vector_elt to catch
2706   // more cases.
2707   if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2708        N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2709       N0.getOpcode() == ISD::LOAD) {
2710     LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2711                                          N0 : N0.getOperand(0) );
2712
2713     // Get the constant (if applicable) the zero'th operand is being ANDed with.
2714     // This can be a pure constant or a vector splat, in which case we treat the
2715     // vector as a scalar and use the splat value.
2716     APInt Constant = APInt::getNullValue(1);
2717     if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2718       Constant = C->getAPIntValue();
2719     } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2720       APInt SplatValue, SplatUndef;
2721       unsigned SplatBitSize;
2722       bool HasAnyUndefs;
2723       bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2724                                              SplatBitSize, HasAnyUndefs);
2725       if (IsSplat) {
2726         // Undef bits can contribute to a possible optimisation if set, so
2727         // set them.
2728         SplatValue |= SplatUndef;
2729
2730         // The splat value may be something like "0x00FFFFFF", which means 0 for
2731         // the first vector value and FF for the rest, repeating. We need a mask
2732         // that will apply equally to all members of the vector, so AND all the
2733         // lanes of the constant together.
2734         EVT VT = Vector->getValueType(0);
2735         unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
2736
2737         // If the splat value has been compressed to a bitlength lower
2738         // than the size of the vector lane, we need to re-expand it to
2739         // the lane size.
2740         if (BitWidth > SplatBitSize)
2741           for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
2742                SplatBitSize < BitWidth;
2743                SplatBitSize = SplatBitSize * 2)
2744             SplatValue |= SplatValue.shl(SplatBitSize);
2745
2746         Constant = APInt::getAllOnesValue(BitWidth);
2747         for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
2748           Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
2749       }
2750     }
2751
2752     // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
2753     // actually legal and isn't going to get expanded, else this is a false
2754     // optimisation.
2755     bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
2756                                                     Load->getMemoryVT());
2757
2758     // Resize the constant to the same size as the original memory access before
2759     // extension. If it is still the AllOnesValue then this AND is completely
2760     // unneeded.
2761     Constant =
2762       Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
2763
2764     bool B;
2765     switch (Load->getExtensionType()) {
2766     default: B = false; break;
2767     case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
2768     case ISD::ZEXTLOAD:
2769     case ISD::NON_EXTLOAD: B = true; break;
2770     }
2771
2772     if (B && Constant.isAllOnesValue()) {
2773       // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
2774       // preserve semantics once we get rid of the AND.
2775       SDValue NewLoad(Load, 0);
2776       if (Load->getExtensionType() == ISD::EXTLOAD) {
2777         NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
2778                               Load->getValueType(0), SDLoc(Load),
2779                               Load->getChain(), Load->getBasePtr(),
2780                               Load->getOffset(), Load->getMemoryVT(),
2781                               Load->getMemOperand());
2782         // Replace uses of the EXTLOAD with the new ZEXTLOAD.
2783         if (Load->getNumValues() == 3) {
2784           // PRE/POST_INC loads have 3 values.
2785           SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
2786                            NewLoad.getValue(2) };
2787           CombineTo(Load, To, 3, true);
2788         } else {
2789           CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
2790         }
2791       }
2792
2793       // Fold the AND away, taking care not to fold to the old load node if we
2794       // replaced it.
2795       CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
2796
2797       return SDValue(N, 0); // Return N so it doesn't get rechecked!
2798     }
2799   }
2800   // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2801   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2802     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2803     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2804
2805     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2806         LL.getValueType().isInteger()) {
2807       // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2808       if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
2809         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2810                                      LR.getValueType(), LL, RL);
2811         AddToWorklist(ORNode.getNode());
2812         return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2813       }
2814       // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2815       if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
2816         SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2817                                       LR.getValueType(), LL, RL);
2818         AddToWorklist(ANDNode.getNode());
2819         return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
2820       }
2821       // fold (and (setgt X,  -1), (setgt Y,  -1)) -> (setgt (or X, Y), -1)
2822       if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
2823         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2824                                      LR.getValueType(), LL, RL);
2825         AddToWorklist(ORNode.getNode());
2826         return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2827       }
2828     }
2829     // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2830     if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2831         Op0 == Op1 && LL.getValueType().isInteger() &&
2832       Op0 == ISD::SETNE && ((cast<ConstantSDNode>(LR)->isNullValue() &&
2833                                  cast<ConstantSDNode>(RR)->isAllOnesValue()) ||
2834                                 (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
2835                                  cast<ConstantSDNode>(RR)->isNullValue()))) {
2836       SDValue ADDNode = DAG.getNode(ISD::ADD, SDLoc(N0), LL.getValueType(),
2837                                     LL, DAG.getConstant(1, LL.getValueType()));
2838       AddToWorklist(ADDNode.getNode());
2839       return DAG.getSetCC(SDLoc(N), VT, ADDNode,
2840                           DAG.getConstant(2, LL.getValueType()), ISD::SETUGE);
2841     }
2842     // canonicalize equivalent to ll == rl
2843     if (LL == RR && LR == RL) {
2844       Op1 = ISD::getSetCCSwappedOperands(Op1);
2845       std::swap(RL, RR);
2846     }
2847     if (LL == RL && LR == RR) {
2848       bool isInteger = LL.getValueType().isInteger();
2849       ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2850       if (Result != ISD::SETCC_INVALID &&
2851           (!LegalOperations ||
2852            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2853             TLI.isOperationLegal(ISD::SETCC,
2854                             getSetCCResultType(N0.getSimpleValueType())))))
2855         return DAG.getSetCC(SDLoc(N), N0.getValueType(),
2856                             LL, LR, Result);
2857     }
2858   }
2859
2860   // Simplify: (and (op x...), (op y...))  -> (op (and x, y))
2861   if (N0.getOpcode() == N1.getOpcode()) {
2862     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
2863     if (Tmp.getNode()) return Tmp;
2864   }
2865
2866   // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
2867   // fold (and (sra)) -> (and (srl)) when possible.
2868   if (!VT.isVector() &&
2869       SimplifyDemandedBits(SDValue(N, 0)))
2870     return SDValue(N, 0);
2871
2872   // fold (zext_inreg (extload x)) -> (zextload x)
2873   if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
2874     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2875     EVT MemVT = LN0->getMemoryVT();
2876     // If we zero all the possible extended bits, then we can turn this into
2877     // a zextload if we are running before legalize or the operation is legal.
2878     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2879     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2880                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2881         ((!LegalOperations && !LN0->isVolatile()) ||
2882          TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2883       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2884                                        LN0->getChain(), LN0->getBasePtr(),
2885                                        MemVT, LN0->getMemOperand());
2886       AddToWorklist(N);
2887       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2888       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2889     }
2890   }
2891   // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
2892   if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
2893       N0.hasOneUse()) {
2894     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2895     EVT MemVT = LN0->getMemoryVT();
2896     // If we zero all the possible extended bits, then we can turn this into
2897     // a zextload if we are running before legalize or the operation is legal.
2898     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2899     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2900                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2901         ((!LegalOperations && !LN0->isVolatile()) ||
2902          TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2903       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2904                                        LN0->getChain(), LN0->getBasePtr(),
2905                                        MemVT, LN0->getMemOperand());
2906       AddToWorklist(N);
2907       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2908       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2909     }
2910   }
2911
2912   // fold (and (load x), 255) -> (zextload x, i8)
2913   // fold (and (extload x, i16), 255) -> (zextload x, i8)
2914   // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
2915   if (N1C && (N0.getOpcode() == ISD::LOAD ||
2916               (N0.getOpcode() == ISD::ANY_EXTEND &&
2917                N0.getOperand(0).getOpcode() == ISD::LOAD))) {
2918     bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
2919     LoadSDNode *LN0 = HasAnyExt
2920       ? cast<LoadSDNode>(N0.getOperand(0))
2921       : cast<LoadSDNode>(N0);
2922     if (LN0->getExtensionType() != ISD::SEXTLOAD &&
2923         LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
2924       uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
2925       if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
2926         EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
2927         EVT LoadedVT = LN0->getMemoryVT();
2928
2929         if (ExtVT == LoadedVT &&
2930             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2931           EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2932
2933           SDValue NewLoad =
2934             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2935                            LN0->getChain(), LN0->getBasePtr(), ExtVT,
2936                            LN0->getMemOperand());
2937           AddToWorklist(N);
2938           CombineTo(LN0, NewLoad, NewLoad.getValue(1));
2939           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2940         }
2941
2942         // Do not change the width of a volatile load.
2943         // Do not generate loads of non-round integer types since these can
2944         // be expensive (and would be wrong if the type is not byte sized).
2945         if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
2946             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2947           EVT PtrType = LN0->getOperand(1).getValueType();
2948
2949           unsigned Alignment = LN0->getAlignment();
2950           SDValue NewPtr = LN0->getBasePtr();
2951
2952           // For big endian targets, we need to add an offset to the pointer
2953           // to load the correct bytes.  For little endian systems, we merely
2954           // need to read fewer bytes from the same pointer.
2955           if (TLI.isBigEndian()) {
2956             unsigned LVTStoreBytes = LoadedVT.getStoreSize();
2957             unsigned EVTStoreBytes = ExtVT.getStoreSize();
2958             unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
2959             NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0), PtrType,
2960                                  NewPtr, DAG.getConstant(PtrOff, PtrType));
2961             Alignment = MinAlign(Alignment, PtrOff);
2962           }
2963
2964           AddToWorklist(NewPtr.getNode());
2965
2966           EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2967           SDValue Load =
2968             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2969                            LN0->getChain(), NewPtr,
2970                            LN0->getPointerInfo(),
2971                            ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
2972                            LN0->isInvariant(), Alignment, LN0->getAAInfo());
2973           AddToWorklist(N);
2974           CombineTo(LN0, Load, Load.getValue(1));
2975           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2976         }
2977       }
2978     }
2979   }
2980
2981   if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2982       VT.getSizeInBits() <= 64) {
2983     if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2984       APInt ADDC = ADDI->getAPIntValue();
2985       if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2986         // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
2987         // immediate for an add, but it is legal if its top c2 bits are set,
2988         // transform the ADD so the immediate doesn't need to be materialized
2989         // in a register.
2990         if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
2991           APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
2992                                              SRLI->getZExtValue());
2993           if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
2994             ADDC |= Mask;
2995             if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2996               SDValue NewAdd =
2997                 DAG.getNode(ISD::ADD, SDLoc(N0), VT,
2998                             N0.getOperand(0), DAG.getConstant(ADDC, VT));
2999               CombineTo(N0.getNode(), NewAdd);
3000               return SDValue(N, 0); // Return N so it doesn't get rechecked!
3001             }
3002           }
3003         }
3004       }
3005     }
3006   }
3007
3008   // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
3009   if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
3010     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
3011                                        N0.getOperand(1), false);
3012     if (BSwap.getNode())
3013       return BSwap;
3014   }
3015
3016   return SDValue();
3017 }
3018
3019 /// MatchBSwapHWord - Match (a >> 8) | (a << 8) as (bswap a) >> 16
3020 ///
3021 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
3022                                         bool DemandHighBits) {
3023   if (!LegalOperations)
3024     return SDValue();
3025
3026   EVT VT = N->getValueType(0);
3027   if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
3028     return SDValue();
3029   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3030     return SDValue();
3031
3032   // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
3033   bool LookPassAnd0 = false;
3034   bool LookPassAnd1 = false;
3035   if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
3036       std::swap(N0, N1);
3037   if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
3038       std::swap(N0, N1);
3039   if (N0.getOpcode() == ISD::AND) {
3040     if (!N0.getNode()->hasOneUse())
3041       return SDValue();
3042     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3043     if (!N01C || N01C->getZExtValue() != 0xFF00)
3044       return SDValue();
3045     N0 = N0.getOperand(0);
3046     LookPassAnd0 = true;
3047   }
3048
3049   if (N1.getOpcode() == ISD::AND) {
3050     if (!N1.getNode()->hasOneUse())
3051       return SDValue();
3052     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3053     if (!N11C || N11C->getZExtValue() != 0xFF)
3054       return SDValue();
3055     N1 = N1.getOperand(0);
3056     LookPassAnd1 = true;
3057   }
3058
3059   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3060     std::swap(N0, N1);
3061   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3062     return SDValue();
3063   if (!N0.getNode()->hasOneUse() ||
3064       !N1.getNode()->hasOneUse())
3065     return SDValue();
3066
3067   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3068   ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3069   if (!N01C || !N11C)
3070     return SDValue();
3071   if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3072     return SDValue();
3073
3074   // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3075   SDValue N00 = N0->getOperand(0);
3076   if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3077     if (!N00.getNode()->hasOneUse())
3078       return SDValue();
3079     ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3080     if (!N001C || N001C->getZExtValue() != 0xFF)
3081       return SDValue();
3082     N00 = N00.getOperand(0);
3083     LookPassAnd0 = true;
3084   }
3085
3086   SDValue N10 = N1->getOperand(0);
3087   if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3088     if (!N10.getNode()->hasOneUse())
3089       return SDValue();
3090     ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3091     if (!N101C || N101C->getZExtValue() != 0xFF00)
3092       return SDValue();
3093     N10 = N10.getOperand(0);
3094     LookPassAnd1 = true;
3095   }
3096
3097   if (N00 != N10)
3098     return SDValue();
3099
3100   // Make sure everything beyond the low halfword gets set to zero since the SRL
3101   // 16 will clear the top bits.
3102   unsigned OpSizeInBits = VT.getSizeInBits();
3103   if (DemandHighBits && OpSizeInBits > 16) {
3104     // If the left-shift isn't masked out then the only way this is a bswap is
3105     // if all bits beyond the low 8 are 0. In that case the entire pattern
3106     // reduces to a left shift anyway: leave it for other parts of the combiner.
3107     if (!LookPassAnd0)
3108       return SDValue();
3109
3110     // However, if the right shift isn't masked out then it might be because
3111     // it's not needed. See if we can spot that too.
3112     if (!LookPassAnd1 &&
3113         !DAG.MaskedValueIsZero(
3114             N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3115       return SDValue();
3116   }
3117
3118   SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
3119   if (OpSizeInBits > 16)
3120     Res = DAG.getNode(ISD::SRL, SDLoc(N), VT, Res,
3121                       DAG.getConstant(OpSizeInBits-16, getShiftAmountTy(VT)));
3122   return Res;
3123 }
3124
3125 /// isBSwapHWordElement - Return true if the specified node is an element
3126 /// that makes up a 32-bit packed halfword byteswap. i.e.
3127 /// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
3128 static bool isBSwapHWordElement(SDValue N, SmallVectorImpl<SDNode *> &Parts) {
3129   if (!N.getNode()->hasOneUse())
3130     return false;
3131
3132   unsigned Opc = N.getOpcode();
3133   if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3134     return false;
3135
3136   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3137   if (!N1C)
3138     return false;
3139
3140   unsigned Num;
3141   switch (N1C->getZExtValue()) {
3142   default:
3143     return false;
3144   case 0xFF:       Num = 0; break;
3145   case 0xFF00:     Num = 1; break;
3146   case 0xFF0000:   Num = 2; break;
3147   case 0xFF000000: Num = 3; break;
3148   }
3149
3150   // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3151   SDValue N0 = N.getOperand(0);
3152   if (Opc == ISD::AND) {
3153     if (Num == 0 || Num == 2) {
3154       // (x >> 8) & 0xff
3155       // (x >> 8) & 0xff0000
3156       if (N0.getOpcode() != ISD::SRL)
3157         return false;
3158       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3159       if (!C || C->getZExtValue() != 8)
3160         return false;
3161     } else {
3162       // (x << 8) & 0xff00
3163       // (x << 8) & 0xff000000
3164       if (N0.getOpcode() != ISD::SHL)
3165         return false;
3166       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3167       if (!C || C->getZExtValue() != 8)
3168         return false;
3169     }
3170   } else if (Opc == ISD::SHL) {
3171     // (x & 0xff) << 8
3172     // (x & 0xff0000) << 8
3173     if (Num != 0 && Num != 2)
3174       return false;
3175     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3176     if (!C || C->getZExtValue() != 8)
3177       return false;
3178   } else { // Opc == ISD::SRL
3179     // (x & 0xff00) >> 8
3180     // (x & 0xff000000) >> 8
3181     if (Num != 1 && Num != 3)
3182       return false;
3183     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3184     if (!C || C->getZExtValue() != 8)
3185       return false;
3186   }
3187
3188   if (Parts[Num])
3189     return false;
3190
3191   Parts[Num] = N0.getOperand(0).getNode();
3192   return true;
3193 }
3194
3195 /// MatchBSwapHWord - Match a 32-bit packed halfword bswap. That is
3196 /// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
3197 /// => (rotl (bswap x), 16)
3198 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3199   if (!LegalOperations)
3200     return SDValue();
3201
3202   EVT VT = N->getValueType(0);
3203   if (VT != MVT::i32)
3204     return SDValue();
3205   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3206     return SDValue();
3207
3208   SmallVector<SDNode*,4> Parts(4, (SDNode*)nullptr);
3209   // Look for either
3210   // (or (or (and), (and)), (or (and), (and)))
3211   // (or (or (or (and), (and)), (and)), (and))
3212   if (N0.getOpcode() != ISD::OR)
3213     return SDValue();
3214   SDValue N00 = N0.getOperand(0);
3215   SDValue N01 = N0.getOperand(1);
3216
3217   if (N1.getOpcode() == ISD::OR &&
3218       N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3219     // (or (or (and), (and)), (or (and), (and)))
3220     SDValue N000 = N00.getOperand(0);
3221     if (!isBSwapHWordElement(N000, Parts))
3222       return SDValue();
3223
3224     SDValue N001 = N00.getOperand(1);
3225     if (!isBSwapHWordElement(N001, Parts))
3226       return SDValue();
3227     SDValue N010 = N01.getOperand(0);
3228     if (!isBSwapHWordElement(N010, Parts))
3229       return SDValue();
3230     SDValue N011 = N01.getOperand(1);
3231     if (!isBSwapHWordElement(N011, Parts))
3232       return SDValue();
3233   } else {
3234     // (or (or (or (and), (and)), (and)), (and))
3235     if (!isBSwapHWordElement(N1, Parts))
3236       return SDValue();
3237     if (!isBSwapHWordElement(N01, Parts))
3238       return SDValue();
3239     if (N00.getOpcode() != ISD::OR)
3240       return SDValue();
3241     SDValue N000 = N00.getOperand(0);
3242     if (!isBSwapHWordElement(N000, Parts))
3243       return SDValue();
3244     SDValue N001 = N00.getOperand(1);
3245     if (!isBSwapHWordElement(N001, Parts))
3246       return SDValue();
3247   }
3248
3249   // Make sure the parts are all coming from the same node.
3250   if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3251     return SDValue();
3252
3253   SDValue BSwap = DAG.getNode(ISD::BSWAP, SDLoc(N), VT,
3254                               SDValue(Parts[0],0));
3255
3256   // Result of the bswap should be rotated by 16. If it's not legal, then
3257   // do  (x << 16) | (x >> 16).
3258   SDValue ShAmt = DAG.getConstant(16, getShiftAmountTy(VT));
3259   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3260     return DAG.getNode(ISD::ROTL, SDLoc(N), VT, BSwap, ShAmt);
3261   if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3262     return DAG.getNode(ISD::ROTR, SDLoc(N), VT, BSwap, ShAmt);
3263   return DAG.getNode(ISD::OR, SDLoc(N), VT,
3264                      DAG.getNode(ISD::SHL, SDLoc(N), VT, BSwap, ShAmt),
3265                      DAG.getNode(ISD::SRL, SDLoc(N), VT, BSwap, ShAmt));
3266 }
3267
3268 SDValue DAGCombiner::visitOR(SDNode *N) {
3269   SDValue N0 = N->getOperand(0);
3270   SDValue N1 = N->getOperand(1);
3271   SDValue LL, LR, RL, RR, CC0, CC1;
3272   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3273   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3274   EVT VT = N1.getValueType();
3275
3276   // fold vector ops
3277   if (VT.isVector()) {
3278     SDValue FoldedVOp = SimplifyVBinOp(N);
3279     if (FoldedVOp.getNode()) return FoldedVOp;
3280
3281     // fold (or x, 0) -> x, vector edition
3282     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3283       return N1;
3284     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3285       return N0;
3286
3287     // fold (or x, -1) -> -1, vector edition
3288     if (ISD::isBuildVectorAllOnes(N0.getNode()))
3289       return N0;
3290     if (ISD::isBuildVectorAllOnes(N1.getNode()))
3291       return N1;
3292
3293     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
3294     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
3295     // Do this only if the resulting shuffle is legal.
3296     if (isa<ShuffleVectorSDNode>(N0) &&
3297         isa<ShuffleVectorSDNode>(N1) &&
3298         // Avoid folding a node with illegal type.
3299         TLI.isTypeLegal(VT) &&
3300         N0->getOperand(1) == N1->getOperand(1) &&
3301         ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
3302       bool CanFold = true;
3303       unsigned NumElts = VT.getVectorNumElements();
3304       const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3305       const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3306       // We construct two shuffle masks:
3307       // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
3308       // and N1 as the second operand.
3309       // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
3310       // and N0 as the second operand.
3311       // We do this because OR is commutable and therefore there might be
3312       // two ways to fold this node into a shuffle.
3313       SmallVector<int,4> Mask1;
3314       SmallVector<int,4> Mask2;
3315
3316       for (unsigned i = 0; i != NumElts && CanFold; ++i) {
3317         int M0 = SV0->getMaskElt(i);
3318         int M1 = SV1->getMaskElt(i);
3319
3320         // Both shuffle indexes are undef. Propagate Undef.
3321         if (M0 < 0 && M1 < 0) {
3322           Mask1.push_back(M0);
3323           Mask2.push_back(M0);
3324           continue;
3325         }
3326
3327         if (M0 < 0 || M1 < 0 ||
3328             (M0 < (int)NumElts && M1 < (int)NumElts) ||
3329             (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
3330           CanFold = false;
3331           break;
3332         }
3333
3334         Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
3335         Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
3336       }
3337
3338       if (CanFold) {
3339         // Fold this sequence only if the resulting shuffle is 'legal'.
3340         if (TLI.isShuffleMaskLegal(Mask1, VT))
3341           return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
3342                                       N1->getOperand(0), &Mask1[0]);
3343         if (TLI.isShuffleMaskLegal(Mask2, VT))
3344           return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
3345                                       N0->getOperand(0), &Mask2[0]);
3346       }
3347     }
3348   }
3349
3350   // fold (or x, undef) -> -1
3351   if (!LegalOperations &&
3352       (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3353     EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3354     return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
3355   }
3356   // fold (or c1, c2) -> c1|c2
3357   if (N0C && N1C)
3358     return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C);
3359   // canonicalize constant to RHS
3360   if (N0C && !N1C)
3361     return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3362   // fold (or x, 0) -> x
3363   if (N1C && N1C->isNullValue())
3364     return N0;
3365   // fold (or x, -1) -> -1
3366   if (N1C && N1C->isAllOnesValue())
3367     return N1;
3368   // fold (or x, c) -> c iff (x & ~c) == 0
3369   if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3370     return N1;
3371
3372   // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3373   SDValue BSwap = MatchBSwapHWord(N, N0, N1);
3374   if (BSwap.getNode())
3375     return BSwap;
3376   BSwap = MatchBSwapHWordLow(N, N0, N1);
3377   if (BSwap.getNode())
3378     return BSwap;
3379
3380   // reassociate or
3381   SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1);
3382   if (ROR.getNode())
3383     return ROR;
3384   // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3385   // iff (c1 & c2) == 0.
3386   if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3387              isa<ConstantSDNode>(N0.getOperand(1))) {
3388     ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3389     if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3390       SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1);
3391       if (!COR.getNode())
3392         return SDValue();
3393       return DAG.getNode(ISD::AND, SDLoc(N), VT,
3394                          DAG.getNode(ISD::OR, SDLoc(N0), VT,
3395                                      N0.getOperand(0), N1), COR);
3396     }
3397   }
3398   // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3399   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3400     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3401     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3402
3403     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
3404         LL.getValueType().isInteger()) {
3405       // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3406       // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3407       if (cast<ConstantSDNode>(LR)->isNullValue() &&
3408           (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3409         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3410                                      LR.getValueType(), LL, RL);
3411         AddToWorklist(ORNode.getNode());
3412         return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
3413       }
3414       // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3415       // fold (or (setgt X, -1), (setgt Y  -1)) -> (setgt (and X, Y), -1)
3416       if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
3417           (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3418         SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3419                                       LR.getValueType(), LL, RL);
3420         AddToWorklist(ANDNode.getNode());
3421         return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
3422       }
3423     }
3424     // canonicalize equivalent to ll == rl
3425     if (LL == RR && LR == RL) {
3426       Op1 = ISD::getSetCCSwappedOperands(Op1);
3427       std::swap(RL, RR);
3428     }
3429     if (LL == RL && LR == RR) {
3430       bool isInteger = LL.getValueType().isInteger();
3431       ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3432       if (Result != ISD::SETCC_INVALID &&
3433           (!LegalOperations ||
3434            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3435             TLI.isOperationLegal(ISD::SETCC,
3436               getSetCCResultType(N0.getValueType())))))
3437         return DAG.getSetCC(SDLoc(N), N0.getValueType(),
3438                             LL, LR, Result);
3439     }
3440   }
3441
3442   // Simplify: (or (op x...), (op y...))  -> (op (or x, y))
3443   if (N0.getOpcode() == N1.getOpcode()) {
3444     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3445     if (Tmp.getNode()) return Tmp;
3446   }
3447
3448   // (or (and X, C1), (and Y, C2))  -> (and (or X, Y), C3) if possible.
3449   if (N0.getOpcode() == ISD::AND &&
3450       N1.getOpcode() == ISD::AND &&
3451       N0.getOperand(1).getOpcode() == ISD::Constant &&
3452       N1.getOperand(1).getOpcode() == ISD::Constant &&
3453       // Don't increase # computations.
3454       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3455     // We can only do this xform if we know that bits from X that are set in C2
3456     // but not in C1 are already zero.  Likewise for Y.
3457     const APInt &LHSMask =
3458       cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3459     const APInt &RHSMask =
3460       cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
3461
3462     if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3463         DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3464       SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3465                               N0.getOperand(0), N1.getOperand(0));
3466       return DAG.getNode(ISD::AND, SDLoc(N), VT, X,
3467                          DAG.getConstant(LHSMask | RHSMask, VT));
3468     }
3469   }
3470
3471   // See if this is some rotate idiom.
3472   if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3473     return SDValue(Rot, 0);
3474
3475   // Simplify the operands using demanded-bits information.
3476   if (!VT.isVector() &&
3477       SimplifyDemandedBits(SDValue(N, 0)))
3478     return SDValue(N, 0);
3479
3480   return SDValue();
3481 }
3482
3483 /// MatchRotateHalf - Match "(X shl/srl V1) & V2" where V2 may not be present.
3484 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3485   if (Op.getOpcode() == ISD::AND) {
3486     if (isa<ConstantSDNode>(Op.getOperand(1))) {
3487       Mask = Op.getOperand(1);
3488       Op = Op.getOperand(0);
3489     } else {
3490       return false;
3491     }
3492   }
3493
3494   if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3495     Shift = Op;
3496     return true;
3497   }
3498
3499   return false;
3500 }
3501
3502 // Return true if we can prove that, whenever Neg and Pos are both in the
3503 // range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos).  This means that
3504 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3505 //
3506 //     (or (shift1 X, Neg), (shift2 X, Pos))
3507 //
3508 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3509 // in direction shift1 by Neg.  The range [0, OpSize) means that we only need
3510 // to consider shift amounts with defined behavior.
3511 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) {
3512   // If OpSize is a power of 2 then:
3513   //
3514   //  (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1)
3515   //  (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize).
3516   //
3517   // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check
3518   // for the stronger condition:
3519   //
3520   //     Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1)    [A]
3521   //
3522   // for all Neg and Pos.  Since Neg & (OpSize - 1) == Neg' & (OpSize - 1)
3523   // we can just replace Neg with Neg' for the rest of the function.
3524   //
3525   // In other cases we check for the even stronger condition:
3526   //
3527   //     Neg == OpSize - Pos                                    [B]
3528   //
3529   // for all Neg and Pos.  Note that the (or ...) then invokes undefined
3530   // behavior if Pos == 0 (and consequently Neg == OpSize).
3531   //
3532   // We could actually use [A] whenever OpSize is a power of 2, but the
3533   // only extra cases that it would match are those uninteresting ones
3534   // where Neg and Pos are never in range at the same time.  E.g. for
3535   // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3536   // as well as (sub 32, Pos), but:
3537   //
3538   //     (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3539   //
3540   // always invokes undefined behavior for 32-bit X.
3541   //
3542   // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise.
3543   unsigned MaskLoBits = 0;
3544   if (Neg.getOpcode() == ISD::AND &&
3545       isPowerOf2_64(OpSize) &&
3546       Neg.getOperand(1).getOpcode() == ISD::Constant &&
3547       cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) {
3548     Neg = Neg.getOperand(0);
3549     MaskLoBits = Log2_64(OpSize);
3550   }
3551
3552   // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3553   if (Neg.getOpcode() != ISD::SUB)
3554     return 0;
3555   ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0));
3556   if (!NegC)
3557     return 0;
3558   SDValue NegOp1 = Neg.getOperand(1);
3559
3560   // On the RHS of [A], if Pos is Pos' & (OpSize - 1), just replace Pos with
3561   // Pos'.  The truncation is redundant for the purpose of the equality.
3562   if (MaskLoBits &&
3563       Pos.getOpcode() == ISD::AND &&
3564       Pos.getOperand(1).getOpcode() == ISD::Constant &&
3565       cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() == OpSize - 1)
3566     Pos = Pos.getOperand(0);
3567
3568   // The condition we need is now:
3569   //
3570   //     (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask
3571   //
3572   // If NegOp1 == Pos then we need:
3573   //
3574   //              OpSize & Mask == NegC & Mask
3575   //
3576   // (because "x & Mask" is a truncation and distributes through subtraction).
3577   APInt Width;
3578   if (Pos == NegOp1)
3579     Width = NegC->getAPIntValue();
3580   // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3581   // Then the condition we want to prove becomes:
3582   //
3583   //     (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask
3584   //
3585   // which, again because "x & Mask" is a truncation, becomes:
3586   //
3587   //                NegC & Mask == (OpSize - PosC) & Mask
3588   //              OpSize & Mask == (NegC + PosC) & Mask
3589   else if (Pos.getOpcode() == ISD::ADD &&
3590            Pos.getOperand(0) == NegOp1 &&
3591            Pos.getOperand(1).getOpcode() == ISD::Constant)
3592     Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() +
3593              NegC->getAPIntValue());
3594   else
3595     return false;
3596
3597   // Now we just need to check that OpSize & Mask == Width & Mask.
3598   if (MaskLoBits)
3599     // Opsize & Mask is 0 since Mask is Opsize - 1.
3600     return Width.getLoBits(MaskLoBits) == 0;
3601   return Width == OpSize;
3602 }
3603
3604 // A subroutine of MatchRotate used once we have found an OR of two opposite
3605 // shifts of Shifted.  If Neg == <operand size> - Pos then the OR reduces
3606 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3607 // former being preferred if supported.  InnerPos and InnerNeg are Pos and
3608 // Neg with outer conversions stripped away.
3609 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3610                                        SDValue Neg, SDValue InnerPos,
3611                                        SDValue InnerNeg, unsigned PosOpcode,
3612                                        unsigned NegOpcode, SDLoc DL) {
3613   // fold (or (shl x, (*ext y)),
3614   //          (srl x, (*ext (sub 32, y)))) ->
3615   //   (rotl x, y) or (rotr x, (sub 32, y))
3616   //
3617   // fold (or (shl x, (*ext (sub 32, y))),
3618   //          (srl x, (*ext y))) ->
3619   //   (rotr x, y) or (rotl x, (sub 32, y))
3620   EVT VT = Shifted.getValueType();
3621   if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) {
3622     bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3623     return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3624                        HasPos ? Pos : Neg).getNode();
3625   }
3626
3627   return nullptr;
3628 }
3629
3630 // MatchRotate - Handle an 'or' of two operands.  If this is one of the many
3631 // idioms for rotate, and if the target supports rotation instructions, generate
3632 // a rot[lr].
3633 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
3634   // Must be a legal type.  Expanded 'n promoted things won't work with rotates.
3635   EVT VT = LHS.getValueType();
3636   if (!TLI.isTypeLegal(VT)) return nullptr;
3637
3638   // The target must have at least one rotate flavor.
3639   bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3640   bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3641   if (!HasROTL && !HasROTR) return nullptr;
3642
3643   // Match "(X shl/srl V1) & V2" where V2 may not be present.
3644   SDValue LHSShift;   // The shift.
3645   SDValue LHSMask;    // AND value if any.
3646   if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3647     return nullptr; // Not part of a rotate.
3648
3649   SDValue RHSShift;   // The shift.
3650   SDValue RHSMask;    // AND value if any.
3651   if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3652     return nullptr; // Not part of a rotate.
3653
3654   if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3655     return nullptr;   // Not shifting the same value.
3656
3657   if (LHSShift.getOpcode() == RHSShift.getOpcode())
3658     return nullptr;   // Shifts must disagree.
3659
3660   // Canonicalize shl to left side in a shl/srl pair.
3661   if (RHSShift.getOpcode() == ISD::SHL) {
3662     std::swap(LHS, RHS);
3663     std::swap(LHSShift, RHSShift);
3664     std::swap(LHSMask , RHSMask );
3665   }
3666
3667   unsigned OpSizeInBits = VT.getSizeInBits();
3668   SDValue LHSShiftArg = LHSShift.getOperand(0);
3669   SDValue LHSShiftAmt = LHSShift.getOperand(1);
3670   SDValue RHSShiftArg = RHSShift.getOperand(0);
3671   SDValue RHSShiftAmt = RHSShift.getOperand(1);
3672
3673   // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3674   // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
3675   if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3676       RHSShiftAmt.getOpcode() == ISD::Constant) {
3677     uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3678     uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
3679     if ((LShVal + RShVal) != OpSizeInBits)
3680       return nullptr;
3681
3682     SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3683                               LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3684
3685     // If there is an AND of either shifted operand, apply it to the result.
3686     if (LHSMask.getNode() || RHSMask.getNode()) {
3687       APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
3688
3689       if (LHSMask.getNode()) {
3690         APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3691         Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
3692       }
3693       if (RHSMask.getNode()) {
3694         APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3695         Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
3696       }
3697
3698       Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT));
3699     }
3700
3701     return Rot.getNode();
3702   }
3703
3704   // If there is a mask here, and we have a variable shift, we can't be sure
3705   // that we're masking out the right stuff.
3706   if (LHSMask.getNode() || RHSMask.getNode())
3707     return nullptr;
3708
3709   // If the shift amount is sign/zext/any-extended just peel it off.
3710   SDValue LExtOp0 = LHSShiftAmt;
3711   SDValue RExtOp0 = RHSShiftAmt;
3712   if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3713        LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3714        LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3715        LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3716       (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3717        RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3718        RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3719        RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
3720     LExtOp0 = LHSShiftAmt.getOperand(0);
3721     RExtOp0 = RHSShiftAmt.getOperand(0);
3722   }
3723
3724   SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
3725                                    LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
3726   if (TryL)
3727     return TryL;
3728
3729   SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
3730                                    RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
3731   if (TryR)
3732     return TryR;
3733
3734   return nullptr;
3735 }
3736
3737 SDValue DAGCombiner::visitXOR(SDNode *N) {
3738   SDValue N0 = N->getOperand(0);
3739   SDValue N1 = N->getOperand(1);
3740   SDValue LHS, RHS, CC;
3741   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3742   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3743   EVT VT = N0.getValueType();
3744
3745   // fold vector ops
3746   if (VT.isVector()) {
3747     SDValue FoldedVOp = SimplifyVBinOp(N);
3748     if (FoldedVOp.getNode()) return FoldedVOp;
3749
3750     // fold (xor x, 0) -> x, vector edition
3751     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3752       return N1;
3753     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3754       return N0;
3755   }
3756
3757   // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3758   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3759     return DAG.getConstant(0, VT);
3760   // fold (xor x, undef) -> undef
3761   if (N0.getOpcode() == ISD::UNDEF)
3762     return N0;
3763   if (N1.getOpcode() == ISD::UNDEF)
3764     return N1;
3765   // fold (xor c1, c2) -> c1^c2
3766   if (N0C && N1C)
3767     return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
3768   // canonicalize constant to RHS
3769   if (N0C && !N1C)
3770     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
3771   // fold (xor x, 0) -> x
3772   if (N1C && N1C->isNullValue())
3773     return N0;
3774   // reassociate xor
3775   SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1);
3776   if (RXOR.getNode())
3777     return RXOR;
3778
3779   // fold !(x cc y) -> (x !cc y)
3780   if (N1C && N1C->getAPIntValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) {
3781     bool isInt = LHS.getValueType().isInteger();
3782     ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3783                                                isInt);
3784
3785     if (!LegalOperations ||
3786         TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
3787       switch (N0.getOpcode()) {
3788       default:
3789         llvm_unreachable("Unhandled SetCC Equivalent!");
3790       case ISD::SETCC:
3791         return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
3792       case ISD::SELECT_CC:
3793         return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
3794                                N0.getOperand(3), NotCC);
3795       }
3796     }
3797   }
3798
3799   // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
3800   if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
3801       N0.getNode()->hasOneUse() &&
3802       isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
3803     SDValue V = N0.getOperand(0);
3804     V = DAG.getNode(ISD::XOR, SDLoc(N0), V.getValueType(), V,
3805                     DAG.getConstant(1, V.getValueType()));
3806     AddToWorklist(V.getNode());
3807     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
3808   }
3809
3810   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
3811   if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
3812       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3813     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3814     if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
3815       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3816       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3817       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3818       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
3819       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3820     }
3821   }
3822   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
3823   if (N1C && N1C->isAllOnesValue() &&
3824       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3825     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3826     if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
3827       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3828       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3829       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3830       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
3831       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3832     }
3833   }
3834   // fold (xor (and x, y), y) -> (and (not x), y)
3835   if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3836       N0->getOperand(1) == N1) {
3837     SDValue X = N0->getOperand(0);
3838     SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
3839     AddToWorklist(NotX.getNode());
3840     return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
3841   }
3842   // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
3843   if (N1C && N0.getOpcode() == ISD::XOR) {
3844     ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
3845     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3846     if (N00C)
3847       return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(1),
3848                          DAG.getConstant(N1C->getAPIntValue() ^
3849                                          N00C->getAPIntValue(), VT));
3850     if (N01C)
3851       return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(0),
3852                          DAG.getConstant(N1C->getAPIntValue() ^
3853                                          N01C->getAPIntValue(), VT));
3854   }
3855   // fold (xor x, x) -> 0
3856   if (N0 == N1)
3857     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
3858
3859   // Simplify: xor (op x...), (op y...)  -> (op (xor x, y))
3860   if (N0.getOpcode() == N1.getOpcode()) {
3861     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3862     if (Tmp.getNode()) return Tmp;
3863   }
3864
3865   // Simplify the expression using non-local knowledge.
3866   if (!VT.isVector() &&
3867       SimplifyDemandedBits(SDValue(N, 0)))
3868     return SDValue(N, 0);
3869
3870   return SDValue();
3871 }
3872
3873 /// visitShiftByConstant - Handle transforms common to the three shifts, when
3874 /// the shift amount is a constant.
3875 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
3876   // We can't and shouldn't fold opaque constants.
3877   if (Amt->isOpaque())
3878     return SDValue();
3879
3880   SDNode *LHS = N->getOperand(0).getNode();
3881   if (!LHS->hasOneUse()) return SDValue();
3882
3883   // We want to pull some binops through shifts, so that we have (and (shift))
3884   // instead of (shift (and)), likewise for add, or, xor, etc.  This sort of
3885   // thing happens with address calculations, so it's important to canonicalize
3886   // it.
3887   bool HighBitSet = false;  // Can we transform this if the high bit is set?
3888
3889   switch (LHS->getOpcode()) {
3890   default: return SDValue();
3891   case ISD::OR:
3892   case ISD::XOR:
3893     HighBitSet = false; // We can only transform sra if the high bit is clear.
3894     break;
3895   case ISD::AND:
3896     HighBitSet = true;  // We can only transform sra if the high bit is set.
3897     break;
3898   case ISD::ADD:
3899     if (N->getOpcode() != ISD::SHL)
3900       return SDValue(); // only shl(add) not sr[al](add).
3901     HighBitSet = false; // We can only transform sra if the high bit is clear.
3902     break;
3903   }
3904
3905   // We require the RHS of the binop to be a constant and not opaque as well.
3906   ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
3907   if (!BinOpCst || BinOpCst->isOpaque()) return SDValue();
3908
3909   // FIXME: disable this unless the input to the binop is a shift by a constant.
3910   // If it is not a shift, it pessimizes some common cases like:
3911   //
3912   //    void foo(int *X, int i) { X[i & 1235] = 1; }
3913   //    int bar(int *X, int i) { return X[i & 255]; }
3914   SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
3915   if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
3916        BinOpLHSVal->getOpcode() != ISD::SRA &&
3917        BinOpLHSVal->getOpcode() != ISD::SRL) ||
3918       !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
3919     return SDValue();
3920
3921   EVT VT = N->getValueType(0);
3922
3923   // If this is a signed shift right, and the high bit is modified by the
3924   // logical operation, do not perform the transformation. The highBitSet
3925   // boolean indicates the value of the high bit of the constant which would
3926   // cause it to be modified for this operation.
3927   if (N->getOpcode() == ISD::SRA) {
3928     bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
3929     if (BinOpRHSSignSet != HighBitSet)
3930       return SDValue();
3931   }
3932
3933   if (!TLI.isDesirableToCommuteWithShift(LHS))
3934     return SDValue();
3935
3936   // Fold the constants, shifting the binop RHS by the shift amount.
3937   SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
3938                                N->getValueType(0),
3939                                LHS->getOperand(1), N->getOperand(1));
3940   assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
3941
3942   // Create the new shift.
3943   SDValue NewShift = DAG.getNode(N->getOpcode(),
3944                                  SDLoc(LHS->getOperand(0)),
3945                                  VT, LHS->getOperand(0), N->getOperand(1));
3946
3947   // Create the new binop.
3948   return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
3949 }
3950
3951 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
3952   assert(N->getOpcode() == ISD::TRUNCATE);
3953   assert(N->getOperand(0).getOpcode() == ISD::AND);
3954
3955   // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
3956   if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
3957     SDValue N01 = N->getOperand(0).getOperand(1);
3958
3959     if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
3960       EVT TruncVT = N->getValueType(0);
3961       SDValue N00 = N->getOperand(0).getOperand(0);
3962       APInt TruncC = N01C->getAPIntValue();
3963       TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
3964
3965       return DAG.getNode(ISD::AND, SDLoc(N), TruncVT,
3966                          DAG.getNode(ISD::TRUNCATE, SDLoc(N), TruncVT, N00),
3967                          DAG.getConstant(TruncC, TruncVT));
3968     }
3969   }
3970
3971   return SDValue();
3972 }
3973
3974 SDValue DAGCombiner::visitRotate(SDNode *N) {
3975   // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
3976   if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
3977       N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
3978     SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode());
3979     if (NewOp1.getNode())
3980       return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
3981                          N->getOperand(0), NewOp1);
3982   }
3983   return SDValue();
3984 }
3985
3986 SDValue DAGCombiner::visitSHL(SDNode *N) {
3987   SDValue N0 = N->getOperand(0);
3988   SDValue N1 = N->getOperand(1);
3989   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3990   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3991   EVT VT = N0.getValueType();
3992   unsigned OpSizeInBits = VT.getScalarSizeInBits();
3993
3994   // fold vector ops
3995   if (VT.isVector()) {
3996     SDValue FoldedVOp = SimplifyVBinOp(N);
3997     if (FoldedVOp.getNode()) return FoldedVOp;
3998
3999     BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
4000     // If setcc produces all-one true value then:
4001     // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
4002     if (N1CV && N1CV->isConstant()) {
4003       if (N0.getOpcode() == ISD::AND) {
4004         SDValue N00 = N0->getOperand(0);
4005         SDValue N01 = N0->getOperand(1);
4006         BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
4007
4008         if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
4009             TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
4010                 TargetLowering::ZeroOrNegativeOneBooleanContent) {
4011           SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, VT, N01CV, N1CV);
4012           if (C.getNode())
4013             return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
4014         }
4015       } else {
4016         N1C = isConstOrConstSplat(N1);
4017       }
4018     }
4019   }
4020
4021   // fold (shl c1, c2) -> c1<<c2
4022   if (N0C && N1C)
4023     return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
4024   // fold (shl 0, x) -> 0
4025   if (N0C && N0C->isNullValue())
4026     return N0;
4027   // fold (shl x, c >= size(x)) -> undef
4028   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4029     return DAG.getUNDEF(VT);
4030   // fold (shl x, 0) -> x
4031   if (N1C && N1C->isNullValue())
4032     return N0;
4033   // fold (shl undef, x) -> 0
4034   if (N0.getOpcode() == ISD::UNDEF)
4035     return DAG.getConstant(0, VT);
4036   // if (shl x, c) is known to be zero, return 0
4037   if (DAG.MaskedValueIsZero(SDValue(N, 0),
4038                             APInt::getAllOnesValue(OpSizeInBits)))
4039     return DAG.getConstant(0, VT);
4040   // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
4041   if (N1.getOpcode() == ISD::TRUNCATE &&
4042       N1.getOperand(0).getOpcode() == ISD::AND) {
4043     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4044     if (NewOp1.getNode())
4045       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
4046   }
4047
4048   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4049     return SDValue(N, 0);
4050
4051   // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
4052   if (N1C && N0.getOpcode() == ISD::SHL) {
4053     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4054       uint64_t c1 = N0C1->getZExtValue();
4055       uint64_t c2 = N1C->getZExtValue();
4056       if (c1 + c2 >= OpSizeInBits)
4057         return DAG.getConstant(0, VT);
4058       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4059                          DAG.getConstant(c1 + c2, N1.getValueType()));
4060     }
4061   }
4062
4063   // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4064   // For this to be valid, the second form must not preserve any of the bits
4065   // that are shifted out by the inner shift in the first form.  This means
4066   // the outer shift size must be >= the number of bits added by the ext.
4067   // As a corollary, we don't care what kind of ext it is.
4068   if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4069               N0.getOpcode() == ISD::ANY_EXTEND ||
4070               N0.getOpcode() == ISD::SIGN_EXTEND) &&
4071       N0.getOperand(0).getOpcode() == ISD::SHL) {
4072     SDValue N0Op0 = N0.getOperand(0);
4073     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4074       uint64_t c1 = N0Op0C1->getZExtValue();
4075       uint64_t c2 = N1C->getZExtValue();
4076       EVT InnerShiftVT = N0Op0.getValueType();
4077       uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4078       if (c2 >= OpSizeInBits - InnerShiftSize) {
4079         if (c1 + c2 >= OpSizeInBits)
4080           return DAG.getConstant(0, VT);
4081         return DAG.getNode(ISD::SHL, SDLoc(N0), VT,
4082                            DAG.getNode(N0.getOpcode(), SDLoc(N0), VT,
4083                                        N0Op0->getOperand(0)),
4084                            DAG.getConstant(c1 + c2, N1.getValueType()));
4085       }
4086     }
4087   }
4088
4089   // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4090   // Only fold this if the inner zext has no other uses to avoid increasing
4091   // the total number of instructions.
4092   if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
4093       N0.getOperand(0).getOpcode() == ISD::SRL) {
4094     SDValue N0Op0 = N0.getOperand(0);
4095     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4096       uint64_t c1 = N0Op0C1->getZExtValue();
4097       if (c1 < VT.getScalarSizeInBits()) {
4098         uint64_t c2 = N1C->getZExtValue();
4099         if (c1 == c2) {
4100           SDValue NewOp0 = N0.getOperand(0);
4101           EVT CountVT = NewOp0.getOperand(1).getValueType();
4102           SDValue NewSHL = DAG.getNode(ISD::SHL, SDLoc(N), NewOp0.getValueType(),
4103                                        NewOp0, DAG.getConstant(c2, CountVT));
4104           AddToWorklist(NewSHL.getNode());
4105           return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4106         }
4107       }
4108     }
4109   }
4110
4111   // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4112   //                               (and (srl x, (sub c1, c2), MASK)
4113   // Only fold this if the inner shift has no other uses -- if it does, folding
4114   // this will increase the total number of instructions.
4115   if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4116     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4117       uint64_t c1 = N0C1->getZExtValue();
4118       if (c1 < OpSizeInBits) {
4119         uint64_t c2 = N1C->getZExtValue();
4120         APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4121         SDValue Shift;
4122         if (c2 > c1) {
4123           Mask = Mask.shl(c2 - c1);
4124           Shift = DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4125                               DAG.getConstant(c2 - c1, N1.getValueType()));
4126         } else {
4127           Mask = Mask.lshr(c1 - c2);
4128           Shift = DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4129                               DAG.getConstant(c1 - c2, N1.getValueType()));
4130         }
4131         return DAG.getNode(ISD::AND, SDLoc(N0), VT, Shift,
4132                            DAG.getConstant(Mask, VT));
4133       }
4134     }
4135   }
4136   // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
4137   if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
4138     unsigned BitSize = VT.getScalarSizeInBits();
4139     SDValue HiBitsMask =
4140       DAG.getConstant(APInt::getHighBitsSet(BitSize,
4141                                             BitSize - N1C->getZExtValue()), VT);
4142     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4143                        HiBitsMask);
4144   }
4145
4146   if (N1C) {
4147     SDValue NewSHL = visitShiftByConstant(N, N1C);
4148     if (NewSHL.getNode())
4149       return NewSHL;
4150   }
4151
4152   return SDValue();
4153 }
4154
4155 SDValue DAGCombiner::visitSRA(SDNode *N) {
4156   SDValue N0 = N->getOperand(0);
4157   SDValue N1 = N->getOperand(1);
4158   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4159   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4160   EVT VT = N0.getValueType();
4161   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4162
4163   // fold vector ops
4164   if (VT.isVector()) {
4165     SDValue FoldedVOp = SimplifyVBinOp(N);
4166     if (FoldedVOp.getNode()) return FoldedVOp;
4167
4168     N1C = isConstOrConstSplat(N1);
4169   }
4170
4171   // fold (sra c1, c2) -> (sra c1, c2)
4172   if (N0C && N1C)
4173     return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
4174   // fold (sra 0, x) -> 0
4175   if (N0C && N0C->isNullValue())
4176     return N0;
4177   // fold (sra -1, x) -> -1
4178   if (N0C && N0C->isAllOnesValue())
4179     return N0;
4180   // fold (sra x, (setge c, size(x))) -> undef
4181   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4182     return DAG.getUNDEF(VT);
4183   // fold (sra x, 0) -> x
4184   if (N1C && N1C->isNullValue())
4185     return N0;
4186   // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4187   // sext_inreg.
4188   if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
4189     unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
4190     EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4191     if (VT.isVector())
4192       ExtVT = EVT::getVectorVT(*DAG.getContext(),
4193                                ExtVT, VT.getVectorNumElements());
4194     if ((!LegalOperations ||
4195          TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
4196       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
4197                          N0.getOperand(0), DAG.getValueType(ExtVT));
4198   }
4199
4200   // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
4201   if (N1C && N0.getOpcode() == ISD::SRA) {
4202     if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
4203       unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
4204       if (Sum >= OpSizeInBits)
4205         Sum = OpSizeInBits - 1;
4206       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0.getOperand(0),
4207                          DAG.getConstant(Sum, N1.getValueType()));
4208     }
4209   }
4210
4211   // fold (sra (shl X, m), (sub result_size, n))
4212   // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
4213   // result_size - n != m.
4214   // If truncate is free for the target sext(shl) is likely to result in better
4215   // code.
4216   if (N0.getOpcode() == ISD::SHL && N1C) {
4217     // Get the two constanst of the shifts, CN0 = m, CN = n.
4218     const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4219     if (N01C) {
4220       LLVMContext &Ctx = *DAG.getContext();
4221       // Determine what the truncate's result bitsize and type would be.
4222       EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4223
4224       if (VT.isVector())
4225         TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4226
4227       // Determine the residual right-shift amount.
4228       signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
4229
4230       // If the shift is not a no-op (in which case this should be just a sign
4231       // extend already), the truncated to type is legal, sign_extend is legal
4232       // on that type, and the truncate to that type is both legal and free,
4233       // perform the transform.
4234       if ((ShiftAmt > 0) &&
4235           TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4236           TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
4237           TLI.isTruncateFree(VT, TruncVT)) {
4238
4239           SDValue Amt = DAG.getConstant(ShiftAmt,
4240               getShiftAmountTy(N0.getOperand(0).getValueType()));
4241           SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), VT,
4242                                       N0.getOperand(0), Amt);
4243           SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), TruncVT,
4244                                       Shift);
4245           return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N),
4246                              N->getValueType(0), Trunc);
4247       }
4248     }
4249   }
4250
4251   // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
4252   if (N1.getOpcode() == ISD::TRUNCATE &&
4253       N1.getOperand(0).getOpcode() == ISD::AND) {
4254     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4255     if (NewOp1.getNode())
4256       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
4257   }
4258
4259   // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
4260   //      if c1 is equal to the number of bits the trunc removes
4261   if (N0.getOpcode() == ISD::TRUNCATE &&
4262       (N0.getOperand(0).getOpcode() == ISD::SRL ||
4263        N0.getOperand(0).getOpcode() == ISD::SRA) &&
4264       N0.getOperand(0).hasOneUse() &&
4265       N0.getOperand(0).getOperand(1).hasOneUse() &&
4266       N1C) {
4267     SDValue N0Op0 = N0.getOperand(0);
4268     if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4269       unsigned LargeShiftVal = LargeShift->getZExtValue();
4270       EVT LargeVT = N0Op0.getValueType();
4271
4272       if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4273         SDValue Amt =
4274           DAG.getConstant(LargeShiftVal + N1C->getZExtValue(),
4275                           getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4276         SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), LargeVT,
4277                                   N0Op0.getOperand(0), Amt);
4278         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, SRA);
4279       }
4280     }
4281   }
4282
4283   // Simplify, based on bits shifted out of the LHS.
4284   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4285     return SDValue(N, 0);
4286
4287
4288   // If the sign bit is known to be zero, switch this to a SRL.
4289   if (DAG.SignBitIsZero(N0))
4290     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
4291
4292   if (N1C) {
4293     SDValue NewSRA = visitShiftByConstant(N, N1C);
4294     if (NewSRA.getNode())
4295       return NewSRA;
4296   }
4297
4298   return SDValue();
4299 }
4300
4301 SDValue DAGCombiner::visitSRL(SDNode *N) {
4302   SDValue N0 = N->getOperand(0);
4303   SDValue N1 = N->getOperand(1);
4304   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4305   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4306   EVT VT = N0.getValueType();
4307   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4308
4309   // fold vector ops
4310   if (VT.isVector()) {
4311     SDValue FoldedVOp = SimplifyVBinOp(N);
4312     if (FoldedVOp.getNode()) return FoldedVOp;
4313
4314     N1C = isConstOrConstSplat(N1);
4315   }
4316
4317   // fold (srl c1, c2) -> c1 >>u c2
4318   if (N0C && N1C)
4319     return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C);
4320   // fold (srl 0, x) -> 0
4321   if (N0C && N0C->isNullValue())
4322     return N0;
4323   // fold (srl x, c >= size(x)) -> undef
4324   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4325     return DAG.getUNDEF(VT);
4326   // fold (srl x, 0) -> x
4327   if (N1C && N1C->isNullValue())
4328     return N0;
4329   // if (srl x, c) is known to be zero, return 0
4330   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4331                                    APInt::getAllOnesValue(OpSizeInBits)))
4332     return DAG.getConstant(0, VT);
4333
4334   // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
4335   if (N1C && N0.getOpcode() == ISD::SRL) {
4336     if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
4337       uint64_t c1 = N01C->getZExtValue();
4338       uint64_t c2 = N1C->getZExtValue();
4339       if (c1 + c2 >= OpSizeInBits)
4340         return DAG.getConstant(0, VT);
4341       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4342                          DAG.getConstant(c1 + c2, N1.getValueType()));
4343     }
4344   }
4345
4346   // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4347   if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4348       N0.getOperand(0).getOpcode() == ISD::SRL &&
4349       isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4350     uint64_t c1 =
4351       cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4352     uint64_t c2 = N1C->getZExtValue();
4353     EVT InnerShiftVT = N0.getOperand(0).getValueType();
4354     EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4355     uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
4356     // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4357     if (c1 + OpSizeInBits == InnerShiftSize) {
4358       if (c1 + c2 >= InnerShiftSize)
4359         return DAG.getConstant(0, VT);
4360       return DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT,
4361                          DAG.getNode(ISD::SRL, SDLoc(N0), InnerShiftVT,
4362                                      N0.getOperand(0)->getOperand(0),
4363                                      DAG.getConstant(c1 + c2, ShiftCountVT)));
4364     }
4365   }
4366
4367   // fold (srl (shl x, c), c) -> (and x, cst2)
4368   if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4369     unsigned BitSize = N0.getScalarValueSizeInBits();
4370     if (BitSize <= 64) {
4371       uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4372       return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4373                          DAG.getConstant(~0ULL >> ShAmt, VT));
4374     }
4375   }
4376
4377   // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4378   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4379     // Shifting in all undef bits?
4380     EVT SmallVT = N0.getOperand(0).getValueType();
4381     unsigned BitSize = SmallVT.getScalarSizeInBits();
4382     if (N1C->getZExtValue() >= BitSize)
4383       return DAG.getUNDEF(VT);
4384
4385     if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4386       uint64_t ShiftAmt = N1C->getZExtValue();
4387       SDValue SmallShift = DAG.getNode(ISD::SRL, SDLoc(N0), SmallVT,
4388                                        N0.getOperand(0),
4389                           DAG.getConstant(ShiftAmt, getShiftAmountTy(SmallVT)));
4390       AddToWorklist(SmallShift.getNode());
4391       APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
4392       return DAG.getNode(ISD::AND, SDLoc(N), VT,
4393                          DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, SmallShift),
4394                          DAG.getConstant(Mask, VT));
4395     }
4396   }
4397
4398   // fold (srl (sra X, Y), 31) -> (srl X, 31).  This srl only looks at the sign
4399   // bit, which is unmodified by sra.
4400   if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
4401     if (N0.getOpcode() == ISD::SRA)
4402       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4403   }
4404
4405   // fold (srl (ctlz x), "5") -> x  iff x has one bit set (the low bit).
4406   if (N1C && N0.getOpcode() == ISD::CTLZ &&
4407       N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
4408     APInt KnownZero, KnownOne;
4409     DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne);
4410
4411     // If any of the input bits are KnownOne, then the input couldn't be all
4412     // zeros, thus the result of the srl will always be zero.
4413     if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
4414
4415     // If all of the bits input the to ctlz node are known to be zero, then
4416     // the result of the ctlz is "32" and the result of the shift is one.
4417     APInt UnknownBits = ~KnownZero;
4418     if (UnknownBits == 0) return DAG.getConstant(1, VT);
4419
4420     // Otherwise, check to see if there is exactly one bit input to the ctlz.
4421     if ((UnknownBits & (UnknownBits - 1)) == 0) {
4422       // Okay, we know that only that the single bit specified by UnknownBits
4423       // could be set on input to the CTLZ node. If this bit is set, the SRL
4424       // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4425       // to an SRL/XOR pair, which is likely to simplify more.
4426       unsigned ShAmt = UnknownBits.countTrailingZeros();
4427       SDValue Op = N0.getOperand(0);
4428
4429       if (ShAmt) {
4430         Op = DAG.getNode(ISD::SRL, SDLoc(N0), VT, Op,
4431                   DAG.getConstant(ShAmt, getShiftAmountTy(Op.getValueType())));
4432         AddToWorklist(Op.getNode());
4433       }
4434
4435       return DAG.getNode(ISD::XOR, SDLoc(N), VT,
4436                          Op, DAG.getConstant(1, VT));
4437     }
4438   }
4439
4440   // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4441   if (N1.getOpcode() == ISD::TRUNCATE &&
4442       N1.getOperand(0).getOpcode() == ISD::AND) {
4443     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4444     if (NewOp1.getNode())
4445       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
4446   }
4447
4448   // fold operands of srl based on knowledge that the low bits are not
4449   // demanded.
4450   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4451     return SDValue(N, 0);
4452
4453   if (N1C) {
4454     SDValue NewSRL = visitShiftByConstant(N, N1C);
4455     if (NewSRL.getNode())
4456       return NewSRL;
4457   }
4458
4459   // Attempt to convert a srl of a load into a narrower zero-extending load.
4460   SDValue NarrowLoad = ReduceLoadWidth(N);
4461   if (NarrowLoad.getNode())
4462     return NarrowLoad;
4463
4464   // Here is a common situation. We want to optimize:
4465   //
4466   //   %a = ...
4467   //   %b = and i32 %a, 2
4468   //   %c = srl i32 %b, 1
4469   //   brcond i32 %c ...
4470   //
4471   // into
4472   //
4473   //   %a = ...
4474   //   %b = and %a, 2
4475   //   %c = setcc eq %b, 0
4476   //   brcond %c ...
4477   //
4478   // However when after the source operand of SRL is optimized into AND, the SRL
4479   // itself may not be optimized further. Look for it and add the BRCOND into
4480   // the worklist.
4481   if (N->hasOneUse()) {
4482     SDNode *Use = *N->use_begin();
4483     if (Use->getOpcode() == ISD::BRCOND)
4484       AddToWorklist(Use);
4485     else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4486       // Also look pass the truncate.
4487       Use = *Use->use_begin();
4488       if (Use->getOpcode() == ISD::BRCOND)
4489         AddToWorklist(Use);
4490     }
4491   }
4492
4493   return SDValue();
4494 }
4495
4496 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4497   SDValue N0 = N->getOperand(0);
4498   EVT VT = N->getValueType(0);
4499
4500   // fold (ctlz c1) -> c2
4501   if (isa<ConstantSDNode>(N0))
4502     return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
4503   return SDValue();
4504 }
4505
4506 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4507   SDValue N0 = N->getOperand(0);
4508   EVT VT = N->getValueType(0);
4509
4510   // fold (ctlz_zero_undef c1) -> c2
4511   if (isa<ConstantSDNode>(N0))
4512     return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4513   return SDValue();
4514 }
4515
4516 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4517   SDValue N0 = N->getOperand(0);
4518   EVT VT = N->getValueType(0);
4519
4520   // fold (cttz c1) -> c2
4521   if (isa<ConstantSDNode>(N0))
4522     return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
4523   return SDValue();
4524 }
4525
4526 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4527   SDValue N0 = N->getOperand(0);
4528   EVT VT = N->getValueType(0);
4529
4530   // fold (cttz_zero_undef c1) -> c2
4531   if (isa<ConstantSDNode>(N0))
4532     return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4533   return SDValue();
4534 }
4535
4536 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4537   SDValue N0 = N->getOperand(0);
4538   EVT VT = N->getValueType(0);
4539
4540   // fold (ctpop c1) -> c2
4541   if (isa<ConstantSDNode>(N0))
4542     return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
4543   return SDValue();
4544 }
4545
4546 SDValue DAGCombiner::visitSELECT(SDNode *N) {
4547   SDValue N0 = N->getOperand(0);
4548   SDValue N1 = N->getOperand(1);
4549   SDValue N2 = N->getOperand(2);
4550   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4551   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4552   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
4553   EVT VT = N->getValueType(0);
4554   EVT VT0 = N0.getValueType();
4555
4556   // fold (select C, X, X) -> X
4557   if (N1 == N2)
4558     return N1;
4559   // fold (select true, X, Y) -> X
4560   if (N0C && !N0C->isNullValue())
4561     return N1;
4562   // fold (select false, X, Y) -> Y
4563   if (N0C && N0C->isNullValue())
4564     return N2;
4565   // fold (select C, 1, X) -> (or C, X)
4566   if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
4567     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4568   // fold (select C, 0, 1) -> (xor C, 1)
4569   // We can't do this reliably if integer based booleans have different contents
4570   // to floating point based booleans. This is because we can't tell whether we
4571   // have an integer-based boolean or a floating-point-based boolean unless we
4572   // can find the SETCC that produced it and inspect its operands. This is
4573   // fairly easy if C is the SETCC node, but it can potentially be
4574   // undiscoverable (or not reasonably discoverable). For example, it could be
4575   // in another basic block or it could require searching a complicated
4576   // expression.
4577   if (VT.isInteger() &&
4578       (VT0 == MVT::i1 || (VT0.isInteger() &&
4579                           TLI.getBooleanContents(false, false) ==
4580                               TLI.getBooleanContents(false, true) &&
4581                           TLI.getBooleanContents(false, false) ==
4582                               TargetLowering::ZeroOrOneBooleanContent)) &&
4583       N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
4584     SDValue XORNode;
4585     if (VT == VT0)
4586       return DAG.getNode(ISD::XOR, SDLoc(N), VT0,
4587                          N0, DAG.getConstant(1, VT0));
4588     XORNode = DAG.getNode(ISD::XOR, SDLoc(N0), VT0,
4589                           N0, DAG.getConstant(1, VT0));
4590     AddToWorklist(XORNode.getNode());
4591     if (VT.bitsGT(VT0))
4592       return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4593     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
4594   }
4595   // fold (select C, 0, X) -> (and (not C), X)
4596   if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
4597     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4598     AddToWorklist(NOTNode.getNode());
4599     return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
4600   }
4601   // fold (select C, X, 1) -> (or (not C), X)
4602   if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
4603     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4604     AddToWorklist(NOTNode.getNode());
4605     return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
4606   }
4607   // fold (select C, X, 0) -> (and C, X)
4608   if (VT == MVT::i1 && N2C && N2C->isNullValue())
4609     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4610   // fold (select X, X, Y) -> (or X, Y)
4611   // fold (select X, 1, Y) -> (or X, Y)
4612   if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
4613     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4614   // fold (select X, Y, X) -> (and X, Y)
4615   // fold (select X, Y, 0) -> (and X, Y)
4616   if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
4617     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4618
4619   // If we can fold this based on the true/false value, do so.
4620   if (SimplifySelectOps(N, N1, N2))
4621     return SDValue(N, 0);  // Don't revisit N.
4622
4623   // fold selects based on a setcc into other things, such as min/max/abs
4624   if (N0.getOpcode() == ISD::SETCC) {
4625     if ((!LegalOperations &&
4626          TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
4627         TLI.isOperationLegal(ISD::SELECT_CC, VT))
4628       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
4629                          N0.getOperand(0), N0.getOperand(1),
4630                          N1, N2, N0.getOperand(2));
4631     return SimplifySelect(SDLoc(N), N0, N1, N2);
4632   }
4633
4634   return SDValue();
4635 }
4636
4637 static
4638 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
4639   SDLoc DL(N);
4640   EVT LoVT, HiVT;
4641   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
4642
4643   // Split the inputs.
4644   SDValue Lo, Hi, LL, LH, RL, RH;
4645   std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
4646   std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
4647
4648   Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
4649   Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
4650
4651   return std::make_pair(Lo, Hi);
4652 }
4653
4654 // This function assumes all the vselect's arguments are CONCAT_VECTOR
4655 // nodes and that the condition is a BV of ConstantSDNodes (or undefs).
4656 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
4657   SDLoc dl(N);
4658   SDValue Cond = N->getOperand(0);
4659   SDValue LHS = N->getOperand(1);
4660   SDValue RHS = N->getOperand(2);
4661   MVT VT = N->getSimpleValueType(0);
4662   int NumElems = VT.getVectorNumElements();
4663   assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
4664          RHS.getOpcode() == ISD::CONCAT_VECTORS &&
4665          Cond.getOpcode() == ISD::BUILD_VECTOR);
4666
4667   // We're sure we have an even number of elements due to the
4668   // concat_vectors we have as arguments to vselect.
4669   // Skip BV elements until we find one that's not an UNDEF
4670   // After we find an UNDEF element, keep looping until we get to half the
4671   // length of the BV and see if all the non-undef nodes are the same.
4672   ConstantSDNode *BottomHalf = nullptr;
4673   for (int i = 0; i < NumElems / 2; ++i) {
4674     if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
4675       continue;
4676
4677     if (BottomHalf == nullptr)
4678       BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
4679     else if (Cond->getOperand(i).getNode() != BottomHalf)
4680       return SDValue();
4681   }
4682
4683   // Do the same for the second half of the BuildVector
4684   ConstantSDNode *TopHalf = nullptr;
4685   for (int i = NumElems / 2; i < NumElems; ++i) {
4686     if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
4687       continue;
4688
4689     if (TopHalf == nullptr)
4690       TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
4691     else if (Cond->getOperand(i).getNode() != TopHalf)
4692       return SDValue();
4693   }
4694
4695   assert(TopHalf && BottomHalf &&
4696          "One half of the selector was all UNDEFs and the other was all the "
4697          "same value. This should have been addressed before this function.");
4698   return DAG.getNode(
4699       ISD::CONCAT_VECTORS, dl, VT,
4700       BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
4701       TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
4702 }
4703
4704 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
4705   SDValue N0 = N->getOperand(0);
4706   SDValue N1 = N->getOperand(1);
4707   SDValue N2 = N->getOperand(2);
4708   SDLoc DL(N);
4709
4710   // Canonicalize integer abs.
4711   // vselect (setg[te] X,  0),  X, -X ->
4712   // vselect (setgt    X, -1),  X, -X ->
4713   // vselect (setl[te] X,  0), -X,  X ->
4714   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
4715   if (N0.getOpcode() == ISD::SETCC) {
4716     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4717     ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4718     bool isAbs = false;
4719     bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
4720
4721     if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
4722          (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
4723         N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
4724       isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
4725     else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
4726              N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
4727       isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
4728
4729     if (isAbs) {
4730       EVT VT = LHS.getValueType();
4731       SDValue Shift = DAG.getNode(
4732           ISD::SRA, DL, VT, LHS,
4733           DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, VT));
4734       SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
4735       AddToWorklist(Shift.getNode());
4736       AddToWorklist(Add.getNode());
4737       return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
4738     }
4739   }
4740
4741   // If the VSELECT result requires splitting and the mask is provided by a
4742   // SETCC, then split both nodes and its operands before legalization. This
4743   // prevents the type legalizer from unrolling SETCC into scalar comparisons
4744   // and enables future optimizations (e.g. min/max pattern matching on X86).
4745   if (N0.getOpcode() == ISD::SETCC) {
4746     EVT VT = N->getValueType(0);
4747
4748     // Check if any splitting is required.
4749     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
4750         TargetLowering::TypeSplitVector)
4751       return SDValue();
4752
4753     SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
4754     std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
4755     std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
4756     std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
4757
4758     Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
4759     Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
4760
4761     // Add the new VSELECT nodes to the work list in case they need to be split
4762     // again.
4763     AddToWorklist(Lo.getNode());
4764     AddToWorklist(Hi.getNode());
4765
4766     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
4767   }
4768
4769   // Fold (vselect (build_vector all_ones), N1, N2) -> N1
4770   if (ISD::isBuildVectorAllOnes(N0.getNode()))
4771     return N1;
4772   // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
4773   if (ISD::isBuildVectorAllZeros(N0.getNode()))
4774     return N2;
4775
4776   // The ConvertSelectToConcatVector function is assuming both the above
4777   // checks for (vselect (build_vector all{ones,zeros) ...) have been made
4778   // and addressed.
4779   if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
4780       N2.getOpcode() == ISD::CONCAT_VECTORS &&
4781       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
4782     SDValue CV = ConvertSelectToConcatVector(N, DAG);
4783     if (CV.getNode())
4784       return CV;
4785   }
4786
4787   return SDValue();
4788 }
4789
4790 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
4791   SDValue N0 = N->getOperand(0);
4792   SDValue N1 = N->getOperand(1);
4793   SDValue N2 = N->getOperand(2);
4794   SDValue N3 = N->getOperand(3);
4795   SDValue N4 = N->getOperand(4);
4796   ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
4797
4798   // fold select_cc lhs, rhs, x, x, cc -> x
4799   if (N2 == N3)
4800     return N2;
4801
4802   // Determine if the condition we're dealing with is constant
4803   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
4804                               N0, N1, CC, SDLoc(N), false);
4805   if (SCC.getNode()) {
4806     AddToWorklist(SCC.getNode());
4807
4808     if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
4809       if (!SCCC->isNullValue())
4810         return N2;    // cond always true -> true val
4811       else
4812         return N3;    // cond always false -> false val
4813     }
4814
4815     // Fold to a simpler select_cc
4816     if (SCC.getOpcode() == ISD::SETCC)
4817       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
4818                          SCC.getOperand(0), SCC.getOperand(1), N2, N3,
4819                          SCC.getOperand(2));
4820   }
4821
4822   // If we can fold this based on the true/false value, do so.
4823   if (SimplifySelectOps(N, N2, N3))
4824     return SDValue(N, 0);  // Don't revisit N.
4825
4826   // fold select_cc into other things, such as min/max/abs
4827   return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
4828 }
4829
4830 SDValue DAGCombiner::visitSETCC(SDNode *N) {
4831   return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
4832                        cast<CondCodeSDNode>(N->getOperand(2))->get(),
4833                        SDLoc(N));
4834 }
4835
4836 // tryToFoldExtendOfConstant - Try to fold a sext/zext/aext
4837 // dag node into a ConstantSDNode or a build_vector of constants.
4838 // This function is called by the DAGCombiner when visiting sext/zext/aext
4839 // dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
4840 // Vector extends are not folded if operations are legal; this is to
4841 // avoid introducing illegal build_vector dag nodes.
4842 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
4843                                          SelectionDAG &DAG, bool LegalTypes,
4844                                          bool LegalOperations) {
4845   unsigned Opcode = N->getOpcode();
4846   SDValue N0 = N->getOperand(0);
4847   EVT VT = N->getValueType(0);
4848
4849   assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
4850          Opcode == ISD::ANY_EXTEND) && "Expected EXTEND dag node in input!");
4851
4852   // fold (sext c1) -> c1
4853   // fold (zext c1) -> c1
4854   // fold (aext c1) -> c1
4855   if (isa<ConstantSDNode>(N0))
4856     return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
4857
4858   // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
4859   // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
4860   // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
4861   EVT SVT = VT.getScalarType();
4862   if (!(VT.isVector() &&
4863       (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
4864       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
4865     return nullptr;
4866
4867   // We can fold this node into a build_vector.
4868   unsigned VTBits = SVT.getSizeInBits();
4869   unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
4870   unsigned ShAmt = VTBits - EVTBits;
4871   SmallVector<SDValue, 8> Elts;
4872   unsigned NumElts = N0->getNumOperands();
4873   SDLoc DL(N);
4874
4875   for (unsigned i=0; i != NumElts; ++i) {
4876     SDValue Op = N0->getOperand(i);
4877     if (Op->getOpcode() == ISD::UNDEF) {
4878       Elts.push_back(DAG.getUNDEF(SVT));
4879       continue;
4880     }
4881
4882     ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
4883     const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
4884     if (Opcode == ISD::SIGN_EXTEND)
4885       Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
4886                                      SVT));
4887     else
4888       Elts.push_back(DAG.getConstant(C.shl(ShAmt).lshr(ShAmt).getZExtValue(),
4889                                      SVT));
4890   }
4891
4892   return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts).getNode();
4893 }
4894
4895 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
4896 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
4897 // transformation. Returns true if extension are possible and the above
4898 // mentioned transformation is profitable.
4899 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
4900                                     unsigned ExtOpc,
4901                                     SmallVectorImpl<SDNode *> &ExtendNodes,
4902                                     const TargetLowering &TLI) {
4903   bool HasCopyToRegUses = false;
4904   bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
4905   for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
4906                             UE = N0.getNode()->use_end();
4907        UI != UE; ++UI) {
4908     SDNode *User = *UI;
4909     if (User == N)
4910       continue;
4911     if (UI.getUse().getResNo() != N0.getResNo())
4912       continue;
4913     // FIXME: Only extend SETCC N, N and SETCC N, c for now.
4914     if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
4915       ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
4916       if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
4917         // Sign bits will be lost after a zext.
4918         return false;
4919       bool Add = false;
4920       for (unsigned i = 0; i != 2; ++i) {
4921         SDValue UseOp = User->getOperand(i);
4922         if (UseOp == N0)
4923           continue;
4924         if (!isa<ConstantSDNode>(UseOp))
4925           return false;
4926         Add = true;
4927       }
4928       if (Add)
4929         ExtendNodes.push_back(User);
4930       continue;
4931     }
4932     // If truncates aren't free and there are users we can't
4933     // extend, it isn't worthwhile.
4934     if (!isTruncFree)
4935       return false;
4936     // Remember if this value is live-out.
4937     if (User->getOpcode() == ISD::CopyToReg)
4938       HasCopyToRegUses = true;
4939   }
4940
4941   if (HasCopyToRegUses) {
4942     bool BothLiveOut = false;
4943     for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
4944          UI != UE; ++UI) {
4945       SDUse &Use = UI.getUse();
4946       if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
4947         BothLiveOut = true;
4948         break;
4949       }
4950     }
4951     if (BothLiveOut)
4952       // Both unextended and extended values are live out. There had better be
4953       // a good reason for the transformation.
4954       return ExtendNodes.size();
4955   }
4956   return true;
4957 }
4958
4959 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
4960                                   SDValue Trunc, SDValue ExtLoad, SDLoc DL,
4961                                   ISD::NodeType ExtType) {
4962   // Extend SetCC uses if necessary.
4963   for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
4964     SDNode *SetCC = SetCCs[i];
4965     SmallVector<SDValue, 4> Ops;
4966
4967     for (unsigned j = 0; j != 2; ++j) {
4968       SDValue SOp = SetCC->getOperand(j);
4969       if (SOp == Trunc)
4970         Ops.push_back(ExtLoad);
4971       else
4972         Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
4973     }
4974
4975     Ops.push_back(SetCC->getOperand(2));
4976     CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
4977   }
4978 }
4979
4980 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
4981   SDValue N0 = N->getOperand(0);
4982   EVT VT = N->getValueType(0);
4983
4984   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
4985                                               LegalOperations))
4986     return SDValue(Res, 0);
4987
4988   // fold (sext (sext x)) -> (sext x)
4989   // fold (sext (aext x)) -> (sext x)
4990   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
4991     return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
4992                        N0.getOperand(0));
4993
4994   if (N0.getOpcode() == ISD::TRUNCATE) {
4995     // fold (sext (truncate (load x))) -> (sext (smaller load x))
4996     // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
4997     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4998     if (NarrowLoad.getNode()) {
4999       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5000       if (NarrowLoad.getNode() != N0.getNode()) {
5001         CombineTo(N0.getNode(), NarrowLoad);
5002         // CombineTo deleted the truncate, if needed, but not what's under it.
5003         AddToWorklist(oye);
5004       }
5005       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5006     }
5007
5008     // See if the value being truncated is already sign extended.  If so, just
5009     // eliminate the trunc/sext pair.
5010     SDValue Op = N0.getOperand(0);
5011     unsigned OpBits   = Op.getValueType().getScalarType().getSizeInBits();
5012     unsigned MidBits  = N0.getValueType().getScalarType().getSizeInBits();
5013     unsigned DestBits = VT.getScalarType().getSizeInBits();
5014     unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
5015
5016     if (OpBits == DestBits) {
5017       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
5018       // bits, it is already ready.
5019       if (NumSignBits > DestBits-MidBits)
5020         return Op;
5021     } else if (OpBits < DestBits) {
5022       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
5023       // bits, just sext from i32.
5024       if (NumSignBits > OpBits-MidBits)
5025         return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
5026     } else {
5027       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
5028       // bits, just truncate to i32.
5029       if (NumSignBits > OpBits-MidBits)
5030         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5031     }
5032
5033     // fold (sext (truncate x)) -> (sextinreg x).
5034     if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
5035                                                  N0.getValueType())) {
5036       if (OpBits < DestBits)
5037         Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
5038       else if (OpBits > DestBits)
5039         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
5040       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
5041                          DAG.getValueType(N0.getValueType()));
5042     }
5043   }
5044
5045   // fold (sext (load x)) -> (sext (truncate (sextload x)))
5046   // None of the supported targets knows how to perform load and sign extend
5047   // on vectors in one instruction.  We only perform this transformation on
5048   // scalars.
5049   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5050       ISD::isUNINDEXEDLoad(N0.getNode()) &&
5051       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5052        TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()))) {
5053     bool DoXform = true;
5054     SmallVector<SDNode*, 4> SetCCs;
5055     if (!N0.hasOneUse())
5056       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
5057     if (DoXform) {
5058       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5059       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5060                                        LN0->getChain(),
5061                                        LN0->getBasePtr(), N0.getValueType(),
5062                                        LN0->getMemOperand());
5063       CombineTo(N, ExtLoad);
5064       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5065                                   N0.getValueType(), ExtLoad);
5066       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5067       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5068                       ISD::SIGN_EXTEND);
5069       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5070     }
5071   }
5072
5073   // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
5074   // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
5075   if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5076       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5077     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5078     EVT MemVT = LN0->getMemoryVT();
5079     if ((!LegalOperations && !LN0->isVolatile()) ||
5080         TLI.isLoadExtLegal(ISD::SEXTLOAD, MemVT)) {
5081       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5082                                        LN0->getChain(),
5083                                        LN0->getBasePtr(), MemVT,
5084                                        LN0->getMemOperand());
5085       CombineTo(N, ExtLoad);
5086       CombineTo(N0.getNode(),
5087                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5088                             N0.getValueType(), ExtLoad),
5089                 ExtLoad.getValue(1));
5090       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5091     }
5092   }
5093
5094   // fold (sext (and/or/xor (load x), cst)) ->
5095   //      (and/or/xor (sextload x), (sext cst))
5096   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5097        N0.getOpcode() == ISD::XOR) &&
5098       isa<LoadSDNode>(N0.getOperand(0)) &&
5099       N0.getOperand(1).getOpcode() == ISD::Constant &&
5100       TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()) &&
5101       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5102     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5103     if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
5104       bool DoXform = true;
5105       SmallVector<SDNode*, 4> SetCCs;
5106       if (!N0.hasOneUse())
5107         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
5108                                           SetCCs, TLI);
5109       if (DoXform) {
5110         SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
5111                                          LN0->getChain(), LN0->getBasePtr(),
5112                                          LN0->getMemoryVT(),
5113                                          LN0->getMemOperand());
5114         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5115         Mask = Mask.sext(VT.getSizeInBits());
5116         SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5117                                   ExtLoad, DAG.getConstant(Mask, VT));
5118         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5119                                     SDLoc(N0.getOperand(0)),
5120                                     N0.getOperand(0).getValueType(), ExtLoad);
5121         CombineTo(N, And);
5122         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5123         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5124                         ISD::SIGN_EXTEND);
5125         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5126       }
5127     }
5128   }
5129
5130   if (N0.getOpcode() == ISD::SETCC) {
5131     EVT N0VT = N0.getOperand(0).getValueType();
5132     // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
5133     // Only do this before legalize for now.
5134     if (VT.isVector() && !LegalOperations &&
5135         TLI.getBooleanContents(N0VT) ==
5136             TargetLowering::ZeroOrNegativeOneBooleanContent) {
5137       // On some architectures (such as SSE/NEON/etc) the SETCC result type is
5138       // of the same size as the compared operands. Only optimize sext(setcc())
5139       // if this is the case.
5140       EVT SVT = getSetCCResultType(N0VT);
5141
5142       // We know that the # elements of the results is the same as the
5143       // # elements of the compare (and the # elements of the compare result
5144       // for that matter).  Check to see that they are the same size.  If so,
5145       // we know that the element size of the sext'd result matches the
5146       // element size of the compare operands.
5147       if (VT.getSizeInBits() == SVT.getSizeInBits())
5148         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5149                              N0.getOperand(1),
5150                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
5151
5152       // If the desired elements are smaller or larger than the source
5153       // elements we can use a matching integer vector type and then
5154       // truncate/sign extend
5155       EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5156       if (SVT == MatchingVectorType) {
5157         SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
5158                                N0.getOperand(0), N0.getOperand(1),
5159                                cast<CondCodeSDNode>(N0.getOperand(2))->get());
5160         return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
5161       }
5162     }
5163
5164     // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
5165     unsigned ElementWidth = VT.getScalarType().getSizeInBits();
5166     SDValue NegOne =
5167       DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT);
5168     SDValue SCC =
5169       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5170                        NegOne, DAG.getConstant(0, VT),
5171                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5172     if (SCC.getNode()) return SCC;
5173
5174     if (!VT.isVector()) {
5175       EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
5176       if (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, SetCCVT)) {
5177         SDLoc DL(N);
5178         ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5179         SDValue SetCC = DAG.getSetCC(DL,
5180                                      SetCCVT,
5181                                      N0.getOperand(0), N0.getOperand(1), CC);
5182         EVT SelectVT = getSetCCResultType(VT);
5183         return DAG.getSelect(DL, VT,
5184                              DAG.getSExtOrTrunc(SetCC, DL, SelectVT),
5185                              NegOne, DAG.getConstant(0, VT));
5186
5187       }
5188     }
5189   }
5190
5191   // fold (sext x) -> (zext x) if the sign bit is known zero.
5192   if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
5193       DAG.SignBitIsZero(N0))
5194     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
5195
5196   return SDValue();
5197 }
5198
5199 // isTruncateOf - If N is a truncate of some other value, return true, record
5200 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
5201 // This function computes KnownZero to avoid a duplicated call to
5202 // computeKnownBits in the caller.
5203 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
5204                          APInt &KnownZero) {
5205   APInt KnownOne;
5206   if (N->getOpcode() == ISD::TRUNCATE) {
5207     Op = N->getOperand(0);
5208     DAG.computeKnownBits(Op, KnownZero, KnownOne);
5209     return true;
5210   }
5211
5212   if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
5213       cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
5214     return false;
5215
5216   SDValue Op0 = N->getOperand(0);
5217   SDValue Op1 = N->getOperand(1);
5218   assert(Op0.getValueType() == Op1.getValueType());
5219
5220   ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0);
5221   ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
5222   if (COp0 && COp0->isNullValue())
5223     Op = Op1;
5224   else if (COp1 && COp1->isNullValue())
5225     Op = Op0;
5226   else
5227     return false;
5228
5229   DAG.computeKnownBits(Op, KnownZero, KnownOne);
5230
5231   if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
5232     return false;
5233
5234   return true;
5235 }
5236
5237 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
5238   SDValue N0 = N->getOperand(0);
5239   EVT VT = N->getValueType(0);
5240
5241   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5242                                               LegalOperations))
5243     return SDValue(Res, 0);
5244
5245   // fold (zext (zext x)) -> (zext x)
5246   // fold (zext (aext x)) -> (zext x)
5247   if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5248     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
5249                        N0.getOperand(0));
5250
5251   // fold (zext (truncate x)) -> (zext x) or
5252   //      (zext (truncate x)) -> (truncate x)
5253   // This is valid when the truncated bits of x are already zero.
5254   // FIXME: We should extend this to work for vectors too.
5255   SDValue Op;
5256   APInt KnownZero;
5257   if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
5258     APInt TruncatedBits =
5259       (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
5260       APInt(Op.getValueSizeInBits(), 0) :
5261       APInt::getBitsSet(Op.getValueSizeInBits(),
5262                         N0.getValueSizeInBits(),
5263                         std::min(Op.getValueSizeInBits(),
5264                                  VT.getSizeInBits()));
5265     if (TruncatedBits == (KnownZero & TruncatedBits)) {
5266       if (VT.bitsGT(Op.getValueType()))
5267         return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
5268       if (VT.bitsLT(Op.getValueType()))
5269         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5270
5271       return Op;
5272     }
5273   }
5274
5275   // fold (zext (truncate (load x))) -> (zext (smaller load x))
5276   // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
5277   if (N0.getOpcode() == ISD::TRUNCATE) {
5278     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5279     if (NarrowLoad.getNode()) {
5280       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5281       if (NarrowLoad.getNode() != N0.getNode()) {
5282         CombineTo(N0.getNode(), NarrowLoad);
5283         // CombineTo deleted the truncate, if needed, but not what's under it.
5284         AddToWorklist(oye);
5285       }
5286       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5287     }
5288   }
5289
5290   // fold (zext (truncate x)) -> (and x, mask)
5291   if (N0.getOpcode() == ISD::TRUNCATE &&
5292       (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
5293
5294     // fold (zext (truncate (load x))) -> (zext (smaller load x))
5295     // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
5296     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5297     if (NarrowLoad.getNode()) {
5298       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5299       if (NarrowLoad.getNode() != N0.getNode()) {
5300         CombineTo(N0.getNode(), NarrowLoad);
5301         // CombineTo deleted the truncate, if needed, but not what's under it.
5302         AddToWorklist(oye);
5303       }
5304       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5305     }
5306
5307     SDValue Op = N0.getOperand(0);
5308     if (Op.getValueType().bitsLT(VT)) {
5309       Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
5310       AddToWorklist(Op.getNode());
5311     } else if (Op.getValueType().bitsGT(VT)) {
5312       Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5313       AddToWorklist(Op.getNode());
5314     }
5315     return DAG.getZeroExtendInReg(Op, SDLoc(N),
5316                                   N0.getValueType().getScalarType());
5317   }
5318
5319   // Fold (zext (and (trunc x), cst)) -> (and x, cst),
5320   // if either of the casts is not free.
5321   if (N0.getOpcode() == ISD::AND &&
5322       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5323       N0.getOperand(1).getOpcode() == ISD::Constant &&
5324       (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5325                            N0.getValueType()) ||
5326        !TLI.isZExtFree(N0.getValueType(), VT))) {
5327     SDValue X = N0.getOperand(0).getOperand(0);
5328     if (X.getValueType().bitsLT(VT)) {
5329       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
5330     } else if (X.getValueType().bitsGT(VT)) {
5331       X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
5332     }
5333     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5334     Mask = Mask.zext(VT.getSizeInBits());
5335     return DAG.getNode(ISD::AND, SDLoc(N), VT,
5336                        X, DAG.getConstant(Mask, VT));
5337   }
5338
5339   // fold (zext (load x)) -> (zext (truncate (zextload x)))
5340   // None of the supported targets knows how to perform load and vector_zext
5341   // on vectors in one instruction.  We only perform this transformation on
5342   // scalars.
5343   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5344       ISD::isUNINDEXEDLoad(N0.getNode()) &&
5345       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5346        TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()))) {
5347     bool DoXform = true;
5348     SmallVector<SDNode*, 4> SetCCs;
5349     if (!N0.hasOneUse())
5350       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
5351     if (DoXform) {
5352       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5353       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5354                                        LN0->getChain(),
5355                                        LN0->getBasePtr(), N0.getValueType(),
5356                                        LN0->getMemOperand());
5357       CombineTo(N, ExtLoad);
5358       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5359                                   N0.getValueType(), ExtLoad);
5360       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5361
5362       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5363                       ISD::ZERO_EXTEND);
5364       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5365     }
5366   }
5367
5368   // fold (zext (and/or/xor (load x), cst)) ->
5369   //      (and/or/xor (zextload x), (zext cst))
5370   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5371        N0.getOpcode() == ISD::XOR) &&
5372       isa<LoadSDNode>(N0.getOperand(0)) &&
5373       N0.getOperand(1).getOpcode() == ISD::Constant &&
5374       TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()) &&
5375       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5376     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5377     if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
5378       bool DoXform = true;
5379       SmallVector<SDNode*, 4> SetCCs;
5380       if (!N0.hasOneUse())
5381         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
5382                                           SetCCs, TLI);
5383       if (DoXform) {
5384         SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
5385                                          LN0->getChain(), LN0->getBasePtr(),
5386                                          LN0->getMemoryVT(),
5387                                          LN0->getMemOperand());
5388         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5389         Mask = Mask.zext(VT.getSizeInBits());
5390         SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5391                                   ExtLoad, DAG.getConstant(Mask, VT));
5392         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5393                                     SDLoc(N0.getOperand(0)),
5394                                     N0.getOperand(0).getValueType(), ExtLoad);
5395         CombineTo(N, And);
5396         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5397         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5398                         ISD::ZERO_EXTEND);
5399         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5400       }
5401     }
5402   }
5403
5404   // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
5405   // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
5406   if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5407       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5408     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5409     EVT MemVT = LN0->getMemoryVT();
5410     if ((!LegalOperations && !LN0->isVolatile()) ||
5411         TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT)) {
5412       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5413                                        LN0->getChain(),
5414                                        LN0->getBasePtr(), MemVT,
5415                                        LN0->getMemOperand());
5416       CombineTo(N, ExtLoad);
5417       CombineTo(N0.getNode(),
5418                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
5419                             ExtLoad),
5420                 ExtLoad.getValue(1));
5421       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5422     }
5423   }
5424
5425   if (N0.getOpcode() == ISD::SETCC) {
5426     if (!LegalOperations && VT.isVector() &&
5427         N0.getValueType().getVectorElementType() == MVT::i1) {
5428       EVT N0VT = N0.getOperand(0).getValueType();
5429       if (getSetCCResultType(N0VT) == N0.getValueType())
5430         return SDValue();
5431
5432       // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
5433       // Only do this before legalize for now.
5434       EVT EltVT = VT.getVectorElementType();
5435       SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
5436                                     DAG.getConstant(1, EltVT));
5437       if (VT.getSizeInBits() == N0VT.getSizeInBits())
5438         // We know that the # elements of the results is the same as the
5439         // # elements of the compare (and the # elements of the compare result
5440         // for that matter).  Check to see that they are the same size.  If so,
5441         // we know that the element size of the sext'd result matches the
5442         // element size of the compare operands.
5443         return DAG.getNode(ISD::AND, SDLoc(N), VT,
5444                            DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5445                                          N0.getOperand(1),
5446                                  cast<CondCodeSDNode>(N0.getOperand(2))->get()),
5447                            DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
5448                                        OneOps));
5449
5450       // If the desired elements are smaller or larger than the source
5451       // elements we can use a matching integer vector type and then
5452       // truncate/sign extend
5453       EVT MatchingElementType =
5454         EVT::getIntegerVT(*DAG.getContext(),
5455                           N0VT.getScalarType().getSizeInBits());
5456       EVT MatchingVectorType =
5457         EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
5458                          N0VT.getVectorNumElements());
5459       SDValue VsetCC =
5460         DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5461                       N0.getOperand(1),
5462                       cast<CondCodeSDNode>(N0.getOperand(2))->get());
5463       return DAG.getNode(ISD::AND, SDLoc(N), VT,
5464                          DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT),
5465                          DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, OneOps));
5466     }
5467
5468     // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5469     SDValue SCC =
5470       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5471                        DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5472                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5473     if (SCC.getNode()) return SCC;
5474   }
5475
5476   // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
5477   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
5478       isa<ConstantSDNode>(N0.getOperand(1)) &&
5479       N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
5480       N0.hasOneUse()) {
5481     SDValue ShAmt = N0.getOperand(1);
5482     unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
5483     if (N0.getOpcode() == ISD::SHL) {
5484       SDValue InnerZExt = N0.getOperand(0);
5485       // If the original shl may be shifting out bits, do not perform this
5486       // transformation.
5487       unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
5488         InnerZExt.getOperand(0).getValueType().getSizeInBits();
5489       if (ShAmtVal > KnownZeroBits)
5490         return SDValue();
5491     }
5492
5493     SDLoc DL(N);
5494
5495     // Ensure that the shift amount is wide enough for the shifted value.
5496     if (VT.getSizeInBits() >= 256)
5497       ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
5498
5499     return DAG.getNode(N0.getOpcode(), DL, VT,
5500                        DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
5501                        ShAmt);
5502   }
5503
5504   return SDValue();
5505 }
5506
5507 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
5508   SDValue N0 = N->getOperand(0);
5509   EVT VT = N->getValueType(0);
5510
5511   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5512                                               LegalOperations))
5513     return SDValue(Res, 0);
5514
5515   // fold (aext (aext x)) -> (aext x)
5516   // fold (aext (zext x)) -> (zext x)
5517   // fold (aext (sext x)) -> (sext x)
5518   if (N0.getOpcode() == ISD::ANY_EXTEND  ||
5519       N0.getOpcode() == ISD::ZERO_EXTEND ||
5520       N0.getOpcode() == ISD::SIGN_EXTEND)
5521     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
5522
5523   // fold (aext (truncate (load x))) -> (aext (smaller load x))
5524   // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
5525   if (N0.getOpcode() == ISD::TRUNCATE) {
5526     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5527     if (NarrowLoad.getNode()) {
5528       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5529       if (NarrowLoad.getNode() != N0.getNode()) {
5530         CombineTo(N0.getNode(), NarrowLoad);
5531         // CombineTo deleted the truncate, if needed, but not what's under it.
5532         AddToWorklist(oye);
5533       }
5534       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5535     }
5536   }
5537
5538   // fold (aext (truncate x))
5539   if (N0.getOpcode() == ISD::TRUNCATE) {
5540     SDValue TruncOp = N0.getOperand(0);
5541     if (TruncOp.getValueType() == VT)
5542       return TruncOp; // x iff x size == zext size.
5543     if (TruncOp.getValueType().bitsGT(VT))
5544       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
5545     return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
5546   }
5547
5548   // Fold (aext (and (trunc x), cst)) -> (and x, cst)
5549   // if the trunc is not free.
5550   if (N0.getOpcode() == ISD::AND &&
5551       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5552       N0.getOperand(1).getOpcode() == ISD::Constant &&
5553       !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5554                           N0.getValueType())) {
5555     SDValue X = N0.getOperand(0).getOperand(0);
5556     if (X.getValueType().bitsLT(VT)) {
5557       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
5558     } else if (X.getValueType().bitsGT(VT)) {
5559       X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
5560     }
5561     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5562     Mask = Mask.zext(VT.getSizeInBits());
5563     return DAG.getNode(ISD::AND, SDLoc(N), VT,
5564                        X, DAG.getConstant(Mask, VT));
5565   }
5566
5567   // fold (aext (load x)) -> (aext (truncate (extload x)))
5568   // None of the supported targets knows how to perform load and any_ext
5569   // on vectors in one instruction.  We only perform this transformation on
5570   // scalars.
5571   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5572       ISD::isUNINDEXEDLoad(N0.getNode()) &&
5573       TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType())) {
5574     bool DoXform = true;
5575     SmallVector<SDNode*, 4> SetCCs;
5576     if (!N0.hasOneUse())
5577       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
5578     if (DoXform) {
5579       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5580       SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
5581                                        LN0->getChain(),
5582                                        LN0->getBasePtr(), N0.getValueType(),
5583                                        LN0->getMemOperand());
5584       CombineTo(N, ExtLoad);
5585       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5586                                   N0.getValueType(), ExtLoad);
5587       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5588       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5589                       ISD::ANY_EXTEND);
5590       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5591     }
5592   }
5593
5594   // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
5595   // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
5596   // fold (aext ( extload x)) -> (aext (truncate (extload  x)))
5597   if (N0.getOpcode() == ISD::LOAD &&
5598       !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5599       N0.hasOneUse()) {
5600     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5601     ISD::LoadExtType ExtType = LN0->getExtensionType();
5602     EVT MemVT = LN0->getMemoryVT();
5603     if (!LegalOperations || TLI.isLoadExtLegal(ExtType, MemVT)) {
5604       SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
5605                                        VT, LN0->getChain(), LN0->getBasePtr(),
5606                                        MemVT, LN0->getMemOperand());
5607       CombineTo(N, ExtLoad);
5608       CombineTo(N0.getNode(),
5609                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5610                             N0.getValueType(), ExtLoad),
5611                 ExtLoad.getValue(1));
5612       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5613     }
5614   }
5615
5616   if (N0.getOpcode() == ISD::SETCC) {
5617     // For vectors:
5618     // aext(setcc) -> vsetcc
5619     // aext(setcc) -> truncate(vsetcc)
5620     // aext(setcc) -> aext(vsetcc)
5621     // Only do this before legalize for now.
5622     if (VT.isVector() && !LegalOperations) {
5623       EVT N0VT = N0.getOperand(0).getValueType();
5624         // We know that the # elements of the results is the same as the
5625         // # elements of the compare (and the # elements of the compare result
5626         // for that matter).  Check to see that they are the same size.  If so,
5627         // we know that the element size of the sext'd result matches the
5628         // element size of the compare operands.
5629       if (VT.getSizeInBits() == N0VT.getSizeInBits())
5630         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5631                              N0.getOperand(1),
5632                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
5633       // If the desired elements are smaller or larger than the source
5634       // elements we can use a matching integer vector type and then
5635       // truncate/any extend
5636       else {
5637         EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5638         SDValue VsetCC =
5639           DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5640                         N0.getOperand(1),
5641                         cast<CondCodeSDNode>(N0.getOperand(2))->get());
5642         return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
5643       }
5644     }
5645
5646     // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5647     SDValue SCC =
5648       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5649                        DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5650                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5651     if (SCC.getNode())
5652       return SCC;
5653   }
5654
5655   return SDValue();
5656 }
5657
5658 /// GetDemandedBits - See if the specified operand can be simplified with the
5659 /// knowledge that only the bits specified by Mask are used.  If so, return the
5660 /// simpler operand, otherwise return a null SDValue.
5661 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
5662   switch (V.getOpcode()) {
5663   default: break;
5664   case ISD::Constant: {
5665     const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
5666     assert(CV && "Const value should be ConstSDNode.");
5667     const APInt &CVal = CV->getAPIntValue();
5668     APInt NewVal = CVal & Mask;
5669     if (NewVal != CVal)
5670       return DAG.getConstant(NewVal, V.getValueType());
5671     break;
5672   }
5673   case ISD::OR:
5674   case ISD::XOR:
5675     // If the LHS or RHS don't contribute bits to the or, drop them.
5676     if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
5677       return V.getOperand(1);
5678     if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
5679       return V.getOperand(0);
5680     break;
5681   case ISD::SRL:
5682     // Only look at single-use SRLs.
5683     if (!V.getNode()->hasOneUse())
5684       break;
5685     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
5686       // See if we can recursively simplify the LHS.
5687       unsigned Amt = RHSC->getZExtValue();
5688
5689       // Watch out for shift count overflow though.
5690       if (Amt >= Mask.getBitWidth()) break;
5691       APInt NewMask = Mask << Amt;
5692       SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
5693       if (SimplifyLHS.getNode())
5694         return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
5695                            SimplifyLHS, V.getOperand(1));
5696     }
5697   }
5698   return SDValue();
5699 }
5700
5701 /// ReduceLoadWidth - If the result of a wider load is shifted to right of N
5702 /// bits and then truncated to a narrower type and where N is a multiple
5703 /// of number of bits of the narrower type, transform it to a narrower load
5704 /// from address + N / num of bits of new type. If the result is to be
5705 /// extended, also fold the extension to form a extending load.
5706 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
5707   unsigned Opc = N->getOpcode();
5708
5709   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
5710   SDValue N0 = N->getOperand(0);
5711   EVT VT = N->getValueType(0);
5712   EVT ExtVT = VT;
5713
5714   // This transformation isn't valid for vector loads.
5715   if (VT.isVector())
5716     return SDValue();
5717
5718   // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
5719   // extended to VT.
5720   if (Opc == ISD::SIGN_EXTEND_INREG) {
5721     ExtType = ISD::SEXTLOAD;
5722     ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
5723   } else if (Opc == ISD::SRL) {
5724     // Another special-case: SRL is basically zero-extending a narrower value.
5725     ExtType = ISD::ZEXTLOAD;
5726     N0 = SDValue(N, 0);
5727     ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
5728     if (!N01) return SDValue();
5729     ExtVT = EVT::getIntegerVT(*DAG.getContext(),
5730                               VT.getSizeInBits() - N01->getZExtValue());
5731   }
5732   if (LegalOperations && !TLI.isLoadExtLegal(ExtType, ExtVT))
5733     return SDValue();
5734
5735   unsigned EVTBits = ExtVT.getSizeInBits();
5736
5737   // Do not generate loads of non-round integer types since these can
5738   // be expensive (and would be wrong if the type is not byte sized).
5739   if (!ExtVT.isRound())
5740     return SDValue();
5741
5742   unsigned ShAmt = 0;
5743   if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
5744     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5745       ShAmt = N01->getZExtValue();
5746       // Is the shift amount a multiple of size of VT?
5747       if ((ShAmt & (EVTBits-1)) == 0) {
5748         N0 = N0.getOperand(0);
5749         // Is the load width a multiple of size of VT?
5750         if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
5751           return SDValue();
5752       }
5753
5754       // At this point, we must have a load or else we can't do the transform.
5755       if (!isa<LoadSDNode>(N0)) return SDValue();
5756
5757       // Because a SRL must be assumed to *need* to zero-extend the high bits
5758       // (as opposed to anyext the high bits), we can't combine the zextload
5759       // lowering of SRL and an sextload.
5760       if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
5761         return SDValue();
5762
5763       // If the shift amount is larger than the input type then we're not
5764       // accessing any of the loaded bytes.  If the load was a zextload/extload
5765       // then the result of the shift+trunc is zero/undef (handled elsewhere).
5766       if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
5767         return SDValue();
5768     }
5769   }
5770
5771   // If the load is shifted left (and the result isn't shifted back right),
5772   // we can fold the truncate through the shift.
5773   unsigned ShLeftAmt = 0;
5774   if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
5775       ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
5776     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5777       ShLeftAmt = N01->getZExtValue();
5778       N0 = N0.getOperand(0);
5779     }
5780   }
5781
5782   // If we haven't found a load, we can't narrow it.  Don't transform one with
5783   // multiple uses, this would require adding a new load.
5784   if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
5785     return SDValue();
5786
5787   // Don't change the width of a volatile load.
5788   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5789   if (LN0->isVolatile())
5790     return SDValue();
5791
5792   // Verify that we are actually reducing a load width here.
5793   if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
5794     return SDValue();
5795
5796   // For the transform to be legal, the load must produce only two values
5797   // (the value loaded and the chain).  Don't transform a pre-increment
5798   // load, for example, which produces an extra value.  Otherwise the
5799   // transformation is not equivalent, and the downstream logic to replace
5800   // uses gets things wrong.
5801   if (LN0->getNumValues() > 2)
5802     return SDValue();
5803
5804   // If the load that we're shrinking is an extload and we're not just
5805   // discarding the extension we can't simply shrink the load. Bail.
5806   // TODO: It would be possible to merge the extensions in some cases.
5807   if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
5808       LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
5809     return SDValue();
5810
5811   EVT PtrType = N0.getOperand(1).getValueType();
5812
5813   if (PtrType == MVT::Untyped || PtrType.isExtended())
5814     // It's not possible to generate a constant of extended or untyped type.
5815     return SDValue();
5816
5817   // For big endian targets, we need to adjust the offset to the pointer to
5818   // load the correct bytes.
5819   if (TLI.isBigEndian()) {
5820     unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
5821     unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
5822     ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
5823   }
5824
5825   uint64_t PtrOff = ShAmt / 8;
5826   unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
5827   SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0),
5828                                PtrType, LN0->getBasePtr(),
5829                                DAG.getConstant(PtrOff, PtrType));
5830   AddToWorklist(NewPtr.getNode());
5831
5832   SDValue Load;
5833   if (ExtType == ISD::NON_EXTLOAD)
5834     Load =  DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
5835                         LN0->getPointerInfo().getWithOffset(PtrOff),
5836                         LN0->isVolatile(), LN0->isNonTemporal(),
5837                         LN0->isInvariant(), NewAlign, LN0->getAAInfo());
5838   else
5839     Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
5840                           LN0->getPointerInfo().getWithOffset(PtrOff),
5841                           ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
5842                           LN0->isInvariant(), NewAlign, LN0->getAAInfo());
5843
5844   // Replace the old load's chain with the new load's chain.
5845   WorklistRemover DeadNodes(*this);
5846   DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
5847
5848   // Shift the result left, if we've swallowed a left shift.
5849   SDValue Result = Load;
5850   if (ShLeftAmt != 0) {
5851     EVT ShImmTy = getShiftAmountTy(Result.getValueType());
5852     if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
5853       ShImmTy = VT;
5854     // If the shift amount is as large as the result size (but, presumably,
5855     // no larger than the source) then the useful bits of the result are
5856     // zero; we can't simply return the shortened shift, because the result
5857     // of that operation is undefined.
5858     if (ShLeftAmt >= VT.getSizeInBits())
5859       Result = DAG.getConstant(0, VT);
5860     else
5861       Result = DAG.getNode(ISD::SHL, SDLoc(N0), VT,
5862                           Result, DAG.getConstant(ShLeftAmt, ShImmTy));
5863   }
5864
5865   // Return the new loaded value.
5866   return Result;
5867 }
5868
5869 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
5870   SDValue N0 = N->getOperand(0);
5871   SDValue N1 = N->getOperand(1);
5872   EVT VT = N->getValueType(0);
5873   EVT EVT = cast<VTSDNode>(N1)->getVT();
5874   unsigned VTBits = VT.getScalarType().getSizeInBits();
5875   unsigned EVTBits = EVT.getScalarType().getSizeInBits();
5876
5877   // fold (sext_in_reg c1) -> c1
5878   if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
5879     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
5880
5881   // If the input is already sign extended, just drop the extension.
5882   if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
5883     return N0;
5884
5885   // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
5886   if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
5887       EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
5888     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5889                        N0.getOperand(0), N1);
5890
5891   // fold (sext_in_reg (sext x)) -> (sext x)
5892   // fold (sext_in_reg (aext x)) -> (sext x)
5893   // if x is small enough.
5894   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
5895     SDValue N00 = N0.getOperand(0);
5896     if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
5897         (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
5898       return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
5899   }
5900
5901   // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
5902   if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
5903     return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
5904
5905   // fold operands of sext_in_reg based on knowledge that the top bits are not
5906   // demanded.
5907   if (SimplifyDemandedBits(SDValue(N, 0)))
5908     return SDValue(N, 0);
5909
5910   // fold (sext_in_reg (load x)) -> (smaller sextload x)
5911   // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
5912   SDValue NarrowLoad = ReduceLoadWidth(N);
5913   if (NarrowLoad.getNode())
5914     return NarrowLoad;
5915
5916   // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
5917   // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
5918   // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
5919   if (N0.getOpcode() == ISD::SRL) {
5920     if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
5921       if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
5922         // We can turn this into an SRA iff the input to the SRL is already sign
5923         // extended enough.
5924         unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
5925         if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
5926           return DAG.getNode(ISD::SRA, SDLoc(N), VT,
5927                              N0.getOperand(0), N0.getOperand(1));
5928       }
5929   }
5930
5931   // fold (sext_inreg (extload x)) -> (sextload x)
5932   if (ISD::isEXTLoad(N0.getNode()) &&
5933       ISD::isUNINDEXEDLoad(N0.getNode()) &&
5934       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5935       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5936        TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5937     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5938     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5939                                      LN0->getChain(),
5940                                      LN0->getBasePtr(), EVT,
5941                                      LN0->getMemOperand());
5942     CombineTo(N, ExtLoad);
5943     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5944     AddToWorklist(ExtLoad.getNode());
5945     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5946   }
5947   // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
5948   if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5949       N0.hasOneUse() &&
5950       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5951       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5952        TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5953     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5954     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5955                                      LN0->getChain(),
5956                                      LN0->getBasePtr(), EVT,
5957                                      LN0->getMemOperand());
5958     CombineTo(N, ExtLoad);
5959     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5960     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5961   }
5962
5963   // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
5964   if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
5965     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
5966                                        N0.getOperand(1), false);
5967     if (BSwap.getNode())
5968       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5969                          BSwap, N1);
5970   }
5971
5972   // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs
5973   // into a build_vector.
5974   if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5975     SmallVector<SDValue, 8> Elts;
5976     unsigned NumElts = N0->getNumOperands();
5977     unsigned ShAmt = VTBits - EVTBits;
5978
5979     for (unsigned i = 0; i != NumElts; ++i) {
5980       SDValue Op = N0->getOperand(i);
5981       if (Op->getOpcode() == ISD::UNDEF) {
5982         Elts.push_back(Op);
5983         continue;
5984       }
5985
5986       ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
5987       const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
5988       Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
5989                                      Op.getValueType()));
5990     }
5991
5992     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Elts);
5993   }
5994
5995   return SDValue();
5996 }
5997
5998 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
5999   SDValue N0 = N->getOperand(0);
6000   EVT VT = N->getValueType(0);
6001   bool isLE = TLI.isLittleEndian();
6002
6003   // noop truncate
6004   if (N0.getValueType() == N->getValueType(0))
6005     return N0;
6006   // fold (truncate c1) -> c1
6007   if (isa<ConstantSDNode>(N0))
6008     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
6009   // fold (truncate (truncate x)) -> (truncate x)
6010   if (N0.getOpcode() == ISD::TRUNCATE)
6011     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6012   // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
6013   if (N0.getOpcode() == ISD::ZERO_EXTEND ||
6014       N0.getOpcode() == ISD::SIGN_EXTEND ||
6015       N0.getOpcode() == ISD::ANY_EXTEND) {
6016     if (N0.getOperand(0).getValueType().bitsLT(VT))
6017       // if the source is smaller than the dest, we still need an extend
6018       return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
6019                          N0.getOperand(0));
6020     if (N0.getOperand(0).getValueType().bitsGT(VT))
6021       // if the source is larger than the dest, than we just need the truncate
6022       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6023     // if the source and dest are the same type, we can drop both the extend
6024     // and the truncate.
6025     return N0.getOperand(0);
6026   }
6027
6028   // Fold extract-and-trunc into a narrow extract. For example:
6029   //   i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
6030   //   i32 y = TRUNCATE(i64 x)
6031   //        -- becomes --
6032   //   v16i8 b = BITCAST (v2i64 val)
6033   //   i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
6034   //
6035   // Note: We only run this optimization after type legalization (which often
6036   // creates this pattern) and before operation legalization after which
6037   // we need to be more careful about the vector instructions that we generate.
6038   if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6039       LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
6040
6041     EVT VecTy = N0.getOperand(0).getValueType();
6042     EVT ExTy = N0.getValueType();
6043     EVT TrTy = N->getValueType(0);
6044
6045     unsigned NumElem = VecTy.getVectorNumElements();
6046     unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
6047
6048     EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
6049     assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
6050
6051     SDValue EltNo = N0->getOperand(1);
6052     if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
6053       int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
6054       EVT IndexTy = TLI.getVectorIdxTy();
6055       int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
6056
6057       SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
6058                               NVT, N0.getOperand(0));
6059
6060       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
6061                          SDLoc(N), TrTy, V,
6062                          DAG.getConstant(Index, IndexTy));
6063     }
6064   }
6065
6066   // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
6067   if (N0.getOpcode() == ISD::SELECT) {
6068     EVT SrcVT = N0.getValueType();
6069     if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
6070         TLI.isTruncateFree(SrcVT, VT)) {
6071       SDLoc SL(N0);
6072       SDValue Cond = N0.getOperand(0);
6073       SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
6074       SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
6075       return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
6076     }
6077   }
6078
6079   // Fold a series of buildvector, bitcast, and truncate if possible.
6080   // For example fold
6081   //   (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
6082   //   (2xi32 (buildvector x, y)).
6083   if (Level == AfterLegalizeVectorOps && VT.isVector() &&
6084       N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
6085       N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
6086       N0.getOperand(0).hasOneUse()) {
6087
6088     SDValue BuildVect = N0.getOperand(0);
6089     EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
6090     EVT TruncVecEltTy = VT.getVectorElementType();
6091
6092     // Check that the element types match.
6093     if (BuildVectEltTy == TruncVecEltTy) {
6094       // Now we only need to compute the offset of the truncated elements.
6095       unsigned BuildVecNumElts =  BuildVect.getNumOperands();
6096       unsigned TruncVecNumElts = VT.getVectorNumElements();
6097       unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
6098
6099       assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
6100              "Invalid number of elements");
6101
6102       SmallVector<SDValue, 8> Opnds;
6103       for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
6104         Opnds.push_back(BuildVect.getOperand(i));
6105
6106       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
6107     }
6108   }
6109
6110   // See if we can simplify the input to this truncate through knowledge that
6111   // only the low bits are being used.
6112   // For example "trunc (or (shl x, 8), y)" // -> trunc y
6113   // Currently we only perform this optimization on scalars because vectors
6114   // may have different active low bits.
6115   if (!VT.isVector()) {
6116     SDValue Shorter =
6117       GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
6118                                                VT.getSizeInBits()));
6119     if (Shorter.getNode())
6120       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
6121   }
6122   // fold (truncate (load x)) -> (smaller load x)
6123   // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
6124   if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
6125     SDValue Reduced = ReduceLoadWidth(N);
6126     if (Reduced.getNode())
6127       return Reduced;
6128     // Handle the case where the load remains an extending load even
6129     // after truncation.
6130     if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
6131       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6132       if (!LN0->isVolatile() &&
6133           LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
6134         SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
6135                                          VT, LN0->getChain(), LN0->getBasePtr(),
6136                                          LN0->getMemoryVT(),
6137                                          LN0->getMemOperand());
6138         DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
6139         return NewLoad;
6140       }
6141     }
6142   }
6143   // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
6144   // where ... are all 'undef'.
6145   if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
6146     SmallVector<EVT, 8> VTs;
6147     SDValue V;
6148     unsigned Idx = 0;
6149     unsigned NumDefs = 0;
6150
6151     for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
6152       SDValue X = N0.getOperand(i);
6153       if (X.getOpcode() != ISD::UNDEF) {
6154         V = X;
6155         Idx = i;
6156         NumDefs++;
6157       }
6158       // Stop if more than one members are non-undef.
6159       if (NumDefs > 1)
6160         break;
6161       VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
6162                                      VT.getVectorElementType(),
6163                                      X.getValueType().getVectorNumElements()));
6164     }
6165
6166     if (NumDefs == 0)
6167       return DAG.getUNDEF(VT);
6168
6169     if (NumDefs == 1) {
6170       assert(V.getNode() && "The single defined operand is empty!");
6171       SmallVector<SDValue, 8> Opnds;
6172       for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
6173         if (i != Idx) {
6174           Opnds.push_back(DAG.getUNDEF(VTs[i]));
6175           continue;
6176         }
6177         SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
6178         AddToWorklist(NV.getNode());
6179         Opnds.push_back(NV);
6180       }
6181       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
6182     }
6183   }
6184
6185   // Simplify the operands using demanded-bits information.
6186   if (!VT.isVector() &&
6187       SimplifyDemandedBits(SDValue(N, 0)))
6188     return SDValue(N, 0);
6189
6190   return SDValue();
6191 }
6192
6193 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
6194   SDValue Elt = N->getOperand(i);
6195   if (Elt.getOpcode() != ISD::MERGE_VALUES)
6196     return Elt.getNode();
6197   return Elt.getOperand(Elt.getResNo()).getNode();
6198 }
6199
6200 /// CombineConsecutiveLoads - build_pair (load, load) -> load
6201 /// if load locations are consecutive.
6202 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
6203   assert(N->getOpcode() == ISD::BUILD_PAIR);
6204
6205   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
6206   LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
6207   if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
6208       LD1->getAddressSpace() != LD2->getAddressSpace())
6209     return SDValue();
6210   EVT LD1VT = LD1->getValueType(0);
6211
6212   if (ISD::isNON_EXTLoad(LD2) &&
6213       LD2->hasOneUse() &&
6214       // If both are volatile this would reduce the number of volatile loads.
6215       // If one is volatile it might be ok, but play conservative and bail out.
6216       !LD1->isVolatile() &&
6217       !LD2->isVolatile() &&
6218       DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
6219     unsigned Align = LD1->getAlignment();
6220     unsigned NewAlign = TLI.getDataLayout()->
6221       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6222
6223     if (NewAlign <= Align &&
6224         (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
6225       return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
6226                          LD1->getBasePtr(), LD1->getPointerInfo(),
6227                          false, false, false, Align);
6228   }
6229
6230   return SDValue();
6231 }
6232
6233 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
6234   SDValue N0 = N->getOperand(0);
6235   EVT VT = N->getValueType(0);
6236
6237   // If the input is a BUILD_VECTOR with all constant elements, fold this now.
6238   // Only do this before legalize, since afterward the target may be depending
6239   // on the bitconvert.
6240   // First check to see if this is all constant.
6241   if (!LegalTypes &&
6242       N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
6243       VT.isVector()) {
6244     bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
6245
6246     EVT DestEltVT = N->getValueType(0).getVectorElementType();
6247     assert(!DestEltVT.isVector() &&
6248            "Element type of vector ValueType must not be vector!");
6249     if (isSimple)
6250       return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
6251   }
6252
6253   // If the input is a constant, let getNode fold it.
6254   if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
6255     SDValue Res = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
6256     if (Res.getNode() != N) {
6257       if (!LegalOperations ||
6258           TLI.isOperationLegal(Res.getNode()->getOpcode(), VT))
6259         return Res;
6260
6261       // Folding it resulted in an illegal node, and it's too late to
6262       // do that. Clean up the old node and forego the transformation.
6263       // Ideally this won't happen very often, because instcombine
6264       // and the earlier dagcombine runs (where illegal nodes are
6265       // permitted) should have folded most of them already.
6266       deleteAndRecombine(Res.getNode());
6267     }
6268   }
6269
6270   // (conv (conv x, t1), t2) -> (conv x, t2)
6271   if (N0.getOpcode() == ISD::BITCAST)
6272     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
6273                        N0.getOperand(0));
6274
6275   // fold (conv (load x)) -> (load (conv*)x)
6276   // If the resultant load doesn't need a higher alignment than the original!
6277   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
6278       // Do not change the width of a volatile load.
6279       !cast<LoadSDNode>(N0)->isVolatile() &&
6280       // Do not remove the cast if the types differ in endian layout.
6281       TLI.hasBigEndianPartOrdering(N0.getValueType()) ==
6282       TLI.hasBigEndianPartOrdering(VT) &&
6283       (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
6284       TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
6285     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6286     unsigned Align = TLI.getDataLayout()->
6287       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6288     unsigned OrigAlign = LN0->getAlignment();
6289
6290     if (Align <= OrigAlign) {
6291       SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
6292                                  LN0->getBasePtr(), LN0->getPointerInfo(),
6293                                  LN0->isVolatile(), LN0->isNonTemporal(),
6294                                  LN0->isInvariant(), OrigAlign,
6295                                  LN0->getAAInfo());
6296       AddToWorklist(N);
6297       CombineTo(N0.getNode(),
6298                 DAG.getNode(ISD::BITCAST, SDLoc(N0),
6299                             N0.getValueType(), Load),
6300                 Load.getValue(1));
6301       return Load;
6302     }
6303   }
6304
6305   // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
6306   // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
6307   // This often reduces constant pool loads.
6308   if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
6309        (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
6310       N0.getNode()->hasOneUse() && VT.isInteger() &&
6311       !VT.isVector() && !N0.getValueType().isVector()) {
6312     SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
6313                                   N0.getOperand(0));
6314     AddToWorklist(NewConv.getNode());
6315
6316     APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6317     if (N0.getOpcode() == ISD::FNEG)
6318       return DAG.getNode(ISD::XOR, SDLoc(N), VT,
6319                          NewConv, DAG.getConstant(SignBit, VT));
6320     assert(N0.getOpcode() == ISD::FABS);
6321     return DAG.getNode(ISD::AND, SDLoc(N), VT,
6322                        NewConv, DAG.getConstant(~SignBit, VT));
6323   }
6324
6325   // fold (bitconvert (fcopysign cst, x)) ->
6326   //         (or (and (bitconvert x), sign), (and cst, (not sign)))
6327   // Note that we don't handle (copysign x, cst) because this can always be
6328   // folded to an fneg or fabs.
6329   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
6330       isa<ConstantFPSDNode>(N0.getOperand(0)) &&
6331       VT.isInteger() && !VT.isVector()) {
6332     unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
6333     EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
6334     if (isTypeLegal(IntXVT)) {
6335       SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6336                               IntXVT, N0.getOperand(1));
6337       AddToWorklist(X.getNode());
6338
6339       // If X has a different width than the result/lhs, sext it or truncate it.
6340       unsigned VTWidth = VT.getSizeInBits();
6341       if (OrigXWidth < VTWidth) {
6342         X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
6343         AddToWorklist(X.getNode());
6344       } else if (OrigXWidth > VTWidth) {
6345         // To get the sign bit in the right place, we have to shift it right
6346         // before truncating.
6347         X = DAG.getNode(ISD::SRL, SDLoc(X),
6348                         X.getValueType(), X,
6349                         DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
6350         AddToWorklist(X.getNode());
6351         X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
6352         AddToWorklist(X.getNode());
6353       }
6354
6355       APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6356       X = DAG.getNode(ISD::AND, SDLoc(X), VT,
6357                       X, DAG.getConstant(SignBit, VT));
6358       AddToWorklist(X.getNode());
6359
6360       SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6361                                 VT, N0.getOperand(0));
6362       Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
6363                         Cst, DAG.getConstant(~SignBit, VT));
6364       AddToWorklist(Cst.getNode());
6365
6366       return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
6367     }
6368   }
6369
6370   // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
6371   if (N0.getOpcode() == ISD::BUILD_PAIR) {
6372     SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
6373     if (CombineLD.getNode())
6374       return CombineLD;
6375   }
6376
6377   return SDValue();
6378 }
6379
6380 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
6381   EVT VT = N->getValueType(0);
6382   return CombineConsecutiveLoads(N, VT);
6383 }
6384
6385 /// ConstantFoldBITCASTofBUILD_VECTOR - We know that BV is a build_vector
6386 /// node with Constant, ConstantFP or Undef operands.  DstEltVT indicates the
6387 /// destination element value type.
6388 SDValue DAGCombiner::
6389 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
6390   EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
6391
6392   // If this is already the right type, we're done.
6393   if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
6394
6395   unsigned SrcBitSize = SrcEltVT.getSizeInBits();
6396   unsigned DstBitSize = DstEltVT.getSizeInBits();
6397
6398   // If this is a conversion of N elements of one type to N elements of another
6399   // type, convert each element.  This handles FP<->INT cases.
6400   if (SrcBitSize == DstBitSize) {
6401     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6402                               BV->getValueType(0).getVectorNumElements());
6403
6404     // Due to the FP element handling below calling this routine recursively,
6405     // we can end up with a scalar-to-vector node here.
6406     if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
6407       return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6408                          DAG.getNode(ISD::BITCAST, SDLoc(BV),
6409                                      DstEltVT, BV->getOperand(0)));
6410
6411     SmallVector<SDValue, 8> Ops;
6412     for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6413       SDValue Op = BV->getOperand(i);
6414       // If the vector element type is not legal, the BUILD_VECTOR operands
6415       // are promoted and implicitly truncated.  Make that explicit here.
6416       if (Op.getValueType() != SrcEltVT)
6417         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
6418       Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
6419                                 DstEltVT, Op));
6420       AddToWorklist(Ops.back().getNode());
6421     }
6422     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6423   }
6424
6425   // Otherwise, we're growing or shrinking the elements.  To avoid having to
6426   // handle annoying details of growing/shrinking FP values, we convert them to
6427   // int first.
6428   if (SrcEltVT.isFloatingPoint()) {
6429     // Convert the input float vector to a int vector where the elements are the
6430     // same sizes.
6431     assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!");
6432     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
6433     BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
6434     SrcEltVT = IntVT;
6435   }
6436
6437   // Now we know the input is an integer vector.  If the output is a FP type,
6438   // convert to integer first, then to FP of the right size.
6439   if (DstEltVT.isFloatingPoint()) {
6440     assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!");
6441     EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
6442     SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
6443
6444     // Next, convert to FP elements of the same size.
6445     return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
6446   }
6447
6448   // Okay, we know the src/dst types are both integers of differing types.
6449   // Handling growing first.
6450   assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
6451   if (SrcBitSize < DstBitSize) {
6452     unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
6453
6454     SmallVector<SDValue, 8> Ops;
6455     for (unsigned i = 0, e = BV->getNumOperands(); i != e;
6456          i += NumInputsPerOutput) {
6457       bool isLE = TLI.isLittleEndian();
6458       APInt NewBits = APInt(DstBitSize, 0);
6459       bool EltIsUndef = true;
6460       for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
6461         // Shift the previously computed bits over.
6462         NewBits <<= SrcBitSize;
6463         SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
6464         if (Op.getOpcode() == ISD::UNDEF) continue;
6465         EltIsUndef = false;
6466
6467         NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
6468                    zextOrTrunc(SrcBitSize).zext(DstBitSize);
6469       }
6470
6471       if (EltIsUndef)
6472         Ops.push_back(DAG.getUNDEF(DstEltVT));
6473       else
6474         Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
6475     }
6476
6477     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
6478     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6479   }
6480
6481   // Finally, this must be the case where we are shrinking elements: each input
6482   // turns into multiple outputs.
6483   bool isS2V = ISD::isScalarToVector(BV);
6484   unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
6485   EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6486                             NumOutputsPerInput*BV->getNumOperands());
6487   SmallVector<SDValue, 8> Ops;
6488
6489   for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6490     if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
6491       for (unsigned j = 0; j != NumOutputsPerInput; ++j)
6492         Ops.push_back(DAG.getUNDEF(DstEltVT));
6493       continue;
6494     }
6495
6496     APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
6497                   getAPIntValue().zextOrTrunc(SrcBitSize);
6498
6499     for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
6500       APInt ThisVal = OpVal.trunc(DstBitSize);
6501       Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
6502       if (isS2V && i == 0 && j == 0 && ThisVal.zext(SrcBitSize) == OpVal)
6503         // Simply turn this into a SCALAR_TO_VECTOR of the new type.
6504         return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6505                            Ops[0]);
6506       OpVal = OpVal.lshr(DstBitSize);
6507     }
6508
6509     // For big endian targets, swap the order of the pieces of each element.
6510     if (TLI.isBigEndian())
6511       std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
6512   }
6513
6514   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6515 }
6516
6517 SDValue DAGCombiner::visitFADD(SDNode *N) {
6518   SDValue N0 = N->getOperand(0);
6519   SDValue N1 = N->getOperand(1);
6520   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6521   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6522   EVT VT = N->getValueType(0);
6523
6524   // fold vector ops
6525   if (VT.isVector()) {
6526     SDValue FoldedVOp = SimplifyVBinOp(N);
6527     if (FoldedVOp.getNode()) return FoldedVOp;
6528   }
6529
6530   // fold (fadd c1, c2) -> c1 + c2
6531   if (N0CFP && N1CFP)
6532     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N1);
6533   // canonicalize constant to RHS
6534   if (N0CFP && !N1CFP)
6535     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N0);
6536   // fold (fadd A, 0) -> A
6537   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6538       N1CFP->getValueAPF().isZero())
6539     return N0;
6540   // fold (fadd A, (fneg B)) -> (fsub A, B)
6541   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6542     isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
6543     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0,
6544                        GetNegatedExpression(N1, DAG, LegalOperations));
6545   // fold (fadd (fneg A), B) -> (fsub B, A)
6546   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6547     isNegatibleForFree(N0, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
6548     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N1,
6549                        GetNegatedExpression(N0, DAG, LegalOperations));
6550
6551   // If allowed, fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
6552   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6553       N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
6554       isa<ConstantFPSDNode>(N0.getOperand(1)))
6555     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0.getOperand(0),
6556                        DAG.getNode(ISD::FADD, SDLoc(N), VT,
6557                                    N0.getOperand(1), N1));
6558
6559   // No FP constant should be created after legalization as Instruction
6560   // Selection pass has hard time in dealing with FP constant.
6561   //
6562   // We don't need test this condition for transformation like following, as
6563   // the DAG being transformed implies it is legal to take FP constant as
6564   // operand.
6565   //
6566   //  (fadd (fmul c, x), x) -> (fmul c+1, x)
6567   //
6568   bool AllowNewFpConst = (Level < AfterLegalizeDAG);
6569
6570   // If allow, fold (fadd (fneg x), x) -> 0.0
6571   if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
6572       N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
6573     return DAG.getConstantFP(0.0, VT);
6574
6575     // If allow, fold (fadd x, (fneg x)) -> 0.0
6576   if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
6577       N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
6578     return DAG.getConstantFP(0.0, VT);
6579
6580   // In unsafe math mode, we can fold chains of FADD's of the same value
6581   // into multiplications.  This transform is not safe in general because
6582   // we are reducing the number of rounding steps.
6583   if (DAG.getTarget().Options.UnsafeFPMath &&
6584       TLI.isOperationLegalOrCustom(ISD::FMUL, VT) &&
6585       !N0CFP && !N1CFP) {
6586     if (N0.getOpcode() == ISD::FMUL) {
6587       ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6588       ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
6589
6590       // (fadd (fmul c, x), x) -> (fmul x, c+1)
6591       if (CFP00 && !CFP01 && N0.getOperand(1) == N1) {
6592         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6593                                      SDValue(CFP00, 0),
6594                                      DAG.getConstantFP(1.0, VT));
6595         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6596                            N1, NewCFP);
6597       }
6598
6599       // (fadd (fmul x, c), x) -> (fmul x, c+1)
6600       if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
6601         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6602                                      SDValue(CFP01, 0),
6603                                      DAG.getConstantFP(1.0, VT));
6604         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6605                            N1, NewCFP);
6606       }
6607
6608       // (fadd (fmul c, x), (fadd x, x)) -> (fmul x, c+2)
6609       if (CFP00 && !CFP01 && N1.getOpcode() == ISD::FADD &&
6610           N1.getOperand(0) == N1.getOperand(1) &&
6611           N0.getOperand(1) == N1.getOperand(0)) {
6612         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6613                                      SDValue(CFP00, 0),
6614                                      DAG.getConstantFP(2.0, VT));
6615         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6616                            N0.getOperand(1), NewCFP);
6617       }
6618
6619       // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
6620       if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
6621           N1.getOperand(0) == N1.getOperand(1) &&
6622           N0.getOperand(0) == N1.getOperand(0)) {
6623         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6624                                      SDValue(CFP01, 0),
6625                                      DAG.getConstantFP(2.0, VT));
6626         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6627                            N0.getOperand(0), NewCFP);
6628       }
6629     }
6630
6631     if (N1.getOpcode() == ISD::FMUL) {
6632       ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6633       ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
6634
6635       // (fadd x, (fmul c, x)) -> (fmul x, c+1)
6636       if (CFP10 && !CFP11 && N1.getOperand(1) == N0) {
6637         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6638                                      SDValue(CFP10, 0),
6639                                      DAG.getConstantFP(1.0, VT));
6640         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6641                            N0, NewCFP);
6642       }
6643
6644       // (fadd x, (fmul x, c)) -> (fmul x, c+1)
6645       if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
6646         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6647                                      SDValue(CFP11, 0),
6648                                      DAG.getConstantFP(1.0, VT));
6649         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6650                            N0, NewCFP);
6651       }
6652
6653
6654       // (fadd (fadd x, x), (fmul c, x)) -> (fmul x, c+2)
6655       if (CFP10 && !CFP11 && N0.getOpcode() == ISD::FADD &&
6656           N0.getOperand(0) == N0.getOperand(1) &&
6657           N1.getOperand(1) == N0.getOperand(0)) {
6658         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6659                                      SDValue(CFP10, 0),
6660                                      DAG.getConstantFP(2.0, VT));
6661         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6662                            N1.getOperand(1), NewCFP);
6663       }
6664
6665       // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
6666       if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
6667           N0.getOperand(0) == N0.getOperand(1) &&
6668           N1.getOperand(0) == N0.getOperand(0)) {
6669         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6670                                      SDValue(CFP11, 0),
6671                                      DAG.getConstantFP(2.0, VT));
6672         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6673                            N1.getOperand(0), NewCFP);
6674       }
6675     }
6676
6677     if (N0.getOpcode() == ISD::FADD && AllowNewFpConst) {
6678       ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6679       // (fadd (fadd x, x), x) -> (fmul x, 3.0)
6680       if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
6681           (N0.getOperand(0) == N1))
6682         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6683                            N1, DAG.getConstantFP(3.0, VT));
6684     }
6685
6686     if (N1.getOpcode() == ISD::FADD && AllowNewFpConst) {
6687       ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6688       // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
6689       if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
6690           N1.getOperand(0) == N0)
6691         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6692                            N0, DAG.getConstantFP(3.0, VT));
6693     }
6694
6695     // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
6696     if (AllowNewFpConst &&
6697         N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
6698         N0.getOperand(0) == N0.getOperand(1) &&
6699         N1.getOperand(0) == N1.getOperand(1) &&
6700         N0.getOperand(0) == N1.getOperand(0))
6701       return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6702                          N0.getOperand(0),
6703                          DAG.getConstantFP(4.0, VT));
6704   }
6705
6706   // FADD -> FMA combines:
6707   if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
6708        DAG.getTarget().Options.UnsafeFPMath) &&
6709       DAG.getTarget()
6710           .getSubtargetImpl()
6711           ->getTargetLowering()
6712           ->isFMAFasterThanFMulAndFAdd(VT) &&
6713       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6714
6715     // fold (fadd (fmul x, y), z) -> (fma x, y, z)
6716     if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
6717       return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6718                          N0.getOperand(0), N0.getOperand(1), N1);
6719
6720     // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
6721     // Note: Commutes FADD operands.
6722     if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
6723       return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6724                          N1.getOperand(0), N1.getOperand(1), N0);
6725   }
6726
6727   return SDValue();
6728 }
6729
6730 SDValue DAGCombiner::visitFSUB(SDNode *N) {
6731   SDValue N0 = N->getOperand(0);
6732   SDValue N1 = N->getOperand(1);
6733   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6734   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6735   EVT VT = N->getValueType(0);
6736   SDLoc dl(N);
6737
6738   // fold vector ops
6739   if (VT.isVector()) {
6740     SDValue FoldedVOp = SimplifyVBinOp(N);
6741     if (FoldedVOp.getNode()) return FoldedVOp;
6742   }
6743
6744   // fold (fsub c1, c2) -> c1-c2
6745   if (N0CFP && N1CFP)
6746     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0, N1);
6747   // fold (fsub A, 0) -> A
6748   if (DAG.getTarget().Options.UnsafeFPMath &&
6749       N1CFP && N1CFP->getValueAPF().isZero())
6750     return N0;
6751   // fold (fsub 0, B) -> -B
6752   if (DAG.getTarget().Options.UnsafeFPMath &&
6753       N0CFP && N0CFP->getValueAPF().isZero()) {
6754     if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
6755       return GetNegatedExpression(N1, DAG, LegalOperations);
6756     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6757       return DAG.getNode(ISD::FNEG, dl, VT, N1);
6758   }
6759   // fold (fsub A, (fneg B)) -> (fadd A, B)
6760   if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
6761     return DAG.getNode(ISD::FADD, dl, VT, N0,
6762                        GetNegatedExpression(N1, DAG, LegalOperations));
6763
6764   // If 'unsafe math' is enabled, fold
6765   //    (fsub x, x) -> 0.0 &
6766   //    (fsub x, (fadd x, y)) -> (fneg y) &
6767   //    (fsub x, (fadd y, x)) -> (fneg y)
6768   if (DAG.getTarget().Options.UnsafeFPMath) {
6769     if (N0 == N1)
6770       return DAG.getConstantFP(0.0f, VT);
6771
6772     if (N1.getOpcode() == ISD::FADD) {
6773       SDValue N10 = N1->getOperand(0);
6774       SDValue N11 = N1->getOperand(1);
6775
6776       if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI,
6777                                           &DAG.getTarget().Options))
6778         return GetNegatedExpression(N11, DAG, LegalOperations);
6779
6780       if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI,
6781                                           &DAG.getTarget().Options))
6782         return GetNegatedExpression(N10, DAG, LegalOperations);
6783     }
6784   }
6785
6786   // FSUB -> FMA combines:
6787   if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
6788        DAG.getTarget().Options.UnsafeFPMath) &&
6789       DAG.getTarget()
6790           .getSubtargetImpl()
6791           ->getTargetLowering()
6792           ->isFMAFasterThanFMulAndFAdd(VT) &&
6793       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6794
6795     // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
6796     if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
6797       return DAG.getNode(ISD::FMA, dl, VT,
6798                          N0.getOperand(0), N0.getOperand(1),
6799                          DAG.getNode(ISD::FNEG, dl, VT, N1));
6800
6801     // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
6802     // Note: Commutes FSUB operands.
6803     if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
6804       return DAG.getNode(ISD::FMA, dl, VT,
6805                          DAG.getNode(ISD::FNEG, dl, VT,
6806                          N1.getOperand(0)),
6807                          N1.getOperand(1), N0);
6808
6809     // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
6810     if (N0.getOpcode() == ISD::FNEG &&
6811         N0.getOperand(0).getOpcode() == ISD::FMUL &&
6812         N0->hasOneUse() && N0.getOperand(0).hasOneUse()) {
6813       SDValue N00 = N0.getOperand(0).getOperand(0);
6814       SDValue N01 = N0.getOperand(0).getOperand(1);
6815       return DAG.getNode(ISD::FMA, dl, VT,
6816                          DAG.getNode(ISD::FNEG, dl, VT, N00), N01,
6817                          DAG.getNode(ISD::FNEG, dl, VT, N1));
6818     }
6819   }
6820
6821   return SDValue();
6822 }
6823
6824 SDValue DAGCombiner::visitFMUL(SDNode *N) {
6825   SDValue N0 = N->getOperand(0);
6826   SDValue N1 = N->getOperand(1);
6827   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6828   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6829   EVT VT = N->getValueType(0);
6830   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6831
6832   // fold vector ops
6833   if (VT.isVector()) {
6834     SDValue FoldedVOp = SimplifyVBinOp(N);
6835     if (FoldedVOp.getNode()) return FoldedVOp;
6836   }
6837
6838   // fold (fmul c1, c2) -> c1*c2
6839   if (N0CFP && N1CFP)
6840     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, N1);
6841   // canonicalize constant to RHS
6842   if (N0CFP && !N1CFP)
6843     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, N0);
6844   // fold (fmul A, 0) -> 0
6845   if (DAG.getTarget().Options.UnsafeFPMath &&
6846       N1CFP && N1CFP->getValueAPF().isZero())
6847     return N1;
6848   // fold (fmul A, 0) -> 0, vector edition.
6849   if (DAG.getTarget().Options.UnsafeFPMath &&
6850       ISD::isBuildVectorAllZeros(N1.getNode()))
6851     return N1;
6852   // fold (fmul A, 1.0) -> A
6853   if (N1CFP && N1CFP->isExactlyValue(1.0))
6854     return N0;
6855   // fold (fmul X, 2.0) -> (fadd X, X)
6856   if (N1CFP && N1CFP->isExactlyValue(+2.0))
6857     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N0);
6858   // fold (fmul X, -1.0) -> (fneg X)
6859   if (N1CFP && N1CFP->isExactlyValue(-1.0))
6860     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6861       return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
6862
6863   // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
6864   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
6865                                        &DAG.getTarget().Options)) {
6866     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
6867                                          &DAG.getTarget().Options)) {
6868       // Both can be negated for free, check to see if at least one is cheaper
6869       // negated.
6870       if (LHSNeg == 2 || RHSNeg == 2)
6871         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6872                            GetNegatedExpression(N0, DAG, LegalOperations),
6873                            GetNegatedExpression(N1, DAG, LegalOperations));
6874     }
6875   }
6876
6877   // If allowed, fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
6878   if (DAG.getTarget().Options.UnsafeFPMath &&
6879       N1CFP && N0.getOpcode() == ISD::FMUL &&
6880       N0.getNode()->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
6881     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
6882                        DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6883                                    N0.getOperand(1), N1));
6884
6885   return SDValue();
6886 }
6887
6888 SDValue DAGCombiner::visitFMA(SDNode *N) {
6889   SDValue N0 = N->getOperand(0);
6890   SDValue N1 = N->getOperand(1);
6891   SDValue N2 = N->getOperand(2);
6892   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6893   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6894   EVT VT = N->getValueType(0);
6895   SDLoc dl(N);
6896
6897
6898   // Constant fold FMA.
6899   if (isa<ConstantFPSDNode>(N0) &&
6900       isa<ConstantFPSDNode>(N1) &&
6901       isa<ConstantFPSDNode>(N2)) {
6902     return DAG.getNode(ISD::FMA, dl, VT, N0, N1, N2);
6903   }
6904
6905   if (DAG.getTarget().Options.UnsafeFPMath) {
6906     if (N0CFP && N0CFP->isZero())
6907       return N2;
6908     if (N1CFP && N1CFP->isZero())
6909       return N2;
6910   }
6911   if (N0CFP && N0CFP->isExactlyValue(1.0))
6912     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
6913   if (N1CFP && N1CFP->isExactlyValue(1.0))
6914     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
6915
6916   // Canonicalize (fma c, x, y) -> (fma x, c, y)
6917   if (N0CFP && !N1CFP)
6918     return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
6919
6920   // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
6921   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6922       N2.getOpcode() == ISD::FMUL &&
6923       N0 == N2.getOperand(0) &&
6924       N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
6925     return DAG.getNode(ISD::FMUL, dl, VT, N0,
6926                        DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
6927   }
6928
6929
6930   // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
6931   if (DAG.getTarget().Options.UnsafeFPMath &&
6932       N0.getOpcode() == ISD::FMUL && N1CFP &&
6933       N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
6934     return DAG.getNode(ISD::FMA, dl, VT,
6935                        N0.getOperand(0),
6936                        DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
6937                        N2);
6938   }
6939
6940   // (fma x, 1, y) -> (fadd x, y)
6941   // (fma x, -1, y) -> (fadd (fneg x), y)
6942   if (N1CFP) {
6943     if (N1CFP->isExactlyValue(1.0))
6944       return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
6945
6946     if (N1CFP->isExactlyValue(-1.0) &&
6947         (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
6948       SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
6949       AddToWorklist(RHSNeg.getNode());
6950       return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
6951     }
6952   }
6953
6954   // (fma x, c, x) -> (fmul x, (c+1))
6955   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP && N0 == N2)
6956     return DAG.getNode(ISD::FMUL, dl, VT, N0,
6957                        DAG.getNode(ISD::FADD, dl, VT,
6958                                    N1, DAG.getConstantFP(1.0, VT)));
6959
6960   // (fma x, c, (fneg x)) -> (fmul x, (c-1))
6961   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6962       N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
6963     return DAG.getNode(ISD::FMUL, dl, VT, N0,
6964                        DAG.getNode(ISD::FADD, dl, VT,
6965                                    N1, DAG.getConstantFP(-1.0, VT)));
6966
6967
6968   return SDValue();
6969 }
6970
6971 SDValue DAGCombiner::visitFDIV(SDNode *N) {
6972   SDValue N0 = N->getOperand(0);
6973   SDValue N1 = N->getOperand(1);
6974   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6975   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6976   EVT VT = N->getValueType(0);
6977   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6978
6979   // fold vector ops
6980   if (VT.isVector()) {
6981     SDValue FoldedVOp = SimplifyVBinOp(N);
6982     if (FoldedVOp.getNode()) return FoldedVOp;
6983   }
6984
6985   // fold (fdiv c1, c2) -> c1/c2
6986   if (N0CFP && N1CFP)
6987     return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
6988
6989   // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
6990   if (N1CFP && DAG.getTarget().Options.UnsafeFPMath) {
6991     // Compute the reciprocal 1.0 / c2.
6992     APFloat N1APF = N1CFP->getValueAPF();
6993     APFloat Recip(N1APF.getSemantics(), 1); // 1.0
6994     APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
6995     // Only do the transform if the reciprocal is a legal fp immediate that
6996     // isn't too nasty (eg NaN, denormal, ...).
6997     if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
6998         (!LegalOperations ||
6999          // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
7000          // backend)... we should handle this gracefully after Legalize.
7001          // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
7002          TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
7003          TLI.isFPImmLegal(Recip, VT)))
7004       return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0,
7005                          DAG.getConstantFP(Recip, VT));
7006   }
7007
7008   // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
7009   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
7010                                        &DAG.getTarget().Options)) {
7011     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
7012                                          &DAG.getTarget().Options)) {
7013       // Both can be negated for free, check to see if at least one is cheaper
7014       // negated.
7015       if (LHSNeg == 2 || RHSNeg == 2)
7016         return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
7017                            GetNegatedExpression(N0, DAG, LegalOperations),
7018                            GetNegatedExpression(N1, DAG, LegalOperations));
7019     }
7020   }
7021
7022   return SDValue();
7023 }
7024
7025 SDValue DAGCombiner::visitFREM(SDNode *N) {
7026   SDValue N0 = N->getOperand(0);
7027   SDValue N1 = N->getOperand(1);
7028   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7029   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7030   EVT VT = N->getValueType(0);
7031
7032   // fold (frem c1, c2) -> fmod(c1,c2)
7033   if (N0CFP && N1CFP)
7034     return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
7035
7036   return SDValue();
7037 }
7038
7039 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
7040   SDValue N0 = N->getOperand(0);
7041   SDValue N1 = N->getOperand(1);
7042   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7043   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7044   EVT VT = N->getValueType(0);
7045
7046   if (N0CFP && N1CFP)  // Constant fold
7047     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
7048
7049   if (N1CFP) {
7050     const APFloat& V = N1CFP->getValueAPF();
7051     // copysign(x, c1) -> fabs(x)       iff ispos(c1)
7052     // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
7053     if (!V.isNegative()) {
7054       if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
7055         return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7056     } else {
7057       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
7058         return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
7059                            DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
7060     }
7061   }
7062
7063   // copysign(fabs(x), y) -> copysign(x, y)
7064   // copysign(fneg(x), y) -> copysign(x, y)
7065   // copysign(copysign(x,z), y) -> copysign(x, y)
7066   if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
7067       N0.getOpcode() == ISD::FCOPYSIGN)
7068     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7069                        N0.getOperand(0), N1);
7070
7071   // copysign(x, abs(y)) -> abs(x)
7072   if (N1.getOpcode() == ISD::FABS)
7073     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7074
7075   // copysign(x, copysign(y,z)) -> copysign(x, z)
7076   if (N1.getOpcode() == ISD::FCOPYSIGN)
7077     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7078                        N0, N1.getOperand(1));
7079
7080   // copysign(x, fp_extend(y)) -> copysign(x, y)
7081   // copysign(x, fp_round(y)) -> copysign(x, y)
7082   if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
7083     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7084                        N0, N1.getOperand(0));
7085
7086   return SDValue();
7087 }
7088
7089 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
7090   SDValue N0 = N->getOperand(0);
7091   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
7092   EVT VT = N->getValueType(0);
7093   EVT OpVT = N0.getValueType();
7094
7095   // fold (sint_to_fp c1) -> c1fp
7096   if (N0C &&
7097       // ...but only if the target supports immediate floating-point values
7098       (!LegalOperations ||
7099        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
7100     return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
7101
7102   // If the input is a legal type, and SINT_TO_FP is not legal on this target,
7103   // but UINT_TO_FP is legal on this target, try to convert.
7104   if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
7105       TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
7106     // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
7107     if (DAG.SignBitIsZero(N0))
7108       return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
7109   }
7110
7111   // The next optimizations are desirable only if SELECT_CC can be lowered.
7112   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
7113     // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
7114     if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
7115         !VT.isVector() &&
7116         (!LegalOperations ||
7117          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7118       SDValue Ops[] =
7119         { N0.getOperand(0), N0.getOperand(1),
7120           DAG.getConstantFP(-1.0, VT) , DAG.getConstantFP(0.0, VT),
7121           N0.getOperand(2) };
7122       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7123     }
7124
7125     // fold (sint_to_fp (zext (setcc x, y, cc))) ->
7126     //      (select_cc x, y, 1.0, 0.0,, cc)
7127     if (N0.getOpcode() == ISD::ZERO_EXTEND &&
7128         N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
7129         (!LegalOperations ||
7130          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7131       SDValue Ops[] =
7132         { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
7133           DAG.getConstantFP(1.0, VT) , DAG.getConstantFP(0.0, VT),
7134           N0.getOperand(0).getOperand(2) };
7135       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7136     }
7137   }
7138
7139   return SDValue();
7140 }
7141
7142 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
7143   SDValue N0 = N->getOperand(0);
7144   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
7145   EVT VT = N->getValueType(0);
7146   EVT OpVT = N0.getValueType();
7147
7148   // fold (uint_to_fp c1) -> c1fp
7149   if (N0C &&
7150       // ...but only if the target supports immediate floating-point values
7151       (!LegalOperations ||
7152        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
7153     return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
7154
7155   // If the input is a legal type, and UINT_TO_FP is not legal on this target,
7156   // but SINT_TO_FP is legal on this target, try to convert.
7157   if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
7158       TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
7159     // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
7160     if (DAG.SignBitIsZero(N0))
7161       return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
7162   }
7163
7164   // The next optimizations are desirable only if SELECT_CC can be lowered.
7165   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
7166     // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
7167
7168     if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
7169         (!LegalOperations ||
7170          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7171       SDValue Ops[] =
7172         { N0.getOperand(0), N0.getOperand(1),
7173           DAG.getConstantFP(1.0, VT),  DAG.getConstantFP(0.0, VT),
7174           N0.getOperand(2) };
7175       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7176     }
7177   }
7178
7179   return SDValue();
7180 }
7181
7182 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
7183   SDValue N0 = N->getOperand(0);
7184   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7185   EVT VT = N->getValueType(0);
7186
7187   // fold (fp_to_sint c1fp) -> c1
7188   if (N0CFP)
7189     return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
7190
7191   return SDValue();
7192 }
7193
7194 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
7195   SDValue N0 = N->getOperand(0);
7196   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7197   EVT VT = N->getValueType(0);
7198
7199   // fold (fp_to_uint c1fp) -> c1
7200   if (N0CFP)
7201     return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
7202
7203   return SDValue();
7204 }
7205
7206 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
7207   SDValue N0 = N->getOperand(0);
7208   SDValue N1 = N->getOperand(1);
7209   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7210   EVT VT = N->getValueType(0);
7211
7212   // fold (fp_round c1fp) -> c1fp
7213   if (N0CFP)
7214     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
7215
7216   // fold (fp_round (fp_extend x)) -> x
7217   if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
7218     return N0.getOperand(0);
7219
7220   // fold (fp_round (fp_round x)) -> (fp_round x)
7221   if (N0.getOpcode() == ISD::FP_ROUND) {
7222     // This is a value preserving truncation if both round's are.
7223     bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
7224                    N0.getNode()->getConstantOperandVal(1) == 1;
7225     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0.getOperand(0),
7226                        DAG.getIntPtrConstant(IsTrunc));
7227   }
7228
7229   // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
7230   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
7231     SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
7232                               N0.getOperand(0), N1);
7233     AddToWorklist(Tmp.getNode());
7234     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7235                        Tmp, N0.getOperand(1));
7236   }
7237
7238   return SDValue();
7239 }
7240
7241 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
7242   SDValue N0 = N->getOperand(0);
7243   EVT VT = N->getValueType(0);
7244   EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
7245   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7246
7247   // fold (fp_round_inreg c1fp) -> c1fp
7248   if (N0CFP && isTypeLegal(EVT)) {
7249     SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
7250     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, Round);
7251   }
7252
7253   return SDValue();
7254 }
7255
7256 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
7257   SDValue N0 = N->getOperand(0);
7258   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7259   EVT VT = N->getValueType(0);
7260
7261   // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
7262   if (N->hasOneUse() &&
7263       N->use_begin()->getOpcode() == ISD::FP_ROUND)
7264     return SDValue();
7265
7266   // fold (fp_extend c1fp) -> c1fp
7267   if (N0CFP)
7268     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
7269
7270   // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
7271   // value of X.
7272   if (N0.getOpcode() == ISD::FP_ROUND
7273       && N0.getNode()->getConstantOperandVal(1) == 1) {
7274     SDValue In = N0.getOperand(0);
7275     if (In.getValueType() == VT) return In;
7276     if (VT.bitsLT(In.getValueType()))
7277       return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
7278                          In, N0.getOperand(1));
7279     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
7280   }
7281
7282   // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
7283   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7284        TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType())) {
7285     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7286     SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
7287                                      LN0->getChain(),
7288                                      LN0->getBasePtr(), N0.getValueType(),
7289                                      LN0->getMemOperand());
7290     CombineTo(N, ExtLoad);
7291     CombineTo(N0.getNode(),
7292               DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
7293                           N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
7294               ExtLoad.getValue(1));
7295     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7296   }
7297
7298   return SDValue();
7299 }
7300
7301 SDValue DAGCombiner::visitFNEG(SDNode *N) {
7302   SDValue N0 = N->getOperand(0);
7303   EVT VT = N->getValueType(0);
7304
7305   // Constant fold FNEG.
7306   if (isa<ConstantFPSDNode>(N0))
7307     return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N->getOperand(0));
7308
7309   if (VT.isVector()) {
7310     SDValue FoldedVOp = SimplifyVUnaryOp(N);
7311     if (FoldedVOp.getNode()) return FoldedVOp;
7312   }
7313
7314   if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
7315                          &DAG.getTarget().Options))
7316     return GetNegatedExpression(N0, DAG, LegalOperations);
7317
7318   // Transform fneg(bitconvert(x)) -> bitconvert(x^sign) to avoid loading
7319   // constant pool values.
7320   // TODO: We can also optimize for vectors here, but we need to make sure
7321   // that the sign mask is created properly for each vector element.
7322   if (!TLI.isFNegFree(VT) && N0.getOpcode() == ISD::BITCAST &&
7323       !VT.isVector() &&
7324       N0.getNode()->hasOneUse() &&
7325       N0.getOperand(0).getValueType().isInteger()) {
7326     SDValue Int = N0.getOperand(0);
7327     EVT IntVT = Int.getValueType();
7328     if (IntVT.isInteger() && !IntVT.isVector()) {
7329       Int = DAG.getNode(ISD::XOR, SDLoc(N0), IntVT, Int,
7330               DAG.getConstant(APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
7331       AddToWorklist(Int.getNode());
7332       return DAG.getNode(ISD::BITCAST, SDLoc(N),
7333                          VT, Int);
7334     }
7335   }
7336
7337   // (fneg (fmul c, x)) -> (fmul -c, x)
7338   if (N0.getOpcode() == ISD::FMUL) {
7339     ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
7340     if (CFP1) {
7341       APFloat CVal = CFP1->getValueAPF();
7342       CVal.changeSign();
7343       if (Level >= AfterLegalizeDAG &&
7344           (TLI.isFPImmLegal(CVal, N->getValueType(0)) ||
7345            TLI.isOperationLegal(ISD::ConstantFP, N->getValueType(0))))
7346         return DAG.getNode(
7347             ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
7348             DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0.getOperand(1)));
7349     }
7350   }
7351
7352   return SDValue();
7353 }
7354
7355 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
7356   SDValue N0 = N->getOperand(0);
7357   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7358   EVT VT = N->getValueType(0);
7359
7360   // fold (fceil c1) -> fceil(c1)
7361   if (N0CFP)
7362     return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
7363
7364   return SDValue();
7365 }
7366
7367 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
7368   SDValue N0 = N->getOperand(0);
7369   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7370   EVT VT = N->getValueType(0);
7371
7372   // fold (ftrunc c1) -> ftrunc(c1)
7373   if (N0CFP)
7374     return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
7375
7376   return SDValue();
7377 }
7378
7379 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
7380   SDValue N0 = N->getOperand(0);
7381   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7382   EVT VT = N->getValueType(0);
7383
7384   // fold (ffloor c1) -> ffloor(c1)
7385   if (N0CFP)
7386     return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
7387
7388   return SDValue();
7389 }
7390
7391 SDValue DAGCombiner::visitFABS(SDNode *N) {
7392   SDValue N0 = N->getOperand(0);
7393   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7394   EVT VT = N->getValueType(0);
7395
7396   if (VT.isVector()) {
7397     SDValue FoldedVOp = SimplifyVUnaryOp(N);
7398     if (FoldedVOp.getNode()) return FoldedVOp;
7399   }
7400
7401   // fold (fabs c1) -> fabs(c1)
7402   if (N0CFP)
7403     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7404   // fold (fabs (fabs x)) -> (fabs x)
7405   if (N0.getOpcode() == ISD::FABS)
7406     return N->getOperand(0);
7407   // fold (fabs (fneg x)) -> (fabs x)
7408   // fold (fabs (fcopysign x, y)) -> (fabs x)
7409   if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
7410     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
7411
7412   // Transform fabs(bitconvert(x)) -> bitconvert(x&~sign) to avoid loading
7413   // constant pool values.
7414   // TODO: We can also optimize for vectors here, but we need to make sure
7415   // that the sign mask is created properly for each vector element.
7416   if (!TLI.isFAbsFree(VT) &&
7417       N0.getOpcode() == ISD::BITCAST && N0.getNode()->hasOneUse() &&
7418       N0.getOperand(0).getValueType().isInteger() &&
7419       !VT.isVector()) {
7420     SDValue Int = N0.getOperand(0);
7421     EVT IntVT = Int.getValueType();
7422     if (IntVT.isInteger() && !IntVT.isVector()) {
7423       Int = DAG.getNode(ISD::AND, SDLoc(N0), IntVT, Int,
7424              DAG.getConstant(~APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
7425       AddToWorklist(Int.getNode());
7426       return DAG.getNode(ISD::BITCAST, SDLoc(N),
7427                          N->getValueType(0), Int);
7428     }
7429   }
7430
7431   return SDValue();
7432 }
7433
7434 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
7435   SDValue Chain = N->getOperand(0);
7436   SDValue N1 = N->getOperand(1);
7437   SDValue N2 = N->getOperand(2);
7438
7439   // If N is a constant we could fold this into a fallthrough or unconditional
7440   // branch. However that doesn't happen very often in normal code, because
7441   // Instcombine/SimplifyCFG should have handled the available opportunities.
7442   // If we did this folding here, it would be necessary to update the
7443   // MachineBasicBlock CFG, which is awkward.
7444
7445   // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
7446   // on the target.
7447   if (N1.getOpcode() == ISD::SETCC &&
7448       TLI.isOperationLegalOrCustom(ISD::BR_CC,
7449                                    N1.getOperand(0).getValueType())) {
7450     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7451                        Chain, N1.getOperand(2),
7452                        N1.getOperand(0), N1.getOperand(1), N2);
7453   }
7454
7455   if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
7456       ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
7457        (N1.getOperand(0).hasOneUse() &&
7458         N1.getOperand(0).getOpcode() == ISD::SRL))) {
7459     SDNode *Trunc = nullptr;
7460     if (N1.getOpcode() == ISD::TRUNCATE) {
7461       // Look pass the truncate.
7462       Trunc = N1.getNode();
7463       N1 = N1.getOperand(0);
7464     }
7465
7466     // Match this pattern so that we can generate simpler code:
7467     //
7468     //   %a = ...
7469     //   %b = and i32 %a, 2
7470     //   %c = srl i32 %b, 1
7471     //   brcond i32 %c ...
7472     //
7473     // into
7474     //
7475     //   %a = ...
7476     //   %b = and i32 %a, 2
7477     //   %c = setcc eq %b, 0
7478     //   brcond %c ...
7479     //
7480     // This applies only when the AND constant value has one bit set and the
7481     // SRL constant is equal to the log2 of the AND constant. The back-end is
7482     // smart enough to convert the result into a TEST/JMP sequence.
7483     SDValue Op0 = N1.getOperand(0);
7484     SDValue Op1 = N1.getOperand(1);
7485
7486     if (Op0.getOpcode() == ISD::AND &&
7487         Op1.getOpcode() == ISD::Constant) {
7488       SDValue AndOp1 = Op0.getOperand(1);
7489
7490       if (AndOp1.getOpcode() == ISD::Constant) {
7491         const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
7492
7493         if (AndConst.isPowerOf2() &&
7494             cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
7495           SDValue SetCC =
7496             DAG.getSetCC(SDLoc(N),
7497                          getSetCCResultType(Op0.getValueType()),
7498                          Op0, DAG.getConstant(0, Op0.getValueType()),
7499                          ISD::SETNE);
7500
7501           SDValue NewBRCond = DAG.getNode(ISD::BRCOND, SDLoc(N),
7502                                           MVT::Other, Chain, SetCC, N2);
7503           // Don't add the new BRCond into the worklist or else SimplifySelectCC
7504           // will convert it back to (X & C1) >> C2.
7505           CombineTo(N, NewBRCond, false);
7506           // Truncate is dead.
7507           if (Trunc)
7508             deleteAndRecombine(Trunc);
7509           // Replace the uses of SRL with SETCC
7510           WorklistRemover DeadNodes(*this);
7511           DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
7512           deleteAndRecombine(N1.getNode());
7513           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7514         }
7515       }
7516     }
7517
7518     if (Trunc)
7519       // Restore N1 if the above transformation doesn't match.
7520       N1 = N->getOperand(1);
7521   }
7522
7523   // Transform br(xor(x, y)) -> br(x != y)
7524   // Transform br(xor(xor(x,y), 1)) -> br (x == y)
7525   if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
7526     SDNode *TheXor = N1.getNode();
7527     SDValue Op0 = TheXor->getOperand(0);
7528     SDValue Op1 = TheXor->getOperand(1);
7529     if (Op0.getOpcode() == Op1.getOpcode()) {
7530       // Avoid missing important xor optimizations.
7531       SDValue Tmp = visitXOR(TheXor);
7532       if (Tmp.getNode()) {
7533         if (Tmp.getNode() != TheXor) {
7534           DEBUG(dbgs() << "\nReplacing.8 ";
7535                 TheXor->dump(&DAG);
7536                 dbgs() << "\nWith: ";
7537                 Tmp.getNode()->dump(&DAG);
7538                 dbgs() << '\n');
7539           WorklistRemover DeadNodes(*this);
7540           DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
7541           deleteAndRecombine(TheXor);
7542           return DAG.getNode(ISD::BRCOND, SDLoc(N),
7543                              MVT::Other, Chain, Tmp, N2);
7544         }
7545
7546         // visitXOR has changed XOR's operands or replaced the XOR completely,
7547         // bail out.
7548         return SDValue(N, 0);
7549       }
7550     }
7551
7552     if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
7553       bool Equal = false;
7554       if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
7555         if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
7556             Op0.getOpcode() == ISD::XOR) {
7557           TheXor = Op0.getNode();
7558           Equal = true;
7559         }
7560
7561       EVT SetCCVT = N1.getValueType();
7562       if (LegalTypes)
7563         SetCCVT = getSetCCResultType(SetCCVT);
7564       SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
7565                                    SetCCVT,
7566                                    Op0, Op1,
7567                                    Equal ? ISD::SETEQ : ISD::SETNE);
7568       // Replace the uses of XOR with SETCC
7569       WorklistRemover DeadNodes(*this);
7570       DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
7571       deleteAndRecombine(N1.getNode());
7572       return DAG.getNode(ISD::BRCOND, SDLoc(N),
7573                          MVT::Other, Chain, SetCC, N2);
7574     }
7575   }
7576
7577   return SDValue();
7578 }
7579
7580 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
7581 //
7582 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
7583   CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
7584   SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
7585
7586   // If N is a constant we could fold this into a fallthrough or unconditional
7587   // branch. However that doesn't happen very often in normal code, because
7588   // Instcombine/SimplifyCFG should have handled the available opportunities.
7589   // If we did this folding here, it would be necessary to update the
7590   // MachineBasicBlock CFG, which is awkward.
7591
7592   // Use SimplifySetCC to simplify SETCC's.
7593   SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
7594                                CondLHS, CondRHS, CC->get(), SDLoc(N),
7595                                false);
7596   if (Simp.getNode()) AddToWorklist(Simp.getNode());
7597
7598   // fold to a simpler setcc
7599   if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
7600     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7601                        N->getOperand(0), Simp.getOperand(2),
7602                        Simp.getOperand(0), Simp.getOperand(1),
7603                        N->getOperand(4));
7604
7605   return SDValue();
7606 }
7607
7608 /// canFoldInAddressingMode - Return true if 'Use' is a load or a store that
7609 /// uses N as its base pointer and that N may be folded in the load / store
7610 /// addressing mode.
7611 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
7612                                     SelectionDAG &DAG,
7613                                     const TargetLowering &TLI) {
7614   EVT VT;
7615   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(Use)) {
7616     if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
7617       return false;
7618     VT = Use->getValueType(0);
7619   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(Use)) {
7620     if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
7621       return false;
7622     VT = ST->getValue().getValueType();
7623   } else
7624     return false;
7625
7626   TargetLowering::AddrMode AM;
7627   if (N->getOpcode() == ISD::ADD) {
7628     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7629     if (Offset)
7630       // [reg +/- imm]
7631       AM.BaseOffs = Offset->getSExtValue();
7632     else
7633       // [reg +/- reg]
7634       AM.Scale = 1;
7635   } else if (N->getOpcode() == ISD::SUB) {
7636     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7637     if (Offset)
7638       // [reg +/- imm]
7639       AM.BaseOffs = -Offset->getSExtValue();
7640     else
7641       // [reg +/- reg]
7642       AM.Scale = 1;
7643   } else
7644     return false;
7645
7646   return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
7647 }
7648
7649 /// CombineToPreIndexedLoadStore - Try turning a load / store into a
7650 /// pre-indexed load / store when the base pointer is an add or subtract
7651 /// and it has other uses besides the load / store. After the
7652 /// transformation, the new indexed load / store has effectively folded
7653 /// the add / subtract in and all of its other uses are redirected to the
7654 /// new load / store.
7655 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
7656   if (Level < AfterLegalizeDAG)
7657     return false;
7658
7659   bool isLoad = true;
7660   SDValue Ptr;
7661   EVT VT;
7662   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
7663     if (LD->isIndexed())
7664       return false;
7665     VT = LD->getMemoryVT();
7666     if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
7667         !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
7668       return false;
7669     Ptr = LD->getBasePtr();
7670   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
7671     if (ST->isIndexed())
7672       return false;
7673     VT = ST->getMemoryVT();
7674     if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
7675         !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
7676       return false;
7677     Ptr = ST->getBasePtr();
7678     isLoad = false;
7679   } else {
7680     return false;
7681   }
7682
7683   // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
7684   // out.  There is no reason to make this a preinc/predec.
7685   if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
7686       Ptr.getNode()->hasOneUse())
7687     return false;
7688
7689   // Ask the target to do addressing mode selection.
7690   SDValue BasePtr;
7691   SDValue Offset;
7692   ISD::MemIndexedMode AM = ISD::UNINDEXED;
7693   if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
7694     return false;
7695
7696   // Backends without true r+i pre-indexed forms may need to pass a
7697   // constant base with a variable offset so that constant coercion
7698   // will work with the patterns in canonical form.
7699   bool Swapped = false;
7700   if (isa<ConstantSDNode>(BasePtr)) {
7701     std::swap(BasePtr, Offset);
7702     Swapped = true;
7703   }
7704
7705   // Don't create a indexed load / store with zero offset.
7706   if (isa<ConstantSDNode>(Offset) &&
7707       cast<ConstantSDNode>(Offset)->isNullValue())
7708     return false;
7709
7710   // Try turning it into a pre-indexed load / store except when:
7711   // 1) The new base ptr is a frame index.
7712   // 2) If N is a store and the new base ptr is either the same as or is a
7713   //    predecessor of the value being stored.
7714   // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
7715   //    that would create a cycle.
7716   // 4) All uses are load / store ops that use it as old base ptr.
7717
7718   // Check #1.  Preinc'ing a frame index would require copying the stack pointer
7719   // (plus the implicit offset) to a register to preinc anyway.
7720   if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7721     return false;
7722
7723   // Check #2.
7724   if (!isLoad) {
7725     SDValue Val = cast<StoreSDNode>(N)->getValue();
7726     if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
7727       return false;
7728   }
7729
7730   // If the offset is a constant, there may be other adds of constants that
7731   // can be folded with this one. We should do this to avoid having to keep
7732   // a copy of the original base pointer.
7733   SmallVector<SDNode *, 16> OtherUses;
7734   if (isa<ConstantSDNode>(Offset))
7735     for (SDNode *Use : BasePtr.getNode()->uses()) {
7736       if (Use == Ptr.getNode())
7737         continue;
7738
7739       if (Use->isPredecessorOf(N))
7740         continue;
7741
7742       if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) {
7743         OtherUses.clear();
7744         break;
7745       }
7746
7747       SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1);
7748       if (Op1.getNode() == BasePtr.getNode())
7749         std::swap(Op0, Op1);
7750       assert(Op0.getNode() == BasePtr.getNode() &&
7751              "Use of ADD/SUB but not an operand");
7752
7753       if (!isa<ConstantSDNode>(Op1)) {
7754         OtherUses.clear();
7755         break;
7756       }
7757
7758       // FIXME: In some cases, we can be smarter about this.
7759       if (Op1.getValueType() != Offset.getValueType()) {
7760         OtherUses.clear();
7761         break;
7762       }
7763
7764       OtherUses.push_back(Use);
7765     }
7766
7767   if (Swapped)
7768     std::swap(BasePtr, Offset);
7769
7770   // Now check for #3 and #4.
7771   bool RealUse = false;
7772
7773   // Caches for hasPredecessorHelper
7774   SmallPtrSet<const SDNode *, 32> Visited;
7775   SmallVector<const SDNode *, 16> Worklist;
7776
7777   for (SDNode *Use : Ptr.getNode()->uses()) {
7778     if (Use == N)
7779       continue;
7780     if (N->hasPredecessorHelper(Use, Visited, Worklist))
7781       return false;
7782
7783     // If Ptr may be folded in addressing mode of other use, then it's
7784     // not profitable to do this transformation.
7785     if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
7786       RealUse = true;
7787   }
7788
7789   if (!RealUse)
7790     return false;
7791
7792   SDValue Result;
7793   if (isLoad)
7794     Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
7795                                 BasePtr, Offset, AM);
7796   else
7797     Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
7798                                  BasePtr, Offset, AM);
7799   ++PreIndexedNodes;
7800   ++NodesCombined;
7801   DEBUG(dbgs() << "\nReplacing.4 ";
7802         N->dump(&DAG);
7803         dbgs() << "\nWith: ";
7804         Result.getNode()->dump(&DAG);
7805         dbgs() << '\n');
7806   WorklistRemover DeadNodes(*this);
7807   if (isLoad) {
7808     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7809     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
7810   } else {
7811     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
7812   }
7813
7814   // Finally, since the node is now dead, remove it from the graph.
7815   deleteAndRecombine(N);
7816
7817   if (Swapped)
7818     std::swap(BasePtr, Offset);
7819
7820   // Replace other uses of BasePtr that can be updated to use Ptr
7821   for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
7822     unsigned OffsetIdx = 1;
7823     if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
7824       OffsetIdx = 0;
7825     assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
7826            BasePtr.getNode() && "Expected BasePtr operand");
7827
7828     // We need to replace ptr0 in the following expression:
7829     //   x0 * offset0 + y0 * ptr0 = t0
7830     // knowing that
7831     //   x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
7832     //
7833     // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
7834     // indexed load/store and the expresion that needs to be re-written.
7835     //
7836     // Therefore, we have:
7837     //   t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
7838
7839     ConstantSDNode *CN =
7840       cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
7841     int X0, X1, Y0, Y1;
7842     APInt Offset0 = CN->getAPIntValue();
7843     APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
7844
7845     X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
7846     Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
7847     X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
7848     Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
7849
7850     unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
7851
7852     APInt CNV = Offset0;
7853     if (X0 < 0) CNV = -CNV;
7854     if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
7855     else CNV = CNV - Offset1;
7856
7857     // We can now generate the new expression.
7858     SDValue NewOp1 = DAG.getConstant(CNV, CN->getValueType(0));
7859     SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
7860
7861     SDValue NewUse = DAG.getNode(Opcode,
7862                                  SDLoc(OtherUses[i]),
7863                                  OtherUses[i]->getValueType(0), NewOp1, NewOp2);
7864     DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
7865     deleteAndRecombine(OtherUses[i]);
7866   }
7867
7868   // Replace the uses of Ptr with uses of the updated base value.
7869   DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
7870   deleteAndRecombine(Ptr.getNode());
7871
7872   return true;
7873 }
7874
7875 /// CombineToPostIndexedLoadStore - Try to combine a load / store with a
7876 /// add / sub of the base pointer node into a post-indexed load / store.
7877 /// The transformation folded the add / subtract into the new indexed
7878 /// load / store effectively and all of its uses are redirected to the
7879 /// new load / store.
7880 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
7881   if (Level < AfterLegalizeDAG)
7882     return false;
7883
7884   bool isLoad = true;
7885   SDValue Ptr;
7886   EVT VT;
7887   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
7888     if (LD->isIndexed())
7889       return false;
7890     VT = LD->getMemoryVT();
7891     if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
7892         !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
7893       return false;
7894     Ptr = LD->getBasePtr();
7895   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
7896     if (ST->isIndexed())
7897       return false;
7898     VT = ST->getMemoryVT();
7899     if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
7900         !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
7901       return false;
7902     Ptr = ST->getBasePtr();
7903     isLoad = false;
7904   } else {
7905     return false;
7906   }
7907
7908   if (Ptr.getNode()->hasOneUse())
7909     return false;
7910
7911   for (SDNode *Op : Ptr.getNode()->uses()) {
7912     if (Op == N ||
7913         (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
7914       continue;
7915
7916     SDValue BasePtr;
7917     SDValue Offset;
7918     ISD::MemIndexedMode AM = ISD::UNINDEXED;
7919     if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
7920       // Don't create a indexed load / store with zero offset.
7921       if (isa<ConstantSDNode>(Offset) &&
7922           cast<ConstantSDNode>(Offset)->isNullValue())
7923         continue;
7924
7925       // Try turning it into a post-indexed load / store except when
7926       // 1) All uses are load / store ops that use it as base ptr (and
7927       //    it may be folded as addressing mmode).
7928       // 2) Op must be independent of N, i.e. Op is neither a predecessor
7929       //    nor a successor of N. Otherwise, if Op is folded that would
7930       //    create a cycle.
7931
7932       if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7933         continue;
7934
7935       // Check for #1.
7936       bool TryNext = false;
7937       for (SDNode *Use : BasePtr.getNode()->uses()) {
7938         if (Use == Ptr.getNode())
7939           continue;
7940
7941         // If all the uses are load / store addresses, then don't do the
7942         // transformation.
7943         if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
7944           bool RealUse = false;
7945           for (SDNode *UseUse : Use->uses()) {
7946             if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
7947               RealUse = true;
7948           }
7949
7950           if (!RealUse) {
7951             TryNext = true;
7952             break;
7953           }
7954         }
7955       }
7956
7957       if (TryNext)
7958         continue;
7959
7960       // Check for #2
7961       if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
7962         SDValue Result = isLoad
7963           ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
7964                                BasePtr, Offset, AM)
7965           : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
7966                                 BasePtr, Offset, AM);
7967         ++PostIndexedNodes;
7968         ++NodesCombined;
7969         DEBUG(dbgs() << "\nReplacing.5 ";
7970               N->dump(&DAG);
7971               dbgs() << "\nWith: ";
7972               Result.getNode()->dump(&DAG);
7973               dbgs() << '\n');
7974         WorklistRemover DeadNodes(*this);
7975         if (isLoad) {
7976           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7977           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
7978         } else {
7979           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
7980         }
7981
7982         // Finally, since the node is now dead, remove it from the graph.
7983         deleteAndRecombine(N);
7984
7985         // Replace the uses of Use with uses of the updated base value.
7986         DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
7987                                       Result.getValue(isLoad ? 1 : 0));
7988         deleteAndRecombine(Op);
7989         return true;
7990       }
7991     }
7992   }
7993
7994   return false;
7995 }
7996
7997 SDValue DAGCombiner::visitLOAD(SDNode *N) {
7998   LoadSDNode *LD  = cast<LoadSDNode>(N);
7999   SDValue Chain = LD->getChain();
8000   SDValue Ptr   = LD->getBasePtr();
8001
8002   // If load is not volatile and there are no uses of the loaded value (and
8003   // the updated indexed value in case of indexed loads), change uses of the
8004   // chain value into uses of the chain input (i.e. delete the dead load).
8005   if (!LD->isVolatile()) {
8006     if (N->getValueType(1) == MVT::Other) {
8007       // Unindexed loads.
8008       if (!N->hasAnyUseOfValue(0)) {
8009         // It's not safe to use the two value CombineTo variant here. e.g.
8010         // v1, chain2 = load chain1, loc
8011         // v2, chain3 = load chain2, loc
8012         // v3         = add v2, c
8013         // Now we replace use of chain2 with chain1.  This makes the second load
8014         // isomorphic to the one we are deleting, and thus makes this load live.
8015         DEBUG(dbgs() << "\nReplacing.6 ";
8016               N->dump(&DAG);
8017               dbgs() << "\nWith chain: ";
8018               Chain.getNode()->dump(&DAG);
8019               dbgs() << "\n");
8020         WorklistRemover DeadNodes(*this);
8021         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
8022
8023         if (N->use_empty())
8024           deleteAndRecombine(N);
8025
8026         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
8027       }
8028     } else {
8029       // Indexed loads.
8030       assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
8031       if (!N->hasAnyUseOfValue(0) && !N->hasAnyUseOfValue(1)) {
8032         SDValue Undef = DAG.getUNDEF(N->getValueType(0));
8033         DEBUG(dbgs() << "\nReplacing.7 ";
8034               N->dump(&DAG);
8035               dbgs() << "\nWith: ";
8036               Undef.getNode()->dump(&DAG);
8037               dbgs() << " and 2 other values\n");
8038         WorklistRemover DeadNodes(*this);
8039         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
8040         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1),
8041                                       DAG.getUNDEF(N->getValueType(1)));
8042         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
8043         deleteAndRecombine(N);
8044         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
8045       }
8046     }
8047   }
8048
8049   // If this load is directly stored, replace the load value with the stored
8050   // value.
8051   // TODO: Handle store large -> read small portion.
8052   // TODO: Handle TRUNCSTORE/LOADEXT
8053   if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
8054     if (ISD::isNON_TRUNCStore(Chain.getNode())) {
8055       StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
8056       if (PrevST->getBasePtr() == Ptr &&
8057           PrevST->getValue().getValueType() == N->getValueType(0))
8058       return CombineTo(N, Chain.getOperand(1), Chain);
8059     }
8060   }
8061
8062   // Try to infer better alignment information than the load already has.
8063   if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
8064     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
8065       if (Align > LD->getMemOperand()->getBaseAlignment()) {
8066         SDValue NewLoad =
8067                DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
8068                               LD->getValueType(0),
8069                               Chain, Ptr, LD->getPointerInfo(),
8070                               LD->getMemoryVT(),
8071                               LD->isVolatile(), LD->isNonTemporal(),
8072                               LD->isInvariant(), Align, LD->getAAInfo());
8073         return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
8074       }
8075     }
8076   }
8077
8078   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
8079     TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
8080 #ifndef NDEBUG
8081   if (CombinerAAOnlyFunc.getNumOccurrences() &&
8082       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
8083     UseAA = false;
8084 #endif
8085   if (UseAA && LD->isUnindexed()) {
8086     // Walk up chain skipping non-aliasing memory nodes.
8087     SDValue BetterChain = FindBetterChain(N, Chain);
8088
8089     // If there is a better chain.
8090     if (Chain != BetterChain) {
8091       SDValue ReplLoad;
8092
8093       // Replace the chain to void dependency.
8094       if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
8095         ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
8096                                BetterChain, Ptr, LD->getMemOperand());
8097       } else {
8098         ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
8099                                   LD->getValueType(0),
8100                                   BetterChain, Ptr, LD->getMemoryVT(),
8101                                   LD->getMemOperand());
8102       }
8103
8104       // Create token factor to keep old chain connected.
8105       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
8106                                   MVT::Other, Chain, ReplLoad.getValue(1));
8107
8108       // Make sure the new and old chains are cleaned up.
8109       AddToWorklist(Token.getNode());
8110
8111       // Replace uses with load result and token factor. Don't add users
8112       // to work list.
8113       return CombineTo(N, ReplLoad.getValue(0), Token, false);
8114     }
8115   }
8116
8117   // Try transforming N to an indexed load.
8118   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
8119     return SDValue(N, 0);
8120
8121   // Try to slice up N to more direct loads if the slices are mapped to
8122   // different register banks or pairing can take place.
8123   if (SliceUpLoad(N))
8124     return SDValue(N, 0);
8125
8126   return SDValue();
8127 }
8128
8129 namespace {
8130 /// \brief Helper structure used to slice a load in smaller loads.
8131 /// Basically a slice is obtained from the following sequence:
8132 /// Origin = load Ty1, Base
8133 /// Shift = srl Ty1 Origin, CstTy Amount
8134 /// Inst = trunc Shift to Ty2
8135 ///
8136 /// Then, it will be rewriten into:
8137 /// Slice = load SliceTy, Base + SliceOffset
8138 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
8139 ///
8140 /// SliceTy is deduced from the number of bits that are actually used to
8141 /// build Inst.
8142 struct LoadedSlice {
8143   /// \brief Helper structure used to compute the cost of a slice.
8144   struct Cost {
8145     /// Are we optimizing for code size.
8146     bool ForCodeSize;
8147     /// Various cost.
8148     unsigned Loads;
8149     unsigned Truncates;
8150     unsigned CrossRegisterBanksCopies;
8151     unsigned ZExts;
8152     unsigned Shift;
8153
8154     Cost(bool ForCodeSize = false)
8155         : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
8156           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
8157
8158     /// \brief Get the cost of one isolated slice.
8159     Cost(const LoadedSlice &LS, bool ForCodeSize = false)
8160         : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
8161           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
8162       EVT TruncType = LS.Inst->getValueType(0);
8163       EVT LoadedType = LS.getLoadedType();
8164       if (TruncType != LoadedType &&
8165           !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
8166         ZExts = 1;
8167     }
8168
8169     /// \brief Account for slicing gain in the current cost.
8170     /// Slicing provide a few gains like removing a shift or a
8171     /// truncate. This method allows to grow the cost of the original
8172     /// load with the gain from this slice.
8173     void addSliceGain(const LoadedSlice &LS) {
8174       // Each slice saves a truncate.
8175       const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
8176       if (!TLI.isTruncateFree(LS.Inst->getValueType(0),
8177                               LS.Inst->getOperand(0).getValueType()))
8178         ++Truncates;
8179       // If there is a shift amount, this slice gets rid of it.
8180       if (LS.Shift)
8181         ++Shift;
8182       // If this slice can merge a cross register bank copy, account for it.
8183       if (LS.canMergeExpensiveCrossRegisterBankCopy())
8184         ++CrossRegisterBanksCopies;
8185     }
8186
8187     Cost &operator+=(const Cost &RHS) {
8188       Loads += RHS.Loads;
8189       Truncates += RHS.Truncates;
8190       CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
8191       ZExts += RHS.ZExts;
8192       Shift += RHS.Shift;
8193       return *this;
8194     }
8195
8196     bool operator==(const Cost &RHS) const {
8197       return Loads == RHS.Loads && Truncates == RHS.Truncates &&
8198              CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
8199              ZExts == RHS.ZExts && Shift == RHS.Shift;
8200     }
8201
8202     bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
8203
8204     bool operator<(const Cost &RHS) const {
8205       // Assume cross register banks copies are as expensive as loads.
8206       // FIXME: Do we want some more target hooks?
8207       unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
8208       unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
8209       // Unless we are optimizing for code size, consider the
8210       // expensive operation first.
8211       if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
8212         return ExpensiveOpsLHS < ExpensiveOpsRHS;
8213       return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
8214              (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
8215     }
8216
8217     bool operator>(const Cost &RHS) const { return RHS < *this; }
8218
8219     bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
8220
8221     bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
8222   };
8223   // The last instruction that represent the slice. This should be a
8224   // truncate instruction.
8225   SDNode *Inst;
8226   // The original load instruction.
8227   LoadSDNode *Origin;
8228   // The right shift amount in bits from the original load.
8229   unsigned Shift;
8230   // The DAG from which Origin came from.
8231   // This is used to get some contextual information about legal types, etc.
8232   SelectionDAG *DAG;
8233
8234   LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
8235               unsigned Shift = 0, SelectionDAG *DAG = nullptr)
8236       : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
8237
8238   LoadedSlice(const LoadedSlice &LS)
8239       : Inst(LS.Inst), Origin(LS.Origin), Shift(LS.Shift), DAG(LS.DAG) {}
8240
8241   /// \brief Get the bits used in a chunk of bits \p BitWidth large.
8242   /// \return Result is \p BitWidth and has used bits set to 1 and
8243   ///         not used bits set to 0.
8244   APInt getUsedBits() const {
8245     // Reproduce the trunc(lshr) sequence:
8246     // - Start from the truncated value.
8247     // - Zero extend to the desired bit width.
8248     // - Shift left.
8249     assert(Origin && "No original load to compare against.");
8250     unsigned BitWidth = Origin->getValueSizeInBits(0);
8251     assert(Inst && "This slice is not bound to an instruction");
8252     assert(Inst->getValueSizeInBits(0) <= BitWidth &&
8253            "Extracted slice is bigger than the whole type!");
8254     APInt UsedBits(Inst->getValueSizeInBits(0), 0);
8255     UsedBits.setAllBits();
8256     UsedBits = UsedBits.zext(BitWidth);
8257     UsedBits <<= Shift;
8258     return UsedBits;
8259   }
8260
8261   /// \brief Get the size of the slice to be loaded in bytes.
8262   unsigned getLoadedSize() const {
8263     unsigned SliceSize = getUsedBits().countPopulation();
8264     assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
8265     return SliceSize / 8;
8266   }
8267
8268   /// \brief Get the type that will be loaded for this slice.
8269   /// Note: This may not be the final type for the slice.
8270   EVT getLoadedType() const {
8271     assert(DAG && "Missing context");
8272     LLVMContext &Ctxt = *DAG->getContext();
8273     return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
8274   }
8275
8276   /// \brief Get the alignment of the load used for this slice.
8277   unsigned getAlignment() const {
8278     unsigned Alignment = Origin->getAlignment();
8279     unsigned Offset = getOffsetFromBase();
8280     if (Offset != 0)
8281       Alignment = MinAlign(Alignment, Alignment + Offset);
8282     return Alignment;
8283   }
8284
8285   /// \brief Check if this slice can be rewritten with legal operations.
8286   bool isLegal() const {
8287     // An invalid slice is not legal.
8288     if (!Origin || !Inst || !DAG)
8289       return false;
8290
8291     // Offsets are for indexed load only, we do not handle that.
8292     if (Origin->getOffset().getOpcode() != ISD::UNDEF)
8293       return false;
8294
8295     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8296
8297     // Check that the type is legal.
8298     EVT SliceType = getLoadedType();
8299     if (!TLI.isTypeLegal(SliceType))
8300       return false;
8301
8302     // Check that the load is legal for this type.
8303     if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
8304       return false;
8305
8306     // Check that the offset can be computed.
8307     // 1. Check its type.
8308     EVT PtrType = Origin->getBasePtr().getValueType();
8309     if (PtrType == MVT::Untyped || PtrType.isExtended())
8310       return false;
8311
8312     // 2. Check that it fits in the immediate.
8313     if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
8314       return false;
8315
8316     // 3. Check that the computation is legal.
8317     if (!TLI.isOperationLegal(ISD::ADD, PtrType))
8318       return false;
8319
8320     // Check that the zext is legal if it needs one.
8321     EVT TruncateType = Inst->getValueType(0);
8322     if (TruncateType != SliceType &&
8323         !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
8324       return false;
8325
8326     return true;
8327   }
8328
8329   /// \brief Get the offset in bytes of this slice in the original chunk of
8330   /// bits.
8331   /// \pre DAG != nullptr.
8332   uint64_t getOffsetFromBase() const {
8333     assert(DAG && "Missing context.");
8334     bool IsBigEndian =
8335         DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian();
8336     assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
8337     uint64_t Offset = Shift / 8;
8338     unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
8339     assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
8340            "The size of the original loaded type is not a multiple of a"
8341            " byte.");
8342     // If Offset is bigger than TySizeInBytes, it means we are loading all
8343     // zeros. This should have been optimized before in the process.
8344     assert(TySizeInBytes > Offset &&
8345            "Invalid shift amount for given loaded size");
8346     if (IsBigEndian)
8347       Offset = TySizeInBytes - Offset - getLoadedSize();
8348     return Offset;
8349   }
8350
8351   /// \brief Generate the sequence of instructions to load the slice
8352   /// represented by this object and redirect the uses of this slice to
8353   /// this new sequence of instructions.
8354   /// \pre this->Inst && this->Origin are valid Instructions and this
8355   /// object passed the legal check: LoadedSlice::isLegal returned true.
8356   /// \return The last instruction of the sequence used to load the slice.
8357   SDValue loadSlice() const {
8358     assert(Inst && Origin && "Unable to replace a non-existing slice.");
8359     const SDValue &OldBaseAddr = Origin->getBasePtr();
8360     SDValue BaseAddr = OldBaseAddr;
8361     // Get the offset in that chunk of bytes w.r.t. the endianess.
8362     int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
8363     assert(Offset >= 0 && "Offset too big to fit in int64_t!");
8364     if (Offset) {
8365       // BaseAddr = BaseAddr + Offset.
8366       EVT ArithType = BaseAddr.getValueType();
8367       BaseAddr = DAG->getNode(ISD::ADD, SDLoc(Origin), ArithType, BaseAddr,
8368                               DAG->getConstant(Offset, ArithType));
8369     }
8370
8371     // Create the type of the loaded slice according to its size.
8372     EVT SliceType = getLoadedType();
8373
8374     // Create the load for the slice.
8375     SDValue LastInst = DAG->getLoad(
8376         SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
8377         Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
8378         Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
8379     // If the final type is not the same as the loaded type, this means that
8380     // we have to pad with zero. Create a zero extend for that.
8381     EVT FinalType = Inst->getValueType(0);
8382     if (SliceType != FinalType)
8383       LastInst =
8384           DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
8385     return LastInst;
8386   }
8387
8388   /// \brief Check if this slice can be merged with an expensive cross register
8389   /// bank copy. E.g.,
8390   /// i = load i32
8391   /// f = bitcast i32 i to float
8392   bool canMergeExpensiveCrossRegisterBankCopy() const {
8393     if (!Inst || !Inst->hasOneUse())
8394       return false;
8395     SDNode *Use = *Inst->use_begin();
8396     if (Use->getOpcode() != ISD::BITCAST)
8397       return false;
8398     assert(DAG && "Missing context");
8399     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8400     EVT ResVT = Use->getValueType(0);
8401     const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
8402     const TargetRegisterClass *ArgRC =
8403         TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
8404     if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
8405       return false;
8406
8407     // At this point, we know that we perform a cross-register-bank copy.
8408     // Check if it is expensive.
8409     const TargetRegisterInfo *TRI =
8410         TLI.getTargetMachine().getSubtargetImpl()->getRegisterInfo();
8411     // Assume bitcasts are cheap, unless both register classes do not
8412     // explicitly share a common sub class.
8413     if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
8414       return false;
8415
8416     // Check if it will be merged with the load.
8417     // 1. Check the alignment constraint.
8418     unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment(
8419         ResVT.getTypeForEVT(*DAG->getContext()));
8420
8421     if (RequiredAlignment > getAlignment())
8422       return false;
8423
8424     // 2. Check that the load is a legal operation for that type.
8425     if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
8426       return false;
8427
8428     // 3. Check that we do not have a zext in the way.
8429     if (Inst->getValueType(0) != getLoadedType())
8430       return false;
8431
8432     return true;
8433   }
8434 };
8435 }
8436
8437 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
8438 /// \p UsedBits looks like 0..0 1..1 0..0.
8439 static bool areUsedBitsDense(const APInt &UsedBits) {
8440   // If all the bits are one, this is dense!
8441   if (UsedBits.isAllOnesValue())
8442     return true;
8443
8444   // Get rid of the unused bits on the right.
8445   APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
8446   // Get rid of the unused bits on the left.
8447   if (NarrowedUsedBits.countLeadingZeros())
8448     NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
8449   // Check that the chunk of bits is completely used.
8450   return NarrowedUsedBits.isAllOnesValue();
8451 }
8452
8453 /// \brief Check whether or not \p First and \p Second are next to each other
8454 /// in memory. This means that there is no hole between the bits loaded
8455 /// by \p First and the bits loaded by \p Second.
8456 static bool areSlicesNextToEachOther(const LoadedSlice &First,
8457                                      const LoadedSlice &Second) {
8458   assert(First.Origin == Second.Origin && First.Origin &&
8459          "Unable to match different memory origins.");
8460   APInt UsedBits = First.getUsedBits();
8461   assert((UsedBits & Second.getUsedBits()) == 0 &&
8462          "Slices are not supposed to overlap.");
8463   UsedBits |= Second.getUsedBits();
8464   return areUsedBitsDense(UsedBits);
8465 }
8466
8467 /// \brief Adjust the \p GlobalLSCost according to the target
8468 /// paring capabilities and the layout of the slices.
8469 /// \pre \p GlobalLSCost should account for at least as many loads as
8470 /// there is in the slices in \p LoadedSlices.
8471 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8472                                  LoadedSlice::Cost &GlobalLSCost) {
8473   unsigned NumberOfSlices = LoadedSlices.size();
8474   // If there is less than 2 elements, no pairing is possible.
8475   if (NumberOfSlices < 2)
8476     return;
8477
8478   // Sort the slices so that elements that are likely to be next to each
8479   // other in memory are next to each other in the list.
8480   std::sort(LoadedSlices.begin(), LoadedSlices.end(),
8481             [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
8482     assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
8483     return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
8484   });
8485   const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
8486   // First (resp. Second) is the first (resp. Second) potentially candidate
8487   // to be placed in a paired load.
8488   const LoadedSlice *First = nullptr;
8489   const LoadedSlice *Second = nullptr;
8490   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
8491                 // Set the beginning of the pair.
8492                                                            First = Second) {
8493
8494     Second = &LoadedSlices[CurrSlice];
8495
8496     // If First is NULL, it means we start a new pair.
8497     // Get to the next slice.
8498     if (!First)
8499       continue;
8500
8501     EVT LoadedType = First->getLoadedType();
8502
8503     // If the types of the slices are different, we cannot pair them.
8504     if (LoadedType != Second->getLoadedType())
8505       continue;
8506
8507     // Check if the target supplies paired loads for this type.
8508     unsigned RequiredAlignment = 0;
8509     if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
8510       // move to the next pair, this type is hopeless.
8511       Second = nullptr;
8512       continue;
8513     }
8514     // Check if we meet the alignment requirement.
8515     if (RequiredAlignment > First->getAlignment())
8516       continue;
8517
8518     // Check that both loads are next to each other in memory.
8519     if (!areSlicesNextToEachOther(*First, *Second))
8520       continue;
8521
8522     assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
8523     --GlobalLSCost.Loads;
8524     // Move to the next pair.
8525     Second = nullptr;
8526   }
8527 }
8528
8529 /// \brief Check the profitability of all involved LoadedSlice.
8530 /// Currently, it is considered profitable if there is exactly two
8531 /// involved slices (1) which are (2) next to each other in memory, and
8532 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
8533 ///
8534 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
8535 /// the elements themselves.
8536 ///
8537 /// FIXME: When the cost model will be mature enough, we can relax
8538 /// constraints (1) and (2).
8539 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8540                                 const APInt &UsedBits, bool ForCodeSize) {
8541   unsigned NumberOfSlices = LoadedSlices.size();
8542   if (StressLoadSlicing)
8543     return NumberOfSlices > 1;
8544
8545   // Check (1).
8546   if (NumberOfSlices != 2)
8547     return false;
8548
8549   // Check (2).
8550   if (!areUsedBitsDense(UsedBits))
8551     return false;
8552
8553   // Check (3).
8554   LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
8555   // The original code has one big load.
8556   OrigCost.Loads = 1;
8557   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
8558     const LoadedSlice &LS = LoadedSlices[CurrSlice];
8559     // Accumulate the cost of all the slices.
8560     LoadedSlice::Cost SliceCost(LS, ForCodeSize);
8561     GlobalSlicingCost += SliceCost;
8562
8563     // Account as cost in the original configuration the gain obtained
8564     // with the current slices.
8565     OrigCost.addSliceGain(LS);
8566   }
8567
8568   // If the target supports paired load, adjust the cost accordingly.
8569   adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
8570   return OrigCost > GlobalSlicingCost;
8571 }
8572
8573 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
8574 /// operations, split it in the various pieces being extracted.
8575 ///
8576 /// This sort of thing is introduced by SROA.
8577 /// This slicing takes care not to insert overlapping loads.
8578 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
8579 bool DAGCombiner::SliceUpLoad(SDNode *N) {
8580   if (Level < AfterLegalizeDAG)
8581     return false;
8582
8583   LoadSDNode *LD = cast<LoadSDNode>(N);
8584   if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
8585       !LD->getValueType(0).isInteger())
8586     return false;
8587
8588   // Keep track of already used bits to detect overlapping values.
8589   // In that case, we will just abort the transformation.
8590   APInt UsedBits(LD->getValueSizeInBits(0), 0);
8591
8592   SmallVector<LoadedSlice, 4> LoadedSlices;
8593
8594   // Check if this load is used as several smaller chunks of bits.
8595   // Basically, look for uses in trunc or trunc(lshr) and record a new chain
8596   // of computation for each trunc.
8597   for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
8598        UI != UIEnd; ++UI) {
8599     // Skip the uses of the chain.
8600     if (UI.getUse().getResNo() != 0)
8601       continue;
8602
8603     SDNode *User = *UI;
8604     unsigned Shift = 0;
8605
8606     // Check if this is a trunc(lshr).
8607     if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
8608         isa<ConstantSDNode>(User->getOperand(1))) {
8609       Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
8610       User = *User->use_begin();
8611     }
8612
8613     // At this point, User is a Truncate, iff we encountered, trunc or
8614     // trunc(lshr).
8615     if (User->getOpcode() != ISD::TRUNCATE)
8616       return false;
8617
8618     // The width of the type must be a power of 2 and greater than 8-bits.
8619     // Otherwise the load cannot be represented in LLVM IR.
8620     // Moreover, if we shifted with a non-8-bits multiple, the slice
8621     // will be across several bytes. We do not support that.
8622     unsigned Width = User->getValueSizeInBits(0);
8623     if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
8624       return 0;
8625
8626     // Build the slice for this chain of computations.
8627     LoadedSlice LS(User, LD, Shift, &DAG);
8628     APInt CurrentUsedBits = LS.getUsedBits();
8629
8630     // Check if this slice overlaps with another.
8631     if ((CurrentUsedBits & UsedBits) != 0)
8632       return false;
8633     // Update the bits used globally.
8634     UsedBits |= CurrentUsedBits;
8635
8636     // Check if the new slice would be legal.
8637     if (!LS.isLegal())
8638       return false;
8639
8640     // Record the slice.
8641     LoadedSlices.push_back(LS);
8642   }
8643
8644   // Abort slicing if it does not seem to be profitable.
8645   if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
8646     return false;
8647
8648   ++SlicedLoads;
8649
8650   // Rewrite each chain to use an independent load.
8651   // By construction, each chain can be represented by a unique load.
8652
8653   // Prepare the argument for the new token factor for all the slices.
8654   SmallVector<SDValue, 8> ArgChains;
8655   for (SmallVectorImpl<LoadedSlice>::const_iterator
8656            LSIt = LoadedSlices.begin(),
8657            LSItEnd = LoadedSlices.end();
8658        LSIt != LSItEnd; ++LSIt) {
8659     SDValue SliceInst = LSIt->loadSlice();
8660     CombineTo(LSIt->Inst, SliceInst, true);
8661     if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
8662       SliceInst = SliceInst.getOperand(0);
8663     assert(SliceInst->getOpcode() == ISD::LOAD &&
8664            "It takes more than a zext to get to the loaded slice!!");
8665     ArgChains.push_back(SliceInst.getValue(1));
8666   }
8667
8668   SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
8669                               ArgChains);
8670   DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
8671   return true;
8672 }
8673
8674 /// CheckForMaskedLoad - Check to see if V is (and load (ptr), imm), where the
8675 /// load is having specific bytes cleared out.  If so, return the byte size
8676 /// being masked out and the shift amount.
8677 static std::pair<unsigned, unsigned>
8678 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
8679   std::pair<unsigned, unsigned> Result(0, 0);
8680
8681   // Check for the structure we're looking for.
8682   if (V->getOpcode() != ISD::AND ||
8683       !isa<ConstantSDNode>(V->getOperand(1)) ||
8684       !ISD::isNormalLoad(V->getOperand(0).getNode()))
8685     return Result;
8686
8687   // Check the chain and pointer.
8688   LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
8689   if (LD->getBasePtr() != Ptr) return Result;  // Not from same pointer.
8690
8691   // The store should be chained directly to the load or be an operand of a
8692   // tokenfactor.
8693   if (LD == Chain.getNode())
8694     ; // ok.
8695   else if (Chain->getOpcode() != ISD::TokenFactor)
8696     return Result; // Fail.
8697   else {
8698     bool isOk = false;
8699     for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
8700       if (Chain->getOperand(i).getNode() == LD) {
8701         isOk = true;
8702         break;
8703       }
8704     if (!isOk) return Result;
8705   }
8706
8707   // This only handles simple types.
8708   if (V.getValueType() != MVT::i16 &&
8709       V.getValueType() != MVT::i32 &&
8710       V.getValueType() != MVT::i64)
8711     return Result;
8712
8713   // Check the constant mask.  Invert it so that the bits being masked out are
8714   // 0 and the bits being kept are 1.  Use getSExtValue so that leading bits
8715   // follow the sign bit for uniformity.
8716   uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
8717   unsigned NotMaskLZ = countLeadingZeros(NotMask);
8718   if (NotMaskLZ & 7) return Result;  // Must be multiple of a byte.
8719   unsigned NotMaskTZ = countTrailingZeros(NotMask);
8720   if (NotMaskTZ & 7) return Result;  // Must be multiple of a byte.
8721   if (NotMaskLZ == 64) return Result;  // All zero mask.
8722
8723   // See if we have a continuous run of bits.  If so, we have 0*1+0*
8724   if (CountTrailingOnes_64(NotMask >> NotMaskTZ)+NotMaskTZ+NotMaskLZ != 64)
8725     return Result;
8726
8727   // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
8728   if (V.getValueType() != MVT::i64 && NotMaskLZ)
8729     NotMaskLZ -= 64-V.getValueSizeInBits();
8730
8731   unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
8732   switch (MaskedBytes) {
8733   case 1:
8734   case 2:
8735   case 4: break;
8736   default: return Result; // All one mask, or 5-byte mask.
8737   }
8738
8739   // Verify that the first bit starts at a multiple of mask so that the access
8740   // is aligned the same as the access width.
8741   if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
8742
8743   Result.first = MaskedBytes;
8744   Result.second = NotMaskTZ/8;
8745   return Result;
8746 }
8747
8748
8749 /// ShrinkLoadReplaceStoreWithStore - Check to see if IVal is something that
8750 /// provides a value as specified by MaskInfo.  If so, replace the specified
8751 /// store with a narrower store of truncated IVal.
8752 static SDNode *
8753 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
8754                                 SDValue IVal, StoreSDNode *St,
8755                                 DAGCombiner *DC) {
8756   unsigned NumBytes = MaskInfo.first;
8757   unsigned ByteShift = MaskInfo.second;
8758   SelectionDAG &DAG = DC->getDAG();
8759
8760   // Check to see if IVal is all zeros in the part being masked in by the 'or'
8761   // that uses this.  If not, this is not a replacement.
8762   APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
8763                                   ByteShift*8, (ByteShift+NumBytes)*8);
8764   if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
8765
8766   // Check that it is legal on the target to do this.  It is legal if the new
8767   // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
8768   // legalization.
8769   MVT VT = MVT::getIntegerVT(NumBytes*8);
8770   if (!DC->isTypeLegal(VT))
8771     return nullptr;
8772
8773   // Okay, we can do this!  Replace the 'St' store with a store of IVal that is
8774   // shifted by ByteShift and truncated down to NumBytes.
8775   if (ByteShift)
8776     IVal = DAG.getNode(ISD::SRL, SDLoc(IVal), IVal.getValueType(), IVal,
8777                        DAG.getConstant(ByteShift*8,
8778                                     DC->getShiftAmountTy(IVal.getValueType())));
8779
8780   // Figure out the offset for the store and the alignment of the access.
8781   unsigned StOffset;
8782   unsigned NewAlign = St->getAlignment();
8783
8784   if (DAG.getTargetLoweringInfo().isLittleEndian())
8785     StOffset = ByteShift;
8786   else
8787     StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
8788
8789   SDValue Ptr = St->getBasePtr();
8790   if (StOffset) {
8791     Ptr = DAG.getNode(ISD::ADD, SDLoc(IVal), Ptr.getValueType(),
8792                       Ptr, DAG.getConstant(StOffset, Ptr.getValueType()));
8793     NewAlign = MinAlign(NewAlign, StOffset);
8794   }
8795
8796   // Truncate down to the new size.
8797   IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
8798
8799   ++OpsNarrowed;
8800   return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
8801                       St->getPointerInfo().getWithOffset(StOffset),
8802                       false, false, NewAlign).getNode();
8803 }
8804
8805
8806 /// ReduceLoadOpStoreWidth - Look for sequence of load / op / store where op is
8807 /// one of 'or', 'xor', and 'and' of immediates. If 'op' is only touching some
8808 /// of the loaded bits, try narrowing the load and store if it would end up
8809 /// being a win for performance or code size.
8810 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
8811   StoreSDNode *ST  = cast<StoreSDNode>(N);
8812   if (ST->isVolatile())
8813     return SDValue();
8814
8815   SDValue Chain = ST->getChain();
8816   SDValue Value = ST->getValue();
8817   SDValue Ptr   = ST->getBasePtr();
8818   EVT VT = Value.getValueType();
8819
8820   if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
8821     return SDValue();
8822
8823   unsigned Opc = Value.getOpcode();
8824
8825   // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
8826   // is a byte mask indicating a consecutive number of bytes, check to see if
8827   // Y is known to provide just those bytes.  If so, we try to replace the
8828   // load + replace + store sequence with a single (narrower) store, which makes
8829   // the load dead.
8830   if (Opc == ISD::OR) {
8831     std::pair<unsigned, unsigned> MaskedLoad;
8832     MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
8833     if (MaskedLoad.first)
8834       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8835                                                   Value.getOperand(1), ST,this))
8836         return SDValue(NewST, 0);
8837
8838     // Or is commutative, so try swapping X and Y.
8839     MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
8840     if (MaskedLoad.first)
8841       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8842                                                   Value.getOperand(0), ST,this))
8843         return SDValue(NewST, 0);
8844   }
8845
8846   if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
8847       Value.getOperand(1).getOpcode() != ISD::Constant)
8848     return SDValue();
8849
8850   SDValue N0 = Value.getOperand(0);
8851   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8852       Chain == SDValue(N0.getNode(), 1)) {
8853     LoadSDNode *LD = cast<LoadSDNode>(N0);
8854     if (LD->getBasePtr() != Ptr ||
8855         LD->getPointerInfo().getAddrSpace() !=
8856         ST->getPointerInfo().getAddrSpace())
8857       return SDValue();
8858
8859     // Find the type to narrow it the load / op / store to.
8860     SDValue N1 = Value.getOperand(1);
8861     unsigned BitWidth = N1.getValueSizeInBits();
8862     APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
8863     if (Opc == ISD::AND)
8864       Imm ^= APInt::getAllOnesValue(BitWidth);
8865     if (Imm == 0 || Imm.isAllOnesValue())
8866       return SDValue();
8867     unsigned ShAmt = Imm.countTrailingZeros();
8868     unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
8869     unsigned NewBW = NextPowerOf2(MSB - ShAmt);
8870     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
8871     while (NewBW < BitWidth &&
8872            !(TLI.isOperationLegalOrCustom(Opc, NewVT) &&
8873              TLI.isNarrowingProfitable(VT, NewVT))) {
8874       NewBW = NextPowerOf2(NewBW);
8875       NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
8876     }
8877     if (NewBW >= BitWidth)
8878       return SDValue();
8879
8880     // If the lsb changed does not start at the type bitwidth boundary,
8881     // start at the previous one.
8882     if (ShAmt % NewBW)
8883       ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
8884     APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
8885                                    std::min(BitWidth, ShAmt + NewBW));
8886     if ((Imm & Mask) == Imm) {
8887       APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
8888       if (Opc == ISD::AND)
8889         NewImm ^= APInt::getAllOnesValue(NewBW);
8890       uint64_t PtrOff = ShAmt / 8;
8891       // For big endian targets, we need to adjust the offset to the pointer to
8892       // load the correct bytes.
8893       if (TLI.isBigEndian())
8894         PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
8895
8896       unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
8897       Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
8898       if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
8899         return SDValue();
8900
8901       SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
8902                                    Ptr.getValueType(), Ptr,
8903                                    DAG.getConstant(PtrOff, Ptr.getValueType()));
8904       SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
8905                                   LD->getChain(), NewPtr,
8906                                   LD->getPointerInfo().getWithOffset(PtrOff),
8907                                   LD->isVolatile(), LD->isNonTemporal(),
8908                                   LD->isInvariant(), NewAlign,
8909                                   LD->getAAInfo());
8910       SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
8911                                    DAG.getConstant(NewImm, NewVT));
8912       SDValue NewST = DAG.getStore(Chain, SDLoc(N),
8913                                    NewVal, NewPtr,
8914                                    ST->getPointerInfo().getWithOffset(PtrOff),
8915                                    false, false, NewAlign);
8916
8917       AddToWorklist(NewPtr.getNode());
8918       AddToWorklist(NewLD.getNode());
8919       AddToWorklist(NewVal.getNode());
8920       WorklistRemover DeadNodes(*this);
8921       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
8922       ++OpsNarrowed;
8923       return NewST;
8924     }
8925   }
8926
8927   return SDValue();
8928 }
8929
8930 /// TransformFPLoadStorePair - For a given floating point load / store pair,
8931 /// if the load value isn't used by any other operations, then consider
8932 /// transforming the pair to integer load / store operations if the target
8933 /// deems the transformation profitable.
8934 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
8935   StoreSDNode *ST  = cast<StoreSDNode>(N);
8936   SDValue Chain = ST->getChain();
8937   SDValue Value = ST->getValue();
8938   if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
8939       Value.hasOneUse() &&
8940       Chain == SDValue(Value.getNode(), 1)) {
8941     LoadSDNode *LD = cast<LoadSDNode>(Value);
8942     EVT VT = LD->getMemoryVT();
8943     if (!VT.isFloatingPoint() ||
8944         VT != ST->getMemoryVT() ||
8945         LD->isNonTemporal() ||
8946         ST->isNonTemporal() ||
8947         LD->getPointerInfo().getAddrSpace() != 0 ||
8948         ST->getPointerInfo().getAddrSpace() != 0)
8949       return SDValue();
8950
8951     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
8952     if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
8953         !TLI.isOperationLegal(ISD::STORE, IntVT) ||
8954         !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
8955         !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
8956       return SDValue();
8957
8958     unsigned LDAlign = LD->getAlignment();
8959     unsigned STAlign = ST->getAlignment();
8960     Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
8961     unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
8962     if (LDAlign < ABIAlign || STAlign < ABIAlign)
8963       return SDValue();
8964
8965     SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
8966                                 LD->getChain(), LD->getBasePtr(),
8967                                 LD->getPointerInfo(),
8968                                 false, false, false, LDAlign);
8969
8970     SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
8971                                  NewLD, ST->getBasePtr(),
8972                                  ST->getPointerInfo(),
8973                                  false, false, STAlign);
8974
8975     AddToWorklist(NewLD.getNode());
8976     AddToWorklist(NewST.getNode());
8977     WorklistRemover DeadNodes(*this);
8978     DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
8979     ++LdStFP2Int;
8980     return NewST;
8981   }
8982
8983   return SDValue();
8984 }
8985
8986 /// Helper struct to parse and store a memory address as base + index + offset.
8987 /// We ignore sign extensions when it is safe to do so.
8988 /// The following two expressions are not equivalent. To differentiate we need
8989 /// to store whether there was a sign extension involved in the index
8990 /// computation.
8991 ///  (load (i64 add (i64 copyfromreg %c)
8992 ///                 (i64 signextend (add (i8 load %index)
8993 ///                                      (i8 1))))
8994 /// vs
8995 ///
8996 /// (load (i64 add (i64 copyfromreg %c)
8997 ///                (i64 signextend (i32 add (i32 signextend (i8 load %index))
8998 ///                                         (i32 1)))))
8999 struct BaseIndexOffset {
9000   SDValue Base;
9001   SDValue Index;
9002   int64_t Offset;
9003   bool IsIndexSignExt;
9004
9005   BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
9006
9007   BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
9008                   bool IsIndexSignExt) :
9009     Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
9010
9011   bool equalBaseIndex(const BaseIndexOffset &Other) {
9012     return Other.Base == Base && Other.Index == Index &&
9013       Other.IsIndexSignExt == IsIndexSignExt;
9014   }
9015
9016   /// Parses tree in Ptr for base, index, offset addresses.
9017   static BaseIndexOffset match(SDValue Ptr) {
9018     bool IsIndexSignExt = false;
9019
9020     // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
9021     // instruction, then it could be just the BASE or everything else we don't
9022     // know how to handle. Just use Ptr as BASE and give up.
9023     if (Ptr->getOpcode() != ISD::ADD)
9024       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9025
9026     // We know that we have at least an ADD instruction. Try to pattern match
9027     // the simple case of BASE + OFFSET.
9028     if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
9029       int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
9030       return  BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
9031                               IsIndexSignExt);
9032     }
9033
9034     // Inside a loop the current BASE pointer is calculated using an ADD and a
9035     // MUL instruction. In this case Ptr is the actual BASE pointer.
9036     // (i64 add (i64 %array_ptr)
9037     //          (i64 mul (i64 %induction_var)
9038     //                   (i64 %element_size)))
9039     if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
9040       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9041
9042     // Look at Base + Index + Offset cases.
9043     SDValue Base = Ptr->getOperand(0);
9044     SDValue IndexOffset = Ptr->getOperand(1);
9045
9046     // Skip signextends.
9047     if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
9048       IndexOffset = IndexOffset->getOperand(0);
9049       IsIndexSignExt = true;
9050     }
9051
9052     // Either the case of Base + Index (no offset) or something else.
9053     if (IndexOffset->getOpcode() != ISD::ADD)
9054       return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
9055
9056     // Now we have the case of Base + Index + offset.
9057     SDValue Index = IndexOffset->getOperand(0);
9058     SDValue Offset = IndexOffset->getOperand(1);
9059
9060     if (!isa<ConstantSDNode>(Offset))
9061       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9062
9063     // Ignore signextends.
9064     if (Index->getOpcode() == ISD::SIGN_EXTEND) {
9065       Index = Index->getOperand(0);
9066       IsIndexSignExt = true;
9067     } else IsIndexSignExt = false;
9068
9069     int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
9070     return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
9071   }
9072 };
9073
9074 /// Holds a pointer to an LSBaseSDNode as well as information on where it
9075 /// is located in a sequence of memory operations connected by a chain.
9076 struct MemOpLink {
9077   MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
9078     MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
9079   // Ptr to the mem node.
9080   LSBaseSDNode *MemNode;
9081   // Offset from the base ptr.
9082   int64_t OffsetFromBase;
9083   // What is the sequence number of this mem node.
9084   // Lowest mem operand in the DAG starts at zero.
9085   unsigned SequenceNum;
9086 };
9087
9088 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
9089   EVT MemVT = St->getMemoryVT();
9090   int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
9091   bool NoVectors = DAG.getMachineFunction().getFunction()->getAttributes().
9092     hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
9093
9094   // Don't merge vectors into wider inputs.
9095   if (MemVT.isVector() || !MemVT.isSimple())
9096     return false;
9097
9098   // Perform an early exit check. Do not bother looking at stored values that
9099   // are not constants or loads.
9100   SDValue StoredVal = St->getValue();
9101   bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
9102   if (!isa<ConstantSDNode>(StoredVal) && !isa<ConstantFPSDNode>(StoredVal) &&
9103       !IsLoadSrc)
9104     return false;
9105
9106   // Only look at ends of store sequences.
9107   SDValue Chain = SDValue(St, 0);
9108   if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
9109     return false;
9110
9111   // This holds the base pointer, index, and the offset in bytes from the base
9112   // pointer.
9113   BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
9114
9115   // We must have a base and an offset.
9116   if (!BasePtr.Base.getNode())
9117     return false;
9118
9119   // Do not handle stores to undef base pointers.
9120   if (BasePtr.Base.getOpcode() == ISD::UNDEF)
9121     return false;
9122
9123   // Save the LoadSDNodes that we find in the chain.
9124   // We need to make sure that these nodes do not interfere with
9125   // any of the store nodes.
9126   SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
9127
9128   // Save the StoreSDNodes that we find in the chain.
9129   SmallVector<MemOpLink, 8> StoreNodes;
9130
9131   // Walk up the chain and look for nodes with offsets from the same
9132   // base pointer. Stop when reaching an instruction with a different kind
9133   // or instruction which has a different base pointer.
9134   unsigned Seq = 0;
9135   StoreSDNode *Index = St;
9136   while (Index) {
9137     // If the chain has more than one use, then we can't reorder the mem ops.
9138     if (Index != St && !SDValue(Index, 0)->hasOneUse())
9139       break;
9140
9141     // Find the base pointer and offset for this memory node.
9142     BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
9143
9144     // Check that the base pointer is the same as the original one.
9145     if (!Ptr.equalBaseIndex(BasePtr))
9146       break;
9147
9148     // Check that the alignment is the same.
9149     if (Index->getAlignment() != St->getAlignment())
9150       break;
9151
9152     // The memory operands must not be volatile.
9153     if (Index->isVolatile() || Index->isIndexed())
9154       break;
9155
9156     // No truncation.
9157     if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
9158       if (St->isTruncatingStore())
9159         break;
9160
9161     // The stored memory type must be the same.
9162     if (Index->getMemoryVT() != MemVT)
9163       break;
9164
9165     // We do not allow unaligned stores because we want to prevent overriding
9166     // stores.
9167     if (Index->getAlignment()*8 != MemVT.getSizeInBits())
9168       break;
9169
9170     // We found a potential memory operand to merge.
9171     StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
9172
9173     // Find the next memory operand in the chain. If the next operand in the
9174     // chain is a store then move up and continue the scan with the next
9175     // memory operand. If the next operand is a load save it and use alias
9176     // information to check if it interferes with anything.
9177     SDNode *NextInChain = Index->getChain().getNode();
9178     while (1) {
9179       if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
9180         // We found a store node. Use it for the next iteration.
9181         Index = STn;
9182         break;
9183       } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
9184         if (Ldn->isVolatile()) {
9185           Index = nullptr;
9186           break;
9187         }
9188
9189         // Save the load node for later. Continue the scan.
9190         AliasLoadNodes.push_back(Ldn);
9191         NextInChain = Ldn->getChain().getNode();
9192         continue;
9193       } else {
9194         Index = nullptr;
9195         break;
9196       }
9197     }
9198   }
9199
9200   // Check if there is anything to merge.
9201   if (StoreNodes.size() < 2)
9202     return false;
9203
9204   // Sort the memory operands according to their distance from the base pointer.
9205   std::sort(StoreNodes.begin(), StoreNodes.end(),
9206             [](MemOpLink LHS, MemOpLink RHS) {
9207     return LHS.OffsetFromBase < RHS.OffsetFromBase ||
9208            (LHS.OffsetFromBase == RHS.OffsetFromBase &&
9209             LHS.SequenceNum > RHS.SequenceNum);
9210   });
9211
9212   // Scan the memory operations on the chain and find the first non-consecutive
9213   // store memory address.
9214   unsigned LastConsecutiveStore = 0;
9215   int64_t StartAddress = StoreNodes[0].OffsetFromBase;
9216   for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
9217
9218     // Check that the addresses are consecutive starting from the second
9219     // element in the list of stores.
9220     if (i > 0) {
9221       int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
9222       if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9223         break;
9224     }
9225
9226     bool Alias = false;
9227     // Check if this store interferes with any of the loads that we found.
9228     for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
9229       if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
9230         Alias = true;
9231         break;
9232       }
9233     // We found a load that alias with this store. Stop the sequence.
9234     if (Alias)
9235       break;
9236
9237     // Mark this node as useful.
9238     LastConsecutiveStore = i;
9239   }
9240
9241   // The node with the lowest store address.
9242   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
9243
9244   // Store the constants into memory as one consecutive store.
9245   if (!IsLoadSrc) {
9246     unsigned LastLegalType = 0;
9247     unsigned LastLegalVectorType = 0;
9248     bool NonZero = false;
9249     for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9250       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
9251       SDValue StoredVal = St->getValue();
9252
9253       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
9254         NonZero |= !C->isNullValue();
9255       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
9256         NonZero |= !C->getConstantFPValue()->isNullValue();
9257       } else {
9258         // Non-constant.
9259         break;
9260       }
9261
9262       // Find a legal type for the constant store.
9263       unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9264       EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9265       if (TLI.isTypeLegal(StoreTy))
9266         LastLegalType = i+1;
9267       // Or check whether a truncstore is legal.
9268       else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9269                TargetLowering::TypePromoteInteger) {
9270         EVT LegalizedStoredValueTy =
9271           TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
9272         if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy))
9273           LastLegalType = i+1;
9274       }
9275
9276       // Find a legal type for the vector store.
9277       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9278       if (TLI.isTypeLegal(Ty))
9279         LastLegalVectorType = i + 1;
9280     }
9281
9282     // We only use vectors if the constant is known to be zero and the
9283     // function is not marked with the noimplicitfloat attribute.
9284     if (NonZero || NoVectors)
9285       LastLegalVectorType = 0;
9286
9287     // Check if we found a legal integer type to store.
9288     if (LastLegalType == 0 && LastLegalVectorType == 0)
9289       return false;
9290
9291     bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
9292     unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
9293
9294     // Make sure we have something to merge.
9295     if (NumElem < 2)
9296       return false;
9297
9298     unsigned EarliestNodeUsed = 0;
9299     for (unsigned i=0; i < NumElem; ++i) {
9300       // Find a chain for the new wide-store operand. Notice that some
9301       // of the store nodes that we found may not be selected for inclusion
9302       // in the wide store. The chain we use needs to be the chain of the
9303       // earliest store node which is *used* and replaced by the wide store.
9304       if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9305         EarliestNodeUsed = i;
9306     }
9307
9308     // The earliest Node in the DAG.
9309     LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9310     SDLoc DL(StoreNodes[0].MemNode);
9311
9312     SDValue StoredVal;
9313     if (UseVector) {
9314       // Find a legal type for the vector store.
9315       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9316       assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
9317       StoredVal = DAG.getConstant(0, Ty);
9318     } else {
9319       unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9320       APInt StoreInt(StoreBW, 0);
9321
9322       // Construct a single integer constant which is made of the smaller
9323       // constant inputs.
9324       bool IsLE = TLI.isLittleEndian();
9325       for (unsigned i = 0; i < NumElem ; ++i) {
9326         unsigned Idx = IsLE ?(NumElem - 1 - i) : i;
9327         StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
9328         SDValue Val = St->getValue();
9329         StoreInt<<=ElementSizeBytes*8;
9330         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
9331           StoreInt|=C->getAPIntValue().zext(StoreBW);
9332         } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
9333           StoreInt|= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
9334         } else {
9335           assert(false && "Invalid constant element type");
9336         }
9337       }
9338
9339       // Create the new Load and Store operations.
9340       EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9341       StoredVal = DAG.getConstant(StoreInt, StoreTy);
9342     }
9343
9344     SDValue NewStore = DAG.getStore(EarliestOp->getChain(), DL, StoredVal,
9345                                     FirstInChain->getBasePtr(),
9346                                     FirstInChain->getPointerInfo(),
9347                                     false, false,
9348                                     FirstInChain->getAlignment());
9349
9350     // Replace the first store with the new store
9351     CombineTo(EarliestOp, NewStore);
9352     // Erase all other stores.
9353     for (unsigned i = 0; i < NumElem ; ++i) {
9354       if (StoreNodes[i].MemNode == EarliestOp)
9355         continue;
9356       StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9357       // ReplaceAllUsesWith will replace all uses that existed when it was
9358       // called, but graph optimizations may cause new ones to appear. For
9359       // example, the case in pr14333 looks like
9360       //
9361       //  St's chain -> St -> another store -> X
9362       //
9363       // And the only difference from St to the other store is the chain.
9364       // When we change it's chain to be St's chain they become identical,
9365       // get CSEed and the net result is that X is now a use of St.
9366       // Since we know that St is redundant, just iterate.
9367       while (!St->use_empty())
9368         DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
9369       deleteAndRecombine(St);
9370     }
9371
9372     return true;
9373   }
9374
9375   // Below we handle the case of multiple consecutive stores that
9376   // come from multiple consecutive loads. We merge them into a single
9377   // wide load and a single wide store.
9378
9379   // Look for load nodes which are used by the stored values.
9380   SmallVector<MemOpLink, 8> LoadNodes;
9381
9382   // Find acceptable loads. Loads need to have the same chain (token factor),
9383   // must not be zext, volatile, indexed, and they must be consecutive.
9384   BaseIndexOffset LdBasePtr;
9385   for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9386     StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
9387     LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
9388     if (!Ld) break;
9389
9390     // Loads must only have one use.
9391     if (!Ld->hasNUsesOfValue(1, 0))
9392       break;
9393
9394     // Check that the alignment is the same as the stores.
9395     if (Ld->getAlignment() != St->getAlignment())
9396       break;
9397
9398     // The memory operands must not be volatile.
9399     if (Ld->isVolatile() || Ld->isIndexed())
9400       break;
9401
9402     // We do not accept ext loads.
9403     if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
9404       break;
9405
9406     // The stored memory type must be the same.
9407     if (Ld->getMemoryVT() != MemVT)
9408       break;
9409
9410     BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
9411     // If this is not the first ptr that we check.
9412     if (LdBasePtr.Base.getNode()) {
9413       // The base ptr must be the same.
9414       if (!LdPtr.equalBaseIndex(LdBasePtr))
9415         break;
9416     } else {
9417       // Check that all other base pointers are the same as this one.
9418       LdBasePtr = LdPtr;
9419     }
9420
9421     // We found a potential memory operand to merge.
9422     LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
9423   }
9424
9425   if (LoadNodes.size() < 2)
9426     return false;
9427
9428   // If we have load/store pair instructions and we only have two values,
9429   // don't bother.
9430   unsigned RequiredAlignment;
9431   if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) &&
9432       St->getAlignment() >= RequiredAlignment)
9433     return false;
9434
9435   // Scan the memory operations on the chain and find the first non-consecutive
9436   // load memory address. These variables hold the index in the store node
9437   // array.
9438   unsigned LastConsecutiveLoad = 0;
9439   // This variable refers to the size and not index in the array.
9440   unsigned LastLegalVectorType = 0;
9441   unsigned LastLegalIntegerType = 0;
9442   StartAddress = LoadNodes[0].OffsetFromBase;
9443   SDValue FirstChain = LoadNodes[0].MemNode->getChain();
9444   for (unsigned i = 1; i < LoadNodes.size(); ++i) {
9445     // All loads much share the same chain.
9446     if (LoadNodes[i].MemNode->getChain() != FirstChain)
9447       break;
9448
9449     int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
9450     if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9451       break;
9452     LastConsecutiveLoad = i;
9453
9454     // Find a legal type for the vector store.
9455     EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9456     if (TLI.isTypeLegal(StoreTy))
9457       LastLegalVectorType = i + 1;
9458
9459     // Find a legal type for the integer store.
9460     unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9461     StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9462     if (TLI.isTypeLegal(StoreTy))
9463       LastLegalIntegerType = i + 1;
9464     // Or check whether a truncstore and extload is legal.
9465     else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9466              TargetLowering::TypePromoteInteger) {
9467       EVT LegalizedStoredValueTy =
9468         TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
9469       if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
9470           TLI.isLoadExtLegal(ISD::ZEXTLOAD, StoreTy) &&
9471           TLI.isLoadExtLegal(ISD::SEXTLOAD, StoreTy) &&
9472           TLI.isLoadExtLegal(ISD::EXTLOAD, StoreTy))
9473         LastLegalIntegerType = i+1;
9474     }
9475   }
9476
9477   // Only use vector types if the vector type is larger than the integer type.
9478   // If they are the same, use integers.
9479   bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
9480   unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
9481
9482   // We add +1 here because the LastXXX variables refer to location while
9483   // the NumElem refers to array/index size.
9484   unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
9485   NumElem = std::min(LastLegalType, NumElem);
9486
9487   if (NumElem < 2)
9488     return false;
9489
9490   // The earliest Node in the DAG.
9491   unsigned EarliestNodeUsed = 0;
9492   LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9493   for (unsigned i=1; i<NumElem; ++i) {
9494     // Find a chain for the new wide-store operand. Notice that some
9495     // of the store nodes that we found may not be selected for inclusion
9496     // in the wide store. The chain we use needs to be the chain of the
9497     // earliest store node which is *used* and replaced by the wide store.
9498     if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9499       EarliestNodeUsed = i;
9500   }
9501
9502   // Find if it is better to use vectors or integers to load and store
9503   // to memory.
9504   EVT JointMemOpVT;
9505   if (UseVectorTy) {
9506     JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9507   } else {
9508     unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9509     JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9510   }
9511
9512   SDLoc LoadDL(LoadNodes[0].MemNode);
9513   SDLoc StoreDL(StoreNodes[0].MemNode);
9514
9515   LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
9516   SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL,
9517                                 FirstLoad->getChain(),
9518                                 FirstLoad->getBasePtr(),
9519                                 FirstLoad->getPointerInfo(),
9520                                 false, false, false,
9521                                 FirstLoad->getAlignment());
9522
9523   SDValue NewStore = DAG.getStore(EarliestOp->getChain(), StoreDL, NewLoad,
9524                                   FirstInChain->getBasePtr(),
9525                                   FirstInChain->getPointerInfo(), false, false,
9526                                   FirstInChain->getAlignment());
9527
9528   // Replace one of the loads with the new load.
9529   LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
9530   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
9531                                 SDValue(NewLoad.getNode(), 1));
9532
9533   // Remove the rest of the load chains.
9534   for (unsigned i = 1; i < NumElem ; ++i) {
9535     // Replace all chain users of the old load nodes with the chain of the new
9536     // load node.
9537     LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
9538     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
9539   }
9540
9541   // Replace the first store with the new store.
9542   CombineTo(EarliestOp, NewStore);
9543   // Erase all other stores.
9544   for (unsigned i = 0; i < NumElem ; ++i) {
9545     // Remove all Store nodes.
9546     if (StoreNodes[i].MemNode == EarliestOp)
9547       continue;
9548     StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9549     DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
9550     deleteAndRecombine(St);
9551   }
9552
9553   return true;
9554 }
9555
9556 SDValue DAGCombiner::visitSTORE(SDNode *N) {
9557   StoreSDNode *ST  = cast<StoreSDNode>(N);
9558   SDValue Chain = ST->getChain();
9559   SDValue Value = ST->getValue();
9560   SDValue Ptr   = ST->getBasePtr();
9561
9562   // If this is a store of a bit convert, store the input value if the
9563   // resultant store does not need a higher alignment than the original.
9564   if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
9565       ST->isUnindexed()) {
9566     unsigned OrigAlign = ST->getAlignment();
9567     EVT SVT = Value.getOperand(0).getValueType();
9568     unsigned Align = TLI.getDataLayout()->
9569       getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
9570     if (Align <= OrigAlign &&
9571         ((!LegalOperations && !ST->isVolatile()) ||
9572          TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
9573       return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
9574                           Ptr, ST->getPointerInfo(), ST->isVolatile(),
9575                           ST->isNonTemporal(), OrigAlign,
9576                           ST->getAAInfo());
9577   }
9578
9579   // Turn 'store undef, Ptr' -> nothing.
9580   if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
9581     return Chain;
9582
9583   // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
9584   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
9585     // NOTE: If the original store is volatile, this transform must not increase
9586     // the number of stores.  For example, on x86-32 an f64 can be stored in one
9587     // processor operation but an i64 (which is not legal) requires two.  So the
9588     // transform should not be done in this case.
9589     if (Value.getOpcode() != ISD::TargetConstantFP) {
9590       SDValue Tmp;
9591       switch (CFP->getSimpleValueType(0).SimpleTy) {
9592       default: llvm_unreachable("Unknown FP type");
9593       case MVT::f16:    // We don't do this for these yet.
9594       case MVT::f80:
9595       case MVT::f128:
9596       case MVT::ppcf128:
9597         break;
9598       case MVT::f32:
9599         if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
9600             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
9601           Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
9602                               bitcastToAPInt().getZExtValue(), MVT::i32);
9603           return DAG.getStore(Chain, SDLoc(N), Tmp,
9604                               Ptr, ST->getMemOperand());
9605         }
9606         break;
9607       case MVT::f64:
9608         if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
9609              !ST->isVolatile()) ||
9610             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
9611           Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
9612                                 getZExtValue(), MVT::i64);
9613           return DAG.getStore(Chain, SDLoc(N), Tmp,
9614                               Ptr, ST->getMemOperand());
9615         }
9616
9617         if (!ST->isVolatile() &&
9618             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
9619           // Many FP stores are not made apparent until after legalize, e.g. for
9620           // argument passing.  Since this is so common, custom legalize the
9621           // 64-bit integer store into two 32-bit stores.
9622           uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
9623           SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
9624           SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
9625           if (TLI.isBigEndian()) std::swap(Lo, Hi);
9626
9627           unsigned Alignment = ST->getAlignment();
9628           bool isVolatile = ST->isVolatile();
9629           bool isNonTemporal = ST->isNonTemporal();
9630           AAMDNodes AAInfo = ST->getAAInfo();
9631
9632           SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
9633                                      Ptr, ST->getPointerInfo(),
9634                                      isVolatile, isNonTemporal,
9635                                      ST->getAlignment(), AAInfo);
9636           Ptr = DAG.getNode(ISD::ADD, SDLoc(N), Ptr.getValueType(), Ptr,
9637                             DAG.getConstant(4, Ptr.getValueType()));
9638           Alignment = MinAlign(Alignment, 4U);
9639           SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
9640                                      Ptr, ST->getPointerInfo().getWithOffset(4),
9641                                      isVolatile, isNonTemporal,
9642                                      Alignment, AAInfo);
9643           return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
9644                              St0, St1);
9645         }
9646
9647         break;
9648       }
9649     }
9650   }
9651
9652   // Try to infer better alignment information than the store already has.
9653   if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
9654     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
9655       if (Align > ST->getAlignment())
9656         return DAG.getTruncStore(Chain, SDLoc(N), Value,
9657                                  Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
9658                                  ST->isVolatile(), ST->isNonTemporal(), Align,
9659                                  ST->getAAInfo());
9660     }
9661   }
9662
9663   // Try transforming a pair floating point load / store ops to integer
9664   // load / store ops.
9665   SDValue NewST = TransformFPLoadStorePair(N);
9666   if (NewST.getNode())
9667     return NewST;
9668
9669   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
9670     TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
9671 #ifndef NDEBUG
9672   if (CombinerAAOnlyFunc.getNumOccurrences() &&
9673       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
9674     UseAA = false;
9675 #endif
9676   if (UseAA && ST->isUnindexed()) {
9677     // Walk up chain skipping non-aliasing memory nodes.
9678     SDValue BetterChain = FindBetterChain(N, Chain);
9679
9680     // If there is a better chain.
9681     if (Chain != BetterChain) {
9682       SDValue ReplStore;
9683
9684       // Replace the chain to avoid dependency.
9685       if (ST->isTruncatingStore()) {
9686         ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
9687                                       ST->getMemoryVT(), ST->getMemOperand());
9688       } else {
9689         ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
9690                                  ST->getMemOperand());
9691       }
9692
9693       // Create token to keep both nodes around.
9694       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
9695                                   MVT::Other, Chain, ReplStore);
9696
9697       // Make sure the new and old chains are cleaned up.
9698       AddToWorklist(Token.getNode());
9699
9700       // Don't add users to work list.
9701       return CombineTo(N, Token, false);
9702     }
9703   }
9704
9705   // Try transforming N to an indexed store.
9706   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
9707     return SDValue(N, 0);
9708
9709   // FIXME: is there such a thing as a truncating indexed store?
9710   if (ST->isTruncatingStore() && ST->isUnindexed() &&
9711       Value.getValueType().isInteger()) {
9712     // See if we can simplify the input to this truncstore with knowledge that
9713     // only the low bits are being used.  For example:
9714     // "truncstore (or (shl x, 8), y), i8"  -> "truncstore y, i8"
9715     SDValue Shorter =
9716       GetDemandedBits(Value,
9717                       APInt::getLowBitsSet(
9718                         Value.getValueType().getScalarType().getSizeInBits(),
9719                         ST->getMemoryVT().getScalarType().getSizeInBits()));
9720     AddToWorklist(Value.getNode());
9721     if (Shorter.getNode())
9722       return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
9723                                Ptr, ST->getMemoryVT(), ST->getMemOperand());
9724
9725     // Otherwise, see if we can simplify the operation with
9726     // SimplifyDemandedBits, which only works if the value has a single use.
9727     if (SimplifyDemandedBits(Value,
9728                         APInt::getLowBitsSet(
9729                           Value.getValueType().getScalarType().getSizeInBits(),
9730                           ST->getMemoryVT().getScalarType().getSizeInBits())))
9731       return SDValue(N, 0);
9732   }
9733
9734   // If this is a load followed by a store to the same location, then the store
9735   // is dead/noop.
9736   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
9737     if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
9738         ST->isUnindexed() && !ST->isVolatile() &&
9739         // There can't be any side effects between the load and store, such as
9740         // a call or store.
9741         Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
9742       // The store is dead, remove it.
9743       return Chain;
9744     }
9745   }
9746
9747   // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
9748   // truncating store.  We can do this even if this is already a truncstore.
9749   if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
9750       && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
9751       TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
9752                             ST->getMemoryVT())) {
9753     return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
9754                              Ptr, ST->getMemoryVT(), ST->getMemOperand());
9755   }
9756
9757   // Only perform this optimization before the types are legal, because we
9758   // don't want to perform this optimization on every DAGCombine invocation.
9759   if (!LegalTypes) {
9760     bool EverChanged = false;
9761
9762     do {
9763       // There can be multiple store sequences on the same chain.
9764       // Keep trying to merge store sequences until we are unable to do so
9765       // or until we merge the last store on the chain.
9766       bool Changed = MergeConsecutiveStores(ST);
9767       EverChanged |= Changed;
9768       if (!Changed) break;
9769     } while (ST->getOpcode() != ISD::DELETED_NODE);
9770
9771     if (EverChanged)
9772       return SDValue(N, 0);
9773   }
9774
9775   return ReduceLoadOpStoreWidth(N);
9776 }
9777
9778 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
9779   SDValue InVec = N->getOperand(0);
9780   SDValue InVal = N->getOperand(1);
9781   SDValue EltNo = N->getOperand(2);
9782   SDLoc dl(N);
9783
9784   // If the inserted element is an UNDEF, just use the input vector.
9785   if (InVal.getOpcode() == ISD::UNDEF)
9786     return InVec;
9787
9788   EVT VT = InVec.getValueType();
9789
9790   // If we can't generate a legal BUILD_VECTOR, exit
9791   if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
9792     return SDValue();
9793
9794   // Check that we know which element is being inserted
9795   if (!isa<ConstantSDNode>(EltNo))
9796     return SDValue();
9797   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9798
9799   // Canonicalize insert_vector_elt dag nodes.
9800   // Example:
9801   // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
9802   // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
9803   //
9804   // Do this only if the child insert_vector node has one use; also
9805   // do this only if indices are both constants and Idx1 < Idx0.
9806   if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
9807       && isa<ConstantSDNode>(InVec.getOperand(2))) {
9808     unsigned OtherElt =
9809       cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue();
9810     if (Elt < OtherElt) {
9811       // Swap nodes.
9812       SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT,
9813                                   InVec.getOperand(0), InVal, EltNo);
9814       AddToWorklist(NewOp.getNode());
9815       return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
9816                          VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
9817     }
9818   }
9819
9820   // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
9821   // be converted to a BUILD_VECTOR).  Fill in the Ops vector with the
9822   // vector elements.
9823   SmallVector<SDValue, 8> Ops;
9824   // Do not combine these two vectors if the output vector will not replace
9825   // the input vector.
9826   if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
9827     Ops.append(InVec.getNode()->op_begin(),
9828                InVec.getNode()->op_end());
9829   } else if (InVec.getOpcode() == ISD::UNDEF) {
9830     unsigned NElts = VT.getVectorNumElements();
9831     Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
9832   } else {
9833     return SDValue();
9834   }
9835
9836   // Insert the element
9837   if (Elt < Ops.size()) {
9838     // All the operands of BUILD_VECTOR must have the same type;
9839     // we enforce that here.
9840     EVT OpVT = Ops[0].getValueType();
9841     if (InVal.getValueType() != OpVT)
9842       InVal = OpVT.bitsGT(InVal.getValueType()) ?
9843                 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
9844                 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
9845     Ops[Elt] = InVal;
9846   }
9847
9848   // Return the new vector
9849   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
9850 }
9851
9852 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
9853   // (vextract (scalar_to_vector val, 0) -> val
9854   SDValue InVec = N->getOperand(0);
9855   EVT VT = InVec.getValueType();
9856   EVT NVT = N->getValueType(0);
9857
9858   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
9859     // Check if the result type doesn't match the inserted element type. A
9860     // SCALAR_TO_VECTOR may truncate the inserted element and the
9861     // EXTRACT_VECTOR_ELT may widen the extracted vector.
9862     SDValue InOp = InVec.getOperand(0);
9863     if (InOp.getValueType() != NVT) {
9864       assert(InOp.getValueType().isInteger() && NVT.isInteger());
9865       return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
9866     }
9867     return InOp;
9868   }
9869
9870   SDValue EltNo = N->getOperand(1);
9871   bool ConstEltNo = isa<ConstantSDNode>(EltNo);
9872
9873   // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
9874   // We only perform this optimization before the op legalization phase because
9875   // we may introduce new vector instructions which are not backed by TD
9876   // patterns. For example on AVX, extracting elements from a wide vector
9877   // without using extract_subvector. However, if we can find an underlying
9878   // scalar value, then we can always use that.
9879   if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
9880       && ConstEltNo) {
9881     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9882     int NumElem = VT.getVectorNumElements();
9883     ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
9884     // Find the new index to extract from.
9885     int OrigElt = SVOp->getMaskElt(Elt);
9886
9887     // Extracting an undef index is undef.
9888     if (OrigElt == -1)
9889       return DAG.getUNDEF(NVT);
9890
9891     // Select the right vector half to extract from.
9892     SDValue SVInVec;
9893     if (OrigElt < NumElem) {
9894       SVInVec = InVec->getOperand(0);
9895     } else {
9896       SVInVec = InVec->getOperand(1);
9897       OrigElt -= NumElem;
9898     }
9899
9900     if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
9901       SDValue InOp = SVInVec.getOperand(OrigElt);
9902       if (InOp.getValueType() != NVT) {
9903         assert(InOp.getValueType().isInteger() && NVT.isInteger());
9904         InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
9905       }
9906
9907       return InOp;
9908     }
9909
9910     // FIXME: We should handle recursing on other vector shuffles and
9911     // scalar_to_vector here as well.
9912
9913     if (!LegalOperations) {
9914       EVT IndexTy = TLI.getVectorIdxTy();
9915       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT,
9916                          SVInVec, DAG.getConstant(OrigElt, IndexTy));
9917     }
9918   }
9919
9920   // Perform only after legalization to ensure build_vector / vector_shuffle
9921   // optimizations have already been done.
9922   if (!LegalOperations) return SDValue();
9923
9924   // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
9925   // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
9926   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
9927
9928   if (ConstEltNo) {
9929     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9930     bool NewLoad = false;
9931     bool BCNumEltsChanged = false;
9932     EVT ExtVT = VT.getVectorElementType();
9933     EVT LVT = ExtVT;
9934
9935     // If the result of load has to be truncated, then it's not necessarily
9936     // profitable.
9937     if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
9938       return SDValue();
9939
9940     if (InVec.getOpcode() == ISD::BITCAST) {
9941       // Don't duplicate a load with other uses.
9942       if (!InVec.hasOneUse())
9943         return SDValue();
9944
9945       EVT BCVT = InVec.getOperand(0).getValueType();
9946       if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
9947         return SDValue();
9948       if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
9949         BCNumEltsChanged = true;
9950       InVec = InVec.getOperand(0);
9951       ExtVT = BCVT.getVectorElementType();
9952       NewLoad = true;
9953     }
9954
9955     LoadSDNode *LN0 = nullptr;
9956     const ShuffleVectorSDNode *SVN = nullptr;
9957     if (ISD::isNormalLoad(InVec.getNode())) {
9958       LN0 = cast<LoadSDNode>(InVec);
9959     } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
9960                InVec.getOperand(0).getValueType() == ExtVT &&
9961                ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
9962       // Don't duplicate a load with other uses.
9963       if (!InVec.hasOneUse())
9964         return SDValue();
9965
9966       LN0 = cast<LoadSDNode>(InVec.getOperand(0));
9967     } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
9968       // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
9969       // =>
9970       // (load $addr+1*size)
9971
9972       // Don't duplicate a load with other uses.
9973       if (!InVec.hasOneUse())
9974         return SDValue();
9975
9976       // If the bit convert changed the number of elements, it is unsafe
9977       // to examine the mask.
9978       if (BCNumEltsChanged)
9979         return SDValue();
9980
9981       // Select the input vector, guarding against out of range extract vector.
9982       unsigned NumElems = VT.getVectorNumElements();
9983       int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
9984       InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
9985
9986       if (InVec.getOpcode() == ISD::BITCAST) {
9987         // Don't duplicate a load with other uses.
9988         if (!InVec.hasOneUse())
9989           return SDValue();
9990
9991         InVec = InVec.getOperand(0);
9992       }
9993       if (ISD::isNormalLoad(InVec.getNode())) {
9994         LN0 = cast<LoadSDNode>(InVec);
9995         Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
9996       }
9997     }
9998
9999     // Make sure we found a non-volatile load and the extractelement is
10000     // the only use.
10001     if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
10002       return SDValue();
10003
10004     // If Idx was -1 above, Elt is going to be -1, so just return undef.
10005     if (Elt == -1)
10006       return DAG.getUNDEF(LVT);
10007
10008     unsigned Align = LN0->getAlignment();
10009     if (NewLoad) {
10010       // Check the resultant load doesn't need a higher alignment than the
10011       // original load.
10012       unsigned NewAlign =
10013         TLI.getDataLayout()
10014             ->getABITypeAlignment(LVT.getTypeForEVT(*DAG.getContext()));
10015
10016       if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, LVT))
10017         return SDValue();
10018
10019       Align = NewAlign;
10020     }
10021
10022     SDValue NewPtr = LN0->getBasePtr();
10023     unsigned PtrOff = 0;
10024
10025     if (Elt) {
10026       PtrOff = LVT.getSizeInBits() * Elt / 8;
10027       EVT PtrType = NewPtr.getValueType();
10028       if (TLI.isBigEndian())
10029         PtrOff = VT.getSizeInBits() / 8 - PtrOff;
10030       NewPtr = DAG.getNode(ISD::ADD, SDLoc(N), PtrType, NewPtr,
10031                            DAG.getConstant(PtrOff, PtrType));
10032     }
10033
10034     // The replacement we need to do here is a little tricky: we need to
10035     // replace an extractelement of a load with a load.
10036     // Use ReplaceAllUsesOfValuesWith to do the replacement.
10037     // Note that this replacement assumes that the extractvalue is the only
10038     // use of the load; that's okay because we don't want to perform this
10039     // transformation in other cases anyway.
10040     SDValue Load;
10041     SDValue Chain;
10042     if (NVT.bitsGT(LVT)) {
10043       // If the result type of vextract is wider than the load, then issue an
10044       // extending load instead.
10045       ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, LVT)
10046         ? ISD::ZEXTLOAD : ISD::EXTLOAD;
10047       Load = DAG.getExtLoad(ExtType, SDLoc(N), NVT, LN0->getChain(),
10048                             NewPtr, LN0->getPointerInfo().getWithOffset(PtrOff),
10049                             LVT, LN0->isVolatile(), LN0->isNonTemporal(),
10050                             LN0->isInvariant(), Align, LN0->getAAInfo());
10051       Chain = Load.getValue(1);
10052     } else {
10053       Load = DAG.getLoad(LVT, SDLoc(N), LN0->getChain(), NewPtr,
10054                          LN0->getPointerInfo().getWithOffset(PtrOff),
10055                          LN0->isVolatile(), LN0->isNonTemporal(),
10056                          LN0->isInvariant(), Align, LN0->getAAInfo());
10057       Chain = Load.getValue(1);
10058       if (NVT.bitsLT(LVT))
10059         Load = DAG.getNode(ISD::TRUNCATE, SDLoc(N), NVT, Load);
10060       else
10061         Load = DAG.getNode(ISD::BITCAST, SDLoc(N), NVT, Load);
10062     }
10063     WorklistRemover DeadNodes(*this);
10064     SDValue From[] = { SDValue(N, 0), SDValue(LN0,1) };
10065     SDValue To[] = { Load, Chain };
10066     DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
10067     // Since we're explcitly calling ReplaceAllUses, add the new node to the
10068     // worklist explicitly as well.
10069     AddToWorklist(Load.getNode());
10070     AddUsersToWorklist(Load.getNode()); // Add users too
10071     // Make sure to revisit this node to clean it up; it will usually be dead.
10072     AddToWorklist(N);
10073     return SDValue(N, 0);
10074   }
10075
10076   return SDValue();
10077 }
10078
10079 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
10080 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
10081   // We perform this optimization post type-legalization because
10082   // the type-legalizer often scalarizes integer-promoted vectors.
10083   // Performing this optimization before may create bit-casts which
10084   // will be type-legalized to complex code sequences.
10085   // We perform this optimization only before the operation legalizer because we
10086   // may introduce illegal operations.
10087   if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
10088     return SDValue();
10089
10090   unsigned NumInScalars = N->getNumOperands();
10091   SDLoc dl(N);
10092   EVT VT = N->getValueType(0);
10093
10094   // Check to see if this is a BUILD_VECTOR of a bunch of values
10095   // which come from any_extend or zero_extend nodes. If so, we can create
10096   // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
10097   // optimizations. We do not handle sign-extend because we can't fill the sign
10098   // using shuffles.
10099   EVT SourceType = MVT::Other;
10100   bool AllAnyExt = true;
10101
10102   for (unsigned i = 0; i != NumInScalars; ++i) {
10103     SDValue In = N->getOperand(i);
10104     // Ignore undef inputs.
10105     if (In.getOpcode() == ISD::UNDEF) continue;
10106
10107     bool AnyExt  = In.getOpcode() == ISD::ANY_EXTEND;
10108     bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
10109
10110     // Abort if the element is not an extension.
10111     if (!ZeroExt && !AnyExt) {
10112       SourceType = MVT::Other;
10113       break;
10114     }
10115
10116     // The input is a ZeroExt or AnyExt. Check the original type.
10117     EVT InTy = In.getOperand(0).getValueType();
10118
10119     // Check that all of the widened source types are the same.
10120     if (SourceType == MVT::Other)
10121       // First time.
10122       SourceType = InTy;
10123     else if (InTy != SourceType) {
10124       // Multiple income types. Abort.
10125       SourceType = MVT::Other;
10126       break;
10127     }
10128
10129     // Check if all of the extends are ANY_EXTENDs.
10130     AllAnyExt &= AnyExt;
10131   }
10132
10133   // In order to have valid types, all of the inputs must be extended from the
10134   // same source type and all of the inputs must be any or zero extend.
10135   // Scalar sizes must be a power of two.
10136   EVT OutScalarTy = VT.getScalarType();
10137   bool ValidTypes = SourceType != MVT::Other &&
10138                  isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
10139                  isPowerOf2_32(SourceType.getSizeInBits());
10140
10141   // Create a new simpler BUILD_VECTOR sequence which other optimizations can
10142   // turn into a single shuffle instruction.
10143   if (!ValidTypes)
10144     return SDValue();
10145
10146   bool isLE = TLI.isLittleEndian();
10147   unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
10148   assert(ElemRatio > 1 && "Invalid element size ratio");
10149   SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
10150                                DAG.getConstant(0, SourceType);
10151
10152   unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
10153   SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
10154
10155   // Populate the new build_vector
10156   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
10157     SDValue Cast = N->getOperand(i);
10158     assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
10159             Cast.getOpcode() == ISD::ZERO_EXTEND ||
10160             Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
10161     SDValue In;
10162     if (Cast.getOpcode() == ISD::UNDEF)
10163       In = DAG.getUNDEF(SourceType);
10164     else
10165       In = Cast->getOperand(0);
10166     unsigned Index = isLE ? (i * ElemRatio) :
10167                             (i * ElemRatio + (ElemRatio - 1));
10168
10169     assert(Index < Ops.size() && "Invalid index");
10170     Ops[Index] = In;
10171   }
10172
10173   // The type of the new BUILD_VECTOR node.
10174   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
10175   assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
10176          "Invalid vector size");
10177   // Check if the new vector type is legal.
10178   if (!isTypeLegal(VecVT)) return SDValue();
10179
10180   // Make the new BUILD_VECTOR.
10181   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
10182
10183   // The new BUILD_VECTOR node has the potential to be further optimized.
10184   AddToWorklist(BV.getNode());
10185   // Bitcast to the desired type.
10186   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
10187 }
10188
10189 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
10190   EVT VT = N->getValueType(0);
10191
10192   unsigned NumInScalars = N->getNumOperands();
10193   SDLoc dl(N);
10194
10195   EVT SrcVT = MVT::Other;
10196   unsigned Opcode = ISD::DELETED_NODE;
10197   unsigned NumDefs = 0;
10198
10199   for (unsigned i = 0; i != NumInScalars; ++i) {
10200     SDValue In = N->getOperand(i);
10201     unsigned Opc = In.getOpcode();
10202
10203     if (Opc == ISD::UNDEF)
10204       continue;
10205
10206     // If all scalar values are floats and converted from integers.
10207     if (Opcode == ISD::DELETED_NODE &&
10208         (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
10209       Opcode = Opc;
10210     }
10211
10212     if (Opc != Opcode)
10213       return SDValue();
10214
10215     EVT InVT = In.getOperand(0).getValueType();
10216
10217     // If all scalar values are typed differently, bail out. It's chosen to
10218     // simplify BUILD_VECTOR of integer types.
10219     if (SrcVT == MVT::Other)
10220       SrcVT = InVT;
10221     if (SrcVT != InVT)
10222       return SDValue();
10223     NumDefs++;
10224   }
10225
10226   // If the vector has just one element defined, it's not worth to fold it into
10227   // a vectorized one.
10228   if (NumDefs < 2)
10229     return SDValue();
10230
10231   assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
10232          && "Should only handle conversion from integer to float.");
10233   assert(SrcVT != MVT::Other && "Cannot determine source type!");
10234
10235   EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
10236
10237   if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
10238     return SDValue();
10239
10240   SmallVector<SDValue, 8> Opnds;
10241   for (unsigned i = 0; i != NumInScalars; ++i) {
10242     SDValue In = N->getOperand(i);
10243
10244     if (In.getOpcode() == ISD::UNDEF)
10245       Opnds.push_back(DAG.getUNDEF(SrcVT));
10246     else
10247       Opnds.push_back(In.getOperand(0));
10248   }
10249   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds);
10250   AddToWorklist(BV.getNode());
10251
10252   return DAG.getNode(Opcode, dl, VT, BV);
10253 }
10254
10255 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
10256   unsigned NumInScalars = N->getNumOperands();
10257   SDLoc dl(N);
10258   EVT VT = N->getValueType(0);
10259
10260   // A vector built entirely of undefs is undef.
10261   if (ISD::allOperandsUndef(N))
10262     return DAG.getUNDEF(VT);
10263
10264   SDValue V = reduceBuildVecExtToExtBuildVec(N);
10265   if (V.getNode())
10266     return V;
10267
10268   V = reduceBuildVecConvertToConvertBuildVec(N);
10269   if (V.getNode())
10270     return V;
10271
10272   // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
10273   // operations.  If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
10274   // at most two distinct vectors, turn this into a shuffle node.
10275
10276   // May only combine to shuffle after legalize if shuffle is legal.
10277   if (LegalOperations &&
10278       !TLI.isOperationLegalOrCustom(ISD::VECTOR_SHUFFLE, VT))
10279     return SDValue();
10280
10281   SDValue VecIn1, VecIn2;
10282   for (unsigned i = 0; i != NumInScalars; ++i) {
10283     // Ignore undef inputs.
10284     if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
10285
10286     // If this input is something other than a EXTRACT_VECTOR_ELT with a
10287     // constant index, bail out.
10288     if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10289         !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) {
10290       VecIn1 = VecIn2 = SDValue(nullptr, 0);
10291       break;
10292     }
10293
10294     // We allow up to two distinct input vectors.
10295     SDValue ExtractedFromVec = N->getOperand(i).getOperand(0);
10296     if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
10297       continue;
10298
10299     if (!VecIn1.getNode()) {
10300       VecIn1 = ExtractedFromVec;
10301     } else if (!VecIn2.getNode()) {
10302       VecIn2 = ExtractedFromVec;
10303     } else {
10304       // Too many inputs.
10305       VecIn1 = VecIn2 = SDValue(nullptr, 0);
10306       break;
10307     }
10308   }
10309
10310   // If everything is good, we can make a shuffle operation.
10311   if (VecIn1.getNode()) {
10312     SmallVector<int, 8> Mask;
10313     for (unsigned i = 0; i != NumInScalars; ++i) {
10314       if (N->getOperand(i).getOpcode() == ISD::UNDEF) {
10315         Mask.push_back(-1);
10316         continue;
10317       }
10318
10319       // If extracting from the first vector, just use the index directly.
10320       SDValue Extract = N->getOperand(i);
10321       SDValue ExtVal = Extract.getOperand(1);
10322       if (Extract.getOperand(0) == VecIn1) {
10323         unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
10324         if (ExtIndex > VT.getVectorNumElements())
10325           return SDValue();
10326
10327         Mask.push_back(ExtIndex);
10328         continue;
10329       }
10330
10331       // Otherwise, use InIdx + VecSize
10332       unsigned Idx = cast<ConstantSDNode>(ExtVal)->getZExtValue();
10333       Mask.push_back(Idx+NumInScalars);
10334     }
10335
10336     // We can't generate a shuffle node with mismatched input and output types.
10337     // Attempt to transform a single input vector to the correct type.
10338     if ((VT != VecIn1.getValueType())) {
10339       // We don't support shuffeling between TWO values of different types.
10340       if (VecIn2.getNode())
10341         return SDValue();
10342
10343       // We only support widening of vectors which are half the size of the
10344       // output registers. For example XMM->YMM widening on X86 with AVX.
10345       if (VecIn1.getValueType().getSizeInBits()*2 != VT.getSizeInBits())
10346         return SDValue();
10347
10348       // If the input vector type has a different base type to the output
10349       // vector type, bail out.
10350       if (VecIn1.getValueType().getVectorElementType() !=
10351           VT.getVectorElementType())
10352         return SDValue();
10353
10354       // Widen the input vector by adding undef values.
10355       VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10356                            VecIn1, DAG.getUNDEF(VecIn1.getValueType()));
10357     }
10358
10359     // If VecIn2 is unused then change it to undef.
10360     VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
10361
10362     // Check that we were able to transform all incoming values to the same
10363     // type.
10364     if (VecIn2.getValueType() != VecIn1.getValueType() ||
10365         VecIn1.getValueType() != VT)
10366           return SDValue();
10367
10368     // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
10369     if (!isTypeLegal(VT))
10370       return SDValue();
10371
10372     // Return the new VECTOR_SHUFFLE node.
10373     SDValue Ops[2];
10374     Ops[0] = VecIn1;
10375     Ops[1] = VecIn2;
10376     return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
10377   }
10378
10379   return SDValue();
10380 }
10381
10382 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
10383   // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
10384   // EXTRACT_SUBVECTOR operations.  If so, and if the EXTRACT_SUBVECTOR vector
10385   // inputs come from at most two distinct vectors, turn this into a shuffle
10386   // node.
10387
10388   // If we only have one input vector, we don't need to do any concatenation.
10389   if (N->getNumOperands() == 1)
10390     return N->getOperand(0);
10391
10392   // Check if all of the operands are undefs.
10393   EVT VT = N->getValueType(0);
10394   if (ISD::allOperandsUndef(N))
10395     return DAG.getUNDEF(VT);
10396
10397   // Optimize concat_vectors where one of the vectors is undef.
10398   if (N->getNumOperands() == 2 &&
10399       N->getOperand(1)->getOpcode() == ISD::UNDEF) {
10400     SDValue In = N->getOperand(0);
10401     assert(In.getValueType().isVector() && "Must concat vectors");
10402
10403     // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
10404     if (In->getOpcode() == ISD::BITCAST &&
10405         !In->getOperand(0)->getValueType(0).isVector()) {
10406       SDValue Scalar = In->getOperand(0);
10407       EVT SclTy = Scalar->getValueType(0);
10408
10409       if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
10410         return SDValue();
10411
10412       EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
10413                                  VT.getSizeInBits() / SclTy.getSizeInBits());
10414       if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
10415         return SDValue();
10416
10417       SDLoc dl = SDLoc(N);
10418       SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
10419       return DAG.getNode(ISD::BITCAST, dl, VT, Res);
10420     }
10421   }
10422
10423   // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
10424   // -> (BUILD_VECTOR A, B, ..., C, D, ...)
10425   if (N->getNumOperands() == 2 &&
10426       N->getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
10427       N->getOperand(1).getOpcode() == ISD::BUILD_VECTOR) {
10428     EVT VT = N->getValueType(0);
10429     SDValue N0 = N->getOperand(0);
10430     SDValue N1 = N->getOperand(1);
10431     SmallVector<SDValue, 8> Opnds;
10432     unsigned BuildVecNumElts =  N0.getNumOperands();
10433
10434     EVT SclTy0 = N0.getOperand(0)->getValueType(0);
10435     EVT SclTy1 = N1.getOperand(0)->getValueType(0);
10436     if (SclTy0.isFloatingPoint()) {
10437       for (unsigned i = 0; i != BuildVecNumElts; ++i)
10438         Opnds.push_back(N0.getOperand(i));
10439       for (unsigned i = 0; i != BuildVecNumElts; ++i)
10440         Opnds.push_back(N1.getOperand(i));
10441     } else {
10442       // If BUILD_VECTOR are from built from integer, they may have different
10443       // operand types. Get the smaller type and truncate all operands to it.
10444       EVT MinTy = SclTy0.bitsLE(SclTy1) ? SclTy0 : SclTy1;
10445       for (unsigned i = 0; i != BuildVecNumElts; ++i)
10446         Opnds.push_back(DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinTy,
10447                         N0.getOperand(i)));
10448       for (unsigned i = 0; i != BuildVecNumElts; ++i)
10449         Opnds.push_back(DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinTy,
10450                         N1.getOperand(i)));
10451     }
10452
10453     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
10454   }
10455
10456   // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
10457   // nodes often generate nop CONCAT_VECTOR nodes.
10458   // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
10459   // place the incoming vectors at the exact same location.
10460   SDValue SingleSource = SDValue();
10461   unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
10462
10463   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
10464     SDValue Op = N->getOperand(i);
10465
10466     if (Op.getOpcode() == ISD::UNDEF)
10467       continue;
10468
10469     // Check if this is the identity extract:
10470     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
10471       return SDValue();
10472
10473     // Find the single incoming vector for the extract_subvector.
10474     if (SingleSource.getNode()) {
10475       if (Op.getOperand(0) != SingleSource)
10476         return SDValue();
10477     } else {
10478       SingleSource = Op.getOperand(0);
10479
10480       // Check the source type is the same as the type of the result.
10481       // If not, this concat may extend the vector, so we can not
10482       // optimize it away.
10483       if (SingleSource.getValueType() != N->getValueType(0))
10484         return SDValue();
10485     }
10486
10487     unsigned IdentityIndex = i * PartNumElem;
10488     ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
10489     // The extract index must be constant.
10490     if (!CS)
10491       return SDValue();
10492
10493     // Check that we are reading from the identity index.
10494     if (CS->getZExtValue() != IdentityIndex)
10495       return SDValue();
10496   }
10497
10498   if (SingleSource.getNode())
10499     return SingleSource;
10500
10501   return SDValue();
10502 }
10503
10504 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
10505   EVT NVT = N->getValueType(0);
10506   SDValue V = N->getOperand(0);
10507
10508   if (V->getOpcode() == ISD::CONCAT_VECTORS) {
10509     // Combine:
10510     //    (extract_subvec (concat V1, V2, ...), i)
10511     // Into:
10512     //    Vi if possible
10513     // Only operand 0 is checked as 'concat' assumes all inputs of the same
10514     // type.
10515     if (V->getOperand(0).getValueType() != NVT)
10516       return SDValue();
10517     unsigned Idx = dyn_cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
10518     unsigned NumElems = NVT.getVectorNumElements();
10519     assert((Idx % NumElems) == 0 &&
10520            "IDX in concat is not a multiple of the result vector length.");
10521     return V->getOperand(Idx / NumElems);
10522   }
10523
10524   // Skip bitcasting
10525   if (V->getOpcode() == ISD::BITCAST)
10526     V = V.getOperand(0);
10527
10528   if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
10529     SDLoc dl(N);
10530     // Handle only simple case where vector being inserted and vector
10531     // being extracted are of same type, and are half size of larger vectors.
10532     EVT BigVT = V->getOperand(0).getValueType();
10533     EVT SmallVT = V->getOperand(1).getValueType();
10534     if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
10535       return SDValue();
10536
10537     // Only handle cases where both indexes are constants with the same type.
10538     ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
10539     ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
10540
10541     if (InsIdx && ExtIdx &&
10542         InsIdx->getValueType(0).getSizeInBits() <= 64 &&
10543         ExtIdx->getValueType(0).getSizeInBits() <= 64) {
10544       // Combine:
10545       //    (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
10546       // Into:
10547       //    indices are equal or bit offsets are equal => V1
10548       //    otherwise => (extract_subvec V1, ExtIdx)
10549       if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
10550           ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
10551         return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
10552       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
10553                          DAG.getNode(ISD::BITCAST, dl,
10554                                      N->getOperand(0).getValueType(),
10555                                      V->getOperand(0)), N->getOperand(1));
10556     }
10557   }
10558
10559   return SDValue();
10560 }
10561
10562 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat.
10563 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
10564   EVT VT = N->getValueType(0);
10565   unsigned NumElts = VT.getVectorNumElements();
10566
10567   SDValue N0 = N->getOperand(0);
10568   SDValue N1 = N->getOperand(1);
10569   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10570
10571   SmallVector<SDValue, 4> Ops;
10572   EVT ConcatVT = N0.getOperand(0).getValueType();
10573   unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
10574   unsigned NumConcats = NumElts / NumElemsPerConcat;
10575
10576   // Look at every vector that's inserted. We're looking for exact
10577   // subvector-sized copies from a concatenated vector
10578   for (unsigned I = 0; I != NumConcats; ++I) {
10579     // Make sure we're dealing with a copy.
10580     unsigned Begin = I * NumElemsPerConcat;
10581     bool AllUndef = true, NoUndef = true;
10582     for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
10583       if (SVN->getMaskElt(J) >= 0)
10584         AllUndef = false;
10585       else
10586         NoUndef = false;
10587     }
10588
10589     if (NoUndef) {
10590       if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
10591         return SDValue();
10592
10593       for (unsigned J = 1; J != NumElemsPerConcat; ++J)
10594         if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
10595           return SDValue();
10596
10597       unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
10598       if (FirstElt < N0.getNumOperands())
10599         Ops.push_back(N0.getOperand(FirstElt));
10600       else
10601         Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
10602
10603     } else if (AllUndef) {
10604       Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
10605     } else { // Mixed with general masks and undefs, can't do optimization.
10606       return SDValue();
10607     }
10608   }
10609
10610   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
10611 }
10612
10613 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
10614   EVT VT = N->getValueType(0);
10615   unsigned NumElts = VT.getVectorNumElements();
10616
10617   SDValue N0 = N->getOperand(0);
10618   SDValue N1 = N->getOperand(1);
10619
10620   assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
10621
10622   // Canonicalize shuffle undef, undef -> undef
10623   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
10624     return DAG.getUNDEF(VT);
10625
10626   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10627
10628   // Canonicalize shuffle v, v -> v, undef
10629   if (N0 == N1) {
10630     SmallVector<int, 8> NewMask;
10631     for (unsigned i = 0; i != NumElts; ++i) {
10632       int Idx = SVN->getMaskElt(i);
10633       if (Idx >= (int)NumElts) Idx -= NumElts;
10634       NewMask.push_back(Idx);
10635     }
10636     return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
10637                                 &NewMask[0]);
10638   }
10639
10640   // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
10641   if (N0.getOpcode() == ISD::UNDEF) {
10642     SmallVector<int, 8> NewMask;
10643     for (unsigned i = 0; i != NumElts; ++i) {
10644       int Idx = SVN->getMaskElt(i);
10645       if (Idx >= 0) {
10646         if (Idx >= (int)NumElts)
10647           Idx -= NumElts;
10648         else
10649           Idx = -1; // remove reference to lhs
10650       }
10651       NewMask.push_back(Idx);
10652     }
10653     return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
10654                                 &NewMask[0]);
10655   }
10656
10657   // Remove references to rhs if it is undef
10658   if (N1.getOpcode() == ISD::UNDEF) {
10659     bool Changed = false;
10660     SmallVector<int, 8> NewMask;
10661     for (unsigned i = 0; i != NumElts; ++i) {
10662       int Idx = SVN->getMaskElt(i);
10663       if (Idx >= (int)NumElts) {
10664         Idx = -1;
10665         Changed = true;
10666       }
10667       NewMask.push_back(Idx);
10668     }
10669     if (Changed)
10670       return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
10671   }
10672
10673   // If it is a splat, check if the argument vector is another splat or a
10674   // build_vector with all scalar elements the same.
10675   if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
10676     SDNode *V = N0.getNode();
10677
10678     // If this is a bit convert that changes the element type of the vector but
10679     // not the number of vector elements, look through it.  Be careful not to
10680     // look though conversions that change things like v4f32 to v2f64.
10681     if (V->getOpcode() == ISD::BITCAST) {
10682       SDValue ConvInput = V->getOperand(0);
10683       if (ConvInput.getValueType().isVector() &&
10684           ConvInput.getValueType().getVectorNumElements() == NumElts)
10685         V = ConvInput.getNode();
10686     }
10687
10688     if (V->getOpcode() == ISD::BUILD_VECTOR) {
10689       assert(V->getNumOperands() == NumElts &&
10690              "BUILD_VECTOR has wrong number of operands");
10691       SDValue Base;
10692       bool AllSame = true;
10693       for (unsigned i = 0; i != NumElts; ++i) {
10694         if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
10695           Base = V->getOperand(i);
10696           break;
10697         }
10698       }
10699       // Splat of <u, u, u, u>, return <u, u, u, u>
10700       if (!Base.getNode())
10701         return N0;
10702       for (unsigned i = 0; i != NumElts; ++i) {
10703         if (V->getOperand(i) != Base) {
10704           AllSame = false;
10705           break;
10706         }
10707       }
10708       // Splat of <x, x, x, x>, return <x, x, x, x>
10709       if (AllSame)
10710         return N0;
10711     }
10712   }
10713
10714   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
10715       Level < AfterLegalizeVectorOps &&
10716       (N1.getOpcode() == ISD::UNDEF ||
10717       (N1.getOpcode() == ISD::CONCAT_VECTORS &&
10718        N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
10719     SDValue V = partitionShuffleOfConcats(N, DAG);
10720
10721     if (V.getNode())
10722       return V;
10723   }
10724
10725   // If this shuffle node is simply a swizzle of another shuffle node,
10726   // then try to simplify it.
10727   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
10728       N1.getOpcode() == ISD::UNDEF) {
10729
10730     ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
10731
10732     // The incoming shuffle must be of the same type as the result of the
10733     // current shuffle.
10734     assert(OtherSV->getOperand(0).getValueType() == VT &&
10735            "Shuffle types don't match");
10736
10737     SmallVector<int, 4> Mask;
10738     // Compute the combined shuffle mask.
10739     for (unsigned i = 0; i != NumElts; ++i) {
10740       int Idx = SVN->getMaskElt(i);
10741       assert(Idx < (int)NumElts && "Index references undef operand");
10742       // Next, this index comes from the first value, which is the incoming
10743       // shuffle. Adopt the incoming index.
10744       if (Idx >= 0)
10745         Idx = OtherSV->getMaskElt(Idx);
10746       Mask.push_back(Idx);
10747     }
10748     
10749     bool CommuteOperands = false;
10750     if (N0.getOperand(1).getOpcode() != ISD::UNDEF) {
10751       // To be valid, the combine shuffle mask should only reference elements
10752       // from one of the two vectors in input to the inner shufflevector.
10753       bool IsValidMask = true;
10754       for (unsigned i = 0; i != NumElts && IsValidMask; ++i)
10755         // See if the combined mask only reference undefs or elements coming
10756         // from the first shufflevector operand.
10757         IsValidMask = Mask[i] < 0 || (unsigned)Mask[i] < NumElts;
10758
10759       if (!IsValidMask) {
10760         IsValidMask = true;
10761         for (unsigned i = 0; i != NumElts && IsValidMask; ++i)
10762           // Check that all the elements come from the second shuffle operand.
10763           IsValidMask = Mask[i] < 0 || (unsigned)Mask[i] >= NumElts;
10764         CommuteOperands = IsValidMask;
10765       }
10766
10767       // Early exit if the combined shuffle mask is not valid.
10768       if (!IsValidMask)
10769         return SDValue();
10770     }
10771
10772     // See if this pair of shuffles can be safely folded according to either
10773     // of the following rules:
10774     //   shuffle(shuffle(x, y), undef) -> x
10775     //   shuffle(shuffle(x, undef), undef) -> x
10776     //   shuffle(shuffle(x, y), undef) -> y
10777     bool IsIdentityMask = true;
10778     unsigned BaseMaskIndex = CommuteOperands ? NumElts : 0;
10779     for (unsigned i = 0; i != NumElts && IsIdentityMask; ++i) {
10780       // Skip Undefs.
10781       if (Mask[i] < 0)
10782         continue;
10783
10784       // The combined shuffle must map each index to itself.
10785       IsIdentityMask = (unsigned)Mask[i] == i + BaseMaskIndex;
10786     }
10787     
10788     if (IsIdentityMask) {
10789       if (CommuteOperands)
10790         // optimize shuffle(shuffle(x, y), undef) -> y.
10791         return OtherSV->getOperand(1);
10792       
10793       // optimize shuffle(shuffle(x, undef), undef) -> x
10794       // optimize shuffle(shuffle(x, y), undef) -> x
10795       return OtherSV->getOperand(0);
10796     }
10797
10798     // It may still be beneficial to combine the two shuffles if the
10799     // resulting shuffle is legal.
10800     if (TLI.isTypeLegal(VT) && TLI.isShuffleMaskLegal(Mask, VT)) {
10801       if (!CommuteOperands)
10802         // shuffle(shuffle(x, undef, M1), undef, M2) -> shuffle(x, undef, M3).
10803         // shuffle(shuffle(x, y, M1), undef, M2) -> shuffle(x, undef, M3)
10804         return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0), N1,
10805                                     &Mask[0]);
10806       
10807       //   shuffle(shuffle(x, y, M1), undef, M2) -> shuffle(undef, y, M3)
10808       return DAG.getVectorShuffle(VT, SDLoc(N), N1, N0->getOperand(1),
10809                                   &Mask[0]);
10810     }
10811   }
10812
10813   // Canonicalize shuffles according to rules:
10814   //  shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
10815   //  shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
10816   //  shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
10817   if (N1.getOpcode() == ISD::VECTOR_SHUFFLE && N0.getOpcode() != ISD::UNDEF &&
10818       N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
10819       TLI.isTypeLegal(VT)) {
10820     // The incoming shuffle must be of the same type as the result of the
10821     // current shuffle.
10822     assert(N1->getOperand(0).getValueType() == VT &&
10823            "Shuffle types don't match");
10824
10825     SDValue SV0 = N1->getOperand(0);
10826     SDValue SV1 = N1->getOperand(1);
10827     bool HasSameOp0 = N0 == SV0;
10828     bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
10829     if (HasSameOp0 || IsSV1Undef || N0 == SV1)
10830       // Commute the operands of this shuffle so that next rule
10831       // will trigger.
10832       return DAG.getCommutedVectorShuffle(*SVN);
10833   }
10834
10835   // Try to fold according to rules:
10836   //   shuffle(shuffle(A, B, M0), B, M1) -> shuffle(A, B, M2)
10837   //   shuffle(shuffle(A, B, M0), A, M1) -> shuffle(A, B, M2)
10838   //   shuffle(shuffle(A, Undef, M0), B, M1) -> shuffle(A, B, M2)
10839   //   shuffle(shuffle(A, Undef, M0), A, M1) -> shuffle(A, Undef, M2)
10840   // Don't try to fold shuffles with illegal type.
10841   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
10842       N1.getOpcode() != ISD::UNDEF && TLI.isTypeLegal(VT)) {
10843     ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
10844
10845     // The incoming shuffle must be of the same type as the result of the
10846     // current shuffle.
10847     assert(OtherSV->getOperand(0).getValueType() == VT &&
10848            "Shuffle types don't match");
10849
10850     SDValue SV0 = OtherSV->getOperand(0);
10851     SDValue SV1 = OtherSV->getOperand(1);
10852     bool HasSameOp0 = N1 == SV0;
10853     bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
10854     if (!HasSameOp0 && !IsSV1Undef && N1 != SV1)
10855       // Early exit.
10856       return SDValue();
10857
10858     SmallVector<int, 4> Mask;
10859     // Compute the combined shuffle mask for a shuffle with SV0 as the first
10860     // operand, and SV1 as the second operand.
10861     for (unsigned i = 0; i != NumElts; ++i) {
10862       int Idx = SVN->getMaskElt(i);
10863       if (Idx < 0) {
10864         // Propagate Undef.
10865         Mask.push_back(Idx);
10866         continue;
10867       }
10868
10869       if (Idx < (int)NumElts) {
10870         Idx = OtherSV->getMaskElt(Idx);
10871         if (IsSV1Undef && Idx >= (int) NumElts)
10872           Idx = -1;  // Propagate Undef.
10873       } else
10874         Idx = HasSameOp0 ? Idx - NumElts : Idx;
10875
10876       Mask.push_back(Idx);
10877     }
10878
10879     // Avoid introducing shuffles with illegal mask.
10880     if (TLI.isShuffleMaskLegal(Mask, VT)) {
10881       if (IsSV1Undef)
10882         //   shuffle(shuffle(A, Undef, M0), B, M1) -> shuffle(A, B, M2)
10883         //   shuffle(shuffle(A, Undef, M0), A, M1) -> shuffle(A, Undef, M2)
10884         return DAG.getVectorShuffle(VT, SDLoc(N), SV0, N1, &Mask[0]);
10885       return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, &Mask[0]);
10886     }
10887   }
10888
10889   return SDValue();
10890 }
10891
10892 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
10893   SDValue N0 = N->getOperand(0);
10894   SDValue N2 = N->getOperand(2);
10895
10896   // If the input vector is a concatenation, and the insert replaces
10897   // one of the halves, we can optimize into a single concat_vectors.
10898   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
10899       N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
10900     APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
10901     EVT VT = N->getValueType(0);
10902
10903     // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
10904     // (concat_vectors Z, Y)
10905     if (InsIdx == 0)
10906       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
10907                          N->getOperand(1), N0.getOperand(1));
10908
10909     // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
10910     // (concat_vectors X, Z)
10911     if (InsIdx == VT.getVectorNumElements()/2)
10912       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
10913                          N0.getOperand(0), N->getOperand(1));
10914   }
10915
10916   return SDValue();
10917 }
10918
10919 /// XformToShuffleWithZero - Returns a vector_shuffle if it able to transform
10920 /// an AND to a vector_shuffle with the destination vector and a zero vector.
10921 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
10922 ///      vector_shuffle V, Zero, <0, 4, 2, 4>
10923 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
10924   EVT VT = N->getValueType(0);
10925   SDLoc dl(N);
10926   SDValue LHS = N->getOperand(0);
10927   SDValue RHS = N->getOperand(1);
10928   if (N->getOpcode() == ISD::AND) {
10929     if (RHS.getOpcode() == ISD::BITCAST)
10930       RHS = RHS.getOperand(0);
10931     if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
10932       SmallVector<int, 8> Indices;
10933       unsigned NumElts = RHS.getNumOperands();
10934       for (unsigned i = 0; i != NumElts; ++i) {
10935         SDValue Elt = RHS.getOperand(i);
10936         if (!isa<ConstantSDNode>(Elt))
10937           return SDValue();
10938
10939         if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
10940           Indices.push_back(i);
10941         else if (cast<ConstantSDNode>(Elt)->isNullValue())
10942           Indices.push_back(NumElts);
10943         else
10944           return SDValue();
10945       }
10946
10947       // Let's see if the target supports this vector_shuffle.
10948       EVT RVT = RHS.getValueType();
10949       if (!TLI.isVectorClearMaskLegal(Indices, RVT))
10950         return SDValue();
10951
10952       // Return the new VECTOR_SHUFFLE node.
10953       EVT EltVT = RVT.getVectorElementType();
10954       SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
10955                                      DAG.getConstant(0, EltVT));
10956       SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), RVT, ZeroOps);
10957       LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
10958       SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
10959       return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
10960     }
10961   }
10962
10963   return SDValue();
10964 }
10965
10966 /// SimplifyVBinOp - Visit a binary vector operation, like ADD.
10967 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
10968   assert(N->getValueType(0).isVector() &&
10969          "SimplifyVBinOp only works on vectors!");
10970
10971   SDValue LHS = N->getOperand(0);
10972   SDValue RHS = N->getOperand(1);
10973   SDValue Shuffle = XformToShuffleWithZero(N);
10974   if (Shuffle.getNode()) return Shuffle;
10975
10976   // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
10977   // this operation.
10978   if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
10979       RHS.getOpcode() == ISD::BUILD_VECTOR) {
10980     // Check if both vectors are constants. If not bail out.
10981     if (!(cast<BuildVectorSDNode>(LHS)->isConstant() &&
10982           cast<BuildVectorSDNode>(RHS)->isConstant()))
10983       return SDValue();
10984
10985     SmallVector<SDValue, 8> Ops;
10986     for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
10987       SDValue LHSOp = LHS.getOperand(i);
10988       SDValue RHSOp = RHS.getOperand(i);
10989
10990       // Can't fold divide by zero.
10991       if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
10992           N->getOpcode() == ISD::FDIV) {
10993         if ((RHSOp.getOpcode() == ISD::Constant &&
10994              cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
10995             (RHSOp.getOpcode() == ISD::ConstantFP &&
10996              cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
10997           break;
10998       }
10999
11000       EVT VT = LHSOp.getValueType();
11001       EVT RVT = RHSOp.getValueType();
11002       if (RVT != VT) {
11003         // Integer BUILD_VECTOR operands may have types larger than the element
11004         // size (e.g., when the element type is not legal).  Prior to type
11005         // legalization, the types may not match between the two BUILD_VECTORS.
11006         // Truncate one of the operands to make them match.
11007         if (RVT.getSizeInBits() > VT.getSizeInBits()) {
11008           RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
11009         } else {
11010           LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
11011           VT = RVT;
11012         }
11013       }
11014       SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
11015                                    LHSOp, RHSOp);
11016       if (FoldOp.getOpcode() != ISD::UNDEF &&
11017           FoldOp.getOpcode() != ISD::Constant &&
11018           FoldOp.getOpcode() != ISD::ConstantFP)
11019         break;
11020       Ops.push_back(FoldOp);
11021       AddToWorklist(FoldOp.getNode());
11022     }
11023
11024     if (Ops.size() == LHS.getNumOperands())
11025       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), LHS.getValueType(), Ops);
11026   }
11027
11028   // Type legalization might introduce new shuffles in the DAG.
11029   // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
11030   //   -> (shuffle (VBinOp (A, B)), Undef, Mask).
11031   if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
11032       isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
11033       LHS.getOperand(1).getOpcode() == ISD::UNDEF &&
11034       RHS.getOperand(1).getOpcode() == ISD::UNDEF) {
11035     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
11036     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
11037
11038     if (SVN0->getMask().equals(SVN1->getMask())) {
11039       EVT VT = N->getValueType(0);
11040       SDValue UndefVector = LHS.getOperand(1);
11041       SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
11042                                      LHS.getOperand(0), RHS.getOperand(0));
11043       AddUsersToWorklist(N);
11044       return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
11045                                   &SVN0->getMask()[0]);
11046     }
11047   }
11048
11049   return SDValue();
11050 }
11051
11052 /// SimplifyVUnaryOp - Visit a binary vector operation, like FABS/FNEG.
11053 SDValue DAGCombiner::SimplifyVUnaryOp(SDNode *N) {
11054   assert(N->getValueType(0).isVector() &&
11055          "SimplifyVUnaryOp only works on vectors!");
11056
11057   SDValue N0 = N->getOperand(0);
11058
11059   if (N0.getOpcode() != ISD::BUILD_VECTOR)
11060     return SDValue();
11061
11062   // Operand is a BUILD_VECTOR node, see if we can constant fold it.
11063   SmallVector<SDValue, 8> Ops;
11064   for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
11065     SDValue Op = N0.getOperand(i);
11066     if (Op.getOpcode() != ISD::UNDEF &&
11067         Op.getOpcode() != ISD::ConstantFP)
11068       break;
11069     EVT EltVT = Op.getValueType();
11070     SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(N0), EltVT, Op);
11071     if (FoldOp.getOpcode() != ISD::UNDEF &&
11072         FoldOp.getOpcode() != ISD::ConstantFP)
11073       break;
11074     Ops.push_back(FoldOp);
11075     AddToWorklist(FoldOp.getNode());
11076   }
11077
11078   if (Ops.size() != N0.getNumOperands())
11079     return SDValue();
11080
11081   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), N0.getValueType(), Ops);
11082 }
11083
11084 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
11085                                     SDValue N1, SDValue N2){
11086   assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
11087
11088   SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
11089                                  cast<CondCodeSDNode>(N0.getOperand(2))->get());
11090
11091   // If we got a simplified select_cc node back from SimplifySelectCC, then
11092   // break it down into a new SETCC node, and a new SELECT node, and then return
11093   // the SELECT node, since we were called with a SELECT node.
11094   if (SCC.getNode()) {
11095     // Check to see if we got a select_cc back (to turn into setcc/select).
11096     // Otherwise, just return whatever node we got back, like fabs.
11097     if (SCC.getOpcode() == ISD::SELECT_CC) {
11098       SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
11099                                   N0.getValueType(),
11100                                   SCC.getOperand(0), SCC.getOperand(1),
11101                                   SCC.getOperand(4));
11102       AddToWorklist(SETCC.getNode());
11103       return DAG.getSelect(SDLoc(SCC), SCC.getValueType(),
11104                            SCC.getOperand(2), SCC.getOperand(3), SETCC);
11105     }
11106
11107     return SCC;
11108   }
11109   return SDValue();
11110 }
11111
11112 /// SimplifySelectOps - Given a SELECT or a SELECT_CC node, where LHS and RHS
11113 /// are the two values being selected between, see if we can simplify the
11114 /// select.  Callers of this should assume that TheSelect is deleted if this
11115 /// returns true.  As such, they should return the appropriate thing (e.g. the
11116 /// node) back to the top-level of the DAG combiner loop to avoid it being
11117 /// looked at.
11118 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
11119                                     SDValue RHS) {
11120
11121   // Cannot simplify select with vector condition
11122   if (TheSelect->getOperand(0).getValueType().isVector()) return false;
11123
11124   // If this is a select from two identical things, try to pull the operation
11125   // through the select.
11126   if (LHS.getOpcode() != RHS.getOpcode() ||
11127       !LHS.hasOneUse() || !RHS.hasOneUse())
11128     return false;
11129
11130   // If this is a load and the token chain is identical, replace the select
11131   // of two loads with a load through a select of the address to load from.
11132   // This triggers in things like "select bool X, 10.0, 123.0" after the FP
11133   // constants have been dropped into the constant pool.
11134   if (LHS.getOpcode() == ISD::LOAD) {
11135     LoadSDNode *LLD = cast<LoadSDNode>(LHS);
11136     LoadSDNode *RLD = cast<LoadSDNode>(RHS);
11137
11138     // Token chains must be identical.
11139     if (LHS.getOperand(0) != RHS.getOperand(0) ||
11140         // Do not let this transformation reduce the number of volatile loads.
11141         LLD->isVolatile() || RLD->isVolatile() ||
11142         // If this is an EXTLOAD, the VT's must match.
11143         LLD->getMemoryVT() != RLD->getMemoryVT() ||
11144         // If this is an EXTLOAD, the kind of extension must match.
11145         (LLD->getExtensionType() != RLD->getExtensionType() &&
11146          // The only exception is if one of the extensions is anyext.
11147          LLD->getExtensionType() != ISD::EXTLOAD &&
11148          RLD->getExtensionType() != ISD::EXTLOAD) ||
11149         // FIXME: this discards src value information.  This is
11150         // over-conservative. It would be beneficial to be able to remember
11151         // both potential memory locations.  Since we are discarding
11152         // src value info, don't do the transformation if the memory
11153         // locations are not in the default address space.
11154         LLD->getPointerInfo().getAddrSpace() != 0 ||
11155         RLD->getPointerInfo().getAddrSpace() != 0 ||
11156         !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
11157                                       LLD->getBasePtr().getValueType()))
11158       return false;
11159
11160     // Check that the select condition doesn't reach either load.  If so,
11161     // folding this will induce a cycle into the DAG.  If not, this is safe to
11162     // xform, so create a select of the addresses.
11163     SDValue Addr;
11164     if (TheSelect->getOpcode() == ISD::SELECT) {
11165       SDNode *CondNode = TheSelect->getOperand(0).getNode();
11166       if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
11167           (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
11168         return false;
11169       // The loads must not depend on one another.
11170       if (LLD->isPredecessorOf(RLD) ||
11171           RLD->isPredecessorOf(LLD))
11172         return false;
11173       Addr = DAG.getSelect(SDLoc(TheSelect),
11174                            LLD->getBasePtr().getValueType(),
11175                            TheSelect->getOperand(0), LLD->getBasePtr(),
11176                            RLD->getBasePtr());
11177     } else {  // Otherwise SELECT_CC
11178       SDNode *CondLHS = TheSelect->getOperand(0).getNode();
11179       SDNode *CondRHS = TheSelect->getOperand(1).getNode();
11180
11181       if ((LLD->hasAnyUseOfValue(1) &&
11182            (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
11183           (RLD->hasAnyUseOfValue(1) &&
11184            (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
11185         return false;
11186
11187       Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
11188                          LLD->getBasePtr().getValueType(),
11189                          TheSelect->getOperand(0),
11190                          TheSelect->getOperand(1),
11191                          LLD->getBasePtr(), RLD->getBasePtr(),
11192                          TheSelect->getOperand(4));
11193     }
11194
11195     SDValue Load;
11196     // It is safe to replace the two loads if they have different alignments,
11197     // but the new load must be the minimum (most restrictive) alignment of the
11198     // inputs.
11199     bool isInvariant = LLD->getAlignment() & RLD->getAlignment();
11200     unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment());
11201     if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
11202       Load = DAG.getLoad(TheSelect->getValueType(0),
11203                          SDLoc(TheSelect),
11204                          // FIXME: Discards pointer and AA info.
11205                          LLD->getChain(), Addr, MachinePointerInfo(),
11206                          LLD->isVolatile(), LLD->isNonTemporal(),
11207                          isInvariant, Alignment);
11208     } else {
11209       Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
11210                             RLD->getExtensionType() : LLD->getExtensionType(),
11211                             SDLoc(TheSelect),
11212                             TheSelect->getValueType(0),
11213                             // FIXME: Discards pointer and AA info.
11214                             LLD->getChain(), Addr, MachinePointerInfo(),
11215                             LLD->getMemoryVT(), LLD->isVolatile(),
11216                             LLD->isNonTemporal(), isInvariant, Alignment);
11217     }
11218
11219     // Users of the select now use the result of the load.
11220     CombineTo(TheSelect, Load);
11221
11222     // Users of the old loads now use the new load's chain.  We know the
11223     // old-load value is dead now.
11224     CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
11225     CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
11226     return true;
11227   }
11228
11229   return false;
11230 }
11231
11232 /// SimplifySelectCC - Simplify an expression of the form (N0 cond N1) ? N2 : N3
11233 /// where 'cond' is the comparison specified by CC.
11234 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
11235                                       SDValue N2, SDValue N3,
11236                                       ISD::CondCode CC, bool NotExtCompare) {
11237   // (x ? y : y) -> y.
11238   if (N2 == N3) return N2;
11239
11240   EVT VT = N2.getValueType();
11241   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
11242   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
11243   ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
11244
11245   // Determine if the condition we're dealing with is constant
11246   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
11247                               N0, N1, CC, DL, false);
11248   if (SCC.getNode()) AddToWorklist(SCC.getNode());
11249   ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
11250
11251   // fold select_cc true, x, y -> x
11252   if (SCCC && !SCCC->isNullValue())
11253     return N2;
11254   // fold select_cc false, x, y -> y
11255   if (SCCC && SCCC->isNullValue())
11256     return N3;
11257
11258   // Check to see if we can simplify the select into an fabs node
11259   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
11260     // Allow either -0.0 or 0.0
11261     if (CFP->getValueAPF().isZero()) {
11262       // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
11263       if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
11264           N0 == N2 && N3.getOpcode() == ISD::FNEG &&
11265           N2 == N3.getOperand(0))
11266         return DAG.getNode(ISD::FABS, DL, VT, N0);
11267
11268       // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
11269       if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
11270           N0 == N3 && N2.getOpcode() == ISD::FNEG &&
11271           N2.getOperand(0) == N3)
11272         return DAG.getNode(ISD::FABS, DL, VT, N3);
11273     }
11274   }
11275
11276   // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
11277   // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
11278   // in it.  This is a win when the constant is not otherwise available because
11279   // it replaces two constant pool loads with one.  We only do this if the FP
11280   // type is known to be legal, because if it isn't, then we are before legalize
11281   // types an we want the other legalization to happen first (e.g. to avoid
11282   // messing with soft float) and if the ConstantFP is not legal, because if
11283   // it is legal, we may not need to store the FP constant in a constant pool.
11284   if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
11285     if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
11286       if (TLI.isTypeLegal(N2.getValueType()) &&
11287           (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
11288                TargetLowering::Legal &&
11289            !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
11290            !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
11291           // If both constants have multiple uses, then we won't need to do an
11292           // extra load, they are likely around in registers for other users.
11293           (TV->hasOneUse() || FV->hasOneUse())) {
11294         Constant *Elts[] = {
11295           const_cast<ConstantFP*>(FV->getConstantFPValue()),
11296           const_cast<ConstantFP*>(TV->getConstantFPValue())
11297         };
11298         Type *FPTy = Elts[0]->getType();
11299         const DataLayout &TD = *TLI.getDataLayout();
11300
11301         // Create a ConstantArray of the two constants.
11302         Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
11303         SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
11304                                             TD.getPrefTypeAlignment(FPTy));
11305         unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
11306
11307         // Get the offsets to the 0 and 1 element of the array so that we can
11308         // select between them.
11309         SDValue Zero = DAG.getIntPtrConstant(0);
11310         unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
11311         SDValue One = DAG.getIntPtrConstant(EltSize);
11312
11313         SDValue Cond = DAG.getSetCC(DL,
11314                                     getSetCCResultType(N0.getValueType()),
11315                                     N0, N1, CC);
11316         AddToWorklist(Cond.getNode());
11317         SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
11318                                           Cond, One, Zero);
11319         AddToWorklist(CstOffset.getNode());
11320         CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
11321                             CstOffset);
11322         AddToWorklist(CPIdx.getNode());
11323         return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
11324                            MachinePointerInfo::getConstantPool(), false,
11325                            false, false, Alignment);
11326
11327       }
11328     }
11329
11330   // Check to see if we can perform the "gzip trick", transforming
11331   // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
11332   if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
11333       (N1C->isNullValue() ||                         // (a < 0) ? b : 0
11334        (N1C->getAPIntValue() == 1 && N0 == N2))) {   // (a < 1) ? a : 0
11335     EVT XType = N0.getValueType();
11336     EVT AType = N2.getValueType();
11337     if (XType.bitsGE(AType)) {
11338       // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
11339       // single-bit constant.
11340       if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
11341         unsigned ShCtV = N2C->getAPIntValue().logBase2();
11342         ShCtV = XType.getSizeInBits()-ShCtV-1;
11343         SDValue ShCt = DAG.getConstant(ShCtV,
11344                                        getShiftAmountTy(N0.getValueType()));
11345         SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
11346                                     XType, N0, ShCt);
11347         AddToWorklist(Shift.getNode());
11348
11349         if (XType.bitsGT(AType)) {
11350           Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
11351           AddToWorklist(Shift.getNode());
11352         }
11353
11354         return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
11355       }
11356
11357       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
11358                                   XType, N0,
11359                                   DAG.getConstant(XType.getSizeInBits()-1,
11360                                          getShiftAmountTy(N0.getValueType())));
11361       AddToWorklist(Shift.getNode());
11362
11363       if (XType.bitsGT(AType)) {
11364         Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
11365         AddToWorklist(Shift.getNode());
11366       }
11367
11368       return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
11369     }
11370   }
11371
11372   // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
11373   // where y is has a single bit set.
11374   // A plaintext description would be, we can turn the SELECT_CC into an AND
11375   // when the condition can be materialized as an all-ones register.  Any
11376   // single bit-test can be materialized as an all-ones register with
11377   // shift-left and shift-right-arith.
11378   if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
11379       N0->getValueType(0) == VT &&
11380       N1C && N1C->isNullValue() &&
11381       N2C && N2C->isNullValue()) {
11382     SDValue AndLHS = N0->getOperand(0);
11383     ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
11384     if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
11385       // Shift the tested bit over the sign bit.
11386       APInt AndMask = ConstAndRHS->getAPIntValue();
11387       SDValue ShlAmt =
11388         DAG.getConstant(AndMask.countLeadingZeros(),
11389                         getShiftAmountTy(AndLHS.getValueType()));
11390       SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
11391
11392       // Now arithmetic right shift it all the way over, so the result is either
11393       // all-ones, or zero.
11394       SDValue ShrAmt =
11395         DAG.getConstant(AndMask.getBitWidth()-1,
11396                         getShiftAmountTy(Shl.getValueType()));
11397       SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
11398
11399       return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
11400     }
11401   }
11402
11403   // fold select C, 16, 0 -> shl C, 4
11404   if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
11405       TLI.getBooleanContents(N0.getValueType()) ==
11406           TargetLowering::ZeroOrOneBooleanContent) {
11407
11408     // If the caller doesn't want us to simplify this into a zext of a compare,
11409     // don't do it.
11410     if (NotExtCompare && N2C->getAPIntValue() == 1)
11411       return SDValue();
11412
11413     // Get a SetCC of the condition
11414     // NOTE: Don't create a SETCC if it's not legal on this target.
11415     if (!LegalOperations ||
11416         TLI.isOperationLegal(ISD::SETCC,
11417           LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
11418       SDValue Temp, SCC;
11419       // cast from setcc result type to select result type
11420       if (LegalTypes) {
11421         SCC  = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
11422                             N0, N1, CC);
11423         if (N2.getValueType().bitsLT(SCC.getValueType()))
11424           Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
11425                                         N2.getValueType());
11426         else
11427           Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
11428                              N2.getValueType(), SCC);
11429       } else {
11430         SCC  = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
11431         Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
11432                            N2.getValueType(), SCC);
11433       }
11434
11435       AddToWorklist(SCC.getNode());
11436       AddToWorklist(Temp.getNode());
11437
11438       if (N2C->getAPIntValue() == 1)
11439         return Temp;
11440
11441       // shl setcc result by log2 n2c
11442       return DAG.getNode(
11443           ISD::SHL, DL, N2.getValueType(), Temp,
11444           DAG.getConstant(N2C->getAPIntValue().logBase2(),
11445                           getShiftAmountTy(Temp.getValueType())));
11446     }
11447   }
11448
11449   // Check to see if this is the equivalent of setcc
11450   // FIXME: Turn all of these into setcc if setcc if setcc is legal
11451   // otherwise, go ahead with the folds.
11452   if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
11453     EVT XType = N0.getValueType();
11454     if (!LegalOperations ||
11455         TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
11456       SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
11457       if (Res.getValueType() != VT)
11458         Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
11459       return Res;
11460     }
11461
11462     // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
11463     if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
11464         (!LegalOperations ||
11465          TLI.isOperationLegal(ISD::CTLZ, XType))) {
11466       SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
11467       return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
11468                          DAG.getConstant(Log2_32(XType.getSizeInBits()),
11469                                        getShiftAmountTy(Ctlz.getValueType())));
11470     }
11471     // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
11472     if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
11473       SDValue NegN0 = DAG.getNode(ISD::SUB, SDLoc(N0),
11474                                   XType, DAG.getConstant(0, XType), N0);
11475       SDValue NotN0 = DAG.getNOT(SDLoc(N0), N0, XType);
11476       return DAG.getNode(ISD::SRL, DL, XType,
11477                          DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
11478                          DAG.getConstant(XType.getSizeInBits()-1,
11479                                          getShiftAmountTy(XType)));
11480     }
11481     // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
11482     if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
11483       SDValue Sign = DAG.getNode(ISD::SRL, SDLoc(N0), XType, N0,
11484                                  DAG.getConstant(XType.getSizeInBits()-1,
11485                                          getShiftAmountTy(N0.getValueType())));
11486       return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
11487     }
11488   }
11489
11490   // Check to see if this is an integer abs.
11491   // select_cc setg[te] X,  0,  X, -X ->
11492   // select_cc setgt    X, -1,  X, -X ->
11493   // select_cc setl[te] X,  0, -X,  X ->
11494   // select_cc setlt    X,  1, -X,  X ->
11495   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
11496   if (N1C) {
11497     ConstantSDNode *SubC = nullptr;
11498     if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
11499          (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
11500         N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
11501       SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
11502     else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
11503               (N1C->isOne() && CC == ISD::SETLT)) &&
11504              N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
11505       SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
11506
11507     EVT XType = N0.getValueType();
11508     if (SubC && SubC->isNullValue() && XType.isInteger()) {
11509       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), XType,
11510                                   N0,
11511                                   DAG.getConstant(XType.getSizeInBits()-1,
11512                                          getShiftAmountTy(N0.getValueType())));
11513       SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0),
11514                                 XType, N0, Shift);
11515       AddToWorklist(Shift.getNode());
11516       AddToWorklist(Add.getNode());
11517       return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
11518     }
11519   }
11520
11521   return SDValue();
11522 }
11523
11524 /// SimplifySetCC - This is a stub for TargetLowering::SimplifySetCC.
11525 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
11526                                    SDValue N1, ISD::CondCode Cond,
11527                                    SDLoc DL, bool foldBooleans) {
11528   TargetLowering::DAGCombinerInfo
11529     DagCombineInfo(DAG, Level, false, this);
11530   return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
11531 }
11532
11533 /// BuildSDIV - Given an ISD::SDIV node expressing a divide by constant, return
11534 /// a DAG expression to select that will generate the same value by multiplying
11535 /// by a magic number.  See:
11536 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
11537 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
11538   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
11539   if (!C)
11540     return SDValue();
11541
11542   // Avoid division by zero.
11543   if (!C->getAPIntValue())
11544     return SDValue();
11545
11546   std::vector<SDNode*> Built;
11547   SDValue S =
11548       TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
11549
11550   for (SDNode *N : Built)
11551     AddToWorklist(N);
11552   return S;
11553 }
11554
11555 /// BuildSDIVPow2 - Given an ISD::SDIV node expressing a divide by constant
11556 /// power of 2, return a DAG expression to select that will generate the same
11557 /// value by right shifting.
11558 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
11559   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
11560   if (!C)
11561     return SDValue();
11562
11563   // Avoid division by zero.
11564   if (!C->getAPIntValue())
11565     return SDValue();
11566
11567   std::vector<SDNode *> Built;
11568   SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
11569
11570   for (SDNode *N : Built)
11571     AddToWorklist(N);
11572   return S;
11573 }
11574
11575 /// BuildUDIV - Given an ISD::UDIV node expressing a divide by constant,
11576 /// return a DAG expression to select that will generate the same value by
11577 /// multiplying by a magic number.  See:
11578 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
11579 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
11580   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
11581   if (!C)
11582     return SDValue();
11583
11584   // Avoid division by zero.
11585   if (!C->getAPIntValue())
11586     return SDValue();
11587
11588   std::vector<SDNode*> Built;
11589   SDValue S =
11590       TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
11591
11592   for (SDNode *N : Built)
11593     AddToWorklist(N);
11594   return S;
11595 }
11596
11597 /// FindBaseOffset - Return true if base is a frame index, which is known not
11598 // to alias with anything but itself.  Provides base object and offset as
11599 // results.
11600 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
11601                            const GlobalValue *&GV, const void *&CV) {
11602   // Assume it is a primitive operation.
11603   Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
11604
11605   // If it's an adding a simple constant then integrate the offset.
11606   if (Base.getOpcode() == ISD::ADD) {
11607     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
11608       Base = Base.getOperand(0);
11609       Offset += C->getZExtValue();
11610     }
11611   }
11612
11613   // Return the underlying GlobalValue, and update the Offset.  Return false
11614   // for GlobalAddressSDNode since the same GlobalAddress may be represented
11615   // by multiple nodes with different offsets.
11616   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
11617     GV = G->getGlobal();
11618     Offset += G->getOffset();
11619     return false;
11620   }
11621
11622   // Return the underlying Constant value, and update the Offset.  Return false
11623   // for ConstantSDNodes since the same constant pool entry may be represented
11624   // by multiple nodes with different offsets.
11625   if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
11626     CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
11627                                          : (const void *)C->getConstVal();
11628     Offset += C->getOffset();
11629     return false;
11630   }
11631   // If it's any of the following then it can't alias with anything but itself.
11632   return isa<FrameIndexSDNode>(Base);
11633 }
11634
11635 /// isAlias - Return true if there is any possibility that the two addresses
11636 /// overlap.
11637 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
11638   // If they are the same then they must be aliases.
11639   if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
11640
11641   // If they are both volatile then they cannot be reordered.
11642   if (Op0->isVolatile() && Op1->isVolatile()) return true;
11643
11644   // Gather base node and offset information.
11645   SDValue Base1, Base2;
11646   int64_t Offset1, Offset2;
11647   const GlobalValue *GV1, *GV2;
11648   const void *CV1, *CV2;
11649   bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
11650                                       Base1, Offset1, GV1, CV1);
11651   bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
11652                                       Base2, Offset2, GV2, CV2);
11653
11654   // If they have a same base address then check to see if they overlap.
11655   if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
11656     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
11657              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
11658
11659   // It is possible for different frame indices to alias each other, mostly
11660   // when tail call optimization reuses return address slots for arguments.
11661   // To catch this case, look up the actual index of frame indices to compute
11662   // the real alias relationship.
11663   if (isFrameIndex1 && isFrameIndex2) {
11664     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11665     Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
11666     Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
11667     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
11668              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
11669   }
11670
11671   // Otherwise, if we know what the bases are, and they aren't identical, then
11672   // we know they cannot alias.
11673   if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
11674     return false;
11675
11676   // If we know required SrcValue1 and SrcValue2 have relatively large alignment
11677   // compared to the size and offset of the access, we may be able to prove they
11678   // do not alias.  This check is conservative for now to catch cases created by
11679   // splitting vector types.
11680   if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
11681       (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
11682       (Op0->getMemoryVT().getSizeInBits() >> 3 ==
11683        Op1->getMemoryVT().getSizeInBits() >> 3) &&
11684       (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) {
11685     int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
11686     int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
11687
11688     // There is no overlap between these relatively aligned accesses of similar
11689     // size, return no alias.
11690     if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
11691         (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
11692       return false;
11693   }
11694
11695   bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0 ? CombinerGlobalAA :
11696     TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
11697 #ifndef NDEBUG
11698   if (CombinerAAOnlyFunc.getNumOccurrences() &&
11699       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
11700     UseAA = false;
11701 #endif
11702   if (UseAA &&
11703       Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
11704     // Use alias analysis information.
11705     int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
11706                                  Op1->getSrcValueOffset());
11707     int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
11708         Op0->getSrcValueOffset() - MinOffset;
11709     int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
11710         Op1->getSrcValueOffset() - MinOffset;
11711     AliasAnalysis::AliasResult AAResult =
11712         AA.alias(AliasAnalysis::Location(Op0->getMemOperand()->getValue(),
11713                                          Overlap1,
11714                                          UseTBAA ? Op0->getAAInfo() : AAMDNodes()),
11715                  AliasAnalysis::Location(Op1->getMemOperand()->getValue(),
11716                                          Overlap2,
11717                                          UseTBAA ? Op1->getAAInfo() : AAMDNodes()));
11718     if (AAResult == AliasAnalysis::NoAlias)
11719       return false;
11720   }
11721
11722   // Otherwise we have to assume they alias.
11723   return true;
11724 }
11725
11726 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
11727 /// looking for aliasing nodes and adding them to the Aliases vector.
11728 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
11729                                    SmallVectorImpl<SDValue> &Aliases) {
11730   SmallVector<SDValue, 8> Chains;     // List of chains to visit.
11731   SmallPtrSet<SDNode *, 16> Visited;  // Visited node set.
11732
11733   // Get alias information for node.
11734   bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
11735
11736   // Starting off.
11737   Chains.push_back(OriginalChain);
11738   unsigned Depth = 0;
11739
11740   // Look at each chain and determine if it is an alias.  If so, add it to the
11741   // aliases list.  If not, then continue up the chain looking for the next
11742   // candidate.
11743   while (!Chains.empty()) {
11744     SDValue Chain = Chains.back();
11745     Chains.pop_back();
11746
11747     // For TokenFactor nodes, look at each operand and only continue up the
11748     // chain until we find two aliases.  If we've seen two aliases, assume we'll
11749     // find more and revert to original chain since the xform is unlikely to be
11750     // profitable.
11751     //
11752     // FIXME: The depth check could be made to return the last non-aliasing
11753     // chain we found before we hit a tokenfactor rather than the original
11754     // chain.
11755     if (Depth > 6 || Aliases.size() == 2) {
11756       Aliases.clear();
11757       Aliases.push_back(OriginalChain);
11758       return;
11759     }
11760
11761     // Don't bother if we've been before.
11762     if (!Visited.insert(Chain.getNode()))
11763       continue;
11764
11765     switch (Chain.getOpcode()) {
11766     case ISD::EntryToken:
11767       // Entry token is ideal chain operand, but handled in FindBetterChain.
11768       break;
11769
11770     case ISD::LOAD:
11771     case ISD::STORE: {
11772       // Get alias information for Chain.
11773       bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
11774           !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
11775
11776       // If chain is alias then stop here.
11777       if (!(IsLoad && IsOpLoad) &&
11778           isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
11779         Aliases.push_back(Chain);
11780       } else {
11781         // Look further up the chain.
11782         Chains.push_back(Chain.getOperand(0));
11783         ++Depth;
11784       }
11785       break;
11786     }
11787
11788     case ISD::TokenFactor:
11789       // We have to check each of the operands of the token factor for "small"
11790       // token factors, so we queue them up.  Adding the operands to the queue
11791       // (stack) in reverse order maintains the original order and increases the
11792       // likelihood that getNode will find a matching token factor (CSE.)
11793       if (Chain.getNumOperands() > 16) {
11794         Aliases.push_back(Chain);
11795         break;
11796       }
11797       for (unsigned n = Chain.getNumOperands(); n;)
11798         Chains.push_back(Chain.getOperand(--n));
11799       ++Depth;
11800       break;
11801
11802     default:
11803       // For all other instructions we will just have to take what we can get.
11804       Aliases.push_back(Chain);
11805       break;
11806     }
11807   }
11808
11809   // We need to be careful here to also search for aliases through the
11810   // value operand of a store, etc. Consider the following situation:
11811   //   Token1 = ...
11812   //   L1 = load Token1, %52
11813   //   S1 = store Token1, L1, %51
11814   //   L2 = load Token1, %52+8
11815   //   S2 = store Token1, L2, %51+8
11816   //   Token2 = Token(S1, S2)
11817   //   L3 = load Token2, %53
11818   //   S3 = store Token2, L3, %52
11819   //   L4 = load Token2, %53+8
11820   //   S4 = store Token2, L4, %52+8
11821   // If we search for aliases of S3 (which loads address %52), and we look
11822   // only through the chain, then we'll miss the trivial dependence on L1
11823   // (which also loads from %52). We then might change all loads and
11824   // stores to use Token1 as their chain operand, which could result in
11825   // copying %53 into %52 before copying %52 into %51 (which should
11826   // happen first).
11827   //
11828   // The problem is, however, that searching for such data dependencies
11829   // can become expensive, and the cost is not directly related to the
11830   // chain depth. Instead, we'll rule out such configurations here by
11831   // insisting that we've visited all chain users (except for users
11832   // of the original chain, which is not necessary). When doing this,
11833   // we need to look through nodes we don't care about (otherwise, things
11834   // like register copies will interfere with trivial cases).
11835
11836   SmallVector<const SDNode *, 16> Worklist;
11837   for (SmallPtrSet<SDNode *, 16>::iterator I = Visited.begin(),
11838        IE = Visited.end(); I != IE; ++I)
11839     if (*I != OriginalChain.getNode())
11840       Worklist.push_back(*I);
11841
11842   while (!Worklist.empty()) {
11843     const SDNode *M = Worklist.pop_back_val();
11844
11845     // We have already visited M, and want to make sure we've visited any uses
11846     // of M that we care about. For uses that we've not visisted, and don't
11847     // care about, queue them to the worklist.
11848
11849     for (SDNode::use_iterator UI = M->use_begin(),
11850          UIE = M->use_end(); UI != UIE; ++UI)
11851       if (UI.getUse().getValueType() == MVT::Other && Visited.insert(*UI)) {
11852         if (isa<MemIntrinsicSDNode>(*UI) || isa<MemSDNode>(*UI)) {
11853           // We've not visited this use, and we care about it (it could have an
11854           // ordering dependency with the original node).
11855           Aliases.clear();
11856           Aliases.push_back(OriginalChain);
11857           return;
11858         }
11859
11860         // We've not visited this use, but we don't care about it. Mark it as
11861         // visited and enqueue it to the worklist.
11862         Worklist.push_back(*UI);
11863       }
11864   }
11865 }
11866
11867 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes, looking
11868 /// for a better chain (aliasing node.)
11869 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
11870   SmallVector<SDValue, 8> Aliases;  // Ops for replacing token factor.
11871
11872   // Accumulate all the aliases to this node.
11873   GatherAllAliases(N, OldChain, Aliases);
11874
11875   // If no operands then chain to entry token.
11876   if (Aliases.size() == 0)
11877     return DAG.getEntryNode();
11878
11879   // If a single operand then chain to it.  We don't need to revisit it.
11880   if (Aliases.size() == 1)
11881     return Aliases[0];
11882
11883   // Construct a custom tailored token factor.
11884   return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
11885 }
11886
11887 // SelectionDAG::Combine - This is the entry point for the file.
11888 //
11889 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
11890                            CodeGenOpt::Level OptLevel) {
11891   /// run - This is the main entry point to this class.
11892   ///
11893   DAGCombiner(*this, AA, OptLevel).Run(Level);
11894 }