Allow vector fsub ops with constants to get the same optimizations as scalars.
[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   static cl::opt<bool>
81     MaySplitLoadIndex("combiner-split-load-index", cl::Hidden, cl::init(true),
82                       cl::desc("DAG combiner may split indexing from loads"));
83
84 //------------------------------ DAGCombiner ---------------------------------//
85
86   class DAGCombiner {
87     SelectionDAG &DAG;
88     const TargetLowering &TLI;
89     CombineLevel Level;
90     CodeGenOpt::Level OptLevel;
91     bool LegalOperations;
92     bool LegalTypes;
93     bool ForCodeSize;
94
95     /// \brief Worklist of all of the nodes that need to be simplified.
96     ///
97     /// This must behave as a stack -- new nodes to process are pushed onto the
98     /// back and when processing we pop off of the back.
99     ///
100     /// The worklist will not contain duplicates but may contain null entries
101     /// due to nodes being deleted from the underlying DAG.
102     SmallVector<SDNode *, 64> Worklist;
103
104     /// \brief Mapping from an SDNode to its position on the worklist.
105     ///
106     /// This is used to find and remove nodes from the worklist (by nulling
107     /// them) when they are deleted from the underlying DAG. It relies on
108     /// stable indices of nodes within the worklist.
109     DenseMap<SDNode *, unsigned> WorklistMap;
110
111     /// \brief Set of nodes which have been combined (at least once).
112     ///
113     /// This is used to allow us to reliably add any operands of a DAG node
114     /// which have not yet been combined to the worklist.
115     SmallPtrSet<SDNode *, 64> CombinedNodes;
116
117     // AA - Used for DAG load/store alias analysis.
118     AliasAnalysis &AA;
119
120     /// When an instruction is simplified, add all users of the instruction to
121     /// the work lists because they might get more simplified now.
122     void AddUsersToWorklist(SDNode *N) {
123       for (SDNode *Node : N->uses())
124         AddToWorklist(Node);
125     }
126
127     /// Call the node-specific routine that folds each particular type of node.
128     SDValue visit(SDNode *N);
129
130   public:
131     /// Add to the worklist making sure its instance is at the back (next to be
132     /// processed.)
133     void AddToWorklist(SDNode *N) {
134       // Skip handle nodes as they can't usefully be combined and confuse the
135       // zero-use deletion strategy.
136       if (N->getOpcode() == ISD::HANDLENODE)
137         return;
138
139       if (WorklistMap.insert(std::make_pair(N, Worklist.size())).second)
140         Worklist.push_back(N);
141     }
142
143     /// Remove all instances of N from the worklist.
144     void removeFromWorklist(SDNode *N) {
145       CombinedNodes.erase(N);
146
147       auto It = WorklistMap.find(N);
148       if (It == WorklistMap.end())
149         return; // Not in the worklist.
150
151       // Null out the entry rather than erasing it to avoid a linear operation.
152       Worklist[It->second] = nullptr;
153       WorklistMap.erase(It);
154     }
155
156     void deleteAndRecombine(SDNode *N);
157     bool recursivelyDeleteUnusedNodes(SDNode *N);
158
159     SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
160                       bool AddTo = true);
161
162     SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
163       return CombineTo(N, &Res, 1, AddTo);
164     }
165
166     SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
167                       bool AddTo = true) {
168       SDValue To[] = { Res0, Res1 };
169       return CombineTo(N, To, 2, AddTo);
170     }
171
172     void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
173
174   private:
175
176     /// Check the specified integer node value to see if it can be simplified or
177     /// if things it uses can be simplified by bit propagation.
178     /// If so, return true.
179     bool SimplifyDemandedBits(SDValue Op) {
180       unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits();
181       APInt Demanded = APInt::getAllOnesValue(BitWidth);
182       return SimplifyDemandedBits(Op, Demanded);
183     }
184
185     bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded);
186
187     bool CombineToPreIndexedLoadStore(SDNode *N);
188     bool CombineToPostIndexedLoadStore(SDNode *N);
189     SDValue SplitIndexingFromLoad(LoadSDNode *LD);
190     bool SliceUpLoad(SDNode *N);
191
192     /// \brief Replace an ISD::EXTRACT_VECTOR_ELT of a load with a narrowed
193     ///   load.
194     ///
195     /// \param EVE ISD::EXTRACT_VECTOR_ELT to be replaced.
196     /// \param InVecVT type of the input vector to EVE with bitcasts resolved.
197     /// \param EltNo index of the vector element to load.
198     /// \param OriginalLoad load that EVE came from to be replaced.
199     /// \returns EVE on success SDValue() on failure.
200     SDValue ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
201         SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad);
202     void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
203     SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
204     SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
205     SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
206     SDValue PromoteIntBinOp(SDValue Op);
207     SDValue PromoteIntShiftOp(SDValue Op);
208     SDValue PromoteExtend(SDValue Op);
209     bool PromoteLoad(SDValue Op);
210
211     void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
212                          SDValue Trunc, SDValue ExtLoad, SDLoc DL,
213                          ISD::NodeType ExtType);
214
215     /// Call the node-specific routine that knows how to fold each
216     /// particular type of node. If that doesn't do anything, try the
217     /// target-specific DAG combines.
218     SDValue combine(SDNode *N);
219
220     // Visitation implementation - Implement dag node combining for different
221     // node types.  The semantics are as follows:
222     // Return Value:
223     //   SDValue.getNode() == 0 - No change was made
224     //   SDValue.getNode() == N - N was replaced, is dead and has been handled.
225     //   otherwise              - N should be replaced by the returned Operand.
226     //
227     SDValue visitTokenFactor(SDNode *N);
228     SDValue visitMERGE_VALUES(SDNode *N);
229     SDValue visitADD(SDNode *N);
230     SDValue visitSUB(SDNode *N);
231     SDValue visitADDC(SDNode *N);
232     SDValue visitSUBC(SDNode *N);
233     SDValue visitADDE(SDNode *N);
234     SDValue visitSUBE(SDNode *N);
235     SDValue visitMUL(SDNode *N);
236     SDValue visitSDIV(SDNode *N);
237     SDValue visitUDIV(SDNode *N);
238     SDValue visitSREM(SDNode *N);
239     SDValue visitUREM(SDNode *N);
240     SDValue visitMULHU(SDNode *N);
241     SDValue visitMULHS(SDNode *N);
242     SDValue visitSMUL_LOHI(SDNode *N);
243     SDValue visitUMUL_LOHI(SDNode *N);
244     SDValue visitSMULO(SDNode *N);
245     SDValue visitUMULO(SDNode *N);
246     SDValue visitSDIVREM(SDNode *N);
247     SDValue visitUDIVREM(SDNode *N);
248     SDValue visitAND(SDNode *N);
249     SDValue visitOR(SDNode *N);
250     SDValue visitXOR(SDNode *N);
251     SDValue SimplifyVBinOp(SDNode *N);
252     SDValue SimplifyVUnaryOp(SDNode *N);
253     SDValue visitSHL(SDNode *N);
254     SDValue visitSRA(SDNode *N);
255     SDValue visitSRL(SDNode *N);
256     SDValue visitRotate(SDNode *N);
257     SDValue visitCTLZ(SDNode *N);
258     SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
259     SDValue visitCTTZ(SDNode *N);
260     SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
261     SDValue visitCTPOP(SDNode *N);
262     SDValue visitSELECT(SDNode *N);
263     SDValue visitVSELECT(SDNode *N);
264     SDValue visitSELECT_CC(SDNode *N);
265     SDValue visitSETCC(SDNode *N);
266     SDValue visitSIGN_EXTEND(SDNode *N);
267     SDValue visitZERO_EXTEND(SDNode *N);
268     SDValue visitANY_EXTEND(SDNode *N);
269     SDValue visitSIGN_EXTEND_INREG(SDNode *N);
270     SDValue visitTRUNCATE(SDNode *N);
271     SDValue visitBITCAST(SDNode *N);
272     SDValue visitBUILD_PAIR(SDNode *N);
273     SDValue visitFADD(SDNode *N);
274     SDValue visitFSUB(SDNode *N);
275     SDValue visitFMUL(SDNode *N);
276     SDValue visitFMA(SDNode *N);
277     SDValue visitFDIV(SDNode *N);
278     SDValue visitFREM(SDNode *N);
279     SDValue visitFCOPYSIGN(SDNode *N);
280     SDValue visitSINT_TO_FP(SDNode *N);
281     SDValue visitUINT_TO_FP(SDNode *N);
282     SDValue visitFP_TO_SINT(SDNode *N);
283     SDValue visitFP_TO_UINT(SDNode *N);
284     SDValue visitFP_ROUND(SDNode *N);
285     SDValue visitFP_ROUND_INREG(SDNode *N);
286     SDValue visitFP_EXTEND(SDNode *N);
287     SDValue visitFNEG(SDNode *N);
288     SDValue visitFABS(SDNode *N);
289     SDValue visitFCEIL(SDNode *N);
290     SDValue visitFTRUNC(SDNode *N);
291     SDValue visitFFLOOR(SDNode *N);
292     SDValue visitBRCOND(SDNode *N);
293     SDValue visitBR_CC(SDNode *N);
294     SDValue visitLOAD(SDNode *N);
295     SDValue visitSTORE(SDNode *N);
296     SDValue visitINSERT_VECTOR_ELT(SDNode *N);
297     SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
298     SDValue visitBUILD_VECTOR(SDNode *N);
299     SDValue visitCONCAT_VECTORS(SDNode *N);
300     SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
301     SDValue visitVECTOR_SHUFFLE(SDNode *N);
302     SDValue visitINSERT_SUBVECTOR(SDNode *N);
303
304     SDValue XformToShuffleWithZero(SDNode *N);
305     SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS);
306
307     SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt);
308
309     bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
310     SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
311     SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2);
312     SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2,
313                              SDValue N3, ISD::CondCode CC,
314                              bool NotExtCompare = false);
315     SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
316                           SDLoc DL, bool foldBooleans = true);
317
318     bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
319                            SDValue &CC) const;
320     bool isOneUseSetCC(SDValue N) const;
321
322     SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
323                                          unsigned HiOp);
324     SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
325     SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
326     SDValue BuildSDIV(SDNode *N);
327     SDValue BuildSDIVPow2(SDNode *N);
328     SDValue BuildUDIV(SDNode *N);
329     SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
330                                bool DemandHighBits = true);
331     SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
332     SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
333                               SDValue InnerPos, SDValue InnerNeg,
334                               unsigned PosOpcode, unsigned NegOpcode,
335                               SDLoc DL);
336     SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL);
337     SDValue ReduceLoadWidth(SDNode *N);
338     SDValue ReduceLoadOpStoreWidth(SDNode *N);
339     SDValue TransformFPLoadStorePair(SDNode *N);
340     SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
341     SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
342
343     SDValue GetDemandedBits(SDValue V, const APInt &Mask);
344
345     /// Walk up chain skipping non-aliasing memory nodes,
346     /// looking for aliasing nodes and adding them to the Aliases vector.
347     void GatherAllAliases(SDNode *N, SDValue OriginalChain,
348                           SmallVectorImpl<SDValue> &Aliases);
349
350     /// Return true if there is any possibility that the two addresses overlap.
351     bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const;
352
353     /// Walk up chain skipping non-aliasing memory nodes, looking for a better
354     /// chain (aliasing node.)
355     SDValue FindBetterChain(SDNode *N, SDValue Chain);
356
357     /// Merge consecutive store operations into a wide store.
358     /// This optimization uses wide integers or vectors when possible.
359     /// \return True if some memory operations were changed.
360     bool MergeConsecutiveStores(StoreSDNode *N);
361
362     /// \brief Try to transform a truncation where C is a constant:
363     ///     (trunc (and X, C)) -> (and (trunc X), (trunc C))
364     ///
365     /// \p N needs to be a truncation and its first operand an AND. Other
366     /// requirements are checked by the function (e.g. that trunc is
367     /// single-use) and if missed an empty SDValue is returned.
368     SDValue distributeTruncateThroughAnd(SDNode *N);
369
370   public:
371     DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
372         : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
373           OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
374       AttributeSet FnAttrs =
375           DAG.getMachineFunction().getFunction()->getAttributes();
376       ForCodeSize =
377           FnAttrs.hasAttribute(AttributeSet::FunctionIndex,
378                                Attribute::OptimizeForSize) ||
379           FnAttrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::MinSize);
380     }
381
382     /// Runs the dag combiner on all nodes in the work list
383     void Run(CombineLevel AtLevel);
384
385     SelectionDAG &getDAG() const { return DAG; }
386
387     /// Returns a type large enough to hold any valid shift amount - before type
388     /// legalization these can be huge.
389     EVT getShiftAmountTy(EVT LHSTy) {
390       assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
391       if (LHSTy.isVector())
392         return LHSTy;
393       return LegalTypes ? TLI.getScalarShiftAmountTy(LHSTy)
394                         : TLI.getPointerTy();
395     }
396
397     /// This method returns true if we are running before type legalization or
398     /// if the specified VT is legal.
399     bool isTypeLegal(const EVT &VT) {
400       if (!LegalTypes) return true;
401       return TLI.isTypeLegal(VT);
402     }
403
404     /// Convenience wrapper around TargetLowering::getSetCCResultType
405     EVT getSetCCResultType(EVT VT) const {
406       return TLI.getSetCCResultType(*DAG.getContext(), VT);
407     }
408   };
409 }
410
411
412 namespace {
413 /// This class is a DAGUpdateListener that removes any deleted
414 /// nodes from the worklist.
415 class WorklistRemover : public SelectionDAG::DAGUpdateListener {
416   DAGCombiner &DC;
417 public:
418   explicit WorklistRemover(DAGCombiner &dc)
419     : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
420
421   void NodeDeleted(SDNode *N, SDNode *E) override {
422     DC.removeFromWorklist(N);
423   }
424 };
425 }
426
427 //===----------------------------------------------------------------------===//
428 //  TargetLowering::DAGCombinerInfo implementation
429 //===----------------------------------------------------------------------===//
430
431 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
432   ((DAGCombiner*)DC)->AddToWorklist(N);
433 }
434
435 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
436   ((DAGCombiner*)DC)->removeFromWorklist(N);
437 }
438
439 SDValue TargetLowering::DAGCombinerInfo::
440 CombineTo(SDNode *N, const std::vector<SDValue> &To, bool AddTo) {
441   return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
442 }
443
444 SDValue TargetLowering::DAGCombinerInfo::
445 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
446   return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
447 }
448
449
450 SDValue TargetLowering::DAGCombinerInfo::
451 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
452   return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
453 }
454
455 void TargetLowering::DAGCombinerInfo::
456 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
457   return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
458 }
459
460 //===----------------------------------------------------------------------===//
461 // Helper Functions
462 //===----------------------------------------------------------------------===//
463
464 void DAGCombiner::deleteAndRecombine(SDNode *N) {
465   removeFromWorklist(N);
466
467   // If the operands of this node are only used by the node, they will now be
468   // dead. Make sure to re-visit them and recursively delete dead nodes.
469   for (const SDValue &Op : N->ops())
470     // For an operand generating multiple values, one of the values may
471     // become dead allowing further simplification (e.g. split index
472     // arithmetic from an indexed load).
473     if (Op->hasOneUse() || Op->getNumValues() > 1)
474       AddToWorklist(Op.getNode());
475
476   DAG.DeleteNode(N);
477 }
478
479 /// Return 1 if we can compute the negated form of the specified expression for
480 /// the same cost as the expression itself, or 2 if we can compute the negated
481 /// form more cheaply than the expression itself.
482 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
483                                const TargetLowering &TLI,
484                                const TargetOptions *Options,
485                                unsigned Depth = 0) {
486   // fneg is removable even if it has multiple uses.
487   if (Op.getOpcode() == ISD::FNEG) return 2;
488
489   // Don't allow anything with multiple uses.
490   if (!Op.hasOneUse()) return 0;
491
492   // Don't recurse exponentially.
493   if (Depth > 6) return 0;
494
495   switch (Op.getOpcode()) {
496   default: return false;
497   case ISD::ConstantFP:
498     // Don't invert constant FP values after legalize.  The negated constant
499     // isn't necessarily legal.
500     return LegalOperations ? 0 : 1;
501   case ISD::FADD:
502     // FIXME: determine better conditions for this xform.
503     if (!Options->UnsafeFPMath) return 0;
504
505     // After operation legalization, it might not be legal to create new FSUBs.
506     if (LegalOperations &&
507         !TLI.isOperationLegalOrCustom(ISD::FSUB,  Op.getValueType()))
508       return 0;
509
510     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
511     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
512                                     Options, Depth + 1))
513       return V;
514     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
515     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
516                               Depth + 1);
517   case ISD::FSUB:
518     // We can't turn -(A-B) into B-A when we honor signed zeros.
519     if (!Options->UnsafeFPMath) return 0;
520
521     // fold (fneg (fsub A, B)) -> (fsub B, A)
522     return 1;
523
524   case ISD::FMUL:
525   case ISD::FDIV:
526     if (Options->HonorSignDependentRoundingFPMath()) return 0;
527
528     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
529     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
530                                     Options, Depth + 1))
531       return V;
532
533     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
534                               Depth + 1);
535
536   case ISD::FP_EXTEND:
537   case ISD::FP_ROUND:
538   case ISD::FSIN:
539     return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
540                               Depth + 1);
541   }
542 }
543
544 /// If isNegatibleForFree returns true, return the newly negated expression.
545 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
546                                     bool LegalOperations, unsigned Depth = 0) {
547   const TargetOptions &Options = DAG.getTarget().Options;
548   // fneg is removable even if it has multiple uses.
549   if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
550
551   // Don't allow anything with multiple uses.
552   assert(Op.hasOneUse() && "Unknown reuse!");
553
554   assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
555   switch (Op.getOpcode()) {
556   default: llvm_unreachable("Unknown code");
557   case ISD::ConstantFP: {
558     APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
559     V.changeSign();
560     return DAG.getConstantFP(V, Op.getValueType());
561   }
562   case ISD::FADD:
563     // FIXME: determine better conditions for this xform.
564     assert(Options.UnsafeFPMath);
565
566     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
567     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
568                            DAG.getTargetLoweringInfo(), &Options, Depth+1))
569       return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
570                          GetNegatedExpression(Op.getOperand(0), DAG,
571                                               LegalOperations, Depth+1),
572                          Op.getOperand(1));
573     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
574     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
575                        GetNegatedExpression(Op.getOperand(1), DAG,
576                                             LegalOperations, Depth+1),
577                        Op.getOperand(0));
578   case ISD::FSUB:
579     // We can't turn -(A-B) into B-A when we honor signed zeros.
580     assert(Options.UnsafeFPMath);
581
582     // fold (fneg (fsub 0, B)) -> B
583     if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
584       if (N0CFP->getValueAPF().isZero())
585         return Op.getOperand(1);
586
587     // fold (fneg (fsub A, B)) -> (fsub B, A)
588     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
589                        Op.getOperand(1), Op.getOperand(0));
590
591   case ISD::FMUL:
592   case ISD::FDIV:
593     assert(!Options.HonorSignDependentRoundingFPMath());
594
595     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
596     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
597                            DAG.getTargetLoweringInfo(), &Options, Depth+1))
598       return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
599                          GetNegatedExpression(Op.getOperand(0), DAG,
600                                               LegalOperations, Depth+1),
601                          Op.getOperand(1));
602
603     // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
604     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
605                        Op.getOperand(0),
606                        GetNegatedExpression(Op.getOperand(1), DAG,
607                                             LegalOperations, Depth+1));
608
609   case ISD::FP_EXTEND:
610   case ISD::FSIN:
611     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
612                        GetNegatedExpression(Op.getOperand(0), DAG,
613                                             LegalOperations, Depth+1));
614   case ISD::FP_ROUND:
615       return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
616                          GetNegatedExpression(Op.getOperand(0), DAG,
617                                               LegalOperations, Depth+1),
618                          Op.getOperand(1));
619   }
620 }
621
622 // Return true if this node is a setcc, or is a select_cc
623 // that selects between the target values used for true and false, making it
624 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
625 // the appropriate nodes based on the type of node we are checking. This
626 // simplifies life a bit for the callers.
627 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
628                                     SDValue &CC) const {
629   if (N.getOpcode() == ISD::SETCC) {
630     LHS = N.getOperand(0);
631     RHS = N.getOperand(1);
632     CC  = N.getOperand(2);
633     return true;
634   }
635
636   if (N.getOpcode() != ISD::SELECT_CC ||
637       !TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
638       !TLI.isConstFalseVal(N.getOperand(3).getNode()))
639     return false;
640
641   LHS = N.getOperand(0);
642   RHS = N.getOperand(1);
643   CC  = N.getOperand(4);
644   return true;
645 }
646
647 /// Return true if this is a SetCC-equivalent operation with only one use.
648 /// If this is true, it allows the users to invert the operation for free when
649 /// it is profitable to do so.
650 bool DAGCombiner::isOneUseSetCC(SDValue N) const {
651   SDValue N0, N1, N2;
652   if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
653     return true;
654   return false;
655 }
656
657 /// Returns true if N is a BUILD_VECTOR node whose
658 /// elements are all the same constant or undefined.
659 static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
660   BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
661   if (!C)
662     return false;
663
664   APInt SplatUndef;
665   unsigned SplatBitSize;
666   bool HasAnyUndefs;
667   EVT EltVT = N->getValueType(0).getVectorElementType();
668   return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
669                              HasAnyUndefs) &&
670           EltVT.getSizeInBits() >= SplatBitSize);
671 }
672
673 // \brief Returns the SDNode if it is a constant BuildVector or constant.
674 static SDNode *isConstantBuildVectorOrConstantInt(SDValue N) {
675   if (isa<ConstantSDNode>(N))
676     return N.getNode();
677   BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N);
678   if (BV && BV->isConstant())
679     return BV;
680   return nullptr;
681 }
682
683 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
684 // int.
685 static ConstantSDNode *isConstOrConstSplat(SDValue N) {
686   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
687     return CN;
688
689   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
690     BitVector UndefElements;
691     ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
692
693     // BuildVectors can truncate their operands. Ignore that case here.
694     // FIXME: We blindly ignore splats which include undef which is overly
695     // pessimistic.
696     if (CN && UndefElements.none() &&
697         CN->getValueType(0) == N.getValueType().getScalarType())
698       return CN;
699   }
700
701   return nullptr;
702 }
703
704 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
705 // float.
706 static ConstantFPSDNode *isConstOrConstSplatFP(SDValue N) {
707   if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
708     return CN;
709
710   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
711     BitVector UndefElements;
712     ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements);
713
714     if (CN && UndefElements.none())
715       return CN;
716   }
717
718   return nullptr;
719 }
720
721 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
722                                     SDValue N0, SDValue N1) {
723   EVT VT = N0.getValueType();
724   if (N0.getOpcode() == Opc) {
725     if (SDNode *L = isConstantBuildVectorOrConstantInt(N0.getOperand(1))) {
726       if (SDNode *R = isConstantBuildVectorOrConstantInt(N1)) {
727         // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
728         SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, L, R);
729         if (!OpNode.getNode())
730           return SDValue();
731         return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
732       }
733       if (N0.hasOneUse()) {
734         // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
735         // use
736         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
737         if (!OpNode.getNode())
738           return SDValue();
739         AddToWorklist(OpNode.getNode());
740         return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
741       }
742     }
743   }
744
745   if (N1.getOpcode() == Opc) {
746     if (SDNode *R = isConstantBuildVectorOrConstantInt(N1.getOperand(1))) {
747       if (SDNode *L = isConstantBuildVectorOrConstantInt(N0)) {
748         // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
749         SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, R, L);
750         if (!OpNode.getNode())
751           return SDValue();
752         return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
753       }
754       if (N1.hasOneUse()) {
755         // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one
756         // use
757         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0);
758         if (!OpNode.getNode())
759           return SDValue();
760         AddToWorklist(OpNode.getNode());
761         return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
762       }
763     }
764   }
765
766   return SDValue();
767 }
768
769 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
770                                bool AddTo) {
771   assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
772   ++NodesCombined;
773   DEBUG(dbgs() << "\nReplacing.1 ";
774         N->dump(&DAG);
775         dbgs() << "\nWith: ";
776         To[0].getNode()->dump(&DAG);
777         dbgs() << " and " << NumTo-1 << " other values\n";
778         for (unsigned i = 0, e = NumTo; i != e; ++i)
779           assert((!To[i].getNode() ||
780                   N->getValueType(i) == To[i].getValueType()) &&
781                  "Cannot combine value to value of different type!"));
782   WorklistRemover DeadNodes(*this);
783   DAG.ReplaceAllUsesWith(N, To);
784   if (AddTo) {
785     // Push the new nodes and any users onto the worklist
786     for (unsigned i = 0, e = NumTo; i != e; ++i) {
787       if (To[i].getNode()) {
788         AddToWorklist(To[i].getNode());
789         AddUsersToWorklist(To[i].getNode());
790       }
791     }
792   }
793
794   // Finally, if the node is now dead, remove it from the graph.  The node
795   // may not be dead if the replacement process recursively simplified to
796   // something else needing this node.
797   if (N->use_empty())
798     deleteAndRecombine(N);
799   return SDValue(N, 0);
800 }
801
802 void DAGCombiner::
803 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
804   // Replace all uses.  If any nodes become isomorphic to other nodes and
805   // are deleted, make sure to remove them from our worklist.
806   WorklistRemover DeadNodes(*this);
807   DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
808
809   // Push the new node and any (possibly new) users onto the worklist.
810   AddToWorklist(TLO.New.getNode());
811   AddUsersToWorklist(TLO.New.getNode());
812
813   // Finally, if the node is now dead, remove it from the graph.  The node
814   // may not be dead if the replacement process recursively simplified to
815   // something else needing this node.
816   if (TLO.Old.getNode()->use_empty())
817     deleteAndRecombine(TLO.Old.getNode());
818 }
819
820 /// Check the specified integer node value to see if it can be simplified or if
821 /// things it uses can be simplified by bit propagation. If so, return true.
822 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
823   TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
824   APInt KnownZero, KnownOne;
825   if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
826     return false;
827
828   // Revisit the node.
829   AddToWorklist(Op.getNode());
830
831   // Replace the old value with the new one.
832   ++NodesCombined;
833   DEBUG(dbgs() << "\nReplacing.2 ";
834         TLO.Old.getNode()->dump(&DAG);
835         dbgs() << "\nWith: ";
836         TLO.New.getNode()->dump(&DAG);
837         dbgs() << '\n');
838
839   CommitTargetLoweringOpt(TLO);
840   return true;
841 }
842
843 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
844   SDLoc dl(Load);
845   EVT VT = Load->getValueType(0);
846   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
847
848   DEBUG(dbgs() << "\nReplacing.9 ";
849         Load->dump(&DAG);
850         dbgs() << "\nWith: ";
851         Trunc.getNode()->dump(&DAG);
852         dbgs() << '\n');
853   WorklistRemover DeadNodes(*this);
854   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
855   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
856   deleteAndRecombine(Load);
857   AddToWorklist(Trunc.getNode());
858 }
859
860 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
861   Replace = false;
862   SDLoc dl(Op);
863   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
864     EVT MemVT = LD->getMemoryVT();
865     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
866       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
867                                                   : ISD::EXTLOAD)
868       : LD->getExtensionType();
869     Replace = true;
870     return DAG.getExtLoad(ExtType, dl, PVT,
871                           LD->getChain(), LD->getBasePtr(),
872                           MemVT, LD->getMemOperand());
873   }
874
875   unsigned Opc = Op.getOpcode();
876   switch (Opc) {
877   default: break;
878   case ISD::AssertSext:
879     return DAG.getNode(ISD::AssertSext, dl, PVT,
880                        SExtPromoteOperand(Op.getOperand(0), PVT),
881                        Op.getOperand(1));
882   case ISD::AssertZext:
883     return DAG.getNode(ISD::AssertZext, dl, PVT,
884                        ZExtPromoteOperand(Op.getOperand(0), PVT),
885                        Op.getOperand(1));
886   case ISD::Constant: {
887     unsigned ExtOpc =
888       Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
889     return DAG.getNode(ExtOpc, dl, PVT, Op);
890   }
891   }
892
893   if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
894     return SDValue();
895   return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
896 }
897
898 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
899   if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
900     return SDValue();
901   EVT OldVT = Op.getValueType();
902   SDLoc dl(Op);
903   bool Replace = false;
904   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
905   if (!NewOp.getNode())
906     return SDValue();
907   AddToWorklist(NewOp.getNode());
908
909   if (Replace)
910     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
911   return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
912                      DAG.getValueType(OldVT));
913 }
914
915 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
916   EVT OldVT = Op.getValueType();
917   SDLoc dl(Op);
918   bool Replace = false;
919   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
920   if (!NewOp.getNode())
921     return SDValue();
922   AddToWorklist(NewOp.getNode());
923
924   if (Replace)
925     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
926   return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
927 }
928
929 /// Promote the specified integer binary operation if the target indicates it is
930 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
931 /// i32 since i16 instructions are longer.
932 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
933   if (!LegalOperations)
934     return SDValue();
935
936   EVT VT = Op.getValueType();
937   if (VT.isVector() || !VT.isInteger())
938     return SDValue();
939
940   // If operation type is 'undesirable', e.g. i16 on x86, consider
941   // promoting it.
942   unsigned Opc = Op.getOpcode();
943   if (TLI.isTypeDesirableForOp(Opc, VT))
944     return SDValue();
945
946   EVT PVT = VT;
947   // Consult target whether it is a good idea to promote this operation and
948   // what's the right type to promote it to.
949   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
950     assert(PVT != VT && "Don't know what type to promote to!");
951
952     bool Replace0 = false;
953     SDValue N0 = Op.getOperand(0);
954     SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
955     if (!NN0.getNode())
956       return SDValue();
957
958     bool Replace1 = false;
959     SDValue N1 = Op.getOperand(1);
960     SDValue NN1;
961     if (N0 == N1)
962       NN1 = NN0;
963     else {
964       NN1 = PromoteOperand(N1, PVT, Replace1);
965       if (!NN1.getNode())
966         return SDValue();
967     }
968
969     AddToWorklist(NN0.getNode());
970     if (NN1.getNode())
971       AddToWorklist(NN1.getNode());
972
973     if (Replace0)
974       ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
975     if (Replace1)
976       ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
977
978     DEBUG(dbgs() << "\nPromoting ";
979           Op.getNode()->dump(&DAG));
980     SDLoc dl(Op);
981     return DAG.getNode(ISD::TRUNCATE, dl, VT,
982                        DAG.getNode(Opc, dl, PVT, NN0, NN1));
983   }
984   return SDValue();
985 }
986
987 /// Promote the specified integer shift operation if the target indicates it is
988 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
989 /// i32 since i16 instructions are longer.
990 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
991   if (!LegalOperations)
992     return SDValue();
993
994   EVT VT = Op.getValueType();
995   if (VT.isVector() || !VT.isInteger())
996     return SDValue();
997
998   // If operation type is 'undesirable', e.g. i16 on x86, consider
999   // promoting it.
1000   unsigned Opc = Op.getOpcode();
1001   if (TLI.isTypeDesirableForOp(Opc, VT))
1002     return SDValue();
1003
1004   EVT PVT = VT;
1005   // Consult target whether it is a good idea to promote this operation and
1006   // what's the right type to promote it to.
1007   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1008     assert(PVT != VT && "Don't know what type to promote to!");
1009
1010     bool Replace = false;
1011     SDValue N0 = Op.getOperand(0);
1012     if (Opc == ISD::SRA)
1013       N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
1014     else if (Opc == ISD::SRL)
1015       N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
1016     else
1017       N0 = PromoteOperand(N0, PVT, Replace);
1018     if (!N0.getNode())
1019       return SDValue();
1020
1021     AddToWorklist(N0.getNode());
1022     if (Replace)
1023       ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
1024
1025     DEBUG(dbgs() << "\nPromoting ";
1026           Op.getNode()->dump(&DAG));
1027     SDLoc dl(Op);
1028     return DAG.getNode(ISD::TRUNCATE, dl, VT,
1029                        DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
1030   }
1031   return SDValue();
1032 }
1033
1034 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
1035   if (!LegalOperations)
1036     return SDValue();
1037
1038   EVT VT = Op.getValueType();
1039   if (VT.isVector() || !VT.isInteger())
1040     return SDValue();
1041
1042   // If operation type is 'undesirable', e.g. i16 on x86, consider
1043   // promoting it.
1044   unsigned Opc = Op.getOpcode();
1045   if (TLI.isTypeDesirableForOp(Opc, VT))
1046     return SDValue();
1047
1048   EVT PVT = VT;
1049   // Consult target whether it is a good idea to promote this operation and
1050   // what's the right type to promote it to.
1051   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1052     assert(PVT != VT && "Don't know what type to promote to!");
1053     // fold (aext (aext x)) -> (aext x)
1054     // fold (aext (zext x)) -> (zext x)
1055     // fold (aext (sext x)) -> (sext x)
1056     DEBUG(dbgs() << "\nPromoting ";
1057           Op.getNode()->dump(&DAG));
1058     return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1059   }
1060   return SDValue();
1061 }
1062
1063 bool DAGCombiner::PromoteLoad(SDValue Op) {
1064   if (!LegalOperations)
1065     return false;
1066
1067   EVT VT = Op.getValueType();
1068   if (VT.isVector() || !VT.isInteger())
1069     return false;
1070
1071   // If operation type is 'undesirable', e.g. i16 on x86, consider
1072   // promoting it.
1073   unsigned Opc = Op.getOpcode();
1074   if (TLI.isTypeDesirableForOp(Opc, VT))
1075     return false;
1076
1077   EVT PVT = VT;
1078   // Consult target whether it is a good idea to promote this operation and
1079   // what's the right type to promote it to.
1080   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1081     assert(PVT != VT && "Don't know what type to promote to!");
1082
1083     SDLoc dl(Op);
1084     SDNode *N = Op.getNode();
1085     LoadSDNode *LD = cast<LoadSDNode>(N);
1086     EVT MemVT = LD->getMemoryVT();
1087     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1088       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
1089                                                   : ISD::EXTLOAD)
1090       : LD->getExtensionType();
1091     SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
1092                                    LD->getChain(), LD->getBasePtr(),
1093                                    MemVT, LD->getMemOperand());
1094     SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
1095
1096     DEBUG(dbgs() << "\nPromoting ";
1097           N->dump(&DAG);
1098           dbgs() << "\nTo: ";
1099           Result.getNode()->dump(&DAG);
1100           dbgs() << '\n');
1101     WorklistRemover DeadNodes(*this);
1102     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1103     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1104     deleteAndRecombine(N);
1105     AddToWorklist(Result.getNode());
1106     return true;
1107   }
1108   return false;
1109 }
1110
1111 /// \brief Recursively delete a node which has no uses and any operands for
1112 /// which it is the only use.
1113 ///
1114 /// Note that this both deletes the nodes and removes them from the worklist.
1115 /// It also adds any nodes who have had a user deleted to the worklist as they
1116 /// may now have only one use and subject to other combines.
1117 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) {
1118   if (!N->use_empty())
1119     return false;
1120
1121   SmallSetVector<SDNode *, 16> Nodes;
1122   Nodes.insert(N);
1123   do {
1124     N = Nodes.pop_back_val();
1125     if (!N)
1126       continue;
1127
1128     if (N->use_empty()) {
1129       for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1130         Nodes.insert(N->getOperand(i).getNode());
1131
1132       removeFromWorklist(N);
1133       DAG.DeleteNode(N);
1134     } else {
1135       AddToWorklist(N);
1136     }
1137   } while (!Nodes.empty());
1138   return true;
1139 }
1140
1141 //===----------------------------------------------------------------------===//
1142 //  Main DAG Combiner implementation
1143 //===----------------------------------------------------------------------===//
1144
1145 void DAGCombiner::Run(CombineLevel AtLevel) {
1146   // set the instance variables, so that the various visit routines may use it.
1147   Level = AtLevel;
1148   LegalOperations = Level >= AfterLegalizeVectorOps;
1149   LegalTypes = Level >= AfterLegalizeTypes;
1150
1151   // Add all the dag nodes to the worklist.
1152   for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
1153        E = DAG.allnodes_end(); I != E; ++I)
1154     AddToWorklist(I);
1155
1156   // Create a dummy node (which is not added to allnodes), that adds a reference
1157   // to the root node, preventing it from being deleted, and tracking any
1158   // changes of the root.
1159   HandleSDNode Dummy(DAG.getRoot());
1160
1161   // while the worklist isn't empty, find a node and
1162   // try and combine it.
1163   while (!WorklistMap.empty()) {
1164     SDNode *N;
1165     // The Worklist holds the SDNodes in order, but it may contain null entries.
1166     do {
1167       N = Worklist.pop_back_val();
1168     } while (!N);
1169
1170     bool GoodWorklistEntry = WorklistMap.erase(N);
1171     (void)GoodWorklistEntry;
1172     assert(GoodWorklistEntry &&
1173            "Found a worklist entry without a corresponding map entry!");
1174
1175     // If N has no uses, it is dead.  Make sure to revisit all N's operands once
1176     // N is deleted from the DAG, since they too may now be dead or may have a
1177     // reduced number of uses, allowing other xforms.
1178     if (recursivelyDeleteUnusedNodes(N))
1179       continue;
1180
1181     WorklistRemover DeadNodes(*this);
1182
1183     // If this combine is running after legalizing the DAG, re-legalize any
1184     // nodes pulled off the worklist.
1185     if (Level == AfterLegalizeDAG) {
1186       SmallSetVector<SDNode *, 16> UpdatedNodes;
1187       bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes);
1188
1189       for (SDNode *LN : UpdatedNodes) {
1190         AddToWorklist(LN);
1191         AddUsersToWorklist(LN);
1192       }
1193       if (!NIsValid)
1194         continue;
1195     }
1196
1197     DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG));
1198
1199     // Add any operands of the new node which have not yet been combined to the
1200     // worklist as well. Because the worklist uniques things already, this
1201     // won't repeatedly process the same operand.
1202     CombinedNodes.insert(N);
1203     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1204       if (!CombinedNodes.count(N->getOperand(i).getNode()))
1205         AddToWorklist(N->getOperand(i).getNode());
1206
1207     SDValue RV = combine(N);
1208
1209     if (!RV.getNode())
1210       continue;
1211
1212     ++NodesCombined;
1213
1214     // If we get back the same node we passed in, rather than a new node or
1215     // zero, we know that the node must have defined multiple values and
1216     // CombineTo was used.  Since CombineTo takes care of the worklist
1217     // mechanics for us, we have no work to do in this case.
1218     if (RV.getNode() == N)
1219       continue;
1220
1221     assert(N->getOpcode() != ISD::DELETED_NODE &&
1222            RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1223            "Node was deleted but visit returned new node!");
1224
1225     DEBUG(dbgs() << " ... into: ";
1226           RV.getNode()->dump(&DAG));
1227
1228     // Transfer debug value.
1229     DAG.TransferDbgValues(SDValue(N, 0), RV);
1230     if (N->getNumValues() == RV.getNode()->getNumValues())
1231       DAG.ReplaceAllUsesWith(N, RV.getNode());
1232     else {
1233       assert(N->getValueType(0) == RV.getValueType() &&
1234              N->getNumValues() == 1 && "Type mismatch");
1235       SDValue OpV = RV;
1236       DAG.ReplaceAllUsesWith(N, &OpV);
1237     }
1238
1239     // Push the new node and any users onto the worklist
1240     AddToWorklist(RV.getNode());
1241     AddUsersToWorklist(RV.getNode());
1242
1243     // Finally, if the node is now dead, remove it from the graph.  The node
1244     // may not be dead if the replacement process recursively simplified to
1245     // something else needing this node. This will also take care of adding any
1246     // operands which have lost a user to the worklist.
1247     recursivelyDeleteUnusedNodes(N);
1248   }
1249
1250   // If the root changed (e.g. it was a dead load, update the root).
1251   DAG.setRoot(Dummy.getValue());
1252   DAG.RemoveDeadNodes();
1253 }
1254
1255 SDValue DAGCombiner::visit(SDNode *N) {
1256   switch (N->getOpcode()) {
1257   default: break;
1258   case ISD::TokenFactor:        return visitTokenFactor(N);
1259   case ISD::MERGE_VALUES:       return visitMERGE_VALUES(N);
1260   case ISD::ADD:                return visitADD(N);
1261   case ISD::SUB:                return visitSUB(N);
1262   case ISD::ADDC:               return visitADDC(N);
1263   case ISD::SUBC:               return visitSUBC(N);
1264   case ISD::ADDE:               return visitADDE(N);
1265   case ISD::SUBE:               return visitSUBE(N);
1266   case ISD::MUL:                return visitMUL(N);
1267   case ISD::SDIV:               return visitSDIV(N);
1268   case ISD::UDIV:               return visitUDIV(N);
1269   case ISD::SREM:               return visitSREM(N);
1270   case ISD::UREM:               return visitUREM(N);
1271   case ISD::MULHU:              return visitMULHU(N);
1272   case ISD::MULHS:              return visitMULHS(N);
1273   case ISD::SMUL_LOHI:          return visitSMUL_LOHI(N);
1274   case ISD::UMUL_LOHI:          return visitUMUL_LOHI(N);
1275   case ISD::SMULO:              return visitSMULO(N);
1276   case ISD::UMULO:              return visitUMULO(N);
1277   case ISD::SDIVREM:            return visitSDIVREM(N);
1278   case ISD::UDIVREM:            return visitUDIVREM(N);
1279   case ISD::AND:                return visitAND(N);
1280   case ISD::OR:                 return visitOR(N);
1281   case ISD::XOR:                return visitXOR(N);
1282   case ISD::SHL:                return visitSHL(N);
1283   case ISD::SRA:                return visitSRA(N);
1284   case ISD::SRL:                return visitSRL(N);
1285   case ISD::ROTR:
1286   case ISD::ROTL:               return visitRotate(N);
1287   case ISD::CTLZ:               return visitCTLZ(N);
1288   case ISD::CTLZ_ZERO_UNDEF:    return visitCTLZ_ZERO_UNDEF(N);
1289   case ISD::CTTZ:               return visitCTTZ(N);
1290   case ISD::CTTZ_ZERO_UNDEF:    return visitCTTZ_ZERO_UNDEF(N);
1291   case ISD::CTPOP:              return visitCTPOP(N);
1292   case ISD::SELECT:             return visitSELECT(N);
1293   case ISD::VSELECT:            return visitVSELECT(N);
1294   case ISD::SELECT_CC:          return visitSELECT_CC(N);
1295   case ISD::SETCC:              return visitSETCC(N);
1296   case ISD::SIGN_EXTEND:        return visitSIGN_EXTEND(N);
1297   case ISD::ZERO_EXTEND:        return visitZERO_EXTEND(N);
1298   case ISD::ANY_EXTEND:         return visitANY_EXTEND(N);
1299   case ISD::SIGN_EXTEND_INREG:  return visitSIGN_EXTEND_INREG(N);
1300   case ISD::TRUNCATE:           return visitTRUNCATE(N);
1301   case ISD::BITCAST:            return visitBITCAST(N);
1302   case ISD::BUILD_PAIR:         return visitBUILD_PAIR(N);
1303   case ISD::FADD:               return visitFADD(N);
1304   case ISD::FSUB:               return visitFSUB(N);
1305   case ISD::FMUL:               return visitFMUL(N);
1306   case ISD::FMA:                return visitFMA(N);
1307   case ISD::FDIV:               return visitFDIV(N);
1308   case ISD::FREM:               return visitFREM(N);
1309   case ISD::FCOPYSIGN:          return visitFCOPYSIGN(N);
1310   case ISD::SINT_TO_FP:         return visitSINT_TO_FP(N);
1311   case ISD::UINT_TO_FP:         return visitUINT_TO_FP(N);
1312   case ISD::FP_TO_SINT:         return visitFP_TO_SINT(N);
1313   case ISD::FP_TO_UINT:         return visitFP_TO_UINT(N);
1314   case ISD::FP_ROUND:           return visitFP_ROUND(N);
1315   case ISD::FP_ROUND_INREG:     return visitFP_ROUND_INREG(N);
1316   case ISD::FP_EXTEND:          return visitFP_EXTEND(N);
1317   case ISD::FNEG:               return visitFNEG(N);
1318   case ISD::FABS:               return visitFABS(N);
1319   case ISD::FFLOOR:             return visitFFLOOR(N);
1320   case ISD::FCEIL:              return visitFCEIL(N);
1321   case ISD::FTRUNC:             return visitFTRUNC(N);
1322   case ISD::BRCOND:             return visitBRCOND(N);
1323   case ISD::BR_CC:              return visitBR_CC(N);
1324   case ISD::LOAD:               return visitLOAD(N);
1325   case ISD::STORE:              return visitSTORE(N);
1326   case ISD::INSERT_VECTOR_ELT:  return visitINSERT_VECTOR_ELT(N);
1327   case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1328   case ISD::BUILD_VECTOR:       return visitBUILD_VECTOR(N);
1329   case ISD::CONCAT_VECTORS:     return visitCONCAT_VECTORS(N);
1330   case ISD::EXTRACT_SUBVECTOR:  return visitEXTRACT_SUBVECTOR(N);
1331   case ISD::VECTOR_SHUFFLE:     return visitVECTOR_SHUFFLE(N);
1332   case ISD::INSERT_SUBVECTOR:   return visitINSERT_SUBVECTOR(N);
1333   }
1334   return SDValue();
1335 }
1336
1337 SDValue DAGCombiner::combine(SDNode *N) {
1338   SDValue RV = visit(N);
1339
1340   // If nothing happened, try a target-specific DAG combine.
1341   if (!RV.getNode()) {
1342     assert(N->getOpcode() != ISD::DELETED_NODE &&
1343            "Node was deleted but visit returned NULL!");
1344
1345     if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1346         TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1347
1348       // Expose the DAG combiner to the target combiner impls.
1349       TargetLowering::DAGCombinerInfo
1350         DagCombineInfo(DAG, Level, false, this);
1351
1352       RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1353     }
1354   }
1355
1356   // If nothing happened still, try promoting the operation.
1357   if (!RV.getNode()) {
1358     switch (N->getOpcode()) {
1359     default: break;
1360     case ISD::ADD:
1361     case ISD::SUB:
1362     case ISD::MUL:
1363     case ISD::AND:
1364     case ISD::OR:
1365     case ISD::XOR:
1366       RV = PromoteIntBinOp(SDValue(N, 0));
1367       break;
1368     case ISD::SHL:
1369     case ISD::SRA:
1370     case ISD::SRL:
1371       RV = PromoteIntShiftOp(SDValue(N, 0));
1372       break;
1373     case ISD::SIGN_EXTEND:
1374     case ISD::ZERO_EXTEND:
1375     case ISD::ANY_EXTEND:
1376       RV = PromoteExtend(SDValue(N, 0));
1377       break;
1378     case ISD::LOAD:
1379       if (PromoteLoad(SDValue(N, 0)))
1380         RV = SDValue(N, 0);
1381       break;
1382     }
1383   }
1384
1385   // If N is a commutative binary node, try commuting it to enable more
1386   // sdisel CSE.
1387   if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1388       N->getNumValues() == 1) {
1389     SDValue N0 = N->getOperand(0);
1390     SDValue N1 = N->getOperand(1);
1391
1392     // Constant operands are canonicalized to RHS.
1393     if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1394       SDValue Ops[] = {N1, N0};
1395       SDNode *CSENode;
1396       if (const BinaryWithFlagsSDNode *BinNode =
1397               dyn_cast<BinaryWithFlagsSDNode>(N)) {
1398         CSENode = DAG.getNodeIfExists(
1399             N->getOpcode(), N->getVTList(), Ops, BinNode->hasNoUnsignedWrap(),
1400             BinNode->hasNoSignedWrap(), BinNode->isExact());
1401       } else {
1402         CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops);
1403       }
1404       if (CSENode)
1405         return SDValue(CSENode, 0);
1406     }
1407   }
1408
1409   return RV;
1410 }
1411
1412 /// Given a node, return its input chain if it has one, otherwise return a null
1413 /// sd operand.
1414 static SDValue getInputChainForNode(SDNode *N) {
1415   if (unsigned NumOps = N->getNumOperands()) {
1416     if (N->getOperand(0).getValueType() == MVT::Other)
1417       return N->getOperand(0);
1418     if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1419       return N->getOperand(NumOps-1);
1420     for (unsigned i = 1; i < NumOps-1; ++i)
1421       if (N->getOperand(i).getValueType() == MVT::Other)
1422         return N->getOperand(i);
1423   }
1424   return SDValue();
1425 }
1426
1427 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1428   // If N has two operands, where one has an input chain equal to the other,
1429   // the 'other' chain is redundant.
1430   if (N->getNumOperands() == 2) {
1431     if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1432       return N->getOperand(0);
1433     if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1434       return N->getOperand(1);
1435   }
1436
1437   SmallVector<SDNode *, 8> TFs;     // List of token factors to visit.
1438   SmallVector<SDValue, 8> Ops;    // Ops for replacing token factor.
1439   SmallPtrSet<SDNode*, 16> SeenOps;
1440   bool Changed = false;             // If we should replace this token factor.
1441
1442   // Start out with this token factor.
1443   TFs.push_back(N);
1444
1445   // Iterate through token factors.  The TFs grows when new token factors are
1446   // encountered.
1447   for (unsigned i = 0; i < TFs.size(); ++i) {
1448     SDNode *TF = TFs[i];
1449
1450     // Check each of the operands.
1451     for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
1452       SDValue Op = TF->getOperand(i);
1453
1454       switch (Op.getOpcode()) {
1455       case ISD::EntryToken:
1456         // Entry tokens don't need to be added to the list. They are
1457         // rededundant.
1458         Changed = true;
1459         break;
1460
1461       case ISD::TokenFactor:
1462         if (Op.hasOneUse() &&
1463             std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1464           // Queue up for processing.
1465           TFs.push_back(Op.getNode());
1466           // Clean up in case the token factor is removed.
1467           AddToWorklist(Op.getNode());
1468           Changed = true;
1469           break;
1470         }
1471         // Fall thru
1472
1473       default:
1474         // Only add if it isn't already in the list.
1475         if (SeenOps.insert(Op.getNode()))
1476           Ops.push_back(Op);
1477         else
1478           Changed = true;
1479         break;
1480       }
1481     }
1482   }
1483
1484   SDValue Result;
1485
1486   // If we've change things around then replace token factor.
1487   if (Changed) {
1488     if (Ops.empty()) {
1489       // The entry token is the only possible outcome.
1490       Result = DAG.getEntryNode();
1491     } else {
1492       // New and improved token factor.
1493       Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
1494     }
1495
1496     // Don't add users to work list.
1497     return CombineTo(N, Result, false);
1498   }
1499
1500   return Result;
1501 }
1502
1503 /// MERGE_VALUES can always be eliminated.
1504 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1505   WorklistRemover DeadNodes(*this);
1506   // Replacing results may cause a different MERGE_VALUES to suddenly
1507   // be CSE'd with N, and carry its uses with it. Iterate until no
1508   // uses remain, to ensure that the node can be safely deleted.
1509   // First add the users of this node to the work list so that they
1510   // can be tried again once they have new operands.
1511   AddUsersToWorklist(N);
1512   do {
1513     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1514       DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1515   } while (!N->use_empty());
1516   deleteAndRecombine(N);
1517   return SDValue(N, 0);   // Return N so it doesn't get rechecked!
1518 }
1519
1520 static
1521 SDValue combineShlAddConstant(SDLoc DL, SDValue N0, SDValue N1,
1522                               SelectionDAG &DAG) {
1523   EVT VT = N0.getValueType();
1524   SDValue N00 = N0.getOperand(0);
1525   SDValue N01 = N0.getOperand(1);
1526   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N01);
1527
1528   if (N01C && N00.getOpcode() == ISD::ADD && N00.getNode()->hasOneUse() &&
1529       isa<ConstantSDNode>(N00.getOperand(1))) {
1530     // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1531     N0 = DAG.getNode(ISD::ADD, SDLoc(N0), VT,
1532                      DAG.getNode(ISD::SHL, SDLoc(N00), VT,
1533                                  N00.getOperand(0), N01),
1534                      DAG.getNode(ISD::SHL, SDLoc(N01), VT,
1535                                  N00.getOperand(1), N01));
1536     return DAG.getNode(ISD::ADD, DL, VT, N0, N1);
1537   }
1538
1539   return SDValue();
1540 }
1541
1542 SDValue DAGCombiner::visitADD(SDNode *N) {
1543   SDValue N0 = N->getOperand(0);
1544   SDValue N1 = N->getOperand(1);
1545   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1546   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1547   EVT VT = N0.getValueType();
1548
1549   // fold vector ops
1550   if (VT.isVector()) {
1551     SDValue FoldedVOp = SimplifyVBinOp(N);
1552     if (FoldedVOp.getNode()) return FoldedVOp;
1553
1554     // fold (add x, 0) -> x, vector edition
1555     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1556       return N0;
1557     if (ISD::isBuildVectorAllZeros(N0.getNode()))
1558       return N1;
1559   }
1560
1561   // fold (add x, undef) -> undef
1562   if (N0.getOpcode() == ISD::UNDEF)
1563     return N0;
1564   if (N1.getOpcode() == ISD::UNDEF)
1565     return N1;
1566   // fold (add c1, c2) -> c1+c2
1567   if (N0C && N1C)
1568     return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C);
1569   // canonicalize constant to RHS
1570   if (N0C && !N1C)
1571     return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
1572   // fold (add x, 0) -> x
1573   if (N1C && N1C->isNullValue())
1574     return N0;
1575   // fold (add Sym, c) -> Sym+c
1576   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1577     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1578         GA->getOpcode() == ISD::GlobalAddress)
1579       return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1580                                   GA->getOffset() +
1581                                     (uint64_t)N1C->getSExtValue());
1582   // fold ((c1-A)+c2) -> (c1+c2)-A
1583   if (N1C && N0.getOpcode() == ISD::SUB)
1584     if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
1585       return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1586                          DAG.getConstant(N1C->getAPIntValue()+
1587                                          N0C->getAPIntValue(), VT),
1588                          N0.getOperand(1));
1589   // reassociate add
1590   SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1);
1591   if (RADD.getNode())
1592     return RADD;
1593   // fold ((0-A) + B) -> B-A
1594   if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
1595       cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
1596     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
1597   // fold (A + (0-B)) -> A-B
1598   if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1599       cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
1600     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
1601   // fold (A+(B-A)) -> B
1602   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1603     return N1.getOperand(0);
1604   // fold ((B-A)+A) -> B
1605   if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1606     return N0.getOperand(0);
1607   // fold (A+(B-(A+C))) to (B-C)
1608   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1609       N0 == N1.getOperand(1).getOperand(0))
1610     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1611                        N1.getOperand(1).getOperand(1));
1612   // fold (A+(B-(C+A))) to (B-C)
1613   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1614       N0 == N1.getOperand(1).getOperand(1))
1615     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1616                        N1.getOperand(1).getOperand(0));
1617   // fold (A+((B-A)+or-C)) to (B+or-C)
1618   if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1619       N1.getOperand(0).getOpcode() == ISD::SUB &&
1620       N0 == N1.getOperand(0).getOperand(1))
1621     return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
1622                        N1.getOperand(0).getOperand(0), N1.getOperand(1));
1623
1624   // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1625   if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1626     SDValue N00 = N0.getOperand(0);
1627     SDValue N01 = N0.getOperand(1);
1628     SDValue N10 = N1.getOperand(0);
1629     SDValue N11 = N1.getOperand(1);
1630
1631     if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1632       return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1633                          DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1634                          DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1635   }
1636
1637   if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1638     return SDValue(N, 0);
1639
1640   // fold (a+b) -> (a|b) iff a and b share no bits.
1641   if (VT.isInteger() && !VT.isVector()) {
1642     APInt LHSZero, LHSOne;
1643     APInt RHSZero, RHSOne;
1644     DAG.computeKnownBits(N0, LHSZero, LHSOne);
1645
1646     if (LHSZero.getBoolValue()) {
1647       DAG.computeKnownBits(N1, RHSZero, RHSOne);
1648
1649       // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1650       // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1651       if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){
1652         if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT))
1653           return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1654       }
1655     }
1656   }
1657
1658   // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1659   if (N0.getOpcode() == ISD::SHL && N0.getNode()->hasOneUse()) {
1660     SDValue Result = combineShlAddConstant(SDLoc(N), N0, N1, DAG);
1661     if (Result.getNode()) return Result;
1662   }
1663   if (N1.getOpcode() == ISD::SHL && N1.getNode()->hasOneUse()) {
1664     SDValue Result = combineShlAddConstant(SDLoc(N), N1, N0, DAG);
1665     if (Result.getNode()) return Result;
1666   }
1667
1668   // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1669   if (N1.getOpcode() == ISD::SHL &&
1670       N1.getOperand(0).getOpcode() == ISD::SUB)
1671     if (ConstantSDNode *C =
1672           dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
1673       if (C->getAPIntValue() == 0)
1674         return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1675                            DAG.getNode(ISD::SHL, SDLoc(N), VT,
1676                                        N1.getOperand(0).getOperand(1),
1677                                        N1.getOperand(1)));
1678   if (N0.getOpcode() == ISD::SHL &&
1679       N0.getOperand(0).getOpcode() == ISD::SUB)
1680     if (ConstantSDNode *C =
1681           dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
1682       if (C->getAPIntValue() == 0)
1683         return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1684                            DAG.getNode(ISD::SHL, SDLoc(N), VT,
1685                                        N0.getOperand(0).getOperand(1),
1686                                        N0.getOperand(1)));
1687
1688   if (N1.getOpcode() == ISD::AND) {
1689     SDValue AndOp0 = N1.getOperand(0);
1690     ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1));
1691     unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1692     unsigned DestBits = VT.getScalarType().getSizeInBits();
1693
1694     // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1695     // and similar xforms where the inner op is either ~0 or 0.
1696     if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) {
1697       SDLoc DL(N);
1698       return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1699     }
1700   }
1701
1702   // add (sext i1), X -> sub X, (zext i1)
1703   if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1704       N0.getOperand(0).getValueType() == MVT::i1 &&
1705       !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1706     SDLoc DL(N);
1707     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1708     return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1709   }
1710
1711   return SDValue();
1712 }
1713
1714 SDValue DAGCombiner::visitADDC(SDNode *N) {
1715   SDValue N0 = N->getOperand(0);
1716   SDValue N1 = N->getOperand(1);
1717   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1718   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1719   EVT VT = N0.getValueType();
1720
1721   // If the flag result is dead, turn this into an ADD.
1722   if (!N->hasAnyUseOfValue(1))
1723     return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1724                      DAG.getNode(ISD::CARRY_FALSE,
1725                                  SDLoc(N), MVT::Glue));
1726
1727   // canonicalize constant to RHS.
1728   if (N0C && !N1C)
1729     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1730
1731   // fold (addc x, 0) -> x + no carry out
1732   if (N1C && N1C->isNullValue())
1733     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1734                                         SDLoc(N), MVT::Glue));
1735
1736   // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1737   APInt LHSZero, LHSOne;
1738   APInt RHSZero, RHSOne;
1739   DAG.computeKnownBits(N0, LHSZero, LHSOne);
1740
1741   if (LHSZero.getBoolValue()) {
1742     DAG.computeKnownBits(N1, RHSZero, RHSOne);
1743
1744     // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1745     // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1746     if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1747       return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1748                        DAG.getNode(ISD::CARRY_FALSE,
1749                                    SDLoc(N), MVT::Glue));
1750   }
1751
1752   return SDValue();
1753 }
1754
1755 SDValue DAGCombiner::visitADDE(SDNode *N) {
1756   SDValue N0 = N->getOperand(0);
1757   SDValue N1 = N->getOperand(1);
1758   SDValue CarryIn = N->getOperand(2);
1759   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1760   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1761
1762   // canonicalize constant to RHS
1763   if (N0C && !N1C)
1764     return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1765                        N1, N0, CarryIn);
1766
1767   // fold (adde x, y, false) -> (addc x, y)
1768   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1769     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1770
1771   return SDValue();
1772 }
1773
1774 // Since it may not be valid to emit a fold to zero for vector initializers
1775 // check if we can before folding.
1776 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
1777                              SelectionDAG &DAG,
1778                              bool LegalOperations, bool LegalTypes) {
1779   if (!VT.isVector())
1780     return DAG.getConstant(0, VT);
1781   if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1782     return DAG.getConstant(0, VT);
1783   return SDValue();
1784 }
1785
1786 SDValue DAGCombiner::visitSUB(SDNode *N) {
1787   SDValue N0 = N->getOperand(0);
1788   SDValue N1 = N->getOperand(1);
1789   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1790   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1791   ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr :
1792     dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1793   EVT VT = N0.getValueType();
1794
1795   // fold vector ops
1796   if (VT.isVector()) {
1797     SDValue FoldedVOp = SimplifyVBinOp(N);
1798     if (FoldedVOp.getNode()) return FoldedVOp;
1799
1800     // fold (sub x, 0) -> x, vector edition
1801     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1802       return N0;
1803   }
1804
1805   // fold (sub x, x) -> 0
1806   // FIXME: Refactor this and xor and other similar operations together.
1807   if (N0 == N1)
1808     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
1809   // fold (sub c1, c2) -> c1-c2
1810   if (N0C && N1C)
1811     return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C);
1812   // fold (sub x, c) -> (add x, -c)
1813   if (N1C)
1814     return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0,
1815                        DAG.getConstant(-N1C->getAPIntValue(), VT));
1816   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1817   if (N0C && N0C->isAllOnesValue())
1818     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
1819   // fold A-(A-B) -> B
1820   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1821     return N1.getOperand(1);
1822   // fold (A+B)-A -> B
1823   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1824     return N0.getOperand(1);
1825   // fold (A+B)-B -> A
1826   if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1827     return N0.getOperand(0);
1828   // fold C2-(A+C1) -> (C2-C1)-A
1829   if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1830     SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1831                                    VT);
1832     return DAG.getNode(ISD::SUB, SDLoc(N), VT, NewC,
1833                        N1.getOperand(0));
1834   }
1835   // fold ((A+(B+or-C))-B) -> A+or-C
1836   if (N0.getOpcode() == ISD::ADD &&
1837       (N0.getOperand(1).getOpcode() == ISD::SUB ||
1838        N0.getOperand(1).getOpcode() == ISD::ADD) &&
1839       N0.getOperand(1).getOperand(0) == N1)
1840     return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
1841                        N0.getOperand(0), N0.getOperand(1).getOperand(1));
1842   // fold ((A+(C+B))-B) -> A+C
1843   if (N0.getOpcode() == ISD::ADD &&
1844       N0.getOperand(1).getOpcode() == ISD::ADD &&
1845       N0.getOperand(1).getOperand(1) == N1)
1846     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1847                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1848   // fold ((A-(B-C))-C) -> A-B
1849   if (N0.getOpcode() == ISD::SUB &&
1850       N0.getOperand(1).getOpcode() == ISD::SUB &&
1851       N0.getOperand(1).getOperand(1) == N1)
1852     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1853                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1854
1855   // If either operand of a sub is undef, the result is undef
1856   if (N0.getOpcode() == ISD::UNDEF)
1857     return N0;
1858   if (N1.getOpcode() == ISD::UNDEF)
1859     return N1;
1860
1861   // If the relocation model supports it, consider symbol offsets.
1862   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1863     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1864       // fold (sub Sym, c) -> Sym-c
1865       if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1866         return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1867                                     GA->getOffset() -
1868                                       (uint64_t)N1C->getSExtValue());
1869       // fold (sub Sym+c1, Sym+c2) -> c1-c2
1870       if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1871         if (GA->getGlobal() == GB->getGlobal())
1872           return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1873                                  VT);
1874     }
1875
1876   return SDValue();
1877 }
1878
1879 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1880   SDValue N0 = N->getOperand(0);
1881   SDValue N1 = N->getOperand(1);
1882   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1883   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1884   EVT VT = N0.getValueType();
1885
1886   // If the flag result is dead, turn this into an SUB.
1887   if (!N->hasAnyUseOfValue(1))
1888     return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1889                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1890                                  MVT::Glue));
1891
1892   // fold (subc x, x) -> 0 + no borrow
1893   if (N0 == N1)
1894     return CombineTo(N, DAG.getConstant(0, VT),
1895                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1896                                  MVT::Glue));
1897
1898   // fold (subc x, 0) -> x + no borrow
1899   if (N1C && N1C->isNullValue())
1900     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1901                                         MVT::Glue));
1902
1903   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1904   if (N0C && N0C->isAllOnesValue())
1905     return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
1906                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1907                                  MVT::Glue));
1908
1909   return SDValue();
1910 }
1911
1912 SDValue DAGCombiner::visitSUBE(SDNode *N) {
1913   SDValue N0 = N->getOperand(0);
1914   SDValue N1 = N->getOperand(1);
1915   SDValue CarryIn = N->getOperand(2);
1916
1917   // fold (sube x, y, false) -> (subc x, y)
1918   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1919     return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
1920
1921   return SDValue();
1922 }
1923
1924 SDValue DAGCombiner::visitMUL(SDNode *N) {
1925   SDValue N0 = N->getOperand(0);
1926   SDValue N1 = N->getOperand(1);
1927   EVT VT = N0.getValueType();
1928
1929   // fold (mul x, undef) -> 0
1930   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1931     return DAG.getConstant(0, VT);
1932
1933   bool N0IsConst = false;
1934   bool N1IsConst = false;
1935   APInt ConstValue0, ConstValue1;
1936   // fold vector ops
1937   if (VT.isVector()) {
1938     SDValue FoldedVOp = SimplifyVBinOp(N);
1939     if (FoldedVOp.getNode()) return FoldedVOp;
1940
1941     N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
1942     N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
1943   } else {
1944     N0IsConst = dyn_cast<ConstantSDNode>(N0) != nullptr;
1945     ConstValue0 = N0IsConst ? (dyn_cast<ConstantSDNode>(N0))->getAPIntValue()
1946                             : APInt();
1947     N1IsConst = dyn_cast<ConstantSDNode>(N1) != nullptr;
1948     ConstValue1 = N1IsConst ? (dyn_cast<ConstantSDNode>(N1))->getAPIntValue()
1949                             : APInt();
1950   }
1951
1952   // fold (mul c1, c2) -> c1*c2
1953   if (N0IsConst && N1IsConst)
1954     return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0.getNode(), N1.getNode());
1955
1956   // canonicalize constant to RHS
1957   if (N0IsConst && !N1IsConst)
1958     return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
1959   // fold (mul x, 0) -> 0
1960   if (N1IsConst && ConstValue1 == 0)
1961     return N1;
1962   // We require a splat of the entire scalar bit width for non-contiguous
1963   // bit patterns.
1964   bool IsFullSplat =
1965     ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
1966   // fold (mul x, 1) -> x
1967   if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
1968     return N0;
1969   // fold (mul x, -1) -> 0-x
1970   if (N1IsConst && ConstValue1.isAllOnesValue())
1971     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1972                        DAG.getConstant(0, VT), N0);
1973   // fold (mul x, (1 << c)) -> x << c
1974   if (N1IsConst && ConstValue1.isPowerOf2() && IsFullSplat)
1975     return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1976                        DAG.getConstant(ConstValue1.logBase2(),
1977                                        getShiftAmountTy(N0.getValueType())));
1978   // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
1979   if (N1IsConst && (-ConstValue1).isPowerOf2() && IsFullSplat) {
1980     unsigned Log2Val = (-ConstValue1).logBase2();
1981     // FIXME: If the input is something that is easily negated (e.g. a
1982     // single-use add), we should put the negate there.
1983     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1984                        DAG.getConstant(0, VT),
1985                        DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1986                             DAG.getConstant(Log2Val,
1987                                       getShiftAmountTy(N0.getValueType()))));
1988   }
1989
1990   APInt Val;
1991   // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
1992   if (N1IsConst && N0.getOpcode() == ISD::SHL &&
1993       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1994                      isa<ConstantSDNode>(N0.getOperand(1)))) {
1995     SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
1996                              N1, N0.getOperand(1));
1997     AddToWorklist(C3.getNode());
1998     return DAG.getNode(ISD::MUL, SDLoc(N), VT,
1999                        N0.getOperand(0), C3);
2000   }
2001
2002   // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
2003   // use.
2004   {
2005     SDValue Sh(nullptr,0), Y(nullptr,0);
2006     // Check for both (mul (shl X, C), Y)  and  (mul Y, (shl X, C)).
2007     if (N0.getOpcode() == ISD::SHL &&
2008         (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2009                        isa<ConstantSDNode>(N0.getOperand(1))) &&
2010         N0.getNode()->hasOneUse()) {
2011       Sh = N0; Y = N1;
2012     } else if (N1.getOpcode() == ISD::SHL &&
2013                isa<ConstantSDNode>(N1.getOperand(1)) &&
2014                N1.getNode()->hasOneUse()) {
2015       Sh = N1; Y = N0;
2016     }
2017
2018     if (Sh.getNode()) {
2019       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2020                                 Sh.getOperand(0), Y);
2021       return DAG.getNode(ISD::SHL, SDLoc(N), VT,
2022                          Mul, Sh.getOperand(1));
2023     }
2024   }
2025
2026   // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
2027   if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
2028       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2029                      isa<ConstantSDNode>(N0.getOperand(1))))
2030     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
2031                        DAG.getNode(ISD::MUL, SDLoc(N0), VT,
2032                                    N0.getOperand(0), N1),
2033                        DAG.getNode(ISD::MUL, SDLoc(N1), VT,
2034                                    N0.getOperand(1), N1));
2035
2036   // reassociate mul
2037   SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1);
2038   if (RMUL.getNode())
2039     return RMUL;
2040
2041   return SDValue();
2042 }
2043
2044 SDValue DAGCombiner::visitSDIV(SDNode *N) {
2045   SDValue N0 = N->getOperand(0);
2046   SDValue N1 = N->getOperand(1);
2047   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2048   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2049   EVT VT = N->getValueType(0);
2050
2051   // fold vector ops
2052   if (VT.isVector()) {
2053     SDValue FoldedVOp = SimplifyVBinOp(N);
2054     if (FoldedVOp.getNode()) return FoldedVOp;
2055   }
2056
2057   // fold (sdiv c1, c2) -> c1/c2
2058   if (N0C && N1C && !N1C->isNullValue())
2059     return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C);
2060   // fold (sdiv X, 1) -> X
2061   if (N1C && N1C->getAPIntValue() == 1LL)
2062     return N0;
2063   // fold (sdiv X, -1) -> 0-X
2064   if (N1C && N1C->isAllOnesValue())
2065     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
2066                        DAG.getConstant(0, VT), N0);
2067   // If we know the sign bits of both operands are zero, strength reduce to a
2068   // udiv instead.  Handles (X&15) /s 4 -> X&15 >> 2
2069   if (!VT.isVector()) {
2070     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2071       return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
2072                          N0, N1);
2073   }
2074
2075   // fold (sdiv X, pow2) -> simple ops after legalize
2076   if (N1C && !N1C->isNullValue() && (N1C->getAPIntValue().isPowerOf2() ||
2077                                      (-N1C->getAPIntValue()).isPowerOf2())) {
2078     // If dividing by powers of two is cheap, then don't perform the following
2079     // fold.
2080     if (TLI.isPow2SDivCheap())
2081       return SDValue();
2082
2083     // Target-specific implementation of sdiv x, pow2.
2084     SDValue Res = BuildSDIVPow2(N);
2085     if (Res.getNode())
2086       return Res;
2087
2088     unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
2089
2090     // Splat the sign bit into the register
2091     SDValue SGN =
2092         DAG.getNode(ISD::SRA, SDLoc(N), VT, N0,
2093                     DAG.getConstant(VT.getScalarSizeInBits() - 1,
2094                                     getShiftAmountTy(N0.getValueType())));
2095     AddToWorklist(SGN.getNode());
2096
2097     // Add (N0 < 0) ? abs2 - 1 : 0;
2098     SDValue SRL =
2099         DAG.getNode(ISD::SRL, SDLoc(N), VT, SGN,
2100                     DAG.getConstant(VT.getScalarSizeInBits() - lg2,
2101                                     getShiftAmountTy(SGN.getValueType())));
2102     SDValue ADD = DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, SRL);
2103     AddToWorklist(SRL.getNode());
2104     AddToWorklist(ADD.getNode());    // Divide by pow2
2105     SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), VT, ADD,
2106                   DAG.getConstant(lg2, getShiftAmountTy(ADD.getValueType())));
2107
2108     // If we're dividing by a positive value, we're done.  Otherwise, we must
2109     // negate the result.
2110     if (N1C->getAPIntValue().isNonNegative())
2111       return SRA;
2112
2113     AddToWorklist(SRA.getNode());
2114     return DAG.getNode(ISD::SUB, SDLoc(N), VT, DAG.getConstant(0, VT), SRA);
2115   }
2116
2117   // if integer divide is expensive and we satisfy the requirements, emit an
2118   // alternate sequence.
2119   if (N1C && !TLI.isIntDivCheap()) {
2120     SDValue Op = BuildSDIV(N);
2121     if (Op.getNode()) return Op;
2122   }
2123
2124   // undef / X -> 0
2125   if (N0.getOpcode() == ISD::UNDEF)
2126     return DAG.getConstant(0, VT);
2127   // X / undef -> undef
2128   if (N1.getOpcode() == ISD::UNDEF)
2129     return N1;
2130
2131   return SDValue();
2132 }
2133
2134 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2135   SDValue N0 = N->getOperand(0);
2136   SDValue N1 = N->getOperand(1);
2137   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2138   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2139   EVT VT = N->getValueType(0);
2140
2141   // fold vector ops
2142   if (VT.isVector()) {
2143     SDValue FoldedVOp = SimplifyVBinOp(N);
2144     if (FoldedVOp.getNode()) return FoldedVOp;
2145   }
2146
2147   // fold (udiv c1, c2) -> c1/c2
2148   if (N0C && N1C && !N1C->isNullValue())
2149     return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C);
2150   // fold (udiv x, (1 << c)) -> x >>u c
2151   if (N1C && N1C->getAPIntValue().isPowerOf2())
2152     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0,
2153                        DAG.getConstant(N1C->getAPIntValue().logBase2(),
2154                                        getShiftAmountTy(N0.getValueType())));
2155   // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2156   if (N1.getOpcode() == ISD::SHL) {
2157     if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2158       if (SHC->getAPIntValue().isPowerOf2()) {
2159         EVT ADDVT = N1.getOperand(1).getValueType();
2160         SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N), ADDVT,
2161                                   N1.getOperand(1),
2162                                   DAG.getConstant(SHC->getAPIntValue()
2163                                                                   .logBase2(),
2164                                                   ADDVT));
2165         AddToWorklist(Add.getNode());
2166         return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, Add);
2167       }
2168     }
2169   }
2170   // fold (udiv x, c) -> alternate
2171   if (N1C && !TLI.isIntDivCheap()) {
2172     SDValue Op = BuildUDIV(N);
2173     if (Op.getNode()) return Op;
2174   }
2175
2176   // undef / X -> 0
2177   if (N0.getOpcode() == ISD::UNDEF)
2178     return DAG.getConstant(0, VT);
2179   // X / undef -> undef
2180   if (N1.getOpcode() == ISD::UNDEF)
2181     return N1;
2182
2183   return SDValue();
2184 }
2185
2186 SDValue DAGCombiner::visitSREM(SDNode *N) {
2187   SDValue N0 = N->getOperand(0);
2188   SDValue N1 = N->getOperand(1);
2189   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2190   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2191   EVT VT = N->getValueType(0);
2192
2193   // fold (srem c1, c2) -> c1%c2
2194   if (N0C && N1C && !N1C->isNullValue())
2195     return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C);
2196   // If we know the sign bits of both operands are zero, strength reduce to a
2197   // urem instead.  Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2198   if (!VT.isVector()) {
2199     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2200       return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
2201   }
2202
2203   // If X/C can be simplified by the division-by-constant logic, lower
2204   // X%C to the equivalent of X-X/C*C.
2205   if (N1C && !N1C->isNullValue()) {
2206     SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
2207     AddToWorklist(Div.getNode());
2208     SDValue OptimizedDiv = combine(Div.getNode());
2209     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2210       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2211                                 OptimizedDiv, N1);
2212       SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2213       AddToWorklist(Mul.getNode());
2214       return Sub;
2215     }
2216   }
2217
2218   // undef % X -> 0
2219   if (N0.getOpcode() == ISD::UNDEF)
2220     return DAG.getConstant(0, VT);
2221   // X % undef -> undef
2222   if (N1.getOpcode() == ISD::UNDEF)
2223     return N1;
2224
2225   return SDValue();
2226 }
2227
2228 SDValue DAGCombiner::visitUREM(SDNode *N) {
2229   SDValue N0 = N->getOperand(0);
2230   SDValue N1 = N->getOperand(1);
2231   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2232   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2233   EVT VT = N->getValueType(0);
2234
2235   // fold (urem c1, c2) -> c1%c2
2236   if (N0C && N1C && !N1C->isNullValue())
2237     return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C);
2238   // fold (urem x, pow2) -> (and x, pow2-1)
2239   if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
2240     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0,
2241                        DAG.getConstant(N1C->getAPIntValue()-1,VT));
2242   // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2243   if (N1.getOpcode() == ISD::SHL) {
2244     if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2245       if (SHC->getAPIntValue().isPowerOf2()) {
2246         SDValue Add =
2247           DAG.getNode(ISD::ADD, SDLoc(N), VT, N1,
2248                  DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
2249                                  VT));
2250         AddToWorklist(Add.getNode());
2251         return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, Add);
2252       }
2253     }
2254   }
2255
2256   // If X/C can be simplified by the division-by-constant logic, lower
2257   // X%C to the equivalent of X-X/C*C.
2258   if (N1C && !N1C->isNullValue()) {
2259     SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
2260     AddToWorklist(Div.getNode());
2261     SDValue OptimizedDiv = combine(Div.getNode());
2262     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2263       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2264                                 OptimizedDiv, N1);
2265       SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2266       AddToWorklist(Mul.getNode());
2267       return Sub;
2268     }
2269   }
2270
2271   // undef % X -> 0
2272   if (N0.getOpcode() == ISD::UNDEF)
2273     return DAG.getConstant(0, VT);
2274   // X % undef -> undef
2275   if (N1.getOpcode() == ISD::UNDEF)
2276     return N1;
2277
2278   return SDValue();
2279 }
2280
2281 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2282   SDValue N0 = N->getOperand(0);
2283   SDValue N1 = N->getOperand(1);
2284   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2285   EVT VT = N->getValueType(0);
2286   SDLoc DL(N);
2287
2288   // fold (mulhs x, 0) -> 0
2289   if (N1C && N1C->isNullValue())
2290     return N1;
2291   // fold (mulhs x, 1) -> (sra x, size(x)-1)
2292   if (N1C && N1C->getAPIntValue() == 1)
2293     return DAG.getNode(ISD::SRA, SDLoc(N), N0.getValueType(), N0,
2294                        DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2295                                        getShiftAmountTy(N0.getValueType())));
2296   // fold (mulhs x, undef) -> 0
2297   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2298     return DAG.getConstant(0, VT);
2299
2300   // If the type twice as wide is legal, transform the mulhs to a wider multiply
2301   // plus a shift.
2302   if (VT.isSimple() && !VT.isVector()) {
2303     MVT Simple = VT.getSimpleVT();
2304     unsigned SimpleSize = Simple.getSizeInBits();
2305     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2306     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2307       N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2308       N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2309       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2310       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2311             DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2312       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2313     }
2314   }
2315
2316   return SDValue();
2317 }
2318
2319 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2320   SDValue N0 = N->getOperand(0);
2321   SDValue N1 = N->getOperand(1);
2322   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2323   EVT VT = N->getValueType(0);
2324   SDLoc DL(N);
2325
2326   // fold (mulhu x, 0) -> 0
2327   if (N1C && N1C->isNullValue())
2328     return N1;
2329   // fold (mulhu x, 1) -> 0
2330   if (N1C && N1C->getAPIntValue() == 1)
2331     return DAG.getConstant(0, N0.getValueType());
2332   // fold (mulhu x, undef) -> 0
2333   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2334     return DAG.getConstant(0, VT);
2335
2336   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2337   // plus a shift.
2338   if (VT.isSimple() && !VT.isVector()) {
2339     MVT Simple = VT.getSimpleVT();
2340     unsigned SimpleSize = Simple.getSizeInBits();
2341     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2342     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2343       N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2344       N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2345       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2346       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2347             DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2348       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2349     }
2350   }
2351
2352   return SDValue();
2353 }
2354
2355 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp
2356 /// give the opcodes for the two computations that are being performed. Return
2357 /// true if a simplification was made.
2358 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2359                                                 unsigned HiOp) {
2360   // If the high half is not needed, just compute the low half.
2361   bool HiExists = N->hasAnyUseOfValue(1);
2362   if (!HiExists &&
2363       (!LegalOperations ||
2364        TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
2365     SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2366     return CombineTo(N, Res, Res);
2367   }
2368
2369   // If the low half is not needed, just compute the high half.
2370   bool LoExists = N->hasAnyUseOfValue(0);
2371   if (!LoExists &&
2372       (!LegalOperations ||
2373        TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2374     SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2375     return CombineTo(N, Res, Res);
2376   }
2377
2378   // If both halves are used, return as it is.
2379   if (LoExists && HiExists)
2380     return SDValue();
2381
2382   // If the two computed results can be simplified separately, separate them.
2383   if (LoExists) {
2384     SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2385     AddToWorklist(Lo.getNode());
2386     SDValue LoOpt = combine(Lo.getNode());
2387     if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2388         (!LegalOperations ||
2389          TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2390       return CombineTo(N, LoOpt, LoOpt);
2391   }
2392
2393   if (HiExists) {
2394     SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2395     AddToWorklist(Hi.getNode());
2396     SDValue HiOpt = combine(Hi.getNode());
2397     if (HiOpt.getNode() && HiOpt != Hi &&
2398         (!LegalOperations ||
2399          TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2400       return CombineTo(N, HiOpt, HiOpt);
2401   }
2402
2403   return SDValue();
2404 }
2405
2406 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2407   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
2408   if (Res.getNode()) return Res;
2409
2410   EVT VT = N->getValueType(0);
2411   SDLoc DL(N);
2412
2413   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2414   // plus a shift.
2415   if (VT.isSimple() && !VT.isVector()) {
2416     MVT Simple = VT.getSimpleVT();
2417     unsigned SimpleSize = Simple.getSizeInBits();
2418     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2419     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2420       SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2421       SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2422       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2423       // Compute the high part as N1.
2424       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2425             DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2426       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2427       // Compute the low part as N0.
2428       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2429       return CombineTo(N, Lo, Hi);
2430     }
2431   }
2432
2433   return SDValue();
2434 }
2435
2436 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2437   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
2438   if (Res.getNode()) return Res;
2439
2440   EVT VT = N->getValueType(0);
2441   SDLoc DL(N);
2442
2443   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2444   // plus a shift.
2445   if (VT.isSimple() && !VT.isVector()) {
2446     MVT Simple = VT.getSimpleVT();
2447     unsigned SimpleSize = Simple.getSizeInBits();
2448     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2449     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2450       SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2451       SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2452       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2453       // Compute the high part as N1.
2454       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2455             DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2456       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2457       // Compute the low part as N0.
2458       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2459       return CombineTo(N, Lo, Hi);
2460     }
2461   }
2462
2463   return SDValue();
2464 }
2465
2466 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2467   // (smulo x, 2) -> (saddo x, x)
2468   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2469     if (C2->getAPIntValue() == 2)
2470       return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2471                          N->getOperand(0), N->getOperand(0));
2472
2473   return SDValue();
2474 }
2475
2476 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2477   // (umulo x, 2) -> (uaddo x, x)
2478   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2479     if (C2->getAPIntValue() == 2)
2480       return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2481                          N->getOperand(0), N->getOperand(0));
2482
2483   return SDValue();
2484 }
2485
2486 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2487   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
2488   if (Res.getNode()) return Res;
2489
2490   return SDValue();
2491 }
2492
2493 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2494   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
2495   if (Res.getNode()) return Res;
2496
2497   return SDValue();
2498 }
2499
2500 /// If this is a binary operator with two operands of the same opcode, try to
2501 /// simplify it.
2502 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2503   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2504   EVT VT = N0.getValueType();
2505   assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2506
2507   // Bail early if none of these transforms apply.
2508   if (N0.getNode()->getNumOperands() == 0) return SDValue();
2509
2510   // For each of OP in AND/OR/XOR:
2511   // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2512   // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2513   // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2514   // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2515   //
2516   // do not sink logical op inside of a vector extend, since it may combine
2517   // into a vsetcc.
2518   EVT Op0VT = N0.getOperand(0).getValueType();
2519   if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2520        N0.getOpcode() == ISD::SIGN_EXTEND ||
2521        // Avoid infinite looping with PromoteIntBinOp.
2522        (N0.getOpcode() == ISD::ANY_EXTEND &&
2523         (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2524        (N0.getOpcode() == ISD::TRUNCATE &&
2525         (!TLI.isZExtFree(VT, Op0VT) ||
2526          !TLI.isTruncateFree(Op0VT, VT)) &&
2527         TLI.isTypeLegal(Op0VT))) &&
2528       !VT.isVector() &&
2529       Op0VT == N1.getOperand(0).getValueType() &&
2530       (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2531     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2532                                  N0.getOperand(0).getValueType(),
2533                                  N0.getOperand(0), N1.getOperand(0));
2534     AddToWorklist(ORNode.getNode());
2535     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2536   }
2537
2538   // For each of OP in SHL/SRL/SRA/AND...
2539   //   fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2540   //   fold (or  (OP x, z), (OP y, z)) -> (OP (or  x, y), z)
2541   //   fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2542   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2543        N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2544       N0.getOperand(1) == N1.getOperand(1)) {
2545     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2546                                  N0.getOperand(0).getValueType(),
2547                                  N0.getOperand(0), N1.getOperand(0));
2548     AddToWorklist(ORNode.getNode());
2549     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2550                        ORNode, N0.getOperand(1));
2551   }
2552
2553   // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2554   // Only perform this optimization after type legalization and before
2555   // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2556   // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2557   // we don't want to undo this promotion.
2558   // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2559   // on scalars.
2560   if ((N0.getOpcode() == ISD::BITCAST ||
2561        N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2562       Level == AfterLegalizeTypes) {
2563     SDValue In0 = N0.getOperand(0);
2564     SDValue In1 = N1.getOperand(0);
2565     EVT In0Ty = In0.getValueType();
2566     EVT In1Ty = In1.getValueType();
2567     SDLoc DL(N);
2568     // If both incoming values are integers, and the original types are the
2569     // same.
2570     if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2571       SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2572       SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2573       AddToWorklist(Op.getNode());
2574       return BC;
2575     }
2576   }
2577
2578   // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2579   // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2580   // If both shuffles use the same mask, and both shuffle within a single
2581   // vector, then it is worthwhile to move the swizzle after the operation.
2582   // The type-legalizer generates this pattern when loading illegal
2583   // vector types from memory. In many cases this allows additional shuffle
2584   // optimizations.
2585   // There are other cases where moving the shuffle after the xor/and/or
2586   // is profitable even if shuffles don't perform a swizzle.
2587   // If both shuffles use the same mask, and both shuffles have the same first
2588   // or second operand, then it might still be profitable to move the shuffle
2589   // after the xor/and/or operation.
2590   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
2591     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2592     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2593
2594     assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
2595            "Inputs to shuffles are not the same type");
2596
2597     // Check that both shuffles use the same mask. The masks are known to be of
2598     // the same length because the result vector type is the same.
2599     // Check also that shuffles have only one use to avoid introducing extra
2600     // instructions.
2601     if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2602         SVN0->getMask().equals(SVN1->getMask())) {
2603       SDValue ShOp = N0->getOperand(1);
2604
2605       // Don't try to fold this node if it requires introducing a
2606       // build vector of all zeros that might be illegal at this stage.
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 (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2615       // (OR  (shuf (A, C), shuf (B, C)) -> shuf (OR  (A, B), C)
2616       // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2617       if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2618         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2619                                       N0->getOperand(0), N1->getOperand(0));
2620         AddToWorklist(NewNode.getNode());
2621         return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2622                                     &SVN0->getMask()[0]);
2623       }
2624
2625       // Don't try to fold this node if it requires introducing a
2626       // build vector of all zeros that might be illegal at this stage.
2627       ShOp = N0->getOperand(0);
2628       if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2629         if (!LegalTypes)
2630           ShOp = DAG.getConstant(0, VT);
2631         else
2632           ShOp = SDValue();
2633       }
2634
2635       // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2636       // (OR  (shuf (C, A), shuf (C, B)) -> shuf (C, OR  (A, B))
2637       // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2638       if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2639         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2640                                       N0->getOperand(1), N1->getOperand(1));
2641         AddToWorklist(NewNode.getNode());
2642         return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2643                                     &SVN0->getMask()[0]);
2644       }
2645     }
2646   }
2647
2648   return SDValue();
2649 }
2650
2651 SDValue DAGCombiner::visitAND(SDNode *N) {
2652   SDValue N0 = N->getOperand(0);
2653   SDValue N1 = N->getOperand(1);
2654   SDValue LL, LR, RL, RR, CC0, CC1;
2655   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2656   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2657   EVT VT = N1.getValueType();
2658   unsigned BitWidth = VT.getScalarType().getSizeInBits();
2659
2660   // fold vector ops
2661   if (VT.isVector()) {
2662     SDValue FoldedVOp = SimplifyVBinOp(N);
2663     if (FoldedVOp.getNode()) return FoldedVOp;
2664
2665     // fold (and x, 0) -> 0, vector edition
2666     if (ISD::isBuildVectorAllZeros(N0.getNode()))
2667       return N0;
2668     if (ISD::isBuildVectorAllZeros(N1.getNode()))
2669       return N1;
2670
2671     // fold (and x, -1) -> x, vector edition
2672     if (ISD::isBuildVectorAllOnes(N0.getNode()))
2673       return N1;
2674     if (ISD::isBuildVectorAllOnes(N1.getNode()))
2675       return N0;
2676   }
2677
2678   // fold (and x, undef) -> 0
2679   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2680     return DAG.getConstant(0, VT);
2681   // fold (and c1, c2) -> c1&c2
2682   if (N0C && N1C)
2683     return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C);
2684   // canonicalize constant to RHS
2685   if (N0C && !N1C)
2686     return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
2687   // fold (and x, -1) -> x
2688   if (N1C && N1C->isAllOnesValue())
2689     return N0;
2690   // if (and x, c) is known to be zero, return 0
2691   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2692                                    APInt::getAllOnesValue(BitWidth)))
2693     return DAG.getConstant(0, VT);
2694   // reassociate and
2695   SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1);
2696   if (RAND.getNode())
2697     return RAND;
2698   // fold (and (or x, C), D) -> D if (C & D) == D
2699   if (N1C && N0.getOpcode() == ISD::OR)
2700     if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2701       if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2702         return N1;
2703   // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2704   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2705     SDValue N0Op0 = N0.getOperand(0);
2706     APInt Mask = ~N1C->getAPIntValue();
2707     Mask = Mask.trunc(N0Op0.getValueSizeInBits());
2708     if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2709       SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
2710                                  N0.getValueType(), N0Op0);
2711
2712       // Replace uses of the AND with uses of the Zero extend node.
2713       CombineTo(N, Zext);
2714
2715       // We actually want to replace all uses of the any_extend with the
2716       // zero_extend, to avoid duplicating things.  This will later cause this
2717       // AND to be folded.
2718       CombineTo(N0.getNode(), Zext);
2719       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2720     }
2721   }
2722   // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
2723   // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2724   // already be zero by virtue of the width of the base type of the load.
2725   //
2726   // the 'X' node here can either be nothing or an extract_vector_elt to catch
2727   // more cases.
2728   if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2729        N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2730       N0.getOpcode() == ISD::LOAD) {
2731     LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2732                                          N0 : N0.getOperand(0) );
2733
2734     // Get the constant (if applicable) the zero'th operand is being ANDed with.
2735     // This can be a pure constant or a vector splat, in which case we treat the
2736     // vector as a scalar and use the splat value.
2737     APInt Constant = APInt::getNullValue(1);
2738     if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2739       Constant = C->getAPIntValue();
2740     } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2741       APInt SplatValue, SplatUndef;
2742       unsigned SplatBitSize;
2743       bool HasAnyUndefs;
2744       bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2745                                              SplatBitSize, HasAnyUndefs);
2746       if (IsSplat) {
2747         // Undef bits can contribute to a possible optimisation if set, so
2748         // set them.
2749         SplatValue |= SplatUndef;
2750
2751         // The splat value may be something like "0x00FFFFFF", which means 0 for
2752         // the first vector value and FF for the rest, repeating. We need a mask
2753         // that will apply equally to all members of the vector, so AND all the
2754         // lanes of the constant together.
2755         EVT VT = Vector->getValueType(0);
2756         unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
2757
2758         // If the splat value has been compressed to a bitlength lower
2759         // than the size of the vector lane, we need to re-expand it to
2760         // the lane size.
2761         if (BitWidth > SplatBitSize)
2762           for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
2763                SplatBitSize < BitWidth;
2764                SplatBitSize = SplatBitSize * 2)
2765             SplatValue |= SplatValue.shl(SplatBitSize);
2766
2767         Constant = APInt::getAllOnesValue(BitWidth);
2768         for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
2769           Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
2770       }
2771     }
2772
2773     // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
2774     // actually legal and isn't going to get expanded, else this is a false
2775     // optimisation.
2776     bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
2777                                                     Load->getMemoryVT());
2778
2779     // Resize the constant to the same size as the original memory access before
2780     // extension. If it is still the AllOnesValue then this AND is completely
2781     // unneeded.
2782     Constant =
2783       Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
2784
2785     bool B;
2786     switch (Load->getExtensionType()) {
2787     default: B = false; break;
2788     case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
2789     case ISD::ZEXTLOAD:
2790     case ISD::NON_EXTLOAD: B = true; break;
2791     }
2792
2793     if (B && Constant.isAllOnesValue()) {
2794       // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
2795       // preserve semantics once we get rid of the AND.
2796       SDValue NewLoad(Load, 0);
2797       if (Load->getExtensionType() == ISD::EXTLOAD) {
2798         NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
2799                               Load->getValueType(0), SDLoc(Load),
2800                               Load->getChain(), Load->getBasePtr(),
2801                               Load->getOffset(), Load->getMemoryVT(),
2802                               Load->getMemOperand());
2803         // Replace uses of the EXTLOAD with the new ZEXTLOAD.
2804         if (Load->getNumValues() == 3) {
2805           // PRE/POST_INC loads have 3 values.
2806           SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
2807                            NewLoad.getValue(2) };
2808           CombineTo(Load, To, 3, true);
2809         } else {
2810           CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
2811         }
2812       }
2813
2814       // Fold the AND away, taking care not to fold to the old load node if we
2815       // replaced it.
2816       CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
2817
2818       return SDValue(N, 0); // Return N so it doesn't get rechecked!
2819     }
2820   }
2821   // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2822   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2823     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2824     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2825
2826     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2827         LL.getValueType().isInteger()) {
2828       // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2829       if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
2830         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2831                                      LR.getValueType(), LL, RL);
2832         AddToWorklist(ORNode.getNode());
2833         return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2834       }
2835       // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2836       if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
2837         SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2838                                       LR.getValueType(), LL, RL);
2839         AddToWorklist(ANDNode.getNode());
2840         return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
2841       }
2842       // fold (and (setgt X,  -1), (setgt Y,  -1)) -> (setgt (or X, Y), -1)
2843       if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
2844         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2845                                      LR.getValueType(), LL, RL);
2846         AddToWorklist(ORNode.getNode());
2847         return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2848       }
2849     }
2850     // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2851     if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2852         Op0 == Op1 && LL.getValueType().isInteger() &&
2853       Op0 == ISD::SETNE && ((cast<ConstantSDNode>(LR)->isNullValue() &&
2854                                  cast<ConstantSDNode>(RR)->isAllOnesValue()) ||
2855                                 (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
2856                                  cast<ConstantSDNode>(RR)->isNullValue()))) {
2857       SDValue ADDNode = DAG.getNode(ISD::ADD, SDLoc(N0), LL.getValueType(),
2858                                     LL, DAG.getConstant(1, LL.getValueType()));
2859       AddToWorklist(ADDNode.getNode());
2860       return DAG.getSetCC(SDLoc(N), VT, ADDNode,
2861                           DAG.getConstant(2, LL.getValueType()), ISD::SETUGE);
2862     }
2863     // canonicalize equivalent to ll == rl
2864     if (LL == RR && LR == RL) {
2865       Op1 = ISD::getSetCCSwappedOperands(Op1);
2866       std::swap(RL, RR);
2867     }
2868     if (LL == RL && LR == RR) {
2869       bool isInteger = LL.getValueType().isInteger();
2870       ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2871       if (Result != ISD::SETCC_INVALID &&
2872           (!LegalOperations ||
2873            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2874             TLI.isOperationLegal(ISD::SETCC,
2875                             getSetCCResultType(N0.getSimpleValueType())))))
2876         return DAG.getSetCC(SDLoc(N), N0.getValueType(),
2877                             LL, LR, Result);
2878     }
2879   }
2880
2881   // Simplify: (and (op x...), (op y...))  -> (op (and x, y))
2882   if (N0.getOpcode() == N1.getOpcode()) {
2883     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
2884     if (Tmp.getNode()) return Tmp;
2885   }
2886
2887   // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
2888   // fold (and (sra)) -> (and (srl)) when possible.
2889   if (!VT.isVector() &&
2890       SimplifyDemandedBits(SDValue(N, 0)))
2891     return SDValue(N, 0);
2892
2893   // fold (zext_inreg (extload x)) -> (zextload x)
2894   if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
2895     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2896     EVT MemVT = LN0->getMemoryVT();
2897     // If we zero all the possible extended bits, then we can turn this into
2898     // a zextload if we are running before legalize or the operation is legal.
2899     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2900     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2901                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2902         ((!LegalOperations && !LN0->isVolatile()) ||
2903          TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2904       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2905                                        LN0->getChain(), LN0->getBasePtr(),
2906                                        MemVT, LN0->getMemOperand());
2907       AddToWorklist(N);
2908       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2909       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2910     }
2911   }
2912   // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
2913   if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
2914       N0.hasOneUse()) {
2915     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2916     EVT MemVT = LN0->getMemoryVT();
2917     // If we zero all the possible extended bits, then we can turn this into
2918     // a zextload if we are running before legalize or the operation is legal.
2919     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2920     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2921                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2922         ((!LegalOperations && !LN0->isVolatile()) ||
2923          TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2924       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2925                                        LN0->getChain(), LN0->getBasePtr(),
2926                                        MemVT, LN0->getMemOperand());
2927       AddToWorklist(N);
2928       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2929       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2930     }
2931   }
2932
2933   // fold (and (load x), 255) -> (zextload x, i8)
2934   // fold (and (extload x, i16), 255) -> (zextload x, i8)
2935   // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
2936   if (N1C && (N0.getOpcode() == ISD::LOAD ||
2937               (N0.getOpcode() == ISD::ANY_EXTEND &&
2938                N0.getOperand(0).getOpcode() == ISD::LOAD))) {
2939     bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
2940     LoadSDNode *LN0 = HasAnyExt
2941       ? cast<LoadSDNode>(N0.getOperand(0))
2942       : cast<LoadSDNode>(N0);
2943     if (LN0->getExtensionType() != ISD::SEXTLOAD &&
2944         LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
2945       uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
2946       if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
2947         EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
2948         EVT LoadedVT = LN0->getMemoryVT();
2949
2950         if (ExtVT == LoadedVT &&
2951             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2952           EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2953
2954           SDValue NewLoad =
2955             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2956                            LN0->getChain(), LN0->getBasePtr(), ExtVT,
2957                            LN0->getMemOperand());
2958           AddToWorklist(N);
2959           CombineTo(LN0, NewLoad, NewLoad.getValue(1));
2960           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2961         }
2962
2963         // Do not change the width of a volatile load.
2964         // Do not generate loads of non-round integer types since these can
2965         // be expensive (and would be wrong if the type is not byte sized).
2966         if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
2967             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2968           EVT PtrType = LN0->getOperand(1).getValueType();
2969
2970           unsigned Alignment = LN0->getAlignment();
2971           SDValue NewPtr = LN0->getBasePtr();
2972
2973           // For big endian targets, we need to add an offset to the pointer
2974           // to load the correct bytes.  For little endian systems, we merely
2975           // need to read fewer bytes from the same pointer.
2976           if (TLI.isBigEndian()) {
2977             unsigned LVTStoreBytes = LoadedVT.getStoreSize();
2978             unsigned EVTStoreBytes = ExtVT.getStoreSize();
2979             unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
2980             NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0), PtrType,
2981                                  NewPtr, DAG.getConstant(PtrOff, PtrType));
2982             Alignment = MinAlign(Alignment, PtrOff);
2983           }
2984
2985           AddToWorklist(NewPtr.getNode());
2986
2987           EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2988           SDValue Load =
2989             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2990                            LN0->getChain(), NewPtr,
2991                            LN0->getPointerInfo(),
2992                            ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
2993                            LN0->isInvariant(), Alignment, LN0->getAAInfo());
2994           AddToWorklist(N);
2995           CombineTo(LN0, Load, Load.getValue(1));
2996           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2997         }
2998       }
2999     }
3000   }
3001
3002   if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
3003       VT.getSizeInBits() <= 64) {
3004     if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3005       APInt ADDC = ADDI->getAPIntValue();
3006       if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
3007         // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
3008         // immediate for an add, but it is legal if its top c2 bits are set,
3009         // transform the ADD so the immediate doesn't need to be materialized
3010         // in a register.
3011         if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
3012           APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
3013                                              SRLI->getZExtValue());
3014           if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
3015             ADDC |= Mask;
3016             if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
3017               SDValue NewAdd =
3018                 DAG.getNode(ISD::ADD, SDLoc(N0), VT,
3019                             N0.getOperand(0), DAG.getConstant(ADDC, VT));
3020               CombineTo(N0.getNode(), NewAdd);
3021               return SDValue(N, 0); // Return N so it doesn't get rechecked!
3022             }
3023           }
3024         }
3025       }
3026     }
3027   }
3028
3029   // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
3030   if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
3031     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
3032                                        N0.getOperand(1), false);
3033     if (BSwap.getNode())
3034       return BSwap;
3035   }
3036
3037   return SDValue();
3038 }
3039
3040 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16.
3041 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
3042                                         bool DemandHighBits) {
3043   if (!LegalOperations)
3044     return SDValue();
3045
3046   EVT VT = N->getValueType(0);
3047   if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
3048     return SDValue();
3049   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3050     return SDValue();
3051
3052   // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
3053   bool LookPassAnd0 = false;
3054   bool LookPassAnd1 = false;
3055   if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
3056       std::swap(N0, N1);
3057   if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
3058       std::swap(N0, N1);
3059   if (N0.getOpcode() == ISD::AND) {
3060     if (!N0.getNode()->hasOneUse())
3061       return SDValue();
3062     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3063     if (!N01C || N01C->getZExtValue() != 0xFF00)
3064       return SDValue();
3065     N0 = N0.getOperand(0);
3066     LookPassAnd0 = true;
3067   }
3068
3069   if (N1.getOpcode() == ISD::AND) {
3070     if (!N1.getNode()->hasOneUse())
3071       return SDValue();
3072     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3073     if (!N11C || N11C->getZExtValue() != 0xFF)
3074       return SDValue();
3075     N1 = N1.getOperand(0);
3076     LookPassAnd1 = true;
3077   }
3078
3079   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3080     std::swap(N0, N1);
3081   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3082     return SDValue();
3083   if (!N0.getNode()->hasOneUse() ||
3084       !N1.getNode()->hasOneUse())
3085     return SDValue();
3086
3087   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3088   ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3089   if (!N01C || !N11C)
3090     return SDValue();
3091   if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3092     return SDValue();
3093
3094   // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3095   SDValue N00 = N0->getOperand(0);
3096   if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3097     if (!N00.getNode()->hasOneUse())
3098       return SDValue();
3099     ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3100     if (!N001C || N001C->getZExtValue() != 0xFF)
3101       return SDValue();
3102     N00 = N00.getOperand(0);
3103     LookPassAnd0 = true;
3104   }
3105
3106   SDValue N10 = N1->getOperand(0);
3107   if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3108     if (!N10.getNode()->hasOneUse())
3109       return SDValue();
3110     ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3111     if (!N101C || N101C->getZExtValue() != 0xFF00)
3112       return SDValue();
3113     N10 = N10.getOperand(0);
3114     LookPassAnd1 = true;
3115   }
3116
3117   if (N00 != N10)
3118     return SDValue();
3119
3120   // Make sure everything beyond the low halfword gets set to zero since the SRL
3121   // 16 will clear the top bits.
3122   unsigned OpSizeInBits = VT.getSizeInBits();
3123   if (DemandHighBits && OpSizeInBits > 16) {
3124     // If the left-shift isn't masked out then the only way this is a bswap is
3125     // if all bits beyond the low 8 are 0. In that case the entire pattern
3126     // reduces to a left shift anyway: leave it for other parts of the combiner.
3127     if (!LookPassAnd0)
3128       return SDValue();
3129
3130     // However, if the right shift isn't masked out then it might be because
3131     // it's not needed. See if we can spot that too.
3132     if (!LookPassAnd1 &&
3133         !DAG.MaskedValueIsZero(
3134             N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3135       return SDValue();
3136   }
3137
3138   SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
3139   if (OpSizeInBits > 16)
3140     Res = DAG.getNode(ISD::SRL, SDLoc(N), VT, Res,
3141                       DAG.getConstant(OpSizeInBits-16, getShiftAmountTy(VT)));
3142   return Res;
3143 }
3144
3145 /// Return true if the specified node is an element that makes up a 32-bit
3146 /// packed halfword byteswap.
3147 /// ((x & 0x000000ff) << 8) |
3148 /// ((x & 0x0000ff00) >> 8) |
3149 /// ((x & 0x00ff0000) << 8) |
3150 /// ((x & 0xff000000) >> 8)
3151 static bool isBSwapHWordElement(SDValue N, SmallVectorImpl<SDNode *> &Parts) {
3152   if (!N.getNode()->hasOneUse())
3153     return false;
3154
3155   unsigned Opc = N.getOpcode();
3156   if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3157     return false;
3158
3159   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3160   if (!N1C)
3161     return false;
3162
3163   unsigned Num;
3164   switch (N1C->getZExtValue()) {
3165   default:
3166     return false;
3167   case 0xFF:       Num = 0; break;
3168   case 0xFF00:     Num = 1; break;
3169   case 0xFF0000:   Num = 2; break;
3170   case 0xFF000000: Num = 3; break;
3171   }
3172
3173   // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3174   SDValue N0 = N.getOperand(0);
3175   if (Opc == ISD::AND) {
3176     if (Num == 0 || Num == 2) {
3177       // (x >> 8) & 0xff
3178       // (x >> 8) & 0xff0000
3179       if (N0.getOpcode() != ISD::SRL)
3180         return false;
3181       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3182       if (!C || C->getZExtValue() != 8)
3183         return false;
3184     } else {
3185       // (x << 8) & 0xff00
3186       // (x << 8) & 0xff000000
3187       if (N0.getOpcode() != ISD::SHL)
3188         return false;
3189       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3190       if (!C || C->getZExtValue() != 8)
3191         return false;
3192     }
3193   } else if (Opc == ISD::SHL) {
3194     // (x & 0xff) << 8
3195     // (x & 0xff0000) << 8
3196     if (Num != 0 && Num != 2)
3197       return false;
3198     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3199     if (!C || C->getZExtValue() != 8)
3200       return false;
3201   } else { // Opc == ISD::SRL
3202     // (x & 0xff00) >> 8
3203     // (x & 0xff000000) >> 8
3204     if (Num != 1 && Num != 3)
3205       return false;
3206     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3207     if (!C || C->getZExtValue() != 8)
3208       return false;
3209   }
3210
3211   if (Parts[Num])
3212     return false;
3213
3214   Parts[Num] = N0.getOperand(0).getNode();
3215   return true;
3216 }
3217
3218 /// Match a 32-bit packed halfword bswap. That is
3219 /// ((x & 0x000000ff) << 8) |
3220 /// ((x & 0x0000ff00) >> 8) |
3221 /// ((x & 0x00ff0000) << 8) |
3222 /// ((x & 0xff000000) >> 8)
3223 /// => (rotl (bswap x), 16)
3224 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3225   if (!LegalOperations)
3226     return SDValue();
3227
3228   EVT VT = N->getValueType(0);
3229   if (VT != MVT::i32)
3230     return SDValue();
3231   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3232     return SDValue();
3233
3234   SmallVector<SDNode*,4> Parts(4, (SDNode*)nullptr);
3235   // Look for either
3236   // (or (or (and), (and)), (or (and), (and)))
3237   // (or (or (or (and), (and)), (and)), (and))
3238   if (N0.getOpcode() != ISD::OR)
3239     return SDValue();
3240   SDValue N00 = N0.getOperand(0);
3241   SDValue N01 = N0.getOperand(1);
3242
3243   if (N1.getOpcode() == ISD::OR &&
3244       N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3245     // (or (or (and), (and)), (or (and), (and)))
3246     SDValue N000 = N00.getOperand(0);
3247     if (!isBSwapHWordElement(N000, Parts))
3248       return SDValue();
3249
3250     SDValue N001 = N00.getOperand(1);
3251     if (!isBSwapHWordElement(N001, Parts))
3252       return SDValue();
3253     SDValue N010 = N01.getOperand(0);
3254     if (!isBSwapHWordElement(N010, Parts))
3255       return SDValue();
3256     SDValue N011 = N01.getOperand(1);
3257     if (!isBSwapHWordElement(N011, Parts))
3258       return SDValue();
3259   } else {
3260     // (or (or (or (and), (and)), (and)), (and))
3261     if (!isBSwapHWordElement(N1, Parts))
3262       return SDValue();
3263     if (!isBSwapHWordElement(N01, Parts))
3264       return SDValue();
3265     if (N00.getOpcode() != ISD::OR)
3266       return SDValue();
3267     SDValue N000 = N00.getOperand(0);
3268     if (!isBSwapHWordElement(N000, Parts))
3269       return SDValue();
3270     SDValue N001 = N00.getOperand(1);
3271     if (!isBSwapHWordElement(N001, Parts))
3272       return SDValue();
3273   }
3274
3275   // Make sure the parts are all coming from the same node.
3276   if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3277     return SDValue();
3278
3279   SDValue BSwap = DAG.getNode(ISD::BSWAP, SDLoc(N), VT,
3280                               SDValue(Parts[0],0));
3281
3282   // Result of the bswap should be rotated by 16. If it's not legal, then
3283   // do  (x << 16) | (x >> 16).
3284   SDValue ShAmt = DAG.getConstant(16, getShiftAmountTy(VT));
3285   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3286     return DAG.getNode(ISD::ROTL, SDLoc(N), VT, BSwap, ShAmt);
3287   if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3288     return DAG.getNode(ISD::ROTR, SDLoc(N), VT, BSwap, ShAmt);
3289   return DAG.getNode(ISD::OR, SDLoc(N), VT,
3290                      DAG.getNode(ISD::SHL, SDLoc(N), VT, BSwap, ShAmt),
3291                      DAG.getNode(ISD::SRL, SDLoc(N), VT, BSwap, ShAmt));
3292 }
3293
3294 SDValue DAGCombiner::visitOR(SDNode *N) {
3295   SDValue N0 = N->getOperand(0);
3296   SDValue N1 = N->getOperand(1);
3297   SDValue LL, LR, RL, RR, CC0, CC1;
3298   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3299   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3300   EVT VT = N1.getValueType();
3301
3302   // fold vector ops
3303   if (VT.isVector()) {
3304     SDValue FoldedVOp = SimplifyVBinOp(N);
3305     if (FoldedVOp.getNode()) return FoldedVOp;
3306
3307     // fold (or x, 0) -> x, vector edition
3308     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3309       return N1;
3310     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3311       return N0;
3312
3313     // fold (or x, -1) -> -1, vector edition
3314     if (ISD::isBuildVectorAllOnes(N0.getNode()))
3315       return N0;
3316     if (ISD::isBuildVectorAllOnes(N1.getNode()))
3317       return N1;
3318
3319     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
3320     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
3321     // Do this only if the resulting shuffle is legal.
3322     if (isa<ShuffleVectorSDNode>(N0) &&
3323         isa<ShuffleVectorSDNode>(N1) &&
3324         // Avoid folding a node with illegal type.
3325         TLI.isTypeLegal(VT) &&
3326         N0->getOperand(1) == N1->getOperand(1) &&
3327         ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
3328       bool CanFold = true;
3329       unsigned NumElts = VT.getVectorNumElements();
3330       const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3331       const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3332       // We construct two shuffle masks:
3333       // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
3334       // and N1 as the second operand.
3335       // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
3336       // and N0 as the second operand.
3337       // We do this because OR is commutable and therefore there might be
3338       // two ways to fold this node into a shuffle.
3339       SmallVector<int,4> Mask1;
3340       SmallVector<int,4> Mask2;
3341
3342       for (unsigned i = 0; i != NumElts && CanFold; ++i) {
3343         int M0 = SV0->getMaskElt(i);
3344         int M1 = SV1->getMaskElt(i);
3345
3346         // Both shuffle indexes are undef. Propagate Undef.
3347         if (M0 < 0 && M1 < 0) {
3348           Mask1.push_back(M0);
3349           Mask2.push_back(M0);
3350           continue;
3351         }
3352
3353         if (M0 < 0 || M1 < 0 ||
3354             (M0 < (int)NumElts && M1 < (int)NumElts) ||
3355             (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
3356           CanFold = false;
3357           break;
3358         }
3359
3360         Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
3361         Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
3362       }
3363
3364       if (CanFold) {
3365         // Fold this sequence only if the resulting shuffle is 'legal'.
3366         if (TLI.isShuffleMaskLegal(Mask1, VT))
3367           return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
3368                                       N1->getOperand(0), &Mask1[0]);
3369         if (TLI.isShuffleMaskLegal(Mask2, VT))
3370           return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
3371                                       N0->getOperand(0), &Mask2[0]);
3372       }
3373     }
3374   }
3375
3376   // fold (or x, undef) -> -1
3377   if (!LegalOperations &&
3378       (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3379     EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3380     return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
3381   }
3382   // fold (or c1, c2) -> c1|c2
3383   if (N0C && N1C)
3384     return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C);
3385   // canonicalize constant to RHS
3386   if (N0C && !N1C)
3387     return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3388   // fold (or x, 0) -> x
3389   if (N1C && N1C->isNullValue())
3390     return N0;
3391   // fold (or x, -1) -> -1
3392   if (N1C && N1C->isAllOnesValue())
3393     return N1;
3394   // fold (or x, c) -> c iff (x & ~c) == 0
3395   if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3396     return N1;
3397
3398   // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3399   SDValue BSwap = MatchBSwapHWord(N, N0, N1);
3400   if (BSwap.getNode())
3401     return BSwap;
3402   BSwap = MatchBSwapHWordLow(N, N0, N1);
3403   if (BSwap.getNode())
3404     return BSwap;
3405
3406   // reassociate or
3407   SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1);
3408   if (ROR.getNode())
3409     return ROR;
3410   // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3411   // iff (c1 & c2) == 0.
3412   if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3413              isa<ConstantSDNode>(N0.getOperand(1))) {
3414     ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3415     if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3416       SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1);
3417       if (!COR.getNode())
3418         return SDValue();
3419       return DAG.getNode(ISD::AND, SDLoc(N), VT,
3420                          DAG.getNode(ISD::OR, SDLoc(N0), VT,
3421                                      N0.getOperand(0), N1), COR);
3422     }
3423   }
3424   // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3425   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3426     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3427     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3428
3429     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
3430         LL.getValueType().isInteger()) {
3431       // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3432       // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3433       if (cast<ConstantSDNode>(LR)->isNullValue() &&
3434           (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3435         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3436                                      LR.getValueType(), LL, RL);
3437         AddToWorklist(ORNode.getNode());
3438         return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
3439       }
3440       // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3441       // fold (or (setgt X, -1), (setgt Y  -1)) -> (setgt (and X, Y), -1)
3442       if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
3443           (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3444         SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3445                                       LR.getValueType(), LL, RL);
3446         AddToWorklist(ANDNode.getNode());
3447         return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
3448       }
3449     }
3450     // canonicalize equivalent to ll == rl
3451     if (LL == RR && LR == RL) {
3452       Op1 = ISD::getSetCCSwappedOperands(Op1);
3453       std::swap(RL, RR);
3454     }
3455     if (LL == RL && LR == RR) {
3456       bool isInteger = LL.getValueType().isInteger();
3457       ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3458       if (Result != ISD::SETCC_INVALID &&
3459           (!LegalOperations ||
3460            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3461             TLI.isOperationLegal(ISD::SETCC,
3462               getSetCCResultType(N0.getValueType())))))
3463         return DAG.getSetCC(SDLoc(N), N0.getValueType(),
3464                             LL, LR, Result);
3465     }
3466   }
3467
3468   // Simplify: (or (op x...), (op y...))  -> (op (or x, y))
3469   if (N0.getOpcode() == N1.getOpcode()) {
3470     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3471     if (Tmp.getNode()) return Tmp;
3472   }
3473
3474   // (or (and X, C1), (and Y, C2))  -> (and (or X, Y), C3) if possible.
3475   if (N0.getOpcode() == ISD::AND &&
3476       N1.getOpcode() == ISD::AND &&
3477       N0.getOperand(1).getOpcode() == ISD::Constant &&
3478       N1.getOperand(1).getOpcode() == ISD::Constant &&
3479       // Don't increase # computations.
3480       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3481     // We can only do this xform if we know that bits from X that are set in C2
3482     // but not in C1 are already zero.  Likewise for Y.
3483     const APInt &LHSMask =
3484       cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3485     const APInt &RHSMask =
3486       cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
3487
3488     if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3489         DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3490       SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3491                               N0.getOperand(0), N1.getOperand(0));
3492       return DAG.getNode(ISD::AND, SDLoc(N), VT, X,
3493                          DAG.getConstant(LHSMask | RHSMask, VT));
3494     }
3495   }
3496
3497   // See if this is some rotate idiom.
3498   if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3499     return SDValue(Rot, 0);
3500
3501   // Simplify the operands using demanded-bits information.
3502   if (!VT.isVector() &&
3503       SimplifyDemandedBits(SDValue(N, 0)))
3504     return SDValue(N, 0);
3505
3506   return SDValue();
3507 }
3508
3509 /// Match "(X shl/srl V1) & V2" where V2 may not be present.
3510 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3511   if (Op.getOpcode() == ISD::AND) {
3512     if (isa<ConstantSDNode>(Op.getOperand(1))) {
3513       Mask = Op.getOperand(1);
3514       Op = Op.getOperand(0);
3515     } else {
3516       return false;
3517     }
3518   }
3519
3520   if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3521     Shift = Op;
3522     return true;
3523   }
3524
3525   return false;
3526 }
3527
3528 // Return true if we can prove that, whenever Neg and Pos are both in the
3529 // range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos).  This means that
3530 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3531 //
3532 //     (or (shift1 X, Neg), (shift2 X, Pos))
3533 //
3534 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3535 // in direction shift1 by Neg.  The range [0, OpSize) means that we only need
3536 // to consider shift amounts with defined behavior.
3537 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) {
3538   // If OpSize is a power of 2 then:
3539   //
3540   //  (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1)
3541   //  (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize).
3542   //
3543   // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check
3544   // for the stronger condition:
3545   //
3546   //     Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1)    [A]
3547   //
3548   // for all Neg and Pos.  Since Neg & (OpSize - 1) == Neg' & (OpSize - 1)
3549   // we can just replace Neg with Neg' for the rest of the function.
3550   //
3551   // In other cases we check for the even stronger condition:
3552   //
3553   //     Neg == OpSize - Pos                                    [B]
3554   //
3555   // for all Neg and Pos.  Note that the (or ...) then invokes undefined
3556   // behavior if Pos == 0 (and consequently Neg == OpSize).
3557   //
3558   // We could actually use [A] whenever OpSize is a power of 2, but the
3559   // only extra cases that it would match are those uninteresting ones
3560   // where Neg and Pos are never in range at the same time.  E.g. for
3561   // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3562   // as well as (sub 32, Pos), but:
3563   //
3564   //     (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3565   //
3566   // always invokes undefined behavior for 32-bit X.
3567   //
3568   // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise.
3569   unsigned MaskLoBits = 0;
3570   if (Neg.getOpcode() == ISD::AND &&
3571       isPowerOf2_64(OpSize) &&
3572       Neg.getOperand(1).getOpcode() == ISD::Constant &&
3573       cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) {
3574     Neg = Neg.getOperand(0);
3575     MaskLoBits = Log2_64(OpSize);
3576   }
3577
3578   // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3579   if (Neg.getOpcode() != ISD::SUB)
3580     return 0;
3581   ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0));
3582   if (!NegC)
3583     return 0;
3584   SDValue NegOp1 = Neg.getOperand(1);
3585
3586   // On the RHS of [A], if Pos is Pos' & (OpSize - 1), just replace Pos with
3587   // Pos'.  The truncation is redundant for the purpose of the equality.
3588   if (MaskLoBits &&
3589       Pos.getOpcode() == ISD::AND &&
3590       Pos.getOperand(1).getOpcode() == ISD::Constant &&
3591       cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() == OpSize - 1)
3592     Pos = Pos.getOperand(0);
3593
3594   // The condition we need is now:
3595   //
3596   //     (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask
3597   //
3598   // If NegOp1 == Pos then we need:
3599   //
3600   //              OpSize & Mask == NegC & Mask
3601   //
3602   // (because "x & Mask" is a truncation and distributes through subtraction).
3603   APInt Width;
3604   if (Pos == NegOp1)
3605     Width = NegC->getAPIntValue();
3606   // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3607   // Then the condition we want to prove becomes:
3608   //
3609   //     (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask
3610   //
3611   // which, again because "x & Mask" is a truncation, becomes:
3612   //
3613   //                NegC & Mask == (OpSize - PosC) & Mask
3614   //              OpSize & Mask == (NegC + PosC) & Mask
3615   else if (Pos.getOpcode() == ISD::ADD &&
3616            Pos.getOperand(0) == NegOp1 &&
3617            Pos.getOperand(1).getOpcode() == ISD::Constant)
3618     Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() +
3619              NegC->getAPIntValue());
3620   else
3621     return false;
3622
3623   // Now we just need to check that OpSize & Mask == Width & Mask.
3624   if (MaskLoBits)
3625     // Opsize & Mask is 0 since Mask is Opsize - 1.
3626     return Width.getLoBits(MaskLoBits) == 0;
3627   return Width == OpSize;
3628 }
3629
3630 // A subroutine of MatchRotate used once we have found an OR of two opposite
3631 // shifts of Shifted.  If Neg == <operand size> - Pos then the OR reduces
3632 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3633 // former being preferred if supported.  InnerPos and InnerNeg are Pos and
3634 // Neg with outer conversions stripped away.
3635 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3636                                        SDValue Neg, SDValue InnerPos,
3637                                        SDValue InnerNeg, unsigned PosOpcode,
3638                                        unsigned NegOpcode, SDLoc DL) {
3639   // fold (or (shl x, (*ext y)),
3640   //          (srl x, (*ext (sub 32, y)))) ->
3641   //   (rotl x, y) or (rotr x, (sub 32, y))
3642   //
3643   // fold (or (shl x, (*ext (sub 32, y))),
3644   //          (srl x, (*ext y))) ->
3645   //   (rotr x, y) or (rotl x, (sub 32, y))
3646   EVT VT = Shifted.getValueType();
3647   if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) {
3648     bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3649     return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3650                        HasPos ? Pos : Neg).getNode();
3651   }
3652
3653   return nullptr;
3654 }
3655
3656 // MatchRotate - Handle an 'or' of two operands.  If this is one of the many
3657 // idioms for rotate, and if the target supports rotation instructions, generate
3658 // a rot[lr].
3659 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
3660   // Must be a legal type.  Expanded 'n promoted things won't work with rotates.
3661   EVT VT = LHS.getValueType();
3662   if (!TLI.isTypeLegal(VT)) return nullptr;
3663
3664   // The target must have at least one rotate flavor.
3665   bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3666   bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3667   if (!HasROTL && !HasROTR) return nullptr;
3668
3669   // Match "(X shl/srl V1) & V2" where V2 may not be present.
3670   SDValue LHSShift;   // The shift.
3671   SDValue LHSMask;    // AND value if any.
3672   if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3673     return nullptr; // Not part of a rotate.
3674
3675   SDValue RHSShift;   // The shift.
3676   SDValue RHSMask;    // AND value if any.
3677   if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3678     return nullptr; // Not part of a rotate.
3679
3680   if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3681     return nullptr;   // Not shifting the same value.
3682
3683   if (LHSShift.getOpcode() == RHSShift.getOpcode())
3684     return nullptr;   // Shifts must disagree.
3685
3686   // Canonicalize shl to left side in a shl/srl pair.
3687   if (RHSShift.getOpcode() == ISD::SHL) {
3688     std::swap(LHS, RHS);
3689     std::swap(LHSShift, RHSShift);
3690     std::swap(LHSMask , RHSMask );
3691   }
3692
3693   unsigned OpSizeInBits = VT.getSizeInBits();
3694   SDValue LHSShiftArg = LHSShift.getOperand(0);
3695   SDValue LHSShiftAmt = LHSShift.getOperand(1);
3696   SDValue RHSShiftArg = RHSShift.getOperand(0);
3697   SDValue RHSShiftAmt = RHSShift.getOperand(1);
3698
3699   // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3700   // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
3701   if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3702       RHSShiftAmt.getOpcode() == ISD::Constant) {
3703     uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3704     uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
3705     if ((LShVal + RShVal) != OpSizeInBits)
3706       return nullptr;
3707
3708     SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3709                               LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3710
3711     // If there is an AND of either shifted operand, apply it to the result.
3712     if (LHSMask.getNode() || RHSMask.getNode()) {
3713       APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
3714
3715       if (LHSMask.getNode()) {
3716         APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3717         Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
3718       }
3719       if (RHSMask.getNode()) {
3720         APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3721         Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
3722       }
3723
3724       Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT));
3725     }
3726
3727     return Rot.getNode();
3728   }
3729
3730   // If there is a mask here, and we have a variable shift, we can't be sure
3731   // that we're masking out the right stuff.
3732   if (LHSMask.getNode() || RHSMask.getNode())
3733     return nullptr;
3734
3735   // If the shift amount is sign/zext/any-extended just peel it off.
3736   SDValue LExtOp0 = LHSShiftAmt;
3737   SDValue RExtOp0 = RHSShiftAmt;
3738   if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3739        LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3740        LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3741        LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3742       (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3743        RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3744        RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3745        RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
3746     LExtOp0 = LHSShiftAmt.getOperand(0);
3747     RExtOp0 = RHSShiftAmt.getOperand(0);
3748   }
3749
3750   SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
3751                                    LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
3752   if (TryL)
3753     return TryL;
3754
3755   SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
3756                                    RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
3757   if (TryR)
3758     return TryR;
3759
3760   return nullptr;
3761 }
3762
3763 SDValue DAGCombiner::visitXOR(SDNode *N) {
3764   SDValue N0 = N->getOperand(0);
3765   SDValue N1 = N->getOperand(1);
3766   SDValue LHS, RHS, CC;
3767   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3768   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3769   EVT VT = N0.getValueType();
3770
3771   // fold vector ops
3772   if (VT.isVector()) {
3773     SDValue FoldedVOp = SimplifyVBinOp(N);
3774     if (FoldedVOp.getNode()) return FoldedVOp;
3775
3776     // fold (xor x, 0) -> x, vector edition
3777     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3778       return N1;
3779     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3780       return N0;
3781   }
3782
3783   // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3784   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3785     return DAG.getConstant(0, VT);
3786   // fold (xor x, undef) -> undef
3787   if (N0.getOpcode() == ISD::UNDEF)
3788     return N0;
3789   if (N1.getOpcode() == ISD::UNDEF)
3790     return N1;
3791   // fold (xor c1, c2) -> c1^c2
3792   if (N0C && N1C)
3793     return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
3794   // canonicalize constant to RHS
3795   if (N0C && !N1C)
3796     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
3797   // fold (xor x, 0) -> x
3798   if (N1C && N1C->isNullValue())
3799     return N0;
3800   // reassociate xor
3801   SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1);
3802   if (RXOR.getNode())
3803     return RXOR;
3804
3805   // fold !(x cc y) -> (x !cc y)
3806   if (N1C && N1C->getAPIntValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) {
3807     bool isInt = LHS.getValueType().isInteger();
3808     ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3809                                                isInt);
3810
3811     if (!LegalOperations ||
3812         TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
3813       switch (N0.getOpcode()) {
3814       default:
3815         llvm_unreachable("Unhandled SetCC Equivalent!");
3816       case ISD::SETCC:
3817         return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
3818       case ISD::SELECT_CC:
3819         return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
3820                                N0.getOperand(3), NotCC);
3821       }
3822     }
3823   }
3824
3825   // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
3826   if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
3827       N0.getNode()->hasOneUse() &&
3828       isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
3829     SDValue V = N0.getOperand(0);
3830     V = DAG.getNode(ISD::XOR, SDLoc(N0), V.getValueType(), V,
3831                     DAG.getConstant(1, V.getValueType()));
3832     AddToWorklist(V.getNode());
3833     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
3834   }
3835
3836   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
3837   if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
3838       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3839     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3840     if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
3841       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3842       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3843       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3844       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
3845       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3846     }
3847   }
3848   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
3849   if (N1C && N1C->isAllOnesValue() &&
3850       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3851     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3852     if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
3853       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3854       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3855       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3856       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
3857       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3858     }
3859   }
3860   // fold (xor (and x, y), y) -> (and (not x), y)
3861   if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3862       N0->getOperand(1) == N1) {
3863     SDValue X = N0->getOperand(0);
3864     SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
3865     AddToWorklist(NotX.getNode());
3866     return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
3867   }
3868   // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
3869   if (N1C && N0.getOpcode() == ISD::XOR) {
3870     ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
3871     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3872     if (N00C)
3873       return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(1),
3874                          DAG.getConstant(N1C->getAPIntValue() ^
3875                                          N00C->getAPIntValue(), VT));
3876     if (N01C)
3877       return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(0),
3878                          DAG.getConstant(N1C->getAPIntValue() ^
3879                                          N01C->getAPIntValue(), VT));
3880   }
3881   // fold (xor x, x) -> 0
3882   if (N0 == N1)
3883     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
3884
3885   // Simplify: xor (op x...), (op y...)  -> (op (xor x, y))
3886   if (N0.getOpcode() == N1.getOpcode()) {
3887     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3888     if (Tmp.getNode()) return Tmp;
3889   }
3890
3891   // Simplify the expression using non-local knowledge.
3892   if (!VT.isVector() &&
3893       SimplifyDemandedBits(SDValue(N, 0)))
3894     return SDValue(N, 0);
3895
3896   return SDValue();
3897 }
3898
3899 /// Handle transforms common to the three shifts, when the shift amount is a
3900 /// constant.
3901 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
3902   // We can't and shouldn't fold opaque constants.
3903   if (Amt->isOpaque())
3904     return SDValue();
3905
3906   SDNode *LHS = N->getOperand(0).getNode();
3907   if (!LHS->hasOneUse()) return SDValue();
3908
3909   // We want to pull some binops through shifts, so that we have (and (shift))
3910   // instead of (shift (and)), likewise for add, or, xor, etc.  This sort of
3911   // thing happens with address calculations, so it's important to canonicalize
3912   // it.
3913   bool HighBitSet = false;  // Can we transform this if the high bit is set?
3914
3915   switch (LHS->getOpcode()) {
3916   default: return SDValue();
3917   case ISD::OR:
3918   case ISD::XOR:
3919     HighBitSet = false; // We can only transform sra if the high bit is clear.
3920     break;
3921   case ISD::AND:
3922     HighBitSet = true;  // We can only transform sra if the high bit is set.
3923     break;
3924   case ISD::ADD:
3925     if (N->getOpcode() != ISD::SHL)
3926       return SDValue(); // only shl(add) not sr[al](add).
3927     HighBitSet = false; // We can only transform sra if the high bit is clear.
3928     break;
3929   }
3930
3931   // We require the RHS of the binop to be a constant and not opaque as well.
3932   ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
3933   if (!BinOpCst || BinOpCst->isOpaque()) return SDValue();
3934
3935   // FIXME: disable this unless the input to the binop is a shift by a constant.
3936   // If it is not a shift, it pessimizes some common cases like:
3937   //
3938   //    void foo(int *X, int i) { X[i & 1235] = 1; }
3939   //    int bar(int *X, int i) { return X[i & 255]; }
3940   SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
3941   if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
3942        BinOpLHSVal->getOpcode() != ISD::SRA &&
3943        BinOpLHSVal->getOpcode() != ISD::SRL) ||
3944       !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
3945     return SDValue();
3946
3947   EVT VT = N->getValueType(0);
3948
3949   // If this is a signed shift right, and the high bit is modified by the
3950   // logical operation, do not perform the transformation. The highBitSet
3951   // boolean indicates the value of the high bit of the constant which would
3952   // cause it to be modified for this operation.
3953   if (N->getOpcode() == ISD::SRA) {
3954     bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
3955     if (BinOpRHSSignSet != HighBitSet)
3956       return SDValue();
3957   }
3958
3959   if (!TLI.isDesirableToCommuteWithShift(LHS))
3960     return SDValue();
3961
3962   // Fold the constants, shifting the binop RHS by the shift amount.
3963   SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
3964                                N->getValueType(0),
3965                                LHS->getOperand(1), N->getOperand(1));
3966   assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
3967
3968   // Create the new shift.
3969   SDValue NewShift = DAG.getNode(N->getOpcode(),
3970                                  SDLoc(LHS->getOperand(0)),
3971                                  VT, LHS->getOperand(0), N->getOperand(1));
3972
3973   // Create the new binop.
3974   return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
3975 }
3976
3977 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
3978   assert(N->getOpcode() == ISD::TRUNCATE);
3979   assert(N->getOperand(0).getOpcode() == ISD::AND);
3980
3981   // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
3982   if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
3983     SDValue N01 = N->getOperand(0).getOperand(1);
3984
3985     if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
3986       EVT TruncVT = N->getValueType(0);
3987       SDValue N00 = N->getOperand(0).getOperand(0);
3988       APInt TruncC = N01C->getAPIntValue();
3989       TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
3990
3991       return DAG.getNode(ISD::AND, SDLoc(N), TruncVT,
3992                          DAG.getNode(ISD::TRUNCATE, SDLoc(N), TruncVT, N00),
3993                          DAG.getConstant(TruncC, TruncVT));
3994     }
3995   }
3996
3997   return SDValue();
3998 }
3999
4000 SDValue DAGCombiner::visitRotate(SDNode *N) {
4001   // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
4002   if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
4003       N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
4004     SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode());
4005     if (NewOp1.getNode())
4006       return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
4007                          N->getOperand(0), NewOp1);
4008   }
4009   return SDValue();
4010 }
4011
4012 SDValue DAGCombiner::visitSHL(SDNode *N) {
4013   SDValue N0 = N->getOperand(0);
4014   SDValue N1 = N->getOperand(1);
4015   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4016   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4017   EVT VT = N0.getValueType();
4018   unsigned OpSizeInBits = VT.getScalarSizeInBits();
4019
4020   // fold vector ops
4021   if (VT.isVector()) {
4022     SDValue FoldedVOp = SimplifyVBinOp(N);
4023     if (FoldedVOp.getNode()) return FoldedVOp;
4024
4025     BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
4026     // If setcc produces all-one true value then:
4027     // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
4028     if (N1CV && N1CV->isConstant()) {
4029       if (N0.getOpcode() == ISD::AND) {
4030         SDValue N00 = N0->getOperand(0);
4031         SDValue N01 = N0->getOperand(1);
4032         BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
4033
4034         if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
4035             TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
4036                 TargetLowering::ZeroOrNegativeOneBooleanContent) {
4037           SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, VT, N01CV, N1CV);
4038           if (C.getNode())
4039             return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
4040         }
4041       } else {
4042         N1C = isConstOrConstSplat(N1);
4043       }
4044     }
4045   }
4046
4047   // fold (shl c1, c2) -> c1<<c2
4048   if (N0C && N1C)
4049     return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
4050   // fold (shl 0, x) -> 0
4051   if (N0C && N0C->isNullValue())
4052     return N0;
4053   // fold (shl x, c >= size(x)) -> undef
4054   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4055     return DAG.getUNDEF(VT);
4056   // fold (shl x, 0) -> x
4057   if (N1C && N1C->isNullValue())
4058     return N0;
4059   // fold (shl undef, x) -> 0
4060   if (N0.getOpcode() == ISD::UNDEF)
4061     return DAG.getConstant(0, VT);
4062   // if (shl x, c) is known to be zero, return 0
4063   if (DAG.MaskedValueIsZero(SDValue(N, 0),
4064                             APInt::getAllOnesValue(OpSizeInBits)))
4065     return DAG.getConstant(0, VT);
4066   // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
4067   if (N1.getOpcode() == ISD::TRUNCATE &&
4068       N1.getOperand(0).getOpcode() == ISD::AND) {
4069     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4070     if (NewOp1.getNode())
4071       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
4072   }
4073
4074   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4075     return SDValue(N, 0);
4076
4077   // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
4078   if (N1C && N0.getOpcode() == ISD::SHL) {
4079     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4080       uint64_t c1 = N0C1->getZExtValue();
4081       uint64_t c2 = N1C->getZExtValue();
4082       if (c1 + c2 >= OpSizeInBits)
4083         return DAG.getConstant(0, VT);
4084       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4085                          DAG.getConstant(c1 + c2, N1.getValueType()));
4086     }
4087   }
4088
4089   // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4090   // For this to be valid, the second form must not preserve any of the bits
4091   // that are shifted out by the inner shift in the first form.  This means
4092   // the outer shift size must be >= the number of bits added by the ext.
4093   // As a corollary, we don't care what kind of ext it is.
4094   if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4095               N0.getOpcode() == ISD::ANY_EXTEND ||
4096               N0.getOpcode() == ISD::SIGN_EXTEND) &&
4097       N0.getOperand(0).getOpcode() == ISD::SHL) {
4098     SDValue N0Op0 = N0.getOperand(0);
4099     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4100       uint64_t c1 = N0Op0C1->getZExtValue();
4101       uint64_t c2 = N1C->getZExtValue();
4102       EVT InnerShiftVT = N0Op0.getValueType();
4103       uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4104       if (c2 >= OpSizeInBits - InnerShiftSize) {
4105         if (c1 + c2 >= OpSizeInBits)
4106           return DAG.getConstant(0, VT);
4107         return DAG.getNode(ISD::SHL, SDLoc(N0), VT,
4108                            DAG.getNode(N0.getOpcode(), SDLoc(N0), VT,
4109                                        N0Op0->getOperand(0)),
4110                            DAG.getConstant(c1 + c2, N1.getValueType()));
4111       }
4112     }
4113   }
4114
4115   // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4116   // Only fold this if the inner zext has no other uses to avoid increasing
4117   // the total number of instructions.
4118   if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
4119       N0.getOperand(0).getOpcode() == ISD::SRL) {
4120     SDValue N0Op0 = N0.getOperand(0);
4121     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4122       uint64_t c1 = N0Op0C1->getZExtValue();
4123       if (c1 < VT.getScalarSizeInBits()) {
4124         uint64_t c2 = N1C->getZExtValue();
4125         if (c1 == c2) {
4126           SDValue NewOp0 = N0.getOperand(0);
4127           EVT CountVT = NewOp0.getOperand(1).getValueType();
4128           SDValue NewSHL = DAG.getNode(ISD::SHL, SDLoc(N), NewOp0.getValueType(),
4129                                        NewOp0, DAG.getConstant(c2, CountVT));
4130           AddToWorklist(NewSHL.getNode());
4131           return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4132         }
4133       }
4134     }
4135   }
4136
4137   // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4138   //                               (and (srl x, (sub c1, c2), MASK)
4139   // Only fold this if the inner shift has no other uses -- if it does, folding
4140   // this will increase the total number of instructions.
4141   if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4142     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4143       uint64_t c1 = N0C1->getZExtValue();
4144       if (c1 < OpSizeInBits) {
4145         uint64_t c2 = N1C->getZExtValue();
4146         APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4147         SDValue Shift;
4148         if (c2 > c1) {
4149           Mask = Mask.shl(c2 - c1);
4150           Shift = DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4151                               DAG.getConstant(c2 - c1, N1.getValueType()));
4152         } else {
4153           Mask = Mask.lshr(c1 - c2);
4154           Shift = DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4155                               DAG.getConstant(c1 - c2, N1.getValueType()));
4156         }
4157         return DAG.getNode(ISD::AND, SDLoc(N0), VT, Shift,
4158                            DAG.getConstant(Mask, VT));
4159       }
4160     }
4161   }
4162   // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
4163   if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
4164     unsigned BitSize = VT.getScalarSizeInBits();
4165     SDValue HiBitsMask =
4166       DAG.getConstant(APInt::getHighBitsSet(BitSize,
4167                                             BitSize - N1C->getZExtValue()), VT);
4168     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4169                        HiBitsMask);
4170   }
4171
4172   if (N1C) {
4173     SDValue NewSHL = visitShiftByConstant(N, N1C);
4174     if (NewSHL.getNode())
4175       return NewSHL;
4176   }
4177
4178   return SDValue();
4179 }
4180
4181 SDValue DAGCombiner::visitSRA(SDNode *N) {
4182   SDValue N0 = N->getOperand(0);
4183   SDValue N1 = N->getOperand(1);
4184   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4185   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4186   EVT VT = N0.getValueType();
4187   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4188
4189   // fold vector ops
4190   if (VT.isVector()) {
4191     SDValue FoldedVOp = SimplifyVBinOp(N);
4192     if (FoldedVOp.getNode()) return FoldedVOp;
4193
4194     N1C = isConstOrConstSplat(N1);
4195   }
4196
4197   // fold (sra c1, c2) -> (sra c1, c2)
4198   if (N0C && N1C)
4199     return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
4200   // fold (sra 0, x) -> 0
4201   if (N0C && N0C->isNullValue())
4202     return N0;
4203   // fold (sra -1, x) -> -1
4204   if (N0C && N0C->isAllOnesValue())
4205     return N0;
4206   // fold (sra x, (setge c, size(x))) -> undef
4207   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4208     return DAG.getUNDEF(VT);
4209   // fold (sra x, 0) -> x
4210   if (N1C && N1C->isNullValue())
4211     return N0;
4212   // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4213   // sext_inreg.
4214   if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
4215     unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
4216     EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4217     if (VT.isVector())
4218       ExtVT = EVT::getVectorVT(*DAG.getContext(),
4219                                ExtVT, VT.getVectorNumElements());
4220     if ((!LegalOperations ||
4221          TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
4222       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
4223                          N0.getOperand(0), DAG.getValueType(ExtVT));
4224   }
4225
4226   // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
4227   if (N1C && N0.getOpcode() == ISD::SRA) {
4228     if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
4229       unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
4230       if (Sum >= OpSizeInBits)
4231         Sum = OpSizeInBits - 1;
4232       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0.getOperand(0),
4233                          DAG.getConstant(Sum, N1.getValueType()));
4234     }
4235   }
4236
4237   // fold (sra (shl X, m), (sub result_size, n))
4238   // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
4239   // result_size - n != m.
4240   // If truncate is free for the target sext(shl) is likely to result in better
4241   // code.
4242   if (N0.getOpcode() == ISD::SHL && N1C) {
4243     // Get the two constanst of the shifts, CN0 = m, CN = n.
4244     const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4245     if (N01C) {
4246       LLVMContext &Ctx = *DAG.getContext();
4247       // Determine what the truncate's result bitsize and type would be.
4248       EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4249
4250       if (VT.isVector())
4251         TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4252
4253       // Determine the residual right-shift amount.
4254       signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
4255
4256       // If the shift is not a no-op (in which case this should be just a sign
4257       // extend already), the truncated to type is legal, sign_extend is legal
4258       // on that type, and the truncate to that type is both legal and free,
4259       // perform the transform.
4260       if ((ShiftAmt > 0) &&
4261           TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4262           TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
4263           TLI.isTruncateFree(VT, TruncVT)) {
4264
4265           SDValue Amt = DAG.getConstant(ShiftAmt,
4266               getShiftAmountTy(N0.getOperand(0).getValueType()));
4267           SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), VT,
4268                                       N0.getOperand(0), Amt);
4269           SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), TruncVT,
4270                                       Shift);
4271           return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N),
4272                              N->getValueType(0), Trunc);
4273       }
4274     }
4275   }
4276
4277   // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
4278   if (N1.getOpcode() == ISD::TRUNCATE &&
4279       N1.getOperand(0).getOpcode() == ISD::AND) {
4280     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4281     if (NewOp1.getNode())
4282       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
4283   }
4284
4285   // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
4286   //      if c1 is equal to the number of bits the trunc removes
4287   if (N0.getOpcode() == ISD::TRUNCATE &&
4288       (N0.getOperand(0).getOpcode() == ISD::SRL ||
4289        N0.getOperand(0).getOpcode() == ISD::SRA) &&
4290       N0.getOperand(0).hasOneUse() &&
4291       N0.getOperand(0).getOperand(1).hasOneUse() &&
4292       N1C) {
4293     SDValue N0Op0 = N0.getOperand(0);
4294     if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4295       unsigned LargeShiftVal = LargeShift->getZExtValue();
4296       EVT LargeVT = N0Op0.getValueType();
4297
4298       if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4299         SDValue Amt =
4300           DAG.getConstant(LargeShiftVal + N1C->getZExtValue(),
4301                           getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4302         SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), LargeVT,
4303                                   N0Op0.getOperand(0), Amt);
4304         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, SRA);
4305       }
4306     }
4307   }
4308
4309   // Simplify, based on bits shifted out of the LHS.
4310   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4311     return SDValue(N, 0);
4312
4313
4314   // If the sign bit is known to be zero, switch this to a SRL.
4315   if (DAG.SignBitIsZero(N0))
4316     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
4317
4318   if (N1C) {
4319     SDValue NewSRA = visitShiftByConstant(N, N1C);
4320     if (NewSRA.getNode())
4321       return NewSRA;
4322   }
4323
4324   return SDValue();
4325 }
4326
4327 SDValue DAGCombiner::visitSRL(SDNode *N) {
4328   SDValue N0 = N->getOperand(0);
4329   SDValue N1 = N->getOperand(1);
4330   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4331   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4332   EVT VT = N0.getValueType();
4333   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4334
4335   // fold vector ops
4336   if (VT.isVector()) {
4337     SDValue FoldedVOp = SimplifyVBinOp(N);
4338     if (FoldedVOp.getNode()) return FoldedVOp;
4339
4340     N1C = isConstOrConstSplat(N1);
4341   }
4342
4343   // fold (srl c1, c2) -> c1 >>u c2
4344   if (N0C && N1C)
4345     return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C);
4346   // fold (srl 0, x) -> 0
4347   if (N0C && N0C->isNullValue())
4348     return N0;
4349   // fold (srl x, c >= size(x)) -> undef
4350   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4351     return DAG.getUNDEF(VT);
4352   // fold (srl x, 0) -> x
4353   if (N1C && N1C->isNullValue())
4354     return N0;
4355   // if (srl x, c) is known to be zero, return 0
4356   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4357                                    APInt::getAllOnesValue(OpSizeInBits)))
4358     return DAG.getConstant(0, VT);
4359
4360   // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
4361   if (N1C && N0.getOpcode() == ISD::SRL) {
4362     if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
4363       uint64_t c1 = N01C->getZExtValue();
4364       uint64_t c2 = N1C->getZExtValue();
4365       if (c1 + c2 >= OpSizeInBits)
4366         return DAG.getConstant(0, VT);
4367       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4368                          DAG.getConstant(c1 + c2, N1.getValueType()));
4369     }
4370   }
4371
4372   // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4373   if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4374       N0.getOperand(0).getOpcode() == ISD::SRL &&
4375       isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4376     uint64_t c1 =
4377       cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4378     uint64_t c2 = N1C->getZExtValue();
4379     EVT InnerShiftVT = N0.getOperand(0).getValueType();
4380     EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4381     uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
4382     // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4383     if (c1 + OpSizeInBits == InnerShiftSize) {
4384       if (c1 + c2 >= InnerShiftSize)
4385         return DAG.getConstant(0, VT);
4386       return DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT,
4387                          DAG.getNode(ISD::SRL, SDLoc(N0), InnerShiftVT,
4388                                      N0.getOperand(0)->getOperand(0),
4389                                      DAG.getConstant(c1 + c2, ShiftCountVT)));
4390     }
4391   }
4392
4393   // fold (srl (shl x, c), c) -> (and x, cst2)
4394   if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4395     unsigned BitSize = N0.getScalarValueSizeInBits();
4396     if (BitSize <= 64) {
4397       uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4398       return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4399                          DAG.getConstant(~0ULL >> ShAmt, VT));
4400     }
4401   }
4402
4403   // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4404   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4405     // Shifting in all undef bits?
4406     EVT SmallVT = N0.getOperand(0).getValueType();
4407     unsigned BitSize = SmallVT.getScalarSizeInBits();
4408     if (N1C->getZExtValue() >= BitSize)
4409       return DAG.getUNDEF(VT);
4410
4411     if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4412       uint64_t ShiftAmt = N1C->getZExtValue();
4413       SDValue SmallShift = DAG.getNode(ISD::SRL, SDLoc(N0), SmallVT,
4414                                        N0.getOperand(0),
4415                           DAG.getConstant(ShiftAmt, getShiftAmountTy(SmallVT)));
4416       AddToWorklist(SmallShift.getNode());
4417       APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
4418       return DAG.getNode(ISD::AND, SDLoc(N), VT,
4419                          DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, SmallShift),
4420                          DAG.getConstant(Mask, VT));
4421     }
4422   }
4423
4424   // fold (srl (sra X, Y), 31) -> (srl X, 31).  This srl only looks at the sign
4425   // bit, which is unmodified by sra.
4426   if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
4427     if (N0.getOpcode() == ISD::SRA)
4428       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4429   }
4430
4431   // fold (srl (ctlz x), "5") -> x  iff x has one bit set (the low bit).
4432   if (N1C && N0.getOpcode() == ISD::CTLZ &&
4433       N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
4434     APInt KnownZero, KnownOne;
4435     DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne);
4436
4437     // If any of the input bits are KnownOne, then the input couldn't be all
4438     // zeros, thus the result of the srl will always be zero.
4439     if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
4440
4441     // If all of the bits input the to ctlz node are known to be zero, then
4442     // the result of the ctlz is "32" and the result of the shift is one.
4443     APInt UnknownBits = ~KnownZero;
4444     if (UnknownBits == 0) return DAG.getConstant(1, VT);
4445
4446     // Otherwise, check to see if there is exactly one bit input to the ctlz.
4447     if ((UnknownBits & (UnknownBits - 1)) == 0) {
4448       // Okay, we know that only that the single bit specified by UnknownBits
4449       // could be set on input to the CTLZ node. If this bit is set, the SRL
4450       // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4451       // to an SRL/XOR pair, which is likely to simplify more.
4452       unsigned ShAmt = UnknownBits.countTrailingZeros();
4453       SDValue Op = N0.getOperand(0);
4454
4455       if (ShAmt) {
4456         Op = DAG.getNode(ISD::SRL, SDLoc(N0), VT, Op,
4457                   DAG.getConstant(ShAmt, getShiftAmountTy(Op.getValueType())));
4458         AddToWorklist(Op.getNode());
4459       }
4460
4461       return DAG.getNode(ISD::XOR, SDLoc(N), VT,
4462                          Op, DAG.getConstant(1, VT));
4463     }
4464   }
4465
4466   // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4467   if (N1.getOpcode() == ISD::TRUNCATE &&
4468       N1.getOperand(0).getOpcode() == ISD::AND) {
4469     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4470     if (NewOp1.getNode())
4471       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
4472   }
4473
4474   // fold operands of srl based on knowledge that the low bits are not
4475   // demanded.
4476   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4477     return SDValue(N, 0);
4478
4479   if (N1C) {
4480     SDValue NewSRL = visitShiftByConstant(N, N1C);
4481     if (NewSRL.getNode())
4482       return NewSRL;
4483   }
4484
4485   // Attempt to convert a srl of a load into a narrower zero-extending load.
4486   SDValue NarrowLoad = ReduceLoadWidth(N);
4487   if (NarrowLoad.getNode())
4488     return NarrowLoad;
4489
4490   // Here is a common situation. We want to optimize:
4491   //
4492   //   %a = ...
4493   //   %b = and i32 %a, 2
4494   //   %c = srl i32 %b, 1
4495   //   brcond i32 %c ...
4496   //
4497   // into
4498   //
4499   //   %a = ...
4500   //   %b = and %a, 2
4501   //   %c = setcc eq %b, 0
4502   //   brcond %c ...
4503   //
4504   // However when after the source operand of SRL is optimized into AND, the SRL
4505   // itself may not be optimized further. Look for it and add the BRCOND into
4506   // the worklist.
4507   if (N->hasOneUse()) {
4508     SDNode *Use = *N->use_begin();
4509     if (Use->getOpcode() == ISD::BRCOND)
4510       AddToWorklist(Use);
4511     else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4512       // Also look pass the truncate.
4513       Use = *Use->use_begin();
4514       if (Use->getOpcode() == ISD::BRCOND)
4515         AddToWorklist(Use);
4516     }
4517   }
4518
4519   return SDValue();
4520 }
4521
4522 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4523   SDValue N0 = N->getOperand(0);
4524   EVT VT = N->getValueType(0);
4525
4526   // fold (ctlz c1) -> c2
4527   if (isa<ConstantSDNode>(N0))
4528     return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
4529   return SDValue();
4530 }
4531
4532 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4533   SDValue N0 = N->getOperand(0);
4534   EVT VT = N->getValueType(0);
4535
4536   // fold (ctlz_zero_undef c1) -> c2
4537   if (isa<ConstantSDNode>(N0))
4538     return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4539   return SDValue();
4540 }
4541
4542 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4543   SDValue N0 = N->getOperand(0);
4544   EVT VT = N->getValueType(0);
4545
4546   // fold (cttz c1) -> c2
4547   if (isa<ConstantSDNode>(N0))
4548     return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
4549   return SDValue();
4550 }
4551
4552 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4553   SDValue N0 = N->getOperand(0);
4554   EVT VT = N->getValueType(0);
4555
4556   // fold (cttz_zero_undef c1) -> c2
4557   if (isa<ConstantSDNode>(N0))
4558     return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4559   return SDValue();
4560 }
4561
4562 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4563   SDValue N0 = N->getOperand(0);
4564   EVT VT = N->getValueType(0);
4565
4566   // fold (ctpop c1) -> c2
4567   if (isa<ConstantSDNode>(N0))
4568     return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
4569   return SDValue();
4570 }
4571
4572 SDValue DAGCombiner::visitSELECT(SDNode *N) {
4573   SDValue N0 = N->getOperand(0);
4574   SDValue N1 = N->getOperand(1);
4575   SDValue N2 = N->getOperand(2);
4576   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4577   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4578   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
4579   EVT VT = N->getValueType(0);
4580   EVT VT0 = N0.getValueType();
4581
4582   // fold (select C, X, X) -> X
4583   if (N1 == N2)
4584     return N1;
4585   // fold (select true, X, Y) -> X
4586   if (N0C && !N0C->isNullValue())
4587     return N1;
4588   // fold (select false, X, Y) -> Y
4589   if (N0C && N0C->isNullValue())
4590     return N2;
4591   // fold (select C, 1, X) -> (or C, X)
4592   if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
4593     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4594   // fold (select C, 0, 1) -> (xor C, 1)
4595   // We can't do this reliably if integer based booleans have different contents
4596   // to floating point based booleans. This is because we can't tell whether we
4597   // have an integer-based boolean or a floating-point-based boolean unless we
4598   // can find the SETCC that produced it and inspect its operands. This is
4599   // fairly easy if C is the SETCC node, but it can potentially be
4600   // undiscoverable (or not reasonably discoverable). For example, it could be
4601   // in another basic block or it could require searching a complicated
4602   // expression.
4603   if (VT.isInteger() &&
4604       (VT0 == MVT::i1 || (VT0.isInteger() &&
4605                           TLI.getBooleanContents(false, false) ==
4606                               TLI.getBooleanContents(false, true) &&
4607                           TLI.getBooleanContents(false, false) ==
4608                               TargetLowering::ZeroOrOneBooleanContent)) &&
4609       N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
4610     SDValue XORNode;
4611     if (VT == VT0)
4612       return DAG.getNode(ISD::XOR, SDLoc(N), VT0,
4613                          N0, DAG.getConstant(1, VT0));
4614     XORNode = DAG.getNode(ISD::XOR, SDLoc(N0), VT0,
4615                           N0, DAG.getConstant(1, VT0));
4616     AddToWorklist(XORNode.getNode());
4617     if (VT.bitsGT(VT0))
4618       return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4619     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
4620   }
4621   // fold (select C, 0, X) -> (and (not C), X)
4622   if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
4623     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4624     AddToWorklist(NOTNode.getNode());
4625     return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
4626   }
4627   // fold (select C, X, 1) -> (or (not C), X)
4628   if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
4629     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4630     AddToWorklist(NOTNode.getNode());
4631     return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
4632   }
4633   // fold (select C, X, 0) -> (and C, X)
4634   if (VT == MVT::i1 && N2C && N2C->isNullValue())
4635     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4636   // fold (select X, X, Y) -> (or X, Y)
4637   // fold (select X, 1, Y) -> (or X, Y)
4638   if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
4639     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4640   // fold (select X, Y, X) -> (and X, Y)
4641   // fold (select X, Y, 0) -> (and X, Y)
4642   if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
4643     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4644
4645   // If we can fold this based on the true/false value, do so.
4646   if (SimplifySelectOps(N, N1, N2))
4647     return SDValue(N, 0);  // Don't revisit N.
4648
4649   // fold selects based on a setcc into other things, such as min/max/abs
4650   if (N0.getOpcode() == ISD::SETCC) {
4651     if ((!LegalOperations &&
4652          TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
4653         TLI.isOperationLegal(ISD::SELECT_CC, VT))
4654       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
4655                          N0.getOperand(0), N0.getOperand(1),
4656                          N1, N2, N0.getOperand(2));
4657     return SimplifySelect(SDLoc(N), N0, N1, N2);
4658   }
4659
4660   return SDValue();
4661 }
4662
4663 static
4664 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
4665   SDLoc DL(N);
4666   EVT LoVT, HiVT;
4667   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
4668
4669   // Split the inputs.
4670   SDValue Lo, Hi, LL, LH, RL, RH;
4671   std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
4672   std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
4673
4674   Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
4675   Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
4676
4677   return std::make_pair(Lo, Hi);
4678 }
4679
4680 // This function assumes all the vselect's arguments are CONCAT_VECTOR
4681 // nodes and that the condition is a BV of ConstantSDNodes (or undefs).
4682 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
4683   SDLoc dl(N);
4684   SDValue Cond = N->getOperand(0);
4685   SDValue LHS = N->getOperand(1);
4686   SDValue RHS = N->getOperand(2);
4687   EVT VT = N->getValueType(0);
4688   int NumElems = VT.getVectorNumElements();
4689   assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
4690          RHS.getOpcode() == ISD::CONCAT_VECTORS &&
4691          Cond.getOpcode() == ISD::BUILD_VECTOR);
4692
4693   // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about
4694   // binary ones here.
4695   if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2)
4696     return SDValue();
4697
4698   // We're sure we have an even number of elements due to the
4699   // concat_vectors we have as arguments to vselect.
4700   // Skip BV elements until we find one that's not an UNDEF
4701   // After we find an UNDEF element, keep looping until we get to half the
4702   // length of the BV and see if all the non-undef nodes are the same.
4703   ConstantSDNode *BottomHalf = nullptr;
4704   for (int i = 0; i < NumElems / 2; ++i) {
4705     if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
4706       continue;
4707
4708     if (BottomHalf == nullptr)
4709       BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
4710     else if (Cond->getOperand(i).getNode() != BottomHalf)
4711       return SDValue();
4712   }
4713
4714   // Do the same for the second half of the BuildVector
4715   ConstantSDNode *TopHalf = nullptr;
4716   for (int i = NumElems / 2; i < NumElems; ++i) {
4717     if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
4718       continue;
4719
4720     if (TopHalf == nullptr)
4721       TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
4722     else if (Cond->getOperand(i).getNode() != TopHalf)
4723       return SDValue();
4724   }
4725
4726   assert(TopHalf && BottomHalf &&
4727          "One half of the selector was all UNDEFs and the other was all the "
4728          "same value. This should have been addressed before this function.");
4729   return DAG.getNode(
4730       ISD::CONCAT_VECTORS, dl, VT,
4731       BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
4732       TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
4733 }
4734
4735 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
4736   SDValue N0 = N->getOperand(0);
4737   SDValue N1 = N->getOperand(1);
4738   SDValue N2 = N->getOperand(2);
4739   SDLoc DL(N);
4740
4741   // Canonicalize integer abs.
4742   // vselect (setg[te] X,  0),  X, -X ->
4743   // vselect (setgt    X, -1),  X, -X ->
4744   // vselect (setl[te] X,  0), -X,  X ->
4745   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
4746   if (N0.getOpcode() == ISD::SETCC) {
4747     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4748     ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4749     bool isAbs = false;
4750     bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
4751
4752     if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
4753          (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
4754         N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
4755       isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
4756     else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
4757              N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
4758       isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
4759
4760     if (isAbs) {
4761       EVT VT = LHS.getValueType();
4762       SDValue Shift = DAG.getNode(
4763           ISD::SRA, DL, VT, LHS,
4764           DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, VT));
4765       SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
4766       AddToWorklist(Shift.getNode());
4767       AddToWorklist(Add.getNode());
4768       return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
4769     }
4770   }
4771
4772   // If the VSELECT result requires splitting and the mask is provided by a
4773   // SETCC, then split both nodes and its operands before legalization. This
4774   // prevents the type legalizer from unrolling SETCC into scalar comparisons
4775   // and enables future optimizations (e.g. min/max pattern matching on X86).
4776   if (N0.getOpcode() == ISD::SETCC) {
4777     EVT VT = N->getValueType(0);
4778
4779     // Check if any splitting is required.
4780     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
4781         TargetLowering::TypeSplitVector)
4782       return SDValue();
4783
4784     SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
4785     std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
4786     std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
4787     std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
4788
4789     Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
4790     Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
4791
4792     // Add the new VSELECT nodes to the work list in case they need to be split
4793     // again.
4794     AddToWorklist(Lo.getNode());
4795     AddToWorklist(Hi.getNode());
4796
4797     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
4798   }
4799
4800   // Fold (vselect (build_vector all_ones), N1, N2) -> N1
4801   if (ISD::isBuildVectorAllOnes(N0.getNode()))
4802     return N1;
4803   // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
4804   if (ISD::isBuildVectorAllZeros(N0.getNode()))
4805     return N2;
4806
4807   // The ConvertSelectToConcatVector function is assuming both the above
4808   // checks for (vselect (build_vector all{ones,zeros) ...) have been made
4809   // and addressed.
4810   if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
4811       N2.getOpcode() == ISD::CONCAT_VECTORS &&
4812       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
4813     SDValue CV = ConvertSelectToConcatVector(N, DAG);
4814     if (CV.getNode())
4815       return CV;
4816   }
4817
4818   return SDValue();
4819 }
4820
4821 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
4822   SDValue N0 = N->getOperand(0);
4823   SDValue N1 = N->getOperand(1);
4824   SDValue N2 = N->getOperand(2);
4825   SDValue N3 = N->getOperand(3);
4826   SDValue N4 = N->getOperand(4);
4827   ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
4828
4829   // fold select_cc lhs, rhs, x, x, cc -> x
4830   if (N2 == N3)
4831     return N2;
4832
4833   // Determine if the condition we're dealing with is constant
4834   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
4835                               N0, N1, CC, SDLoc(N), false);
4836   if (SCC.getNode()) {
4837     AddToWorklist(SCC.getNode());
4838
4839     if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
4840       if (!SCCC->isNullValue())
4841         return N2;    // cond always true -> true val
4842       else
4843         return N3;    // cond always false -> false val
4844     }
4845
4846     // Fold to a simpler select_cc
4847     if (SCC.getOpcode() == ISD::SETCC)
4848       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
4849                          SCC.getOperand(0), SCC.getOperand(1), N2, N3,
4850                          SCC.getOperand(2));
4851   }
4852
4853   // If we can fold this based on the true/false value, do so.
4854   if (SimplifySelectOps(N, N2, N3))
4855     return SDValue(N, 0);  // Don't revisit N.
4856
4857   // fold select_cc into other things, such as min/max/abs
4858   return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
4859 }
4860
4861 SDValue DAGCombiner::visitSETCC(SDNode *N) {
4862   return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
4863                        cast<CondCodeSDNode>(N->getOperand(2))->get(),
4864                        SDLoc(N));
4865 }
4866
4867 // tryToFoldExtendOfConstant - Try to fold a sext/zext/aext
4868 // dag node into a ConstantSDNode or a build_vector of constants.
4869 // This function is called by the DAGCombiner when visiting sext/zext/aext
4870 // dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
4871 // Vector extends are not folded if operations are legal; this is to
4872 // avoid introducing illegal build_vector dag nodes.
4873 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
4874                                          SelectionDAG &DAG, bool LegalTypes,
4875                                          bool LegalOperations) {
4876   unsigned Opcode = N->getOpcode();
4877   SDValue N0 = N->getOperand(0);
4878   EVT VT = N->getValueType(0);
4879
4880   assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
4881          Opcode == ISD::ANY_EXTEND) && "Expected EXTEND dag node in input!");
4882
4883   // fold (sext c1) -> c1
4884   // fold (zext c1) -> c1
4885   // fold (aext c1) -> c1
4886   if (isa<ConstantSDNode>(N0))
4887     return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
4888
4889   // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
4890   // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
4891   // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
4892   EVT SVT = VT.getScalarType();
4893   if (!(VT.isVector() &&
4894       (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
4895       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
4896     return nullptr;
4897
4898   // We can fold this node into a build_vector.
4899   unsigned VTBits = SVT.getSizeInBits();
4900   unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
4901   unsigned ShAmt = VTBits - EVTBits;
4902   SmallVector<SDValue, 8> Elts;
4903   unsigned NumElts = N0->getNumOperands();
4904   SDLoc DL(N);
4905
4906   for (unsigned i=0; i != NumElts; ++i) {
4907     SDValue Op = N0->getOperand(i);
4908     if (Op->getOpcode() == ISD::UNDEF) {
4909       Elts.push_back(DAG.getUNDEF(SVT));
4910       continue;
4911     }
4912
4913     ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
4914     const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
4915     if (Opcode == ISD::SIGN_EXTEND)
4916       Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
4917                                      SVT));
4918     else
4919       Elts.push_back(DAG.getConstant(C.shl(ShAmt).lshr(ShAmt).getZExtValue(),
4920                                      SVT));
4921   }
4922
4923   return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts).getNode();
4924 }
4925
4926 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
4927 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
4928 // transformation. Returns true if extension are possible and the above
4929 // mentioned transformation is profitable.
4930 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
4931                                     unsigned ExtOpc,
4932                                     SmallVectorImpl<SDNode *> &ExtendNodes,
4933                                     const TargetLowering &TLI) {
4934   bool HasCopyToRegUses = false;
4935   bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
4936   for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
4937                             UE = N0.getNode()->use_end();
4938        UI != UE; ++UI) {
4939     SDNode *User = *UI;
4940     if (User == N)
4941       continue;
4942     if (UI.getUse().getResNo() != N0.getResNo())
4943       continue;
4944     // FIXME: Only extend SETCC N, N and SETCC N, c for now.
4945     if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
4946       ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
4947       if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
4948         // Sign bits will be lost after a zext.
4949         return false;
4950       bool Add = false;
4951       for (unsigned i = 0; i != 2; ++i) {
4952         SDValue UseOp = User->getOperand(i);
4953         if (UseOp == N0)
4954           continue;
4955         if (!isa<ConstantSDNode>(UseOp))
4956           return false;
4957         Add = true;
4958       }
4959       if (Add)
4960         ExtendNodes.push_back(User);
4961       continue;
4962     }
4963     // If truncates aren't free and there are users we can't
4964     // extend, it isn't worthwhile.
4965     if (!isTruncFree)
4966       return false;
4967     // Remember if this value is live-out.
4968     if (User->getOpcode() == ISD::CopyToReg)
4969       HasCopyToRegUses = true;
4970   }
4971
4972   if (HasCopyToRegUses) {
4973     bool BothLiveOut = false;
4974     for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
4975          UI != UE; ++UI) {
4976       SDUse &Use = UI.getUse();
4977       if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
4978         BothLiveOut = true;
4979         break;
4980       }
4981     }
4982     if (BothLiveOut)
4983       // Both unextended and extended values are live out. There had better be
4984       // a good reason for the transformation.
4985       return ExtendNodes.size();
4986   }
4987   return true;
4988 }
4989
4990 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
4991                                   SDValue Trunc, SDValue ExtLoad, SDLoc DL,
4992                                   ISD::NodeType ExtType) {
4993   // Extend SetCC uses if necessary.
4994   for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
4995     SDNode *SetCC = SetCCs[i];
4996     SmallVector<SDValue, 4> Ops;
4997
4998     for (unsigned j = 0; j != 2; ++j) {
4999       SDValue SOp = SetCC->getOperand(j);
5000       if (SOp == Trunc)
5001         Ops.push_back(ExtLoad);
5002       else
5003         Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
5004     }
5005
5006     Ops.push_back(SetCC->getOperand(2));
5007     CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
5008   }
5009 }
5010
5011 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
5012   SDValue N0 = N->getOperand(0);
5013   EVT VT = N->getValueType(0);
5014
5015   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5016                                               LegalOperations))
5017     return SDValue(Res, 0);
5018
5019   // fold (sext (sext x)) -> (sext x)
5020   // fold (sext (aext x)) -> (sext x)
5021   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5022     return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
5023                        N0.getOperand(0));
5024
5025   if (N0.getOpcode() == ISD::TRUNCATE) {
5026     // fold (sext (truncate (load x))) -> (sext (smaller load x))
5027     // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
5028     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5029     if (NarrowLoad.getNode()) {
5030       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5031       if (NarrowLoad.getNode() != N0.getNode()) {
5032         CombineTo(N0.getNode(), NarrowLoad);
5033         // CombineTo deleted the truncate, if needed, but not what's under it.
5034         AddToWorklist(oye);
5035       }
5036       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5037     }
5038
5039     // See if the value being truncated is already sign extended.  If so, just
5040     // eliminate the trunc/sext pair.
5041     SDValue Op = N0.getOperand(0);
5042     unsigned OpBits   = Op.getValueType().getScalarType().getSizeInBits();
5043     unsigned MidBits  = N0.getValueType().getScalarType().getSizeInBits();
5044     unsigned DestBits = VT.getScalarType().getSizeInBits();
5045     unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
5046
5047     if (OpBits == DestBits) {
5048       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
5049       // bits, it is already ready.
5050       if (NumSignBits > DestBits-MidBits)
5051         return Op;
5052     } else if (OpBits < DestBits) {
5053       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
5054       // bits, just sext from i32.
5055       if (NumSignBits > OpBits-MidBits)
5056         return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
5057     } else {
5058       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
5059       // bits, just truncate to i32.
5060       if (NumSignBits > OpBits-MidBits)
5061         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5062     }
5063
5064     // fold (sext (truncate x)) -> (sextinreg x).
5065     if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
5066                                                  N0.getValueType())) {
5067       if (OpBits < DestBits)
5068         Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
5069       else if (OpBits > DestBits)
5070         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
5071       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
5072                          DAG.getValueType(N0.getValueType()));
5073     }
5074   }
5075
5076   // fold (sext (load x)) -> (sext (truncate (sextload x)))
5077   // None of the supported targets knows how to perform load and sign extend
5078   // on vectors in one instruction.  We only perform this transformation on
5079   // scalars.
5080   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5081       ISD::isUNINDEXEDLoad(N0.getNode()) &&
5082       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5083        TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()))) {
5084     bool DoXform = true;
5085     SmallVector<SDNode*, 4> SetCCs;
5086     if (!N0.hasOneUse())
5087       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
5088     if (DoXform) {
5089       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5090       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5091                                        LN0->getChain(),
5092                                        LN0->getBasePtr(), N0.getValueType(),
5093                                        LN0->getMemOperand());
5094       CombineTo(N, ExtLoad);
5095       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5096                                   N0.getValueType(), ExtLoad);
5097       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5098       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5099                       ISD::SIGN_EXTEND);
5100       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5101     }
5102   }
5103
5104   // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
5105   // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
5106   if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5107       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5108     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5109     EVT MemVT = LN0->getMemoryVT();
5110     if ((!LegalOperations && !LN0->isVolatile()) ||
5111         TLI.isLoadExtLegal(ISD::SEXTLOAD, MemVT)) {
5112       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5113                                        LN0->getChain(),
5114                                        LN0->getBasePtr(), MemVT,
5115                                        LN0->getMemOperand());
5116       CombineTo(N, ExtLoad);
5117       CombineTo(N0.getNode(),
5118                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5119                             N0.getValueType(), ExtLoad),
5120                 ExtLoad.getValue(1));
5121       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5122     }
5123   }
5124
5125   // fold (sext (and/or/xor (load x), cst)) ->
5126   //      (and/or/xor (sextload x), (sext cst))
5127   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5128        N0.getOpcode() == ISD::XOR) &&
5129       isa<LoadSDNode>(N0.getOperand(0)) &&
5130       N0.getOperand(1).getOpcode() == ISD::Constant &&
5131       TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()) &&
5132       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5133     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5134     if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
5135       bool DoXform = true;
5136       SmallVector<SDNode*, 4> SetCCs;
5137       if (!N0.hasOneUse())
5138         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
5139                                           SetCCs, TLI);
5140       if (DoXform) {
5141         SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
5142                                          LN0->getChain(), LN0->getBasePtr(),
5143                                          LN0->getMemoryVT(),
5144                                          LN0->getMemOperand());
5145         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5146         Mask = Mask.sext(VT.getSizeInBits());
5147         SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5148                                   ExtLoad, DAG.getConstant(Mask, VT));
5149         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5150                                     SDLoc(N0.getOperand(0)),
5151                                     N0.getOperand(0).getValueType(), ExtLoad);
5152         CombineTo(N, And);
5153         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5154         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5155                         ISD::SIGN_EXTEND);
5156         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5157       }
5158     }
5159   }
5160
5161   if (N0.getOpcode() == ISD::SETCC) {
5162     EVT N0VT = N0.getOperand(0).getValueType();
5163     // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
5164     // Only do this before legalize for now.
5165     if (VT.isVector() && !LegalOperations &&
5166         TLI.getBooleanContents(N0VT) ==
5167             TargetLowering::ZeroOrNegativeOneBooleanContent) {
5168       // On some architectures (such as SSE/NEON/etc) the SETCC result type is
5169       // of the same size as the compared operands. Only optimize sext(setcc())
5170       // if this is the case.
5171       EVT SVT = getSetCCResultType(N0VT);
5172
5173       // We know that the # elements of the results is the same as the
5174       // # elements of the compare (and the # elements of the compare result
5175       // for that matter).  Check to see that they are the same size.  If so,
5176       // we know that the element size of the sext'd result matches the
5177       // element size of the compare operands.
5178       if (VT.getSizeInBits() == SVT.getSizeInBits())
5179         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5180                              N0.getOperand(1),
5181                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
5182
5183       // If the desired elements are smaller or larger than the source
5184       // elements we can use a matching integer vector type and then
5185       // truncate/sign extend
5186       EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5187       if (SVT == MatchingVectorType) {
5188         SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
5189                                N0.getOperand(0), N0.getOperand(1),
5190                                cast<CondCodeSDNode>(N0.getOperand(2))->get());
5191         return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
5192       }
5193     }
5194
5195     // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
5196     unsigned ElementWidth = VT.getScalarType().getSizeInBits();
5197     SDValue NegOne =
5198       DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT);
5199     SDValue SCC =
5200       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5201                        NegOne, DAG.getConstant(0, VT),
5202                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5203     if (SCC.getNode()) return SCC;
5204
5205     if (!VT.isVector()) {
5206       EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
5207       if (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, SetCCVT)) {
5208         SDLoc DL(N);
5209         ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5210         SDValue SetCC = DAG.getSetCC(DL,
5211                                      SetCCVT,
5212                                      N0.getOperand(0), N0.getOperand(1), CC);
5213         EVT SelectVT = getSetCCResultType(VT);
5214         return DAG.getSelect(DL, VT,
5215                              DAG.getSExtOrTrunc(SetCC, DL, SelectVT),
5216                              NegOne, DAG.getConstant(0, VT));
5217
5218       }
5219     }
5220   }
5221
5222   // fold (sext x) -> (zext x) if the sign bit is known zero.
5223   if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
5224       DAG.SignBitIsZero(N0))
5225     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
5226
5227   return SDValue();
5228 }
5229
5230 // isTruncateOf - If N is a truncate of some other value, return true, record
5231 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
5232 // This function computes KnownZero to avoid a duplicated call to
5233 // computeKnownBits in the caller.
5234 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
5235                          APInt &KnownZero) {
5236   APInt KnownOne;
5237   if (N->getOpcode() == ISD::TRUNCATE) {
5238     Op = N->getOperand(0);
5239     DAG.computeKnownBits(Op, KnownZero, KnownOne);
5240     return true;
5241   }
5242
5243   if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
5244       cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
5245     return false;
5246
5247   SDValue Op0 = N->getOperand(0);
5248   SDValue Op1 = N->getOperand(1);
5249   assert(Op0.getValueType() == Op1.getValueType());
5250
5251   ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0);
5252   ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
5253   if (COp0 && COp0->isNullValue())
5254     Op = Op1;
5255   else if (COp1 && COp1->isNullValue())
5256     Op = Op0;
5257   else
5258     return false;
5259
5260   DAG.computeKnownBits(Op, KnownZero, KnownOne);
5261
5262   if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
5263     return false;
5264
5265   return true;
5266 }
5267
5268 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
5269   SDValue N0 = N->getOperand(0);
5270   EVT VT = N->getValueType(0);
5271
5272   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5273                                               LegalOperations))
5274     return SDValue(Res, 0);
5275
5276   // fold (zext (zext x)) -> (zext x)
5277   // fold (zext (aext x)) -> (zext x)
5278   if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5279     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
5280                        N0.getOperand(0));
5281
5282   // fold (zext (truncate x)) -> (zext x) or
5283   //      (zext (truncate x)) -> (truncate x)
5284   // This is valid when the truncated bits of x are already zero.
5285   // FIXME: We should extend this to work for vectors too.
5286   SDValue Op;
5287   APInt KnownZero;
5288   if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
5289     APInt TruncatedBits =
5290       (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
5291       APInt(Op.getValueSizeInBits(), 0) :
5292       APInt::getBitsSet(Op.getValueSizeInBits(),
5293                         N0.getValueSizeInBits(),
5294                         std::min(Op.getValueSizeInBits(),
5295                                  VT.getSizeInBits()));
5296     if (TruncatedBits == (KnownZero & TruncatedBits)) {
5297       if (VT.bitsGT(Op.getValueType()))
5298         return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
5299       if (VT.bitsLT(Op.getValueType()))
5300         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5301
5302       return Op;
5303     }
5304   }
5305
5306   // fold (zext (truncate (load x))) -> (zext (smaller load x))
5307   // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
5308   if (N0.getOpcode() == ISD::TRUNCATE) {
5309     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5310     if (NarrowLoad.getNode()) {
5311       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5312       if (NarrowLoad.getNode() != N0.getNode()) {
5313         CombineTo(N0.getNode(), NarrowLoad);
5314         // CombineTo deleted the truncate, if needed, but not what's under it.
5315         AddToWorklist(oye);
5316       }
5317       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5318     }
5319   }
5320
5321   // fold (zext (truncate x)) -> (and x, mask)
5322   if (N0.getOpcode() == ISD::TRUNCATE &&
5323       (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
5324
5325     // fold (zext (truncate (load x))) -> (zext (smaller load x))
5326     // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
5327     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5328     if (NarrowLoad.getNode()) {
5329       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5330       if (NarrowLoad.getNode() != N0.getNode()) {
5331         CombineTo(N0.getNode(), NarrowLoad);
5332         // CombineTo deleted the truncate, if needed, but not what's under it.
5333         AddToWorklist(oye);
5334       }
5335       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5336     }
5337
5338     SDValue Op = N0.getOperand(0);
5339     if (Op.getValueType().bitsLT(VT)) {
5340       Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
5341       AddToWorklist(Op.getNode());
5342     } else if (Op.getValueType().bitsGT(VT)) {
5343       Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5344       AddToWorklist(Op.getNode());
5345     }
5346     return DAG.getZeroExtendInReg(Op, SDLoc(N),
5347                                   N0.getValueType().getScalarType());
5348   }
5349
5350   // Fold (zext (and (trunc x), cst)) -> (and x, cst),
5351   // if either of the casts is not free.
5352   if (N0.getOpcode() == ISD::AND &&
5353       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5354       N0.getOperand(1).getOpcode() == ISD::Constant &&
5355       (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5356                            N0.getValueType()) ||
5357        !TLI.isZExtFree(N0.getValueType(), VT))) {
5358     SDValue X = N0.getOperand(0).getOperand(0);
5359     if (X.getValueType().bitsLT(VT)) {
5360       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
5361     } else if (X.getValueType().bitsGT(VT)) {
5362       X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
5363     }
5364     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5365     Mask = Mask.zext(VT.getSizeInBits());
5366     return DAG.getNode(ISD::AND, SDLoc(N), VT,
5367                        X, DAG.getConstant(Mask, VT));
5368   }
5369
5370   // fold (zext (load x)) -> (zext (truncate (zextload x)))
5371   // None of the supported targets knows how to perform load and vector_zext
5372   // on vectors in one instruction.  We only perform this transformation on
5373   // scalars.
5374   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5375       ISD::isUNINDEXEDLoad(N0.getNode()) &&
5376       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5377        TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()))) {
5378     bool DoXform = true;
5379     SmallVector<SDNode*, 4> SetCCs;
5380     if (!N0.hasOneUse())
5381       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
5382     if (DoXform) {
5383       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5384       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5385                                        LN0->getChain(),
5386                                        LN0->getBasePtr(), N0.getValueType(),
5387                                        LN0->getMemOperand());
5388       CombineTo(N, ExtLoad);
5389       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5390                                   N0.getValueType(), ExtLoad);
5391       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5392
5393       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5394                       ISD::ZERO_EXTEND);
5395       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5396     }
5397   }
5398
5399   // fold (zext (and/or/xor (load x), cst)) ->
5400   //      (and/or/xor (zextload x), (zext cst))
5401   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5402        N0.getOpcode() == ISD::XOR) &&
5403       isa<LoadSDNode>(N0.getOperand(0)) &&
5404       N0.getOperand(1).getOpcode() == ISD::Constant &&
5405       TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()) &&
5406       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5407     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5408     if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
5409       bool DoXform = true;
5410       SmallVector<SDNode*, 4> SetCCs;
5411       if (!N0.hasOneUse())
5412         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
5413                                           SetCCs, TLI);
5414       if (DoXform) {
5415         SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
5416                                          LN0->getChain(), LN0->getBasePtr(),
5417                                          LN0->getMemoryVT(),
5418                                          LN0->getMemOperand());
5419         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5420         Mask = Mask.zext(VT.getSizeInBits());
5421         SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5422                                   ExtLoad, DAG.getConstant(Mask, VT));
5423         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5424                                     SDLoc(N0.getOperand(0)),
5425                                     N0.getOperand(0).getValueType(), ExtLoad);
5426         CombineTo(N, And);
5427         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5428         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5429                         ISD::ZERO_EXTEND);
5430         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5431       }
5432     }
5433   }
5434
5435   // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
5436   // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
5437   if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5438       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5439     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5440     EVT MemVT = LN0->getMemoryVT();
5441     if ((!LegalOperations && !LN0->isVolatile()) ||
5442         TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT)) {
5443       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5444                                        LN0->getChain(),
5445                                        LN0->getBasePtr(), MemVT,
5446                                        LN0->getMemOperand());
5447       CombineTo(N, ExtLoad);
5448       CombineTo(N0.getNode(),
5449                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
5450                             ExtLoad),
5451                 ExtLoad.getValue(1));
5452       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5453     }
5454   }
5455
5456   if (N0.getOpcode() == ISD::SETCC) {
5457     if (!LegalOperations && VT.isVector() &&
5458         N0.getValueType().getVectorElementType() == MVT::i1) {
5459       EVT N0VT = N0.getOperand(0).getValueType();
5460       if (getSetCCResultType(N0VT) == N0.getValueType())
5461         return SDValue();
5462
5463       // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
5464       // Only do this before legalize for now.
5465       EVT EltVT = VT.getVectorElementType();
5466       SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
5467                                     DAG.getConstant(1, EltVT));
5468       if (VT.getSizeInBits() == N0VT.getSizeInBits())
5469         // We know that the # elements of the results is the same as the
5470         // # elements of the compare (and the # elements of the compare result
5471         // for that matter).  Check to see that they are the same size.  If so,
5472         // we know that the element size of the sext'd result matches the
5473         // element size of the compare operands.
5474         return DAG.getNode(ISD::AND, SDLoc(N), VT,
5475                            DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5476                                          N0.getOperand(1),
5477                                  cast<CondCodeSDNode>(N0.getOperand(2))->get()),
5478                            DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
5479                                        OneOps));
5480
5481       // If the desired elements are smaller or larger than the source
5482       // elements we can use a matching integer vector type and then
5483       // truncate/sign extend
5484       EVT MatchingElementType =
5485         EVT::getIntegerVT(*DAG.getContext(),
5486                           N0VT.getScalarType().getSizeInBits());
5487       EVT MatchingVectorType =
5488         EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
5489                          N0VT.getVectorNumElements());
5490       SDValue VsetCC =
5491         DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5492                       N0.getOperand(1),
5493                       cast<CondCodeSDNode>(N0.getOperand(2))->get());
5494       return DAG.getNode(ISD::AND, SDLoc(N), VT,
5495                          DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT),
5496                          DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, OneOps));
5497     }
5498
5499     // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5500     SDValue SCC =
5501       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5502                        DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5503                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5504     if (SCC.getNode()) return SCC;
5505   }
5506
5507   // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
5508   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
5509       isa<ConstantSDNode>(N0.getOperand(1)) &&
5510       N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
5511       N0.hasOneUse()) {
5512     SDValue ShAmt = N0.getOperand(1);
5513     unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
5514     if (N0.getOpcode() == ISD::SHL) {
5515       SDValue InnerZExt = N0.getOperand(0);
5516       // If the original shl may be shifting out bits, do not perform this
5517       // transformation.
5518       unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
5519         InnerZExt.getOperand(0).getValueType().getSizeInBits();
5520       if (ShAmtVal > KnownZeroBits)
5521         return SDValue();
5522     }
5523
5524     SDLoc DL(N);
5525
5526     // Ensure that the shift amount is wide enough for the shifted value.
5527     if (VT.getSizeInBits() >= 256)
5528       ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
5529
5530     return DAG.getNode(N0.getOpcode(), DL, VT,
5531                        DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
5532                        ShAmt);
5533   }
5534
5535   return SDValue();
5536 }
5537
5538 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
5539   SDValue N0 = N->getOperand(0);
5540   EVT VT = N->getValueType(0);
5541
5542   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5543                                               LegalOperations))
5544     return SDValue(Res, 0);
5545
5546   // fold (aext (aext x)) -> (aext x)
5547   // fold (aext (zext x)) -> (zext x)
5548   // fold (aext (sext x)) -> (sext x)
5549   if (N0.getOpcode() == ISD::ANY_EXTEND  ||
5550       N0.getOpcode() == ISD::ZERO_EXTEND ||
5551       N0.getOpcode() == ISD::SIGN_EXTEND)
5552     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
5553
5554   // fold (aext (truncate (load x))) -> (aext (smaller load x))
5555   // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
5556   if (N0.getOpcode() == ISD::TRUNCATE) {
5557     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5558     if (NarrowLoad.getNode()) {
5559       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5560       if (NarrowLoad.getNode() != N0.getNode()) {
5561         CombineTo(N0.getNode(), NarrowLoad);
5562         // CombineTo deleted the truncate, if needed, but not what's under it.
5563         AddToWorklist(oye);
5564       }
5565       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5566     }
5567   }
5568
5569   // fold (aext (truncate x))
5570   if (N0.getOpcode() == ISD::TRUNCATE) {
5571     SDValue TruncOp = N0.getOperand(0);
5572     if (TruncOp.getValueType() == VT)
5573       return TruncOp; // x iff x size == zext size.
5574     if (TruncOp.getValueType().bitsGT(VT))
5575       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
5576     return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
5577   }
5578
5579   // Fold (aext (and (trunc x), cst)) -> (and x, cst)
5580   // if the trunc is not free.
5581   if (N0.getOpcode() == ISD::AND &&
5582       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5583       N0.getOperand(1).getOpcode() == ISD::Constant &&
5584       !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5585                           N0.getValueType())) {
5586     SDValue X = N0.getOperand(0).getOperand(0);
5587     if (X.getValueType().bitsLT(VT)) {
5588       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
5589     } else if (X.getValueType().bitsGT(VT)) {
5590       X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
5591     }
5592     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5593     Mask = Mask.zext(VT.getSizeInBits());
5594     return DAG.getNode(ISD::AND, SDLoc(N), VT,
5595                        X, DAG.getConstant(Mask, VT));
5596   }
5597
5598   // fold (aext (load x)) -> (aext (truncate (extload x)))
5599   // None of the supported targets knows how to perform load and any_ext
5600   // on vectors in one instruction.  We only perform this transformation on
5601   // scalars.
5602   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5603       ISD::isUNINDEXEDLoad(N0.getNode()) &&
5604       TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType())) {
5605     bool DoXform = true;
5606     SmallVector<SDNode*, 4> SetCCs;
5607     if (!N0.hasOneUse())
5608       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
5609     if (DoXform) {
5610       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5611       SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
5612                                        LN0->getChain(),
5613                                        LN0->getBasePtr(), N0.getValueType(),
5614                                        LN0->getMemOperand());
5615       CombineTo(N, ExtLoad);
5616       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5617                                   N0.getValueType(), ExtLoad);
5618       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5619       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5620                       ISD::ANY_EXTEND);
5621       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5622     }
5623   }
5624
5625   // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
5626   // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
5627   // fold (aext ( extload x)) -> (aext (truncate (extload  x)))
5628   if (N0.getOpcode() == ISD::LOAD &&
5629       !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5630       N0.hasOneUse()) {
5631     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5632     ISD::LoadExtType ExtType = LN0->getExtensionType();
5633     EVT MemVT = LN0->getMemoryVT();
5634     if (!LegalOperations || TLI.isLoadExtLegal(ExtType, MemVT)) {
5635       SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
5636                                        VT, LN0->getChain(), LN0->getBasePtr(),
5637                                        MemVT, LN0->getMemOperand());
5638       CombineTo(N, ExtLoad);
5639       CombineTo(N0.getNode(),
5640                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5641                             N0.getValueType(), ExtLoad),
5642                 ExtLoad.getValue(1));
5643       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5644     }
5645   }
5646
5647   if (N0.getOpcode() == ISD::SETCC) {
5648     // For vectors:
5649     // aext(setcc) -> vsetcc
5650     // aext(setcc) -> truncate(vsetcc)
5651     // aext(setcc) -> aext(vsetcc)
5652     // Only do this before legalize for now.
5653     if (VT.isVector() && !LegalOperations) {
5654       EVT N0VT = N0.getOperand(0).getValueType();
5655         // We know that the # elements of the results is the same as the
5656         // # elements of the compare (and the # elements of the compare result
5657         // for that matter).  Check to see that they are the same size.  If so,
5658         // we know that the element size of the sext'd result matches the
5659         // element size of the compare operands.
5660       if (VT.getSizeInBits() == N0VT.getSizeInBits())
5661         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5662                              N0.getOperand(1),
5663                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
5664       // If the desired elements are smaller or larger than the source
5665       // elements we can use a matching integer vector type and then
5666       // truncate/any extend
5667       else {
5668         EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5669         SDValue VsetCC =
5670           DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5671                         N0.getOperand(1),
5672                         cast<CondCodeSDNode>(N0.getOperand(2))->get());
5673         return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
5674       }
5675     }
5676
5677     // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5678     SDValue SCC =
5679       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5680                        DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5681                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5682     if (SCC.getNode())
5683       return SCC;
5684   }
5685
5686   return SDValue();
5687 }
5688
5689 /// See if the specified operand can be simplified with the knowledge that only
5690 /// the bits specified by Mask are used.  If so, return the simpler operand,
5691 /// otherwise return a null SDValue.
5692 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
5693   switch (V.getOpcode()) {
5694   default: break;
5695   case ISD::Constant: {
5696     const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
5697     assert(CV && "Const value should be ConstSDNode.");
5698     const APInt &CVal = CV->getAPIntValue();
5699     APInt NewVal = CVal & Mask;
5700     if (NewVal != CVal)
5701       return DAG.getConstant(NewVal, V.getValueType());
5702     break;
5703   }
5704   case ISD::OR:
5705   case ISD::XOR:
5706     // If the LHS or RHS don't contribute bits to the or, drop them.
5707     if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
5708       return V.getOperand(1);
5709     if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
5710       return V.getOperand(0);
5711     break;
5712   case ISD::SRL:
5713     // Only look at single-use SRLs.
5714     if (!V.getNode()->hasOneUse())
5715       break;
5716     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
5717       // See if we can recursively simplify the LHS.
5718       unsigned Amt = RHSC->getZExtValue();
5719
5720       // Watch out for shift count overflow though.
5721       if (Amt >= Mask.getBitWidth()) break;
5722       APInt NewMask = Mask << Amt;
5723       SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
5724       if (SimplifyLHS.getNode())
5725         return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
5726                            SimplifyLHS, V.getOperand(1));
5727     }
5728   }
5729   return SDValue();
5730 }
5731
5732 /// If the result of a wider load is shifted to right of N  bits and then
5733 /// truncated to a narrower type and where N is a multiple of number of bits of
5734 /// the narrower type, transform it to a narrower load from address + N / num of
5735 /// bits of new type. If the result is to be extended, also fold the extension
5736 /// to form a extending load.
5737 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
5738   unsigned Opc = N->getOpcode();
5739
5740   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
5741   SDValue N0 = N->getOperand(0);
5742   EVT VT = N->getValueType(0);
5743   EVT ExtVT = VT;
5744
5745   // This transformation isn't valid for vector loads.
5746   if (VT.isVector())
5747     return SDValue();
5748
5749   // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
5750   // extended to VT.
5751   if (Opc == ISD::SIGN_EXTEND_INREG) {
5752     ExtType = ISD::SEXTLOAD;
5753     ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
5754   } else if (Opc == ISD::SRL) {
5755     // Another special-case: SRL is basically zero-extending a narrower value.
5756     ExtType = ISD::ZEXTLOAD;
5757     N0 = SDValue(N, 0);
5758     ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
5759     if (!N01) return SDValue();
5760     ExtVT = EVT::getIntegerVT(*DAG.getContext(),
5761                               VT.getSizeInBits() - N01->getZExtValue());
5762   }
5763   if (LegalOperations && !TLI.isLoadExtLegal(ExtType, ExtVT))
5764     return SDValue();
5765
5766   unsigned EVTBits = ExtVT.getSizeInBits();
5767
5768   // Do not generate loads of non-round integer types since these can
5769   // be expensive (and would be wrong if the type is not byte sized).
5770   if (!ExtVT.isRound())
5771     return SDValue();
5772
5773   unsigned ShAmt = 0;
5774   if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
5775     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5776       ShAmt = N01->getZExtValue();
5777       // Is the shift amount a multiple of size of VT?
5778       if ((ShAmt & (EVTBits-1)) == 0) {
5779         N0 = N0.getOperand(0);
5780         // Is the load width a multiple of size of VT?
5781         if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
5782           return SDValue();
5783       }
5784
5785       // At this point, we must have a load or else we can't do the transform.
5786       if (!isa<LoadSDNode>(N0)) return SDValue();
5787
5788       // Because a SRL must be assumed to *need* to zero-extend the high bits
5789       // (as opposed to anyext the high bits), we can't combine the zextload
5790       // lowering of SRL and an sextload.
5791       if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
5792         return SDValue();
5793
5794       // If the shift amount is larger than the input type then we're not
5795       // accessing any of the loaded bytes.  If the load was a zextload/extload
5796       // then the result of the shift+trunc is zero/undef (handled elsewhere).
5797       if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
5798         return SDValue();
5799     }
5800   }
5801
5802   // If the load is shifted left (and the result isn't shifted back right),
5803   // we can fold the truncate through the shift.
5804   unsigned ShLeftAmt = 0;
5805   if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
5806       ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
5807     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5808       ShLeftAmt = N01->getZExtValue();
5809       N0 = N0.getOperand(0);
5810     }
5811   }
5812
5813   // If we haven't found a load, we can't narrow it.  Don't transform one with
5814   // multiple uses, this would require adding a new load.
5815   if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
5816     return SDValue();
5817
5818   // Don't change the width of a volatile load.
5819   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5820   if (LN0->isVolatile())
5821     return SDValue();
5822
5823   // Verify that we are actually reducing a load width here.
5824   if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
5825     return SDValue();
5826
5827   // For the transform to be legal, the load must produce only two values
5828   // (the value loaded and the chain).  Don't transform a pre-increment
5829   // load, for example, which produces an extra value.  Otherwise the
5830   // transformation is not equivalent, and the downstream logic to replace
5831   // uses gets things wrong.
5832   if (LN0->getNumValues() > 2)
5833     return SDValue();
5834
5835   // If the load that we're shrinking is an extload and we're not just
5836   // discarding the extension we can't simply shrink the load. Bail.
5837   // TODO: It would be possible to merge the extensions in some cases.
5838   if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
5839       LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
5840     return SDValue();
5841
5842   EVT PtrType = N0.getOperand(1).getValueType();
5843
5844   if (PtrType == MVT::Untyped || PtrType.isExtended())
5845     // It's not possible to generate a constant of extended or untyped type.
5846     return SDValue();
5847
5848   // For big endian targets, we need to adjust the offset to the pointer to
5849   // load the correct bytes.
5850   if (TLI.isBigEndian()) {
5851     unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
5852     unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
5853     ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
5854   }
5855
5856   uint64_t PtrOff = ShAmt / 8;
5857   unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
5858   SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0),
5859                                PtrType, LN0->getBasePtr(),
5860                                DAG.getConstant(PtrOff, PtrType));
5861   AddToWorklist(NewPtr.getNode());
5862
5863   SDValue Load;
5864   if (ExtType == ISD::NON_EXTLOAD)
5865     Load =  DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
5866                         LN0->getPointerInfo().getWithOffset(PtrOff),
5867                         LN0->isVolatile(), LN0->isNonTemporal(),
5868                         LN0->isInvariant(), NewAlign, LN0->getAAInfo());
5869   else
5870     Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
5871                           LN0->getPointerInfo().getWithOffset(PtrOff),
5872                           ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
5873                           LN0->isInvariant(), NewAlign, LN0->getAAInfo());
5874
5875   // Replace the old load's chain with the new load's chain.
5876   WorklistRemover DeadNodes(*this);
5877   DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
5878
5879   // Shift the result left, if we've swallowed a left shift.
5880   SDValue Result = Load;
5881   if (ShLeftAmt != 0) {
5882     EVT ShImmTy = getShiftAmountTy(Result.getValueType());
5883     if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
5884       ShImmTy = VT;
5885     // If the shift amount is as large as the result size (but, presumably,
5886     // no larger than the source) then the useful bits of the result are
5887     // zero; we can't simply return the shortened shift, because the result
5888     // of that operation is undefined.
5889     if (ShLeftAmt >= VT.getSizeInBits())
5890       Result = DAG.getConstant(0, VT);
5891     else
5892       Result = DAG.getNode(ISD::SHL, SDLoc(N0), VT,
5893                           Result, DAG.getConstant(ShLeftAmt, ShImmTy));
5894   }
5895
5896   // Return the new loaded value.
5897   return Result;
5898 }
5899
5900 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
5901   SDValue N0 = N->getOperand(0);
5902   SDValue N1 = N->getOperand(1);
5903   EVT VT = N->getValueType(0);
5904   EVT EVT = cast<VTSDNode>(N1)->getVT();
5905   unsigned VTBits = VT.getScalarType().getSizeInBits();
5906   unsigned EVTBits = EVT.getScalarType().getSizeInBits();
5907
5908   // fold (sext_in_reg c1) -> c1
5909   if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
5910     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
5911
5912   // If the input is already sign extended, just drop the extension.
5913   if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
5914     return N0;
5915
5916   // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
5917   if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
5918       EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
5919     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5920                        N0.getOperand(0), N1);
5921
5922   // fold (sext_in_reg (sext x)) -> (sext x)
5923   // fold (sext_in_reg (aext x)) -> (sext x)
5924   // if x is small enough.
5925   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
5926     SDValue N00 = N0.getOperand(0);
5927     if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
5928         (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
5929       return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
5930   }
5931
5932   // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
5933   if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
5934     return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
5935
5936   // fold operands of sext_in_reg based on knowledge that the top bits are not
5937   // demanded.
5938   if (SimplifyDemandedBits(SDValue(N, 0)))
5939     return SDValue(N, 0);
5940
5941   // fold (sext_in_reg (load x)) -> (smaller sextload x)
5942   // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
5943   SDValue NarrowLoad = ReduceLoadWidth(N);
5944   if (NarrowLoad.getNode())
5945     return NarrowLoad;
5946
5947   // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
5948   // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
5949   // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
5950   if (N0.getOpcode() == ISD::SRL) {
5951     if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
5952       if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
5953         // We can turn this into an SRA iff the input to the SRL is already sign
5954         // extended enough.
5955         unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
5956         if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
5957           return DAG.getNode(ISD::SRA, SDLoc(N), VT,
5958                              N0.getOperand(0), N0.getOperand(1));
5959       }
5960   }
5961
5962   // fold (sext_inreg (extload x)) -> (sextload x)
5963   if (ISD::isEXTLoad(N0.getNode()) &&
5964       ISD::isUNINDEXEDLoad(N0.getNode()) &&
5965       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5966       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5967        TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5968     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5969     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5970                                      LN0->getChain(),
5971                                      LN0->getBasePtr(), EVT,
5972                                      LN0->getMemOperand());
5973     CombineTo(N, ExtLoad);
5974     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5975     AddToWorklist(ExtLoad.getNode());
5976     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5977   }
5978   // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
5979   if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5980       N0.hasOneUse() &&
5981       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5982       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5983        TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5984     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5985     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5986                                      LN0->getChain(),
5987                                      LN0->getBasePtr(), EVT,
5988                                      LN0->getMemOperand());
5989     CombineTo(N, ExtLoad);
5990     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5991     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5992   }
5993
5994   // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
5995   if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
5996     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
5997                                        N0.getOperand(1), false);
5998     if (BSwap.getNode())
5999       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6000                          BSwap, N1);
6001   }
6002
6003   // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs
6004   // into a build_vector.
6005   if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
6006     SmallVector<SDValue, 8> Elts;
6007     unsigned NumElts = N0->getNumOperands();
6008     unsigned ShAmt = VTBits - EVTBits;
6009
6010     for (unsigned i = 0; i != NumElts; ++i) {
6011       SDValue Op = N0->getOperand(i);
6012       if (Op->getOpcode() == ISD::UNDEF) {
6013         Elts.push_back(Op);
6014         continue;
6015       }
6016
6017       ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
6018       const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
6019       Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
6020                                      Op.getValueType()));
6021     }
6022
6023     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Elts);
6024   }
6025
6026   return SDValue();
6027 }
6028
6029 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
6030   SDValue N0 = N->getOperand(0);
6031   EVT VT = N->getValueType(0);
6032   bool isLE = TLI.isLittleEndian();
6033
6034   // noop truncate
6035   if (N0.getValueType() == N->getValueType(0))
6036     return N0;
6037   // fold (truncate c1) -> c1
6038   if (isa<ConstantSDNode>(N0))
6039     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
6040   // fold (truncate (truncate x)) -> (truncate x)
6041   if (N0.getOpcode() == ISD::TRUNCATE)
6042     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6043   // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
6044   if (N0.getOpcode() == ISD::ZERO_EXTEND ||
6045       N0.getOpcode() == ISD::SIGN_EXTEND ||
6046       N0.getOpcode() == ISD::ANY_EXTEND) {
6047     if (N0.getOperand(0).getValueType().bitsLT(VT))
6048       // if the source is smaller than the dest, we still need an extend
6049       return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
6050                          N0.getOperand(0));
6051     if (N0.getOperand(0).getValueType().bitsGT(VT))
6052       // if the source is larger than the dest, than we just need the truncate
6053       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6054     // if the source and dest are the same type, we can drop both the extend
6055     // and the truncate.
6056     return N0.getOperand(0);
6057   }
6058
6059   // Fold extract-and-trunc into a narrow extract. For example:
6060   //   i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
6061   //   i32 y = TRUNCATE(i64 x)
6062   //        -- becomes --
6063   //   v16i8 b = BITCAST (v2i64 val)
6064   //   i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
6065   //
6066   // Note: We only run this optimization after type legalization (which often
6067   // creates this pattern) and before operation legalization after which
6068   // we need to be more careful about the vector instructions that we generate.
6069   if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6070       LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
6071
6072     EVT VecTy = N0.getOperand(0).getValueType();
6073     EVT ExTy = N0.getValueType();
6074     EVT TrTy = N->getValueType(0);
6075
6076     unsigned NumElem = VecTy.getVectorNumElements();
6077     unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
6078
6079     EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
6080     assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
6081
6082     SDValue EltNo = N0->getOperand(1);
6083     if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
6084       int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
6085       EVT IndexTy = TLI.getVectorIdxTy();
6086       int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
6087
6088       SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
6089                               NVT, N0.getOperand(0));
6090
6091       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
6092                          SDLoc(N), TrTy, V,
6093                          DAG.getConstant(Index, IndexTy));
6094     }
6095   }
6096
6097   // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
6098   if (N0.getOpcode() == ISD::SELECT) {
6099     EVT SrcVT = N0.getValueType();
6100     if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
6101         TLI.isTruncateFree(SrcVT, VT)) {
6102       SDLoc SL(N0);
6103       SDValue Cond = N0.getOperand(0);
6104       SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
6105       SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
6106       return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
6107     }
6108   }
6109
6110   // Fold a series of buildvector, bitcast, and truncate if possible.
6111   // For example fold
6112   //   (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
6113   //   (2xi32 (buildvector x, y)).
6114   if (Level == AfterLegalizeVectorOps && VT.isVector() &&
6115       N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
6116       N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
6117       N0.getOperand(0).hasOneUse()) {
6118
6119     SDValue BuildVect = N0.getOperand(0);
6120     EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
6121     EVT TruncVecEltTy = VT.getVectorElementType();
6122
6123     // Check that the element types match.
6124     if (BuildVectEltTy == TruncVecEltTy) {
6125       // Now we only need to compute the offset of the truncated elements.
6126       unsigned BuildVecNumElts =  BuildVect.getNumOperands();
6127       unsigned TruncVecNumElts = VT.getVectorNumElements();
6128       unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
6129
6130       assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
6131              "Invalid number of elements");
6132
6133       SmallVector<SDValue, 8> Opnds;
6134       for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
6135         Opnds.push_back(BuildVect.getOperand(i));
6136
6137       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
6138     }
6139   }
6140
6141   // See if we can simplify the input to this truncate through knowledge that
6142   // only the low bits are being used.
6143   // For example "trunc (or (shl x, 8), y)" // -> trunc y
6144   // Currently we only perform this optimization on scalars because vectors
6145   // may have different active low bits.
6146   if (!VT.isVector()) {
6147     SDValue Shorter =
6148       GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
6149                                                VT.getSizeInBits()));
6150     if (Shorter.getNode())
6151       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
6152   }
6153   // fold (truncate (load x)) -> (smaller load x)
6154   // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
6155   if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
6156     SDValue Reduced = ReduceLoadWidth(N);
6157     if (Reduced.getNode())
6158       return Reduced;
6159     // Handle the case where the load remains an extending load even
6160     // after truncation.
6161     if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
6162       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6163       if (!LN0->isVolatile() &&
6164           LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
6165         SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
6166                                          VT, LN0->getChain(), LN0->getBasePtr(),
6167                                          LN0->getMemoryVT(),
6168                                          LN0->getMemOperand());
6169         DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
6170         return NewLoad;
6171       }
6172     }
6173   }
6174   // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
6175   // where ... are all 'undef'.
6176   if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
6177     SmallVector<EVT, 8> VTs;
6178     SDValue V;
6179     unsigned Idx = 0;
6180     unsigned NumDefs = 0;
6181
6182     for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
6183       SDValue X = N0.getOperand(i);
6184       if (X.getOpcode() != ISD::UNDEF) {
6185         V = X;
6186         Idx = i;
6187         NumDefs++;
6188       }
6189       // Stop if more than one members are non-undef.
6190       if (NumDefs > 1)
6191         break;
6192       VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
6193                                      VT.getVectorElementType(),
6194                                      X.getValueType().getVectorNumElements()));
6195     }
6196
6197     if (NumDefs == 0)
6198       return DAG.getUNDEF(VT);
6199
6200     if (NumDefs == 1) {
6201       assert(V.getNode() && "The single defined operand is empty!");
6202       SmallVector<SDValue, 8> Opnds;
6203       for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
6204         if (i != Idx) {
6205           Opnds.push_back(DAG.getUNDEF(VTs[i]));
6206           continue;
6207         }
6208         SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
6209         AddToWorklist(NV.getNode());
6210         Opnds.push_back(NV);
6211       }
6212       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
6213     }
6214   }
6215
6216   // Simplify the operands using demanded-bits information.
6217   if (!VT.isVector() &&
6218       SimplifyDemandedBits(SDValue(N, 0)))
6219     return SDValue(N, 0);
6220
6221   return SDValue();
6222 }
6223
6224 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
6225   SDValue Elt = N->getOperand(i);
6226   if (Elt.getOpcode() != ISD::MERGE_VALUES)
6227     return Elt.getNode();
6228   return Elt.getOperand(Elt.getResNo()).getNode();
6229 }
6230
6231 /// build_pair (load, load) -> load
6232 /// if load locations are consecutive.
6233 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
6234   assert(N->getOpcode() == ISD::BUILD_PAIR);
6235
6236   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
6237   LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
6238   if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
6239       LD1->getAddressSpace() != LD2->getAddressSpace())
6240     return SDValue();
6241   EVT LD1VT = LD1->getValueType(0);
6242
6243   if (ISD::isNON_EXTLoad(LD2) &&
6244       LD2->hasOneUse() &&
6245       // If both are volatile this would reduce the number of volatile loads.
6246       // If one is volatile it might be ok, but play conservative and bail out.
6247       !LD1->isVolatile() &&
6248       !LD2->isVolatile() &&
6249       DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
6250     unsigned Align = LD1->getAlignment();
6251     unsigned NewAlign = TLI.getDataLayout()->
6252       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6253
6254     if (NewAlign <= Align &&
6255         (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
6256       return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
6257                          LD1->getBasePtr(), LD1->getPointerInfo(),
6258                          false, false, false, Align);
6259   }
6260
6261   return SDValue();
6262 }
6263
6264 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
6265   SDValue N0 = N->getOperand(0);
6266   EVT VT = N->getValueType(0);
6267
6268   // If the input is a BUILD_VECTOR with all constant elements, fold this now.
6269   // Only do this before legalize, since afterward the target may be depending
6270   // on the bitconvert.
6271   // First check to see if this is all constant.
6272   if (!LegalTypes &&
6273       N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
6274       VT.isVector()) {
6275     bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
6276
6277     EVT DestEltVT = N->getValueType(0).getVectorElementType();
6278     assert(!DestEltVT.isVector() &&
6279            "Element type of vector ValueType must not be vector!");
6280     if (isSimple)
6281       return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
6282   }
6283
6284   // If the input is a constant, let getNode fold it.
6285   if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
6286     SDValue Res = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
6287     if (Res.getNode() != N) {
6288       if (!LegalOperations ||
6289           TLI.isOperationLegal(Res.getNode()->getOpcode(), VT))
6290         return Res;
6291
6292       // Folding it resulted in an illegal node, and it's too late to
6293       // do that. Clean up the old node and forego the transformation.
6294       // Ideally this won't happen very often, because instcombine
6295       // and the earlier dagcombine runs (where illegal nodes are
6296       // permitted) should have folded most of them already.
6297       deleteAndRecombine(Res.getNode());
6298     }
6299   }
6300
6301   // (conv (conv x, t1), t2) -> (conv x, t2)
6302   if (N0.getOpcode() == ISD::BITCAST)
6303     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
6304                        N0.getOperand(0));
6305
6306   // fold (conv (load x)) -> (load (conv*)x)
6307   // If the resultant load doesn't need a higher alignment than the original!
6308   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
6309       // Do not change the width of a volatile load.
6310       !cast<LoadSDNode>(N0)->isVolatile() &&
6311       // Do not remove the cast if the types differ in endian layout.
6312       TLI.hasBigEndianPartOrdering(N0.getValueType()) ==
6313       TLI.hasBigEndianPartOrdering(VT) &&
6314       (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
6315       TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
6316     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6317     unsigned Align = TLI.getDataLayout()->
6318       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6319     unsigned OrigAlign = LN0->getAlignment();
6320
6321     if (Align <= OrigAlign) {
6322       SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
6323                                  LN0->getBasePtr(), LN0->getPointerInfo(),
6324                                  LN0->isVolatile(), LN0->isNonTemporal(),
6325                                  LN0->isInvariant(), OrigAlign,
6326                                  LN0->getAAInfo());
6327       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
6328       return Load;
6329     }
6330   }
6331
6332   // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
6333   // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
6334   // This often reduces constant pool loads.
6335   if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
6336        (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
6337       N0.getNode()->hasOneUse() && VT.isInteger() &&
6338       !VT.isVector() && !N0.getValueType().isVector()) {
6339     SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
6340                                   N0.getOperand(0));
6341     AddToWorklist(NewConv.getNode());
6342
6343     APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6344     if (N0.getOpcode() == ISD::FNEG)
6345       return DAG.getNode(ISD::XOR, SDLoc(N), VT,
6346                          NewConv, DAG.getConstant(SignBit, VT));
6347     assert(N0.getOpcode() == ISD::FABS);
6348     return DAG.getNode(ISD::AND, SDLoc(N), VT,
6349                        NewConv, DAG.getConstant(~SignBit, VT));
6350   }
6351
6352   // fold (bitconvert (fcopysign cst, x)) ->
6353   //         (or (and (bitconvert x), sign), (and cst, (not sign)))
6354   // Note that we don't handle (copysign x, cst) because this can always be
6355   // folded to an fneg or fabs.
6356   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
6357       isa<ConstantFPSDNode>(N0.getOperand(0)) &&
6358       VT.isInteger() && !VT.isVector()) {
6359     unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
6360     EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
6361     if (isTypeLegal(IntXVT)) {
6362       SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6363                               IntXVT, N0.getOperand(1));
6364       AddToWorklist(X.getNode());
6365
6366       // If X has a different width than the result/lhs, sext it or truncate it.
6367       unsigned VTWidth = VT.getSizeInBits();
6368       if (OrigXWidth < VTWidth) {
6369         X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
6370         AddToWorklist(X.getNode());
6371       } else if (OrigXWidth > VTWidth) {
6372         // To get the sign bit in the right place, we have to shift it right
6373         // before truncating.
6374         X = DAG.getNode(ISD::SRL, SDLoc(X),
6375                         X.getValueType(), X,
6376                         DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
6377         AddToWorklist(X.getNode());
6378         X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
6379         AddToWorklist(X.getNode());
6380       }
6381
6382       APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6383       X = DAG.getNode(ISD::AND, SDLoc(X), VT,
6384                       X, DAG.getConstant(SignBit, VT));
6385       AddToWorklist(X.getNode());
6386
6387       SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6388                                 VT, N0.getOperand(0));
6389       Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
6390                         Cst, DAG.getConstant(~SignBit, VT));
6391       AddToWorklist(Cst.getNode());
6392
6393       return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
6394     }
6395   }
6396
6397   // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
6398   if (N0.getOpcode() == ISD::BUILD_PAIR) {
6399     SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
6400     if (CombineLD.getNode())
6401       return CombineLD;
6402   }
6403
6404   return SDValue();
6405 }
6406
6407 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
6408   EVT VT = N->getValueType(0);
6409   return CombineConsecutiveLoads(N, VT);
6410 }
6411
6412 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef
6413 /// operands. DstEltVT indicates the destination element value type.
6414 SDValue DAGCombiner::
6415 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
6416   EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
6417
6418   // If this is already the right type, we're done.
6419   if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
6420
6421   unsigned SrcBitSize = SrcEltVT.getSizeInBits();
6422   unsigned DstBitSize = DstEltVT.getSizeInBits();
6423
6424   // If this is a conversion of N elements of one type to N elements of another
6425   // type, convert each element.  This handles FP<->INT cases.
6426   if (SrcBitSize == DstBitSize) {
6427     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6428                               BV->getValueType(0).getVectorNumElements());
6429
6430     // Due to the FP element handling below calling this routine recursively,
6431     // we can end up with a scalar-to-vector node here.
6432     if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
6433       return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6434                          DAG.getNode(ISD::BITCAST, SDLoc(BV),
6435                                      DstEltVT, BV->getOperand(0)));
6436
6437     SmallVector<SDValue, 8> Ops;
6438     for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6439       SDValue Op = BV->getOperand(i);
6440       // If the vector element type is not legal, the BUILD_VECTOR operands
6441       // are promoted and implicitly truncated.  Make that explicit here.
6442       if (Op.getValueType() != SrcEltVT)
6443         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
6444       Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
6445                                 DstEltVT, Op));
6446       AddToWorklist(Ops.back().getNode());
6447     }
6448     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6449   }
6450
6451   // Otherwise, we're growing or shrinking the elements.  To avoid having to
6452   // handle annoying details of growing/shrinking FP values, we convert them to
6453   // int first.
6454   if (SrcEltVT.isFloatingPoint()) {
6455     // Convert the input float vector to a int vector where the elements are the
6456     // same sizes.
6457     assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!");
6458     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
6459     BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
6460     SrcEltVT = IntVT;
6461   }
6462
6463   // Now we know the input is an integer vector.  If the output is a FP type,
6464   // convert to integer first, then to FP of the right size.
6465   if (DstEltVT.isFloatingPoint()) {
6466     assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!");
6467     EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
6468     SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
6469
6470     // Next, convert to FP elements of the same size.
6471     return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
6472   }
6473
6474   // Okay, we know the src/dst types are both integers of differing types.
6475   // Handling growing first.
6476   assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
6477   if (SrcBitSize < DstBitSize) {
6478     unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
6479
6480     SmallVector<SDValue, 8> Ops;
6481     for (unsigned i = 0, e = BV->getNumOperands(); i != e;
6482          i += NumInputsPerOutput) {
6483       bool isLE = TLI.isLittleEndian();
6484       APInt NewBits = APInt(DstBitSize, 0);
6485       bool EltIsUndef = true;
6486       for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
6487         // Shift the previously computed bits over.
6488         NewBits <<= SrcBitSize;
6489         SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
6490         if (Op.getOpcode() == ISD::UNDEF) continue;
6491         EltIsUndef = false;
6492
6493         NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
6494                    zextOrTrunc(SrcBitSize).zext(DstBitSize);
6495       }
6496
6497       if (EltIsUndef)
6498         Ops.push_back(DAG.getUNDEF(DstEltVT));
6499       else
6500         Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
6501     }
6502
6503     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
6504     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6505   }
6506
6507   // Finally, this must be the case where we are shrinking elements: each input
6508   // turns into multiple outputs.
6509   bool isS2V = ISD::isScalarToVector(BV);
6510   unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
6511   EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6512                             NumOutputsPerInput*BV->getNumOperands());
6513   SmallVector<SDValue, 8> Ops;
6514
6515   for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6516     if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
6517       for (unsigned j = 0; j != NumOutputsPerInput; ++j)
6518         Ops.push_back(DAG.getUNDEF(DstEltVT));
6519       continue;
6520     }
6521
6522     APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
6523                   getAPIntValue().zextOrTrunc(SrcBitSize);
6524
6525     for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
6526       APInt ThisVal = OpVal.trunc(DstBitSize);
6527       Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
6528       if (isS2V && i == 0 && j == 0 && ThisVal.zext(SrcBitSize) == OpVal)
6529         // Simply turn this into a SCALAR_TO_VECTOR of the new type.
6530         return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6531                            Ops[0]);
6532       OpVal = OpVal.lshr(DstBitSize);
6533     }
6534
6535     // For big endian targets, swap the order of the pieces of each element.
6536     if (TLI.isBigEndian())
6537       std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
6538   }
6539
6540   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6541 }
6542
6543 SDValue DAGCombiner::visitFADD(SDNode *N) {
6544   SDValue N0 = N->getOperand(0);
6545   SDValue N1 = N->getOperand(1);
6546   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6547   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6548   EVT VT = N->getValueType(0);
6549   const TargetOptions &Options = DAG.getTarget().Options;
6550   
6551   // fold vector ops
6552   if (VT.isVector()) {
6553     SDValue FoldedVOp = SimplifyVBinOp(N);
6554     if (FoldedVOp.getNode()) return FoldedVOp;
6555   }
6556
6557   // fold (fadd c1, c2) -> c1 + c2
6558   if (N0CFP && N1CFP)
6559     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N1);
6560   // canonicalize constant to RHS
6561   if (N0CFP && !N1CFP)
6562     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N0);
6563   // fold (fadd A, 0) -> A
6564   if (Options.UnsafeFPMath && N1CFP && N1CFP->getValueAPF().isZero())
6565     return N0;
6566   // fold (fadd A, (fneg B)) -> (fsub A, B)
6567   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6568     isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2)
6569     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0,
6570                        GetNegatedExpression(N1, DAG, LegalOperations));
6571   // fold (fadd (fneg A), B) -> (fsub B, A)
6572   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6573     isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2)
6574     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N1,
6575                        GetNegatedExpression(N0, DAG, LegalOperations));
6576
6577   // If allowed, fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
6578   if (Options.UnsafeFPMath && N1CFP &&
6579       N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
6580       isa<ConstantFPSDNode>(N0.getOperand(1)))
6581     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0.getOperand(0),
6582                        DAG.getNode(ISD::FADD, SDLoc(N), VT,
6583                                    N0.getOperand(1), N1));
6584
6585   // No FP constant should be created after legalization as Instruction
6586   // Selection pass has hard time in dealing with FP constant.
6587   //
6588   // We don't need test this condition for transformation like following, as
6589   // the DAG being transformed implies it is legal to take FP constant as
6590   // operand.
6591   //
6592   //  (fadd (fmul c, x), x) -> (fmul c+1, x)
6593   //
6594   bool AllowNewFpConst = (Level < AfterLegalizeDAG);
6595
6596   // If allow, fold (fadd (fneg x), x) -> 0.0
6597   if (AllowNewFpConst && Options.UnsafeFPMath &&
6598       N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
6599     return DAG.getConstantFP(0.0, VT);
6600
6601   // If allow, fold (fadd x, (fneg x)) -> 0.0
6602   if (AllowNewFpConst && Options.UnsafeFPMath &&
6603       N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
6604     return DAG.getConstantFP(0.0, VT);
6605
6606   // In unsafe math mode, we can fold chains of FADD's of the same value
6607   // into multiplications.  This transform is not safe in general because
6608   // we are reducing the number of rounding steps.
6609   if (Options.UnsafeFPMath && TLI.isOperationLegalOrCustom(ISD::FMUL, VT) &&
6610       !N0CFP && !N1CFP) {
6611     if (N0.getOpcode() == ISD::FMUL) {
6612       ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6613       ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
6614
6615       // (fadd (fmul c, x), x) -> (fmul x, c+1)
6616       if (CFP00 && !CFP01 && N0.getOperand(1) == N1) {
6617         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6618                                      SDValue(CFP00, 0),
6619                                      DAG.getConstantFP(1.0, VT));
6620         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6621                            N1, NewCFP);
6622       }
6623
6624       // (fadd (fmul x, c), x) -> (fmul x, c+1)
6625       if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
6626         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6627                                      SDValue(CFP01, 0),
6628                                      DAG.getConstantFP(1.0, VT));
6629         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6630                            N1, NewCFP);
6631       }
6632
6633       // (fadd (fmul c, x), (fadd x, x)) -> (fmul x, c+2)
6634       if (CFP00 && !CFP01 && N1.getOpcode() == ISD::FADD &&
6635           N1.getOperand(0) == N1.getOperand(1) &&
6636           N0.getOperand(1) == N1.getOperand(0)) {
6637         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6638                                      SDValue(CFP00, 0),
6639                                      DAG.getConstantFP(2.0, VT));
6640         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6641                            N0.getOperand(1), NewCFP);
6642       }
6643
6644       // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
6645       if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
6646           N1.getOperand(0) == N1.getOperand(1) &&
6647           N0.getOperand(0) == N1.getOperand(0)) {
6648         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6649                                      SDValue(CFP01, 0),
6650                                      DAG.getConstantFP(2.0, VT));
6651         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6652                            N0.getOperand(0), NewCFP);
6653       }
6654     }
6655
6656     if (N1.getOpcode() == ISD::FMUL) {
6657       ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6658       ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
6659
6660       // (fadd x, (fmul c, x)) -> (fmul x, c+1)
6661       if (CFP10 && !CFP11 && N1.getOperand(1) == N0) {
6662         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6663                                      SDValue(CFP10, 0),
6664                                      DAG.getConstantFP(1.0, VT));
6665         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6666                            N0, NewCFP);
6667       }
6668
6669       // (fadd x, (fmul x, c)) -> (fmul x, c+1)
6670       if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
6671         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6672                                      SDValue(CFP11, 0),
6673                                      DAG.getConstantFP(1.0, VT));
6674         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6675                            N0, NewCFP);
6676       }
6677
6678
6679       // (fadd (fadd x, x), (fmul c, x)) -> (fmul x, c+2)
6680       if (CFP10 && !CFP11 && N0.getOpcode() == ISD::FADD &&
6681           N0.getOperand(0) == N0.getOperand(1) &&
6682           N1.getOperand(1) == N0.getOperand(0)) {
6683         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6684                                      SDValue(CFP10, 0),
6685                                      DAG.getConstantFP(2.0, VT));
6686         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6687                            N1.getOperand(1), NewCFP);
6688       }
6689
6690       // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
6691       if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
6692           N0.getOperand(0) == N0.getOperand(1) &&
6693           N1.getOperand(0) == N0.getOperand(0)) {
6694         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6695                                      SDValue(CFP11, 0),
6696                                      DAG.getConstantFP(2.0, VT));
6697         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6698                            N1.getOperand(0), NewCFP);
6699       }
6700     }
6701
6702     if (N0.getOpcode() == ISD::FADD && AllowNewFpConst) {
6703       ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6704       // (fadd (fadd x, x), x) -> (fmul x, 3.0)
6705       if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
6706           (N0.getOperand(0) == N1))
6707         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6708                            N1, DAG.getConstantFP(3.0, VT));
6709     }
6710
6711     if (N1.getOpcode() == ISD::FADD && AllowNewFpConst) {
6712       ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6713       // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
6714       if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
6715           N1.getOperand(0) == N0)
6716         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6717                            N0, DAG.getConstantFP(3.0, VT));
6718     }
6719
6720     // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
6721     if (AllowNewFpConst &&
6722         N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
6723         N0.getOperand(0) == N0.getOperand(1) &&
6724         N1.getOperand(0) == N1.getOperand(1) &&
6725         N0.getOperand(0) == N1.getOperand(0))
6726       return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6727                          N0.getOperand(0),
6728                          DAG.getConstantFP(4.0, VT));
6729   }
6730
6731   // FADD -> FMA combines:
6732   if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath) &&
6733       DAG.getTarget()
6734           .getSubtargetImpl()
6735           ->getTargetLowering()
6736           ->isFMAFasterThanFMulAndFAdd(VT) &&
6737       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6738
6739     // fold (fadd (fmul x, y), z) -> (fma x, y, z)
6740     if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
6741       return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6742                          N0.getOperand(0), N0.getOperand(1), N1);
6743
6744     // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
6745     // Note: Commutes FADD operands.
6746     if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
6747       return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6748                          N1.getOperand(0), N1.getOperand(1), N0);
6749   }
6750
6751   return SDValue();
6752 }
6753
6754 SDValue DAGCombiner::visitFSUB(SDNode *N) {
6755   SDValue N0 = N->getOperand(0);
6756   SDValue N1 = N->getOperand(1);
6757   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
6758   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
6759   EVT VT = N->getValueType(0);
6760   SDLoc dl(N);
6761   const TargetOptions &Options = DAG.getTarget().Options;
6762
6763   // fold vector ops
6764   if (VT.isVector()) {
6765     SDValue FoldedVOp = SimplifyVBinOp(N);
6766     if (FoldedVOp.getNode()) return FoldedVOp;
6767   }
6768
6769   // fold (fsub c1, c2) -> c1-c2
6770   if (N0CFP && N1CFP)
6771     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0, N1);
6772
6773   // fold (fsub A, (fneg B)) -> (fadd A, B)
6774   if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
6775     return DAG.getNode(ISD::FADD, dl, VT, N0,
6776                        GetNegatedExpression(N1, DAG, LegalOperations));
6777
6778   // If 'unsafe math' is enabled, fold lots of things.
6779   if (Options.UnsafeFPMath) {
6780     // (fsub A, 0) -> A
6781     if (N1CFP && N1CFP->getValueAPF().isZero())
6782       return N0;
6783
6784     // (fsub 0, B) -> -B
6785     if (N0CFP && N0CFP->getValueAPF().isZero()) {
6786       if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
6787         return GetNegatedExpression(N1, DAG, LegalOperations);
6788       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6789         return DAG.getNode(ISD::FNEG, dl, VT, N1);
6790     }
6791
6792     // (fsub x, x) -> 0.0
6793     if (N0 == N1)
6794       return DAG.getConstantFP(0.0f, VT);
6795
6796     // (fsub x, (fadd x, y)) -> (fneg y)
6797     // (fsub x, (fadd y, x)) -> (fneg y)
6798     if (N1.getOpcode() == ISD::FADD) {
6799       SDValue N10 = N1->getOperand(0);
6800       SDValue N11 = N1->getOperand(1);
6801
6802       if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options))
6803         return GetNegatedExpression(N11, DAG, LegalOperations);
6804
6805       if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options))
6806         return GetNegatedExpression(N10, DAG, LegalOperations);
6807     }
6808   }
6809
6810   // FSUB -> FMA combines:
6811   if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath) &&
6812       DAG.getTarget().getSubtargetImpl()
6813           ->getTargetLowering()
6814           ->isFMAFasterThanFMulAndFAdd(VT) &&
6815       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6816
6817     // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
6818     if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
6819       return DAG.getNode(ISD::FMA, dl, VT,
6820                          N0.getOperand(0), N0.getOperand(1),
6821                          DAG.getNode(ISD::FNEG, dl, VT, N1));
6822
6823     // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
6824     // Note: Commutes FSUB operands.
6825     if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
6826       return DAG.getNode(ISD::FMA, dl, VT,
6827                          DAG.getNode(ISD::FNEG, dl, VT,
6828                          N1.getOperand(0)),
6829                          N1.getOperand(1), N0);
6830
6831     // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
6832     if (N0.getOpcode() == ISD::FNEG &&
6833         N0.getOperand(0).getOpcode() == ISD::FMUL &&
6834         N0->hasOneUse() && N0.getOperand(0).hasOneUse()) {
6835       SDValue N00 = N0.getOperand(0).getOperand(0);
6836       SDValue N01 = N0.getOperand(0).getOperand(1);
6837       return DAG.getNode(ISD::FMA, dl, VT,
6838                          DAG.getNode(ISD::FNEG, dl, VT, N00), N01,
6839                          DAG.getNode(ISD::FNEG, dl, VT, N1));
6840     }
6841   }
6842
6843   return SDValue();
6844 }
6845
6846 SDValue DAGCombiner::visitFMUL(SDNode *N) {
6847   SDValue N0 = N->getOperand(0);
6848   SDValue N1 = N->getOperand(1);
6849   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
6850   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
6851   EVT VT = N->getValueType(0);
6852   const TargetOptions &Options = DAG.getTarget().Options;
6853
6854   // fold vector ops
6855   if (VT.isVector()) {
6856     SDValue FoldedVOp = SimplifyVBinOp(N);
6857     if (FoldedVOp.getNode()) return FoldedVOp;
6858   }
6859
6860   // fold (fmul c1, c2) -> c1*c2
6861   if (N0CFP && N1CFP)
6862     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, N1);
6863   // canonicalize constant to RHS
6864   if (N0CFP && !N1CFP)
6865     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, N0);
6866   // fold (fmul A, 0) -> 0
6867   if (Options.UnsafeFPMath && N1CFP && N1CFP->getValueAPF().isZero())
6868     return N1;
6869   // fold (fmul A, 1.0) -> A
6870   if (N1CFP && N1CFP->isExactlyValue(1.0))
6871     return N0;
6872
6873   if (DAG.getTarget().Options.UnsafeFPMath) {
6874     // If allowed, fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
6875     if (N1CFP && N0.getOpcode() == ISD::FMUL &&
6876         N0.getNode()->hasOneUse() && isConstOrConstSplatFP(N0.getOperand(1))) {
6877       SDLoc SL(N);
6878       SDValue MulConsts = DAG.getNode(ISD::FMUL, SL, VT, N0.getOperand(1), N1);
6879       return DAG.getNode(ISD::FMUL, SL, VT, N0.getOperand(0), MulConsts);
6880     }
6881
6882     // If allowed, fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c))
6883     // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs
6884     // during an early run of DAGCombiner can prevent folding with fmuls
6885     // inserted during lowering.
6886     if (N0.getOpcode() == ISD::FADD && N0.getOperand(0) == N0.getOperand(1)) {
6887       SDLoc SL(N);
6888       const SDValue Two = DAG.getConstantFP(2.0, VT);
6889       SDValue MulConsts = DAG.getNode(ISD::FMUL, SL, VT, Two, N1);
6890       return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0), MulConsts);
6891     }
6892   }
6893
6894   // fold (fmul X, 2.0) -> (fadd X, X)
6895   if (N1CFP && N1CFP->isExactlyValue(+2.0))
6896     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N0);
6897   // fold (fmul X, -1.0) -> (fneg X)
6898   if (N1CFP && N1CFP->isExactlyValue(-1.0))
6899     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6900       return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
6901
6902   // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
6903   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
6904     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
6905       // Both can be negated for free, check to see if at least one is cheaper
6906       // negated.
6907       if (LHSNeg == 2 || RHSNeg == 2)
6908         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6909                            GetNegatedExpression(N0, DAG, LegalOperations),
6910                            GetNegatedExpression(N1, DAG, LegalOperations));
6911     }
6912   }
6913
6914   return SDValue();
6915 }
6916
6917 SDValue DAGCombiner::visitFMA(SDNode *N) {
6918   SDValue N0 = N->getOperand(0);
6919   SDValue N1 = N->getOperand(1);
6920   SDValue N2 = N->getOperand(2);
6921   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6922   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6923   EVT VT = N->getValueType(0);
6924   SDLoc dl(N);
6925   const TargetOptions &Options = DAG.getTarget().Options;
6926
6927   // Constant fold FMA.
6928   if (isa<ConstantFPSDNode>(N0) &&
6929       isa<ConstantFPSDNode>(N1) &&
6930       isa<ConstantFPSDNode>(N2)) {
6931     return DAG.getNode(ISD::FMA, dl, VT, N0, N1, N2);
6932   }
6933
6934   if (Options.UnsafeFPMath) {
6935     if (N0CFP && N0CFP->isZero())
6936       return N2;
6937     if (N1CFP && N1CFP->isZero())
6938       return N2;
6939   }
6940   if (N0CFP && N0CFP->isExactlyValue(1.0))
6941     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
6942   if (N1CFP && N1CFP->isExactlyValue(1.0))
6943     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
6944
6945   // Canonicalize (fma c, x, y) -> (fma x, c, y)
6946   if (N0CFP && !N1CFP)
6947     return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
6948
6949   // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
6950   if (Options.UnsafeFPMath && N1CFP &&
6951       N2.getOpcode() == ISD::FMUL &&
6952       N0 == N2.getOperand(0) &&
6953       N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
6954     return DAG.getNode(ISD::FMUL, dl, VT, N0,
6955                        DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
6956   }
6957
6958
6959   // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
6960   if (Options.UnsafeFPMath &&
6961       N0.getOpcode() == ISD::FMUL && N1CFP &&
6962       N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
6963     return DAG.getNode(ISD::FMA, dl, VT,
6964                        N0.getOperand(0),
6965                        DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
6966                        N2);
6967   }
6968
6969   // (fma x, 1, y) -> (fadd x, y)
6970   // (fma x, -1, y) -> (fadd (fneg x), y)
6971   if (N1CFP) {
6972     if (N1CFP->isExactlyValue(1.0))
6973       return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
6974
6975     if (N1CFP->isExactlyValue(-1.0) &&
6976         (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
6977       SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
6978       AddToWorklist(RHSNeg.getNode());
6979       return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
6980     }
6981   }
6982
6983   // (fma x, c, x) -> (fmul x, (c+1))
6984   if (Options.UnsafeFPMath && N1CFP && N0 == N2)
6985     return DAG.getNode(ISD::FMUL, dl, VT, N0,
6986                        DAG.getNode(ISD::FADD, dl, VT,
6987                                    N1, DAG.getConstantFP(1.0, VT)));
6988
6989   // (fma x, c, (fneg x)) -> (fmul x, (c-1))
6990   if (Options.UnsafeFPMath && N1CFP &&
6991       N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
6992     return DAG.getNode(ISD::FMUL, dl, VT, N0,
6993                        DAG.getNode(ISD::FADD, dl, VT,
6994                                    N1, DAG.getConstantFP(-1.0, VT)));
6995
6996
6997   return SDValue();
6998 }
6999
7000 SDValue DAGCombiner::visitFDIV(SDNode *N) {
7001   SDValue N0 = N->getOperand(0);
7002   SDValue N1 = N->getOperand(1);
7003   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7004   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7005   EVT VT = N->getValueType(0);
7006   const TargetOptions &Options = DAG.getTarget().Options;
7007
7008   // fold vector ops
7009   if (VT.isVector()) {
7010     SDValue FoldedVOp = SimplifyVBinOp(N);
7011     if (FoldedVOp.getNode()) return FoldedVOp;
7012   }
7013
7014   // fold (fdiv c1, c2) -> c1/c2
7015   if (N0CFP && N1CFP)
7016     return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
7017
7018   // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
7019   if (N1CFP && Options.UnsafeFPMath) {
7020     // Compute the reciprocal 1.0 / c2.
7021     APFloat N1APF = N1CFP->getValueAPF();
7022     APFloat Recip(N1APF.getSemantics(), 1); // 1.0
7023     APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
7024     // Only do the transform if the reciprocal is a legal fp immediate that
7025     // isn't too nasty (eg NaN, denormal, ...).
7026     if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
7027         (!LegalOperations ||
7028          // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
7029          // backend)... we should handle this gracefully after Legalize.
7030          // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
7031          TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
7032          TLI.isFPImmLegal(Recip, VT)))
7033       return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0,
7034                          DAG.getConstantFP(Recip, VT));
7035   }
7036
7037   // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
7038   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
7039     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
7040       // Both can be negated for free, check to see if at least one is cheaper
7041       // negated.
7042       if (LHSNeg == 2 || RHSNeg == 2)
7043         return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
7044                            GetNegatedExpression(N0, DAG, LegalOperations),
7045                            GetNegatedExpression(N1, DAG, LegalOperations));
7046     }
7047   }
7048
7049   return SDValue();
7050 }
7051
7052 SDValue DAGCombiner::visitFREM(SDNode *N) {
7053   SDValue N0 = N->getOperand(0);
7054   SDValue N1 = N->getOperand(1);
7055   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7056   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7057   EVT VT = N->getValueType(0);
7058
7059   // fold (frem c1, c2) -> fmod(c1,c2)
7060   if (N0CFP && N1CFP)
7061     return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
7062
7063   return SDValue();
7064 }
7065
7066 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
7067   SDValue N0 = N->getOperand(0);
7068   SDValue N1 = N->getOperand(1);
7069   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7070   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7071   EVT VT = N->getValueType(0);
7072
7073   if (N0CFP && N1CFP)  // Constant fold
7074     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
7075
7076   if (N1CFP) {
7077     const APFloat& V = N1CFP->getValueAPF();
7078     // copysign(x, c1) -> fabs(x)       iff ispos(c1)
7079     // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
7080     if (!V.isNegative()) {
7081       if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
7082         return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7083     } else {
7084       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
7085         return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
7086                            DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
7087     }
7088   }
7089
7090   // copysign(fabs(x), y) -> copysign(x, y)
7091   // copysign(fneg(x), y) -> copysign(x, y)
7092   // copysign(copysign(x,z), y) -> copysign(x, y)
7093   if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
7094       N0.getOpcode() == ISD::FCOPYSIGN)
7095     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7096                        N0.getOperand(0), N1);
7097
7098   // copysign(x, abs(y)) -> abs(x)
7099   if (N1.getOpcode() == ISD::FABS)
7100     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7101
7102   // copysign(x, copysign(y,z)) -> copysign(x, z)
7103   if (N1.getOpcode() == ISD::FCOPYSIGN)
7104     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7105                        N0, N1.getOperand(1));
7106
7107   // copysign(x, fp_extend(y)) -> copysign(x, y)
7108   // copysign(x, fp_round(y)) -> copysign(x, y)
7109   if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
7110     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7111                        N0, N1.getOperand(0));
7112
7113   return SDValue();
7114 }
7115
7116 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
7117   SDValue N0 = N->getOperand(0);
7118   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
7119   EVT VT = N->getValueType(0);
7120   EVT OpVT = N0.getValueType();
7121
7122   // fold (sint_to_fp c1) -> c1fp
7123   if (N0C &&
7124       // ...but only if the target supports immediate floating-point values
7125       (!LegalOperations ||
7126        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
7127     return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
7128
7129   // If the input is a legal type, and SINT_TO_FP is not legal on this target,
7130   // but UINT_TO_FP is legal on this target, try to convert.
7131   if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
7132       TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
7133     // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
7134     if (DAG.SignBitIsZero(N0))
7135       return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
7136   }
7137
7138   // The next optimizations are desirable only if SELECT_CC can be lowered.
7139   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
7140     // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
7141     if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
7142         !VT.isVector() &&
7143         (!LegalOperations ||
7144          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7145       SDValue Ops[] =
7146         { N0.getOperand(0), N0.getOperand(1),
7147           DAG.getConstantFP(-1.0, VT) , DAG.getConstantFP(0.0, VT),
7148           N0.getOperand(2) };
7149       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7150     }
7151
7152     // fold (sint_to_fp (zext (setcc x, y, cc))) ->
7153     //      (select_cc x, y, 1.0, 0.0,, cc)
7154     if (N0.getOpcode() == ISD::ZERO_EXTEND &&
7155         N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
7156         (!LegalOperations ||
7157          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7158       SDValue Ops[] =
7159         { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
7160           DAG.getConstantFP(1.0, VT) , DAG.getConstantFP(0.0, VT),
7161           N0.getOperand(0).getOperand(2) };
7162       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7163     }
7164   }
7165
7166   return SDValue();
7167 }
7168
7169 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
7170   SDValue N0 = N->getOperand(0);
7171   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
7172   EVT VT = N->getValueType(0);
7173   EVT OpVT = N0.getValueType();
7174
7175   // fold (uint_to_fp c1) -> c1fp
7176   if (N0C &&
7177       // ...but only if the target supports immediate floating-point values
7178       (!LegalOperations ||
7179        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
7180     return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
7181
7182   // If the input is a legal type, and UINT_TO_FP is not legal on this target,
7183   // but SINT_TO_FP is legal on this target, try to convert.
7184   if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
7185       TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
7186     // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
7187     if (DAG.SignBitIsZero(N0))
7188       return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
7189   }
7190
7191   // The next optimizations are desirable only if SELECT_CC can be lowered.
7192   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
7193     // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
7194
7195     if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
7196         (!LegalOperations ||
7197          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7198       SDValue Ops[] =
7199         { N0.getOperand(0), N0.getOperand(1),
7200           DAG.getConstantFP(1.0, VT),  DAG.getConstantFP(0.0, VT),
7201           N0.getOperand(2) };
7202       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7203     }
7204   }
7205
7206   return SDValue();
7207 }
7208
7209 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
7210   SDValue N0 = N->getOperand(0);
7211   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7212   EVT VT = N->getValueType(0);
7213
7214   // fold (fp_to_sint c1fp) -> c1
7215   if (N0CFP)
7216     return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
7217
7218   return SDValue();
7219 }
7220
7221 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
7222   SDValue N0 = N->getOperand(0);
7223   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7224   EVT VT = N->getValueType(0);
7225
7226   // fold (fp_to_uint c1fp) -> c1
7227   if (N0CFP)
7228     return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
7229
7230   return SDValue();
7231 }
7232
7233 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
7234   SDValue N0 = N->getOperand(0);
7235   SDValue N1 = N->getOperand(1);
7236   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7237   EVT VT = N->getValueType(0);
7238
7239   // fold (fp_round c1fp) -> c1fp
7240   if (N0CFP)
7241     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
7242
7243   // fold (fp_round (fp_extend x)) -> x
7244   if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
7245     return N0.getOperand(0);
7246
7247   // fold (fp_round (fp_round x)) -> (fp_round x)
7248   if (N0.getOpcode() == ISD::FP_ROUND) {
7249     // This is a value preserving truncation if both round's are.
7250     bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
7251                    N0.getNode()->getConstantOperandVal(1) == 1;
7252     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0.getOperand(0),
7253                        DAG.getIntPtrConstant(IsTrunc));
7254   }
7255
7256   // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
7257   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
7258     SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
7259                               N0.getOperand(0), N1);
7260     AddToWorklist(Tmp.getNode());
7261     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7262                        Tmp, N0.getOperand(1));
7263   }
7264
7265   return SDValue();
7266 }
7267
7268 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
7269   SDValue N0 = N->getOperand(0);
7270   EVT VT = N->getValueType(0);
7271   EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
7272   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7273
7274   // fold (fp_round_inreg c1fp) -> c1fp
7275   if (N0CFP && isTypeLegal(EVT)) {
7276     SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
7277     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, Round);
7278   }
7279
7280   return SDValue();
7281 }
7282
7283 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
7284   SDValue N0 = N->getOperand(0);
7285   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7286   EVT VT = N->getValueType(0);
7287
7288   // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
7289   if (N->hasOneUse() &&
7290       N->use_begin()->getOpcode() == ISD::FP_ROUND)
7291     return SDValue();
7292
7293   // fold (fp_extend c1fp) -> c1fp
7294   if (N0CFP)
7295     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
7296
7297   // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
7298   // value of X.
7299   if (N0.getOpcode() == ISD::FP_ROUND
7300       && N0.getNode()->getConstantOperandVal(1) == 1) {
7301     SDValue In = N0.getOperand(0);
7302     if (In.getValueType() == VT) return In;
7303     if (VT.bitsLT(In.getValueType()))
7304       return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
7305                          In, N0.getOperand(1));
7306     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
7307   }
7308
7309   // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
7310   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7311        TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType())) {
7312     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7313     SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
7314                                      LN0->getChain(),
7315                                      LN0->getBasePtr(), N0.getValueType(),
7316                                      LN0->getMemOperand());
7317     CombineTo(N, ExtLoad);
7318     CombineTo(N0.getNode(),
7319               DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
7320                           N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
7321               ExtLoad.getValue(1));
7322     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7323   }
7324
7325   return SDValue();
7326 }
7327
7328 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
7329   SDValue N0 = N->getOperand(0);
7330   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7331   EVT VT = N->getValueType(0);
7332
7333   // fold (fceil c1) -> fceil(c1)
7334   if (N0CFP)
7335     return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
7336
7337   return SDValue();
7338 }
7339
7340 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
7341   SDValue N0 = N->getOperand(0);
7342   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7343   EVT VT = N->getValueType(0);
7344
7345   // fold (ftrunc c1) -> ftrunc(c1)
7346   if (N0CFP)
7347     return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
7348
7349   return SDValue();
7350 }
7351
7352 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
7353   SDValue N0 = N->getOperand(0);
7354   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7355   EVT VT = N->getValueType(0);
7356
7357   // fold (ffloor c1) -> ffloor(c1)
7358   if (N0CFP)
7359     return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
7360
7361   return SDValue();
7362 }
7363
7364 // FIXME: FNEG and FABS have a lot in common; refactor.
7365 SDValue DAGCombiner::visitFNEG(SDNode *N) {
7366   SDValue N0 = N->getOperand(0);
7367   EVT VT = N->getValueType(0);
7368
7369   if (VT.isVector()) {
7370     SDValue FoldedVOp = SimplifyVUnaryOp(N);
7371     if (FoldedVOp.getNode()) return FoldedVOp;
7372   }
7373
7374   // Constant fold FNEG.
7375   if (isa<ConstantFPSDNode>(N0))
7376     return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N->getOperand(0));
7377
7378   if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
7379                          &DAG.getTarget().Options))
7380     return GetNegatedExpression(N0, DAG, LegalOperations);
7381
7382   // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading
7383   // constant pool values.
7384   if (!TLI.isFNegFree(VT) &&
7385       N0.getOpcode() == ISD::BITCAST &&
7386       N0.getNode()->hasOneUse()) {
7387     SDValue Int = N0.getOperand(0);
7388     EVT IntVT = Int.getValueType();
7389     if (IntVT.isInteger() && !IntVT.isVector()) {
7390       APInt SignMask;
7391       if (N0.getValueType().isVector()) {
7392         // For a vector, get a mask such as 0x80... per scalar element
7393         // and splat it.
7394         SignMask = APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
7395         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
7396       } else {
7397         // For a scalar, just generate 0x80...
7398         SignMask = APInt::getSignBit(IntVT.getSizeInBits());
7399       }
7400       Int = DAG.getNode(ISD::XOR, SDLoc(N0), IntVT, Int,
7401                         DAG.getConstant(SignMask, IntVT));
7402       AddToWorklist(Int.getNode());
7403       return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Int);
7404     }
7405   }
7406
7407   // (fneg (fmul c, x)) -> (fmul -c, x)
7408   if (N0.getOpcode() == ISD::FMUL) {
7409     ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
7410     if (CFP1) {
7411       APFloat CVal = CFP1->getValueAPF();
7412       CVal.changeSign();
7413       if (Level >= AfterLegalizeDAG &&
7414           (TLI.isFPImmLegal(CVal, N->getValueType(0)) ||
7415            TLI.isOperationLegal(ISD::ConstantFP, N->getValueType(0))))
7416         return DAG.getNode(
7417             ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
7418             DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0.getOperand(1)));
7419     }
7420   }
7421
7422   return SDValue();
7423 }
7424
7425 SDValue DAGCombiner::visitFABS(SDNode *N) {
7426   SDValue N0 = N->getOperand(0);
7427   EVT VT = N->getValueType(0);
7428
7429   if (VT.isVector()) {
7430     SDValue FoldedVOp = SimplifyVUnaryOp(N);
7431     if (FoldedVOp.getNode()) return FoldedVOp;
7432   }
7433
7434   // fold (fabs c1) -> fabs(c1)
7435   if (isa<ConstantFPSDNode>(N0))
7436     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7437   
7438   // fold (fabs (fabs x)) -> (fabs x)
7439   if (N0.getOpcode() == ISD::FABS)
7440     return N->getOperand(0);
7441
7442   // fold (fabs (fneg x)) -> (fabs x)
7443   // fold (fabs (fcopysign x, y)) -> (fabs x)
7444   if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
7445     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
7446
7447   // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading
7448   // constant pool values.
7449   if (!TLI.isFAbsFree(VT) &&
7450       N0.getOpcode() == ISD::BITCAST &&
7451       N0.getNode()->hasOneUse()) {
7452     SDValue Int = N0.getOperand(0);
7453     EVT IntVT = Int.getValueType();
7454     if (IntVT.isInteger() && !IntVT.isVector()) {
7455       APInt SignMask;
7456       if (N0.getValueType().isVector()) {
7457         // For a vector, get a mask such as 0x7f... per scalar element
7458         // and splat it.
7459         SignMask = ~APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
7460         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
7461       } else {
7462         // For a scalar, just generate 0x7f...
7463         SignMask = ~APInt::getSignBit(IntVT.getSizeInBits());
7464       }
7465       Int = DAG.getNode(ISD::AND, SDLoc(N0), IntVT, Int,
7466                         DAG.getConstant(SignMask, IntVT));
7467       AddToWorklist(Int.getNode());
7468       return DAG.getNode(ISD::BITCAST, SDLoc(N), N->getValueType(0), Int);
7469     }
7470   }
7471
7472   return SDValue();
7473 }
7474
7475 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
7476   SDValue Chain = N->getOperand(0);
7477   SDValue N1 = N->getOperand(1);
7478   SDValue N2 = N->getOperand(2);
7479
7480   // If N is a constant we could fold this into a fallthrough or unconditional
7481   // branch. However that doesn't happen very often in normal code, because
7482   // Instcombine/SimplifyCFG should have handled the available opportunities.
7483   // If we did this folding here, it would be necessary to update the
7484   // MachineBasicBlock CFG, which is awkward.
7485
7486   // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
7487   // on the target.
7488   if (N1.getOpcode() == ISD::SETCC &&
7489       TLI.isOperationLegalOrCustom(ISD::BR_CC,
7490                                    N1.getOperand(0).getValueType())) {
7491     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7492                        Chain, N1.getOperand(2),
7493                        N1.getOperand(0), N1.getOperand(1), N2);
7494   }
7495
7496   if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
7497       ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
7498        (N1.getOperand(0).hasOneUse() &&
7499         N1.getOperand(0).getOpcode() == ISD::SRL))) {
7500     SDNode *Trunc = nullptr;
7501     if (N1.getOpcode() == ISD::TRUNCATE) {
7502       // Look pass the truncate.
7503       Trunc = N1.getNode();
7504       N1 = N1.getOperand(0);
7505     }
7506
7507     // Match this pattern so that we can generate simpler code:
7508     //
7509     //   %a = ...
7510     //   %b = and i32 %a, 2
7511     //   %c = srl i32 %b, 1
7512     //   brcond i32 %c ...
7513     //
7514     // into
7515     //
7516     //   %a = ...
7517     //   %b = and i32 %a, 2
7518     //   %c = setcc eq %b, 0
7519     //   brcond %c ...
7520     //
7521     // This applies only when the AND constant value has one bit set and the
7522     // SRL constant is equal to the log2 of the AND constant. The back-end is
7523     // smart enough to convert the result into a TEST/JMP sequence.
7524     SDValue Op0 = N1.getOperand(0);
7525     SDValue Op1 = N1.getOperand(1);
7526
7527     if (Op0.getOpcode() == ISD::AND &&
7528         Op1.getOpcode() == ISD::Constant) {
7529       SDValue AndOp1 = Op0.getOperand(1);
7530
7531       if (AndOp1.getOpcode() == ISD::Constant) {
7532         const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
7533
7534         if (AndConst.isPowerOf2() &&
7535             cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
7536           SDValue SetCC =
7537             DAG.getSetCC(SDLoc(N),
7538                          getSetCCResultType(Op0.getValueType()),
7539                          Op0, DAG.getConstant(0, Op0.getValueType()),
7540                          ISD::SETNE);
7541
7542           SDValue NewBRCond = DAG.getNode(ISD::BRCOND, SDLoc(N),
7543                                           MVT::Other, Chain, SetCC, N2);
7544           // Don't add the new BRCond into the worklist or else SimplifySelectCC
7545           // will convert it back to (X & C1) >> C2.
7546           CombineTo(N, NewBRCond, false);
7547           // Truncate is dead.
7548           if (Trunc)
7549             deleteAndRecombine(Trunc);
7550           // Replace the uses of SRL with SETCC
7551           WorklistRemover DeadNodes(*this);
7552           DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
7553           deleteAndRecombine(N1.getNode());
7554           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7555         }
7556       }
7557     }
7558
7559     if (Trunc)
7560       // Restore N1 if the above transformation doesn't match.
7561       N1 = N->getOperand(1);
7562   }
7563
7564   // Transform br(xor(x, y)) -> br(x != y)
7565   // Transform br(xor(xor(x,y), 1)) -> br (x == y)
7566   if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
7567     SDNode *TheXor = N1.getNode();
7568     SDValue Op0 = TheXor->getOperand(0);
7569     SDValue Op1 = TheXor->getOperand(1);
7570     if (Op0.getOpcode() == Op1.getOpcode()) {
7571       // Avoid missing important xor optimizations.
7572       SDValue Tmp = visitXOR(TheXor);
7573       if (Tmp.getNode()) {
7574         if (Tmp.getNode() != TheXor) {
7575           DEBUG(dbgs() << "\nReplacing.8 ";
7576                 TheXor->dump(&DAG);
7577                 dbgs() << "\nWith: ";
7578                 Tmp.getNode()->dump(&DAG);
7579                 dbgs() << '\n');
7580           WorklistRemover DeadNodes(*this);
7581           DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
7582           deleteAndRecombine(TheXor);
7583           return DAG.getNode(ISD::BRCOND, SDLoc(N),
7584                              MVT::Other, Chain, Tmp, N2);
7585         }
7586
7587         // visitXOR has changed XOR's operands or replaced the XOR completely,
7588         // bail out.
7589         return SDValue(N, 0);
7590       }
7591     }
7592
7593     if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
7594       bool Equal = false;
7595       if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
7596         if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
7597             Op0.getOpcode() == ISD::XOR) {
7598           TheXor = Op0.getNode();
7599           Equal = true;
7600         }
7601
7602       EVT SetCCVT = N1.getValueType();
7603       if (LegalTypes)
7604         SetCCVT = getSetCCResultType(SetCCVT);
7605       SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
7606                                    SetCCVT,
7607                                    Op0, Op1,
7608                                    Equal ? ISD::SETEQ : ISD::SETNE);
7609       // Replace the uses of XOR with SETCC
7610       WorklistRemover DeadNodes(*this);
7611       DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
7612       deleteAndRecombine(N1.getNode());
7613       return DAG.getNode(ISD::BRCOND, SDLoc(N),
7614                          MVT::Other, Chain, SetCC, N2);
7615     }
7616   }
7617
7618   return SDValue();
7619 }
7620
7621 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
7622 //
7623 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
7624   CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
7625   SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
7626
7627   // If N is a constant we could fold this into a fallthrough or unconditional
7628   // branch. However that doesn't happen very often in normal code, because
7629   // Instcombine/SimplifyCFG should have handled the available opportunities.
7630   // If we did this folding here, it would be necessary to update the
7631   // MachineBasicBlock CFG, which is awkward.
7632
7633   // Use SimplifySetCC to simplify SETCC's.
7634   SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
7635                                CondLHS, CondRHS, CC->get(), SDLoc(N),
7636                                false);
7637   if (Simp.getNode()) AddToWorklist(Simp.getNode());
7638
7639   // fold to a simpler setcc
7640   if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
7641     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7642                        N->getOperand(0), Simp.getOperand(2),
7643                        Simp.getOperand(0), Simp.getOperand(1),
7644                        N->getOperand(4));
7645
7646   return SDValue();
7647 }
7648
7649 /// Return true if 'Use' is a load or a store that uses N as its base pointer
7650 /// and that N may be folded in the load / store addressing mode.
7651 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
7652                                     SelectionDAG &DAG,
7653                                     const TargetLowering &TLI) {
7654   EVT VT;
7655   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(Use)) {
7656     if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
7657       return false;
7658     VT = Use->getValueType(0);
7659   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(Use)) {
7660     if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
7661       return false;
7662     VT = ST->getValue().getValueType();
7663   } else
7664     return false;
7665
7666   TargetLowering::AddrMode AM;
7667   if (N->getOpcode() == ISD::ADD) {
7668     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7669     if (Offset)
7670       // [reg +/- imm]
7671       AM.BaseOffs = Offset->getSExtValue();
7672     else
7673       // [reg +/- reg]
7674       AM.Scale = 1;
7675   } else if (N->getOpcode() == ISD::SUB) {
7676     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7677     if (Offset)
7678       // [reg +/- imm]
7679       AM.BaseOffs = -Offset->getSExtValue();
7680     else
7681       // [reg +/- reg]
7682       AM.Scale = 1;
7683   } else
7684     return false;
7685
7686   return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
7687 }
7688
7689 /// Try turning a load/store into a pre-indexed load/store when the base
7690 /// pointer is an add or subtract and it has other uses besides the load/store.
7691 /// After the transformation, the new indexed load/store has effectively folded
7692 /// the add/subtract in and all of its other uses are redirected to the
7693 /// new load/store.
7694 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
7695   if (Level < AfterLegalizeDAG)
7696     return false;
7697
7698   bool isLoad = true;
7699   SDValue Ptr;
7700   EVT VT;
7701   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
7702     if (LD->isIndexed())
7703       return false;
7704     VT = LD->getMemoryVT();
7705     if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
7706         !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
7707       return false;
7708     Ptr = LD->getBasePtr();
7709   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
7710     if (ST->isIndexed())
7711       return false;
7712     VT = ST->getMemoryVT();
7713     if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
7714         !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
7715       return false;
7716     Ptr = ST->getBasePtr();
7717     isLoad = false;
7718   } else {
7719     return false;
7720   }
7721
7722   // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
7723   // out.  There is no reason to make this a preinc/predec.
7724   if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
7725       Ptr.getNode()->hasOneUse())
7726     return false;
7727
7728   // Ask the target to do addressing mode selection.
7729   SDValue BasePtr;
7730   SDValue Offset;
7731   ISD::MemIndexedMode AM = ISD::UNINDEXED;
7732   if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
7733     return false;
7734
7735   // Backends without true r+i pre-indexed forms may need to pass a
7736   // constant base with a variable offset so that constant coercion
7737   // will work with the patterns in canonical form.
7738   bool Swapped = false;
7739   if (isa<ConstantSDNode>(BasePtr)) {
7740     std::swap(BasePtr, Offset);
7741     Swapped = true;
7742   }
7743
7744   // Don't create a indexed load / store with zero offset.
7745   if (isa<ConstantSDNode>(Offset) &&
7746       cast<ConstantSDNode>(Offset)->isNullValue())
7747     return false;
7748
7749   // Try turning it into a pre-indexed load / store except when:
7750   // 1) The new base ptr is a frame index.
7751   // 2) If N is a store and the new base ptr is either the same as or is a
7752   //    predecessor of the value being stored.
7753   // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
7754   //    that would create a cycle.
7755   // 4) All uses are load / store ops that use it as old base ptr.
7756
7757   // Check #1.  Preinc'ing a frame index would require copying the stack pointer
7758   // (plus the implicit offset) to a register to preinc anyway.
7759   if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7760     return false;
7761
7762   // Check #2.
7763   if (!isLoad) {
7764     SDValue Val = cast<StoreSDNode>(N)->getValue();
7765     if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
7766       return false;
7767   }
7768
7769   // If the offset is a constant, there may be other adds of constants that
7770   // can be folded with this one. We should do this to avoid having to keep
7771   // a copy of the original base pointer.
7772   SmallVector<SDNode *, 16> OtherUses;
7773   if (isa<ConstantSDNode>(Offset))
7774     for (SDNode *Use : BasePtr.getNode()->uses()) {
7775       if (Use == Ptr.getNode())
7776         continue;
7777
7778       if (Use->isPredecessorOf(N))
7779         continue;
7780
7781       if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) {
7782         OtherUses.clear();
7783         break;
7784       }
7785
7786       SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1);
7787       if (Op1.getNode() == BasePtr.getNode())
7788         std::swap(Op0, Op1);
7789       assert(Op0.getNode() == BasePtr.getNode() &&
7790              "Use of ADD/SUB but not an operand");
7791
7792       if (!isa<ConstantSDNode>(Op1)) {
7793         OtherUses.clear();
7794         break;
7795       }
7796
7797       // FIXME: In some cases, we can be smarter about this.
7798       if (Op1.getValueType() != Offset.getValueType()) {
7799         OtherUses.clear();
7800         break;
7801       }
7802
7803       OtherUses.push_back(Use);
7804     }
7805
7806   if (Swapped)
7807     std::swap(BasePtr, Offset);
7808
7809   // Now check for #3 and #4.
7810   bool RealUse = false;
7811
7812   // Caches for hasPredecessorHelper
7813   SmallPtrSet<const SDNode *, 32> Visited;
7814   SmallVector<const SDNode *, 16> Worklist;
7815
7816   for (SDNode *Use : Ptr.getNode()->uses()) {
7817     if (Use == N)
7818       continue;
7819     if (N->hasPredecessorHelper(Use, Visited, Worklist))
7820       return false;
7821
7822     // If Ptr may be folded in addressing mode of other use, then it's
7823     // not profitable to do this transformation.
7824     if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
7825       RealUse = true;
7826   }
7827
7828   if (!RealUse)
7829     return false;
7830
7831   SDValue Result;
7832   if (isLoad)
7833     Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
7834                                 BasePtr, Offset, AM);
7835   else
7836     Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
7837                                  BasePtr, Offset, AM);
7838   ++PreIndexedNodes;
7839   ++NodesCombined;
7840   DEBUG(dbgs() << "\nReplacing.4 ";
7841         N->dump(&DAG);
7842         dbgs() << "\nWith: ";
7843         Result.getNode()->dump(&DAG);
7844         dbgs() << '\n');
7845   WorklistRemover DeadNodes(*this);
7846   if (isLoad) {
7847     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7848     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
7849   } else {
7850     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
7851   }
7852
7853   // Finally, since the node is now dead, remove it from the graph.
7854   deleteAndRecombine(N);
7855
7856   if (Swapped)
7857     std::swap(BasePtr, Offset);
7858
7859   // Replace other uses of BasePtr that can be updated to use Ptr
7860   for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
7861     unsigned OffsetIdx = 1;
7862     if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
7863       OffsetIdx = 0;
7864     assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
7865            BasePtr.getNode() && "Expected BasePtr operand");
7866
7867     // We need to replace ptr0 in the following expression:
7868     //   x0 * offset0 + y0 * ptr0 = t0
7869     // knowing that
7870     //   x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
7871     //
7872     // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
7873     // indexed load/store and the expresion that needs to be re-written.
7874     //
7875     // Therefore, we have:
7876     //   t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
7877
7878     ConstantSDNode *CN =
7879       cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
7880     int X0, X1, Y0, Y1;
7881     APInt Offset0 = CN->getAPIntValue();
7882     APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
7883
7884     X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
7885     Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
7886     X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
7887     Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
7888
7889     unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
7890
7891     APInt CNV = Offset0;
7892     if (X0 < 0) CNV = -CNV;
7893     if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
7894     else CNV = CNV - Offset1;
7895
7896     // We can now generate the new expression.
7897     SDValue NewOp1 = DAG.getConstant(CNV, CN->getValueType(0));
7898     SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
7899
7900     SDValue NewUse = DAG.getNode(Opcode,
7901                                  SDLoc(OtherUses[i]),
7902                                  OtherUses[i]->getValueType(0), NewOp1, NewOp2);
7903     DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
7904     deleteAndRecombine(OtherUses[i]);
7905   }
7906
7907   // Replace the uses of Ptr with uses of the updated base value.
7908   DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
7909   deleteAndRecombine(Ptr.getNode());
7910
7911   return true;
7912 }
7913
7914 /// Try to combine a load/store with a add/sub of the base pointer node into a
7915 /// post-indexed load/store. The transformation folded the add/subtract into the
7916 /// new indexed load/store effectively and all of its uses are redirected to the
7917 /// new load/store.
7918 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
7919   if (Level < AfterLegalizeDAG)
7920     return false;
7921
7922   bool isLoad = true;
7923   SDValue Ptr;
7924   EVT VT;
7925   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
7926     if (LD->isIndexed())
7927       return false;
7928     VT = LD->getMemoryVT();
7929     if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
7930         !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
7931       return false;
7932     Ptr = LD->getBasePtr();
7933   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
7934     if (ST->isIndexed())
7935       return false;
7936     VT = ST->getMemoryVT();
7937     if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
7938         !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
7939       return false;
7940     Ptr = ST->getBasePtr();
7941     isLoad = false;
7942   } else {
7943     return false;
7944   }
7945
7946   if (Ptr.getNode()->hasOneUse())
7947     return false;
7948
7949   for (SDNode *Op : Ptr.getNode()->uses()) {
7950     if (Op == N ||
7951         (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
7952       continue;
7953
7954     SDValue BasePtr;
7955     SDValue Offset;
7956     ISD::MemIndexedMode AM = ISD::UNINDEXED;
7957     if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
7958       // Don't create a indexed load / store with zero offset.
7959       if (isa<ConstantSDNode>(Offset) &&
7960           cast<ConstantSDNode>(Offset)->isNullValue())
7961         continue;
7962
7963       // Try turning it into a post-indexed load / store except when
7964       // 1) All uses are load / store ops that use it as base ptr (and
7965       //    it may be folded as addressing mmode).
7966       // 2) Op must be independent of N, i.e. Op is neither a predecessor
7967       //    nor a successor of N. Otherwise, if Op is folded that would
7968       //    create a cycle.
7969
7970       if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7971         continue;
7972
7973       // Check for #1.
7974       bool TryNext = false;
7975       for (SDNode *Use : BasePtr.getNode()->uses()) {
7976         if (Use == Ptr.getNode())
7977           continue;
7978
7979         // If all the uses are load / store addresses, then don't do the
7980         // transformation.
7981         if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
7982           bool RealUse = false;
7983           for (SDNode *UseUse : Use->uses()) {
7984             if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
7985               RealUse = true;
7986           }
7987
7988           if (!RealUse) {
7989             TryNext = true;
7990             break;
7991           }
7992         }
7993       }
7994
7995       if (TryNext)
7996         continue;
7997
7998       // Check for #2
7999       if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
8000         SDValue Result = isLoad
8001           ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
8002                                BasePtr, Offset, AM)
8003           : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
8004                                 BasePtr, Offset, AM);
8005         ++PostIndexedNodes;
8006         ++NodesCombined;
8007         DEBUG(dbgs() << "\nReplacing.5 ";
8008               N->dump(&DAG);
8009               dbgs() << "\nWith: ";
8010               Result.getNode()->dump(&DAG);
8011               dbgs() << '\n');
8012         WorklistRemover DeadNodes(*this);
8013         if (isLoad) {
8014           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
8015           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
8016         } else {
8017           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
8018         }
8019
8020         // Finally, since the node is now dead, remove it from the graph.
8021         deleteAndRecombine(N);
8022
8023         // Replace the uses of Use with uses of the updated base value.
8024         DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
8025                                       Result.getValue(isLoad ? 1 : 0));
8026         deleteAndRecombine(Op);
8027         return true;
8028       }
8029     }
8030   }
8031
8032   return false;
8033 }
8034
8035 /// \brief Return the base-pointer arithmetic from an indexed \p LD.
8036 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) {
8037   ISD::MemIndexedMode AM = LD->getAddressingMode();
8038   assert(AM != ISD::UNINDEXED);
8039   SDValue BP = LD->getOperand(1);
8040   SDValue Inc = LD->getOperand(2);
8041
8042   // Some backends use TargetConstants for load offsets, but don't expect
8043   // TargetConstants in general ADD nodes. We can convert these constants into
8044   // regular Constants (if the constant is not opaque).
8045   assert((Inc.getOpcode() != ISD::TargetConstant ||
8046           !cast<ConstantSDNode>(Inc)->isOpaque()) &&
8047          "Cannot split out indexing using opaque target constants");
8048   if (Inc.getOpcode() == ISD::TargetConstant) {
8049     ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc);
8050     Inc = DAG.getConstant(*ConstInc->getConstantIntValue(),
8051                           ConstInc->getValueType(0));
8052   }
8053
8054   unsigned Opc =
8055       (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB);
8056   return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc);
8057 }
8058
8059 SDValue DAGCombiner::visitLOAD(SDNode *N) {
8060   LoadSDNode *LD  = cast<LoadSDNode>(N);
8061   SDValue Chain = LD->getChain();
8062   SDValue Ptr   = LD->getBasePtr();
8063
8064   // If load is not volatile and there are no uses of the loaded value (and
8065   // the updated indexed value in case of indexed loads), change uses of the
8066   // chain value into uses of the chain input (i.e. delete the dead load).
8067   if (!LD->isVolatile()) {
8068     if (N->getValueType(1) == MVT::Other) {
8069       // Unindexed loads.
8070       if (!N->hasAnyUseOfValue(0)) {
8071         // It's not safe to use the two value CombineTo variant here. e.g.
8072         // v1, chain2 = load chain1, loc
8073         // v2, chain3 = load chain2, loc
8074         // v3         = add v2, c
8075         // Now we replace use of chain2 with chain1.  This makes the second load
8076         // isomorphic to the one we are deleting, and thus makes this load live.
8077         DEBUG(dbgs() << "\nReplacing.6 ";
8078               N->dump(&DAG);
8079               dbgs() << "\nWith chain: ";
8080               Chain.getNode()->dump(&DAG);
8081               dbgs() << "\n");
8082         WorklistRemover DeadNodes(*this);
8083         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
8084
8085         if (N->use_empty())
8086           deleteAndRecombine(N);
8087
8088         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
8089       }
8090     } else {
8091       // Indexed loads.
8092       assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
8093
8094       // If this load has an opaque TargetConstant offset, then we cannot split
8095       // the indexing into an add/sub directly (that TargetConstant may not be
8096       // valid for a different type of node, and we cannot convert an opaque
8097       // target constant into a regular constant).
8098       bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant &&
8099                        cast<ConstantSDNode>(LD->getOperand(2))->isOpaque();
8100
8101       if (!N->hasAnyUseOfValue(0) &&
8102           ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) {
8103         SDValue Undef = DAG.getUNDEF(N->getValueType(0));
8104         SDValue Index;
8105         if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) {
8106           Index = SplitIndexingFromLoad(LD);
8107           // Try to fold the base pointer arithmetic into subsequent loads and
8108           // stores.
8109           AddUsersToWorklist(N);
8110         } else
8111           Index = DAG.getUNDEF(N->getValueType(1));
8112         DEBUG(dbgs() << "\nReplacing.7 ";
8113               N->dump(&DAG);
8114               dbgs() << "\nWith: ";
8115               Undef.getNode()->dump(&DAG);
8116               dbgs() << " and 2 other values\n");
8117         WorklistRemover DeadNodes(*this);
8118         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
8119         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index);
8120         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
8121         deleteAndRecombine(N);
8122         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
8123       }
8124     }
8125   }
8126
8127   // If this load is directly stored, replace the load value with the stored
8128   // value.
8129   // TODO: Handle store large -> read small portion.
8130   // TODO: Handle TRUNCSTORE/LOADEXT
8131   if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
8132     if (ISD::isNON_TRUNCStore(Chain.getNode())) {
8133       StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
8134       if (PrevST->getBasePtr() == Ptr &&
8135           PrevST->getValue().getValueType() == N->getValueType(0))
8136       return CombineTo(N, Chain.getOperand(1), Chain);
8137     }
8138   }
8139
8140   // Try to infer better alignment information than the load already has.
8141   if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
8142     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
8143       if (Align > LD->getMemOperand()->getBaseAlignment()) {
8144         SDValue NewLoad =
8145                DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
8146                               LD->getValueType(0),
8147                               Chain, Ptr, LD->getPointerInfo(),
8148                               LD->getMemoryVT(),
8149                               LD->isVolatile(), LD->isNonTemporal(),
8150                               LD->isInvariant(), Align, LD->getAAInfo());
8151         return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
8152       }
8153     }
8154   }
8155
8156   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
8157     TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
8158 #ifndef NDEBUG
8159   if (CombinerAAOnlyFunc.getNumOccurrences() &&
8160       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
8161     UseAA = false;
8162 #endif
8163   if (UseAA && LD->isUnindexed()) {
8164     // Walk up chain skipping non-aliasing memory nodes.
8165     SDValue BetterChain = FindBetterChain(N, Chain);
8166
8167     // If there is a better chain.
8168     if (Chain != BetterChain) {
8169       SDValue ReplLoad;
8170
8171       // Replace the chain to void dependency.
8172       if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
8173         ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
8174                                BetterChain, Ptr, LD->getMemOperand());
8175       } else {
8176         ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
8177                                   LD->getValueType(0),
8178                                   BetterChain, Ptr, LD->getMemoryVT(),
8179                                   LD->getMemOperand());
8180       }
8181
8182       // Create token factor to keep old chain connected.
8183       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
8184                                   MVT::Other, Chain, ReplLoad.getValue(1));
8185
8186       // Make sure the new and old chains are cleaned up.
8187       AddToWorklist(Token.getNode());
8188
8189       // Replace uses with load result and token factor. Don't add users
8190       // to work list.
8191       return CombineTo(N, ReplLoad.getValue(0), Token, false);
8192     }
8193   }
8194
8195   // Try transforming N to an indexed load.
8196   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
8197     return SDValue(N, 0);
8198
8199   // Try to slice up N to more direct loads if the slices are mapped to
8200   // different register banks or pairing can take place.
8201   if (SliceUpLoad(N))
8202     return SDValue(N, 0);
8203
8204   return SDValue();
8205 }
8206
8207 namespace {
8208 /// \brief Helper structure used to slice a load in smaller loads.
8209 /// Basically a slice is obtained from the following sequence:
8210 /// Origin = load Ty1, Base
8211 /// Shift = srl Ty1 Origin, CstTy Amount
8212 /// Inst = trunc Shift to Ty2
8213 ///
8214 /// Then, it will be rewriten into:
8215 /// Slice = load SliceTy, Base + SliceOffset
8216 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
8217 ///
8218 /// SliceTy is deduced from the number of bits that are actually used to
8219 /// build Inst.
8220 struct LoadedSlice {
8221   /// \brief Helper structure used to compute the cost of a slice.
8222   struct Cost {
8223     /// Are we optimizing for code size.
8224     bool ForCodeSize;
8225     /// Various cost.
8226     unsigned Loads;
8227     unsigned Truncates;
8228     unsigned CrossRegisterBanksCopies;
8229     unsigned ZExts;
8230     unsigned Shift;
8231
8232     Cost(bool ForCodeSize = false)
8233         : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
8234           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
8235
8236     /// \brief Get the cost of one isolated slice.
8237     Cost(const LoadedSlice &LS, bool ForCodeSize = false)
8238         : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
8239           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
8240       EVT TruncType = LS.Inst->getValueType(0);
8241       EVT LoadedType = LS.getLoadedType();
8242       if (TruncType != LoadedType &&
8243           !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
8244         ZExts = 1;
8245     }
8246
8247     /// \brief Account for slicing gain in the current cost.
8248     /// Slicing provide a few gains like removing a shift or a
8249     /// truncate. This method allows to grow the cost of the original
8250     /// load with the gain from this slice.
8251     void addSliceGain(const LoadedSlice &LS) {
8252       // Each slice saves a truncate.
8253       const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
8254       if (!TLI.isTruncateFree(LS.Inst->getValueType(0),
8255                               LS.Inst->getOperand(0).getValueType()))
8256         ++Truncates;
8257       // If there is a shift amount, this slice gets rid of it.
8258       if (LS.Shift)
8259         ++Shift;
8260       // If this slice can merge a cross register bank copy, account for it.
8261       if (LS.canMergeExpensiveCrossRegisterBankCopy())
8262         ++CrossRegisterBanksCopies;
8263     }
8264
8265     Cost &operator+=(const Cost &RHS) {
8266       Loads += RHS.Loads;
8267       Truncates += RHS.Truncates;
8268       CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
8269       ZExts += RHS.ZExts;
8270       Shift += RHS.Shift;
8271       return *this;
8272     }
8273
8274     bool operator==(const Cost &RHS) const {
8275       return Loads == RHS.Loads && Truncates == RHS.Truncates &&
8276              CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
8277              ZExts == RHS.ZExts && Shift == RHS.Shift;
8278     }
8279
8280     bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
8281
8282     bool operator<(const Cost &RHS) const {
8283       // Assume cross register banks copies are as expensive as loads.
8284       // FIXME: Do we want some more target hooks?
8285       unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
8286       unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
8287       // Unless we are optimizing for code size, consider the
8288       // expensive operation first.
8289       if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
8290         return ExpensiveOpsLHS < ExpensiveOpsRHS;
8291       return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
8292              (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
8293     }
8294
8295     bool operator>(const Cost &RHS) const { return RHS < *this; }
8296
8297     bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
8298
8299     bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
8300   };
8301   // The last instruction that represent the slice. This should be a
8302   // truncate instruction.
8303   SDNode *Inst;
8304   // The original load instruction.
8305   LoadSDNode *Origin;
8306   // The right shift amount in bits from the original load.
8307   unsigned Shift;
8308   // The DAG from which Origin came from.
8309   // This is used to get some contextual information about legal types, etc.
8310   SelectionDAG *DAG;
8311
8312   LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
8313               unsigned Shift = 0, SelectionDAG *DAG = nullptr)
8314       : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
8315
8316   LoadedSlice(const LoadedSlice &LS)
8317       : Inst(LS.Inst), Origin(LS.Origin), Shift(LS.Shift), DAG(LS.DAG) {}
8318
8319   /// \brief Get the bits used in a chunk of bits \p BitWidth large.
8320   /// \return Result is \p BitWidth and has used bits set to 1 and
8321   ///         not used bits set to 0.
8322   APInt getUsedBits() const {
8323     // Reproduce the trunc(lshr) sequence:
8324     // - Start from the truncated value.
8325     // - Zero extend to the desired bit width.
8326     // - Shift left.
8327     assert(Origin && "No original load to compare against.");
8328     unsigned BitWidth = Origin->getValueSizeInBits(0);
8329     assert(Inst && "This slice is not bound to an instruction");
8330     assert(Inst->getValueSizeInBits(0) <= BitWidth &&
8331            "Extracted slice is bigger than the whole type!");
8332     APInt UsedBits(Inst->getValueSizeInBits(0), 0);
8333     UsedBits.setAllBits();
8334     UsedBits = UsedBits.zext(BitWidth);
8335     UsedBits <<= Shift;
8336     return UsedBits;
8337   }
8338
8339   /// \brief Get the size of the slice to be loaded in bytes.
8340   unsigned getLoadedSize() const {
8341     unsigned SliceSize = getUsedBits().countPopulation();
8342     assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
8343     return SliceSize / 8;
8344   }
8345
8346   /// \brief Get the type that will be loaded for this slice.
8347   /// Note: This may not be the final type for the slice.
8348   EVT getLoadedType() const {
8349     assert(DAG && "Missing context");
8350     LLVMContext &Ctxt = *DAG->getContext();
8351     return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
8352   }
8353
8354   /// \brief Get the alignment of the load used for this slice.
8355   unsigned getAlignment() const {
8356     unsigned Alignment = Origin->getAlignment();
8357     unsigned Offset = getOffsetFromBase();
8358     if (Offset != 0)
8359       Alignment = MinAlign(Alignment, Alignment + Offset);
8360     return Alignment;
8361   }
8362
8363   /// \brief Check if this slice can be rewritten with legal operations.
8364   bool isLegal() const {
8365     // An invalid slice is not legal.
8366     if (!Origin || !Inst || !DAG)
8367       return false;
8368
8369     // Offsets are for indexed load only, we do not handle that.
8370     if (Origin->getOffset().getOpcode() != ISD::UNDEF)
8371       return false;
8372
8373     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8374
8375     // Check that the type is legal.
8376     EVT SliceType = getLoadedType();
8377     if (!TLI.isTypeLegal(SliceType))
8378       return false;
8379
8380     // Check that the load is legal for this type.
8381     if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
8382       return false;
8383
8384     // Check that the offset can be computed.
8385     // 1. Check its type.
8386     EVT PtrType = Origin->getBasePtr().getValueType();
8387     if (PtrType == MVT::Untyped || PtrType.isExtended())
8388       return false;
8389
8390     // 2. Check that it fits in the immediate.
8391     if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
8392       return false;
8393
8394     // 3. Check that the computation is legal.
8395     if (!TLI.isOperationLegal(ISD::ADD, PtrType))
8396       return false;
8397
8398     // Check that the zext is legal if it needs one.
8399     EVT TruncateType = Inst->getValueType(0);
8400     if (TruncateType != SliceType &&
8401         !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
8402       return false;
8403
8404     return true;
8405   }
8406
8407   /// \brief Get the offset in bytes of this slice in the original chunk of
8408   /// bits.
8409   /// \pre DAG != nullptr.
8410   uint64_t getOffsetFromBase() const {
8411     assert(DAG && "Missing context.");
8412     bool IsBigEndian =
8413         DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian();
8414     assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
8415     uint64_t Offset = Shift / 8;
8416     unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
8417     assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
8418            "The size of the original loaded type is not a multiple of a"
8419            " byte.");
8420     // If Offset is bigger than TySizeInBytes, it means we are loading all
8421     // zeros. This should have been optimized before in the process.
8422     assert(TySizeInBytes > Offset &&
8423            "Invalid shift amount for given loaded size");
8424     if (IsBigEndian)
8425       Offset = TySizeInBytes - Offset - getLoadedSize();
8426     return Offset;
8427   }
8428
8429   /// \brief Generate the sequence of instructions to load the slice
8430   /// represented by this object and redirect the uses of this slice to
8431   /// this new sequence of instructions.
8432   /// \pre this->Inst && this->Origin are valid Instructions and this
8433   /// object passed the legal check: LoadedSlice::isLegal returned true.
8434   /// \return The last instruction of the sequence used to load the slice.
8435   SDValue loadSlice() const {
8436     assert(Inst && Origin && "Unable to replace a non-existing slice.");
8437     const SDValue &OldBaseAddr = Origin->getBasePtr();
8438     SDValue BaseAddr = OldBaseAddr;
8439     // Get the offset in that chunk of bytes w.r.t. the endianess.
8440     int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
8441     assert(Offset >= 0 && "Offset too big to fit in int64_t!");
8442     if (Offset) {
8443       // BaseAddr = BaseAddr + Offset.
8444       EVT ArithType = BaseAddr.getValueType();
8445       BaseAddr = DAG->getNode(ISD::ADD, SDLoc(Origin), ArithType, BaseAddr,
8446                               DAG->getConstant(Offset, ArithType));
8447     }
8448
8449     // Create the type of the loaded slice according to its size.
8450     EVT SliceType = getLoadedType();
8451
8452     // Create the load for the slice.
8453     SDValue LastInst = DAG->getLoad(
8454         SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
8455         Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
8456         Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
8457     // If the final type is not the same as the loaded type, this means that
8458     // we have to pad with zero. Create a zero extend for that.
8459     EVT FinalType = Inst->getValueType(0);
8460     if (SliceType != FinalType)
8461       LastInst =
8462           DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
8463     return LastInst;
8464   }
8465
8466   /// \brief Check if this slice can be merged with an expensive cross register
8467   /// bank copy. E.g.,
8468   /// i = load i32
8469   /// f = bitcast i32 i to float
8470   bool canMergeExpensiveCrossRegisterBankCopy() const {
8471     if (!Inst || !Inst->hasOneUse())
8472       return false;
8473     SDNode *Use = *Inst->use_begin();
8474     if (Use->getOpcode() != ISD::BITCAST)
8475       return false;
8476     assert(DAG && "Missing context");
8477     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8478     EVT ResVT = Use->getValueType(0);
8479     const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
8480     const TargetRegisterClass *ArgRC =
8481         TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
8482     if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
8483       return false;
8484
8485     // At this point, we know that we perform a cross-register-bank copy.
8486     // Check if it is expensive.
8487     const TargetRegisterInfo *TRI =
8488         TLI.getTargetMachine().getSubtargetImpl()->getRegisterInfo();
8489     // Assume bitcasts are cheap, unless both register classes do not
8490     // explicitly share a common sub class.
8491     if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
8492       return false;
8493
8494     // Check if it will be merged with the load.
8495     // 1. Check the alignment constraint.
8496     unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment(
8497         ResVT.getTypeForEVT(*DAG->getContext()));
8498
8499     if (RequiredAlignment > getAlignment())
8500       return false;
8501
8502     // 2. Check that the load is a legal operation for that type.
8503     if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
8504       return false;
8505
8506     // 3. Check that we do not have a zext in the way.
8507     if (Inst->getValueType(0) != getLoadedType())
8508       return false;
8509
8510     return true;
8511   }
8512 };
8513 }
8514
8515 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
8516 /// \p UsedBits looks like 0..0 1..1 0..0.
8517 static bool areUsedBitsDense(const APInt &UsedBits) {
8518   // If all the bits are one, this is dense!
8519   if (UsedBits.isAllOnesValue())
8520     return true;
8521
8522   // Get rid of the unused bits on the right.
8523   APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
8524   // Get rid of the unused bits on the left.
8525   if (NarrowedUsedBits.countLeadingZeros())
8526     NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
8527   // Check that the chunk of bits is completely used.
8528   return NarrowedUsedBits.isAllOnesValue();
8529 }
8530
8531 /// \brief Check whether or not \p First and \p Second are next to each other
8532 /// in memory. This means that there is no hole between the bits loaded
8533 /// by \p First and the bits loaded by \p Second.
8534 static bool areSlicesNextToEachOther(const LoadedSlice &First,
8535                                      const LoadedSlice &Second) {
8536   assert(First.Origin == Second.Origin && First.Origin &&
8537          "Unable to match different memory origins.");
8538   APInt UsedBits = First.getUsedBits();
8539   assert((UsedBits & Second.getUsedBits()) == 0 &&
8540          "Slices are not supposed to overlap.");
8541   UsedBits |= Second.getUsedBits();
8542   return areUsedBitsDense(UsedBits);
8543 }
8544
8545 /// \brief Adjust the \p GlobalLSCost according to the target
8546 /// paring capabilities and the layout of the slices.
8547 /// \pre \p GlobalLSCost should account for at least as many loads as
8548 /// there is in the slices in \p LoadedSlices.
8549 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8550                                  LoadedSlice::Cost &GlobalLSCost) {
8551   unsigned NumberOfSlices = LoadedSlices.size();
8552   // If there is less than 2 elements, no pairing is possible.
8553   if (NumberOfSlices < 2)
8554     return;
8555
8556   // Sort the slices so that elements that are likely to be next to each
8557   // other in memory are next to each other in the list.
8558   std::sort(LoadedSlices.begin(), LoadedSlices.end(),
8559             [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
8560     assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
8561     return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
8562   });
8563   const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
8564   // First (resp. Second) is the first (resp. Second) potentially candidate
8565   // to be placed in a paired load.
8566   const LoadedSlice *First = nullptr;
8567   const LoadedSlice *Second = nullptr;
8568   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
8569                 // Set the beginning of the pair.
8570                                                            First = Second) {
8571
8572     Second = &LoadedSlices[CurrSlice];
8573
8574     // If First is NULL, it means we start a new pair.
8575     // Get to the next slice.
8576     if (!First)
8577       continue;
8578
8579     EVT LoadedType = First->getLoadedType();
8580
8581     // If the types of the slices are different, we cannot pair them.
8582     if (LoadedType != Second->getLoadedType())
8583       continue;
8584
8585     // Check if the target supplies paired loads for this type.
8586     unsigned RequiredAlignment = 0;
8587     if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
8588       // move to the next pair, this type is hopeless.
8589       Second = nullptr;
8590       continue;
8591     }
8592     // Check if we meet the alignment requirement.
8593     if (RequiredAlignment > First->getAlignment())
8594       continue;
8595
8596     // Check that both loads are next to each other in memory.
8597     if (!areSlicesNextToEachOther(*First, *Second))
8598       continue;
8599
8600     assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
8601     --GlobalLSCost.Loads;
8602     // Move to the next pair.
8603     Second = nullptr;
8604   }
8605 }
8606
8607 /// \brief Check the profitability of all involved LoadedSlice.
8608 /// Currently, it is considered profitable if there is exactly two
8609 /// involved slices (1) which are (2) next to each other in memory, and
8610 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
8611 ///
8612 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
8613 /// the elements themselves.
8614 ///
8615 /// FIXME: When the cost model will be mature enough, we can relax
8616 /// constraints (1) and (2).
8617 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8618                                 const APInt &UsedBits, bool ForCodeSize) {
8619   unsigned NumberOfSlices = LoadedSlices.size();
8620   if (StressLoadSlicing)
8621     return NumberOfSlices > 1;
8622
8623   // Check (1).
8624   if (NumberOfSlices != 2)
8625     return false;
8626
8627   // Check (2).
8628   if (!areUsedBitsDense(UsedBits))
8629     return false;
8630
8631   // Check (3).
8632   LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
8633   // The original code has one big load.
8634   OrigCost.Loads = 1;
8635   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
8636     const LoadedSlice &LS = LoadedSlices[CurrSlice];
8637     // Accumulate the cost of all the slices.
8638     LoadedSlice::Cost SliceCost(LS, ForCodeSize);
8639     GlobalSlicingCost += SliceCost;
8640
8641     // Account as cost in the original configuration the gain obtained
8642     // with the current slices.
8643     OrigCost.addSliceGain(LS);
8644   }
8645
8646   // If the target supports paired load, adjust the cost accordingly.
8647   adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
8648   return OrigCost > GlobalSlicingCost;
8649 }
8650
8651 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
8652 /// operations, split it in the various pieces being extracted.
8653 ///
8654 /// This sort of thing is introduced by SROA.
8655 /// This slicing takes care not to insert overlapping loads.
8656 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
8657 bool DAGCombiner::SliceUpLoad(SDNode *N) {
8658   if (Level < AfterLegalizeDAG)
8659     return false;
8660
8661   LoadSDNode *LD = cast<LoadSDNode>(N);
8662   if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
8663       !LD->getValueType(0).isInteger())
8664     return false;
8665
8666   // Keep track of already used bits to detect overlapping values.
8667   // In that case, we will just abort the transformation.
8668   APInt UsedBits(LD->getValueSizeInBits(0), 0);
8669
8670   SmallVector<LoadedSlice, 4> LoadedSlices;
8671
8672   // Check if this load is used as several smaller chunks of bits.
8673   // Basically, look for uses in trunc or trunc(lshr) and record a new chain
8674   // of computation for each trunc.
8675   for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
8676        UI != UIEnd; ++UI) {
8677     // Skip the uses of the chain.
8678     if (UI.getUse().getResNo() != 0)
8679       continue;
8680
8681     SDNode *User = *UI;
8682     unsigned Shift = 0;
8683
8684     // Check if this is a trunc(lshr).
8685     if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
8686         isa<ConstantSDNode>(User->getOperand(1))) {
8687       Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
8688       User = *User->use_begin();
8689     }
8690
8691     // At this point, User is a Truncate, iff we encountered, trunc or
8692     // trunc(lshr).
8693     if (User->getOpcode() != ISD::TRUNCATE)
8694       return false;
8695
8696     // The width of the type must be a power of 2 and greater than 8-bits.
8697     // Otherwise the load cannot be represented in LLVM IR.
8698     // Moreover, if we shifted with a non-8-bits multiple, the slice
8699     // will be across several bytes. We do not support that.
8700     unsigned Width = User->getValueSizeInBits(0);
8701     if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
8702       return 0;
8703
8704     // Build the slice for this chain of computations.
8705     LoadedSlice LS(User, LD, Shift, &DAG);
8706     APInt CurrentUsedBits = LS.getUsedBits();
8707
8708     // Check if this slice overlaps with another.
8709     if ((CurrentUsedBits & UsedBits) != 0)
8710       return false;
8711     // Update the bits used globally.
8712     UsedBits |= CurrentUsedBits;
8713
8714     // Check if the new slice would be legal.
8715     if (!LS.isLegal())
8716       return false;
8717
8718     // Record the slice.
8719     LoadedSlices.push_back(LS);
8720   }
8721
8722   // Abort slicing if it does not seem to be profitable.
8723   if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
8724     return false;
8725
8726   ++SlicedLoads;
8727
8728   // Rewrite each chain to use an independent load.
8729   // By construction, each chain can be represented by a unique load.
8730
8731   // Prepare the argument for the new token factor for all the slices.
8732   SmallVector<SDValue, 8> ArgChains;
8733   for (SmallVectorImpl<LoadedSlice>::const_iterator
8734            LSIt = LoadedSlices.begin(),
8735            LSItEnd = LoadedSlices.end();
8736        LSIt != LSItEnd; ++LSIt) {
8737     SDValue SliceInst = LSIt->loadSlice();
8738     CombineTo(LSIt->Inst, SliceInst, true);
8739     if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
8740       SliceInst = SliceInst.getOperand(0);
8741     assert(SliceInst->getOpcode() == ISD::LOAD &&
8742            "It takes more than a zext to get to the loaded slice!!");
8743     ArgChains.push_back(SliceInst.getValue(1));
8744   }
8745
8746   SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
8747                               ArgChains);
8748   DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
8749   return true;
8750 }
8751
8752 /// Check to see if V is (and load (ptr), imm), where the load is having
8753 /// specific bytes cleared out.  If so, return the byte size being masked out
8754 /// and the shift amount.
8755 static std::pair<unsigned, unsigned>
8756 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
8757   std::pair<unsigned, unsigned> Result(0, 0);
8758
8759   // Check for the structure we're looking for.
8760   if (V->getOpcode() != ISD::AND ||
8761       !isa<ConstantSDNode>(V->getOperand(1)) ||
8762       !ISD::isNormalLoad(V->getOperand(0).getNode()))
8763     return Result;
8764
8765   // Check the chain and pointer.
8766   LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
8767   if (LD->getBasePtr() != Ptr) return Result;  // Not from same pointer.
8768
8769   // The store should be chained directly to the load or be an operand of a
8770   // tokenfactor.
8771   if (LD == Chain.getNode())
8772     ; // ok.
8773   else if (Chain->getOpcode() != ISD::TokenFactor)
8774     return Result; // Fail.
8775   else {
8776     bool isOk = false;
8777     for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
8778       if (Chain->getOperand(i).getNode() == LD) {
8779         isOk = true;
8780         break;
8781       }
8782     if (!isOk) return Result;
8783   }
8784
8785   // This only handles simple types.
8786   if (V.getValueType() != MVT::i16 &&
8787       V.getValueType() != MVT::i32 &&
8788       V.getValueType() != MVT::i64)
8789     return Result;
8790
8791   // Check the constant mask.  Invert it so that the bits being masked out are
8792   // 0 and the bits being kept are 1.  Use getSExtValue so that leading bits
8793   // follow the sign bit for uniformity.
8794   uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
8795   unsigned NotMaskLZ = countLeadingZeros(NotMask);
8796   if (NotMaskLZ & 7) return Result;  // Must be multiple of a byte.
8797   unsigned NotMaskTZ = countTrailingZeros(NotMask);
8798   if (NotMaskTZ & 7) return Result;  // Must be multiple of a byte.
8799   if (NotMaskLZ == 64) return Result;  // All zero mask.
8800
8801   // See if we have a continuous run of bits.  If so, we have 0*1+0*
8802   if (CountTrailingOnes_64(NotMask >> NotMaskTZ)+NotMaskTZ+NotMaskLZ != 64)
8803     return Result;
8804
8805   // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
8806   if (V.getValueType() != MVT::i64 && NotMaskLZ)
8807     NotMaskLZ -= 64-V.getValueSizeInBits();
8808
8809   unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
8810   switch (MaskedBytes) {
8811   case 1:
8812   case 2:
8813   case 4: break;
8814   default: return Result; // All one mask, or 5-byte mask.
8815   }
8816
8817   // Verify that the first bit starts at a multiple of mask so that the access
8818   // is aligned the same as the access width.
8819   if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
8820
8821   Result.first = MaskedBytes;
8822   Result.second = NotMaskTZ/8;
8823   return Result;
8824 }
8825
8826
8827 /// Check to see if IVal is something that provides a value as specified by
8828 /// MaskInfo. If so, replace the specified store with a narrower store of
8829 /// truncated IVal.
8830 static SDNode *
8831 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
8832                                 SDValue IVal, StoreSDNode *St,
8833                                 DAGCombiner *DC) {
8834   unsigned NumBytes = MaskInfo.first;
8835   unsigned ByteShift = MaskInfo.second;
8836   SelectionDAG &DAG = DC->getDAG();
8837
8838   // Check to see if IVal is all zeros in the part being masked in by the 'or'
8839   // that uses this.  If not, this is not a replacement.
8840   APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
8841                                   ByteShift*8, (ByteShift+NumBytes)*8);
8842   if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
8843
8844   // Check that it is legal on the target to do this.  It is legal if the new
8845   // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
8846   // legalization.
8847   MVT VT = MVT::getIntegerVT(NumBytes*8);
8848   if (!DC->isTypeLegal(VT))
8849     return nullptr;
8850
8851   // Okay, we can do this!  Replace the 'St' store with a store of IVal that is
8852   // shifted by ByteShift and truncated down to NumBytes.
8853   if (ByteShift)
8854     IVal = DAG.getNode(ISD::SRL, SDLoc(IVal), IVal.getValueType(), IVal,
8855                        DAG.getConstant(ByteShift*8,
8856                                     DC->getShiftAmountTy(IVal.getValueType())));
8857
8858   // Figure out the offset for the store and the alignment of the access.
8859   unsigned StOffset;
8860   unsigned NewAlign = St->getAlignment();
8861
8862   if (DAG.getTargetLoweringInfo().isLittleEndian())
8863     StOffset = ByteShift;
8864   else
8865     StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
8866
8867   SDValue Ptr = St->getBasePtr();
8868   if (StOffset) {
8869     Ptr = DAG.getNode(ISD::ADD, SDLoc(IVal), Ptr.getValueType(),
8870                       Ptr, DAG.getConstant(StOffset, Ptr.getValueType()));
8871     NewAlign = MinAlign(NewAlign, StOffset);
8872   }
8873
8874   // Truncate down to the new size.
8875   IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
8876
8877   ++OpsNarrowed;
8878   return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
8879                       St->getPointerInfo().getWithOffset(StOffset),
8880                       false, false, NewAlign).getNode();
8881 }
8882
8883
8884 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and
8885 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try
8886 /// narrowing the load and store if it would end up being a win for performance
8887 /// or code size.
8888 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
8889   StoreSDNode *ST  = cast<StoreSDNode>(N);
8890   if (ST->isVolatile())
8891     return SDValue();
8892
8893   SDValue Chain = ST->getChain();
8894   SDValue Value = ST->getValue();
8895   SDValue Ptr   = ST->getBasePtr();
8896   EVT VT = Value.getValueType();
8897
8898   if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
8899     return SDValue();
8900
8901   unsigned Opc = Value.getOpcode();
8902
8903   // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
8904   // is a byte mask indicating a consecutive number of bytes, check to see if
8905   // Y is known to provide just those bytes.  If so, we try to replace the
8906   // load + replace + store sequence with a single (narrower) store, which makes
8907   // the load dead.
8908   if (Opc == ISD::OR) {
8909     std::pair<unsigned, unsigned> MaskedLoad;
8910     MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
8911     if (MaskedLoad.first)
8912       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8913                                                   Value.getOperand(1), ST,this))
8914         return SDValue(NewST, 0);
8915
8916     // Or is commutative, so try swapping X and Y.
8917     MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
8918     if (MaskedLoad.first)
8919       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8920                                                   Value.getOperand(0), ST,this))
8921         return SDValue(NewST, 0);
8922   }
8923
8924   if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
8925       Value.getOperand(1).getOpcode() != ISD::Constant)
8926     return SDValue();
8927
8928   SDValue N0 = Value.getOperand(0);
8929   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8930       Chain == SDValue(N0.getNode(), 1)) {
8931     LoadSDNode *LD = cast<LoadSDNode>(N0);
8932     if (LD->getBasePtr() != Ptr ||
8933         LD->getPointerInfo().getAddrSpace() !=
8934         ST->getPointerInfo().getAddrSpace())
8935       return SDValue();
8936
8937     // Find the type to narrow it the load / op / store to.
8938     SDValue N1 = Value.getOperand(1);
8939     unsigned BitWidth = N1.getValueSizeInBits();
8940     APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
8941     if (Opc == ISD::AND)
8942       Imm ^= APInt::getAllOnesValue(BitWidth);
8943     if (Imm == 0 || Imm.isAllOnesValue())
8944       return SDValue();
8945     unsigned ShAmt = Imm.countTrailingZeros();
8946     unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
8947     unsigned NewBW = NextPowerOf2(MSB - ShAmt);
8948     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
8949     while (NewBW < BitWidth &&
8950            !(TLI.isOperationLegalOrCustom(Opc, NewVT) &&
8951              TLI.isNarrowingProfitable(VT, NewVT))) {
8952       NewBW = NextPowerOf2(NewBW);
8953       NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
8954     }
8955     if (NewBW >= BitWidth)
8956       return SDValue();
8957
8958     // If the lsb changed does not start at the type bitwidth boundary,
8959     // start at the previous one.
8960     if (ShAmt % NewBW)
8961       ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
8962     APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
8963                                    std::min(BitWidth, ShAmt + NewBW));
8964     if ((Imm & Mask) == Imm) {
8965       APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
8966       if (Opc == ISD::AND)
8967         NewImm ^= APInt::getAllOnesValue(NewBW);
8968       uint64_t PtrOff = ShAmt / 8;
8969       // For big endian targets, we need to adjust the offset to the pointer to
8970       // load the correct bytes.
8971       if (TLI.isBigEndian())
8972         PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
8973
8974       unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
8975       Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
8976       if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
8977         return SDValue();
8978
8979       SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
8980                                    Ptr.getValueType(), Ptr,
8981                                    DAG.getConstant(PtrOff, Ptr.getValueType()));
8982       SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
8983                                   LD->getChain(), NewPtr,
8984                                   LD->getPointerInfo().getWithOffset(PtrOff),
8985                                   LD->isVolatile(), LD->isNonTemporal(),
8986                                   LD->isInvariant(), NewAlign,
8987                                   LD->getAAInfo());
8988       SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
8989                                    DAG.getConstant(NewImm, NewVT));
8990       SDValue NewST = DAG.getStore(Chain, SDLoc(N),
8991                                    NewVal, NewPtr,
8992                                    ST->getPointerInfo().getWithOffset(PtrOff),
8993                                    false, false, NewAlign);
8994
8995       AddToWorklist(NewPtr.getNode());
8996       AddToWorklist(NewLD.getNode());
8997       AddToWorklist(NewVal.getNode());
8998       WorklistRemover DeadNodes(*this);
8999       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
9000       ++OpsNarrowed;
9001       return NewST;
9002     }
9003   }
9004
9005   return SDValue();
9006 }
9007
9008 /// For a given floating point load / store pair, if the load value isn't used
9009 /// by any other operations, then consider transforming the pair to integer
9010 /// load / store operations if the target deems the transformation profitable.
9011 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
9012   StoreSDNode *ST  = cast<StoreSDNode>(N);
9013   SDValue Chain = ST->getChain();
9014   SDValue Value = ST->getValue();
9015   if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
9016       Value.hasOneUse() &&
9017       Chain == SDValue(Value.getNode(), 1)) {
9018     LoadSDNode *LD = cast<LoadSDNode>(Value);
9019     EVT VT = LD->getMemoryVT();
9020     if (!VT.isFloatingPoint() ||
9021         VT != ST->getMemoryVT() ||
9022         LD->isNonTemporal() ||
9023         ST->isNonTemporal() ||
9024         LD->getPointerInfo().getAddrSpace() != 0 ||
9025         ST->getPointerInfo().getAddrSpace() != 0)
9026       return SDValue();
9027
9028     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
9029     if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
9030         !TLI.isOperationLegal(ISD::STORE, IntVT) ||
9031         !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
9032         !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
9033       return SDValue();
9034
9035     unsigned LDAlign = LD->getAlignment();
9036     unsigned STAlign = ST->getAlignment();
9037     Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
9038     unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
9039     if (LDAlign < ABIAlign || STAlign < ABIAlign)
9040       return SDValue();
9041
9042     SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
9043                                 LD->getChain(), LD->getBasePtr(),
9044                                 LD->getPointerInfo(),
9045                                 false, false, false, LDAlign);
9046
9047     SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
9048                                  NewLD, ST->getBasePtr(),
9049                                  ST->getPointerInfo(),
9050                                  false, false, STAlign);
9051
9052     AddToWorklist(NewLD.getNode());
9053     AddToWorklist(NewST.getNode());
9054     WorklistRemover DeadNodes(*this);
9055     DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
9056     ++LdStFP2Int;
9057     return NewST;
9058   }
9059
9060   return SDValue();
9061 }
9062
9063 /// Helper struct to parse and store a memory address as base + index + offset.
9064 /// We ignore sign extensions when it is safe to do so.
9065 /// The following two expressions are not equivalent. To differentiate we need
9066 /// to store whether there was a sign extension involved in the index
9067 /// computation.
9068 ///  (load (i64 add (i64 copyfromreg %c)
9069 ///                 (i64 signextend (add (i8 load %index)
9070 ///                                      (i8 1))))
9071 /// vs
9072 ///
9073 /// (load (i64 add (i64 copyfromreg %c)
9074 ///                (i64 signextend (i32 add (i32 signextend (i8 load %index))
9075 ///                                         (i32 1)))))
9076 struct BaseIndexOffset {
9077   SDValue Base;
9078   SDValue Index;
9079   int64_t Offset;
9080   bool IsIndexSignExt;
9081
9082   BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
9083
9084   BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
9085                   bool IsIndexSignExt) :
9086     Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
9087
9088   bool equalBaseIndex(const BaseIndexOffset &Other) {
9089     return Other.Base == Base && Other.Index == Index &&
9090       Other.IsIndexSignExt == IsIndexSignExt;
9091   }
9092
9093   /// Parses tree in Ptr for base, index, offset addresses.
9094   static BaseIndexOffset match(SDValue Ptr) {
9095     bool IsIndexSignExt = false;
9096
9097     // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
9098     // instruction, then it could be just the BASE or everything else we don't
9099     // know how to handle. Just use Ptr as BASE and give up.
9100     if (Ptr->getOpcode() != ISD::ADD)
9101       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9102
9103     // We know that we have at least an ADD instruction. Try to pattern match
9104     // the simple case of BASE + OFFSET.
9105     if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
9106       int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
9107       return  BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
9108                               IsIndexSignExt);
9109     }
9110
9111     // Inside a loop the current BASE pointer is calculated using an ADD and a
9112     // MUL instruction. In this case Ptr is the actual BASE pointer.
9113     // (i64 add (i64 %array_ptr)
9114     //          (i64 mul (i64 %induction_var)
9115     //                   (i64 %element_size)))
9116     if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
9117       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9118
9119     // Look at Base + Index + Offset cases.
9120     SDValue Base = Ptr->getOperand(0);
9121     SDValue IndexOffset = Ptr->getOperand(1);
9122
9123     // Skip signextends.
9124     if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
9125       IndexOffset = IndexOffset->getOperand(0);
9126       IsIndexSignExt = true;
9127     }
9128
9129     // Either the case of Base + Index (no offset) or something else.
9130     if (IndexOffset->getOpcode() != ISD::ADD)
9131       return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
9132
9133     // Now we have the case of Base + Index + offset.
9134     SDValue Index = IndexOffset->getOperand(0);
9135     SDValue Offset = IndexOffset->getOperand(1);
9136
9137     if (!isa<ConstantSDNode>(Offset))
9138       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9139
9140     // Ignore signextends.
9141     if (Index->getOpcode() == ISD::SIGN_EXTEND) {
9142       Index = Index->getOperand(0);
9143       IsIndexSignExt = true;
9144     } else IsIndexSignExt = false;
9145
9146     int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
9147     return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
9148   }
9149 };
9150
9151 /// Holds a pointer to an LSBaseSDNode as well as information on where it
9152 /// is located in a sequence of memory operations connected by a chain.
9153 struct MemOpLink {
9154   MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
9155     MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
9156   // Ptr to the mem node.
9157   LSBaseSDNode *MemNode;
9158   // Offset from the base ptr.
9159   int64_t OffsetFromBase;
9160   // What is the sequence number of this mem node.
9161   // Lowest mem operand in the DAG starts at zero.
9162   unsigned SequenceNum;
9163 };
9164
9165 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
9166   EVT MemVT = St->getMemoryVT();
9167   int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
9168   bool NoVectors = DAG.getMachineFunction().getFunction()->getAttributes().
9169     hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
9170
9171   // Don't merge vectors into wider inputs.
9172   if (MemVT.isVector() || !MemVT.isSimple())
9173     return false;
9174
9175   // Perform an early exit check. Do not bother looking at stored values that
9176   // are not constants or loads.
9177   SDValue StoredVal = St->getValue();
9178   bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
9179   if (!isa<ConstantSDNode>(StoredVal) && !isa<ConstantFPSDNode>(StoredVal) &&
9180       !IsLoadSrc)
9181     return false;
9182
9183   // Only look at ends of store sequences.
9184   SDValue Chain = SDValue(St, 0);
9185   if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
9186     return false;
9187
9188   // This holds the base pointer, index, and the offset in bytes from the base
9189   // pointer.
9190   BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
9191
9192   // We must have a base and an offset.
9193   if (!BasePtr.Base.getNode())
9194     return false;
9195
9196   // Do not handle stores to undef base pointers.
9197   if (BasePtr.Base.getOpcode() == ISD::UNDEF)
9198     return false;
9199
9200   // Save the LoadSDNodes that we find in the chain.
9201   // We need to make sure that these nodes do not interfere with
9202   // any of the store nodes.
9203   SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
9204
9205   // Save the StoreSDNodes that we find in the chain.
9206   SmallVector<MemOpLink, 8> StoreNodes;
9207
9208   // Walk up the chain and look for nodes with offsets from the same
9209   // base pointer. Stop when reaching an instruction with a different kind
9210   // or instruction which has a different base pointer.
9211   unsigned Seq = 0;
9212   StoreSDNode *Index = St;
9213   while (Index) {
9214     // If the chain has more than one use, then we can't reorder the mem ops.
9215     if (Index != St && !SDValue(Index, 0)->hasOneUse())
9216       break;
9217
9218     // Find the base pointer and offset for this memory node.
9219     BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
9220
9221     // Check that the base pointer is the same as the original one.
9222     if (!Ptr.equalBaseIndex(BasePtr))
9223       break;
9224
9225     // Check that the alignment is the same.
9226     if (Index->getAlignment() != St->getAlignment())
9227       break;
9228
9229     // The memory operands must not be volatile.
9230     if (Index->isVolatile() || Index->isIndexed())
9231       break;
9232
9233     // No truncation.
9234     if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
9235       if (St->isTruncatingStore())
9236         break;
9237
9238     // The stored memory type must be the same.
9239     if (Index->getMemoryVT() != MemVT)
9240       break;
9241
9242     // We do not allow unaligned stores because we want to prevent overriding
9243     // stores.
9244     if (Index->getAlignment()*8 != MemVT.getSizeInBits())
9245       break;
9246
9247     // We found a potential memory operand to merge.
9248     StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
9249
9250     // Find the next memory operand in the chain. If the next operand in the
9251     // chain is a store then move up and continue the scan with the next
9252     // memory operand. If the next operand is a load save it and use alias
9253     // information to check if it interferes with anything.
9254     SDNode *NextInChain = Index->getChain().getNode();
9255     while (1) {
9256       if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
9257         // We found a store node. Use it for the next iteration.
9258         Index = STn;
9259         break;
9260       } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
9261         if (Ldn->isVolatile()) {
9262           Index = nullptr;
9263           break;
9264         }
9265
9266         // Save the load node for later. Continue the scan.
9267         AliasLoadNodes.push_back(Ldn);
9268         NextInChain = Ldn->getChain().getNode();
9269         continue;
9270       } else {
9271         Index = nullptr;
9272         break;
9273       }
9274     }
9275   }
9276
9277   // Check if there is anything to merge.
9278   if (StoreNodes.size() < 2)
9279     return false;
9280
9281   // Sort the memory operands according to their distance from the base pointer.
9282   std::sort(StoreNodes.begin(), StoreNodes.end(),
9283             [](MemOpLink LHS, MemOpLink RHS) {
9284     return LHS.OffsetFromBase < RHS.OffsetFromBase ||
9285            (LHS.OffsetFromBase == RHS.OffsetFromBase &&
9286             LHS.SequenceNum > RHS.SequenceNum);
9287   });
9288
9289   // Scan the memory operations on the chain and find the first non-consecutive
9290   // store memory address.
9291   unsigned LastConsecutiveStore = 0;
9292   int64_t StartAddress = StoreNodes[0].OffsetFromBase;
9293   for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
9294
9295     // Check that the addresses are consecutive starting from the second
9296     // element in the list of stores.
9297     if (i > 0) {
9298       int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
9299       if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9300         break;
9301     }
9302
9303     bool Alias = false;
9304     // Check if this store interferes with any of the loads that we found.
9305     for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
9306       if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
9307         Alias = true;
9308         break;
9309       }
9310     // We found a load that alias with this store. Stop the sequence.
9311     if (Alias)
9312       break;
9313
9314     // Mark this node as useful.
9315     LastConsecutiveStore = i;
9316   }
9317
9318   // The node with the lowest store address.
9319   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
9320
9321   // Store the constants into memory as one consecutive store.
9322   if (!IsLoadSrc) {
9323     unsigned LastLegalType = 0;
9324     unsigned LastLegalVectorType = 0;
9325     bool NonZero = false;
9326     for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9327       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
9328       SDValue StoredVal = St->getValue();
9329
9330       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
9331         NonZero |= !C->isNullValue();
9332       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
9333         NonZero |= !C->getConstantFPValue()->isNullValue();
9334       } else {
9335         // Non-constant.
9336         break;
9337       }
9338
9339       // Find a legal type for the constant store.
9340       unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9341       EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9342       if (TLI.isTypeLegal(StoreTy))
9343         LastLegalType = i+1;
9344       // Or check whether a truncstore is legal.
9345       else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9346                TargetLowering::TypePromoteInteger) {
9347         EVT LegalizedStoredValueTy =
9348           TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
9349         if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy))
9350           LastLegalType = i+1;
9351       }
9352
9353       // Find a legal type for the vector store.
9354       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9355       if (TLI.isTypeLegal(Ty))
9356         LastLegalVectorType = i + 1;
9357     }
9358
9359     // We only use vectors if the constant is known to be zero and the
9360     // function is not marked with the noimplicitfloat attribute.
9361     if (NonZero || NoVectors)
9362       LastLegalVectorType = 0;
9363
9364     // Check if we found a legal integer type to store.
9365     if (LastLegalType == 0 && LastLegalVectorType == 0)
9366       return false;
9367
9368     bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
9369     unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
9370
9371     // Make sure we have something to merge.
9372     if (NumElem < 2)
9373       return false;
9374
9375     unsigned EarliestNodeUsed = 0;
9376     for (unsigned i=0; i < NumElem; ++i) {
9377       // Find a chain for the new wide-store operand. Notice that some
9378       // of the store nodes that we found may not be selected for inclusion
9379       // in the wide store. The chain we use needs to be the chain of the
9380       // earliest store node which is *used* and replaced by the wide store.
9381       if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9382         EarliestNodeUsed = i;
9383     }
9384
9385     // The earliest Node in the DAG.
9386     LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9387     SDLoc DL(StoreNodes[0].MemNode);
9388
9389     SDValue StoredVal;
9390     if (UseVector) {
9391       // Find a legal type for the vector store.
9392       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9393       assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
9394       StoredVal = DAG.getConstant(0, Ty);
9395     } else {
9396       unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9397       APInt StoreInt(StoreBW, 0);
9398
9399       // Construct a single integer constant which is made of the smaller
9400       // constant inputs.
9401       bool IsLE = TLI.isLittleEndian();
9402       for (unsigned i = 0; i < NumElem ; ++i) {
9403         unsigned Idx = IsLE ?(NumElem - 1 - i) : i;
9404         StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
9405         SDValue Val = St->getValue();
9406         StoreInt<<=ElementSizeBytes*8;
9407         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
9408           StoreInt|=C->getAPIntValue().zext(StoreBW);
9409         } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
9410           StoreInt|= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
9411         } else {
9412           assert(false && "Invalid constant element type");
9413         }
9414       }
9415
9416       // Create the new Load and Store operations.
9417       EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9418       StoredVal = DAG.getConstant(StoreInt, StoreTy);
9419     }
9420
9421     SDValue NewStore = DAG.getStore(EarliestOp->getChain(), DL, StoredVal,
9422                                     FirstInChain->getBasePtr(),
9423                                     FirstInChain->getPointerInfo(),
9424                                     false, false,
9425                                     FirstInChain->getAlignment());
9426
9427     // Replace the first store with the new store
9428     CombineTo(EarliestOp, NewStore);
9429     // Erase all other stores.
9430     for (unsigned i = 0; i < NumElem ; ++i) {
9431       if (StoreNodes[i].MemNode == EarliestOp)
9432         continue;
9433       StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9434       // ReplaceAllUsesWith will replace all uses that existed when it was
9435       // called, but graph optimizations may cause new ones to appear. For
9436       // example, the case in pr14333 looks like
9437       //
9438       //  St's chain -> St -> another store -> X
9439       //
9440       // And the only difference from St to the other store is the chain.
9441       // When we change it's chain to be St's chain they become identical,
9442       // get CSEed and the net result is that X is now a use of St.
9443       // Since we know that St is redundant, just iterate.
9444       while (!St->use_empty())
9445         DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
9446       deleteAndRecombine(St);
9447     }
9448
9449     return true;
9450   }
9451
9452   // Below we handle the case of multiple consecutive stores that
9453   // come from multiple consecutive loads. We merge them into a single
9454   // wide load and a single wide store.
9455
9456   // Look for load nodes which are used by the stored values.
9457   SmallVector<MemOpLink, 8> LoadNodes;
9458
9459   // Find acceptable loads. Loads need to have the same chain (token factor),
9460   // must not be zext, volatile, indexed, and they must be consecutive.
9461   BaseIndexOffset LdBasePtr;
9462   for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9463     StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
9464     LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
9465     if (!Ld) break;
9466
9467     // Loads must only have one use.
9468     if (!Ld->hasNUsesOfValue(1, 0))
9469       break;
9470
9471     // Check that the alignment is the same as the stores.
9472     if (Ld->getAlignment() != St->getAlignment())
9473       break;
9474
9475     // The memory operands must not be volatile.
9476     if (Ld->isVolatile() || Ld->isIndexed())
9477       break;
9478
9479     // We do not accept ext loads.
9480     if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
9481       break;
9482
9483     // The stored memory type must be the same.
9484     if (Ld->getMemoryVT() != MemVT)
9485       break;
9486
9487     BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
9488     // If this is not the first ptr that we check.
9489     if (LdBasePtr.Base.getNode()) {
9490       // The base ptr must be the same.
9491       if (!LdPtr.equalBaseIndex(LdBasePtr))
9492         break;
9493     } else {
9494       // Check that all other base pointers are the same as this one.
9495       LdBasePtr = LdPtr;
9496     }
9497
9498     // We found a potential memory operand to merge.
9499     LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
9500   }
9501
9502   if (LoadNodes.size() < 2)
9503     return false;
9504
9505   // If we have load/store pair instructions and we only have two values,
9506   // don't bother.
9507   unsigned RequiredAlignment;
9508   if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) &&
9509       St->getAlignment() >= RequiredAlignment)
9510     return false;
9511
9512   // Scan the memory operations on the chain and find the first non-consecutive
9513   // load memory address. These variables hold the index in the store node
9514   // array.
9515   unsigned LastConsecutiveLoad = 0;
9516   // This variable refers to the size and not index in the array.
9517   unsigned LastLegalVectorType = 0;
9518   unsigned LastLegalIntegerType = 0;
9519   StartAddress = LoadNodes[0].OffsetFromBase;
9520   SDValue FirstChain = LoadNodes[0].MemNode->getChain();
9521   for (unsigned i = 1; i < LoadNodes.size(); ++i) {
9522     // All loads much share the same chain.
9523     if (LoadNodes[i].MemNode->getChain() != FirstChain)
9524       break;
9525
9526     int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
9527     if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9528       break;
9529     LastConsecutiveLoad = i;
9530
9531     // Find a legal type for the vector store.
9532     EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9533     if (TLI.isTypeLegal(StoreTy))
9534       LastLegalVectorType = i + 1;
9535
9536     // Find a legal type for the integer store.
9537     unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9538     StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9539     if (TLI.isTypeLegal(StoreTy))
9540       LastLegalIntegerType = i + 1;
9541     // Or check whether a truncstore and extload is legal.
9542     else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9543              TargetLowering::TypePromoteInteger) {
9544       EVT LegalizedStoredValueTy =
9545         TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
9546       if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
9547           TLI.isLoadExtLegal(ISD::ZEXTLOAD, StoreTy) &&
9548           TLI.isLoadExtLegal(ISD::SEXTLOAD, StoreTy) &&
9549           TLI.isLoadExtLegal(ISD::EXTLOAD, StoreTy))
9550         LastLegalIntegerType = i+1;
9551     }
9552   }
9553
9554   // Only use vector types if the vector type is larger than the integer type.
9555   // If they are the same, use integers.
9556   bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
9557   unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
9558
9559   // We add +1 here because the LastXXX variables refer to location while
9560   // the NumElem refers to array/index size.
9561   unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
9562   NumElem = std::min(LastLegalType, NumElem);
9563
9564   if (NumElem < 2)
9565     return false;
9566
9567   // The earliest Node in the DAG.
9568   unsigned EarliestNodeUsed = 0;
9569   LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9570   for (unsigned i=1; i<NumElem; ++i) {
9571     // Find a chain for the new wide-store operand. Notice that some
9572     // of the store nodes that we found may not be selected for inclusion
9573     // in the wide store. The chain we use needs to be the chain of the
9574     // earliest store node which is *used* and replaced by the wide store.
9575     if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9576       EarliestNodeUsed = i;
9577   }
9578
9579   // Find if it is better to use vectors or integers to load and store
9580   // to memory.
9581   EVT JointMemOpVT;
9582   if (UseVectorTy) {
9583     JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9584   } else {
9585     unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9586     JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9587   }
9588
9589   SDLoc LoadDL(LoadNodes[0].MemNode);
9590   SDLoc StoreDL(StoreNodes[0].MemNode);
9591
9592   LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
9593   SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL,
9594                                 FirstLoad->getChain(),
9595                                 FirstLoad->getBasePtr(),
9596                                 FirstLoad->getPointerInfo(),
9597                                 false, false, false,
9598                                 FirstLoad->getAlignment());
9599
9600   SDValue NewStore = DAG.getStore(EarliestOp->getChain(), StoreDL, NewLoad,
9601                                   FirstInChain->getBasePtr(),
9602                                   FirstInChain->getPointerInfo(), false, false,
9603                                   FirstInChain->getAlignment());
9604
9605   // Replace one of the loads with the new load.
9606   LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
9607   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
9608                                 SDValue(NewLoad.getNode(), 1));
9609
9610   // Remove the rest of the load chains.
9611   for (unsigned i = 1; i < NumElem ; ++i) {
9612     // Replace all chain users of the old load nodes with the chain of the new
9613     // load node.
9614     LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
9615     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
9616   }
9617
9618   // Replace the first store with the new store.
9619   CombineTo(EarliestOp, NewStore);
9620   // Erase all other stores.
9621   for (unsigned i = 0; i < NumElem ; ++i) {
9622     // Remove all Store nodes.
9623     if (StoreNodes[i].MemNode == EarliestOp)
9624       continue;
9625     StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9626     DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
9627     deleteAndRecombine(St);
9628   }
9629
9630   return true;
9631 }
9632
9633 SDValue DAGCombiner::visitSTORE(SDNode *N) {
9634   StoreSDNode *ST  = cast<StoreSDNode>(N);
9635   SDValue Chain = ST->getChain();
9636   SDValue Value = ST->getValue();
9637   SDValue Ptr   = ST->getBasePtr();
9638
9639   // If this is a store of a bit convert, store the input value if the
9640   // resultant store does not need a higher alignment than the original.
9641   if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
9642       ST->isUnindexed()) {
9643     unsigned OrigAlign = ST->getAlignment();
9644     EVT SVT = Value.getOperand(0).getValueType();
9645     unsigned Align = TLI.getDataLayout()->
9646       getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
9647     if (Align <= OrigAlign &&
9648         ((!LegalOperations && !ST->isVolatile()) ||
9649          TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
9650       return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
9651                           Ptr, ST->getPointerInfo(), ST->isVolatile(),
9652                           ST->isNonTemporal(), OrigAlign,
9653                           ST->getAAInfo());
9654   }
9655
9656   // Turn 'store undef, Ptr' -> nothing.
9657   if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
9658     return Chain;
9659
9660   // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
9661   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
9662     // NOTE: If the original store is volatile, this transform must not increase
9663     // the number of stores.  For example, on x86-32 an f64 can be stored in one
9664     // processor operation but an i64 (which is not legal) requires two.  So the
9665     // transform should not be done in this case.
9666     if (Value.getOpcode() != ISD::TargetConstantFP) {
9667       SDValue Tmp;
9668       switch (CFP->getSimpleValueType(0).SimpleTy) {
9669       default: llvm_unreachable("Unknown FP type");
9670       case MVT::f16:    // We don't do this for these yet.
9671       case MVT::f80:
9672       case MVT::f128:
9673       case MVT::ppcf128:
9674         break;
9675       case MVT::f32:
9676         if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
9677             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
9678           Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
9679                               bitcastToAPInt().getZExtValue(), MVT::i32);
9680           return DAG.getStore(Chain, SDLoc(N), Tmp,
9681                               Ptr, ST->getMemOperand());
9682         }
9683         break;
9684       case MVT::f64:
9685         if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
9686              !ST->isVolatile()) ||
9687             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
9688           Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
9689                                 getZExtValue(), MVT::i64);
9690           return DAG.getStore(Chain, SDLoc(N), Tmp,
9691                               Ptr, ST->getMemOperand());
9692         }
9693
9694         if (!ST->isVolatile() &&
9695             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
9696           // Many FP stores are not made apparent until after legalize, e.g. for
9697           // argument passing.  Since this is so common, custom legalize the
9698           // 64-bit integer store into two 32-bit stores.
9699           uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
9700           SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
9701           SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
9702           if (TLI.isBigEndian()) std::swap(Lo, Hi);
9703
9704           unsigned Alignment = ST->getAlignment();
9705           bool isVolatile = ST->isVolatile();
9706           bool isNonTemporal = ST->isNonTemporal();
9707           AAMDNodes AAInfo = ST->getAAInfo();
9708
9709           SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
9710                                      Ptr, ST->getPointerInfo(),
9711                                      isVolatile, isNonTemporal,
9712                                      ST->getAlignment(), AAInfo);
9713           Ptr = DAG.getNode(ISD::ADD, SDLoc(N), Ptr.getValueType(), Ptr,
9714                             DAG.getConstant(4, Ptr.getValueType()));
9715           Alignment = MinAlign(Alignment, 4U);
9716           SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
9717                                      Ptr, ST->getPointerInfo().getWithOffset(4),
9718                                      isVolatile, isNonTemporal,
9719                                      Alignment, AAInfo);
9720           return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
9721                              St0, St1);
9722         }
9723
9724         break;
9725       }
9726     }
9727   }
9728
9729   // Try to infer better alignment information than the store already has.
9730   if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
9731     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
9732       if (Align > ST->getAlignment())
9733         return DAG.getTruncStore(Chain, SDLoc(N), Value,
9734                                  Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
9735                                  ST->isVolatile(), ST->isNonTemporal(), Align,
9736                                  ST->getAAInfo());
9737     }
9738   }
9739
9740   // Try transforming a pair floating point load / store ops to integer
9741   // load / store ops.
9742   SDValue NewST = TransformFPLoadStorePair(N);
9743   if (NewST.getNode())
9744     return NewST;
9745
9746   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
9747     TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
9748 #ifndef NDEBUG
9749   if (CombinerAAOnlyFunc.getNumOccurrences() &&
9750       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
9751     UseAA = false;
9752 #endif
9753   if (UseAA && ST->isUnindexed()) {
9754     // Walk up chain skipping non-aliasing memory nodes.
9755     SDValue BetterChain = FindBetterChain(N, Chain);
9756
9757     // If there is a better chain.
9758     if (Chain != BetterChain) {
9759       SDValue ReplStore;
9760
9761       // Replace the chain to avoid dependency.
9762       if (ST->isTruncatingStore()) {
9763         ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
9764                                       ST->getMemoryVT(), ST->getMemOperand());
9765       } else {
9766         ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
9767                                  ST->getMemOperand());
9768       }
9769
9770       // Create token to keep both nodes around.
9771       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
9772                                   MVT::Other, Chain, ReplStore);
9773
9774       // Make sure the new and old chains are cleaned up.
9775       AddToWorklist(Token.getNode());
9776
9777       // Don't add users to work list.
9778       return CombineTo(N, Token, false);
9779     }
9780   }
9781
9782   // Try transforming N to an indexed store.
9783   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
9784     return SDValue(N, 0);
9785
9786   // FIXME: is there such a thing as a truncating indexed store?
9787   if (ST->isTruncatingStore() && ST->isUnindexed() &&
9788       Value.getValueType().isInteger()) {
9789     // See if we can simplify the input to this truncstore with knowledge that
9790     // only the low bits are being used.  For example:
9791     // "truncstore (or (shl x, 8), y), i8"  -> "truncstore y, i8"
9792     SDValue Shorter =
9793       GetDemandedBits(Value,
9794                       APInt::getLowBitsSet(
9795                         Value.getValueType().getScalarType().getSizeInBits(),
9796                         ST->getMemoryVT().getScalarType().getSizeInBits()));
9797     AddToWorklist(Value.getNode());
9798     if (Shorter.getNode())
9799       return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
9800                                Ptr, ST->getMemoryVT(), ST->getMemOperand());
9801
9802     // Otherwise, see if we can simplify the operation with
9803     // SimplifyDemandedBits, which only works if the value has a single use.
9804     if (SimplifyDemandedBits(Value,
9805                         APInt::getLowBitsSet(
9806                           Value.getValueType().getScalarType().getSizeInBits(),
9807                           ST->getMemoryVT().getScalarType().getSizeInBits())))
9808       return SDValue(N, 0);
9809   }
9810
9811   // If this is a load followed by a store to the same location, then the store
9812   // is dead/noop.
9813   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
9814     if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
9815         ST->isUnindexed() && !ST->isVolatile() &&
9816         // There can't be any side effects between the load and store, such as
9817         // a call or store.
9818         Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
9819       // The store is dead, remove it.
9820       return Chain;
9821     }
9822   }
9823
9824   // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
9825   // truncating store.  We can do this even if this is already a truncstore.
9826   if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
9827       && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
9828       TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
9829                             ST->getMemoryVT())) {
9830     return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
9831                              Ptr, ST->getMemoryVT(), ST->getMemOperand());
9832   }
9833
9834   // Only perform this optimization before the types are legal, because we
9835   // don't want to perform this optimization on every DAGCombine invocation.
9836   if (!LegalTypes) {
9837     bool EverChanged = false;
9838
9839     do {
9840       // There can be multiple store sequences on the same chain.
9841       // Keep trying to merge store sequences until we are unable to do so
9842       // or until we merge the last store on the chain.
9843       bool Changed = MergeConsecutiveStores(ST);
9844       EverChanged |= Changed;
9845       if (!Changed) break;
9846     } while (ST->getOpcode() != ISD::DELETED_NODE);
9847
9848     if (EverChanged)
9849       return SDValue(N, 0);
9850   }
9851
9852   return ReduceLoadOpStoreWidth(N);
9853 }
9854
9855 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
9856   SDValue InVec = N->getOperand(0);
9857   SDValue InVal = N->getOperand(1);
9858   SDValue EltNo = N->getOperand(2);
9859   SDLoc dl(N);
9860
9861   // If the inserted element is an UNDEF, just use the input vector.
9862   if (InVal.getOpcode() == ISD::UNDEF)
9863     return InVec;
9864
9865   EVT VT = InVec.getValueType();
9866
9867   // If we can't generate a legal BUILD_VECTOR, exit
9868   if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
9869     return SDValue();
9870
9871   // Check that we know which element is being inserted
9872   if (!isa<ConstantSDNode>(EltNo))
9873     return SDValue();
9874   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9875
9876   // Canonicalize insert_vector_elt dag nodes.
9877   // Example:
9878   // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
9879   // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
9880   //
9881   // Do this only if the child insert_vector node has one use; also
9882   // do this only if indices are both constants and Idx1 < Idx0.
9883   if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
9884       && isa<ConstantSDNode>(InVec.getOperand(2))) {
9885     unsigned OtherElt =
9886       cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue();
9887     if (Elt < OtherElt) {
9888       // Swap nodes.
9889       SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT,
9890                                   InVec.getOperand(0), InVal, EltNo);
9891       AddToWorklist(NewOp.getNode());
9892       return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
9893                          VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
9894     }
9895   }
9896
9897   // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
9898   // be converted to a BUILD_VECTOR).  Fill in the Ops vector with the
9899   // vector elements.
9900   SmallVector<SDValue, 8> Ops;
9901   // Do not combine these two vectors if the output vector will not replace
9902   // the input vector.
9903   if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
9904     Ops.append(InVec.getNode()->op_begin(),
9905                InVec.getNode()->op_end());
9906   } else if (InVec.getOpcode() == ISD::UNDEF) {
9907     unsigned NElts = VT.getVectorNumElements();
9908     Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
9909   } else {
9910     return SDValue();
9911   }
9912
9913   // Insert the element
9914   if (Elt < Ops.size()) {
9915     // All the operands of BUILD_VECTOR must have the same type;
9916     // we enforce that here.
9917     EVT OpVT = Ops[0].getValueType();
9918     if (InVal.getValueType() != OpVT)
9919       InVal = OpVT.bitsGT(InVal.getValueType()) ?
9920                 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
9921                 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
9922     Ops[Elt] = InVal;
9923   }
9924
9925   // Return the new vector
9926   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
9927 }
9928
9929 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
9930     SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) {
9931   EVT ResultVT = EVE->getValueType(0);
9932   EVT VecEltVT = InVecVT.getVectorElementType();
9933   unsigned Align = OriginalLoad->getAlignment();
9934   unsigned NewAlign = TLI.getDataLayout()->getABITypeAlignment(
9935       VecEltVT.getTypeForEVT(*DAG.getContext()));
9936
9937   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
9938     return SDValue();
9939
9940   Align = NewAlign;
9941
9942   SDValue NewPtr = OriginalLoad->getBasePtr();
9943   SDValue Offset;
9944   EVT PtrType = NewPtr.getValueType();
9945   MachinePointerInfo MPI;
9946   if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
9947     int Elt = ConstEltNo->getZExtValue();
9948     unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
9949     if (TLI.isBigEndian())
9950       PtrOff = InVecVT.getSizeInBits() / 8 - PtrOff;
9951     Offset = DAG.getConstant(PtrOff, PtrType);
9952     MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
9953   } else {
9954     Offset = DAG.getNode(
9955         ISD::MUL, SDLoc(EVE), EltNo.getValueType(), EltNo,
9956         DAG.getConstant(VecEltVT.getStoreSize(), EltNo.getValueType()));
9957     if (TLI.isBigEndian())
9958       Offset = DAG.getNode(
9959           ISD::SUB, SDLoc(EVE), EltNo.getValueType(),
9960           DAG.getConstant(InVecVT.getStoreSize(), EltNo.getValueType()), Offset);
9961     MPI = OriginalLoad->getPointerInfo();
9962   }
9963   NewPtr = DAG.getNode(ISD::ADD, SDLoc(EVE), PtrType, NewPtr, Offset);
9964
9965   // The replacement we need to do here is a little tricky: we need to
9966   // replace an extractelement of a load with a load.
9967   // Use ReplaceAllUsesOfValuesWith to do the replacement.
9968   // Note that this replacement assumes that the extractvalue is the only
9969   // use of the load; that's okay because we don't want to perform this
9970   // transformation in other cases anyway.
9971   SDValue Load;
9972   SDValue Chain;
9973   if (ResultVT.bitsGT(VecEltVT)) {
9974     // If the result type of vextract is wider than the load, then issue an
9975     // extending load instead.
9976     ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, VecEltVT)
9977                                    ? ISD::ZEXTLOAD
9978                                    : ISD::EXTLOAD;
9979     Load = DAG.getExtLoad(
9980         ExtType, SDLoc(EVE), ResultVT, OriginalLoad->getChain(), NewPtr, MPI,
9981         VecEltVT, OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
9982         OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
9983     Chain = Load.getValue(1);
9984   } else {
9985     Load = DAG.getLoad(
9986         VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, MPI,
9987         OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
9988         OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
9989     Chain = Load.getValue(1);
9990     if (ResultVT.bitsLT(VecEltVT))
9991       Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
9992     else
9993       Load = DAG.getNode(ISD::BITCAST, SDLoc(EVE), ResultVT, Load);
9994   }
9995   WorklistRemover DeadNodes(*this);
9996   SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
9997   SDValue To[] = { Load, Chain };
9998   DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
9999   // Since we're explicitly calling ReplaceAllUses, add the new node to the
10000   // worklist explicitly as well.
10001   AddToWorklist(Load.getNode());
10002   AddUsersToWorklist(Load.getNode()); // Add users too
10003   // Make sure to revisit this node to clean it up; it will usually be dead.
10004   AddToWorklist(EVE);
10005   ++OpsNarrowed;
10006   return SDValue(EVE, 0);
10007 }
10008
10009 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
10010   // (vextract (scalar_to_vector val, 0) -> val
10011   SDValue InVec = N->getOperand(0);
10012   EVT VT = InVec.getValueType();
10013   EVT NVT = N->getValueType(0);
10014
10015   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
10016     // Check if the result type doesn't match the inserted element type. A
10017     // SCALAR_TO_VECTOR may truncate the inserted element and the
10018     // EXTRACT_VECTOR_ELT may widen the extracted vector.
10019     SDValue InOp = InVec.getOperand(0);
10020     if (InOp.getValueType() != NVT) {
10021       assert(InOp.getValueType().isInteger() && NVT.isInteger());
10022       return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
10023     }
10024     return InOp;
10025   }
10026
10027   SDValue EltNo = N->getOperand(1);
10028   bool ConstEltNo = isa<ConstantSDNode>(EltNo);
10029
10030   // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
10031   // We only perform this optimization before the op legalization phase because
10032   // we may introduce new vector instructions which are not backed by TD
10033   // patterns. For example on AVX, extracting elements from a wide vector
10034   // without using extract_subvector. However, if we can find an underlying
10035   // scalar value, then we can always use that.
10036   if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
10037       && ConstEltNo) {
10038     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
10039     int NumElem = VT.getVectorNumElements();
10040     ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
10041     // Find the new index to extract from.
10042     int OrigElt = SVOp->getMaskElt(Elt);
10043
10044     // Extracting an undef index is undef.
10045     if (OrigElt == -1)
10046       return DAG.getUNDEF(NVT);
10047
10048     // Select the right vector half to extract from.
10049     SDValue SVInVec;
10050     if (OrigElt < NumElem) {
10051       SVInVec = InVec->getOperand(0);
10052     } else {
10053       SVInVec = InVec->getOperand(1);
10054       OrigElt -= NumElem;
10055     }
10056
10057     if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
10058       SDValue InOp = SVInVec.getOperand(OrigElt);
10059       if (InOp.getValueType() != NVT) {
10060         assert(InOp.getValueType().isInteger() && NVT.isInteger());
10061         InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
10062       }
10063
10064       return InOp;
10065     }
10066
10067     // FIXME: We should handle recursing on other vector shuffles and
10068     // scalar_to_vector here as well.
10069
10070     if (!LegalOperations) {
10071       EVT IndexTy = TLI.getVectorIdxTy();
10072       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT,
10073                          SVInVec, DAG.getConstant(OrigElt, IndexTy));
10074     }
10075   }
10076
10077   bool BCNumEltsChanged = false;
10078   EVT ExtVT = VT.getVectorElementType();
10079   EVT LVT = ExtVT;
10080
10081   // If the result of load has to be truncated, then it's not necessarily
10082   // profitable.
10083   if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
10084     return SDValue();
10085
10086   if (InVec.getOpcode() == ISD::BITCAST) {
10087     // Don't duplicate a load with other uses.
10088     if (!InVec.hasOneUse())
10089       return SDValue();
10090
10091     EVT BCVT = InVec.getOperand(0).getValueType();
10092     if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
10093       return SDValue();
10094     if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
10095       BCNumEltsChanged = true;
10096     InVec = InVec.getOperand(0);
10097     ExtVT = BCVT.getVectorElementType();
10098   }
10099
10100   // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size)
10101   if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() &&
10102       ISD::isNormalLoad(InVec.getNode()) &&
10103       !N->getOperand(1)->hasPredecessor(InVec.getNode())) {
10104     SDValue Index = N->getOperand(1);
10105     if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec))
10106       return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index,
10107                                                            OrigLoad);
10108   }
10109
10110   // Perform only after legalization to ensure build_vector / vector_shuffle
10111   // optimizations have already been done.
10112   if (!LegalOperations) return SDValue();
10113
10114   // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
10115   // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
10116   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
10117
10118   if (ConstEltNo) {
10119     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
10120
10121     LoadSDNode *LN0 = nullptr;
10122     const ShuffleVectorSDNode *SVN = nullptr;
10123     if (ISD::isNormalLoad(InVec.getNode())) {
10124       LN0 = cast<LoadSDNode>(InVec);
10125     } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
10126                InVec.getOperand(0).getValueType() == ExtVT &&
10127                ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
10128       // Don't duplicate a load with other uses.
10129       if (!InVec.hasOneUse())
10130         return SDValue();
10131
10132       LN0 = cast<LoadSDNode>(InVec.getOperand(0));
10133     } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
10134       // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
10135       // =>
10136       // (load $addr+1*size)
10137
10138       // Don't duplicate a load with other uses.
10139       if (!InVec.hasOneUse())
10140         return SDValue();
10141
10142       // If the bit convert changed the number of elements, it is unsafe
10143       // to examine the mask.
10144       if (BCNumEltsChanged)
10145         return SDValue();
10146
10147       // Select the input vector, guarding against out of range extract vector.
10148       unsigned NumElems = VT.getVectorNumElements();
10149       int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
10150       InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
10151
10152       if (InVec.getOpcode() == ISD::BITCAST) {
10153         // Don't duplicate a load with other uses.
10154         if (!InVec.hasOneUse())
10155           return SDValue();
10156
10157         InVec = InVec.getOperand(0);
10158       }
10159       if (ISD::isNormalLoad(InVec.getNode())) {
10160         LN0 = cast<LoadSDNode>(InVec);
10161         Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
10162         EltNo = DAG.getConstant(Elt, EltNo.getValueType());
10163       }
10164     }
10165
10166     // Make sure we found a non-volatile load and the extractelement is
10167     // the only use.
10168     if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
10169       return SDValue();
10170
10171     // If Idx was -1 above, Elt is going to be -1, so just return undef.
10172     if (Elt == -1)
10173       return DAG.getUNDEF(LVT);
10174
10175     return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0);
10176   }
10177
10178   return SDValue();
10179 }
10180
10181 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
10182 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
10183   // We perform this optimization post type-legalization because
10184   // the type-legalizer often scalarizes integer-promoted vectors.
10185   // Performing this optimization before may create bit-casts which
10186   // will be type-legalized to complex code sequences.
10187   // We perform this optimization only before the operation legalizer because we
10188   // may introduce illegal operations.
10189   if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
10190     return SDValue();
10191
10192   unsigned NumInScalars = N->getNumOperands();
10193   SDLoc dl(N);
10194   EVT VT = N->getValueType(0);
10195
10196   // Check to see if this is a BUILD_VECTOR of a bunch of values
10197   // which come from any_extend or zero_extend nodes. If so, we can create
10198   // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
10199   // optimizations. We do not handle sign-extend because we can't fill the sign
10200   // using shuffles.
10201   EVT SourceType = MVT::Other;
10202   bool AllAnyExt = true;
10203
10204   for (unsigned i = 0; i != NumInScalars; ++i) {
10205     SDValue In = N->getOperand(i);
10206     // Ignore undef inputs.
10207     if (In.getOpcode() == ISD::UNDEF) continue;
10208
10209     bool AnyExt  = In.getOpcode() == ISD::ANY_EXTEND;
10210     bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
10211
10212     // Abort if the element is not an extension.
10213     if (!ZeroExt && !AnyExt) {
10214       SourceType = MVT::Other;
10215       break;
10216     }
10217
10218     // The input is a ZeroExt or AnyExt. Check the original type.
10219     EVT InTy = In.getOperand(0).getValueType();
10220
10221     // Check that all of the widened source types are the same.
10222     if (SourceType == MVT::Other)
10223       // First time.
10224       SourceType = InTy;
10225     else if (InTy != SourceType) {
10226       // Multiple income types. Abort.
10227       SourceType = MVT::Other;
10228       break;
10229     }
10230
10231     // Check if all of the extends are ANY_EXTENDs.
10232     AllAnyExt &= AnyExt;
10233   }
10234
10235   // In order to have valid types, all of the inputs must be extended from the
10236   // same source type and all of the inputs must be any or zero extend.
10237   // Scalar sizes must be a power of two.
10238   EVT OutScalarTy = VT.getScalarType();
10239   bool ValidTypes = SourceType != MVT::Other &&
10240                  isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
10241                  isPowerOf2_32(SourceType.getSizeInBits());
10242
10243   // Create a new simpler BUILD_VECTOR sequence which other optimizations can
10244   // turn into a single shuffle instruction.
10245   if (!ValidTypes)
10246     return SDValue();
10247
10248   bool isLE = TLI.isLittleEndian();
10249   unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
10250   assert(ElemRatio > 1 && "Invalid element size ratio");
10251   SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
10252                                DAG.getConstant(0, SourceType);
10253
10254   unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
10255   SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
10256
10257   // Populate the new build_vector
10258   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
10259     SDValue Cast = N->getOperand(i);
10260     assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
10261             Cast.getOpcode() == ISD::ZERO_EXTEND ||
10262             Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
10263     SDValue In;
10264     if (Cast.getOpcode() == ISD::UNDEF)
10265       In = DAG.getUNDEF(SourceType);
10266     else
10267       In = Cast->getOperand(0);
10268     unsigned Index = isLE ? (i * ElemRatio) :
10269                             (i * ElemRatio + (ElemRatio - 1));
10270
10271     assert(Index < Ops.size() && "Invalid index");
10272     Ops[Index] = In;
10273   }
10274
10275   // The type of the new BUILD_VECTOR node.
10276   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
10277   assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
10278          "Invalid vector size");
10279   // Check if the new vector type is legal.
10280   if (!isTypeLegal(VecVT)) return SDValue();
10281
10282   // Make the new BUILD_VECTOR.
10283   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
10284
10285   // The new BUILD_VECTOR node has the potential to be further optimized.
10286   AddToWorklist(BV.getNode());
10287   // Bitcast to the desired type.
10288   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
10289 }
10290
10291 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
10292   EVT VT = N->getValueType(0);
10293
10294   unsigned NumInScalars = N->getNumOperands();
10295   SDLoc dl(N);
10296
10297   EVT SrcVT = MVT::Other;
10298   unsigned Opcode = ISD::DELETED_NODE;
10299   unsigned NumDefs = 0;
10300
10301   for (unsigned i = 0; i != NumInScalars; ++i) {
10302     SDValue In = N->getOperand(i);
10303     unsigned Opc = In.getOpcode();
10304
10305     if (Opc == ISD::UNDEF)
10306       continue;
10307
10308     // If all scalar values are floats and converted from integers.
10309     if (Opcode == ISD::DELETED_NODE &&
10310         (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
10311       Opcode = Opc;
10312     }
10313
10314     if (Opc != Opcode)
10315       return SDValue();
10316
10317     EVT InVT = In.getOperand(0).getValueType();
10318
10319     // If all scalar values are typed differently, bail out. It's chosen to
10320     // simplify BUILD_VECTOR of integer types.
10321     if (SrcVT == MVT::Other)
10322       SrcVT = InVT;
10323     if (SrcVT != InVT)
10324       return SDValue();
10325     NumDefs++;
10326   }
10327
10328   // If the vector has just one element defined, it's not worth to fold it into
10329   // a vectorized one.
10330   if (NumDefs < 2)
10331     return SDValue();
10332
10333   assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
10334          && "Should only handle conversion from integer to float.");
10335   assert(SrcVT != MVT::Other && "Cannot determine source type!");
10336
10337   EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
10338
10339   if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
10340     return SDValue();
10341
10342   SmallVector<SDValue, 8> Opnds;
10343   for (unsigned i = 0; i != NumInScalars; ++i) {
10344     SDValue In = N->getOperand(i);
10345
10346     if (In.getOpcode() == ISD::UNDEF)
10347       Opnds.push_back(DAG.getUNDEF(SrcVT));
10348     else
10349       Opnds.push_back(In.getOperand(0));
10350   }
10351   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds);
10352   AddToWorklist(BV.getNode());
10353
10354   return DAG.getNode(Opcode, dl, VT, BV);
10355 }
10356
10357 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
10358   unsigned NumInScalars = N->getNumOperands();
10359   SDLoc dl(N);
10360   EVT VT = N->getValueType(0);
10361
10362   // A vector built entirely of undefs is undef.
10363   if (ISD::allOperandsUndef(N))
10364     return DAG.getUNDEF(VT);
10365
10366   SDValue V = reduceBuildVecExtToExtBuildVec(N);
10367   if (V.getNode())
10368     return V;
10369
10370   V = reduceBuildVecConvertToConvertBuildVec(N);
10371   if (V.getNode())
10372     return V;
10373
10374   // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
10375   // operations.  If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
10376   // at most two distinct vectors, turn this into a shuffle node.
10377
10378   // May only combine to shuffle after legalize if shuffle is legal.
10379   if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT))
10380     return SDValue();
10381
10382   SDValue VecIn1, VecIn2;
10383   for (unsigned i = 0; i != NumInScalars; ++i) {
10384     // Ignore undef inputs.
10385     if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
10386
10387     // If this input is something other than a EXTRACT_VECTOR_ELT with a
10388     // constant index, bail out.
10389     if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10390         !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) {
10391       VecIn1 = VecIn2 = SDValue(nullptr, 0);
10392       break;
10393     }
10394
10395     // We allow up to two distinct input vectors.
10396     SDValue ExtractedFromVec = N->getOperand(i).getOperand(0);
10397     if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
10398       continue;
10399
10400     if (!VecIn1.getNode()) {
10401       VecIn1 = ExtractedFromVec;
10402     } else if (!VecIn2.getNode()) {
10403       VecIn2 = ExtractedFromVec;
10404     } else {
10405       // Too many inputs.
10406       VecIn1 = VecIn2 = SDValue(nullptr, 0);
10407       break;
10408     }
10409   }
10410
10411   // If everything is good, we can make a shuffle operation.
10412   if (VecIn1.getNode()) {
10413     SmallVector<int, 8> Mask;
10414     for (unsigned i = 0; i != NumInScalars; ++i) {
10415       if (N->getOperand(i).getOpcode() == ISD::UNDEF) {
10416         Mask.push_back(-1);
10417         continue;
10418       }
10419
10420       // If extracting from the first vector, just use the index directly.
10421       SDValue Extract = N->getOperand(i);
10422       SDValue ExtVal = Extract.getOperand(1);
10423       if (Extract.getOperand(0) == VecIn1) {
10424         unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
10425         if (ExtIndex > VT.getVectorNumElements())
10426           return SDValue();
10427
10428         Mask.push_back(ExtIndex);
10429         continue;
10430       }
10431
10432       // Otherwise, use InIdx + VecSize
10433       unsigned Idx = cast<ConstantSDNode>(ExtVal)->getZExtValue();
10434       Mask.push_back(Idx+NumInScalars);
10435     }
10436
10437     // We can't generate a shuffle node with mismatched input and output types.
10438     // Attempt to transform a single input vector to the correct type.
10439     if ((VT != VecIn1.getValueType())) {
10440       // We don't support shuffeling between TWO values of different types.
10441       if (VecIn2.getNode())
10442         return SDValue();
10443
10444       // We only support widening of vectors which are half the size of the
10445       // output registers. For example XMM->YMM widening on X86 with AVX.
10446       if (VecIn1.getValueType().getSizeInBits()*2 != VT.getSizeInBits())
10447         return SDValue();
10448
10449       // If the input vector type has a different base type to the output
10450       // vector type, bail out.
10451       if (VecIn1.getValueType().getVectorElementType() !=
10452           VT.getVectorElementType())
10453         return SDValue();
10454
10455       // Widen the input vector by adding undef values.
10456       VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10457                            VecIn1, DAG.getUNDEF(VecIn1.getValueType()));
10458     }
10459
10460     // If VecIn2 is unused then change it to undef.
10461     VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
10462
10463     // Check that we were able to transform all incoming values to the same
10464     // type.
10465     if (VecIn2.getValueType() != VecIn1.getValueType() ||
10466         VecIn1.getValueType() != VT)
10467           return SDValue();
10468
10469     // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
10470     if (!isTypeLegal(VT))
10471       return SDValue();
10472
10473     // Return the new VECTOR_SHUFFLE node.
10474     SDValue Ops[2];
10475     Ops[0] = VecIn1;
10476     Ops[1] = VecIn2;
10477     return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
10478   }
10479
10480   return SDValue();
10481 }
10482
10483 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
10484   // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
10485   // EXTRACT_SUBVECTOR operations.  If so, and if the EXTRACT_SUBVECTOR vector
10486   // inputs come from at most two distinct vectors, turn this into a shuffle
10487   // node.
10488
10489   // If we only have one input vector, we don't need to do any concatenation.
10490   if (N->getNumOperands() == 1)
10491     return N->getOperand(0);
10492
10493   // Check if all of the operands are undefs.
10494   EVT VT = N->getValueType(0);
10495   if (ISD::allOperandsUndef(N))
10496     return DAG.getUNDEF(VT);
10497
10498   // Optimize concat_vectors where one of the vectors is undef.
10499   if (N->getNumOperands() == 2 &&
10500       N->getOperand(1)->getOpcode() == ISD::UNDEF) {
10501     SDValue In = N->getOperand(0);
10502     assert(In.getValueType().isVector() && "Must concat vectors");
10503
10504     // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
10505     if (In->getOpcode() == ISD::BITCAST &&
10506         !In->getOperand(0)->getValueType(0).isVector()) {
10507       SDValue Scalar = In->getOperand(0);
10508       EVT SclTy = Scalar->getValueType(0);
10509
10510       if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
10511         return SDValue();
10512
10513       EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
10514                                  VT.getSizeInBits() / SclTy.getSizeInBits());
10515       if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
10516         return SDValue();
10517
10518       SDLoc dl = SDLoc(N);
10519       SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
10520       return DAG.getNode(ISD::BITCAST, dl, VT, Res);
10521     }
10522   }
10523
10524   // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
10525   // -> (BUILD_VECTOR A, B, ..., C, D, ...)
10526   if (N->getNumOperands() == 2 &&
10527       N->getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
10528       N->getOperand(1).getOpcode() == ISD::BUILD_VECTOR) {
10529     EVT VT = N->getValueType(0);
10530     SDValue N0 = N->getOperand(0);
10531     SDValue N1 = N->getOperand(1);
10532     SmallVector<SDValue, 8> Opnds;
10533     unsigned BuildVecNumElts =  N0.getNumOperands();
10534
10535     EVT SclTy0 = N0.getOperand(0)->getValueType(0);
10536     EVT SclTy1 = N1.getOperand(0)->getValueType(0);
10537     if (SclTy0.isFloatingPoint()) {
10538       for (unsigned i = 0; i != BuildVecNumElts; ++i)
10539         Opnds.push_back(N0.getOperand(i));
10540       for (unsigned i = 0; i != BuildVecNumElts; ++i)
10541         Opnds.push_back(N1.getOperand(i));
10542     } else {
10543       // If BUILD_VECTOR are from built from integer, they may have different
10544       // operand types. Get the smaller type and truncate all operands to it.
10545       EVT MinTy = SclTy0.bitsLE(SclTy1) ? SclTy0 : SclTy1;
10546       for (unsigned i = 0; i != BuildVecNumElts; ++i)
10547         Opnds.push_back(DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinTy,
10548                         N0.getOperand(i)));
10549       for (unsigned i = 0; i != BuildVecNumElts; ++i)
10550         Opnds.push_back(DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinTy,
10551                         N1.getOperand(i)));
10552     }
10553
10554     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
10555   }
10556
10557   // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
10558   // nodes often generate nop CONCAT_VECTOR nodes.
10559   // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
10560   // place the incoming vectors at the exact same location.
10561   SDValue SingleSource = SDValue();
10562   unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
10563
10564   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
10565     SDValue Op = N->getOperand(i);
10566
10567     if (Op.getOpcode() == ISD::UNDEF)
10568       continue;
10569
10570     // Check if this is the identity extract:
10571     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
10572       return SDValue();
10573
10574     // Find the single incoming vector for the extract_subvector.
10575     if (SingleSource.getNode()) {
10576       if (Op.getOperand(0) != SingleSource)
10577         return SDValue();
10578     } else {
10579       SingleSource = Op.getOperand(0);
10580
10581       // Check the source type is the same as the type of the result.
10582       // If not, this concat may extend the vector, so we can not
10583       // optimize it away.
10584       if (SingleSource.getValueType() != N->getValueType(0))
10585         return SDValue();
10586     }
10587
10588     unsigned IdentityIndex = i * PartNumElem;
10589     ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
10590     // The extract index must be constant.
10591     if (!CS)
10592       return SDValue();
10593
10594     // Check that we are reading from the identity index.
10595     if (CS->getZExtValue() != IdentityIndex)
10596       return SDValue();
10597   }
10598
10599   if (SingleSource.getNode())
10600     return SingleSource;
10601
10602   return SDValue();
10603 }
10604
10605 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
10606   EVT NVT = N->getValueType(0);
10607   SDValue V = N->getOperand(0);
10608
10609   if (V->getOpcode() == ISD::CONCAT_VECTORS) {
10610     // Combine:
10611     //    (extract_subvec (concat V1, V2, ...), i)
10612     // Into:
10613     //    Vi if possible
10614     // Only operand 0 is checked as 'concat' assumes all inputs of the same
10615     // type.
10616     if (V->getOperand(0).getValueType() != NVT)
10617       return SDValue();
10618     unsigned Idx = dyn_cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
10619     unsigned NumElems = NVT.getVectorNumElements();
10620     assert((Idx % NumElems) == 0 &&
10621            "IDX in concat is not a multiple of the result vector length.");
10622     return V->getOperand(Idx / NumElems);
10623   }
10624
10625   // Skip bitcasting
10626   if (V->getOpcode() == ISD::BITCAST)
10627     V = V.getOperand(0);
10628
10629   if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
10630     SDLoc dl(N);
10631     // Handle only simple case where vector being inserted and vector
10632     // being extracted are of same type, and are half size of larger vectors.
10633     EVT BigVT = V->getOperand(0).getValueType();
10634     EVT SmallVT = V->getOperand(1).getValueType();
10635     if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
10636       return SDValue();
10637
10638     // Only handle cases where both indexes are constants with the same type.
10639     ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
10640     ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
10641
10642     if (InsIdx && ExtIdx &&
10643         InsIdx->getValueType(0).getSizeInBits() <= 64 &&
10644         ExtIdx->getValueType(0).getSizeInBits() <= 64) {
10645       // Combine:
10646       //    (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
10647       // Into:
10648       //    indices are equal or bit offsets are equal => V1
10649       //    otherwise => (extract_subvec V1, ExtIdx)
10650       if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
10651           ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
10652         return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
10653       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
10654                          DAG.getNode(ISD::BITCAST, dl,
10655                                      N->getOperand(0).getValueType(),
10656                                      V->getOperand(0)), N->getOperand(1));
10657     }
10658   }
10659
10660   return SDValue();
10661 }
10662
10663 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat.
10664 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
10665   EVT VT = N->getValueType(0);
10666   unsigned NumElts = VT.getVectorNumElements();
10667
10668   SDValue N0 = N->getOperand(0);
10669   SDValue N1 = N->getOperand(1);
10670   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10671
10672   SmallVector<SDValue, 4> Ops;
10673   EVT ConcatVT = N0.getOperand(0).getValueType();
10674   unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
10675   unsigned NumConcats = NumElts / NumElemsPerConcat;
10676
10677   // Look at every vector that's inserted. We're looking for exact
10678   // subvector-sized copies from a concatenated vector
10679   for (unsigned I = 0; I != NumConcats; ++I) {
10680     // Make sure we're dealing with a copy.
10681     unsigned Begin = I * NumElemsPerConcat;
10682     bool AllUndef = true, NoUndef = true;
10683     for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
10684       if (SVN->getMaskElt(J) >= 0)
10685         AllUndef = false;
10686       else
10687         NoUndef = false;
10688     }
10689
10690     if (NoUndef) {
10691       if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
10692         return SDValue();
10693
10694       for (unsigned J = 1; J != NumElemsPerConcat; ++J)
10695         if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
10696           return SDValue();
10697
10698       unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
10699       if (FirstElt < N0.getNumOperands())
10700         Ops.push_back(N0.getOperand(FirstElt));
10701       else
10702         Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
10703
10704     } else if (AllUndef) {
10705       Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
10706     } else { // Mixed with general masks and undefs, can't do optimization.
10707       return SDValue();
10708     }
10709   }
10710
10711   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
10712 }
10713
10714 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
10715   EVT VT = N->getValueType(0);
10716   unsigned NumElts = VT.getVectorNumElements();
10717
10718   SDValue N0 = N->getOperand(0);
10719   SDValue N1 = N->getOperand(1);
10720
10721   assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
10722
10723   // Canonicalize shuffle undef, undef -> undef
10724   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
10725     return DAG.getUNDEF(VT);
10726
10727   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10728
10729   // Canonicalize shuffle v, v -> v, undef
10730   if (N0 == N1) {
10731     SmallVector<int, 8> NewMask;
10732     for (unsigned i = 0; i != NumElts; ++i) {
10733       int Idx = SVN->getMaskElt(i);
10734       if (Idx >= (int)NumElts) Idx -= NumElts;
10735       NewMask.push_back(Idx);
10736     }
10737     return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
10738                                 &NewMask[0]);
10739   }
10740
10741   // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
10742   if (N0.getOpcode() == ISD::UNDEF) {
10743     SmallVector<int, 8> NewMask;
10744     for (unsigned i = 0; i != NumElts; ++i) {
10745       int Idx = SVN->getMaskElt(i);
10746       if (Idx >= 0) {
10747         if (Idx >= (int)NumElts)
10748           Idx -= NumElts;
10749         else
10750           Idx = -1; // remove reference to lhs
10751       }
10752       NewMask.push_back(Idx);
10753     }
10754     return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
10755                                 &NewMask[0]);
10756   }
10757
10758   // Remove references to rhs if it is undef
10759   if (N1.getOpcode() == ISD::UNDEF) {
10760     bool Changed = false;
10761     SmallVector<int, 8> NewMask;
10762     for (unsigned i = 0; i != NumElts; ++i) {
10763       int Idx = SVN->getMaskElt(i);
10764       if (Idx >= (int)NumElts) {
10765         Idx = -1;
10766         Changed = true;
10767       }
10768       NewMask.push_back(Idx);
10769     }
10770     if (Changed)
10771       return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
10772   }
10773
10774   // If it is a splat, check if the argument vector is another splat or a
10775   // build_vector with all scalar elements the same.
10776   if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
10777     SDNode *V = N0.getNode();
10778
10779     // If this is a bit convert that changes the element type of the vector but
10780     // not the number of vector elements, look through it.  Be careful not to
10781     // look though conversions that change things like v4f32 to v2f64.
10782     if (V->getOpcode() == ISD::BITCAST) {
10783       SDValue ConvInput = V->getOperand(0);
10784       if (ConvInput.getValueType().isVector() &&
10785           ConvInput.getValueType().getVectorNumElements() == NumElts)
10786         V = ConvInput.getNode();
10787     }
10788
10789     if (V->getOpcode() == ISD::BUILD_VECTOR) {
10790       assert(V->getNumOperands() == NumElts &&
10791              "BUILD_VECTOR has wrong number of operands");
10792       SDValue Base;
10793       bool AllSame = true;
10794       for (unsigned i = 0; i != NumElts; ++i) {
10795         if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
10796           Base = V->getOperand(i);
10797           break;
10798         }
10799       }
10800       // Splat of <u, u, u, u>, return <u, u, u, u>
10801       if (!Base.getNode())
10802         return N0;
10803       for (unsigned i = 0; i != NumElts; ++i) {
10804         if (V->getOperand(i) != Base) {
10805           AllSame = false;
10806           break;
10807         }
10808       }
10809       // Splat of <x, x, x, x>, return <x, x, x, x>
10810       if (AllSame)
10811         return N0;
10812     }
10813   }
10814
10815   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
10816       Level < AfterLegalizeVectorOps &&
10817       (N1.getOpcode() == ISD::UNDEF ||
10818       (N1.getOpcode() == ISD::CONCAT_VECTORS &&
10819        N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
10820     SDValue V = partitionShuffleOfConcats(N, DAG);
10821
10822     if (V.getNode())
10823       return V;
10824   }
10825
10826   // If this shuffle node is simply a swizzle of another shuffle node,
10827   // then try to simplify it.
10828   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
10829       N1.getOpcode() == ISD::UNDEF) {
10830
10831     ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
10832
10833     // The incoming shuffle must be of the same type as the result of the
10834     // current shuffle.
10835     assert(OtherSV->getOperand(0).getValueType() == VT &&
10836            "Shuffle types don't match");
10837
10838     SmallVector<int, 4> Mask;
10839     // Compute the combined shuffle mask.
10840     for (unsigned i = 0; i != NumElts; ++i) {
10841       int Idx = SVN->getMaskElt(i);
10842       assert(Idx < (int)NumElts && "Index references undef operand");
10843       // Next, this index comes from the first value, which is the incoming
10844       // shuffle. Adopt the incoming index.
10845       if (Idx >= 0)
10846         Idx = OtherSV->getMaskElt(Idx);
10847       Mask.push_back(Idx);
10848     }
10849
10850     // Check if all indices in Mask are Undef. In case, propagate Undef.
10851     bool isUndefMask = true;
10852     for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
10853       isUndefMask &= Mask[i] < 0;
10854
10855     if (isUndefMask)
10856       return DAG.getUNDEF(VT);
10857     
10858     bool CommuteOperands = false;
10859     if (N0.getOperand(1).getOpcode() != ISD::UNDEF) {
10860       // To be valid, the combine shuffle mask should only reference elements
10861       // from one of the two vectors in input to the inner shufflevector.
10862       bool IsValidMask = true;
10863       for (unsigned i = 0; i != NumElts && IsValidMask; ++i)
10864         // See if the combined mask only reference undefs or elements coming
10865         // from the first shufflevector operand.
10866         IsValidMask = Mask[i] < 0 || (unsigned)Mask[i] < NumElts;
10867
10868       if (!IsValidMask) {
10869         IsValidMask = true;
10870         for (unsigned i = 0; i != NumElts && IsValidMask; ++i)
10871           // Check that all the elements come from the second shuffle operand.
10872           IsValidMask = Mask[i] < 0 || (unsigned)Mask[i] >= NumElts;
10873         CommuteOperands = IsValidMask;
10874       }
10875
10876       // Early exit if the combined shuffle mask is not valid.
10877       if (!IsValidMask)
10878         return SDValue();
10879     }
10880
10881     // See if this pair of shuffles can be safely folded according to either
10882     // of the following rules:
10883     //   shuffle(shuffle(x, y), undef) -> x
10884     //   shuffle(shuffle(x, undef), undef) -> x
10885     //   shuffle(shuffle(x, y), undef) -> y
10886     bool IsIdentityMask = true;
10887     unsigned BaseMaskIndex = CommuteOperands ? NumElts : 0;
10888     for (unsigned i = 0; i != NumElts && IsIdentityMask; ++i) {
10889       // Skip Undefs.
10890       if (Mask[i] < 0)
10891         continue;
10892
10893       // The combined shuffle must map each index to itself.
10894       IsIdentityMask = (unsigned)Mask[i] == i + BaseMaskIndex;
10895     }
10896     
10897     if (IsIdentityMask) {
10898       if (CommuteOperands)
10899         // optimize shuffle(shuffle(x, y), undef) -> y.
10900         return OtherSV->getOperand(1);
10901       
10902       // optimize shuffle(shuffle(x, undef), undef) -> x
10903       // optimize shuffle(shuffle(x, y), undef) -> x
10904       return OtherSV->getOperand(0);
10905     }
10906
10907     // It may still be beneficial to combine the two shuffles if the
10908     // resulting shuffle is legal.
10909     if (TLI.isTypeLegal(VT)) {
10910       if (!CommuteOperands) {
10911         if (TLI.isShuffleMaskLegal(Mask, VT))
10912           // shuffle(shuffle(x, undef, M1), undef, M2) -> shuffle(x, undef, M3).
10913           // shuffle(shuffle(x, y, M1), undef, M2) -> shuffle(x, undef, M3)
10914           return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0), N1,
10915                                       &Mask[0]);
10916       } else {
10917         // Compute the commuted shuffle mask.
10918         for (unsigned i = 0; i != NumElts; ++i) {
10919           int idx = Mask[i];
10920           if (idx < 0)
10921             continue;
10922           else if (idx < (int)NumElts)
10923             Mask[i] = idx + NumElts;
10924           else
10925             Mask[i] = idx - NumElts;
10926         }
10927
10928         if (TLI.isShuffleMaskLegal(Mask, VT))
10929           //   shuffle(shuffle(x, y, M1), undef, M2) -> shuffle(y, undef, M3)
10930           return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(1), N1,
10931                                       &Mask[0]);
10932       }
10933     }
10934   }
10935
10936   // Canonicalize shuffles according to rules:
10937   //  shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
10938   //  shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
10939   //  shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
10940   if (N1.getOpcode() == ISD::VECTOR_SHUFFLE && N0.getOpcode() != ISD::UNDEF &&
10941       N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
10942       TLI.isTypeLegal(VT)) {
10943     // The incoming shuffle must be of the same type as the result of the
10944     // current shuffle.
10945     assert(N1->getOperand(0).getValueType() == VT &&
10946            "Shuffle types don't match");
10947
10948     SDValue SV0 = N1->getOperand(0);
10949     SDValue SV1 = N1->getOperand(1);
10950     bool HasSameOp0 = N0 == SV0;
10951     bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
10952     if (HasSameOp0 || IsSV1Undef || N0 == SV1)
10953       // Commute the operands of this shuffle so that next rule
10954       // will trigger.
10955       return DAG.getCommutedVectorShuffle(*SVN);
10956   }
10957
10958   // Try to fold according to rules:
10959   //   shuffle(shuffle(A, B, M0), B, M1) -> shuffle(A, B, M2)
10960   //   shuffle(shuffle(A, B, M0), A, M1) -> shuffle(A, B, M2)
10961   //   shuffle(shuffle(A, Undef, M0), B, M1) -> shuffle(A, B, M2)
10962   //   shuffle(shuffle(A, Undef, M0), A, M1) -> shuffle(A, Undef, M2)
10963   // Don't try to fold shuffles with illegal type.
10964   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
10965       N1.getOpcode() != ISD::UNDEF && TLI.isTypeLegal(VT)) {
10966     ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
10967
10968     // The incoming shuffle must be of the same type as the result of the
10969     // current shuffle.
10970     assert(OtherSV->getOperand(0).getValueType() == VT &&
10971            "Shuffle types don't match");
10972
10973     SDValue SV0 = OtherSV->getOperand(0);
10974     SDValue SV1 = OtherSV->getOperand(1);
10975     bool HasSameOp0 = N1 == SV0;
10976     bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
10977     if (!HasSameOp0 && !IsSV1Undef && N1 != SV1)
10978       // Early exit.
10979       return SDValue();
10980
10981     SmallVector<int, 4> Mask;
10982     // Compute the combined shuffle mask for a shuffle with SV0 as the first
10983     // operand, and SV1 as the second operand.
10984     for (unsigned i = 0; i != NumElts; ++i) {
10985       int Idx = SVN->getMaskElt(i);
10986       if (Idx < 0) {
10987         // Propagate Undef.
10988         Mask.push_back(Idx);
10989         continue;
10990       }
10991
10992       if (Idx < (int)NumElts) {
10993         Idx = OtherSV->getMaskElt(Idx);
10994         if (IsSV1Undef && Idx >= (int) NumElts)
10995           Idx = -1;  // Propagate Undef.
10996       } else
10997         Idx = HasSameOp0 ? Idx - NumElts : Idx;
10998
10999       Mask.push_back(Idx);
11000     }
11001
11002     // Check if all indices in Mask are Undef. In case, propagate Undef.
11003     bool isUndefMask = true;
11004     for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
11005       isUndefMask &= Mask[i] < 0;
11006
11007     if (isUndefMask)
11008       return DAG.getUNDEF(VT);
11009
11010     // Avoid introducing shuffles with illegal mask.
11011     if (TLI.isShuffleMaskLegal(Mask, VT)) {
11012       if (IsSV1Undef)
11013         //   shuffle(shuffle(A, Undef, M0), B, M1) -> shuffle(A, B, M2)
11014         //   shuffle(shuffle(A, Undef, M0), A, M1) -> shuffle(A, Undef, M2)
11015         return DAG.getVectorShuffle(VT, SDLoc(N), SV0, N1, &Mask[0]);
11016       return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, &Mask[0]);
11017     }
11018   }
11019
11020   return SDValue();
11021 }
11022
11023 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
11024   SDValue N0 = N->getOperand(0);
11025   SDValue N2 = N->getOperand(2);
11026
11027   // If the input vector is a concatenation, and the insert replaces
11028   // one of the halves, we can optimize into a single concat_vectors.
11029   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
11030       N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
11031     APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
11032     EVT VT = N->getValueType(0);
11033
11034     // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
11035     // (concat_vectors Z, Y)
11036     if (InsIdx == 0)
11037       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
11038                          N->getOperand(1), N0.getOperand(1));
11039
11040     // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
11041     // (concat_vectors X, Z)
11042     if (InsIdx == VT.getVectorNumElements()/2)
11043       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
11044                          N0.getOperand(0), N->getOperand(1));
11045   }
11046
11047   return SDValue();
11048 }
11049
11050 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle
11051 /// with the destination vector and a zero vector.
11052 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
11053 ///      vector_shuffle V, Zero, <0, 4, 2, 4>
11054 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
11055   EVT VT = N->getValueType(0);
11056   SDLoc dl(N);
11057   SDValue LHS = N->getOperand(0);
11058   SDValue RHS = N->getOperand(1);
11059   if (N->getOpcode() == ISD::AND) {
11060     if (RHS.getOpcode() == ISD::BITCAST)
11061       RHS = RHS.getOperand(0);
11062     if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
11063       SmallVector<int, 8> Indices;
11064       unsigned NumElts = RHS.getNumOperands();
11065       for (unsigned i = 0; i != NumElts; ++i) {
11066         SDValue Elt = RHS.getOperand(i);
11067         if (!isa<ConstantSDNode>(Elt))
11068           return SDValue();
11069
11070         if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
11071           Indices.push_back(i);
11072         else if (cast<ConstantSDNode>(Elt)->isNullValue())
11073           Indices.push_back(NumElts);
11074         else
11075           return SDValue();
11076       }
11077
11078       // Let's see if the target supports this vector_shuffle.
11079       EVT RVT = RHS.getValueType();
11080       if (!TLI.isVectorClearMaskLegal(Indices, RVT))
11081         return SDValue();
11082
11083       // Return the new VECTOR_SHUFFLE node.
11084       EVT EltVT = RVT.getVectorElementType();
11085       SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
11086                                      DAG.getConstant(0, EltVT));
11087       SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), RVT, ZeroOps);
11088       LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
11089       SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
11090       return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
11091     }
11092   }
11093
11094   return SDValue();
11095 }
11096
11097 /// Visit a binary vector operation, like ADD.
11098 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
11099   assert(N->getValueType(0).isVector() &&
11100          "SimplifyVBinOp only works on vectors!");
11101
11102   SDValue LHS = N->getOperand(0);
11103   SDValue RHS = N->getOperand(1);
11104   SDValue Shuffle = XformToShuffleWithZero(N);
11105   if (Shuffle.getNode()) return Shuffle;
11106
11107   // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
11108   // this operation.
11109   if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
11110       RHS.getOpcode() == ISD::BUILD_VECTOR) {
11111     // Check if both vectors are constants. If not bail out.
11112     if (!(cast<BuildVectorSDNode>(LHS)->isConstant() &&
11113           cast<BuildVectorSDNode>(RHS)->isConstant()))
11114       return SDValue();
11115
11116     SmallVector<SDValue, 8> Ops;
11117     for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
11118       SDValue LHSOp = LHS.getOperand(i);
11119       SDValue RHSOp = RHS.getOperand(i);
11120
11121       // Can't fold divide by zero.
11122       if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
11123           N->getOpcode() == ISD::FDIV) {
11124         if ((RHSOp.getOpcode() == ISD::Constant &&
11125              cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
11126             (RHSOp.getOpcode() == ISD::ConstantFP &&
11127              cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
11128           break;
11129       }
11130
11131       EVT VT = LHSOp.getValueType();
11132       EVT RVT = RHSOp.getValueType();
11133       if (RVT != VT) {
11134         // Integer BUILD_VECTOR operands may have types larger than the element
11135         // size (e.g., when the element type is not legal).  Prior to type
11136         // legalization, the types may not match between the two BUILD_VECTORS.
11137         // Truncate one of the operands to make them match.
11138         if (RVT.getSizeInBits() > VT.getSizeInBits()) {
11139           RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
11140         } else {
11141           LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
11142           VT = RVT;
11143         }
11144       }
11145       SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
11146                                    LHSOp, RHSOp);
11147       if (FoldOp.getOpcode() != ISD::UNDEF &&
11148           FoldOp.getOpcode() != ISD::Constant &&
11149           FoldOp.getOpcode() != ISD::ConstantFP)
11150         break;
11151       Ops.push_back(FoldOp);
11152       AddToWorklist(FoldOp.getNode());
11153     }
11154
11155     if (Ops.size() == LHS.getNumOperands())
11156       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), LHS.getValueType(), Ops);
11157   }
11158
11159   // Type legalization might introduce new shuffles in the DAG.
11160   // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
11161   //   -> (shuffle (VBinOp (A, B)), Undef, Mask).
11162   if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
11163       isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
11164       LHS.getOperand(1).getOpcode() == ISD::UNDEF &&
11165       RHS.getOperand(1).getOpcode() == ISD::UNDEF) {
11166     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
11167     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
11168
11169     if (SVN0->getMask().equals(SVN1->getMask())) {
11170       EVT VT = N->getValueType(0);
11171       SDValue UndefVector = LHS.getOperand(1);
11172       SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
11173                                      LHS.getOperand(0), RHS.getOperand(0));
11174       AddUsersToWorklist(N);
11175       return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
11176                                   &SVN0->getMask()[0]);
11177     }
11178   }
11179
11180   return SDValue();
11181 }
11182
11183 /// Visit a binary vector operation, like FABS/FNEG.
11184 SDValue DAGCombiner::SimplifyVUnaryOp(SDNode *N) {
11185   assert(N->getValueType(0).isVector() &&
11186          "SimplifyVUnaryOp only works on vectors!");
11187
11188   SDValue N0 = N->getOperand(0);
11189
11190   if (N0.getOpcode() != ISD::BUILD_VECTOR)
11191     return SDValue();
11192
11193   // Operand is a BUILD_VECTOR node, see if we can constant fold it.
11194   SmallVector<SDValue, 8> Ops;
11195   for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
11196     SDValue Op = N0.getOperand(i);
11197     if (Op.getOpcode() != ISD::UNDEF &&
11198         Op.getOpcode() != ISD::ConstantFP)
11199       break;
11200     EVT EltVT = Op.getValueType();
11201     SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(N0), EltVT, Op);
11202     if (FoldOp.getOpcode() != ISD::UNDEF &&
11203         FoldOp.getOpcode() != ISD::ConstantFP)
11204       break;
11205     Ops.push_back(FoldOp);
11206     AddToWorklist(FoldOp.getNode());
11207   }
11208
11209   if (Ops.size() != N0.getNumOperands())
11210     return SDValue();
11211
11212   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), N0.getValueType(), Ops);
11213 }
11214
11215 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
11216                                     SDValue N1, SDValue N2){
11217   assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
11218
11219   SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
11220                                  cast<CondCodeSDNode>(N0.getOperand(2))->get());
11221
11222   // If we got a simplified select_cc node back from SimplifySelectCC, then
11223   // break it down into a new SETCC node, and a new SELECT node, and then return
11224   // the SELECT node, since we were called with a SELECT node.
11225   if (SCC.getNode()) {
11226     // Check to see if we got a select_cc back (to turn into setcc/select).
11227     // Otherwise, just return whatever node we got back, like fabs.
11228     if (SCC.getOpcode() == ISD::SELECT_CC) {
11229       SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
11230                                   N0.getValueType(),
11231                                   SCC.getOperand(0), SCC.getOperand(1),
11232                                   SCC.getOperand(4));
11233       AddToWorklist(SETCC.getNode());
11234       return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC,
11235                            SCC.getOperand(2), SCC.getOperand(3));
11236     }
11237
11238     return SCC;
11239   }
11240   return SDValue();
11241 }
11242
11243 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values
11244 /// being selected between, see if we can simplify the select.  Callers of this
11245 /// should assume that TheSelect is deleted if this returns true.  As such, they
11246 /// should return the appropriate thing (e.g. the node) back to the top-level of
11247 /// the DAG combiner loop to avoid it being looked at.
11248 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
11249                                     SDValue RHS) {
11250
11251   // Cannot simplify select with vector condition
11252   if (TheSelect->getOperand(0).getValueType().isVector()) return false;
11253
11254   // If this is a select from two identical things, try to pull the operation
11255   // through the select.
11256   if (LHS.getOpcode() != RHS.getOpcode() ||
11257       !LHS.hasOneUse() || !RHS.hasOneUse())
11258     return false;
11259
11260   // If this is a load and the token chain is identical, replace the select
11261   // of two loads with a load through a select of the address to load from.
11262   // This triggers in things like "select bool X, 10.0, 123.0" after the FP
11263   // constants have been dropped into the constant pool.
11264   if (LHS.getOpcode() == ISD::LOAD) {
11265     LoadSDNode *LLD = cast<LoadSDNode>(LHS);
11266     LoadSDNode *RLD = cast<LoadSDNode>(RHS);
11267
11268     // Token chains must be identical.
11269     if (LHS.getOperand(0) != RHS.getOperand(0) ||
11270         // Do not let this transformation reduce the number of volatile loads.
11271         LLD->isVolatile() || RLD->isVolatile() ||
11272         // If this is an EXTLOAD, the VT's must match.
11273         LLD->getMemoryVT() != RLD->getMemoryVT() ||
11274         // If this is an EXTLOAD, the kind of extension must match.
11275         (LLD->getExtensionType() != RLD->getExtensionType() &&
11276          // The only exception is if one of the extensions is anyext.
11277          LLD->getExtensionType() != ISD::EXTLOAD &&
11278          RLD->getExtensionType() != ISD::EXTLOAD) ||
11279         // FIXME: this discards src value information.  This is
11280         // over-conservative. It would be beneficial to be able to remember
11281         // both potential memory locations.  Since we are discarding
11282         // src value info, don't do the transformation if the memory
11283         // locations are not in the default address space.
11284         LLD->getPointerInfo().getAddrSpace() != 0 ||
11285         RLD->getPointerInfo().getAddrSpace() != 0 ||
11286         !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
11287                                       LLD->getBasePtr().getValueType()))
11288       return false;
11289
11290     // Check that the select condition doesn't reach either load.  If so,
11291     // folding this will induce a cycle into the DAG.  If not, this is safe to
11292     // xform, so create a select of the addresses.
11293     SDValue Addr;
11294     if (TheSelect->getOpcode() == ISD::SELECT) {
11295       SDNode *CondNode = TheSelect->getOperand(0).getNode();
11296       if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
11297           (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
11298         return false;
11299       // The loads must not depend on one another.
11300       if (LLD->isPredecessorOf(RLD) ||
11301           RLD->isPredecessorOf(LLD))
11302         return false;
11303       Addr = DAG.getSelect(SDLoc(TheSelect),
11304                            LLD->getBasePtr().getValueType(),
11305                            TheSelect->getOperand(0), LLD->getBasePtr(),
11306                            RLD->getBasePtr());
11307     } else {  // Otherwise SELECT_CC
11308       SDNode *CondLHS = TheSelect->getOperand(0).getNode();
11309       SDNode *CondRHS = TheSelect->getOperand(1).getNode();
11310
11311       if ((LLD->hasAnyUseOfValue(1) &&
11312            (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
11313           (RLD->hasAnyUseOfValue(1) &&
11314            (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
11315         return false;
11316
11317       Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
11318                          LLD->getBasePtr().getValueType(),
11319                          TheSelect->getOperand(0),
11320                          TheSelect->getOperand(1),
11321                          LLD->getBasePtr(), RLD->getBasePtr(),
11322                          TheSelect->getOperand(4));
11323     }
11324
11325     SDValue Load;
11326     // It is safe to replace the two loads if they have different alignments,
11327     // but the new load must be the minimum (most restrictive) alignment of the
11328     // inputs.
11329     bool isInvariant = LLD->getAlignment() & RLD->getAlignment();
11330     unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment());
11331     if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
11332       Load = DAG.getLoad(TheSelect->getValueType(0),
11333                          SDLoc(TheSelect),
11334                          // FIXME: Discards pointer and AA info.
11335                          LLD->getChain(), Addr, MachinePointerInfo(),
11336                          LLD->isVolatile(), LLD->isNonTemporal(),
11337                          isInvariant, Alignment);
11338     } else {
11339       Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
11340                             RLD->getExtensionType() : LLD->getExtensionType(),
11341                             SDLoc(TheSelect),
11342                             TheSelect->getValueType(0),
11343                             // FIXME: Discards pointer and AA info.
11344                             LLD->getChain(), Addr, MachinePointerInfo(),
11345                             LLD->getMemoryVT(), LLD->isVolatile(),
11346                             LLD->isNonTemporal(), isInvariant, Alignment);
11347     }
11348
11349     // Users of the select now use the result of the load.
11350     CombineTo(TheSelect, Load);
11351
11352     // Users of the old loads now use the new load's chain.  We know the
11353     // old-load value is dead now.
11354     CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
11355     CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
11356     return true;
11357   }
11358
11359   return false;
11360 }
11361
11362 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3
11363 /// where 'cond' is the comparison specified by CC.
11364 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
11365                                       SDValue N2, SDValue N3,
11366                                       ISD::CondCode CC, bool NotExtCompare) {
11367   // (x ? y : y) -> y.
11368   if (N2 == N3) return N2;
11369
11370   EVT VT = N2.getValueType();
11371   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
11372   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
11373   ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
11374
11375   // Determine if the condition we're dealing with is constant
11376   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
11377                               N0, N1, CC, DL, false);
11378   if (SCC.getNode()) AddToWorklist(SCC.getNode());
11379   ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
11380
11381   // fold select_cc true, x, y -> x
11382   if (SCCC && !SCCC->isNullValue())
11383     return N2;
11384   // fold select_cc false, x, y -> y
11385   if (SCCC && SCCC->isNullValue())
11386     return N3;
11387
11388   // Check to see if we can simplify the select into an fabs node
11389   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
11390     // Allow either -0.0 or 0.0
11391     if (CFP->getValueAPF().isZero()) {
11392       // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
11393       if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
11394           N0 == N2 && N3.getOpcode() == ISD::FNEG &&
11395           N2 == N3.getOperand(0))
11396         return DAG.getNode(ISD::FABS, DL, VT, N0);
11397
11398       // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
11399       if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
11400           N0 == N3 && N2.getOpcode() == ISD::FNEG &&
11401           N2.getOperand(0) == N3)
11402         return DAG.getNode(ISD::FABS, DL, VT, N3);
11403     }
11404   }
11405
11406   // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
11407   // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
11408   // in it.  This is a win when the constant is not otherwise available because
11409   // it replaces two constant pool loads with one.  We only do this if the FP
11410   // type is known to be legal, because if it isn't, then we are before legalize
11411   // types an we want the other legalization to happen first (e.g. to avoid
11412   // messing with soft float) and if the ConstantFP is not legal, because if
11413   // it is legal, we may not need to store the FP constant in a constant pool.
11414   if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
11415     if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
11416       if (TLI.isTypeLegal(N2.getValueType()) &&
11417           (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
11418                TargetLowering::Legal &&
11419            !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
11420            !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
11421           // If both constants have multiple uses, then we won't need to do an
11422           // extra load, they are likely around in registers for other users.
11423           (TV->hasOneUse() || FV->hasOneUse())) {
11424         Constant *Elts[] = {
11425           const_cast<ConstantFP*>(FV->getConstantFPValue()),
11426           const_cast<ConstantFP*>(TV->getConstantFPValue())
11427         };
11428         Type *FPTy = Elts[0]->getType();
11429         const DataLayout &TD = *TLI.getDataLayout();
11430
11431         // Create a ConstantArray of the two constants.
11432         Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
11433         SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
11434                                             TD.getPrefTypeAlignment(FPTy));
11435         unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
11436
11437         // Get the offsets to the 0 and 1 element of the array so that we can
11438         // select between them.
11439         SDValue Zero = DAG.getIntPtrConstant(0);
11440         unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
11441         SDValue One = DAG.getIntPtrConstant(EltSize);
11442
11443         SDValue Cond = DAG.getSetCC(DL,
11444                                     getSetCCResultType(N0.getValueType()),
11445                                     N0, N1, CC);
11446         AddToWorklist(Cond.getNode());
11447         SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
11448                                           Cond, One, Zero);
11449         AddToWorklist(CstOffset.getNode());
11450         CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
11451                             CstOffset);
11452         AddToWorklist(CPIdx.getNode());
11453         return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
11454                            MachinePointerInfo::getConstantPool(), false,
11455                            false, false, Alignment);
11456
11457       }
11458     }
11459
11460   // Check to see if we can perform the "gzip trick", transforming
11461   // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
11462   if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
11463       (N1C->isNullValue() ||                         // (a < 0) ? b : 0
11464        (N1C->getAPIntValue() == 1 && N0 == N2))) {   // (a < 1) ? a : 0
11465     EVT XType = N0.getValueType();
11466     EVT AType = N2.getValueType();
11467     if (XType.bitsGE(AType)) {
11468       // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
11469       // single-bit constant.
11470       if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
11471         unsigned ShCtV = N2C->getAPIntValue().logBase2();
11472         ShCtV = XType.getSizeInBits()-ShCtV-1;
11473         SDValue ShCt = DAG.getConstant(ShCtV,
11474                                        getShiftAmountTy(N0.getValueType()));
11475         SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
11476                                     XType, N0, ShCt);
11477         AddToWorklist(Shift.getNode());
11478
11479         if (XType.bitsGT(AType)) {
11480           Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
11481           AddToWorklist(Shift.getNode());
11482         }
11483
11484         return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
11485       }
11486
11487       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
11488                                   XType, N0,
11489                                   DAG.getConstant(XType.getSizeInBits()-1,
11490                                          getShiftAmountTy(N0.getValueType())));
11491       AddToWorklist(Shift.getNode());
11492
11493       if (XType.bitsGT(AType)) {
11494         Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
11495         AddToWorklist(Shift.getNode());
11496       }
11497
11498       return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
11499     }
11500   }
11501
11502   // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
11503   // where y is has a single bit set.
11504   // A plaintext description would be, we can turn the SELECT_CC into an AND
11505   // when the condition can be materialized as an all-ones register.  Any
11506   // single bit-test can be materialized as an all-ones register with
11507   // shift-left and shift-right-arith.
11508   if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
11509       N0->getValueType(0) == VT &&
11510       N1C && N1C->isNullValue() &&
11511       N2C && N2C->isNullValue()) {
11512     SDValue AndLHS = N0->getOperand(0);
11513     ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
11514     if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
11515       // Shift the tested bit over the sign bit.
11516       APInt AndMask = ConstAndRHS->getAPIntValue();
11517       SDValue ShlAmt =
11518         DAG.getConstant(AndMask.countLeadingZeros(),
11519                         getShiftAmountTy(AndLHS.getValueType()));
11520       SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
11521
11522       // Now arithmetic right shift it all the way over, so the result is either
11523       // all-ones, or zero.
11524       SDValue ShrAmt =
11525         DAG.getConstant(AndMask.getBitWidth()-1,
11526                         getShiftAmountTy(Shl.getValueType()));
11527       SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
11528
11529       return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
11530     }
11531   }
11532
11533   // fold select C, 16, 0 -> shl C, 4
11534   if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
11535       TLI.getBooleanContents(N0.getValueType()) ==
11536           TargetLowering::ZeroOrOneBooleanContent) {
11537
11538     // If the caller doesn't want us to simplify this into a zext of a compare,
11539     // don't do it.
11540     if (NotExtCompare && N2C->getAPIntValue() == 1)
11541       return SDValue();
11542
11543     // Get a SetCC of the condition
11544     // NOTE: Don't create a SETCC if it's not legal on this target.
11545     if (!LegalOperations ||
11546         TLI.isOperationLegal(ISD::SETCC,
11547           LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
11548       SDValue Temp, SCC;
11549       // cast from setcc result type to select result type
11550       if (LegalTypes) {
11551         SCC  = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
11552                             N0, N1, CC);
11553         if (N2.getValueType().bitsLT(SCC.getValueType()))
11554           Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
11555                                         N2.getValueType());
11556         else
11557           Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
11558                              N2.getValueType(), SCC);
11559       } else {
11560         SCC  = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
11561         Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
11562                            N2.getValueType(), SCC);
11563       }
11564
11565       AddToWorklist(SCC.getNode());
11566       AddToWorklist(Temp.getNode());
11567
11568       if (N2C->getAPIntValue() == 1)
11569         return Temp;
11570
11571       // shl setcc result by log2 n2c
11572       return DAG.getNode(
11573           ISD::SHL, DL, N2.getValueType(), Temp,
11574           DAG.getConstant(N2C->getAPIntValue().logBase2(),
11575                           getShiftAmountTy(Temp.getValueType())));
11576     }
11577   }
11578
11579   // Check to see if this is the equivalent of setcc
11580   // FIXME: Turn all of these into setcc if setcc if setcc is legal
11581   // otherwise, go ahead with the folds.
11582   if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
11583     EVT XType = N0.getValueType();
11584     if (!LegalOperations ||
11585         TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
11586       SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
11587       if (Res.getValueType() != VT)
11588         Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
11589       return Res;
11590     }
11591
11592     // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
11593     if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
11594         (!LegalOperations ||
11595          TLI.isOperationLegal(ISD::CTLZ, XType))) {
11596       SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
11597       return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
11598                          DAG.getConstant(Log2_32(XType.getSizeInBits()),
11599                                        getShiftAmountTy(Ctlz.getValueType())));
11600     }
11601     // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
11602     if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
11603       SDValue NegN0 = DAG.getNode(ISD::SUB, SDLoc(N0),
11604                                   XType, DAG.getConstant(0, XType), N0);
11605       SDValue NotN0 = DAG.getNOT(SDLoc(N0), N0, XType);
11606       return DAG.getNode(ISD::SRL, DL, XType,
11607                          DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
11608                          DAG.getConstant(XType.getSizeInBits()-1,
11609                                          getShiftAmountTy(XType)));
11610     }
11611     // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
11612     if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
11613       SDValue Sign = DAG.getNode(ISD::SRL, SDLoc(N0), XType, N0,
11614                                  DAG.getConstant(XType.getSizeInBits()-1,
11615                                          getShiftAmountTy(N0.getValueType())));
11616       return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
11617     }
11618   }
11619
11620   // Check to see if this is an integer abs.
11621   // select_cc setg[te] X,  0,  X, -X ->
11622   // select_cc setgt    X, -1,  X, -X ->
11623   // select_cc setl[te] X,  0, -X,  X ->
11624   // select_cc setlt    X,  1, -X,  X ->
11625   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
11626   if (N1C) {
11627     ConstantSDNode *SubC = nullptr;
11628     if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
11629          (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
11630         N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
11631       SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
11632     else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
11633               (N1C->isOne() && CC == ISD::SETLT)) &&
11634              N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
11635       SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
11636
11637     EVT XType = N0.getValueType();
11638     if (SubC && SubC->isNullValue() && XType.isInteger()) {
11639       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), XType,
11640                                   N0,
11641                                   DAG.getConstant(XType.getSizeInBits()-1,
11642                                          getShiftAmountTy(N0.getValueType())));
11643       SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0),
11644                                 XType, N0, Shift);
11645       AddToWorklist(Shift.getNode());
11646       AddToWorklist(Add.getNode());
11647       return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
11648     }
11649   }
11650
11651   return SDValue();
11652 }
11653
11654 /// This is a stub for TargetLowering::SimplifySetCC.
11655 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
11656                                    SDValue N1, ISD::CondCode Cond,
11657                                    SDLoc DL, bool foldBooleans) {
11658   TargetLowering::DAGCombinerInfo
11659     DagCombineInfo(DAG, Level, false, this);
11660   return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
11661 }
11662
11663 /// Given an ISD::SDIV node expressing a divide by constant, return
11664 /// a DAG expression to select that will generate the same value by multiplying
11665 /// by a magic number.  See:
11666 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
11667 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
11668   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
11669   if (!C)
11670     return SDValue();
11671
11672   // Avoid division by zero.
11673   if (!C->getAPIntValue())
11674     return SDValue();
11675
11676   std::vector<SDNode*> Built;
11677   SDValue S =
11678       TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
11679
11680   for (SDNode *N : Built)
11681     AddToWorklist(N);
11682   return S;
11683 }
11684
11685 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a
11686 /// DAG expression that will generate the same value by right shifting.
11687 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
11688   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
11689   if (!C)
11690     return SDValue();
11691
11692   // Avoid division by zero.
11693   if (!C->getAPIntValue())
11694     return SDValue();
11695
11696   std::vector<SDNode *> Built;
11697   SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
11698
11699   for (SDNode *N : Built)
11700     AddToWorklist(N);
11701   return S;
11702 }
11703
11704 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG
11705 /// expression that will generate the same value by multiplying by a magic
11706 /// number. See:
11707 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
11708 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
11709   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
11710   if (!C)
11711     return SDValue();
11712
11713   // Avoid division by zero.
11714   if (!C->getAPIntValue())
11715     return SDValue();
11716
11717   std::vector<SDNode*> Built;
11718   SDValue S =
11719       TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
11720
11721   for (SDNode *N : Built)
11722     AddToWorklist(N);
11723   return S;
11724 }
11725
11726 /// Return true if base is a frame index, which is known not to alias with
11727 /// anything but itself.  Provides base object and offset as results.
11728 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
11729                            const GlobalValue *&GV, const void *&CV) {
11730   // Assume it is a primitive operation.
11731   Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
11732
11733   // If it's an adding a simple constant then integrate the offset.
11734   if (Base.getOpcode() == ISD::ADD) {
11735     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
11736       Base = Base.getOperand(0);
11737       Offset += C->getZExtValue();
11738     }
11739   }
11740
11741   // Return the underlying GlobalValue, and update the Offset.  Return false
11742   // for GlobalAddressSDNode since the same GlobalAddress may be represented
11743   // by multiple nodes with different offsets.
11744   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
11745     GV = G->getGlobal();
11746     Offset += G->getOffset();
11747     return false;
11748   }
11749
11750   // Return the underlying Constant value, and update the Offset.  Return false
11751   // for ConstantSDNodes since the same constant pool entry may be represented
11752   // by multiple nodes with different offsets.
11753   if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
11754     CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
11755                                          : (const void *)C->getConstVal();
11756     Offset += C->getOffset();
11757     return false;
11758   }
11759   // If it's any of the following then it can't alias with anything but itself.
11760   return isa<FrameIndexSDNode>(Base);
11761 }
11762
11763 /// Return true if there is any possibility that the two addresses overlap.
11764 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
11765   // If they are the same then they must be aliases.
11766   if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
11767
11768   // If they are both volatile then they cannot be reordered.
11769   if (Op0->isVolatile() && Op1->isVolatile()) return true;
11770
11771   // Gather base node and offset information.
11772   SDValue Base1, Base2;
11773   int64_t Offset1, Offset2;
11774   const GlobalValue *GV1, *GV2;
11775   const void *CV1, *CV2;
11776   bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
11777                                       Base1, Offset1, GV1, CV1);
11778   bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
11779                                       Base2, Offset2, GV2, CV2);
11780
11781   // If they have a same base address then check to see if they overlap.
11782   if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
11783     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
11784              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
11785
11786   // It is possible for different frame indices to alias each other, mostly
11787   // when tail call optimization reuses return address slots for arguments.
11788   // To catch this case, look up the actual index of frame indices to compute
11789   // the real alias relationship.
11790   if (isFrameIndex1 && isFrameIndex2) {
11791     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11792     Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
11793     Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
11794     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
11795              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
11796   }
11797
11798   // Otherwise, if we know what the bases are, and they aren't identical, then
11799   // we know they cannot alias.
11800   if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
11801     return false;
11802
11803   // If we know required SrcValue1 and SrcValue2 have relatively large alignment
11804   // compared to the size and offset of the access, we may be able to prove they
11805   // do not alias.  This check is conservative for now to catch cases created by
11806   // splitting vector types.
11807   if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
11808       (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
11809       (Op0->getMemoryVT().getSizeInBits() >> 3 ==
11810        Op1->getMemoryVT().getSizeInBits() >> 3) &&
11811       (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) {
11812     int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
11813     int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
11814
11815     // There is no overlap between these relatively aligned accesses of similar
11816     // size, return no alias.
11817     if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
11818         (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
11819       return false;
11820   }
11821
11822   bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0 ? CombinerGlobalAA :
11823     TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
11824 #ifndef NDEBUG
11825   if (CombinerAAOnlyFunc.getNumOccurrences() &&
11826       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
11827     UseAA = false;
11828 #endif
11829   if (UseAA &&
11830       Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
11831     // Use alias analysis information.
11832     int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
11833                                  Op1->getSrcValueOffset());
11834     int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
11835         Op0->getSrcValueOffset() - MinOffset;
11836     int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
11837         Op1->getSrcValueOffset() - MinOffset;
11838     AliasAnalysis::AliasResult AAResult =
11839         AA.alias(AliasAnalysis::Location(Op0->getMemOperand()->getValue(),
11840                                          Overlap1,
11841                                          UseTBAA ? Op0->getAAInfo() : AAMDNodes()),
11842                  AliasAnalysis::Location(Op1->getMemOperand()->getValue(),
11843                                          Overlap2,
11844                                          UseTBAA ? Op1->getAAInfo() : AAMDNodes()));
11845     if (AAResult == AliasAnalysis::NoAlias)
11846       return false;
11847   }
11848
11849   // Otherwise we have to assume they alias.
11850   return true;
11851 }
11852
11853 /// Walk up chain skipping non-aliasing memory nodes,
11854 /// looking for aliasing nodes and adding them to the Aliases vector.
11855 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
11856                                    SmallVectorImpl<SDValue> &Aliases) {
11857   SmallVector<SDValue, 8> Chains;     // List of chains to visit.
11858   SmallPtrSet<SDNode *, 16> Visited;  // Visited node set.
11859
11860   // Get alias information for node.
11861   bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
11862
11863   // Starting off.
11864   Chains.push_back(OriginalChain);
11865   unsigned Depth = 0;
11866
11867   // Look at each chain and determine if it is an alias.  If so, add it to the
11868   // aliases list.  If not, then continue up the chain looking for the next
11869   // candidate.
11870   while (!Chains.empty()) {
11871     SDValue Chain = Chains.back();
11872     Chains.pop_back();
11873
11874     // For TokenFactor nodes, look at each operand and only continue up the
11875     // chain until we find two aliases.  If we've seen two aliases, assume we'll
11876     // find more and revert to original chain since the xform is unlikely to be
11877     // profitable.
11878     //
11879     // FIXME: The depth check could be made to return the last non-aliasing
11880     // chain we found before we hit a tokenfactor rather than the original
11881     // chain.
11882     if (Depth > 6 || Aliases.size() == 2) {
11883       Aliases.clear();
11884       Aliases.push_back(OriginalChain);
11885       return;
11886     }
11887
11888     // Don't bother if we've been before.
11889     if (!Visited.insert(Chain.getNode()))
11890       continue;
11891
11892     switch (Chain.getOpcode()) {
11893     case ISD::EntryToken:
11894       // Entry token is ideal chain operand, but handled in FindBetterChain.
11895       break;
11896
11897     case ISD::LOAD:
11898     case ISD::STORE: {
11899       // Get alias information for Chain.
11900       bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
11901           !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
11902
11903       // If chain is alias then stop here.
11904       if (!(IsLoad && IsOpLoad) &&
11905           isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
11906         Aliases.push_back(Chain);
11907       } else {
11908         // Look further up the chain.
11909         Chains.push_back(Chain.getOperand(0));
11910         ++Depth;
11911       }
11912       break;
11913     }
11914
11915     case ISD::TokenFactor:
11916       // We have to check each of the operands of the token factor for "small"
11917       // token factors, so we queue them up.  Adding the operands to the queue
11918       // (stack) in reverse order maintains the original order and increases the
11919       // likelihood that getNode will find a matching token factor (CSE.)
11920       if (Chain.getNumOperands() > 16) {
11921         Aliases.push_back(Chain);
11922         break;
11923       }
11924       for (unsigned n = Chain.getNumOperands(); n;)
11925         Chains.push_back(Chain.getOperand(--n));
11926       ++Depth;
11927       break;
11928
11929     default:
11930       // For all other instructions we will just have to take what we can get.
11931       Aliases.push_back(Chain);
11932       break;
11933     }
11934   }
11935
11936   // We need to be careful here to also search for aliases through the
11937   // value operand of a store, etc. Consider the following situation:
11938   //   Token1 = ...
11939   //   L1 = load Token1, %52
11940   //   S1 = store Token1, L1, %51
11941   //   L2 = load Token1, %52+8
11942   //   S2 = store Token1, L2, %51+8
11943   //   Token2 = Token(S1, S2)
11944   //   L3 = load Token2, %53
11945   //   S3 = store Token2, L3, %52
11946   //   L4 = load Token2, %53+8
11947   //   S4 = store Token2, L4, %52+8
11948   // If we search for aliases of S3 (which loads address %52), and we look
11949   // only through the chain, then we'll miss the trivial dependence on L1
11950   // (which also loads from %52). We then might change all loads and
11951   // stores to use Token1 as their chain operand, which could result in
11952   // copying %53 into %52 before copying %52 into %51 (which should
11953   // happen first).
11954   //
11955   // The problem is, however, that searching for such data dependencies
11956   // can become expensive, and the cost is not directly related to the
11957   // chain depth. Instead, we'll rule out such configurations here by
11958   // insisting that we've visited all chain users (except for users
11959   // of the original chain, which is not necessary). When doing this,
11960   // we need to look through nodes we don't care about (otherwise, things
11961   // like register copies will interfere with trivial cases).
11962
11963   SmallVector<const SDNode *, 16> Worklist;
11964   for (const SDNode *N : Visited)
11965     if (N != OriginalChain.getNode())
11966       Worklist.push_back(N);
11967
11968   while (!Worklist.empty()) {
11969     const SDNode *M = Worklist.pop_back_val();
11970
11971     // We have already visited M, and want to make sure we've visited any uses
11972     // of M that we care about. For uses that we've not visisted, and don't
11973     // care about, queue them to the worklist.
11974
11975     for (SDNode::use_iterator UI = M->use_begin(),
11976          UIE = M->use_end(); UI != UIE; ++UI)
11977       if (UI.getUse().getValueType() == MVT::Other && Visited.insert(*UI)) {
11978         if (isa<MemIntrinsicSDNode>(*UI) || isa<MemSDNode>(*UI)) {
11979           // We've not visited this use, and we care about it (it could have an
11980           // ordering dependency with the original node).
11981           Aliases.clear();
11982           Aliases.push_back(OriginalChain);
11983           return;
11984         }
11985
11986         // We've not visited this use, but we don't care about it. Mark it as
11987         // visited and enqueue it to the worklist.
11988         Worklist.push_back(*UI);
11989       }
11990   }
11991 }
11992
11993 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain
11994 /// (aliasing node.)
11995 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
11996   SmallVector<SDValue, 8> Aliases;  // Ops for replacing token factor.
11997
11998   // Accumulate all the aliases to this node.
11999   GatherAllAliases(N, OldChain, Aliases);
12000
12001   // If no operands then chain to entry token.
12002   if (Aliases.size() == 0)
12003     return DAG.getEntryNode();
12004
12005   // If a single operand then chain to it.  We don't need to revisit it.
12006   if (Aliases.size() == 1)
12007     return Aliases[0];
12008
12009   // Construct a custom tailored token factor.
12010   return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
12011 }
12012
12013 /// This is the entry point for the file.
12014 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
12015                            CodeGenOpt::Level OptLevel) {
12016   /// This is the main entry point to this class.
12017   DAGCombiner(*this, AA, OptLevel).Run(Level);
12018 }