094dce193fbb4f9775382ac20adfdb9e4e6de83e
[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().getTargetLowering()->isFMAFasterThanFMulAndFAdd(VT) &&
6710       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6711
6712     // fold (fadd (fmul x, y), z) -> (fma x, y, z)
6713     if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
6714       return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6715                          N0.getOperand(0), N0.getOperand(1), N1);
6716
6717     // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
6718     // Note: Commutes FADD operands.
6719     if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
6720       return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6721                          N1.getOperand(0), N1.getOperand(1), N0);
6722   }
6723
6724   return SDValue();
6725 }
6726
6727 SDValue DAGCombiner::visitFSUB(SDNode *N) {
6728   SDValue N0 = N->getOperand(0);
6729   SDValue N1 = N->getOperand(1);
6730   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6731   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6732   EVT VT = N->getValueType(0);
6733   SDLoc dl(N);
6734
6735   // fold vector ops
6736   if (VT.isVector()) {
6737     SDValue FoldedVOp = SimplifyVBinOp(N);
6738     if (FoldedVOp.getNode()) return FoldedVOp;
6739   }
6740
6741   // fold (fsub c1, c2) -> c1-c2
6742   if (N0CFP && N1CFP)
6743     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0, N1);
6744   // fold (fsub A, 0) -> A
6745   if (DAG.getTarget().Options.UnsafeFPMath &&
6746       N1CFP && N1CFP->getValueAPF().isZero())
6747     return N0;
6748   // fold (fsub 0, B) -> -B
6749   if (DAG.getTarget().Options.UnsafeFPMath &&
6750       N0CFP && N0CFP->getValueAPF().isZero()) {
6751     if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
6752       return GetNegatedExpression(N1, DAG, LegalOperations);
6753     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6754       return DAG.getNode(ISD::FNEG, dl, VT, N1);
6755   }
6756   // fold (fsub A, (fneg B)) -> (fadd A, B)
6757   if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
6758     return DAG.getNode(ISD::FADD, dl, VT, N0,
6759                        GetNegatedExpression(N1, DAG, LegalOperations));
6760
6761   // If 'unsafe math' is enabled, fold
6762   //    (fsub x, x) -> 0.0 &
6763   //    (fsub x, (fadd x, y)) -> (fneg y) &
6764   //    (fsub x, (fadd y, x)) -> (fneg y)
6765   if (DAG.getTarget().Options.UnsafeFPMath) {
6766     if (N0 == N1)
6767       return DAG.getConstantFP(0.0f, VT);
6768
6769     if (N1.getOpcode() == ISD::FADD) {
6770       SDValue N10 = N1->getOperand(0);
6771       SDValue N11 = N1->getOperand(1);
6772
6773       if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI,
6774                                           &DAG.getTarget().Options))
6775         return GetNegatedExpression(N11, DAG, LegalOperations);
6776
6777       if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI,
6778                                           &DAG.getTarget().Options))
6779         return GetNegatedExpression(N10, DAG, LegalOperations);
6780     }
6781   }
6782
6783   // FSUB -> FMA combines:
6784   if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
6785        DAG.getTarget().Options.UnsafeFPMath) &&
6786       DAG.getTarget().getTargetLowering()->isFMAFasterThanFMulAndFAdd(VT) &&
6787       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6788
6789     // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
6790     if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
6791       return DAG.getNode(ISD::FMA, dl, VT,
6792                          N0.getOperand(0), N0.getOperand(1),
6793                          DAG.getNode(ISD::FNEG, dl, VT, N1));
6794
6795     // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
6796     // Note: Commutes FSUB operands.
6797     if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
6798       return DAG.getNode(ISD::FMA, dl, VT,
6799                          DAG.getNode(ISD::FNEG, dl, VT,
6800                          N1.getOperand(0)),
6801                          N1.getOperand(1), N0);
6802
6803     // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
6804     if (N0.getOpcode() == ISD::FNEG &&
6805         N0.getOperand(0).getOpcode() == ISD::FMUL &&
6806         N0->hasOneUse() && N0.getOperand(0).hasOneUse()) {
6807       SDValue N00 = N0.getOperand(0).getOperand(0);
6808       SDValue N01 = N0.getOperand(0).getOperand(1);
6809       return DAG.getNode(ISD::FMA, dl, VT,
6810                          DAG.getNode(ISD::FNEG, dl, VT, N00), N01,
6811                          DAG.getNode(ISD::FNEG, dl, VT, N1));
6812     }
6813   }
6814
6815   return SDValue();
6816 }
6817
6818 SDValue DAGCombiner::visitFMUL(SDNode *N) {
6819   SDValue N0 = N->getOperand(0);
6820   SDValue N1 = N->getOperand(1);
6821   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6822   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6823   EVT VT = N->getValueType(0);
6824   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6825
6826   // fold vector ops
6827   if (VT.isVector()) {
6828     SDValue FoldedVOp = SimplifyVBinOp(N);
6829     if (FoldedVOp.getNode()) return FoldedVOp;
6830   }
6831
6832   // fold (fmul c1, c2) -> c1*c2
6833   if (N0CFP && N1CFP)
6834     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, N1);
6835   // canonicalize constant to RHS
6836   if (N0CFP && !N1CFP)
6837     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, N0);
6838   // fold (fmul A, 0) -> 0
6839   if (DAG.getTarget().Options.UnsafeFPMath &&
6840       N1CFP && N1CFP->getValueAPF().isZero())
6841     return N1;
6842   // fold (fmul A, 0) -> 0, vector edition.
6843   if (DAG.getTarget().Options.UnsafeFPMath &&
6844       ISD::isBuildVectorAllZeros(N1.getNode()))
6845     return N1;
6846   // fold (fmul A, 1.0) -> A
6847   if (N1CFP && N1CFP->isExactlyValue(1.0))
6848     return N0;
6849   // fold (fmul X, 2.0) -> (fadd X, X)
6850   if (N1CFP && N1CFP->isExactlyValue(+2.0))
6851     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N0);
6852   // fold (fmul X, -1.0) -> (fneg X)
6853   if (N1CFP && N1CFP->isExactlyValue(-1.0))
6854     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6855       return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
6856
6857   // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
6858   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
6859                                        &DAG.getTarget().Options)) {
6860     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
6861                                          &DAG.getTarget().Options)) {
6862       // Both can be negated for free, check to see if at least one is cheaper
6863       // negated.
6864       if (LHSNeg == 2 || RHSNeg == 2)
6865         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6866                            GetNegatedExpression(N0, DAG, LegalOperations),
6867                            GetNegatedExpression(N1, DAG, LegalOperations));
6868     }
6869   }
6870
6871   // If allowed, fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
6872   if (DAG.getTarget().Options.UnsafeFPMath &&
6873       N1CFP && N0.getOpcode() == ISD::FMUL &&
6874       N0.getNode()->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
6875     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
6876                        DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6877                                    N0.getOperand(1), N1));
6878
6879   return SDValue();
6880 }
6881
6882 SDValue DAGCombiner::visitFMA(SDNode *N) {
6883   SDValue N0 = N->getOperand(0);
6884   SDValue N1 = N->getOperand(1);
6885   SDValue N2 = N->getOperand(2);
6886   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6887   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6888   EVT VT = N->getValueType(0);
6889   SDLoc dl(N);
6890
6891
6892   // Constant fold FMA.
6893   if (isa<ConstantFPSDNode>(N0) &&
6894       isa<ConstantFPSDNode>(N1) &&
6895       isa<ConstantFPSDNode>(N2)) {
6896     return DAG.getNode(ISD::FMA, dl, VT, N0, N1, N2);
6897   }
6898
6899   if (DAG.getTarget().Options.UnsafeFPMath) {
6900     if (N0CFP && N0CFP->isZero())
6901       return N2;
6902     if (N1CFP && N1CFP->isZero())
6903       return N2;
6904   }
6905   if (N0CFP && N0CFP->isExactlyValue(1.0))
6906     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
6907   if (N1CFP && N1CFP->isExactlyValue(1.0))
6908     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
6909
6910   // Canonicalize (fma c, x, y) -> (fma x, c, y)
6911   if (N0CFP && !N1CFP)
6912     return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
6913
6914   // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
6915   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6916       N2.getOpcode() == ISD::FMUL &&
6917       N0 == N2.getOperand(0) &&
6918       N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
6919     return DAG.getNode(ISD::FMUL, dl, VT, N0,
6920                        DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
6921   }
6922
6923
6924   // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
6925   if (DAG.getTarget().Options.UnsafeFPMath &&
6926       N0.getOpcode() == ISD::FMUL && N1CFP &&
6927       N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
6928     return DAG.getNode(ISD::FMA, dl, VT,
6929                        N0.getOperand(0),
6930                        DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
6931                        N2);
6932   }
6933
6934   // (fma x, 1, y) -> (fadd x, y)
6935   // (fma x, -1, y) -> (fadd (fneg x), y)
6936   if (N1CFP) {
6937     if (N1CFP->isExactlyValue(1.0))
6938       return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
6939
6940     if (N1CFP->isExactlyValue(-1.0) &&
6941         (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
6942       SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
6943       AddToWorklist(RHSNeg.getNode());
6944       return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
6945     }
6946   }
6947
6948   // (fma x, c, x) -> (fmul x, (c+1))
6949   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP && N0 == N2)
6950     return DAG.getNode(ISD::FMUL, dl, VT, N0,
6951                        DAG.getNode(ISD::FADD, dl, VT,
6952                                    N1, DAG.getConstantFP(1.0, VT)));
6953
6954   // (fma x, c, (fneg x)) -> (fmul x, (c-1))
6955   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6956       N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
6957     return DAG.getNode(ISD::FMUL, dl, VT, N0,
6958                        DAG.getNode(ISD::FADD, dl, VT,
6959                                    N1, DAG.getConstantFP(-1.0, VT)));
6960
6961
6962   return SDValue();
6963 }
6964
6965 SDValue DAGCombiner::visitFDIV(SDNode *N) {
6966   SDValue N0 = N->getOperand(0);
6967   SDValue N1 = N->getOperand(1);
6968   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6969   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6970   EVT VT = N->getValueType(0);
6971   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6972
6973   // fold vector ops
6974   if (VT.isVector()) {
6975     SDValue FoldedVOp = SimplifyVBinOp(N);
6976     if (FoldedVOp.getNode()) return FoldedVOp;
6977   }
6978
6979   // fold (fdiv c1, c2) -> c1/c2
6980   if (N0CFP && N1CFP)
6981     return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
6982
6983   // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
6984   if (N1CFP && DAG.getTarget().Options.UnsafeFPMath) {
6985     // Compute the reciprocal 1.0 / c2.
6986     APFloat N1APF = N1CFP->getValueAPF();
6987     APFloat Recip(N1APF.getSemantics(), 1); // 1.0
6988     APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
6989     // Only do the transform if the reciprocal is a legal fp immediate that
6990     // isn't too nasty (eg NaN, denormal, ...).
6991     if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
6992         (!LegalOperations ||
6993          // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
6994          // backend)... we should handle this gracefully after Legalize.
6995          // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
6996          TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
6997          TLI.isFPImmLegal(Recip, VT)))
6998       return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0,
6999                          DAG.getConstantFP(Recip, VT));
7000   }
7001
7002   // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
7003   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
7004                                        &DAG.getTarget().Options)) {
7005     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
7006                                          &DAG.getTarget().Options)) {
7007       // Both can be negated for free, check to see if at least one is cheaper
7008       // negated.
7009       if (LHSNeg == 2 || RHSNeg == 2)
7010         return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
7011                            GetNegatedExpression(N0, DAG, LegalOperations),
7012                            GetNegatedExpression(N1, DAG, LegalOperations));
7013     }
7014   }
7015
7016   return SDValue();
7017 }
7018
7019 SDValue DAGCombiner::visitFREM(SDNode *N) {
7020   SDValue N0 = N->getOperand(0);
7021   SDValue N1 = N->getOperand(1);
7022   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7023   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7024   EVT VT = N->getValueType(0);
7025
7026   // fold (frem c1, c2) -> fmod(c1,c2)
7027   if (N0CFP && N1CFP)
7028     return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
7029
7030   return SDValue();
7031 }
7032
7033 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
7034   SDValue N0 = N->getOperand(0);
7035   SDValue N1 = N->getOperand(1);
7036   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7037   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7038   EVT VT = N->getValueType(0);
7039
7040   if (N0CFP && N1CFP)  // Constant fold
7041     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
7042
7043   if (N1CFP) {
7044     const APFloat& V = N1CFP->getValueAPF();
7045     // copysign(x, c1) -> fabs(x)       iff ispos(c1)
7046     // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
7047     if (!V.isNegative()) {
7048       if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
7049         return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7050     } else {
7051       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
7052         return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
7053                            DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
7054     }
7055   }
7056
7057   // copysign(fabs(x), y) -> copysign(x, y)
7058   // copysign(fneg(x), y) -> copysign(x, y)
7059   // copysign(copysign(x,z), y) -> copysign(x, y)
7060   if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
7061       N0.getOpcode() == ISD::FCOPYSIGN)
7062     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7063                        N0.getOperand(0), N1);
7064
7065   // copysign(x, abs(y)) -> abs(x)
7066   if (N1.getOpcode() == ISD::FABS)
7067     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7068
7069   // copysign(x, copysign(y,z)) -> copysign(x, z)
7070   if (N1.getOpcode() == ISD::FCOPYSIGN)
7071     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7072                        N0, N1.getOperand(1));
7073
7074   // copysign(x, fp_extend(y)) -> copysign(x, y)
7075   // copysign(x, fp_round(y)) -> copysign(x, y)
7076   if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
7077     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7078                        N0, N1.getOperand(0));
7079
7080   return SDValue();
7081 }
7082
7083 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
7084   SDValue N0 = N->getOperand(0);
7085   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
7086   EVT VT = N->getValueType(0);
7087   EVT OpVT = N0.getValueType();
7088
7089   // fold (sint_to_fp c1) -> c1fp
7090   if (N0C &&
7091       // ...but only if the target supports immediate floating-point values
7092       (!LegalOperations ||
7093        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
7094     return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
7095
7096   // If the input is a legal type, and SINT_TO_FP is not legal on this target,
7097   // but UINT_TO_FP is legal on this target, try to convert.
7098   if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
7099       TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
7100     // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
7101     if (DAG.SignBitIsZero(N0))
7102       return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
7103   }
7104
7105   // The next optimizations are desirable only if SELECT_CC can be lowered.
7106   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
7107     // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
7108     if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
7109         !VT.isVector() &&
7110         (!LegalOperations ||
7111          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7112       SDValue Ops[] =
7113         { N0.getOperand(0), N0.getOperand(1),
7114           DAG.getConstantFP(-1.0, VT) , DAG.getConstantFP(0.0, VT),
7115           N0.getOperand(2) };
7116       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7117     }
7118
7119     // fold (sint_to_fp (zext (setcc x, y, cc))) ->
7120     //      (select_cc x, y, 1.0, 0.0,, cc)
7121     if (N0.getOpcode() == ISD::ZERO_EXTEND &&
7122         N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
7123         (!LegalOperations ||
7124          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7125       SDValue Ops[] =
7126         { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
7127           DAG.getConstantFP(1.0, VT) , DAG.getConstantFP(0.0, VT),
7128           N0.getOperand(0).getOperand(2) };
7129       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7130     }
7131   }
7132
7133   return SDValue();
7134 }
7135
7136 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
7137   SDValue N0 = N->getOperand(0);
7138   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
7139   EVT VT = N->getValueType(0);
7140   EVT OpVT = N0.getValueType();
7141
7142   // fold (uint_to_fp c1) -> c1fp
7143   if (N0C &&
7144       // ...but only if the target supports immediate floating-point values
7145       (!LegalOperations ||
7146        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
7147     return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
7148
7149   // If the input is a legal type, and UINT_TO_FP is not legal on this target,
7150   // but SINT_TO_FP is legal on this target, try to convert.
7151   if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
7152       TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
7153     // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
7154     if (DAG.SignBitIsZero(N0))
7155       return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
7156   }
7157
7158   // The next optimizations are desirable only if SELECT_CC can be lowered.
7159   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
7160     // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
7161
7162     if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
7163         (!LegalOperations ||
7164          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7165       SDValue Ops[] =
7166         { N0.getOperand(0), N0.getOperand(1),
7167           DAG.getConstantFP(1.0, VT),  DAG.getConstantFP(0.0, VT),
7168           N0.getOperand(2) };
7169       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7170     }
7171   }
7172
7173   return SDValue();
7174 }
7175
7176 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
7177   SDValue N0 = N->getOperand(0);
7178   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7179   EVT VT = N->getValueType(0);
7180
7181   // fold (fp_to_sint c1fp) -> c1
7182   if (N0CFP)
7183     return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
7184
7185   return SDValue();
7186 }
7187
7188 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
7189   SDValue N0 = N->getOperand(0);
7190   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7191   EVT VT = N->getValueType(0);
7192
7193   // fold (fp_to_uint c1fp) -> c1
7194   if (N0CFP)
7195     return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
7196
7197   return SDValue();
7198 }
7199
7200 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
7201   SDValue N0 = N->getOperand(0);
7202   SDValue N1 = N->getOperand(1);
7203   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7204   EVT VT = N->getValueType(0);
7205
7206   // fold (fp_round c1fp) -> c1fp
7207   if (N0CFP)
7208     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
7209
7210   // fold (fp_round (fp_extend x)) -> x
7211   if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
7212     return N0.getOperand(0);
7213
7214   // fold (fp_round (fp_round x)) -> (fp_round x)
7215   if (N0.getOpcode() == ISD::FP_ROUND) {
7216     // This is a value preserving truncation if both round's are.
7217     bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
7218                    N0.getNode()->getConstantOperandVal(1) == 1;
7219     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0.getOperand(0),
7220                        DAG.getIntPtrConstant(IsTrunc));
7221   }
7222
7223   // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
7224   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
7225     SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
7226                               N0.getOperand(0), N1);
7227     AddToWorklist(Tmp.getNode());
7228     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7229                        Tmp, N0.getOperand(1));
7230   }
7231
7232   return SDValue();
7233 }
7234
7235 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
7236   SDValue N0 = N->getOperand(0);
7237   EVT VT = N->getValueType(0);
7238   EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
7239   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7240
7241   // fold (fp_round_inreg c1fp) -> c1fp
7242   if (N0CFP && isTypeLegal(EVT)) {
7243     SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
7244     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, Round);
7245   }
7246
7247   return SDValue();
7248 }
7249
7250 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
7251   SDValue N0 = N->getOperand(0);
7252   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7253   EVT VT = N->getValueType(0);
7254
7255   // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
7256   if (N->hasOneUse() &&
7257       N->use_begin()->getOpcode() == ISD::FP_ROUND)
7258     return SDValue();
7259
7260   // fold (fp_extend c1fp) -> c1fp
7261   if (N0CFP)
7262     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
7263
7264   // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
7265   // value of X.
7266   if (N0.getOpcode() == ISD::FP_ROUND
7267       && N0.getNode()->getConstantOperandVal(1) == 1) {
7268     SDValue In = N0.getOperand(0);
7269     if (In.getValueType() == VT) return In;
7270     if (VT.bitsLT(In.getValueType()))
7271       return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
7272                          In, N0.getOperand(1));
7273     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
7274   }
7275
7276   // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
7277   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7278        TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType())) {
7279     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7280     SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
7281                                      LN0->getChain(),
7282                                      LN0->getBasePtr(), N0.getValueType(),
7283                                      LN0->getMemOperand());
7284     CombineTo(N, ExtLoad);
7285     CombineTo(N0.getNode(),
7286               DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
7287                           N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
7288               ExtLoad.getValue(1));
7289     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7290   }
7291
7292   return SDValue();
7293 }
7294
7295 SDValue DAGCombiner::visitFNEG(SDNode *N) {
7296   SDValue N0 = N->getOperand(0);
7297   EVT VT = N->getValueType(0);
7298
7299   // Constant fold FNEG.
7300   if (isa<ConstantFPSDNode>(N0))
7301     return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N->getOperand(0));
7302
7303   if (VT.isVector()) {
7304     SDValue FoldedVOp = SimplifyVUnaryOp(N);
7305     if (FoldedVOp.getNode()) return FoldedVOp;
7306   }
7307
7308   if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
7309                          &DAG.getTarget().Options))
7310     return GetNegatedExpression(N0, DAG, LegalOperations);
7311
7312   // Transform fneg(bitconvert(x)) -> bitconvert(x^sign) to avoid loading
7313   // constant pool values.
7314   // TODO: We can also optimize for vectors here, but we need to make sure
7315   // that the sign mask is created properly for each vector element.
7316   if (!TLI.isFNegFree(VT) && N0.getOpcode() == ISD::BITCAST &&
7317       !VT.isVector() &&
7318       N0.getNode()->hasOneUse() &&
7319       N0.getOperand(0).getValueType().isInteger()) {
7320     SDValue Int = N0.getOperand(0);
7321     EVT IntVT = Int.getValueType();
7322     if (IntVT.isInteger() && !IntVT.isVector()) {
7323       Int = DAG.getNode(ISD::XOR, SDLoc(N0), IntVT, Int,
7324               DAG.getConstant(APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
7325       AddToWorklist(Int.getNode());
7326       return DAG.getNode(ISD::BITCAST, SDLoc(N),
7327                          VT, Int);
7328     }
7329   }
7330
7331   // (fneg (fmul c, x)) -> (fmul -c, x)
7332   if (N0.getOpcode() == ISD::FMUL) {
7333     ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
7334     if (CFP1) {
7335       APFloat CVal = CFP1->getValueAPF();
7336       CVal.changeSign();
7337       if (Level >= AfterLegalizeDAG &&
7338           (TLI.isFPImmLegal(CVal, N->getValueType(0)) ||
7339            TLI.isOperationLegal(ISD::ConstantFP, N->getValueType(0))))
7340         return DAG.getNode(
7341             ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
7342             DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0.getOperand(1)));
7343     }
7344   }
7345
7346   return SDValue();
7347 }
7348
7349 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
7350   SDValue N0 = N->getOperand(0);
7351   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7352   EVT VT = N->getValueType(0);
7353
7354   // fold (fceil c1) -> fceil(c1)
7355   if (N0CFP)
7356     return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
7357
7358   return SDValue();
7359 }
7360
7361 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
7362   SDValue N0 = N->getOperand(0);
7363   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7364   EVT VT = N->getValueType(0);
7365
7366   // fold (ftrunc c1) -> ftrunc(c1)
7367   if (N0CFP)
7368     return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
7369
7370   return SDValue();
7371 }
7372
7373 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
7374   SDValue N0 = N->getOperand(0);
7375   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7376   EVT VT = N->getValueType(0);
7377
7378   // fold (ffloor c1) -> ffloor(c1)
7379   if (N0CFP)
7380     return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
7381
7382   return SDValue();
7383 }
7384
7385 SDValue DAGCombiner::visitFABS(SDNode *N) {
7386   SDValue N0 = N->getOperand(0);
7387   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7388   EVT VT = N->getValueType(0);
7389
7390   if (VT.isVector()) {
7391     SDValue FoldedVOp = SimplifyVUnaryOp(N);
7392     if (FoldedVOp.getNode()) return FoldedVOp;
7393   }
7394
7395   // fold (fabs c1) -> fabs(c1)
7396   if (N0CFP)
7397     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7398   // fold (fabs (fabs x)) -> (fabs x)
7399   if (N0.getOpcode() == ISD::FABS)
7400     return N->getOperand(0);
7401   // fold (fabs (fneg x)) -> (fabs x)
7402   // fold (fabs (fcopysign x, y)) -> (fabs x)
7403   if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
7404     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
7405
7406   // Transform fabs(bitconvert(x)) -> bitconvert(x&~sign) to avoid loading
7407   // constant pool values.
7408   // TODO: We can also optimize for vectors here, but we need to make sure
7409   // that the sign mask is created properly for each vector element.
7410   if (!TLI.isFAbsFree(VT) &&
7411       N0.getOpcode() == ISD::BITCAST && N0.getNode()->hasOneUse() &&
7412       N0.getOperand(0).getValueType().isInteger() &&
7413       !VT.isVector()) {
7414     SDValue Int = N0.getOperand(0);
7415     EVT IntVT = Int.getValueType();
7416     if (IntVT.isInteger() && !IntVT.isVector()) {
7417       Int = DAG.getNode(ISD::AND, SDLoc(N0), IntVT, Int,
7418              DAG.getConstant(~APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
7419       AddToWorklist(Int.getNode());
7420       return DAG.getNode(ISD::BITCAST, SDLoc(N),
7421                          N->getValueType(0), Int);
7422     }
7423   }
7424
7425   return SDValue();
7426 }
7427
7428 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
7429   SDValue Chain = N->getOperand(0);
7430   SDValue N1 = N->getOperand(1);
7431   SDValue N2 = N->getOperand(2);
7432
7433   // If N is a constant we could fold this into a fallthrough or unconditional
7434   // branch. However that doesn't happen very often in normal code, because
7435   // Instcombine/SimplifyCFG should have handled the available opportunities.
7436   // If we did this folding here, it would be necessary to update the
7437   // MachineBasicBlock CFG, which is awkward.
7438
7439   // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
7440   // on the target.
7441   if (N1.getOpcode() == ISD::SETCC &&
7442       TLI.isOperationLegalOrCustom(ISD::BR_CC,
7443                                    N1.getOperand(0).getValueType())) {
7444     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7445                        Chain, N1.getOperand(2),
7446                        N1.getOperand(0), N1.getOperand(1), N2);
7447   }
7448
7449   if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
7450       ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
7451        (N1.getOperand(0).hasOneUse() &&
7452         N1.getOperand(0).getOpcode() == ISD::SRL))) {
7453     SDNode *Trunc = nullptr;
7454     if (N1.getOpcode() == ISD::TRUNCATE) {
7455       // Look pass the truncate.
7456       Trunc = N1.getNode();
7457       N1 = N1.getOperand(0);
7458     }
7459
7460     // Match this pattern so that we can generate simpler code:
7461     //
7462     //   %a = ...
7463     //   %b = and i32 %a, 2
7464     //   %c = srl i32 %b, 1
7465     //   brcond i32 %c ...
7466     //
7467     // into
7468     //
7469     //   %a = ...
7470     //   %b = and i32 %a, 2
7471     //   %c = setcc eq %b, 0
7472     //   brcond %c ...
7473     //
7474     // This applies only when the AND constant value has one bit set and the
7475     // SRL constant is equal to the log2 of the AND constant. The back-end is
7476     // smart enough to convert the result into a TEST/JMP sequence.
7477     SDValue Op0 = N1.getOperand(0);
7478     SDValue Op1 = N1.getOperand(1);
7479
7480     if (Op0.getOpcode() == ISD::AND &&
7481         Op1.getOpcode() == ISD::Constant) {
7482       SDValue AndOp1 = Op0.getOperand(1);
7483
7484       if (AndOp1.getOpcode() == ISD::Constant) {
7485         const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
7486
7487         if (AndConst.isPowerOf2() &&
7488             cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
7489           SDValue SetCC =
7490             DAG.getSetCC(SDLoc(N),
7491                          getSetCCResultType(Op0.getValueType()),
7492                          Op0, DAG.getConstant(0, Op0.getValueType()),
7493                          ISD::SETNE);
7494
7495           SDValue NewBRCond = DAG.getNode(ISD::BRCOND, SDLoc(N),
7496                                           MVT::Other, Chain, SetCC, N2);
7497           // Don't add the new BRCond into the worklist or else SimplifySelectCC
7498           // will convert it back to (X & C1) >> C2.
7499           CombineTo(N, NewBRCond, false);
7500           // Truncate is dead.
7501           if (Trunc)
7502             deleteAndRecombine(Trunc);
7503           // Replace the uses of SRL with SETCC
7504           WorklistRemover DeadNodes(*this);
7505           DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
7506           deleteAndRecombine(N1.getNode());
7507           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7508         }
7509       }
7510     }
7511
7512     if (Trunc)
7513       // Restore N1 if the above transformation doesn't match.
7514       N1 = N->getOperand(1);
7515   }
7516
7517   // Transform br(xor(x, y)) -> br(x != y)
7518   // Transform br(xor(xor(x,y), 1)) -> br (x == y)
7519   if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
7520     SDNode *TheXor = N1.getNode();
7521     SDValue Op0 = TheXor->getOperand(0);
7522     SDValue Op1 = TheXor->getOperand(1);
7523     if (Op0.getOpcode() == Op1.getOpcode()) {
7524       // Avoid missing important xor optimizations.
7525       SDValue Tmp = visitXOR(TheXor);
7526       if (Tmp.getNode()) {
7527         if (Tmp.getNode() != TheXor) {
7528           DEBUG(dbgs() << "\nReplacing.8 ";
7529                 TheXor->dump(&DAG);
7530                 dbgs() << "\nWith: ";
7531                 Tmp.getNode()->dump(&DAG);
7532                 dbgs() << '\n');
7533           WorklistRemover DeadNodes(*this);
7534           DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
7535           deleteAndRecombine(TheXor);
7536           return DAG.getNode(ISD::BRCOND, SDLoc(N),
7537                              MVT::Other, Chain, Tmp, N2);
7538         }
7539
7540         // visitXOR has changed XOR's operands or replaced the XOR completely,
7541         // bail out.
7542         return SDValue(N, 0);
7543       }
7544     }
7545
7546     if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
7547       bool Equal = false;
7548       if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
7549         if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
7550             Op0.getOpcode() == ISD::XOR) {
7551           TheXor = Op0.getNode();
7552           Equal = true;
7553         }
7554
7555       EVT SetCCVT = N1.getValueType();
7556       if (LegalTypes)
7557         SetCCVT = getSetCCResultType(SetCCVT);
7558       SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
7559                                    SetCCVT,
7560                                    Op0, Op1,
7561                                    Equal ? ISD::SETEQ : ISD::SETNE);
7562       // Replace the uses of XOR with SETCC
7563       WorklistRemover DeadNodes(*this);
7564       DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
7565       deleteAndRecombine(N1.getNode());
7566       return DAG.getNode(ISD::BRCOND, SDLoc(N),
7567                          MVT::Other, Chain, SetCC, N2);
7568     }
7569   }
7570
7571   return SDValue();
7572 }
7573
7574 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
7575 //
7576 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
7577   CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
7578   SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
7579
7580   // If N is a constant we could fold this into a fallthrough or unconditional
7581   // branch. However that doesn't happen very often in normal code, because
7582   // Instcombine/SimplifyCFG should have handled the available opportunities.
7583   // If we did this folding here, it would be necessary to update the
7584   // MachineBasicBlock CFG, which is awkward.
7585
7586   // Use SimplifySetCC to simplify SETCC's.
7587   SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
7588                                CondLHS, CondRHS, CC->get(), SDLoc(N),
7589                                false);
7590   if (Simp.getNode()) AddToWorklist(Simp.getNode());
7591
7592   // fold to a simpler setcc
7593   if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
7594     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7595                        N->getOperand(0), Simp.getOperand(2),
7596                        Simp.getOperand(0), Simp.getOperand(1),
7597                        N->getOperand(4));
7598
7599   return SDValue();
7600 }
7601
7602 /// canFoldInAddressingMode - Return true if 'Use' is a load or a store that
7603 /// uses N as its base pointer and that N may be folded in the load / store
7604 /// addressing mode.
7605 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
7606                                     SelectionDAG &DAG,
7607                                     const TargetLowering &TLI) {
7608   EVT VT;
7609   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(Use)) {
7610     if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
7611       return false;
7612     VT = Use->getValueType(0);
7613   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(Use)) {
7614     if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
7615       return false;
7616     VT = ST->getValue().getValueType();
7617   } else
7618     return false;
7619
7620   TargetLowering::AddrMode AM;
7621   if (N->getOpcode() == ISD::ADD) {
7622     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7623     if (Offset)
7624       // [reg +/- imm]
7625       AM.BaseOffs = Offset->getSExtValue();
7626     else
7627       // [reg +/- reg]
7628       AM.Scale = 1;
7629   } else if (N->getOpcode() == ISD::SUB) {
7630     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7631     if (Offset)
7632       // [reg +/- imm]
7633       AM.BaseOffs = -Offset->getSExtValue();
7634     else
7635       // [reg +/- reg]
7636       AM.Scale = 1;
7637   } else
7638     return false;
7639
7640   return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
7641 }
7642
7643 /// CombineToPreIndexedLoadStore - Try turning a load / store into a
7644 /// pre-indexed load / store when the base pointer is an add or subtract
7645 /// and it has other uses besides the load / store. After the
7646 /// transformation, the new indexed load / store has effectively folded
7647 /// the add / subtract in and all of its other uses are redirected to the
7648 /// new load / store.
7649 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
7650   if (Level < AfterLegalizeDAG)
7651     return false;
7652
7653   bool isLoad = true;
7654   SDValue Ptr;
7655   EVT VT;
7656   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
7657     if (LD->isIndexed())
7658       return false;
7659     VT = LD->getMemoryVT();
7660     if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
7661         !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
7662       return false;
7663     Ptr = LD->getBasePtr();
7664   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
7665     if (ST->isIndexed())
7666       return false;
7667     VT = ST->getMemoryVT();
7668     if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
7669         !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
7670       return false;
7671     Ptr = ST->getBasePtr();
7672     isLoad = false;
7673   } else {
7674     return false;
7675   }
7676
7677   // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
7678   // out.  There is no reason to make this a preinc/predec.
7679   if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
7680       Ptr.getNode()->hasOneUse())
7681     return false;
7682
7683   // Ask the target to do addressing mode selection.
7684   SDValue BasePtr;
7685   SDValue Offset;
7686   ISD::MemIndexedMode AM = ISD::UNINDEXED;
7687   if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
7688     return false;
7689
7690   // Backends without true r+i pre-indexed forms may need to pass a
7691   // constant base with a variable offset so that constant coercion
7692   // will work with the patterns in canonical form.
7693   bool Swapped = false;
7694   if (isa<ConstantSDNode>(BasePtr)) {
7695     std::swap(BasePtr, Offset);
7696     Swapped = true;
7697   }
7698
7699   // Don't create a indexed load / store with zero offset.
7700   if (isa<ConstantSDNode>(Offset) &&
7701       cast<ConstantSDNode>(Offset)->isNullValue())
7702     return false;
7703
7704   // Try turning it into a pre-indexed load / store except when:
7705   // 1) The new base ptr is a frame index.
7706   // 2) If N is a store and the new base ptr is either the same as or is a
7707   //    predecessor of the value being stored.
7708   // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
7709   //    that would create a cycle.
7710   // 4) All uses are load / store ops that use it as old base ptr.
7711
7712   // Check #1.  Preinc'ing a frame index would require copying the stack pointer
7713   // (plus the implicit offset) to a register to preinc anyway.
7714   if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7715     return false;
7716
7717   // Check #2.
7718   if (!isLoad) {
7719     SDValue Val = cast<StoreSDNode>(N)->getValue();
7720     if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
7721       return false;
7722   }
7723
7724   // If the offset is a constant, there may be other adds of constants that
7725   // can be folded with this one. We should do this to avoid having to keep
7726   // a copy of the original base pointer.
7727   SmallVector<SDNode *, 16> OtherUses;
7728   if (isa<ConstantSDNode>(Offset))
7729     for (SDNode *Use : BasePtr.getNode()->uses()) {
7730       if (Use == Ptr.getNode())
7731         continue;
7732
7733       if (Use->isPredecessorOf(N))
7734         continue;
7735
7736       if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) {
7737         OtherUses.clear();
7738         break;
7739       }
7740
7741       SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1);
7742       if (Op1.getNode() == BasePtr.getNode())
7743         std::swap(Op0, Op1);
7744       assert(Op0.getNode() == BasePtr.getNode() &&
7745              "Use of ADD/SUB but not an operand");
7746
7747       if (!isa<ConstantSDNode>(Op1)) {
7748         OtherUses.clear();
7749         break;
7750       }
7751
7752       // FIXME: In some cases, we can be smarter about this.
7753       if (Op1.getValueType() != Offset.getValueType()) {
7754         OtherUses.clear();
7755         break;
7756       }
7757
7758       OtherUses.push_back(Use);
7759     }
7760
7761   if (Swapped)
7762     std::swap(BasePtr, Offset);
7763
7764   // Now check for #3 and #4.
7765   bool RealUse = false;
7766
7767   // Caches for hasPredecessorHelper
7768   SmallPtrSet<const SDNode *, 32> Visited;
7769   SmallVector<const SDNode *, 16> Worklist;
7770
7771   for (SDNode *Use : Ptr.getNode()->uses()) {
7772     if (Use == N)
7773       continue;
7774     if (N->hasPredecessorHelper(Use, Visited, Worklist))
7775       return false;
7776
7777     // If Ptr may be folded in addressing mode of other use, then it's
7778     // not profitable to do this transformation.
7779     if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
7780       RealUse = true;
7781   }
7782
7783   if (!RealUse)
7784     return false;
7785
7786   SDValue Result;
7787   if (isLoad)
7788     Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
7789                                 BasePtr, Offset, AM);
7790   else
7791     Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
7792                                  BasePtr, Offset, AM);
7793   ++PreIndexedNodes;
7794   ++NodesCombined;
7795   DEBUG(dbgs() << "\nReplacing.4 ";
7796         N->dump(&DAG);
7797         dbgs() << "\nWith: ";
7798         Result.getNode()->dump(&DAG);
7799         dbgs() << '\n');
7800   WorklistRemover DeadNodes(*this);
7801   if (isLoad) {
7802     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7803     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
7804   } else {
7805     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
7806   }
7807
7808   // Finally, since the node is now dead, remove it from the graph.
7809   deleteAndRecombine(N);
7810
7811   if (Swapped)
7812     std::swap(BasePtr, Offset);
7813
7814   // Replace other uses of BasePtr that can be updated to use Ptr
7815   for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
7816     unsigned OffsetIdx = 1;
7817     if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
7818       OffsetIdx = 0;
7819     assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
7820            BasePtr.getNode() && "Expected BasePtr operand");
7821
7822     // We need to replace ptr0 in the following expression:
7823     //   x0 * offset0 + y0 * ptr0 = t0
7824     // knowing that
7825     //   x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
7826     //
7827     // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
7828     // indexed load/store and the expresion that needs to be re-written.
7829     //
7830     // Therefore, we have:
7831     //   t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
7832
7833     ConstantSDNode *CN =
7834       cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
7835     int X0, X1, Y0, Y1;
7836     APInt Offset0 = CN->getAPIntValue();
7837     APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
7838
7839     X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
7840     Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
7841     X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
7842     Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
7843
7844     unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
7845
7846     APInt CNV = Offset0;
7847     if (X0 < 0) CNV = -CNV;
7848     if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
7849     else CNV = CNV - Offset1;
7850
7851     // We can now generate the new expression.
7852     SDValue NewOp1 = DAG.getConstant(CNV, CN->getValueType(0));
7853     SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
7854
7855     SDValue NewUse = DAG.getNode(Opcode,
7856                                  SDLoc(OtherUses[i]),
7857                                  OtherUses[i]->getValueType(0), NewOp1, NewOp2);
7858     DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
7859     deleteAndRecombine(OtherUses[i]);
7860   }
7861
7862   // Replace the uses of Ptr with uses of the updated base value.
7863   DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
7864   deleteAndRecombine(Ptr.getNode());
7865
7866   return true;
7867 }
7868
7869 /// CombineToPostIndexedLoadStore - Try to combine a load / store with a
7870 /// add / sub of the base pointer node into a post-indexed load / store.
7871 /// The transformation folded the add / subtract into the new indexed
7872 /// load / store effectively and all of its uses are redirected to the
7873 /// new load / store.
7874 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
7875   if (Level < AfterLegalizeDAG)
7876     return false;
7877
7878   bool isLoad = true;
7879   SDValue Ptr;
7880   EVT VT;
7881   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
7882     if (LD->isIndexed())
7883       return false;
7884     VT = LD->getMemoryVT();
7885     if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
7886         !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
7887       return false;
7888     Ptr = LD->getBasePtr();
7889   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
7890     if (ST->isIndexed())
7891       return false;
7892     VT = ST->getMemoryVT();
7893     if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
7894         !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
7895       return false;
7896     Ptr = ST->getBasePtr();
7897     isLoad = false;
7898   } else {
7899     return false;
7900   }
7901
7902   if (Ptr.getNode()->hasOneUse())
7903     return false;
7904
7905   for (SDNode *Op : Ptr.getNode()->uses()) {
7906     if (Op == N ||
7907         (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
7908       continue;
7909
7910     SDValue BasePtr;
7911     SDValue Offset;
7912     ISD::MemIndexedMode AM = ISD::UNINDEXED;
7913     if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
7914       // Don't create a indexed load / store with zero offset.
7915       if (isa<ConstantSDNode>(Offset) &&
7916           cast<ConstantSDNode>(Offset)->isNullValue())
7917         continue;
7918
7919       // Try turning it into a post-indexed load / store except when
7920       // 1) All uses are load / store ops that use it as base ptr (and
7921       //    it may be folded as addressing mmode).
7922       // 2) Op must be independent of N, i.e. Op is neither a predecessor
7923       //    nor a successor of N. Otherwise, if Op is folded that would
7924       //    create a cycle.
7925
7926       if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7927         continue;
7928
7929       // Check for #1.
7930       bool TryNext = false;
7931       for (SDNode *Use : BasePtr.getNode()->uses()) {
7932         if (Use == Ptr.getNode())
7933           continue;
7934
7935         // If all the uses are load / store addresses, then don't do the
7936         // transformation.
7937         if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
7938           bool RealUse = false;
7939           for (SDNode *UseUse : Use->uses()) {
7940             if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
7941               RealUse = true;
7942           }
7943
7944           if (!RealUse) {
7945             TryNext = true;
7946             break;
7947           }
7948         }
7949       }
7950
7951       if (TryNext)
7952         continue;
7953
7954       // Check for #2
7955       if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
7956         SDValue Result = isLoad
7957           ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
7958                                BasePtr, Offset, AM)
7959           : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
7960                                 BasePtr, Offset, AM);
7961         ++PostIndexedNodes;
7962         ++NodesCombined;
7963         DEBUG(dbgs() << "\nReplacing.5 ";
7964               N->dump(&DAG);
7965               dbgs() << "\nWith: ";
7966               Result.getNode()->dump(&DAG);
7967               dbgs() << '\n');
7968         WorklistRemover DeadNodes(*this);
7969         if (isLoad) {
7970           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7971           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
7972         } else {
7973           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
7974         }
7975
7976         // Finally, since the node is now dead, remove it from the graph.
7977         deleteAndRecombine(N);
7978
7979         // Replace the uses of Use with uses of the updated base value.
7980         DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
7981                                       Result.getValue(isLoad ? 1 : 0));
7982         deleteAndRecombine(Op);
7983         return true;
7984       }
7985     }
7986   }
7987
7988   return false;
7989 }
7990
7991 SDValue DAGCombiner::visitLOAD(SDNode *N) {
7992   LoadSDNode *LD  = cast<LoadSDNode>(N);
7993   SDValue Chain = LD->getChain();
7994   SDValue Ptr   = LD->getBasePtr();
7995
7996   // If load is not volatile and there are no uses of the loaded value (and
7997   // the updated indexed value in case of indexed loads), change uses of the
7998   // chain value into uses of the chain input (i.e. delete the dead load).
7999   if (!LD->isVolatile()) {
8000     if (N->getValueType(1) == MVT::Other) {
8001       // Unindexed loads.
8002       if (!N->hasAnyUseOfValue(0)) {
8003         // It's not safe to use the two value CombineTo variant here. e.g.
8004         // v1, chain2 = load chain1, loc
8005         // v2, chain3 = load chain2, loc
8006         // v3         = add v2, c
8007         // Now we replace use of chain2 with chain1.  This makes the second load
8008         // isomorphic to the one we are deleting, and thus makes this load live.
8009         DEBUG(dbgs() << "\nReplacing.6 ";
8010               N->dump(&DAG);
8011               dbgs() << "\nWith chain: ";
8012               Chain.getNode()->dump(&DAG);
8013               dbgs() << "\n");
8014         WorklistRemover DeadNodes(*this);
8015         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
8016
8017         if (N->use_empty())
8018           deleteAndRecombine(N);
8019
8020         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
8021       }
8022     } else {
8023       // Indexed loads.
8024       assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
8025       if (!N->hasAnyUseOfValue(0) && !N->hasAnyUseOfValue(1)) {
8026         SDValue Undef = DAG.getUNDEF(N->getValueType(0));
8027         DEBUG(dbgs() << "\nReplacing.7 ";
8028               N->dump(&DAG);
8029               dbgs() << "\nWith: ";
8030               Undef.getNode()->dump(&DAG);
8031               dbgs() << " and 2 other values\n");
8032         WorklistRemover DeadNodes(*this);
8033         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
8034         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1),
8035                                       DAG.getUNDEF(N->getValueType(1)));
8036         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
8037         deleteAndRecombine(N);
8038         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
8039       }
8040     }
8041   }
8042
8043   // If this load is directly stored, replace the load value with the stored
8044   // value.
8045   // TODO: Handle store large -> read small portion.
8046   // TODO: Handle TRUNCSTORE/LOADEXT
8047   if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
8048     if (ISD::isNON_TRUNCStore(Chain.getNode())) {
8049       StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
8050       if (PrevST->getBasePtr() == Ptr &&
8051           PrevST->getValue().getValueType() == N->getValueType(0))
8052       return CombineTo(N, Chain.getOperand(1), Chain);
8053     }
8054   }
8055
8056   // Try to infer better alignment information than the load already has.
8057   if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
8058     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
8059       if (Align > LD->getMemOperand()->getBaseAlignment()) {
8060         SDValue NewLoad =
8061                DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
8062                               LD->getValueType(0),
8063                               Chain, Ptr, LD->getPointerInfo(),
8064                               LD->getMemoryVT(),
8065                               LD->isVolatile(), LD->isNonTemporal(),
8066                               LD->isInvariant(), Align, LD->getAAInfo());
8067         return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
8068       }
8069     }
8070   }
8071
8072   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
8073     TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
8074 #ifndef NDEBUG
8075   if (CombinerAAOnlyFunc.getNumOccurrences() &&
8076       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
8077     UseAA = false;
8078 #endif
8079   if (UseAA && LD->isUnindexed()) {
8080     // Walk up chain skipping non-aliasing memory nodes.
8081     SDValue BetterChain = FindBetterChain(N, Chain);
8082
8083     // If there is a better chain.
8084     if (Chain != BetterChain) {
8085       SDValue ReplLoad;
8086
8087       // Replace the chain to void dependency.
8088       if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
8089         ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
8090                                BetterChain, Ptr, LD->getMemOperand());
8091       } else {
8092         ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
8093                                   LD->getValueType(0),
8094                                   BetterChain, Ptr, LD->getMemoryVT(),
8095                                   LD->getMemOperand());
8096       }
8097
8098       // Create token factor to keep old chain connected.
8099       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
8100                                   MVT::Other, Chain, ReplLoad.getValue(1));
8101
8102       // Make sure the new and old chains are cleaned up.
8103       AddToWorklist(Token.getNode());
8104
8105       // Replace uses with load result and token factor. Don't add users
8106       // to work list.
8107       return CombineTo(N, ReplLoad.getValue(0), Token, false);
8108     }
8109   }
8110
8111   // Try transforming N to an indexed load.
8112   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
8113     return SDValue(N, 0);
8114
8115   // Try to slice up N to more direct loads if the slices are mapped to
8116   // different register banks or pairing can take place.
8117   if (SliceUpLoad(N))
8118     return SDValue(N, 0);
8119
8120   return SDValue();
8121 }
8122
8123 namespace {
8124 /// \brief Helper structure used to slice a load in smaller loads.
8125 /// Basically a slice is obtained from the following sequence:
8126 /// Origin = load Ty1, Base
8127 /// Shift = srl Ty1 Origin, CstTy Amount
8128 /// Inst = trunc Shift to Ty2
8129 ///
8130 /// Then, it will be rewriten into:
8131 /// Slice = load SliceTy, Base + SliceOffset
8132 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
8133 ///
8134 /// SliceTy is deduced from the number of bits that are actually used to
8135 /// build Inst.
8136 struct LoadedSlice {
8137   /// \brief Helper structure used to compute the cost of a slice.
8138   struct Cost {
8139     /// Are we optimizing for code size.
8140     bool ForCodeSize;
8141     /// Various cost.
8142     unsigned Loads;
8143     unsigned Truncates;
8144     unsigned CrossRegisterBanksCopies;
8145     unsigned ZExts;
8146     unsigned Shift;
8147
8148     Cost(bool ForCodeSize = false)
8149         : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
8150           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
8151
8152     /// \brief Get the cost of one isolated slice.
8153     Cost(const LoadedSlice &LS, bool ForCodeSize = false)
8154         : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
8155           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
8156       EVT TruncType = LS.Inst->getValueType(0);
8157       EVT LoadedType = LS.getLoadedType();
8158       if (TruncType != LoadedType &&
8159           !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
8160         ZExts = 1;
8161     }
8162
8163     /// \brief Account for slicing gain in the current cost.
8164     /// Slicing provide a few gains like removing a shift or a
8165     /// truncate. This method allows to grow the cost of the original
8166     /// load with the gain from this slice.
8167     void addSliceGain(const LoadedSlice &LS) {
8168       // Each slice saves a truncate.
8169       const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
8170       if (!TLI.isTruncateFree(LS.Inst->getValueType(0),
8171                               LS.Inst->getOperand(0).getValueType()))
8172         ++Truncates;
8173       // If there is a shift amount, this slice gets rid of it.
8174       if (LS.Shift)
8175         ++Shift;
8176       // If this slice can merge a cross register bank copy, account for it.
8177       if (LS.canMergeExpensiveCrossRegisterBankCopy())
8178         ++CrossRegisterBanksCopies;
8179     }
8180
8181     Cost &operator+=(const Cost &RHS) {
8182       Loads += RHS.Loads;
8183       Truncates += RHS.Truncates;
8184       CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
8185       ZExts += RHS.ZExts;
8186       Shift += RHS.Shift;
8187       return *this;
8188     }
8189
8190     bool operator==(const Cost &RHS) const {
8191       return Loads == RHS.Loads && Truncates == RHS.Truncates &&
8192              CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
8193              ZExts == RHS.ZExts && Shift == RHS.Shift;
8194     }
8195
8196     bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
8197
8198     bool operator<(const Cost &RHS) const {
8199       // Assume cross register banks copies are as expensive as loads.
8200       // FIXME: Do we want some more target hooks?
8201       unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
8202       unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
8203       // Unless we are optimizing for code size, consider the
8204       // expensive operation first.
8205       if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
8206         return ExpensiveOpsLHS < ExpensiveOpsRHS;
8207       return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
8208              (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
8209     }
8210
8211     bool operator>(const Cost &RHS) const { return RHS < *this; }
8212
8213     bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
8214
8215     bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
8216   };
8217   // The last instruction that represent the slice. This should be a
8218   // truncate instruction.
8219   SDNode *Inst;
8220   // The original load instruction.
8221   LoadSDNode *Origin;
8222   // The right shift amount in bits from the original load.
8223   unsigned Shift;
8224   // The DAG from which Origin came from.
8225   // This is used to get some contextual information about legal types, etc.
8226   SelectionDAG *DAG;
8227
8228   LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
8229               unsigned Shift = 0, SelectionDAG *DAG = nullptr)
8230       : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
8231
8232   LoadedSlice(const LoadedSlice &LS)
8233       : Inst(LS.Inst), Origin(LS.Origin), Shift(LS.Shift), DAG(LS.DAG) {}
8234
8235   /// \brief Get the bits used in a chunk of bits \p BitWidth large.
8236   /// \return Result is \p BitWidth and has used bits set to 1 and
8237   ///         not used bits set to 0.
8238   APInt getUsedBits() const {
8239     // Reproduce the trunc(lshr) sequence:
8240     // - Start from the truncated value.
8241     // - Zero extend to the desired bit width.
8242     // - Shift left.
8243     assert(Origin && "No original load to compare against.");
8244     unsigned BitWidth = Origin->getValueSizeInBits(0);
8245     assert(Inst && "This slice is not bound to an instruction");
8246     assert(Inst->getValueSizeInBits(0) <= BitWidth &&
8247            "Extracted slice is bigger than the whole type!");
8248     APInt UsedBits(Inst->getValueSizeInBits(0), 0);
8249     UsedBits.setAllBits();
8250     UsedBits = UsedBits.zext(BitWidth);
8251     UsedBits <<= Shift;
8252     return UsedBits;
8253   }
8254
8255   /// \brief Get the size of the slice to be loaded in bytes.
8256   unsigned getLoadedSize() const {
8257     unsigned SliceSize = getUsedBits().countPopulation();
8258     assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
8259     return SliceSize / 8;
8260   }
8261
8262   /// \brief Get the type that will be loaded for this slice.
8263   /// Note: This may not be the final type for the slice.
8264   EVT getLoadedType() const {
8265     assert(DAG && "Missing context");
8266     LLVMContext &Ctxt = *DAG->getContext();
8267     return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
8268   }
8269
8270   /// \brief Get the alignment of the load used for this slice.
8271   unsigned getAlignment() const {
8272     unsigned Alignment = Origin->getAlignment();
8273     unsigned Offset = getOffsetFromBase();
8274     if (Offset != 0)
8275       Alignment = MinAlign(Alignment, Alignment + Offset);
8276     return Alignment;
8277   }
8278
8279   /// \brief Check if this slice can be rewritten with legal operations.
8280   bool isLegal() const {
8281     // An invalid slice is not legal.
8282     if (!Origin || !Inst || !DAG)
8283       return false;
8284
8285     // Offsets are for indexed load only, we do not handle that.
8286     if (Origin->getOffset().getOpcode() != ISD::UNDEF)
8287       return false;
8288
8289     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8290
8291     // Check that the type is legal.
8292     EVT SliceType = getLoadedType();
8293     if (!TLI.isTypeLegal(SliceType))
8294       return false;
8295
8296     // Check that the load is legal for this type.
8297     if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
8298       return false;
8299
8300     // Check that the offset can be computed.
8301     // 1. Check its type.
8302     EVT PtrType = Origin->getBasePtr().getValueType();
8303     if (PtrType == MVT::Untyped || PtrType.isExtended())
8304       return false;
8305
8306     // 2. Check that it fits in the immediate.
8307     if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
8308       return false;
8309
8310     // 3. Check that the computation is legal.
8311     if (!TLI.isOperationLegal(ISD::ADD, PtrType))
8312       return false;
8313
8314     // Check that the zext is legal if it needs one.
8315     EVT TruncateType = Inst->getValueType(0);
8316     if (TruncateType != SliceType &&
8317         !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
8318       return false;
8319
8320     return true;
8321   }
8322
8323   /// \brief Get the offset in bytes of this slice in the original chunk of
8324   /// bits.
8325   /// \pre DAG != nullptr.
8326   uint64_t getOffsetFromBase() const {
8327     assert(DAG && "Missing context.");
8328     bool IsBigEndian =
8329         DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian();
8330     assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
8331     uint64_t Offset = Shift / 8;
8332     unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
8333     assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
8334            "The size of the original loaded type is not a multiple of a"
8335            " byte.");
8336     // If Offset is bigger than TySizeInBytes, it means we are loading all
8337     // zeros. This should have been optimized before in the process.
8338     assert(TySizeInBytes > Offset &&
8339            "Invalid shift amount for given loaded size");
8340     if (IsBigEndian)
8341       Offset = TySizeInBytes - Offset - getLoadedSize();
8342     return Offset;
8343   }
8344
8345   /// \brief Generate the sequence of instructions to load the slice
8346   /// represented by this object and redirect the uses of this slice to
8347   /// this new sequence of instructions.
8348   /// \pre this->Inst && this->Origin are valid Instructions and this
8349   /// object passed the legal check: LoadedSlice::isLegal returned true.
8350   /// \return The last instruction of the sequence used to load the slice.
8351   SDValue loadSlice() const {
8352     assert(Inst && Origin && "Unable to replace a non-existing slice.");
8353     const SDValue &OldBaseAddr = Origin->getBasePtr();
8354     SDValue BaseAddr = OldBaseAddr;
8355     // Get the offset in that chunk of bytes w.r.t. the endianess.
8356     int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
8357     assert(Offset >= 0 && "Offset too big to fit in int64_t!");
8358     if (Offset) {
8359       // BaseAddr = BaseAddr + Offset.
8360       EVT ArithType = BaseAddr.getValueType();
8361       BaseAddr = DAG->getNode(ISD::ADD, SDLoc(Origin), ArithType, BaseAddr,
8362                               DAG->getConstant(Offset, ArithType));
8363     }
8364
8365     // Create the type of the loaded slice according to its size.
8366     EVT SliceType = getLoadedType();
8367
8368     // Create the load for the slice.
8369     SDValue LastInst = DAG->getLoad(
8370         SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
8371         Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
8372         Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
8373     // If the final type is not the same as the loaded type, this means that
8374     // we have to pad with zero. Create a zero extend for that.
8375     EVT FinalType = Inst->getValueType(0);
8376     if (SliceType != FinalType)
8377       LastInst =
8378           DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
8379     return LastInst;
8380   }
8381
8382   /// \brief Check if this slice can be merged with an expensive cross register
8383   /// bank copy. E.g.,
8384   /// i = load i32
8385   /// f = bitcast i32 i to float
8386   bool canMergeExpensiveCrossRegisterBankCopy() const {
8387     if (!Inst || !Inst->hasOneUse())
8388       return false;
8389     SDNode *Use = *Inst->use_begin();
8390     if (Use->getOpcode() != ISD::BITCAST)
8391       return false;
8392     assert(DAG && "Missing context");
8393     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8394     EVT ResVT = Use->getValueType(0);
8395     const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
8396     const TargetRegisterClass *ArgRC =
8397         TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
8398     if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
8399       return false;
8400
8401     // At this point, we know that we perform a cross-register-bank copy.
8402     // Check if it is expensive.
8403     const TargetRegisterInfo *TRI = TLI.getTargetMachine().getRegisterInfo();
8404     // Assume bitcasts are cheap, unless both register classes do not
8405     // explicitly share a common sub class.
8406     if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
8407       return false;
8408
8409     // Check if it will be merged with the load.
8410     // 1. Check the alignment constraint.
8411     unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment(
8412         ResVT.getTypeForEVT(*DAG->getContext()));
8413
8414     if (RequiredAlignment > getAlignment())
8415       return false;
8416
8417     // 2. Check that the load is a legal operation for that type.
8418     if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
8419       return false;
8420
8421     // 3. Check that we do not have a zext in the way.
8422     if (Inst->getValueType(0) != getLoadedType())
8423       return false;
8424
8425     return true;
8426   }
8427 };
8428 }
8429
8430 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
8431 /// \p UsedBits looks like 0..0 1..1 0..0.
8432 static bool areUsedBitsDense(const APInt &UsedBits) {
8433   // If all the bits are one, this is dense!
8434   if (UsedBits.isAllOnesValue())
8435     return true;
8436
8437   // Get rid of the unused bits on the right.
8438   APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
8439   // Get rid of the unused bits on the left.
8440   if (NarrowedUsedBits.countLeadingZeros())
8441     NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
8442   // Check that the chunk of bits is completely used.
8443   return NarrowedUsedBits.isAllOnesValue();
8444 }
8445
8446 /// \brief Check whether or not \p First and \p Second are next to each other
8447 /// in memory. This means that there is no hole between the bits loaded
8448 /// by \p First and the bits loaded by \p Second.
8449 static bool areSlicesNextToEachOther(const LoadedSlice &First,
8450                                      const LoadedSlice &Second) {
8451   assert(First.Origin == Second.Origin && First.Origin &&
8452          "Unable to match different memory origins.");
8453   APInt UsedBits = First.getUsedBits();
8454   assert((UsedBits & Second.getUsedBits()) == 0 &&
8455          "Slices are not supposed to overlap.");
8456   UsedBits |= Second.getUsedBits();
8457   return areUsedBitsDense(UsedBits);
8458 }
8459
8460 /// \brief Adjust the \p GlobalLSCost according to the target
8461 /// paring capabilities and the layout of the slices.
8462 /// \pre \p GlobalLSCost should account for at least as many loads as
8463 /// there is in the slices in \p LoadedSlices.
8464 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8465                                  LoadedSlice::Cost &GlobalLSCost) {
8466   unsigned NumberOfSlices = LoadedSlices.size();
8467   // If there is less than 2 elements, no pairing is possible.
8468   if (NumberOfSlices < 2)
8469     return;
8470
8471   // Sort the slices so that elements that are likely to be next to each
8472   // other in memory are next to each other in the list.
8473   std::sort(LoadedSlices.begin(), LoadedSlices.end(),
8474             [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
8475     assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
8476     return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
8477   });
8478   const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
8479   // First (resp. Second) is the first (resp. Second) potentially candidate
8480   // to be placed in a paired load.
8481   const LoadedSlice *First = nullptr;
8482   const LoadedSlice *Second = nullptr;
8483   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
8484                 // Set the beginning of the pair.
8485                                                            First = Second) {
8486
8487     Second = &LoadedSlices[CurrSlice];
8488
8489     // If First is NULL, it means we start a new pair.
8490     // Get to the next slice.
8491     if (!First)
8492       continue;
8493
8494     EVT LoadedType = First->getLoadedType();
8495
8496     // If the types of the slices are different, we cannot pair them.
8497     if (LoadedType != Second->getLoadedType())
8498       continue;
8499
8500     // Check if the target supplies paired loads for this type.
8501     unsigned RequiredAlignment = 0;
8502     if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
8503       // move to the next pair, this type is hopeless.
8504       Second = nullptr;
8505       continue;
8506     }
8507     // Check if we meet the alignment requirement.
8508     if (RequiredAlignment > First->getAlignment())
8509       continue;
8510
8511     // Check that both loads are next to each other in memory.
8512     if (!areSlicesNextToEachOther(*First, *Second))
8513       continue;
8514
8515     assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
8516     --GlobalLSCost.Loads;
8517     // Move to the next pair.
8518     Second = nullptr;
8519   }
8520 }
8521
8522 /// \brief Check the profitability of all involved LoadedSlice.
8523 /// Currently, it is considered profitable if there is exactly two
8524 /// involved slices (1) which are (2) next to each other in memory, and
8525 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
8526 ///
8527 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
8528 /// the elements themselves.
8529 ///
8530 /// FIXME: When the cost model will be mature enough, we can relax
8531 /// constraints (1) and (2).
8532 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8533                                 const APInt &UsedBits, bool ForCodeSize) {
8534   unsigned NumberOfSlices = LoadedSlices.size();
8535   if (StressLoadSlicing)
8536     return NumberOfSlices > 1;
8537
8538   // Check (1).
8539   if (NumberOfSlices != 2)
8540     return false;
8541
8542   // Check (2).
8543   if (!areUsedBitsDense(UsedBits))
8544     return false;
8545
8546   // Check (3).
8547   LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
8548   // The original code has one big load.
8549   OrigCost.Loads = 1;
8550   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
8551     const LoadedSlice &LS = LoadedSlices[CurrSlice];
8552     // Accumulate the cost of all the slices.
8553     LoadedSlice::Cost SliceCost(LS, ForCodeSize);
8554     GlobalSlicingCost += SliceCost;
8555
8556     // Account as cost in the original configuration the gain obtained
8557     // with the current slices.
8558     OrigCost.addSliceGain(LS);
8559   }
8560
8561   // If the target supports paired load, adjust the cost accordingly.
8562   adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
8563   return OrigCost > GlobalSlicingCost;
8564 }
8565
8566 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
8567 /// operations, split it in the various pieces being extracted.
8568 ///
8569 /// This sort of thing is introduced by SROA.
8570 /// This slicing takes care not to insert overlapping loads.
8571 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
8572 bool DAGCombiner::SliceUpLoad(SDNode *N) {
8573   if (Level < AfterLegalizeDAG)
8574     return false;
8575
8576   LoadSDNode *LD = cast<LoadSDNode>(N);
8577   if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
8578       !LD->getValueType(0).isInteger())
8579     return false;
8580
8581   // Keep track of already used bits to detect overlapping values.
8582   // In that case, we will just abort the transformation.
8583   APInt UsedBits(LD->getValueSizeInBits(0), 0);
8584
8585   SmallVector<LoadedSlice, 4> LoadedSlices;
8586
8587   // Check if this load is used as several smaller chunks of bits.
8588   // Basically, look for uses in trunc or trunc(lshr) and record a new chain
8589   // of computation for each trunc.
8590   for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
8591        UI != UIEnd; ++UI) {
8592     // Skip the uses of the chain.
8593     if (UI.getUse().getResNo() != 0)
8594       continue;
8595
8596     SDNode *User = *UI;
8597     unsigned Shift = 0;
8598
8599     // Check if this is a trunc(lshr).
8600     if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
8601         isa<ConstantSDNode>(User->getOperand(1))) {
8602       Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
8603       User = *User->use_begin();
8604     }
8605
8606     // At this point, User is a Truncate, iff we encountered, trunc or
8607     // trunc(lshr).
8608     if (User->getOpcode() != ISD::TRUNCATE)
8609       return false;
8610
8611     // The width of the type must be a power of 2 and greater than 8-bits.
8612     // Otherwise the load cannot be represented in LLVM IR.
8613     // Moreover, if we shifted with a non-8-bits multiple, the slice
8614     // will be across several bytes. We do not support that.
8615     unsigned Width = User->getValueSizeInBits(0);
8616     if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
8617       return 0;
8618
8619     // Build the slice for this chain of computations.
8620     LoadedSlice LS(User, LD, Shift, &DAG);
8621     APInt CurrentUsedBits = LS.getUsedBits();
8622
8623     // Check if this slice overlaps with another.
8624     if ((CurrentUsedBits & UsedBits) != 0)
8625       return false;
8626     // Update the bits used globally.
8627     UsedBits |= CurrentUsedBits;
8628
8629     // Check if the new slice would be legal.
8630     if (!LS.isLegal())
8631       return false;
8632
8633     // Record the slice.
8634     LoadedSlices.push_back(LS);
8635   }
8636
8637   // Abort slicing if it does not seem to be profitable.
8638   if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
8639     return false;
8640
8641   ++SlicedLoads;
8642
8643   // Rewrite each chain to use an independent load.
8644   // By construction, each chain can be represented by a unique load.
8645
8646   // Prepare the argument for the new token factor for all the slices.
8647   SmallVector<SDValue, 8> ArgChains;
8648   for (SmallVectorImpl<LoadedSlice>::const_iterator
8649            LSIt = LoadedSlices.begin(),
8650            LSItEnd = LoadedSlices.end();
8651        LSIt != LSItEnd; ++LSIt) {
8652     SDValue SliceInst = LSIt->loadSlice();
8653     CombineTo(LSIt->Inst, SliceInst, true);
8654     if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
8655       SliceInst = SliceInst.getOperand(0);
8656     assert(SliceInst->getOpcode() == ISD::LOAD &&
8657            "It takes more than a zext to get to the loaded slice!!");
8658     ArgChains.push_back(SliceInst.getValue(1));
8659   }
8660
8661   SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
8662                               ArgChains);
8663   DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
8664   return true;
8665 }
8666
8667 /// CheckForMaskedLoad - Check to see if V is (and load (ptr), imm), where the
8668 /// load is having specific bytes cleared out.  If so, return the byte size
8669 /// being masked out and the shift amount.
8670 static std::pair<unsigned, unsigned>
8671 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
8672   std::pair<unsigned, unsigned> Result(0, 0);
8673
8674   // Check for the structure we're looking for.
8675   if (V->getOpcode() != ISD::AND ||
8676       !isa<ConstantSDNode>(V->getOperand(1)) ||
8677       !ISD::isNormalLoad(V->getOperand(0).getNode()))
8678     return Result;
8679
8680   // Check the chain and pointer.
8681   LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
8682   if (LD->getBasePtr() != Ptr) return Result;  // Not from same pointer.
8683
8684   // The store should be chained directly to the load or be an operand of a
8685   // tokenfactor.
8686   if (LD == Chain.getNode())
8687     ; // ok.
8688   else if (Chain->getOpcode() != ISD::TokenFactor)
8689     return Result; // Fail.
8690   else {
8691     bool isOk = false;
8692     for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
8693       if (Chain->getOperand(i).getNode() == LD) {
8694         isOk = true;
8695         break;
8696       }
8697     if (!isOk) return Result;
8698   }
8699
8700   // This only handles simple types.
8701   if (V.getValueType() != MVT::i16 &&
8702       V.getValueType() != MVT::i32 &&
8703       V.getValueType() != MVT::i64)
8704     return Result;
8705
8706   // Check the constant mask.  Invert it so that the bits being masked out are
8707   // 0 and the bits being kept are 1.  Use getSExtValue so that leading bits
8708   // follow the sign bit for uniformity.
8709   uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
8710   unsigned NotMaskLZ = countLeadingZeros(NotMask);
8711   if (NotMaskLZ & 7) return Result;  // Must be multiple of a byte.
8712   unsigned NotMaskTZ = countTrailingZeros(NotMask);
8713   if (NotMaskTZ & 7) return Result;  // Must be multiple of a byte.
8714   if (NotMaskLZ == 64) return Result;  // All zero mask.
8715
8716   // See if we have a continuous run of bits.  If so, we have 0*1+0*
8717   if (CountTrailingOnes_64(NotMask >> NotMaskTZ)+NotMaskTZ+NotMaskLZ != 64)
8718     return Result;
8719
8720   // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
8721   if (V.getValueType() != MVT::i64 && NotMaskLZ)
8722     NotMaskLZ -= 64-V.getValueSizeInBits();
8723
8724   unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
8725   switch (MaskedBytes) {
8726   case 1:
8727   case 2:
8728   case 4: break;
8729   default: return Result; // All one mask, or 5-byte mask.
8730   }
8731
8732   // Verify that the first bit starts at a multiple of mask so that the access
8733   // is aligned the same as the access width.
8734   if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
8735
8736   Result.first = MaskedBytes;
8737   Result.second = NotMaskTZ/8;
8738   return Result;
8739 }
8740
8741
8742 /// ShrinkLoadReplaceStoreWithStore - Check to see if IVal is something that
8743 /// provides a value as specified by MaskInfo.  If so, replace the specified
8744 /// store with a narrower store of truncated IVal.
8745 static SDNode *
8746 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
8747                                 SDValue IVal, StoreSDNode *St,
8748                                 DAGCombiner *DC) {
8749   unsigned NumBytes = MaskInfo.first;
8750   unsigned ByteShift = MaskInfo.second;
8751   SelectionDAG &DAG = DC->getDAG();
8752
8753   // Check to see if IVal is all zeros in the part being masked in by the 'or'
8754   // that uses this.  If not, this is not a replacement.
8755   APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
8756                                   ByteShift*8, (ByteShift+NumBytes)*8);
8757   if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
8758
8759   // Check that it is legal on the target to do this.  It is legal if the new
8760   // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
8761   // legalization.
8762   MVT VT = MVT::getIntegerVT(NumBytes*8);
8763   if (!DC->isTypeLegal(VT))
8764     return nullptr;
8765
8766   // Okay, we can do this!  Replace the 'St' store with a store of IVal that is
8767   // shifted by ByteShift and truncated down to NumBytes.
8768   if (ByteShift)
8769     IVal = DAG.getNode(ISD::SRL, SDLoc(IVal), IVal.getValueType(), IVal,
8770                        DAG.getConstant(ByteShift*8,
8771                                     DC->getShiftAmountTy(IVal.getValueType())));
8772
8773   // Figure out the offset for the store and the alignment of the access.
8774   unsigned StOffset;
8775   unsigned NewAlign = St->getAlignment();
8776
8777   if (DAG.getTargetLoweringInfo().isLittleEndian())
8778     StOffset = ByteShift;
8779   else
8780     StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
8781
8782   SDValue Ptr = St->getBasePtr();
8783   if (StOffset) {
8784     Ptr = DAG.getNode(ISD::ADD, SDLoc(IVal), Ptr.getValueType(),
8785                       Ptr, DAG.getConstant(StOffset, Ptr.getValueType()));
8786     NewAlign = MinAlign(NewAlign, StOffset);
8787   }
8788
8789   // Truncate down to the new size.
8790   IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
8791
8792   ++OpsNarrowed;
8793   return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
8794                       St->getPointerInfo().getWithOffset(StOffset),
8795                       false, false, NewAlign).getNode();
8796 }
8797
8798
8799 /// ReduceLoadOpStoreWidth - Look for sequence of load / op / store where op is
8800 /// one of 'or', 'xor', and 'and' of immediates. If 'op' is only touching some
8801 /// of the loaded bits, try narrowing the load and store if it would end up
8802 /// being a win for performance or code size.
8803 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
8804   StoreSDNode *ST  = cast<StoreSDNode>(N);
8805   if (ST->isVolatile())
8806     return SDValue();
8807
8808   SDValue Chain = ST->getChain();
8809   SDValue Value = ST->getValue();
8810   SDValue Ptr   = ST->getBasePtr();
8811   EVT VT = Value.getValueType();
8812
8813   if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
8814     return SDValue();
8815
8816   unsigned Opc = Value.getOpcode();
8817
8818   // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
8819   // is a byte mask indicating a consecutive number of bytes, check to see if
8820   // Y is known to provide just those bytes.  If so, we try to replace the
8821   // load + replace + store sequence with a single (narrower) store, which makes
8822   // the load dead.
8823   if (Opc == ISD::OR) {
8824     std::pair<unsigned, unsigned> MaskedLoad;
8825     MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
8826     if (MaskedLoad.first)
8827       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8828                                                   Value.getOperand(1), ST,this))
8829         return SDValue(NewST, 0);
8830
8831     // Or is commutative, so try swapping X and Y.
8832     MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
8833     if (MaskedLoad.first)
8834       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8835                                                   Value.getOperand(0), ST,this))
8836         return SDValue(NewST, 0);
8837   }
8838
8839   if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
8840       Value.getOperand(1).getOpcode() != ISD::Constant)
8841     return SDValue();
8842
8843   SDValue N0 = Value.getOperand(0);
8844   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8845       Chain == SDValue(N0.getNode(), 1)) {
8846     LoadSDNode *LD = cast<LoadSDNode>(N0);
8847     if (LD->getBasePtr() != Ptr ||
8848         LD->getPointerInfo().getAddrSpace() !=
8849         ST->getPointerInfo().getAddrSpace())
8850       return SDValue();
8851
8852     // Find the type to narrow it the load / op / store to.
8853     SDValue N1 = Value.getOperand(1);
8854     unsigned BitWidth = N1.getValueSizeInBits();
8855     APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
8856     if (Opc == ISD::AND)
8857       Imm ^= APInt::getAllOnesValue(BitWidth);
8858     if (Imm == 0 || Imm.isAllOnesValue())
8859       return SDValue();
8860     unsigned ShAmt = Imm.countTrailingZeros();
8861     unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
8862     unsigned NewBW = NextPowerOf2(MSB - ShAmt);
8863     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
8864     while (NewBW < BitWidth &&
8865            !(TLI.isOperationLegalOrCustom(Opc, NewVT) &&
8866              TLI.isNarrowingProfitable(VT, NewVT))) {
8867       NewBW = NextPowerOf2(NewBW);
8868       NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
8869     }
8870     if (NewBW >= BitWidth)
8871       return SDValue();
8872
8873     // If the lsb changed does not start at the type bitwidth boundary,
8874     // start at the previous one.
8875     if (ShAmt % NewBW)
8876       ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
8877     APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
8878                                    std::min(BitWidth, ShAmt + NewBW));
8879     if ((Imm & Mask) == Imm) {
8880       APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
8881       if (Opc == ISD::AND)
8882         NewImm ^= APInt::getAllOnesValue(NewBW);
8883       uint64_t PtrOff = ShAmt / 8;
8884       // For big endian targets, we need to adjust the offset to the pointer to
8885       // load the correct bytes.
8886       if (TLI.isBigEndian())
8887         PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
8888
8889       unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
8890       Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
8891       if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
8892         return SDValue();
8893
8894       SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
8895                                    Ptr.getValueType(), Ptr,
8896                                    DAG.getConstant(PtrOff, Ptr.getValueType()));
8897       SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
8898                                   LD->getChain(), NewPtr,
8899                                   LD->getPointerInfo().getWithOffset(PtrOff),
8900                                   LD->isVolatile(), LD->isNonTemporal(),
8901                                   LD->isInvariant(), NewAlign,
8902                                   LD->getAAInfo());
8903       SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
8904                                    DAG.getConstant(NewImm, NewVT));
8905       SDValue NewST = DAG.getStore(Chain, SDLoc(N),
8906                                    NewVal, NewPtr,
8907                                    ST->getPointerInfo().getWithOffset(PtrOff),
8908                                    false, false, NewAlign);
8909
8910       AddToWorklist(NewPtr.getNode());
8911       AddToWorklist(NewLD.getNode());
8912       AddToWorklist(NewVal.getNode());
8913       WorklistRemover DeadNodes(*this);
8914       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
8915       ++OpsNarrowed;
8916       return NewST;
8917     }
8918   }
8919
8920   return SDValue();
8921 }
8922
8923 /// TransformFPLoadStorePair - For a given floating point load / store pair,
8924 /// if the load value isn't used by any other operations, then consider
8925 /// transforming the pair to integer load / store operations if the target
8926 /// deems the transformation profitable.
8927 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
8928   StoreSDNode *ST  = cast<StoreSDNode>(N);
8929   SDValue Chain = ST->getChain();
8930   SDValue Value = ST->getValue();
8931   if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
8932       Value.hasOneUse() &&
8933       Chain == SDValue(Value.getNode(), 1)) {
8934     LoadSDNode *LD = cast<LoadSDNode>(Value);
8935     EVT VT = LD->getMemoryVT();
8936     if (!VT.isFloatingPoint() ||
8937         VT != ST->getMemoryVT() ||
8938         LD->isNonTemporal() ||
8939         ST->isNonTemporal() ||
8940         LD->getPointerInfo().getAddrSpace() != 0 ||
8941         ST->getPointerInfo().getAddrSpace() != 0)
8942       return SDValue();
8943
8944     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
8945     if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
8946         !TLI.isOperationLegal(ISD::STORE, IntVT) ||
8947         !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
8948         !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
8949       return SDValue();
8950
8951     unsigned LDAlign = LD->getAlignment();
8952     unsigned STAlign = ST->getAlignment();
8953     Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
8954     unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
8955     if (LDAlign < ABIAlign || STAlign < ABIAlign)
8956       return SDValue();
8957
8958     SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
8959                                 LD->getChain(), LD->getBasePtr(),
8960                                 LD->getPointerInfo(),
8961                                 false, false, false, LDAlign);
8962
8963     SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
8964                                  NewLD, ST->getBasePtr(),
8965                                  ST->getPointerInfo(),
8966                                  false, false, STAlign);
8967
8968     AddToWorklist(NewLD.getNode());
8969     AddToWorklist(NewST.getNode());
8970     WorklistRemover DeadNodes(*this);
8971     DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
8972     ++LdStFP2Int;
8973     return NewST;
8974   }
8975
8976   return SDValue();
8977 }
8978
8979 /// Helper struct to parse and store a memory address as base + index + offset.
8980 /// We ignore sign extensions when it is safe to do so.
8981 /// The following two expressions are not equivalent. To differentiate we need
8982 /// to store whether there was a sign extension involved in the index
8983 /// computation.
8984 ///  (load (i64 add (i64 copyfromreg %c)
8985 ///                 (i64 signextend (add (i8 load %index)
8986 ///                                      (i8 1))))
8987 /// vs
8988 ///
8989 /// (load (i64 add (i64 copyfromreg %c)
8990 ///                (i64 signextend (i32 add (i32 signextend (i8 load %index))
8991 ///                                         (i32 1)))))
8992 struct BaseIndexOffset {
8993   SDValue Base;
8994   SDValue Index;
8995   int64_t Offset;
8996   bool IsIndexSignExt;
8997
8998   BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
8999
9000   BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
9001                   bool IsIndexSignExt) :
9002     Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
9003
9004   bool equalBaseIndex(const BaseIndexOffset &Other) {
9005     return Other.Base == Base && Other.Index == Index &&
9006       Other.IsIndexSignExt == IsIndexSignExt;
9007   }
9008
9009   /// Parses tree in Ptr for base, index, offset addresses.
9010   static BaseIndexOffset match(SDValue Ptr) {
9011     bool IsIndexSignExt = false;
9012
9013     // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
9014     // instruction, then it could be just the BASE or everything else we don't
9015     // know how to handle. Just use Ptr as BASE and give up.
9016     if (Ptr->getOpcode() != ISD::ADD)
9017       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9018
9019     // We know that we have at least an ADD instruction. Try to pattern match
9020     // the simple case of BASE + OFFSET.
9021     if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
9022       int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
9023       return  BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
9024                               IsIndexSignExt);
9025     }
9026
9027     // Inside a loop the current BASE pointer is calculated using an ADD and a
9028     // MUL instruction. In this case Ptr is the actual BASE pointer.
9029     // (i64 add (i64 %array_ptr)
9030     //          (i64 mul (i64 %induction_var)
9031     //                   (i64 %element_size)))
9032     if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
9033       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9034
9035     // Look at Base + Index + Offset cases.
9036     SDValue Base = Ptr->getOperand(0);
9037     SDValue IndexOffset = Ptr->getOperand(1);
9038
9039     // Skip signextends.
9040     if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
9041       IndexOffset = IndexOffset->getOperand(0);
9042       IsIndexSignExt = true;
9043     }
9044
9045     // Either the case of Base + Index (no offset) or something else.
9046     if (IndexOffset->getOpcode() != ISD::ADD)
9047       return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
9048
9049     // Now we have the case of Base + Index + offset.
9050     SDValue Index = IndexOffset->getOperand(0);
9051     SDValue Offset = IndexOffset->getOperand(1);
9052
9053     if (!isa<ConstantSDNode>(Offset))
9054       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9055
9056     // Ignore signextends.
9057     if (Index->getOpcode() == ISD::SIGN_EXTEND) {
9058       Index = Index->getOperand(0);
9059       IsIndexSignExt = true;
9060     } else IsIndexSignExt = false;
9061
9062     int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
9063     return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
9064   }
9065 };
9066
9067 /// Holds a pointer to an LSBaseSDNode as well as information on where it
9068 /// is located in a sequence of memory operations connected by a chain.
9069 struct MemOpLink {
9070   MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
9071     MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
9072   // Ptr to the mem node.
9073   LSBaseSDNode *MemNode;
9074   // Offset from the base ptr.
9075   int64_t OffsetFromBase;
9076   // What is the sequence number of this mem node.
9077   // Lowest mem operand in the DAG starts at zero.
9078   unsigned SequenceNum;
9079 };
9080
9081 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
9082   EVT MemVT = St->getMemoryVT();
9083   int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
9084   bool NoVectors = DAG.getMachineFunction().getFunction()->getAttributes().
9085     hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
9086
9087   // Don't merge vectors into wider inputs.
9088   if (MemVT.isVector() || !MemVT.isSimple())
9089     return false;
9090
9091   // Perform an early exit check. Do not bother looking at stored values that
9092   // are not constants or loads.
9093   SDValue StoredVal = St->getValue();
9094   bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
9095   if (!isa<ConstantSDNode>(StoredVal) && !isa<ConstantFPSDNode>(StoredVal) &&
9096       !IsLoadSrc)
9097     return false;
9098
9099   // Only look at ends of store sequences.
9100   SDValue Chain = SDValue(St, 0);
9101   if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
9102     return false;
9103
9104   // This holds the base pointer, index, and the offset in bytes from the base
9105   // pointer.
9106   BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
9107
9108   // We must have a base and an offset.
9109   if (!BasePtr.Base.getNode())
9110     return false;
9111
9112   // Do not handle stores to undef base pointers.
9113   if (BasePtr.Base.getOpcode() == ISD::UNDEF)
9114     return false;
9115
9116   // Save the LoadSDNodes that we find in the chain.
9117   // We need to make sure that these nodes do not interfere with
9118   // any of the store nodes.
9119   SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
9120
9121   // Save the StoreSDNodes that we find in the chain.
9122   SmallVector<MemOpLink, 8> StoreNodes;
9123
9124   // Walk up the chain and look for nodes with offsets from the same
9125   // base pointer. Stop when reaching an instruction with a different kind
9126   // or instruction which has a different base pointer.
9127   unsigned Seq = 0;
9128   StoreSDNode *Index = St;
9129   while (Index) {
9130     // If the chain has more than one use, then we can't reorder the mem ops.
9131     if (Index != St && !SDValue(Index, 0)->hasOneUse())
9132       break;
9133
9134     // Find the base pointer and offset for this memory node.
9135     BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
9136
9137     // Check that the base pointer is the same as the original one.
9138     if (!Ptr.equalBaseIndex(BasePtr))
9139       break;
9140
9141     // Check that the alignment is the same.
9142     if (Index->getAlignment() != St->getAlignment())
9143       break;
9144
9145     // The memory operands must not be volatile.
9146     if (Index->isVolatile() || Index->isIndexed())
9147       break;
9148
9149     // No truncation.
9150     if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
9151       if (St->isTruncatingStore())
9152         break;
9153
9154     // The stored memory type must be the same.
9155     if (Index->getMemoryVT() != MemVT)
9156       break;
9157
9158     // We do not allow unaligned stores because we want to prevent overriding
9159     // stores.
9160     if (Index->getAlignment()*8 != MemVT.getSizeInBits())
9161       break;
9162
9163     // We found a potential memory operand to merge.
9164     StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
9165
9166     // Find the next memory operand in the chain. If the next operand in the
9167     // chain is a store then move up and continue the scan with the next
9168     // memory operand. If the next operand is a load save it and use alias
9169     // information to check if it interferes with anything.
9170     SDNode *NextInChain = Index->getChain().getNode();
9171     while (1) {
9172       if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
9173         // We found a store node. Use it for the next iteration.
9174         Index = STn;
9175         break;
9176       } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
9177         if (Ldn->isVolatile()) {
9178           Index = nullptr;
9179           break;
9180         }
9181
9182         // Save the load node for later. Continue the scan.
9183         AliasLoadNodes.push_back(Ldn);
9184         NextInChain = Ldn->getChain().getNode();
9185         continue;
9186       } else {
9187         Index = nullptr;
9188         break;
9189       }
9190     }
9191   }
9192
9193   // Check if there is anything to merge.
9194   if (StoreNodes.size() < 2)
9195     return false;
9196
9197   // Sort the memory operands according to their distance from the base pointer.
9198   std::sort(StoreNodes.begin(), StoreNodes.end(),
9199             [](MemOpLink LHS, MemOpLink RHS) {
9200     return LHS.OffsetFromBase < RHS.OffsetFromBase ||
9201            (LHS.OffsetFromBase == RHS.OffsetFromBase &&
9202             LHS.SequenceNum > RHS.SequenceNum);
9203   });
9204
9205   // Scan the memory operations on the chain and find the first non-consecutive
9206   // store memory address.
9207   unsigned LastConsecutiveStore = 0;
9208   int64_t StartAddress = StoreNodes[0].OffsetFromBase;
9209   for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
9210
9211     // Check that the addresses are consecutive starting from the second
9212     // element in the list of stores.
9213     if (i > 0) {
9214       int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
9215       if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9216         break;
9217     }
9218
9219     bool Alias = false;
9220     // Check if this store interferes with any of the loads that we found.
9221     for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
9222       if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
9223         Alias = true;
9224         break;
9225       }
9226     // We found a load that alias with this store. Stop the sequence.
9227     if (Alias)
9228       break;
9229
9230     // Mark this node as useful.
9231     LastConsecutiveStore = i;
9232   }
9233
9234   // The node with the lowest store address.
9235   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
9236
9237   // Store the constants into memory as one consecutive store.
9238   if (!IsLoadSrc) {
9239     unsigned LastLegalType = 0;
9240     unsigned LastLegalVectorType = 0;
9241     bool NonZero = false;
9242     for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9243       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
9244       SDValue StoredVal = St->getValue();
9245
9246       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
9247         NonZero |= !C->isNullValue();
9248       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
9249         NonZero |= !C->getConstantFPValue()->isNullValue();
9250       } else {
9251         // Non-constant.
9252         break;
9253       }
9254
9255       // Find a legal type for the constant store.
9256       unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9257       EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9258       if (TLI.isTypeLegal(StoreTy))
9259         LastLegalType = i+1;
9260       // Or check whether a truncstore is legal.
9261       else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9262                TargetLowering::TypePromoteInteger) {
9263         EVT LegalizedStoredValueTy =
9264           TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
9265         if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy))
9266           LastLegalType = i+1;
9267       }
9268
9269       // Find a legal type for the vector store.
9270       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9271       if (TLI.isTypeLegal(Ty))
9272         LastLegalVectorType = i + 1;
9273     }
9274
9275     // We only use vectors if the constant is known to be zero and the
9276     // function is not marked with the noimplicitfloat attribute.
9277     if (NonZero || NoVectors)
9278       LastLegalVectorType = 0;
9279
9280     // Check if we found a legal integer type to store.
9281     if (LastLegalType == 0 && LastLegalVectorType == 0)
9282       return false;
9283
9284     bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
9285     unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
9286
9287     // Make sure we have something to merge.
9288     if (NumElem < 2)
9289       return false;
9290
9291     unsigned EarliestNodeUsed = 0;
9292     for (unsigned i=0; i < NumElem; ++i) {
9293       // Find a chain for the new wide-store operand. Notice that some
9294       // of the store nodes that we found may not be selected for inclusion
9295       // in the wide store. The chain we use needs to be the chain of the
9296       // earliest store node which is *used* and replaced by the wide store.
9297       if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9298         EarliestNodeUsed = i;
9299     }
9300
9301     // The earliest Node in the DAG.
9302     LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9303     SDLoc DL(StoreNodes[0].MemNode);
9304
9305     SDValue StoredVal;
9306     if (UseVector) {
9307       // Find a legal type for the vector store.
9308       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9309       assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
9310       StoredVal = DAG.getConstant(0, Ty);
9311     } else {
9312       unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9313       APInt StoreInt(StoreBW, 0);
9314
9315       // Construct a single integer constant which is made of the smaller
9316       // constant inputs.
9317       bool IsLE = TLI.isLittleEndian();
9318       for (unsigned i = 0; i < NumElem ; ++i) {
9319         unsigned Idx = IsLE ?(NumElem - 1 - i) : i;
9320         StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
9321         SDValue Val = St->getValue();
9322         StoreInt<<=ElementSizeBytes*8;
9323         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
9324           StoreInt|=C->getAPIntValue().zext(StoreBW);
9325         } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
9326           StoreInt|= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
9327         } else {
9328           assert(false && "Invalid constant element type");
9329         }
9330       }
9331
9332       // Create the new Load and Store operations.
9333       EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9334       StoredVal = DAG.getConstant(StoreInt, StoreTy);
9335     }
9336
9337     SDValue NewStore = DAG.getStore(EarliestOp->getChain(), DL, StoredVal,
9338                                     FirstInChain->getBasePtr(),
9339                                     FirstInChain->getPointerInfo(),
9340                                     false, false,
9341                                     FirstInChain->getAlignment());
9342
9343     // Replace the first store with the new store
9344     CombineTo(EarliestOp, NewStore);
9345     // Erase all other stores.
9346     for (unsigned i = 0; i < NumElem ; ++i) {
9347       if (StoreNodes[i].MemNode == EarliestOp)
9348         continue;
9349       StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9350       // ReplaceAllUsesWith will replace all uses that existed when it was
9351       // called, but graph optimizations may cause new ones to appear. For
9352       // example, the case in pr14333 looks like
9353       //
9354       //  St's chain -> St -> another store -> X
9355       //
9356       // And the only difference from St to the other store is the chain.
9357       // When we change it's chain to be St's chain they become identical,
9358       // get CSEed and the net result is that X is now a use of St.
9359       // Since we know that St is redundant, just iterate.
9360       while (!St->use_empty())
9361         DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
9362       deleteAndRecombine(St);
9363     }
9364
9365     return true;
9366   }
9367
9368   // Below we handle the case of multiple consecutive stores that
9369   // come from multiple consecutive loads. We merge them into a single
9370   // wide load and a single wide store.
9371
9372   // Look for load nodes which are used by the stored values.
9373   SmallVector<MemOpLink, 8> LoadNodes;
9374
9375   // Find acceptable loads. Loads need to have the same chain (token factor),
9376   // must not be zext, volatile, indexed, and they must be consecutive.
9377   BaseIndexOffset LdBasePtr;
9378   for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9379     StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
9380     LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
9381     if (!Ld) break;
9382
9383     // Loads must only have one use.
9384     if (!Ld->hasNUsesOfValue(1, 0))
9385       break;
9386
9387     // Check that the alignment is the same as the stores.
9388     if (Ld->getAlignment() != St->getAlignment())
9389       break;
9390
9391     // The memory operands must not be volatile.
9392     if (Ld->isVolatile() || Ld->isIndexed())
9393       break;
9394
9395     // We do not accept ext loads.
9396     if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
9397       break;
9398
9399     // The stored memory type must be the same.
9400     if (Ld->getMemoryVT() != MemVT)
9401       break;
9402
9403     BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
9404     // If this is not the first ptr that we check.
9405     if (LdBasePtr.Base.getNode()) {
9406       // The base ptr must be the same.
9407       if (!LdPtr.equalBaseIndex(LdBasePtr))
9408         break;
9409     } else {
9410       // Check that all other base pointers are the same as this one.
9411       LdBasePtr = LdPtr;
9412     }
9413
9414     // We found a potential memory operand to merge.
9415     LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
9416   }
9417
9418   if (LoadNodes.size() < 2)
9419     return false;
9420
9421   // If we have load/store pair instructions and we only have two values,
9422   // don't bother.
9423   unsigned RequiredAlignment;
9424   if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) &&
9425       St->getAlignment() >= RequiredAlignment)
9426     return false;
9427
9428   // Scan the memory operations on the chain and find the first non-consecutive
9429   // load memory address. These variables hold the index in the store node
9430   // array.
9431   unsigned LastConsecutiveLoad = 0;
9432   // This variable refers to the size and not index in the array.
9433   unsigned LastLegalVectorType = 0;
9434   unsigned LastLegalIntegerType = 0;
9435   StartAddress = LoadNodes[0].OffsetFromBase;
9436   SDValue FirstChain = LoadNodes[0].MemNode->getChain();
9437   for (unsigned i = 1; i < LoadNodes.size(); ++i) {
9438     // All loads much share the same chain.
9439     if (LoadNodes[i].MemNode->getChain() != FirstChain)
9440       break;
9441
9442     int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
9443     if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9444       break;
9445     LastConsecutiveLoad = i;
9446
9447     // Find a legal type for the vector store.
9448     EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9449     if (TLI.isTypeLegal(StoreTy))
9450       LastLegalVectorType = i + 1;
9451
9452     // Find a legal type for the integer store.
9453     unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9454     StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9455     if (TLI.isTypeLegal(StoreTy))
9456       LastLegalIntegerType = i + 1;
9457     // Or check whether a truncstore and extload is legal.
9458     else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9459              TargetLowering::TypePromoteInteger) {
9460       EVT LegalizedStoredValueTy =
9461         TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
9462       if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
9463           TLI.isLoadExtLegal(ISD::ZEXTLOAD, StoreTy) &&
9464           TLI.isLoadExtLegal(ISD::SEXTLOAD, StoreTy) &&
9465           TLI.isLoadExtLegal(ISD::EXTLOAD, StoreTy))
9466         LastLegalIntegerType = i+1;
9467     }
9468   }
9469
9470   // Only use vector types if the vector type is larger than the integer type.
9471   // If they are the same, use integers.
9472   bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
9473   unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
9474
9475   // We add +1 here because the LastXXX variables refer to location while
9476   // the NumElem refers to array/index size.
9477   unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
9478   NumElem = std::min(LastLegalType, NumElem);
9479
9480   if (NumElem < 2)
9481     return false;
9482
9483   // The earliest Node in the DAG.
9484   unsigned EarliestNodeUsed = 0;
9485   LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9486   for (unsigned i=1; i<NumElem; ++i) {
9487     // Find a chain for the new wide-store operand. Notice that some
9488     // of the store nodes that we found may not be selected for inclusion
9489     // in the wide store. The chain we use needs to be the chain of the
9490     // earliest store node which is *used* and replaced by the wide store.
9491     if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9492       EarliestNodeUsed = i;
9493   }
9494
9495   // Find if it is better to use vectors or integers to load and store
9496   // to memory.
9497   EVT JointMemOpVT;
9498   if (UseVectorTy) {
9499     JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9500   } else {
9501     unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9502     JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9503   }
9504
9505   SDLoc LoadDL(LoadNodes[0].MemNode);
9506   SDLoc StoreDL(StoreNodes[0].MemNode);
9507
9508   LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
9509   SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL,
9510                                 FirstLoad->getChain(),
9511                                 FirstLoad->getBasePtr(),
9512                                 FirstLoad->getPointerInfo(),
9513                                 false, false, false,
9514                                 FirstLoad->getAlignment());
9515
9516   SDValue NewStore = DAG.getStore(EarliestOp->getChain(), StoreDL, NewLoad,
9517                                   FirstInChain->getBasePtr(),
9518                                   FirstInChain->getPointerInfo(), false, false,
9519                                   FirstInChain->getAlignment());
9520
9521   // Replace one of the loads with the new load.
9522   LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
9523   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
9524                                 SDValue(NewLoad.getNode(), 1));
9525
9526   // Remove the rest of the load chains.
9527   for (unsigned i = 1; i < NumElem ; ++i) {
9528     // Replace all chain users of the old load nodes with the chain of the new
9529     // load node.
9530     LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
9531     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
9532   }
9533
9534   // Replace the first store with the new store.
9535   CombineTo(EarliestOp, NewStore);
9536   // Erase all other stores.
9537   for (unsigned i = 0; i < NumElem ; ++i) {
9538     // Remove all Store nodes.
9539     if (StoreNodes[i].MemNode == EarliestOp)
9540       continue;
9541     StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9542     DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
9543     deleteAndRecombine(St);
9544   }
9545
9546   return true;
9547 }
9548
9549 SDValue DAGCombiner::visitSTORE(SDNode *N) {
9550   StoreSDNode *ST  = cast<StoreSDNode>(N);
9551   SDValue Chain = ST->getChain();
9552   SDValue Value = ST->getValue();
9553   SDValue Ptr   = ST->getBasePtr();
9554
9555   // If this is a store of a bit convert, store the input value if the
9556   // resultant store does not need a higher alignment than the original.
9557   if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
9558       ST->isUnindexed()) {
9559     unsigned OrigAlign = ST->getAlignment();
9560     EVT SVT = Value.getOperand(0).getValueType();
9561     unsigned Align = TLI.getDataLayout()->
9562       getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
9563     if (Align <= OrigAlign &&
9564         ((!LegalOperations && !ST->isVolatile()) ||
9565          TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
9566       return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
9567                           Ptr, ST->getPointerInfo(), ST->isVolatile(),
9568                           ST->isNonTemporal(), OrigAlign,
9569                           ST->getAAInfo());
9570   }
9571
9572   // Turn 'store undef, Ptr' -> nothing.
9573   if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
9574     return Chain;
9575
9576   // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
9577   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
9578     // NOTE: If the original store is volatile, this transform must not increase
9579     // the number of stores.  For example, on x86-32 an f64 can be stored in one
9580     // processor operation but an i64 (which is not legal) requires two.  So the
9581     // transform should not be done in this case.
9582     if (Value.getOpcode() != ISD::TargetConstantFP) {
9583       SDValue Tmp;
9584       switch (CFP->getSimpleValueType(0).SimpleTy) {
9585       default: llvm_unreachable("Unknown FP type");
9586       case MVT::f16:    // We don't do this for these yet.
9587       case MVT::f80:
9588       case MVT::f128:
9589       case MVT::ppcf128:
9590         break;
9591       case MVT::f32:
9592         if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
9593             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
9594           Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
9595                               bitcastToAPInt().getZExtValue(), MVT::i32);
9596           return DAG.getStore(Chain, SDLoc(N), Tmp,
9597                               Ptr, ST->getMemOperand());
9598         }
9599         break;
9600       case MVT::f64:
9601         if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
9602              !ST->isVolatile()) ||
9603             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
9604           Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
9605                                 getZExtValue(), MVT::i64);
9606           return DAG.getStore(Chain, SDLoc(N), Tmp,
9607                               Ptr, ST->getMemOperand());
9608         }
9609
9610         if (!ST->isVolatile() &&
9611             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
9612           // Many FP stores are not made apparent until after legalize, e.g. for
9613           // argument passing.  Since this is so common, custom legalize the
9614           // 64-bit integer store into two 32-bit stores.
9615           uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
9616           SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
9617           SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
9618           if (TLI.isBigEndian()) std::swap(Lo, Hi);
9619
9620           unsigned Alignment = ST->getAlignment();
9621           bool isVolatile = ST->isVolatile();
9622           bool isNonTemporal = ST->isNonTemporal();
9623           AAMDNodes AAInfo = ST->getAAInfo();
9624
9625           SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
9626                                      Ptr, ST->getPointerInfo(),
9627                                      isVolatile, isNonTemporal,
9628                                      ST->getAlignment(), AAInfo);
9629           Ptr = DAG.getNode(ISD::ADD, SDLoc(N), Ptr.getValueType(), Ptr,
9630                             DAG.getConstant(4, Ptr.getValueType()));
9631           Alignment = MinAlign(Alignment, 4U);
9632           SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
9633                                      Ptr, ST->getPointerInfo().getWithOffset(4),
9634                                      isVolatile, isNonTemporal,
9635                                      Alignment, AAInfo);
9636           return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
9637                              St0, St1);
9638         }
9639
9640         break;
9641       }
9642     }
9643   }
9644
9645   // Try to infer better alignment information than the store already has.
9646   if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
9647     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
9648       if (Align > ST->getAlignment())
9649         return DAG.getTruncStore(Chain, SDLoc(N), Value,
9650                                  Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
9651                                  ST->isVolatile(), ST->isNonTemporal(), Align,
9652                                  ST->getAAInfo());
9653     }
9654   }
9655
9656   // Try transforming a pair floating point load / store ops to integer
9657   // load / store ops.
9658   SDValue NewST = TransformFPLoadStorePair(N);
9659   if (NewST.getNode())
9660     return NewST;
9661
9662   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
9663     TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
9664 #ifndef NDEBUG
9665   if (CombinerAAOnlyFunc.getNumOccurrences() &&
9666       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
9667     UseAA = false;
9668 #endif
9669   if (UseAA && ST->isUnindexed()) {
9670     // Walk up chain skipping non-aliasing memory nodes.
9671     SDValue BetterChain = FindBetterChain(N, Chain);
9672
9673     // If there is a better chain.
9674     if (Chain != BetterChain) {
9675       SDValue ReplStore;
9676
9677       // Replace the chain to avoid dependency.
9678       if (ST->isTruncatingStore()) {
9679         ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
9680                                       ST->getMemoryVT(), ST->getMemOperand());
9681       } else {
9682         ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
9683                                  ST->getMemOperand());
9684       }
9685
9686       // Create token to keep both nodes around.
9687       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
9688                                   MVT::Other, Chain, ReplStore);
9689
9690       // Make sure the new and old chains are cleaned up.
9691       AddToWorklist(Token.getNode());
9692
9693       // Don't add users to work list.
9694       return CombineTo(N, Token, false);
9695     }
9696   }
9697
9698   // Try transforming N to an indexed store.
9699   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
9700     return SDValue(N, 0);
9701
9702   // FIXME: is there such a thing as a truncating indexed store?
9703   if (ST->isTruncatingStore() && ST->isUnindexed() &&
9704       Value.getValueType().isInteger()) {
9705     // See if we can simplify the input to this truncstore with knowledge that
9706     // only the low bits are being used.  For example:
9707     // "truncstore (or (shl x, 8), y), i8"  -> "truncstore y, i8"
9708     SDValue Shorter =
9709       GetDemandedBits(Value,
9710                       APInt::getLowBitsSet(
9711                         Value.getValueType().getScalarType().getSizeInBits(),
9712                         ST->getMemoryVT().getScalarType().getSizeInBits()));
9713     AddToWorklist(Value.getNode());
9714     if (Shorter.getNode())
9715       return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
9716                                Ptr, ST->getMemoryVT(), ST->getMemOperand());
9717
9718     // Otherwise, see if we can simplify the operation with
9719     // SimplifyDemandedBits, which only works if the value has a single use.
9720     if (SimplifyDemandedBits(Value,
9721                         APInt::getLowBitsSet(
9722                           Value.getValueType().getScalarType().getSizeInBits(),
9723                           ST->getMemoryVT().getScalarType().getSizeInBits())))
9724       return SDValue(N, 0);
9725   }
9726
9727   // If this is a load followed by a store to the same location, then the store
9728   // is dead/noop.
9729   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
9730     if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
9731         ST->isUnindexed() && !ST->isVolatile() &&
9732         // There can't be any side effects between the load and store, such as
9733         // a call or store.
9734         Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
9735       // The store is dead, remove it.
9736       return Chain;
9737     }
9738   }
9739
9740   // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
9741   // truncating store.  We can do this even if this is already a truncstore.
9742   if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
9743       && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
9744       TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
9745                             ST->getMemoryVT())) {
9746     return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
9747                              Ptr, ST->getMemoryVT(), ST->getMemOperand());
9748   }
9749
9750   // Only perform this optimization before the types are legal, because we
9751   // don't want to perform this optimization on every DAGCombine invocation.
9752   if (!LegalTypes) {
9753     bool EverChanged = false;
9754
9755     do {
9756       // There can be multiple store sequences on the same chain.
9757       // Keep trying to merge store sequences until we are unable to do so
9758       // or until we merge the last store on the chain.
9759       bool Changed = MergeConsecutiveStores(ST);
9760       EverChanged |= Changed;
9761       if (!Changed) break;
9762     } while (ST->getOpcode() != ISD::DELETED_NODE);
9763
9764     if (EverChanged)
9765       return SDValue(N, 0);
9766   }
9767
9768   return ReduceLoadOpStoreWidth(N);
9769 }
9770
9771 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
9772   SDValue InVec = N->getOperand(0);
9773   SDValue InVal = N->getOperand(1);
9774   SDValue EltNo = N->getOperand(2);
9775   SDLoc dl(N);
9776
9777   // If the inserted element is an UNDEF, just use the input vector.
9778   if (InVal.getOpcode() == ISD::UNDEF)
9779     return InVec;
9780
9781   EVT VT = InVec.getValueType();
9782
9783   // If we can't generate a legal BUILD_VECTOR, exit
9784   if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
9785     return SDValue();
9786
9787   // Check that we know which element is being inserted
9788   if (!isa<ConstantSDNode>(EltNo))
9789     return SDValue();
9790   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9791
9792   // Canonicalize insert_vector_elt dag nodes.
9793   // Example:
9794   // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
9795   // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
9796   //
9797   // Do this only if the child insert_vector node has one use; also
9798   // do this only if indices are both constants and Idx1 < Idx0.
9799   if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
9800       && isa<ConstantSDNode>(InVec.getOperand(2))) {
9801     unsigned OtherElt =
9802       cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue();
9803     if (Elt < OtherElt) {
9804       // Swap nodes.
9805       SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT,
9806                                   InVec.getOperand(0), InVal, EltNo);
9807       AddToWorklist(NewOp.getNode());
9808       return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
9809                          VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
9810     }
9811   }
9812
9813   // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
9814   // be converted to a BUILD_VECTOR).  Fill in the Ops vector with the
9815   // vector elements.
9816   SmallVector<SDValue, 8> Ops;
9817   // Do not combine these two vectors if the output vector will not replace
9818   // the input vector.
9819   if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
9820     Ops.append(InVec.getNode()->op_begin(),
9821                InVec.getNode()->op_end());
9822   } else if (InVec.getOpcode() == ISD::UNDEF) {
9823     unsigned NElts = VT.getVectorNumElements();
9824     Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
9825   } else {
9826     return SDValue();
9827   }
9828
9829   // Insert the element
9830   if (Elt < Ops.size()) {
9831     // All the operands of BUILD_VECTOR must have the same type;
9832     // we enforce that here.
9833     EVT OpVT = Ops[0].getValueType();
9834     if (InVal.getValueType() != OpVT)
9835       InVal = OpVT.bitsGT(InVal.getValueType()) ?
9836                 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
9837                 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
9838     Ops[Elt] = InVal;
9839   }
9840
9841   // Return the new vector
9842   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
9843 }
9844
9845 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
9846   // (vextract (scalar_to_vector val, 0) -> val
9847   SDValue InVec = N->getOperand(0);
9848   EVT VT = InVec.getValueType();
9849   EVT NVT = N->getValueType(0);
9850
9851   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
9852     // Check if the result type doesn't match the inserted element type. A
9853     // SCALAR_TO_VECTOR may truncate the inserted element and the
9854     // EXTRACT_VECTOR_ELT may widen the extracted vector.
9855     SDValue InOp = InVec.getOperand(0);
9856     if (InOp.getValueType() != NVT) {
9857       assert(InOp.getValueType().isInteger() && NVT.isInteger());
9858       return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
9859     }
9860     return InOp;
9861   }
9862
9863   SDValue EltNo = N->getOperand(1);
9864   bool ConstEltNo = isa<ConstantSDNode>(EltNo);
9865
9866   // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
9867   // We only perform this optimization before the op legalization phase because
9868   // we may introduce new vector instructions which are not backed by TD
9869   // patterns. For example on AVX, extracting elements from a wide vector
9870   // without using extract_subvector. However, if we can find an underlying
9871   // scalar value, then we can always use that.
9872   if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
9873       && ConstEltNo) {
9874     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9875     int NumElem = VT.getVectorNumElements();
9876     ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
9877     // Find the new index to extract from.
9878     int OrigElt = SVOp->getMaskElt(Elt);
9879
9880     // Extracting an undef index is undef.
9881     if (OrigElt == -1)
9882       return DAG.getUNDEF(NVT);
9883
9884     // Select the right vector half to extract from.
9885     SDValue SVInVec;
9886     if (OrigElt < NumElem) {
9887       SVInVec = InVec->getOperand(0);
9888     } else {
9889       SVInVec = InVec->getOperand(1);
9890       OrigElt -= NumElem;
9891     }
9892
9893     if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
9894       SDValue InOp = SVInVec.getOperand(OrigElt);
9895       if (InOp.getValueType() != NVT) {
9896         assert(InOp.getValueType().isInteger() && NVT.isInteger());
9897         InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
9898       }
9899
9900       return InOp;
9901     }
9902
9903     // FIXME: We should handle recursing on other vector shuffles and
9904     // scalar_to_vector here as well.
9905
9906     if (!LegalOperations) {
9907       EVT IndexTy = TLI.getVectorIdxTy();
9908       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT,
9909                          SVInVec, DAG.getConstant(OrigElt, IndexTy));
9910     }
9911   }
9912
9913   // Perform only after legalization to ensure build_vector / vector_shuffle
9914   // optimizations have already been done.
9915   if (!LegalOperations) return SDValue();
9916
9917   // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
9918   // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
9919   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
9920
9921   if (ConstEltNo) {
9922     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9923     bool NewLoad = false;
9924     bool BCNumEltsChanged = false;
9925     EVT ExtVT = VT.getVectorElementType();
9926     EVT LVT = ExtVT;
9927
9928     // If the result of load has to be truncated, then it's not necessarily
9929     // profitable.
9930     if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
9931       return SDValue();
9932
9933     if (InVec.getOpcode() == ISD::BITCAST) {
9934       // Don't duplicate a load with other uses.
9935       if (!InVec.hasOneUse())
9936         return SDValue();
9937
9938       EVT BCVT = InVec.getOperand(0).getValueType();
9939       if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
9940         return SDValue();
9941       if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
9942         BCNumEltsChanged = true;
9943       InVec = InVec.getOperand(0);
9944       ExtVT = BCVT.getVectorElementType();
9945       NewLoad = true;
9946     }
9947
9948     LoadSDNode *LN0 = nullptr;
9949     const ShuffleVectorSDNode *SVN = nullptr;
9950     if (ISD::isNormalLoad(InVec.getNode())) {
9951       LN0 = cast<LoadSDNode>(InVec);
9952     } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
9953                InVec.getOperand(0).getValueType() == ExtVT &&
9954                ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
9955       // Don't duplicate a load with other uses.
9956       if (!InVec.hasOneUse())
9957         return SDValue();
9958
9959       LN0 = cast<LoadSDNode>(InVec.getOperand(0));
9960     } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
9961       // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
9962       // =>
9963       // (load $addr+1*size)
9964
9965       // Don't duplicate a load with other uses.
9966       if (!InVec.hasOneUse())
9967         return SDValue();
9968
9969       // If the bit convert changed the number of elements, it is unsafe
9970       // to examine the mask.
9971       if (BCNumEltsChanged)
9972         return SDValue();
9973
9974       // Select the input vector, guarding against out of range extract vector.
9975       unsigned NumElems = VT.getVectorNumElements();
9976       int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
9977       InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
9978
9979       if (InVec.getOpcode() == ISD::BITCAST) {
9980         // Don't duplicate a load with other uses.
9981         if (!InVec.hasOneUse())
9982           return SDValue();
9983
9984         InVec = InVec.getOperand(0);
9985       }
9986       if (ISD::isNormalLoad(InVec.getNode())) {
9987         LN0 = cast<LoadSDNode>(InVec);
9988         Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
9989       }
9990     }
9991
9992     // Make sure we found a non-volatile load and the extractelement is
9993     // the only use.
9994     if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
9995       return SDValue();
9996
9997     // If Idx was -1 above, Elt is going to be -1, so just return undef.
9998     if (Elt == -1)
9999       return DAG.getUNDEF(LVT);
10000
10001     unsigned Align = LN0->getAlignment();
10002     if (NewLoad) {
10003       // Check the resultant load doesn't need a higher alignment than the
10004       // original load.
10005       unsigned NewAlign =
10006         TLI.getDataLayout()
10007             ->getABITypeAlignment(LVT.getTypeForEVT(*DAG.getContext()));
10008
10009       if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, LVT))
10010         return SDValue();
10011
10012       Align = NewAlign;
10013     }
10014
10015     SDValue NewPtr = LN0->getBasePtr();
10016     unsigned PtrOff = 0;
10017
10018     if (Elt) {
10019       PtrOff = LVT.getSizeInBits() * Elt / 8;
10020       EVT PtrType = NewPtr.getValueType();
10021       if (TLI.isBigEndian())
10022         PtrOff = VT.getSizeInBits() / 8 - PtrOff;
10023       NewPtr = DAG.getNode(ISD::ADD, SDLoc(N), PtrType, NewPtr,
10024                            DAG.getConstant(PtrOff, PtrType));
10025     }
10026
10027     // The replacement we need to do here is a little tricky: we need to
10028     // replace an extractelement of a load with a load.
10029     // Use ReplaceAllUsesOfValuesWith to do the replacement.
10030     // Note that this replacement assumes that the extractvalue is the only
10031     // use of the load; that's okay because we don't want to perform this
10032     // transformation in other cases anyway.
10033     SDValue Load;
10034     SDValue Chain;
10035     if (NVT.bitsGT(LVT)) {
10036       // If the result type of vextract is wider than the load, then issue an
10037       // extending load instead.
10038       ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, LVT)
10039         ? ISD::ZEXTLOAD : ISD::EXTLOAD;
10040       Load = DAG.getExtLoad(ExtType, SDLoc(N), NVT, LN0->getChain(),
10041                             NewPtr, LN0->getPointerInfo().getWithOffset(PtrOff),
10042                             LVT, LN0->isVolatile(), LN0->isNonTemporal(),
10043                             LN0->isInvariant(), Align, LN0->getAAInfo());
10044       Chain = Load.getValue(1);
10045     } else {
10046       Load = DAG.getLoad(LVT, SDLoc(N), LN0->getChain(), NewPtr,
10047                          LN0->getPointerInfo().getWithOffset(PtrOff),
10048                          LN0->isVolatile(), LN0->isNonTemporal(),
10049                          LN0->isInvariant(), Align, LN0->getAAInfo());
10050       Chain = Load.getValue(1);
10051       if (NVT.bitsLT(LVT))
10052         Load = DAG.getNode(ISD::TRUNCATE, SDLoc(N), NVT, Load);
10053       else
10054         Load = DAG.getNode(ISD::BITCAST, SDLoc(N), NVT, Load);
10055     }
10056     WorklistRemover DeadNodes(*this);
10057     SDValue From[] = { SDValue(N, 0), SDValue(LN0,1) };
10058     SDValue To[] = { Load, Chain };
10059     DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
10060     // Since we're explcitly calling ReplaceAllUses, add the new node to the
10061     // worklist explicitly as well.
10062     AddToWorklist(Load.getNode());
10063     AddUsersToWorklist(Load.getNode()); // Add users too
10064     // Make sure to revisit this node to clean it up; it will usually be dead.
10065     AddToWorklist(N);
10066     return SDValue(N, 0);
10067   }
10068
10069   return SDValue();
10070 }
10071
10072 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
10073 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
10074   // We perform this optimization post type-legalization because
10075   // the type-legalizer often scalarizes integer-promoted vectors.
10076   // Performing this optimization before may create bit-casts which
10077   // will be type-legalized to complex code sequences.
10078   // We perform this optimization only before the operation legalizer because we
10079   // may introduce illegal operations.
10080   if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
10081     return SDValue();
10082
10083   unsigned NumInScalars = N->getNumOperands();
10084   SDLoc dl(N);
10085   EVT VT = N->getValueType(0);
10086
10087   // Check to see if this is a BUILD_VECTOR of a bunch of values
10088   // which come from any_extend or zero_extend nodes. If so, we can create
10089   // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
10090   // optimizations. We do not handle sign-extend because we can't fill the sign
10091   // using shuffles.
10092   EVT SourceType = MVT::Other;
10093   bool AllAnyExt = true;
10094
10095   for (unsigned i = 0; i != NumInScalars; ++i) {
10096     SDValue In = N->getOperand(i);
10097     // Ignore undef inputs.
10098     if (In.getOpcode() == ISD::UNDEF) continue;
10099
10100     bool AnyExt  = In.getOpcode() == ISD::ANY_EXTEND;
10101     bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
10102
10103     // Abort if the element is not an extension.
10104     if (!ZeroExt && !AnyExt) {
10105       SourceType = MVT::Other;
10106       break;
10107     }
10108
10109     // The input is a ZeroExt or AnyExt. Check the original type.
10110     EVT InTy = In.getOperand(0).getValueType();
10111
10112     // Check that all of the widened source types are the same.
10113     if (SourceType == MVT::Other)
10114       // First time.
10115       SourceType = InTy;
10116     else if (InTy != SourceType) {
10117       // Multiple income types. Abort.
10118       SourceType = MVT::Other;
10119       break;
10120     }
10121
10122     // Check if all of the extends are ANY_EXTENDs.
10123     AllAnyExt &= AnyExt;
10124   }
10125
10126   // In order to have valid types, all of the inputs must be extended from the
10127   // same source type and all of the inputs must be any or zero extend.
10128   // Scalar sizes must be a power of two.
10129   EVT OutScalarTy = VT.getScalarType();
10130   bool ValidTypes = SourceType != MVT::Other &&
10131                  isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
10132                  isPowerOf2_32(SourceType.getSizeInBits());
10133
10134   // Create a new simpler BUILD_VECTOR sequence which other optimizations can
10135   // turn into a single shuffle instruction.
10136   if (!ValidTypes)
10137     return SDValue();
10138
10139   bool isLE = TLI.isLittleEndian();
10140   unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
10141   assert(ElemRatio > 1 && "Invalid element size ratio");
10142   SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
10143                                DAG.getConstant(0, SourceType);
10144
10145   unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
10146   SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
10147
10148   // Populate the new build_vector
10149   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
10150     SDValue Cast = N->getOperand(i);
10151     assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
10152             Cast.getOpcode() == ISD::ZERO_EXTEND ||
10153             Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
10154     SDValue In;
10155     if (Cast.getOpcode() == ISD::UNDEF)
10156       In = DAG.getUNDEF(SourceType);
10157     else
10158       In = Cast->getOperand(0);
10159     unsigned Index = isLE ? (i * ElemRatio) :
10160                             (i * ElemRatio + (ElemRatio - 1));
10161
10162     assert(Index < Ops.size() && "Invalid index");
10163     Ops[Index] = In;
10164   }
10165
10166   // The type of the new BUILD_VECTOR node.
10167   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
10168   assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
10169          "Invalid vector size");
10170   // Check if the new vector type is legal.
10171   if (!isTypeLegal(VecVT)) return SDValue();
10172
10173   // Make the new BUILD_VECTOR.
10174   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
10175
10176   // The new BUILD_VECTOR node has the potential to be further optimized.
10177   AddToWorklist(BV.getNode());
10178   // Bitcast to the desired type.
10179   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
10180 }
10181
10182 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
10183   EVT VT = N->getValueType(0);
10184
10185   unsigned NumInScalars = N->getNumOperands();
10186   SDLoc dl(N);
10187
10188   EVT SrcVT = MVT::Other;
10189   unsigned Opcode = ISD::DELETED_NODE;
10190   unsigned NumDefs = 0;
10191
10192   for (unsigned i = 0; i != NumInScalars; ++i) {
10193     SDValue In = N->getOperand(i);
10194     unsigned Opc = In.getOpcode();
10195
10196     if (Opc == ISD::UNDEF)
10197       continue;
10198
10199     // If all scalar values are floats and converted from integers.
10200     if (Opcode == ISD::DELETED_NODE &&
10201         (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
10202       Opcode = Opc;
10203     }
10204
10205     if (Opc != Opcode)
10206       return SDValue();
10207
10208     EVT InVT = In.getOperand(0).getValueType();
10209
10210     // If all scalar values are typed differently, bail out. It's chosen to
10211     // simplify BUILD_VECTOR of integer types.
10212     if (SrcVT == MVT::Other)
10213       SrcVT = InVT;
10214     if (SrcVT != InVT)
10215       return SDValue();
10216     NumDefs++;
10217   }
10218
10219   // If the vector has just one element defined, it's not worth to fold it into
10220   // a vectorized one.
10221   if (NumDefs < 2)
10222     return SDValue();
10223
10224   assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
10225          && "Should only handle conversion from integer to float.");
10226   assert(SrcVT != MVT::Other && "Cannot determine source type!");
10227
10228   EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
10229
10230   if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
10231     return SDValue();
10232
10233   SmallVector<SDValue, 8> Opnds;
10234   for (unsigned i = 0; i != NumInScalars; ++i) {
10235     SDValue In = N->getOperand(i);
10236
10237     if (In.getOpcode() == ISD::UNDEF)
10238       Opnds.push_back(DAG.getUNDEF(SrcVT));
10239     else
10240       Opnds.push_back(In.getOperand(0));
10241   }
10242   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds);
10243   AddToWorklist(BV.getNode());
10244
10245   return DAG.getNode(Opcode, dl, VT, BV);
10246 }
10247
10248 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
10249   unsigned NumInScalars = N->getNumOperands();
10250   SDLoc dl(N);
10251   EVT VT = N->getValueType(0);
10252
10253   // A vector built entirely of undefs is undef.
10254   if (ISD::allOperandsUndef(N))
10255     return DAG.getUNDEF(VT);
10256
10257   SDValue V = reduceBuildVecExtToExtBuildVec(N);
10258   if (V.getNode())
10259     return V;
10260
10261   V = reduceBuildVecConvertToConvertBuildVec(N);
10262   if (V.getNode())
10263     return V;
10264
10265   // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
10266   // operations.  If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
10267   // at most two distinct vectors, turn this into a shuffle node.
10268
10269   // May only combine to shuffle after legalize if shuffle is legal.
10270   if (LegalOperations &&
10271       !TLI.isOperationLegalOrCustom(ISD::VECTOR_SHUFFLE, VT))
10272     return SDValue();
10273
10274   SDValue VecIn1, VecIn2;
10275   for (unsigned i = 0; i != NumInScalars; ++i) {
10276     // Ignore undef inputs.
10277     if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
10278
10279     // If this input is something other than a EXTRACT_VECTOR_ELT with a
10280     // constant index, bail out.
10281     if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10282         !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) {
10283       VecIn1 = VecIn2 = SDValue(nullptr, 0);
10284       break;
10285     }
10286
10287     // We allow up to two distinct input vectors.
10288     SDValue ExtractedFromVec = N->getOperand(i).getOperand(0);
10289     if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
10290       continue;
10291
10292     if (!VecIn1.getNode()) {
10293       VecIn1 = ExtractedFromVec;
10294     } else if (!VecIn2.getNode()) {
10295       VecIn2 = ExtractedFromVec;
10296     } else {
10297       // Too many inputs.
10298       VecIn1 = VecIn2 = SDValue(nullptr, 0);
10299       break;
10300     }
10301   }
10302
10303   // If everything is good, we can make a shuffle operation.
10304   if (VecIn1.getNode()) {
10305     SmallVector<int, 8> Mask;
10306     for (unsigned i = 0; i != NumInScalars; ++i) {
10307       if (N->getOperand(i).getOpcode() == ISD::UNDEF) {
10308         Mask.push_back(-1);
10309         continue;
10310       }
10311
10312       // If extracting from the first vector, just use the index directly.
10313       SDValue Extract = N->getOperand(i);
10314       SDValue ExtVal = Extract.getOperand(1);
10315       if (Extract.getOperand(0) == VecIn1) {
10316         unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
10317         if (ExtIndex > VT.getVectorNumElements())
10318           return SDValue();
10319
10320         Mask.push_back(ExtIndex);
10321         continue;
10322       }
10323
10324       // Otherwise, use InIdx + VecSize
10325       unsigned Idx = cast<ConstantSDNode>(ExtVal)->getZExtValue();
10326       Mask.push_back(Idx+NumInScalars);
10327     }
10328
10329     // We can't generate a shuffle node with mismatched input and output types.
10330     // Attempt to transform a single input vector to the correct type.
10331     if ((VT != VecIn1.getValueType())) {
10332       // We don't support shuffeling between TWO values of different types.
10333       if (VecIn2.getNode())
10334         return SDValue();
10335
10336       // We only support widening of vectors which are half the size of the
10337       // output registers. For example XMM->YMM widening on X86 with AVX.
10338       if (VecIn1.getValueType().getSizeInBits()*2 != VT.getSizeInBits())
10339         return SDValue();
10340
10341       // If the input vector type has a different base type to the output
10342       // vector type, bail out.
10343       if (VecIn1.getValueType().getVectorElementType() !=
10344           VT.getVectorElementType())
10345         return SDValue();
10346
10347       // Widen the input vector by adding undef values.
10348       VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10349                            VecIn1, DAG.getUNDEF(VecIn1.getValueType()));
10350     }
10351
10352     // If VecIn2 is unused then change it to undef.
10353     VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
10354
10355     // Check that we were able to transform all incoming values to the same
10356     // type.
10357     if (VecIn2.getValueType() != VecIn1.getValueType() ||
10358         VecIn1.getValueType() != VT)
10359           return SDValue();
10360
10361     // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
10362     if (!isTypeLegal(VT))
10363       return SDValue();
10364
10365     // Return the new VECTOR_SHUFFLE node.
10366     SDValue Ops[2];
10367     Ops[0] = VecIn1;
10368     Ops[1] = VecIn2;
10369     return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
10370   }
10371
10372   return SDValue();
10373 }
10374
10375 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
10376   // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
10377   // EXTRACT_SUBVECTOR operations.  If so, and if the EXTRACT_SUBVECTOR vector
10378   // inputs come from at most two distinct vectors, turn this into a shuffle
10379   // node.
10380
10381   // If we only have one input vector, we don't need to do any concatenation.
10382   if (N->getNumOperands() == 1)
10383     return N->getOperand(0);
10384
10385   // Check if all of the operands are undefs.
10386   EVT VT = N->getValueType(0);
10387   if (ISD::allOperandsUndef(N))
10388     return DAG.getUNDEF(VT);
10389
10390   // Optimize concat_vectors where one of the vectors is undef.
10391   if (N->getNumOperands() == 2 &&
10392       N->getOperand(1)->getOpcode() == ISD::UNDEF) {
10393     SDValue In = N->getOperand(0);
10394     assert(In.getValueType().isVector() && "Must concat vectors");
10395
10396     // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
10397     if (In->getOpcode() == ISD::BITCAST &&
10398         !In->getOperand(0)->getValueType(0).isVector()) {
10399       SDValue Scalar = In->getOperand(0);
10400       EVT SclTy = Scalar->getValueType(0);
10401
10402       if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
10403         return SDValue();
10404
10405       EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
10406                                  VT.getSizeInBits() / SclTy.getSizeInBits());
10407       if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
10408         return SDValue();
10409
10410       SDLoc dl = SDLoc(N);
10411       SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
10412       return DAG.getNode(ISD::BITCAST, dl, VT, Res);
10413     }
10414   }
10415
10416   // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
10417   // -> (BUILD_VECTOR A, B, ..., C, D, ...)
10418   if (N->getNumOperands() == 2 &&
10419       N->getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
10420       N->getOperand(1).getOpcode() == ISD::BUILD_VECTOR) {
10421     EVT VT = N->getValueType(0);
10422     SDValue N0 = N->getOperand(0);
10423     SDValue N1 = N->getOperand(1);
10424     SmallVector<SDValue, 8> Opnds;
10425     unsigned BuildVecNumElts =  N0.getNumOperands();
10426
10427     EVT SclTy0 = N0.getOperand(0)->getValueType(0);
10428     EVT SclTy1 = N1.getOperand(0)->getValueType(0);
10429     if (SclTy0.isFloatingPoint()) {
10430       for (unsigned i = 0; i != BuildVecNumElts; ++i)
10431         Opnds.push_back(N0.getOperand(i));
10432       for (unsigned i = 0; i != BuildVecNumElts; ++i)
10433         Opnds.push_back(N1.getOperand(i));
10434     } else {
10435       // If BUILD_VECTOR are from built from integer, they may have different
10436       // operand types. Get the smaller type and truncate all operands to it.
10437       EVT MinTy = SclTy0.bitsLE(SclTy1) ? SclTy0 : SclTy1;
10438       for (unsigned i = 0; i != BuildVecNumElts; ++i)
10439         Opnds.push_back(DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinTy,
10440                         N0.getOperand(i)));
10441       for (unsigned i = 0; i != BuildVecNumElts; ++i)
10442         Opnds.push_back(DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinTy,
10443                         N1.getOperand(i)));
10444     }
10445
10446     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
10447   }
10448
10449   // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
10450   // nodes often generate nop CONCAT_VECTOR nodes.
10451   // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
10452   // place the incoming vectors at the exact same location.
10453   SDValue SingleSource = SDValue();
10454   unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
10455
10456   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
10457     SDValue Op = N->getOperand(i);
10458
10459     if (Op.getOpcode() == ISD::UNDEF)
10460       continue;
10461
10462     // Check if this is the identity extract:
10463     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
10464       return SDValue();
10465
10466     // Find the single incoming vector for the extract_subvector.
10467     if (SingleSource.getNode()) {
10468       if (Op.getOperand(0) != SingleSource)
10469         return SDValue();
10470     } else {
10471       SingleSource = Op.getOperand(0);
10472
10473       // Check the source type is the same as the type of the result.
10474       // If not, this concat may extend the vector, so we can not
10475       // optimize it away.
10476       if (SingleSource.getValueType() != N->getValueType(0))
10477         return SDValue();
10478     }
10479
10480     unsigned IdentityIndex = i * PartNumElem;
10481     ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
10482     // The extract index must be constant.
10483     if (!CS)
10484       return SDValue();
10485
10486     // Check that we are reading from the identity index.
10487     if (CS->getZExtValue() != IdentityIndex)
10488       return SDValue();
10489   }
10490
10491   if (SingleSource.getNode())
10492     return SingleSource;
10493
10494   return SDValue();
10495 }
10496
10497 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
10498   EVT NVT = N->getValueType(0);
10499   SDValue V = N->getOperand(0);
10500
10501   if (V->getOpcode() == ISD::CONCAT_VECTORS) {
10502     // Combine:
10503     //    (extract_subvec (concat V1, V2, ...), i)
10504     // Into:
10505     //    Vi if possible
10506     // Only operand 0 is checked as 'concat' assumes all inputs of the same
10507     // type.
10508     if (V->getOperand(0).getValueType() != NVT)
10509       return SDValue();
10510     unsigned Idx = dyn_cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
10511     unsigned NumElems = NVT.getVectorNumElements();
10512     assert((Idx % NumElems) == 0 &&
10513            "IDX in concat is not a multiple of the result vector length.");
10514     return V->getOperand(Idx / NumElems);
10515   }
10516
10517   // Skip bitcasting
10518   if (V->getOpcode() == ISD::BITCAST)
10519     V = V.getOperand(0);
10520
10521   if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
10522     SDLoc dl(N);
10523     // Handle only simple case where vector being inserted and vector
10524     // being extracted are of same type, and are half size of larger vectors.
10525     EVT BigVT = V->getOperand(0).getValueType();
10526     EVT SmallVT = V->getOperand(1).getValueType();
10527     if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
10528       return SDValue();
10529
10530     // Only handle cases where both indexes are constants with the same type.
10531     ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
10532     ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
10533
10534     if (InsIdx && ExtIdx &&
10535         InsIdx->getValueType(0).getSizeInBits() <= 64 &&
10536         ExtIdx->getValueType(0).getSizeInBits() <= 64) {
10537       // Combine:
10538       //    (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
10539       // Into:
10540       //    indices are equal or bit offsets are equal => V1
10541       //    otherwise => (extract_subvec V1, ExtIdx)
10542       if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
10543           ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
10544         return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
10545       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
10546                          DAG.getNode(ISD::BITCAST, dl,
10547                                      N->getOperand(0).getValueType(),
10548                                      V->getOperand(0)), N->getOperand(1));
10549     }
10550   }
10551
10552   return SDValue();
10553 }
10554
10555 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat.
10556 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
10557   EVT VT = N->getValueType(0);
10558   unsigned NumElts = VT.getVectorNumElements();
10559
10560   SDValue N0 = N->getOperand(0);
10561   SDValue N1 = N->getOperand(1);
10562   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10563
10564   SmallVector<SDValue, 4> Ops;
10565   EVT ConcatVT = N0.getOperand(0).getValueType();
10566   unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
10567   unsigned NumConcats = NumElts / NumElemsPerConcat;
10568
10569   // Look at every vector that's inserted. We're looking for exact
10570   // subvector-sized copies from a concatenated vector
10571   for (unsigned I = 0; I != NumConcats; ++I) {
10572     // Make sure we're dealing with a copy.
10573     unsigned Begin = I * NumElemsPerConcat;
10574     bool AllUndef = true, NoUndef = true;
10575     for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
10576       if (SVN->getMaskElt(J) >= 0)
10577         AllUndef = false;
10578       else
10579         NoUndef = false;
10580     }
10581
10582     if (NoUndef) {
10583       if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
10584         return SDValue();
10585
10586       for (unsigned J = 1; J != NumElemsPerConcat; ++J)
10587         if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
10588           return SDValue();
10589
10590       unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
10591       if (FirstElt < N0.getNumOperands())
10592         Ops.push_back(N0.getOperand(FirstElt));
10593       else
10594         Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
10595
10596     } else if (AllUndef) {
10597       Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
10598     } else { // Mixed with general masks and undefs, can't do optimization.
10599       return SDValue();
10600     }
10601   }
10602
10603   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
10604 }
10605
10606 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
10607   EVT VT = N->getValueType(0);
10608   unsigned NumElts = VT.getVectorNumElements();
10609
10610   SDValue N0 = N->getOperand(0);
10611   SDValue N1 = N->getOperand(1);
10612
10613   assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
10614
10615   // Canonicalize shuffle undef, undef -> undef
10616   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
10617     return DAG.getUNDEF(VT);
10618
10619   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10620
10621   // Canonicalize shuffle v, v -> v, undef
10622   if (N0 == N1) {
10623     SmallVector<int, 8> NewMask;
10624     for (unsigned i = 0; i != NumElts; ++i) {
10625       int Idx = SVN->getMaskElt(i);
10626       if (Idx >= (int)NumElts) Idx -= NumElts;
10627       NewMask.push_back(Idx);
10628     }
10629     return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
10630                                 &NewMask[0]);
10631   }
10632
10633   // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
10634   if (N0.getOpcode() == ISD::UNDEF) {
10635     SmallVector<int, 8> NewMask;
10636     for (unsigned i = 0; i != NumElts; ++i) {
10637       int Idx = SVN->getMaskElt(i);
10638       if (Idx >= 0) {
10639         if (Idx >= (int)NumElts)
10640           Idx -= NumElts;
10641         else
10642           Idx = -1; // remove reference to lhs
10643       }
10644       NewMask.push_back(Idx);
10645     }
10646     return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
10647                                 &NewMask[0]);
10648   }
10649
10650   // Remove references to rhs if it is undef
10651   if (N1.getOpcode() == ISD::UNDEF) {
10652     bool Changed = false;
10653     SmallVector<int, 8> NewMask;
10654     for (unsigned i = 0; i != NumElts; ++i) {
10655       int Idx = SVN->getMaskElt(i);
10656       if (Idx >= (int)NumElts) {
10657         Idx = -1;
10658         Changed = true;
10659       }
10660       NewMask.push_back(Idx);
10661     }
10662     if (Changed)
10663       return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
10664   }
10665
10666   // If it is a splat, check if the argument vector is another splat or a
10667   // build_vector with all scalar elements the same.
10668   if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
10669     SDNode *V = N0.getNode();
10670
10671     // If this is a bit convert that changes the element type of the vector but
10672     // not the number of vector elements, look through it.  Be careful not to
10673     // look though conversions that change things like v4f32 to v2f64.
10674     if (V->getOpcode() == ISD::BITCAST) {
10675       SDValue ConvInput = V->getOperand(0);
10676       if (ConvInput.getValueType().isVector() &&
10677           ConvInput.getValueType().getVectorNumElements() == NumElts)
10678         V = ConvInput.getNode();
10679     }
10680
10681     if (V->getOpcode() == ISD::BUILD_VECTOR) {
10682       assert(V->getNumOperands() == NumElts &&
10683              "BUILD_VECTOR has wrong number of operands");
10684       SDValue Base;
10685       bool AllSame = true;
10686       for (unsigned i = 0; i != NumElts; ++i) {
10687         if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
10688           Base = V->getOperand(i);
10689           break;
10690         }
10691       }
10692       // Splat of <u, u, u, u>, return <u, u, u, u>
10693       if (!Base.getNode())
10694         return N0;
10695       for (unsigned i = 0; i != NumElts; ++i) {
10696         if (V->getOperand(i) != Base) {
10697           AllSame = false;
10698           break;
10699         }
10700       }
10701       // Splat of <x, x, x, x>, return <x, x, x, x>
10702       if (AllSame)
10703         return N0;
10704     }
10705   }
10706
10707   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
10708       Level < AfterLegalizeVectorOps &&
10709       (N1.getOpcode() == ISD::UNDEF ||
10710       (N1.getOpcode() == ISD::CONCAT_VECTORS &&
10711        N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
10712     SDValue V = partitionShuffleOfConcats(N, DAG);
10713
10714     if (V.getNode())
10715       return V;
10716   }
10717
10718   // If this shuffle node is simply a swizzle of another shuffle node,
10719   // then try to simplify it.
10720   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
10721       N1.getOpcode() == ISD::UNDEF) {
10722
10723     ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
10724
10725     // The incoming shuffle must be of the same type as the result of the
10726     // current shuffle.
10727     assert(OtherSV->getOperand(0).getValueType() == VT &&
10728            "Shuffle types don't match");
10729
10730     SmallVector<int, 4> Mask;
10731     // Compute the combined shuffle mask.
10732     for (unsigned i = 0; i != NumElts; ++i) {
10733       int Idx = SVN->getMaskElt(i);
10734       assert(Idx < (int)NumElts && "Index references undef operand");
10735       // Next, this index comes from the first value, which is the incoming
10736       // shuffle. Adopt the incoming index.
10737       if (Idx >= 0)
10738         Idx = OtherSV->getMaskElt(Idx);
10739       Mask.push_back(Idx);
10740     }
10741     
10742     bool CommuteOperands = false;
10743     if (N0.getOperand(1).getOpcode() != ISD::UNDEF) {
10744       // To be valid, the combine shuffle mask should only reference elements
10745       // from one of the two vectors in input to the inner shufflevector.
10746       bool IsValidMask = true;
10747       for (unsigned i = 0; i != NumElts && IsValidMask; ++i)
10748         // See if the combined mask only reference undefs or elements coming
10749         // from the first shufflevector operand.
10750         IsValidMask = Mask[i] < 0 || (unsigned)Mask[i] < NumElts;
10751
10752       if (!IsValidMask) {
10753         IsValidMask = true;
10754         for (unsigned i = 0; i != NumElts && IsValidMask; ++i)
10755           // Check that all the elements come from the second shuffle operand.
10756           IsValidMask = Mask[i] < 0 || (unsigned)Mask[i] >= NumElts;
10757         CommuteOperands = IsValidMask;
10758       }
10759
10760       // Early exit if the combined shuffle mask is not valid.
10761       if (!IsValidMask)
10762         return SDValue();
10763     }
10764
10765     // See if this pair of shuffles can be safely folded according to either
10766     // of the following rules:
10767     //   shuffle(shuffle(x, y), undef) -> x
10768     //   shuffle(shuffle(x, undef), undef) -> x
10769     //   shuffle(shuffle(x, y), undef) -> y
10770     bool IsIdentityMask = true;
10771     unsigned BaseMaskIndex = CommuteOperands ? NumElts : 0;
10772     for (unsigned i = 0; i != NumElts && IsIdentityMask; ++i) {
10773       // Skip Undefs.
10774       if (Mask[i] < 0)
10775         continue;
10776
10777       // The combined shuffle must map each index to itself.
10778       IsIdentityMask = (unsigned)Mask[i] == i + BaseMaskIndex;
10779     }
10780     
10781     if (IsIdentityMask) {
10782       if (CommuteOperands)
10783         // optimize shuffle(shuffle(x, y), undef) -> y.
10784         return OtherSV->getOperand(1);
10785       
10786       // optimize shuffle(shuffle(x, undef), undef) -> x
10787       // optimize shuffle(shuffle(x, y), undef) -> x
10788       return OtherSV->getOperand(0);
10789     }
10790
10791     // It may still be beneficial to combine the two shuffles if the
10792     // resulting shuffle is legal.
10793     if (TLI.isTypeLegal(VT) && TLI.isShuffleMaskLegal(Mask, VT)) {
10794       if (!CommuteOperands)
10795         // shuffle(shuffle(x, undef, M1), undef, M2) -> shuffle(x, undef, M3).
10796         // shuffle(shuffle(x, y, M1), undef, M2) -> shuffle(x, undef, M3)
10797         return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0), N1,
10798                                     &Mask[0]);
10799       
10800       //   shuffle(shuffle(x, y, M1), undef, M2) -> shuffle(undef, y, M3)
10801       return DAG.getVectorShuffle(VT, SDLoc(N), N1, N0->getOperand(1),
10802                                   &Mask[0]);
10803     }
10804   }
10805
10806   // Canonicalize shuffles according to rules:
10807   //  shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
10808   //  shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
10809   //  shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
10810   if (N1.getOpcode() == ISD::VECTOR_SHUFFLE && N0.getOpcode() != ISD::UNDEF &&
10811       N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
10812       TLI.isTypeLegal(VT)) {
10813     // The incoming shuffle must be of the same type as the result of the
10814     // current shuffle.
10815     assert(N1->getOperand(0).getValueType() == VT &&
10816            "Shuffle types don't match");
10817
10818     SDValue SV0 = N1->getOperand(0);
10819     SDValue SV1 = N1->getOperand(1);
10820     bool HasSameOp0 = N0 == SV0;
10821     bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
10822     if (HasSameOp0 || IsSV1Undef || N0 == SV1)
10823       // Commute the operands of this shuffle so that next rule
10824       // will trigger.
10825       return DAG.getCommutedVectorShuffle(*SVN);
10826   }
10827
10828   // Try to fold according to rules:
10829   //   shuffle(shuffle(A, B, M0), B, M1) -> shuffle(A, B, M2)
10830   //   shuffle(shuffle(A, B, M0), A, M1) -> shuffle(A, B, M2)
10831   //   shuffle(shuffle(A, Undef, M0), B, M1) -> shuffle(A, B, M2)
10832   //   shuffle(shuffle(A, Undef, M0), A, M1) -> shuffle(A, Undef, M2)
10833   // Don't try to fold shuffles with illegal type.
10834   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
10835       N1.getOpcode() != ISD::UNDEF && TLI.isTypeLegal(VT)) {
10836     ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
10837
10838     // The incoming shuffle must be of the same type as the result of the
10839     // current shuffle.
10840     assert(OtherSV->getOperand(0).getValueType() == VT &&
10841            "Shuffle types don't match");
10842
10843     SDValue SV0 = OtherSV->getOperand(0);
10844     SDValue SV1 = OtherSV->getOperand(1);
10845     bool HasSameOp0 = N1 == SV0;
10846     bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
10847     if (!HasSameOp0 && !IsSV1Undef && N1 != SV1)
10848       // Early exit.
10849       return SDValue();
10850
10851     SmallVector<int, 4> Mask;
10852     // Compute the combined shuffle mask for a shuffle with SV0 as the first
10853     // operand, and SV1 as the second operand.
10854     for (unsigned i = 0; i != NumElts; ++i) {
10855       int Idx = SVN->getMaskElt(i);
10856       if (Idx < 0) {
10857         // Propagate Undef.
10858         Mask.push_back(Idx);
10859         continue;
10860       }
10861
10862       if (Idx < (int)NumElts) {
10863         Idx = OtherSV->getMaskElt(Idx);
10864         if (IsSV1Undef && Idx >= (int) NumElts)
10865           Idx = -1;  // Propagate Undef.
10866       } else
10867         Idx = HasSameOp0 ? Idx - NumElts : Idx;
10868
10869       Mask.push_back(Idx);
10870     }
10871
10872     // Avoid introducing shuffles with illegal mask.
10873     if (TLI.isShuffleMaskLegal(Mask, VT)) {
10874       if (IsSV1Undef)
10875         //   shuffle(shuffle(A, Undef, M0), B, M1) -> shuffle(A, B, M2)
10876         //   shuffle(shuffle(A, Undef, M0), A, M1) -> shuffle(A, Undef, M2)
10877         return DAG.getVectorShuffle(VT, SDLoc(N), SV0, N1, &Mask[0]);
10878       return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, &Mask[0]);
10879     }
10880   }
10881
10882   return SDValue();
10883 }
10884
10885 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
10886   SDValue N0 = N->getOperand(0);
10887   SDValue N2 = N->getOperand(2);
10888
10889   // If the input vector is a concatenation, and the insert replaces
10890   // one of the halves, we can optimize into a single concat_vectors.
10891   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
10892       N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
10893     APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
10894     EVT VT = N->getValueType(0);
10895
10896     // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
10897     // (concat_vectors Z, Y)
10898     if (InsIdx == 0)
10899       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
10900                          N->getOperand(1), N0.getOperand(1));
10901
10902     // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
10903     // (concat_vectors X, Z)
10904     if (InsIdx == VT.getVectorNumElements()/2)
10905       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
10906                          N0.getOperand(0), N->getOperand(1));
10907   }
10908
10909   return SDValue();
10910 }
10911
10912 /// XformToShuffleWithZero - Returns a vector_shuffle if it able to transform
10913 /// an AND to a vector_shuffle with the destination vector and a zero vector.
10914 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
10915 ///      vector_shuffle V, Zero, <0, 4, 2, 4>
10916 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
10917   EVT VT = N->getValueType(0);
10918   SDLoc dl(N);
10919   SDValue LHS = N->getOperand(0);
10920   SDValue RHS = N->getOperand(1);
10921   if (N->getOpcode() == ISD::AND) {
10922     if (RHS.getOpcode() == ISD::BITCAST)
10923       RHS = RHS.getOperand(0);
10924     if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
10925       SmallVector<int, 8> Indices;
10926       unsigned NumElts = RHS.getNumOperands();
10927       for (unsigned i = 0; i != NumElts; ++i) {
10928         SDValue Elt = RHS.getOperand(i);
10929         if (!isa<ConstantSDNode>(Elt))
10930           return SDValue();
10931
10932         if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
10933           Indices.push_back(i);
10934         else if (cast<ConstantSDNode>(Elt)->isNullValue())
10935           Indices.push_back(NumElts);
10936         else
10937           return SDValue();
10938       }
10939
10940       // Let's see if the target supports this vector_shuffle.
10941       EVT RVT = RHS.getValueType();
10942       if (!TLI.isVectorClearMaskLegal(Indices, RVT))
10943         return SDValue();
10944
10945       // Return the new VECTOR_SHUFFLE node.
10946       EVT EltVT = RVT.getVectorElementType();
10947       SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
10948                                      DAG.getConstant(0, EltVT));
10949       SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), RVT, ZeroOps);
10950       LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
10951       SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
10952       return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
10953     }
10954   }
10955
10956   return SDValue();
10957 }
10958
10959 /// SimplifyVBinOp - Visit a binary vector operation, like ADD.
10960 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
10961   assert(N->getValueType(0).isVector() &&
10962          "SimplifyVBinOp only works on vectors!");
10963
10964   SDValue LHS = N->getOperand(0);
10965   SDValue RHS = N->getOperand(1);
10966   SDValue Shuffle = XformToShuffleWithZero(N);
10967   if (Shuffle.getNode()) return Shuffle;
10968
10969   // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
10970   // this operation.
10971   if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
10972       RHS.getOpcode() == ISD::BUILD_VECTOR) {
10973     // Check if both vectors are constants. If not bail out.
10974     if (!(cast<BuildVectorSDNode>(LHS)->isConstant() &&
10975           cast<BuildVectorSDNode>(RHS)->isConstant()))
10976       return SDValue();
10977
10978     SmallVector<SDValue, 8> Ops;
10979     for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
10980       SDValue LHSOp = LHS.getOperand(i);
10981       SDValue RHSOp = RHS.getOperand(i);
10982
10983       // Can't fold divide by zero.
10984       if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
10985           N->getOpcode() == ISD::FDIV) {
10986         if ((RHSOp.getOpcode() == ISD::Constant &&
10987              cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
10988             (RHSOp.getOpcode() == ISD::ConstantFP &&
10989              cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
10990           break;
10991       }
10992
10993       EVT VT = LHSOp.getValueType();
10994       EVT RVT = RHSOp.getValueType();
10995       if (RVT != VT) {
10996         // Integer BUILD_VECTOR operands may have types larger than the element
10997         // size (e.g., when the element type is not legal).  Prior to type
10998         // legalization, the types may not match between the two BUILD_VECTORS.
10999         // Truncate one of the operands to make them match.
11000         if (RVT.getSizeInBits() > VT.getSizeInBits()) {
11001           RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
11002         } else {
11003           LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
11004           VT = RVT;
11005         }
11006       }
11007       SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
11008                                    LHSOp, RHSOp);
11009       if (FoldOp.getOpcode() != ISD::UNDEF &&
11010           FoldOp.getOpcode() != ISD::Constant &&
11011           FoldOp.getOpcode() != ISD::ConstantFP)
11012         break;
11013       Ops.push_back(FoldOp);
11014       AddToWorklist(FoldOp.getNode());
11015     }
11016
11017     if (Ops.size() == LHS.getNumOperands())
11018       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), LHS.getValueType(), Ops);
11019   }
11020
11021   // Type legalization might introduce new shuffles in the DAG.
11022   // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
11023   //   -> (shuffle (VBinOp (A, B)), Undef, Mask).
11024   if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
11025       isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
11026       LHS.getOperand(1).getOpcode() == ISD::UNDEF &&
11027       RHS.getOperand(1).getOpcode() == ISD::UNDEF) {
11028     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
11029     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
11030
11031     if (SVN0->getMask().equals(SVN1->getMask())) {
11032       EVT VT = N->getValueType(0);
11033       SDValue UndefVector = LHS.getOperand(1);
11034       SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
11035                                      LHS.getOperand(0), RHS.getOperand(0));
11036       AddUsersToWorklist(N);
11037       return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
11038                                   &SVN0->getMask()[0]);
11039     }
11040   }
11041
11042   return SDValue();
11043 }
11044
11045 /// SimplifyVUnaryOp - Visit a binary vector operation, like FABS/FNEG.
11046 SDValue DAGCombiner::SimplifyVUnaryOp(SDNode *N) {
11047   assert(N->getValueType(0).isVector() &&
11048          "SimplifyVUnaryOp only works on vectors!");
11049
11050   SDValue N0 = N->getOperand(0);
11051
11052   if (N0.getOpcode() != ISD::BUILD_VECTOR)
11053     return SDValue();
11054
11055   // Operand is a BUILD_VECTOR node, see if we can constant fold it.
11056   SmallVector<SDValue, 8> Ops;
11057   for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
11058     SDValue Op = N0.getOperand(i);
11059     if (Op.getOpcode() != ISD::UNDEF &&
11060         Op.getOpcode() != ISD::ConstantFP)
11061       break;
11062     EVT EltVT = Op.getValueType();
11063     SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(N0), EltVT, Op);
11064     if (FoldOp.getOpcode() != ISD::UNDEF &&
11065         FoldOp.getOpcode() != ISD::ConstantFP)
11066       break;
11067     Ops.push_back(FoldOp);
11068     AddToWorklist(FoldOp.getNode());
11069   }
11070
11071   if (Ops.size() != N0.getNumOperands())
11072     return SDValue();
11073
11074   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), N0.getValueType(), Ops);
11075 }
11076
11077 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
11078                                     SDValue N1, SDValue N2){
11079   assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
11080
11081   SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
11082                                  cast<CondCodeSDNode>(N0.getOperand(2))->get());
11083
11084   // If we got a simplified select_cc node back from SimplifySelectCC, then
11085   // break it down into a new SETCC node, and a new SELECT node, and then return
11086   // the SELECT node, since we were called with a SELECT node.
11087   if (SCC.getNode()) {
11088     // Check to see if we got a select_cc back (to turn into setcc/select).
11089     // Otherwise, just return whatever node we got back, like fabs.
11090     if (SCC.getOpcode() == ISD::SELECT_CC) {
11091       SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
11092                                   N0.getValueType(),
11093                                   SCC.getOperand(0), SCC.getOperand(1),
11094                                   SCC.getOperand(4));
11095       AddToWorklist(SETCC.getNode());
11096       return DAG.getSelect(SDLoc(SCC), SCC.getValueType(),
11097                            SCC.getOperand(2), SCC.getOperand(3), SETCC);
11098     }
11099
11100     return SCC;
11101   }
11102   return SDValue();
11103 }
11104
11105 /// SimplifySelectOps - Given a SELECT or a SELECT_CC node, where LHS and RHS
11106 /// are the two values being selected between, see if we can simplify the
11107 /// select.  Callers of this should assume that TheSelect is deleted if this
11108 /// returns true.  As such, they should return the appropriate thing (e.g. the
11109 /// node) back to the top-level of the DAG combiner loop to avoid it being
11110 /// looked at.
11111 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
11112                                     SDValue RHS) {
11113
11114   // Cannot simplify select with vector condition
11115   if (TheSelect->getOperand(0).getValueType().isVector()) return false;
11116
11117   // If this is a select from two identical things, try to pull the operation
11118   // through the select.
11119   if (LHS.getOpcode() != RHS.getOpcode() ||
11120       !LHS.hasOneUse() || !RHS.hasOneUse())
11121     return false;
11122
11123   // If this is a load and the token chain is identical, replace the select
11124   // of two loads with a load through a select of the address to load from.
11125   // This triggers in things like "select bool X, 10.0, 123.0" after the FP
11126   // constants have been dropped into the constant pool.
11127   if (LHS.getOpcode() == ISD::LOAD) {
11128     LoadSDNode *LLD = cast<LoadSDNode>(LHS);
11129     LoadSDNode *RLD = cast<LoadSDNode>(RHS);
11130
11131     // Token chains must be identical.
11132     if (LHS.getOperand(0) != RHS.getOperand(0) ||
11133         // Do not let this transformation reduce the number of volatile loads.
11134         LLD->isVolatile() || RLD->isVolatile() ||
11135         // If this is an EXTLOAD, the VT's must match.
11136         LLD->getMemoryVT() != RLD->getMemoryVT() ||
11137         // If this is an EXTLOAD, the kind of extension must match.
11138         (LLD->getExtensionType() != RLD->getExtensionType() &&
11139          // The only exception is if one of the extensions is anyext.
11140          LLD->getExtensionType() != ISD::EXTLOAD &&
11141          RLD->getExtensionType() != ISD::EXTLOAD) ||
11142         // FIXME: this discards src value information.  This is
11143         // over-conservative. It would be beneficial to be able to remember
11144         // both potential memory locations.  Since we are discarding
11145         // src value info, don't do the transformation if the memory
11146         // locations are not in the default address space.
11147         LLD->getPointerInfo().getAddrSpace() != 0 ||
11148         RLD->getPointerInfo().getAddrSpace() != 0 ||
11149         !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
11150                                       LLD->getBasePtr().getValueType()))
11151       return false;
11152
11153     // Check that the select condition doesn't reach either load.  If so,
11154     // folding this will induce a cycle into the DAG.  If not, this is safe to
11155     // xform, so create a select of the addresses.
11156     SDValue Addr;
11157     if (TheSelect->getOpcode() == ISD::SELECT) {
11158       SDNode *CondNode = TheSelect->getOperand(0).getNode();
11159       if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
11160           (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
11161         return false;
11162       // The loads must not depend on one another.
11163       if (LLD->isPredecessorOf(RLD) ||
11164           RLD->isPredecessorOf(LLD))
11165         return false;
11166       Addr = DAG.getSelect(SDLoc(TheSelect),
11167                            LLD->getBasePtr().getValueType(),
11168                            TheSelect->getOperand(0), LLD->getBasePtr(),
11169                            RLD->getBasePtr());
11170     } else {  // Otherwise SELECT_CC
11171       SDNode *CondLHS = TheSelect->getOperand(0).getNode();
11172       SDNode *CondRHS = TheSelect->getOperand(1).getNode();
11173
11174       if ((LLD->hasAnyUseOfValue(1) &&
11175            (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
11176           (RLD->hasAnyUseOfValue(1) &&
11177            (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
11178         return false;
11179
11180       Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
11181                          LLD->getBasePtr().getValueType(),
11182                          TheSelect->getOperand(0),
11183                          TheSelect->getOperand(1),
11184                          LLD->getBasePtr(), RLD->getBasePtr(),
11185                          TheSelect->getOperand(4));
11186     }
11187
11188     SDValue Load;
11189     // It is safe to replace the two loads if they have different alignments,
11190     // but the new load must be the minimum (most restrictive) alignment of the
11191     // inputs.
11192     bool isInvariant = LLD->getAlignment() & RLD->getAlignment();
11193     unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment());
11194     if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
11195       Load = DAG.getLoad(TheSelect->getValueType(0),
11196                          SDLoc(TheSelect),
11197                          // FIXME: Discards pointer and AA info.
11198                          LLD->getChain(), Addr, MachinePointerInfo(),
11199                          LLD->isVolatile(), LLD->isNonTemporal(),
11200                          isInvariant, Alignment);
11201     } else {
11202       Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
11203                             RLD->getExtensionType() : LLD->getExtensionType(),
11204                             SDLoc(TheSelect),
11205                             TheSelect->getValueType(0),
11206                             // FIXME: Discards pointer and AA info.
11207                             LLD->getChain(), Addr, MachinePointerInfo(),
11208                             LLD->getMemoryVT(), LLD->isVolatile(),
11209                             LLD->isNonTemporal(), isInvariant, Alignment);
11210     }
11211
11212     // Users of the select now use the result of the load.
11213     CombineTo(TheSelect, Load);
11214
11215     // Users of the old loads now use the new load's chain.  We know the
11216     // old-load value is dead now.
11217     CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
11218     CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
11219     return true;
11220   }
11221
11222   return false;
11223 }
11224
11225 /// SimplifySelectCC - Simplify an expression of the form (N0 cond N1) ? N2 : N3
11226 /// where 'cond' is the comparison specified by CC.
11227 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
11228                                       SDValue N2, SDValue N3,
11229                                       ISD::CondCode CC, bool NotExtCompare) {
11230   // (x ? y : y) -> y.
11231   if (N2 == N3) return N2;
11232
11233   EVT VT = N2.getValueType();
11234   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
11235   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
11236   ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
11237
11238   // Determine if the condition we're dealing with is constant
11239   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
11240                               N0, N1, CC, DL, false);
11241   if (SCC.getNode()) AddToWorklist(SCC.getNode());
11242   ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
11243
11244   // fold select_cc true, x, y -> x
11245   if (SCCC && !SCCC->isNullValue())
11246     return N2;
11247   // fold select_cc false, x, y -> y
11248   if (SCCC && SCCC->isNullValue())
11249     return N3;
11250
11251   // Check to see if we can simplify the select into an fabs node
11252   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
11253     // Allow either -0.0 or 0.0
11254     if (CFP->getValueAPF().isZero()) {
11255       // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
11256       if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
11257           N0 == N2 && N3.getOpcode() == ISD::FNEG &&
11258           N2 == N3.getOperand(0))
11259         return DAG.getNode(ISD::FABS, DL, VT, N0);
11260
11261       // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
11262       if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
11263           N0 == N3 && N2.getOpcode() == ISD::FNEG &&
11264           N2.getOperand(0) == N3)
11265         return DAG.getNode(ISD::FABS, DL, VT, N3);
11266     }
11267   }
11268
11269   // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
11270   // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
11271   // in it.  This is a win when the constant is not otherwise available because
11272   // it replaces two constant pool loads with one.  We only do this if the FP
11273   // type is known to be legal, because if it isn't, then we are before legalize
11274   // types an we want the other legalization to happen first (e.g. to avoid
11275   // messing with soft float) and if the ConstantFP is not legal, because if
11276   // it is legal, we may not need to store the FP constant in a constant pool.
11277   if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
11278     if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
11279       if (TLI.isTypeLegal(N2.getValueType()) &&
11280           (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
11281                TargetLowering::Legal &&
11282            !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
11283            !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
11284           // If both constants have multiple uses, then we won't need to do an
11285           // extra load, they are likely around in registers for other users.
11286           (TV->hasOneUse() || FV->hasOneUse())) {
11287         Constant *Elts[] = {
11288           const_cast<ConstantFP*>(FV->getConstantFPValue()),
11289           const_cast<ConstantFP*>(TV->getConstantFPValue())
11290         };
11291         Type *FPTy = Elts[0]->getType();
11292         const DataLayout &TD = *TLI.getDataLayout();
11293
11294         // Create a ConstantArray of the two constants.
11295         Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
11296         SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
11297                                             TD.getPrefTypeAlignment(FPTy));
11298         unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
11299
11300         // Get the offsets to the 0 and 1 element of the array so that we can
11301         // select between them.
11302         SDValue Zero = DAG.getIntPtrConstant(0);
11303         unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
11304         SDValue One = DAG.getIntPtrConstant(EltSize);
11305
11306         SDValue Cond = DAG.getSetCC(DL,
11307                                     getSetCCResultType(N0.getValueType()),
11308                                     N0, N1, CC);
11309         AddToWorklist(Cond.getNode());
11310         SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
11311                                           Cond, One, Zero);
11312         AddToWorklist(CstOffset.getNode());
11313         CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
11314                             CstOffset);
11315         AddToWorklist(CPIdx.getNode());
11316         return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
11317                            MachinePointerInfo::getConstantPool(), false,
11318                            false, false, Alignment);
11319
11320       }
11321     }
11322
11323   // Check to see if we can perform the "gzip trick", transforming
11324   // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
11325   if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
11326       (N1C->isNullValue() ||                         // (a < 0) ? b : 0
11327        (N1C->getAPIntValue() == 1 && N0 == N2))) {   // (a < 1) ? a : 0
11328     EVT XType = N0.getValueType();
11329     EVT AType = N2.getValueType();
11330     if (XType.bitsGE(AType)) {
11331       // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
11332       // single-bit constant.
11333       if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
11334         unsigned ShCtV = N2C->getAPIntValue().logBase2();
11335         ShCtV = XType.getSizeInBits()-ShCtV-1;
11336         SDValue ShCt = DAG.getConstant(ShCtV,
11337                                        getShiftAmountTy(N0.getValueType()));
11338         SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
11339                                     XType, N0, ShCt);
11340         AddToWorklist(Shift.getNode());
11341
11342         if (XType.bitsGT(AType)) {
11343           Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
11344           AddToWorklist(Shift.getNode());
11345         }
11346
11347         return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
11348       }
11349
11350       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
11351                                   XType, N0,
11352                                   DAG.getConstant(XType.getSizeInBits()-1,
11353                                          getShiftAmountTy(N0.getValueType())));
11354       AddToWorklist(Shift.getNode());
11355
11356       if (XType.bitsGT(AType)) {
11357         Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
11358         AddToWorklist(Shift.getNode());
11359       }
11360
11361       return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
11362     }
11363   }
11364
11365   // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
11366   // where y is has a single bit set.
11367   // A plaintext description would be, we can turn the SELECT_CC into an AND
11368   // when the condition can be materialized as an all-ones register.  Any
11369   // single bit-test can be materialized as an all-ones register with
11370   // shift-left and shift-right-arith.
11371   if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
11372       N0->getValueType(0) == VT &&
11373       N1C && N1C->isNullValue() &&
11374       N2C && N2C->isNullValue()) {
11375     SDValue AndLHS = N0->getOperand(0);
11376     ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
11377     if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
11378       // Shift the tested bit over the sign bit.
11379       APInt AndMask = ConstAndRHS->getAPIntValue();
11380       SDValue ShlAmt =
11381         DAG.getConstant(AndMask.countLeadingZeros(),
11382                         getShiftAmountTy(AndLHS.getValueType()));
11383       SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
11384
11385       // Now arithmetic right shift it all the way over, so the result is either
11386       // all-ones, or zero.
11387       SDValue ShrAmt =
11388         DAG.getConstant(AndMask.getBitWidth()-1,
11389                         getShiftAmountTy(Shl.getValueType()));
11390       SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
11391
11392       return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
11393     }
11394   }
11395
11396   // fold select C, 16, 0 -> shl C, 4
11397   if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
11398       TLI.getBooleanContents(N0.getValueType()) ==
11399           TargetLowering::ZeroOrOneBooleanContent) {
11400
11401     // If the caller doesn't want us to simplify this into a zext of a compare,
11402     // don't do it.
11403     if (NotExtCompare && N2C->getAPIntValue() == 1)
11404       return SDValue();
11405
11406     // Get a SetCC of the condition
11407     // NOTE: Don't create a SETCC if it's not legal on this target.
11408     if (!LegalOperations ||
11409         TLI.isOperationLegal(ISD::SETCC,
11410           LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
11411       SDValue Temp, SCC;
11412       // cast from setcc result type to select result type
11413       if (LegalTypes) {
11414         SCC  = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
11415                             N0, N1, CC);
11416         if (N2.getValueType().bitsLT(SCC.getValueType()))
11417           Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
11418                                         N2.getValueType());
11419         else
11420           Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
11421                              N2.getValueType(), SCC);
11422       } else {
11423         SCC  = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
11424         Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
11425                            N2.getValueType(), SCC);
11426       }
11427
11428       AddToWorklist(SCC.getNode());
11429       AddToWorklist(Temp.getNode());
11430
11431       if (N2C->getAPIntValue() == 1)
11432         return Temp;
11433
11434       // shl setcc result by log2 n2c
11435       return DAG.getNode(
11436           ISD::SHL, DL, N2.getValueType(), Temp,
11437           DAG.getConstant(N2C->getAPIntValue().logBase2(),
11438                           getShiftAmountTy(Temp.getValueType())));
11439     }
11440   }
11441
11442   // Check to see if this is the equivalent of setcc
11443   // FIXME: Turn all of these into setcc if setcc if setcc is legal
11444   // otherwise, go ahead with the folds.
11445   if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
11446     EVT XType = N0.getValueType();
11447     if (!LegalOperations ||
11448         TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
11449       SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
11450       if (Res.getValueType() != VT)
11451         Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
11452       return Res;
11453     }
11454
11455     // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
11456     if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
11457         (!LegalOperations ||
11458          TLI.isOperationLegal(ISD::CTLZ, XType))) {
11459       SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
11460       return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
11461                          DAG.getConstant(Log2_32(XType.getSizeInBits()),
11462                                        getShiftAmountTy(Ctlz.getValueType())));
11463     }
11464     // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
11465     if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
11466       SDValue NegN0 = DAG.getNode(ISD::SUB, SDLoc(N0),
11467                                   XType, DAG.getConstant(0, XType), N0);
11468       SDValue NotN0 = DAG.getNOT(SDLoc(N0), N0, XType);
11469       return DAG.getNode(ISD::SRL, DL, XType,
11470                          DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
11471                          DAG.getConstant(XType.getSizeInBits()-1,
11472                                          getShiftAmountTy(XType)));
11473     }
11474     // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
11475     if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
11476       SDValue Sign = DAG.getNode(ISD::SRL, SDLoc(N0), XType, N0,
11477                                  DAG.getConstant(XType.getSizeInBits()-1,
11478                                          getShiftAmountTy(N0.getValueType())));
11479       return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
11480     }
11481   }
11482
11483   // Check to see if this is an integer abs.
11484   // select_cc setg[te] X,  0,  X, -X ->
11485   // select_cc setgt    X, -1,  X, -X ->
11486   // select_cc setl[te] X,  0, -X,  X ->
11487   // select_cc setlt    X,  1, -X,  X ->
11488   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
11489   if (N1C) {
11490     ConstantSDNode *SubC = nullptr;
11491     if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
11492          (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
11493         N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
11494       SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
11495     else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
11496               (N1C->isOne() && CC == ISD::SETLT)) &&
11497              N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
11498       SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
11499
11500     EVT XType = N0.getValueType();
11501     if (SubC && SubC->isNullValue() && XType.isInteger()) {
11502       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), XType,
11503                                   N0,
11504                                   DAG.getConstant(XType.getSizeInBits()-1,
11505                                          getShiftAmountTy(N0.getValueType())));
11506       SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0),
11507                                 XType, N0, Shift);
11508       AddToWorklist(Shift.getNode());
11509       AddToWorklist(Add.getNode());
11510       return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
11511     }
11512   }
11513
11514   return SDValue();
11515 }
11516
11517 /// SimplifySetCC - This is a stub for TargetLowering::SimplifySetCC.
11518 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
11519                                    SDValue N1, ISD::CondCode Cond,
11520                                    SDLoc DL, bool foldBooleans) {
11521   TargetLowering::DAGCombinerInfo
11522     DagCombineInfo(DAG, Level, false, this);
11523   return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
11524 }
11525
11526 /// BuildSDIV - Given an ISD::SDIV node expressing a divide by constant, return
11527 /// a DAG expression to select that will generate the same value by multiplying
11528 /// by a magic number.  See:
11529 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
11530 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
11531   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
11532   if (!C)
11533     return SDValue();
11534
11535   // Avoid division by zero.
11536   if (!C->getAPIntValue())
11537     return SDValue();
11538
11539   std::vector<SDNode*> Built;
11540   SDValue S =
11541       TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
11542
11543   for (SDNode *N : Built)
11544     AddToWorklist(N);
11545   return S;
11546 }
11547
11548 /// BuildSDIVPow2 - Given an ISD::SDIV node expressing a divide by constant
11549 /// power of 2, return a DAG expression to select that will generate the same
11550 /// value by right shifting.
11551 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
11552   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
11553   if (!C)
11554     return SDValue();
11555
11556   // Avoid division by zero.
11557   if (!C->getAPIntValue())
11558     return SDValue();
11559
11560   std::vector<SDNode *> Built;
11561   SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
11562
11563   for (SDNode *N : Built)
11564     AddToWorklist(N);
11565   return S;
11566 }
11567
11568 /// BuildUDIV - Given an ISD::UDIV node expressing a divide by constant,
11569 /// return a DAG expression to select that will generate the same value by
11570 /// multiplying by a magic number.  See:
11571 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
11572 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
11573   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
11574   if (!C)
11575     return SDValue();
11576
11577   // Avoid division by zero.
11578   if (!C->getAPIntValue())
11579     return SDValue();
11580
11581   std::vector<SDNode*> Built;
11582   SDValue S =
11583       TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
11584
11585   for (SDNode *N : Built)
11586     AddToWorklist(N);
11587   return S;
11588 }
11589
11590 /// FindBaseOffset - Return true if base is a frame index, which is known not
11591 // to alias with anything but itself.  Provides base object and offset as
11592 // results.
11593 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
11594                            const GlobalValue *&GV, const void *&CV) {
11595   // Assume it is a primitive operation.
11596   Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
11597
11598   // If it's an adding a simple constant then integrate the offset.
11599   if (Base.getOpcode() == ISD::ADD) {
11600     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
11601       Base = Base.getOperand(0);
11602       Offset += C->getZExtValue();
11603     }
11604   }
11605
11606   // Return the underlying GlobalValue, and update the Offset.  Return false
11607   // for GlobalAddressSDNode since the same GlobalAddress may be represented
11608   // by multiple nodes with different offsets.
11609   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
11610     GV = G->getGlobal();
11611     Offset += G->getOffset();
11612     return false;
11613   }
11614
11615   // Return the underlying Constant value, and update the Offset.  Return false
11616   // for ConstantSDNodes since the same constant pool entry may be represented
11617   // by multiple nodes with different offsets.
11618   if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
11619     CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
11620                                          : (const void *)C->getConstVal();
11621     Offset += C->getOffset();
11622     return false;
11623   }
11624   // If it's any of the following then it can't alias with anything but itself.
11625   return isa<FrameIndexSDNode>(Base);
11626 }
11627
11628 /// isAlias - Return true if there is any possibility that the two addresses
11629 /// overlap.
11630 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
11631   // If they are the same then they must be aliases.
11632   if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
11633
11634   // If they are both volatile then they cannot be reordered.
11635   if (Op0->isVolatile() && Op1->isVolatile()) return true;
11636
11637   // Gather base node and offset information.
11638   SDValue Base1, Base2;
11639   int64_t Offset1, Offset2;
11640   const GlobalValue *GV1, *GV2;
11641   const void *CV1, *CV2;
11642   bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
11643                                       Base1, Offset1, GV1, CV1);
11644   bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
11645                                       Base2, Offset2, GV2, CV2);
11646
11647   // If they have a same base address then check to see if they overlap.
11648   if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
11649     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
11650              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
11651
11652   // It is possible for different frame indices to alias each other, mostly
11653   // when tail call optimization reuses return address slots for arguments.
11654   // To catch this case, look up the actual index of frame indices to compute
11655   // the real alias relationship.
11656   if (isFrameIndex1 && isFrameIndex2) {
11657     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11658     Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
11659     Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
11660     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
11661              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
11662   }
11663
11664   // Otherwise, if we know what the bases are, and they aren't identical, then
11665   // we know they cannot alias.
11666   if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
11667     return false;
11668
11669   // If we know required SrcValue1 and SrcValue2 have relatively large alignment
11670   // compared to the size and offset of the access, we may be able to prove they
11671   // do not alias.  This check is conservative for now to catch cases created by
11672   // splitting vector types.
11673   if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
11674       (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
11675       (Op0->getMemoryVT().getSizeInBits() >> 3 ==
11676        Op1->getMemoryVT().getSizeInBits() >> 3) &&
11677       (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) {
11678     int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
11679     int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
11680
11681     // There is no overlap between these relatively aligned accesses of similar
11682     // size, return no alias.
11683     if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
11684         (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
11685       return false;
11686   }
11687
11688   bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0 ? CombinerGlobalAA :
11689     TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
11690 #ifndef NDEBUG
11691   if (CombinerAAOnlyFunc.getNumOccurrences() &&
11692       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
11693     UseAA = false;
11694 #endif
11695   if (UseAA &&
11696       Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
11697     // Use alias analysis information.
11698     int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
11699                                  Op1->getSrcValueOffset());
11700     int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
11701         Op0->getSrcValueOffset() - MinOffset;
11702     int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
11703         Op1->getSrcValueOffset() - MinOffset;
11704     AliasAnalysis::AliasResult AAResult =
11705         AA.alias(AliasAnalysis::Location(Op0->getMemOperand()->getValue(),
11706                                          Overlap1,
11707                                          UseTBAA ? Op0->getAAInfo() : AAMDNodes()),
11708                  AliasAnalysis::Location(Op1->getMemOperand()->getValue(),
11709                                          Overlap2,
11710                                          UseTBAA ? Op1->getAAInfo() : AAMDNodes()));
11711     if (AAResult == AliasAnalysis::NoAlias)
11712       return false;
11713   }
11714
11715   // Otherwise we have to assume they alias.
11716   return true;
11717 }
11718
11719 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
11720 /// looking for aliasing nodes and adding them to the Aliases vector.
11721 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
11722                                    SmallVectorImpl<SDValue> &Aliases) {
11723   SmallVector<SDValue, 8> Chains;     // List of chains to visit.
11724   SmallPtrSet<SDNode *, 16> Visited;  // Visited node set.
11725
11726   // Get alias information for node.
11727   bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
11728
11729   // Starting off.
11730   Chains.push_back(OriginalChain);
11731   unsigned Depth = 0;
11732
11733   // Look at each chain and determine if it is an alias.  If so, add it to the
11734   // aliases list.  If not, then continue up the chain looking for the next
11735   // candidate.
11736   while (!Chains.empty()) {
11737     SDValue Chain = Chains.back();
11738     Chains.pop_back();
11739
11740     // For TokenFactor nodes, look at each operand and only continue up the
11741     // chain until we find two aliases.  If we've seen two aliases, assume we'll
11742     // find more and revert to original chain since the xform is unlikely to be
11743     // profitable.
11744     //
11745     // FIXME: The depth check could be made to return the last non-aliasing
11746     // chain we found before we hit a tokenfactor rather than the original
11747     // chain.
11748     if (Depth > 6 || Aliases.size() == 2) {
11749       Aliases.clear();
11750       Aliases.push_back(OriginalChain);
11751       return;
11752     }
11753
11754     // Don't bother if we've been before.
11755     if (!Visited.insert(Chain.getNode()))
11756       continue;
11757
11758     switch (Chain.getOpcode()) {
11759     case ISD::EntryToken:
11760       // Entry token is ideal chain operand, but handled in FindBetterChain.
11761       break;
11762
11763     case ISD::LOAD:
11764     case ISD::STORE: {
11765       // Get alias information for Chain.
11766       bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
11767           !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
11768
11769       // If chain is alias then stop here.
11770       if (!(IsLoad && IsOpLoad) &&
11771           isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
11772         Aliases.push_back(Chain);
11773       } else {
11774         // Look further up the chain.
11775         Chains.push_back(Chain.getOperand(0));
11776         ++Depth;
11777       }
11778       break;
11779     }
11780
11781     case ISD::TokenFactor:
11782       // We have to check each of the operands of the token factor for "small"
11783       // token factors, so we queue them up.  Adding the operands to the queue
11784       // (stack) in reverse order maintains the original order and increases the
11785       // likelihood that getNode will find a matching token factor (CSE.)
11786       if (Chain.getNumOperands() > 16) {
11787         Aliases.push_back(Chain);
11788         break;
11789       }
11790       for (unsigned n = Chain.getNumOperands(); n;)
11791         Chains.push_back(Chain.getOperand(--n));
11792       ++Depth;
11793       break;
11794
11795     default:
11796       // For all other instructions we will just have to take what we can get.
11797       Aliases.push_back(Chain);
11798       break;
11799     }
11800   }
11801
11802   // We need to be careful here to also search for aliases through the
11803   // value operand of a store, etc. Consider the following situation:
11804   //   Token1 = ...
11805   //   L1 = load Token1, %52
11806   //   S1 = store Token1, L1, %51
11807   //   L2 = load Token1, %52+8
11808   //   S2 = store Token1, L2, %51+8
11809   //   Token2 = Token(S1, S2)
11810   //   L3 = load Token2, %53
11811   //   S3 = store Token2, L3, %52
11812   //   L4 = load Token2, %53+8
11813   //   S4 = store Token2, L4, %52+8
11814   // If we search for aliases of S3 (which loads address %52), and we look
11815   // only through the chain, then we'll miss the trivial dependence on L1
11816   // (which also loads from %52). We then might change all loads and
11817   // stores to use Token1 as their chain operand, which could result in
11818   // copying %53 into %52 before copying %52 into %51 (which should
11819   // happen first).
11820   //
11821   // The problem is, however, that searching for such data dependencies
11822   // can become expensive, and the cost is not directly related to the
11823   // chain depth. Instead, we'll rule out such configurations here by
11824   // insisting that we've visited all chain users (except for users
11825   // of the original chain, which is not necessary). When doing this,
11826   // we need to look through nodes we don't care about (otherwise, things
11827   // like register copies will interfere with trivial cases).
11828
11829   SmallVector<const SDNode *, 16> Worklist;
11830   for (SmallPtrSet<SDNode *, 16>::iterator I = Visited.begin(),
11831        IE = Visited.end(); I != IE; ++I)
11832     if (*I != OriginalChain.getNode())
11833       Worklist.push_back(*I);
11834
11835   while (!Worklist.empty()) {
11836     const SDNode *M = Worklist.pop_back_val();
11837
11838     // We have already visited M, and want to make sure we've visited any uses
11839     // of M that we care about. For uses that we've not visisted, and don't
11840     // care about, queue them to the worklist.
11841
11842     for (SDNode::use_iterator UI = M->use_begin(),
11843          UIE = M->use_end(); UI != UIE; ++UI)
11844       if (UI.getUse().getValueType() == MVT::Other && Visited.insert(*UI)) {
11845         if (isa<MemIntrinsicSDNode>(*UI) || isa<MemSDNode>(*UI)) {
11846           // We've not visited this use, and we care about it (it could have an
11847           // ordering dependency with the original node).
11848           Aliases.clear();
11849           Aliases.push_back(OriginalChain);
11850           return;
11851         }
11852
11853         // We've not visited this use, but we don't care about it. Mark it as
11854         // visited and enqueue it to the worklist.
11855         Worklist.push_back(*UI);
11856       }
11857   }
11858 }
11859
11860 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes, looking
11861 /// for a better chain (aliasing node.)
11862 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
11863   SmallVector<SDValue, 8> Aliases;  // Ops for replacing token factor.
11864
11865   // Accumulate all the aliases to this node.
11866   GatherAllAliases(N, OldChain, Aliases);
11867
11868   // If no operands then chain to entry token.
11869   if (Aliases.size() == 0)
11870     return DAG.getEntryNode();
11871
11872   // If a single operand then chain to it.  We don't need to revisit it.
11873   if (Aliases.size() == 1)
11874     return Aliases[0];
11875
11876   // Construct a custom tailored token factor.
11877   return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
11878 }
11879
11880 // SelectionDAG::Combine - This is the entry point for the file.
11881 //
11882 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
11883                            CodeGenOpt::Level OptLevel) {
11884   /// run - This is the main entry point to this class.
11885   ///
11886   DAGCombiner(*this, AA, OptLevel).Run(Level);
11887 }