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