Move FNEG next to FABS and make them more similar, so it's easier that they can be...
[oota-llvm.git] / lib / CodeGen / SelectionDAG / DAGCombiner.cpp
1 //===-- DAGCombiner.cpp - Implement a DAG node combiner -------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This pass combines dag nodes to form fewer, simpler DAG nodes.  It can be run
11 // both before and after the DAG is legalized.
12 //
13 // This pass is not a substitute for the LLVM IR instcombine pass. This pass is
14 // primarily intended to handle simplification opportunities that are implicit
15 // in the LLVM IR and exposed by the various codegen lowering phases.
16 //
17 //===----------------------------------------------------------------------===//
18
19 #include "llvm/CodeGen/SelectionDAG.h"
20 #include "llvm/ADT/SmallPtrSet.h"
21 #include "llvm/ADT/SetVector.h"
22 #include "llvm/ADT/Statistic.h"
23 #include "llvm/Analysis/AliasAnalysis.h"
24 #include "llvm/CodeGen/MachineFrameInfo.h"
25 #include "llvm/CodeGen/MachineFunction.h"
26 #include "llvm/IR/DataLayout.h"
27 #include "llvm/IR/DerivedTypes.h"
28 #include "llvm/IR/Function.h"
29 #include "llvm/IR/LLVMContext.h"
30 #include "llvm/Support/CommandLine.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/Support/ErrorHandling.h"
33 #include "llvm/Support/MathExtras.h"
34 #include "llvm/Support/raw_ostream.h"
35 #include "llvm/Target/TargetLowering.h"
36 #include "llvm/Target/TargetMachine.h"
37 #include "llvm/Target/TargetOptions.h"
38 #include "llvm/Target/TargetRegisterInfo.h"
39 #include "llvm/Target/TargetSubtargetInfo.h"
40 #include <algorithm>
41 using namespace llvm;
42
43 #define DEBUG_TYPE "dagcombine"
44
45 STATISTIC(NodesCombined   , "Number of dag nodes combined");
46 STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created");
47 STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created");
48 STATISTIC(OpsNarrowed     , "Number of load/op/store narrowed");
49 STATISTIC(LdStFP2Int      , "Number of fp load/store pairs transformed to int");
50 STATISTIC(SlicedLoads, "Number of load sliced");
51
52 namespace {
53   static cl::opt<bool>
54     CombinerAA("combiner-alias-analysis", cl::Hidden,
55                cl::desc("Enable DAG combiner alias-analysis heuristics"));
56
57   static cl::opt<bool>
58     CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
59                cl::desc("Enable DAG combiner's use of IR alias analysis"));
60
61   static cl::opt<bool>
62     UseTBAA("combiner-use-tbaa", cl::Hidden, cl::init(true),
63                cl::desc("Enable DAG combiner's use of TBAA"));
64
65 #ifndef NDEBUG
66   static cl::opt<std::string>
67     CombinerAAOnlyFunc("combiner-aa-only-func", cl::Hidden,
68                cl::desc("Only use DAG-combiner alias analysis in this"
69                         " function"));
70 #endif
71
72   /// Hidden option to stress test load slicing, i.e., when this option
73   /// is enabled, load slicing bypasses most of its profitability guards.
74   static cl::opt<bool>
75   StressLoadSlicing("combiner-stress-load-slicing", cl::Hidden,
76                     cl::desc("Bypass the profitability model of load "
77                              "slicing"),
78                     cl::init(false));
79
80 //------------------------------ DAGCombiner ---------------------------------//
81
82   class DAGCombiner {
83     SelectionDAG &DAG;
84     const TargetLowering &TLI;
85     CombineLevel Level;
86     CodeGenOpt::Level OptLevel;
87     bool LegalOperations;
88     bool LegalTypes;
89     bool ForCodeSize;
90
91     /// \brief Worklist of all of the nodes that need to be simplified.
92     ///
93     /// This must behave as a stack -- new nodes to process are pushed onto the
94     /// back and when processing we pop off of the back.
95     ///
96     /// The worklist will not contain duplicates but may contain null entries
97     /// due to nodes being deleted from the underlying DAG.
98     SmallVector<SDNode *, 64> Worklist;
99
100     /// \brief Mapping from an SDNode to its position on the worklist.
101     ///
102     /// This is used to find and remove nodes from the worklist (by nulling
103     /// them) when they are deleted from the underlying DAG. It relies on
104     /// stable indices of nodes within the worklist.
105     DenseMap<SDNode *, unsigned> WorklistMap;
106
107     /// \brief Set of nodes which have been combined (at least once).
108     ///
109     /// This is used to allow us to reliably add any operands of a DAG node
110     /// which have not yet been combined to the worklist.
111     SmallPtrSet<SDNode *, 64> CombinedNodes;
112
113     // AA - Used for DAG load/store alias analysis.
114     AliasAnalysis &AA;
115
116     /// When an instruction is simplified, add all users of the instruction to
117     /// the work lists because they might get more simplified now.
118     void AddUsersToWorklist(SDNode *N) {
119       for (SDNode *Node : N->uses())
120         AddToWorklist(Node);
121     }
122
123     /// Call the node-specific routine that folds each particular type of node.
124     SDValue visit(SDNode *N);
125
126   public:
127     /// Add to the worklist making sure its instance is at the back (next to be
128     /// processed.)
129     void AddToWorklist(SDNode *N) {
130       // Skip handle nodes as they can't usefully be combined and confuse the
131       // zero-use deletion strategy.
132       if (N->getOpcode() == ISD::HANDLENODE)
133         return;
134
135       if (WorklistMap.insert(std::make_pair(N, Worklist.size())).second)
136         Worklist.push_back(N);
137     }
138
139     /// Remove all instances of N from the worklist.
140     void removeFromWorklist(SDNode *N) {
141       CombinedNodes.erase(N);
142
143       auto It = WorklistMap.find(N);
144       if (It == WorklistMap.end())
145         return; // Not in the worklist.
146
147       // Null out the entry rather than erasing it to avoid a linear operation.
148       Worklist[It->second] = nullptr;
149       WorklistMap.erase(It);
150     }
151
152     void deleteAndRecombine(SDNode *N);
153     bool recursivelyDeleteUnusedNodes(SDNode *N);
154
155     SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
156                       bool AddTo = true);
157
158     SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
159       return CombineTo(N, &Res, 1, AddTo);
160     }
161
162     SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
163                       bool AddTo = true) {
164       SDValue To[] = { Res0, Res1 };
165       return CombineTo(N, To, 2, AddTo);
166     }
167
168     void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
169
170   private:
171
172     /// Check the specified integer node value to see if it can be simplified or
173     /// if things it uses can be simplified by bit propagation.
174     /// If so, return true.
175     bool SimplifyDemandedBits(SDValue Op) {
176       unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits();
177       APInt Demanded = APInt::getAllOnesValue(BitWidth);
178       return SimplifyDemandedBits(Op, Demanded);
179     }
180
181     bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded);
182
183     bool CombineToPreIndexedLoadStore(SDNode *N);
184     bool CombineToPostIndexedLoadStore(SDNode *N);
185     bool SliceUpLoad(SDNode *N);
186
187     /// \brief Replace an ISD::EXTRACT_VECTOR_ELT of a load with a narrowed
188     ///   load.
189     ///
190     /// \param EVE ISD::EXTRACT_VECTOR_ELT to be replaced.
191     /// \param InVecVT type of the input vector to EVE with bitcasts resolved.
192     /// \param EltNo index of the vector element to load.
193     /// \param OriginalLoad load that EVE came from to be replaced.
194     /// \returns EVE on success SDValue() on failure.
195     SDValue ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
196         SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad);
197     void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
198     SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
199     SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
200     SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
201     SDValue PromoteIntBinOp(SDValue Op);
202     SDValue PromoteIntShiftOp(SDValue Op);
203     SDValue PromoteExtend(SDValue Op);
204     bool PromoteLoad(SDValue Op);
205
206     void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
207                          SDValue Trunc, SDValue ExtLoad, SDLoc DL,
208                          ISD::NodeType ExtType);
209
210     /// Call the node-specific routine that knows how to fold each
211     /// particular type of node. If that doesn't do anything, try the
212     /// target-specific DAG combines.
213     SDValue combine(SDNode *N);
214
215     // Visitation implementation - Implement dag node combining for different
216     // node types.  The semantics are as follows:
217     // Return Value:
218     //   SDValue.getNode() == 0 - No change was made
219     //   SDValue.getNode() == N - N was replaced, is dead and has been handled.
220     //   otherwise              - N should be replaced by the returned Operand.
221     //
222     SDValue visitTokenFactor(SDNode *N);
223     SDValue visitMERGE_VALUES(SDNode *N);
224     SDValue visitADD(SDNode *N);
225     SDValue visitSUB(SDNode *N);
226     SDValue visitADDC(SDNode *N);
227     SDValue visitSUBC(SDNode *N);
228     SDValue visitADDE(SDNode *N);
229     SDValue visitSUBE(SDNode *N);
230     SDValue visitMUL(SDNode *N);
231     SDValue visitSDIV(SDNode *N);
232     SDValue visitUDIV(SDNode *N);
233     SDValue visitSREM(SDNode *N);
234     SDValue visitUREM(SDNode *N);
235     SDValue visitMULHU(SDNode *N);
236     SDValue visitMULHS(SDNode *N);
237     SDValue visitSMUL_LOHI(SDNode *N);
238     SDValue visitUMUL_LOHI(SDNode *N);
239     SDValue visitSMULO(SDNode *N);
240     SDValue visitUMULO(SDNode *N);
241     SDValue visitSDIVREM(SDNode *N);
242     SDValue visitUDIVREM(SDNode *N);
243     SDValue visitAND(SDNode *N);
244     SDValue visitOR(SDNode *N);
245     SDValue visitXOR(SDNode *N);
246     SDValue SimplifyVBinOp(SDNode *N);
247     SDValue SimplifyVUnaryOp(SDNode *N);
248     SDValue visitSHL(SDNode *N);
249     SDValue visitSRA(SDNode *N);
250     SDValue visitSRL(SDNode *N);
251     SDValue visitRotate(SDNode *N);
252     SDValue visitCTLZ(SDNode *N);
253     SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
254     SDValue visitCTTZ(SDNode *N);
255     SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
256     SDValue visitCTPOP(SDNode *N);
257     SDValue visitSELECT(SDNode *N);
258     SDValue visitVSELECT(SDNode *N);
259     SDValue visitSELECT_CC(SDNode *N);
260     SDValue visitSETCC(SDNode *N);
261     SDValue visitSIGN_EXTEND(SDNode *N);
262     SDValue visitZERO_EXTEND(SDNode *N);
263     SDValue visitANY_EXTEND(SDNode *N);
264     SDValue visitSIGN_EXTEND_INREG(SDNode *N);
265     SDValue visitTRUNCATE(SDNode *N);
266     SDValue visitBITCAST(SDNode *N);
267     SDValue visitBUILD_PAIR(SDNode *N);
268     SDValue visitFADD(SDNode *N);
269     SDValue visitFSUB(SDNode *N);
270     SDValue visitFMUL(SDNode *N);
271     SDValue visitFMA(SDNode *N);
272     SDValue visitFDIV(SDNode *N);
273     SDValue visitFREM(SDNode *N);
274     SDValue visitFCOPYSIGN(SDNode *N);
275     SDValue visitSINT_TO_FP(SDNode *N);
276     SDValue visitUINT_TO_FP(SDNode *N);
277     SDValue visitFP_TO_SINT(SDNode *N);
278     SDValue visitFP_TO_UINT(SDNode *N);
279     SDValue visitFP_ROUND(SDNode *N);
280     SDValue visitFP_ROUND_INREG(SDNode *N);
281     SDValue visitFP_EXTEND(SDNode *N);
282     SDValue visitFNEG(SDNode *N);
283     SDValue visitFABS(SDNode *N);
284     SDValue visitFCEIL(SDNode *N);
285     SDValue visitFTRUNC(SDNode *N);
286     SDValue visitFFLOOR(SDNode *N);
287     SDValue visitBRCOND(SDNode *N);
288     SDValue visitBR_CC(SDNode *N);
289     SDValue visitLOAD(SDNode *N);
290     SDValue visitSTORE(SDNode *N);
291     SDValue visitINSERT_VECTOR_ELT(SDNode *N);
292     SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
293     SDValue visitBUILD_VECTOR(SDNode *N);
294     SDValue visitCONCAT_VECTORS(SDNode *N);
295     SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
296     SDValue visitVECTOR_SHUFFLE(SDNode *N);
297     SDValue visitINSERT_SUBVECTOR(SDNode *N);
298
299     SDValue XformToShuffleWithZero(SDNode *N);
300     SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS);
301
302     SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt);
303
304     bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
305     SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
306     SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2);
307     SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2,
308                              SDValue N3, ISD::CondCode CC,
309                              bool NotExtCompare = false);
310     SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
311                           SDLoc DL, bool foldBooleans = true);
312
313     bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
314                            SDValue &CC) const;
315     bool isOneUseSetCC(SDValue N) const;
316
317     SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
318                                          unsigned HiOp);
319     SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
320     SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
321     SDValue BuildSDIV(SDNode *N);
322     SDValue BuildSDIVPow2(SDNode *N);
323     SDValue BuildUDIV(SDNode *N);
324     SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
325                                bool DemandHighBits = true);
326     SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
327     SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
328                               SDValue InnerPos, SDValue InnerNeg,
329                               unsigned PosOpcode, unsigned NegOpcode,
330                               SDLoc DL);
331     SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL);
332     SDValue ReduceLoadWidth(SDNode *N);
333     SDValue ReduceLoadOpStoreWidth(SDNode *N);
334     SDValue TransformFPLoadStorePair(SDNode *N);
335     SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
336     SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
337
338     SDValue GetDemandedBits(SDValue V, const APInt &Mask);
339
340     /// Walk up chain skipping non-aliasing memory nodes,
341     /// looking for aliasing nodes and adding them to the Aliases vector.
342     void GatherAllAliases(SDNode *N, SDValue OriginalChain,
343                           SmallVectorImpl<SDValue> &Aliases);
344
345     /// Return true if there is any possibility that the two addresses overlap.
346     bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const;
347
348     /// Walk up chain skipping non-aliasing memory nodes, looking for a better
349     /// chain (aliasing node.)
350     SDValue FindBetterChain(SDNode *N, SDValue Chain);
351
352     /// Merge consecutive store operations into a wide store.
353     /// This optimization uses wide integers or vectors when possible.
354     /// \return True if some memory operations were changed.
355     bool MergeConsecutiveStores(StoreSDNode *N);
356
357     /// \brief Try to transform a truncation where C is a constant:
358     ///     (trunc (and X, C)) -> (and (trunc X), (trunc C))
359     ///
360     /// \p N needs to be a truncation and its first operand an AND. Other
361     /// requirements are checked by the function (e.g. that trunc is
362     /// single-use) and if missed an empty SDValue is returned.
363     SDValue distributeTruncateThroughAnd(SDNode *N);
364
365   public:
366     DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
367         : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
368           OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
369       AttributeSet FnAttrs =
370           DAG.getMachineFunction().getFunction()->getAttributes();
371       ForCodeSize =
372           FnAttrs.hasAttribute(AttributeSet::FunctionIndex,
373                                Attribute::OptimizeForSize) ||
374           FnAttrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::MinSize);
375     }
376
377     /// Runs the dag combiner on all nodes in the work list
378     void Run(CombineLevel AtLevel);
379
380     SelectionDAG &getDAG() const { return DAG; }
381
382     /// Returns a type large enough to hold any valid shift amount - before type
383     /// legalization these can be huge.
384     EVT getShiftAmountTy(EVT LHSTy) {
385       assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
386       if (LHSTy.isVector())
387         return LHSTy;
388       return LegalTypes ? TLI.getScalarShiftAmountTy(LHSTy)
389                         : TLI.getPointerTy();
390     }
391
392     /// This method returns true if we are running before type legalization or
393     /// if the specified VT is legal.
394     bool isTypeLegal(const EVT &VT) {
395       if (!LegalTypes) return true;
396       return TLI.isTypeLegal(VT);
397     }
398
399     /// Convenience wrapper around TargetLowering::getSetCCResultType
400     EVT getSetCCResultType(EVT VT) const {
401       return TLI.getSetCCResultType(*DAG.getContext(), VT);
402     }
403   };
404 }
405
406
407 namespace {
408 /// This class is a DAGUpdateListener that removes any deleted
409 /// nodes from the worklist.
410 class WorklistRemover : public SelectionDAG::DAGUpdateListener {
411   DAGCombiner &DC;
412 public:
413   explicit WorklistRemover(DAGCombiner &dc)
414     : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
415
416   void NodeDeleted(SDNode *N, SDNode *E) override {
417     DC.removeFromWorklist(N);
418   }
419 };
420 }
421
422 //===----------------------------------------------------------------------===//
423 //  TargetLowering::DAGCombinerInfo implementation
424 //===----------------------------------------------------------------------===//
425
426 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
427   ((DAGCombiner*)DC)->AddToWorklist(N);
428 }
429
430 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
431   ((DAGCombiner*)DC)->removeFromWorklist(N);
432 }
433
434 SDValue TargetLowering::DAGCombinerInfo::
435 CombineTo(SDNode *N, const std::vector<SDValue> &To, bool AddTo) {
436   return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
437 }
438
439 SDValue TargetLowering::DAGCombinerInfo::
440 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
441   return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
442 }
443
444
445 SDValue TargetLowering::DAGCombinerInfo::
446 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
447   return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
448 }
449
450 void TargetLowering::DAGCombinerInfo::
451 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
452   return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
453 }
454
455 //===----------------------------------------------------------------------===//
456 // Helper Functions
457 //===----------------------------------------------------------------------===//
458
459 void DAGCombiner::deleteAndRecombine(SDNode *N) {
460   removeFromWorklist(N);
461
462   // If the operands of this node are only used by the node, they will now be
463   // dead. Make sure to re-visit them and recursively delete dead nodes.
464   for (const SDValue &Op : N->ops())
465     if (Op->hasOneUse())
466       AddToWorklist(Op.getNode());
467
468   DAG.DeleteNode(N);
469 }
470
471 /// Return 1 if we can compute the negated form of the specified expression for
472 /// the same cost as the expression itself, or 2 if we can compute the negated
473 /// form more cheaply than the expression itself.
474 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
475                                const TargetLowering &TLI,
476                                const TargetOptions *Options,
477                                unsigned Depth = 0) {
478   // fneg is removable even if it has multiple uses.
479   if (Op.getOpcode() == ISD::FNEG) return 2;
480
481   // Don't allow anything with multiple uses.
482   if (!Op.hasOneUse()) return 0;
483
484   // Don't recurse exponentially.
485   if (Depth > 6) return 0;
486
487   switch (Op.getOpcode()) {
488   default: return false;
489   case ISD::ConstantFP:
490     // Don't invert constant FP values after legalize.  The negated constant
491     // isn't necessarily legal.
492     return LegalOperations ? 0 : 1;
493   case ISD::FADD:
494     // FIXME: determine better conditions for this xform.
495     if (!Options->UnsafeFPMath) return 0;
496
497     // After operation legalization, it might not be legal to create new FSUBs.
498     if (LegalOperations &&
499         !TLI.isOperationLegalOrCustom(ISD::FSUB,  Op.getValueType()))
500       return 0;
501
502     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
503     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
504                                     Options, Depth + 1))
505       return V;
506     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
507     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
508                               Depth + 1);
509   case ISD::FSUB:
510     // We can't turn -(A-B) into B-A when we honor signed zeros.
511     if (!Options->UnsafeFPMath) return 0;
512
513     // fold (fneg (fsub A, B)) -> (fsub B, A)
514     return 1;
515
516   case ISD::FMUL:
517   case ISD::FDIV:
518     if (Options->HonorSignDependentRoundingFPMath()) return 0;
519
520     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
521     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
522                                     Options, Depth + 1))
523       return V;
524
525     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
526                               Depth + 1);
527
528   case ISD::FP_EXTEND:
529   case ISD::FP_ROUND:
530   case ISD::FSIN:
531     return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
532                               Depth + 1);
533   }
534 }
535
536 /// If isNegatibleForFree returns true, return the newly negated expression.
537 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
538                                     bool LegalOperations, unsigned Depth = 0) {
539   const TargetOptions &Options = DAG.getTarget().Options;
540   // fneg is removable even if it has multiple uses.
541   if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
542
543   // Don't allow anything with multiple uses.
544   assert(Op.hasOneUse() && "Unknown reuse!");
545
546   assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
547   switch (Op.getOpcode()) {
548   default: llvm_unreachable("Unknown code");
549   case ISD::ConstantFP: {
550     APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
551     V.changeSign();
552     return DAG.getConstantFP(V, Op.getValueType());
553   }
554   case ISD::FADD:
555     // FIXME: determine better conditions for this xform.
556     assert(Options.UnsafeFPMath);
557
558     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
559     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
560                            DAG.getTargetLoweringInfo(), &Options, Depth+1))
561       return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
562                          GetNegatedExpression(Op.getOperand(0), DAG,
563                                               LegalOperations, Depth+1),
564                          Op.getOperand(1));
565     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
566     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
567                        GetNegatedExpression(Op.getOperand(1), DAG,
568                                             LegalOperations, Depth+1),
569                        Op.getOperand(0));
570   case ISD::FSUB:
571     // We can't turn -(A-B) into B-A when we honor signed zeros.
572     assert(Options.UnsafeFPMath);
573
574     // fold (fneg (fsub 0, B)) -> B
575     if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
576       if (N0CFP->getValueAPF().isZero())
577         return Op.getOperand(1);
578
579     // fold (fneg (fsub A, B)) -> (fsub B, A)
580     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
581                        Op.getOperand(1), Op.getOperand(0));
582
583   case ISD::FMUL:
584   case ISD::FDIV:
585     assert(!Options.HonorSignDependentRoundingFPMath());
586
587     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
588     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
589                            DAG.getTargetLoweringInfo(), &Options, Depth+1))
590       return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
591                          GetNegatedExpression(Op.getOperand(0), DAG,
592                                               LegalOperations, Depth+1),
593                          Op.getOperand(1));
594
595     // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
596     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
597                        Op.getOperand(0),
598                        GetNegatedExpression(Op.getOperand(1), DAG,
599                                             LegalOperations, Depth+1));
600
601   case ISD::FP_EXTEND:
602   case ISD::FSIN:
603     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
604                        GetNegatedExpression(Op.getOperand(0), DAG,
605                                             LegalOperations, Depth+1));
606   case ISD::FP_ROUND:
607       return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
608                          GetNegatedExpression(Op.getOperand(0), DAG,
609                                               LegalOperations, Depth+1),
610                          Op.getOperand(1));
611   }
612 }
613
614 // isSetCCEquivalent - Return true if this node is a setcc, or is a select_cc
615 // that selects between the target values used for true and false, making it
616 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
617 // the appropriate nodes based on the type of node we are checking. This
618 // simplifies life a bit for the callers.
619 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
620                                     SDValue &CC) const {
621   if (N.getOpcode() == ISD::SETCC) {
622     LHS = N.getOperand(0);
623     RHS = N.getOperand(1);
624     CC  = N.getOperand(2);
625     return true;
626   }
627
628   if (N.getOpcode() != ISD::SELECT_CC ||
629       !TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
630       !TLI.isConstFalseVal(N.getOperand(3).getNode()))
631     return false;
632
633   LHS = N.getOperand(0);
634   RHS = N.getOperand(1);
635   CC  = N.getOperand(4);
636   return true;
637 }
638
639 /// Return true if this is a SetCC-equivalent operation with only one use.
640 /// If this is true, it allows the users to invert the operation for free when
641 /// it is profitable to do so.
642 bool DAGCombiner::isOneUseSetCC(SDValue N) const {
643   SDValue N0, N1, N2;
644   if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
645     return true;
646   return false;
647 }
648
649 /// Returns true if N is a BUILD_VECTOR node whose
650 /// elements are all the same constant or undefined.
651 static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
652   BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
653   if (!C)
654     return false;
655
656   APInt SplatUndef;
657   unsigned SplatBitSize;
658   bool HasAnyUndefs;
659   EVT EltVT = N->getValueType(0).getVectorElementType();
660   return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
661                              HasAnyUndefs) &&
662           EltVT.getSizeInBits() >= SplatBitSize);
663 }
664
665 // \brief Returns the SDNode if it is a constant BuildVector or constant.
666 static SDNode *isConstantBuildVectorOrConstantInt(SDValue N) {
667   if (isa<ConstantSDNode>(N))
668     return N.getNode();
669   BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N);
670   if(BV && BV->isConstant())
671     return BV;
672   return nullptr;
673 }
674
675 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
676 // int.
677 static ConstantSDNode *isConstOrConstSplat(SDValue N) {
678   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
679     return CN;
680
681   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
682     BitVector UndefElements;
683     ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
684
685     // BuildVectors can truncate their operands. Ignore that case here.
686     // FIXME: We blindly ignore splats which include undef which is overly
687     // pessimistic.
688     if (CN && UndefElements.none() &&
689         CN->getValueType(0) == N.getValueType().getScalarType())
690       return CN;
691   }
692
693   return nullptr;
694 }
695
696 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
697 // float.
698 static ConstantFPSDNode *isConstOrConstSplatFP(SDValue N) {
699   if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
700     return CN;
701
702   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
703     BitVector UndefElements;
704     ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements);
705
706     // BuildVectors can truncate their operands. Ignore that case here.
707     // FIXME: We blindly ignore splats which include undef which is overly
708     // pessimistic.
709     if (CN && UndefElements.none() &&
710         CN->getValueType(0) == N.getValueType().getScalarType())
711       return CN;
712   }
713
714   return nullptr;
715 }
716
717 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
718                                     SDValue N0, SDValue N1) {
719   EVT VT = N0.getValueType();
720   if (N0.getOpcode() == Opc) {
721     if (SDNode *L = isConstantBuildVectorOrConstantInt(N0.getOperand(1))) {
722       if (SDNode *R = isConstantBuildVectorOrConstantInt(N1)) {
723         // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
724         SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, L, R);
725         if (!OpNode.getNode())
726           return SDValue();
727         return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
728       }
729       if (N0.hasOneUse()) {
730         // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
731         // use
732         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
733         if (!OpNode.getNode())
734           return SDValue();
735         AddToWorklist(OpNode.getNode());
736         return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
737       }
738     }
739   }
740
741   if (N1.getOpcode() == Opc) {
742     if (SDNode *R = isConstantBuildVectorOrConstantInt(N1.getOperand(1))) {
743       if (SDNode *L = isConstantBuildVectorOrConstantInt(N0)) {
744         // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
745         SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, R, L);
746         if (!OpNode.getNode())
747           return SDValue();
748         return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
749       }
750       if (N1.hasOneUse()) {
751         // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one
752         // use
753         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0);
754         if (!OpNode.getNode())
755           return SDValue();
756         AddToWorklist(OpNode.getNode());
757         return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
758       }
759     }
760   }
761
762   return SDValue();
763 }
764
765 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
766                                bool AddTo) {
767   assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
768   ++NodesCombined;
769   DEBUG(dbgs() << "\nReplacing.1 ";
770         N->dump(&DAG);
771         dbgs() << "\nWith: ";
772         To[0].getNode()->dump(&DAG);
773         dbgs() << " and " << NumTo-1 << " other values\n";
774         for (unsigned i = 0, e = NumTo; i != e; ++i)
775           assert((!To[i].getNode() ||
776                   N->getValueType(i) == To[i].getValueType()) &&
777                  "Cannot combine value to value of different type!"));
778   WorklistRemover DeadNodes(*this);
779   DAG.ReplaceAllUsesWith(N, To);
780   if (AddTo) {
781     // Push the new nodes and any users onto the worklist
782     for (unsigned i = 0, e = NumTo; i != e; ++i) {
783       if (To[i].getNode()) {
784         AddToWorklist(To[i].getNode());
785         AddUsersToWorklist(To[i].getNode());
786       }
787     }
788   }
789
790   // Finally, if the node is now dead, remove it from the graph.  The node
791   // may not be dead if the replacement process recursively simplified to
792   // something else needing this node.
793   if (N->use_empty())
794     deleteAndRecombine(N);
795   return SDValue(N, 0);
796 }
797
798 void DAGCombiner::
799 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
800   // Replace all uses.  If any nodes become isomorphic to other nodes and
801   // are deleted, make sure to remove them from our worklist.
802   WorklistRemover DeadNodes(*this);
803   DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
804
805   // Push the new node and any (possibly new) users onto the worklist.
806   AddToWorklist(TLO.New.getNode());
807   AddUsersToWorklist(TLO.New.getNode());
808
809   // Finally, if the node is now dead, remove it from the graph.  The node
810   // may not be dead if the replacement process recursively simplified to
811   // something else needing this node.
812   if (TLO.Old.getNode()->use_empty())
813     deleteAndRecombine(TLO.Old.getNode());
814 }
815
816 /// Check the specified integer node value to see if it can be simplified or if
817 /// things it uses can be simplified by bit propagation. If so, return true.
818 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
819   TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
820   APInt KnownZero, KnownOne;
821   if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
822     return false;
823
824   // Revisit the node.
825   AddToWorklist(Op.getNode());
826
827   // Replace the old value with the new one.
828   ++NodesCombined;
829   DEBUG(dbgs() << "\nReplacing.2 ";
830         TLO.Old.getNode()->dump(&DAG);
831         dbgs() << "\nWith: ";
832         TLO.New.getNode()->dump(&DAG);
833         dbgs() << '\n');
834
835   CommitTargetLoweringOpt(TLO);
836   return true;
837 }
838
839 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
840   SDLoc dl(Load);
841   EVT VT = Load->getValueType(0);
842   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
843
844   DEBUG(dbgs() << "\nReplacing.9 ";
845         Load->dump(&DAG);
846         dbgs() << "\nWith: ";
847         Trunc.getNode()->dump(&DAG);
848         dbgs() << '\n');
849   WorklistRemover DeadNodes(*this);
850   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
851   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
852   deleteAndRecombine(Load);
853   AddToWorklist(Trunc.getNode());
854 }
855
856 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
857   Replace = false;
858   SDLoc dl(Op);
859   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
860     EVT MemVT = LD->getMemoryVT();
861     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
862       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
863                                                   : ISD::EXTLOAD)
864       : LD->getExtensionType();
865     Replace = true;
866     return DAG.getExtLoad(ExtType, dl, PVT,
867                           LD->getChain(), LD->getBasePtr(),
868                           MemVT, LD->getMemOperand());
869   }
870
871   unsigned Opc = Op.getOpcode();
872   switch (Opc) {
873   default: break;
874   case ISD::AssertSext:
875     return DAG.getNode(ISD::AssertSext, dl, PVT,
876                        SExtPromoteOperand(Op.getOperand(0), PVT),
877                        Op.getOperand(1));
878   case ISD::AssertZext:
879     return DAG.getNode(ISD::AssertZext, dl, PVT,
880                        ZExtPromoteOperand(Op.getOperand(0), PVT),
881                        Op.getOperand(1));
882   case ISD::Constant: {
883     unsigned ExtOpc =
884       Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
885     return DAG.getNode(ExtOpc, dl, PVT, Op);
886   }
887   }
888
889   if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
890     return SDValue();
891   return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
892 }
893
894 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
895   if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
896     return SDValue();
897   EVT OldVT = Op.getValueType();
898   SDLoc dl(Op);
899   bool Replace = false;
900   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
901   if (!NewOp.getNode())
902     return SDValue();
903   AddToWorklist(NewOp.getNode());
904
905   if (Replace)
906     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
907   return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
908                      DAG.getValueType(OldVT));
909 }
910
911 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
912   EVT OldVT = Op.getValueType();
913   SDLoc dl(Op);
914   bool Replace = false;
915   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
916   if (!NewOp.getNode())
917     return SDValue();
918   AddToWorklist(NewOp.getNode());
919
920   if (Replace)
921     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
922   return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
923 }
924
925 /// Promote the specified integer binary operation if the target indicates it is
926 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
927 /// i32 since i16 instructions are longer.
928 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
929   if (!LegalOperations)
930     return SDValue();
931
932   EVT VT = Op.getValueType();
933   if (VT.isVector() || !VT.isInteger())
934     return SDValue();
935
936   // If operation type is 'undesirable', e.g. i16 on x86, consider
937   // promoting it.
938   unsigned Opc = Op.getOpcode();
939   if (TLI.isTypeDesirableForOp(Opc, VT))
940     return SDValue();
941
942   EVT PVT = VT;
943   // Consult target whether it is a good idea to promote this operation and
944   // what's the right type to promote it to.
945   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
946     assert(PVT != VT && "Don't know what type to promote to!");
947
948     bool Replace0 = false;
949     SDValue N0 = Op.getOperand(0);
950     SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
951     if (!NN0.getNode())
952       return SDValue();
953
954     bool Replace1 = false;
955     SDValue N1 = Op.getOperand(1);
956     SDValue NN1;
957     if (N0 == N1)
958       NN1 = NN0;
959     else {
960       NN1 = PromoteOperand(N1, PVT, Replace1);
961       if (!NN1.getNode())
962         return SDValue();
963     }
964
965     AddToWorklist(NN0.getNode());
966     if (NN1.getNode())
967       AddToWorklist(NN1.getNode());
968
969     if (Replace0)
970       ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
971     if (Replace1)
972       ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
973
974     DEBUG(dbgs() << "\nPromoting ";
975           Op.getNode()->dump(&DAG));
976     SDLoc dl(Op);
977     return DAG.getNode(ISD::TRUNCATE, dl, VT,
978                        DAG.getNode(Opc, dl, PVT, NN0, NN1));
979   }
980   return SDValue();
981 }
982
983 /// Promote the specified integer shift operation if the target indicates it is
984 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
985 /// i32 since i16 instructions are longer.
986 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
987   if (!LegalOperations)
988     return SDValue();
989
990   EVT VT = Op.getValueType();
991   if (VT.isVector() || !VT.isInteger())
992     return SDValue();
993
994   // If operation type is 'undesirable', e.g. i16 on x86, consider
995   // promoting it.
996   unsigned Opc = Op.getOpcode();
997   if (TLI.isTypeDesirableForOp(Opc, VT))
998     return SDValue();
999
1000   EVT PVT = VT;
1001   // Consult target whether it is a good idea to promote this operation and
1002   // what's the right type to promote it to.
1003   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1004     assert(PVT != VT && "Don't know what type to promote to!");
1005
1006     bool Replace = false;
1007     SDValue N0 = Op.getOperand(0);
1008     if (Opc == ISD::SRA)
1009       N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
1010     else if (Opc == ISD::SRL)
1011       N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
1012     else
1013       N0 = PromoteOperand(N0, PVT, Replace);
1014     if (!N0.getNode())
1015       return SDValue();
1016
1017     AddToWorklist(N0.getNode());
1018     if (Replace)
1019       ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
1020
1021     DEBUG(dbgs() << "\nPromoting ";
1022           Op.getNode()->dump(&DAG));
1023     SDLoc dl(Op);
1024     return DAG.getNode(ISD::TRUNCATE, dl, VT,
1025                        DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
1026   }
1027   return SDValue();
1028 }
1029
1030 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
1031   if (!LegalOperations)
1032     return SDValue();
1033
1034   EVT VT = Op.getValueType();
1035   if (VT.isVector() || !VT.isInteger())
1036     return SDValue();
1037
1038   // If operation type is 'undesirable', e.g. i16 on x86, consider
1039   // promoting it.
1040   unsigned Opc = Op.getOpcode();
1041   if (TLI.isTypeDesirableForOp(Opc, VT))
1042     return SDValue();
1043
1044   EVT PVT = VT;
1045   // Consult target whether it is a good idea to promote this operation and
1046   // what's the right type to promote it to.
1047   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1048     assert(PVT != VT && "Don't know what type to promote to!");
1049     // fold (aext (aext x)) -> (aext x)
1050     // fold (aext (zext x)) -> (zext x)
1051     // fold (aext (sext x)) -> (sext x)
1052     DEBUG(dbgs() << "\nPromoting ";
1053           Op.getNode()->dump(&DAG));
1054     return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1055   }
1056   return SDValue();
1057 }
1058
1059 bool DAGCombiner::PromoteLoad(SDValue Op) {
1060   if (!LegalOperations)
1061     return false;
1062
1063   EVT VT = Op.getValueType();
1064   if (VT.isVector() || !VT.isInteger())
1065     return false;
1066
1067   // If operation type is 'undesirable', e.g. i16 on x86, consider
1068   // promoting it.
1069   unsigned Opc = Op.getOpcode();
1070   if (TLI.isTypeDesirableForOp(Opc, VT))
1071     return false;
1072
1073   EVT PVT = VT;
1074   // Consult target whether it is a good idea to promote this operation and
1075   // what's the right type to promote it to.
1076   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1077     assert(PVT != VT && "Don't know what type to promote to!");
1078
1079     SDLoc dl(Op);
1080     SDNode *N = Op.getNode();
1081     LoadSDNode *LD = cast<LoadSDNode>(N);
1082     EVT MemVT = LD->getMemoryVT();
1083     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1084       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
1085                                                   : ISD::EXTLOAD)
1086       : LD->getExtensionType();
1087     SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
1088                                    LD->getChain(), LD->getBasePtr(),
1089                                    MemVT, LD->getMemOperand());
1090     SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
1091
1092     DEBUG(dbgs() << "\nPromoting ";
1093           N->dump(&DAG);
1094           dbgs() << "\nTo: ";
1095           Result.getNode()->dump(&DAG);
1096           dbgs() << '\n');
1097     WorklistRemover DeadNodes(*this);
1098     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1099     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1100     deleteAndRecombine(N);
1101     AddToWorklist(Result.getNode());
1102     return true;
1103   }
1104   return false;
1105 }
1106
1107 /// \brief Recursively delete a node which has no uses and any operands for
1108 /// which it is the only use.
1109 ///
1110 /// Note that this both deletes the nodes and removes them from the worklist.
1111 /// It also adds any nodes who have had a user deleted to the worklist as they
1112 /// may now have only one use and subject to other combines.
1113 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) {
1114   if (!N->use_empty())
1115     return false;
1116
1117   SmallSetVector<SDNode *, 16> Nodes;
1118   Nodes.insert(N);
1119   do {
1120     N = Nodes.pop_back_val();
1121     if (!N)
1122       continue;
1123
1124     if (N->use_empty()) {
1125       for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1126         Nodes.insert(N->getOperand(i).getNode());
1127
1128       removeFromWorklist(N);
1129       DAG.DeleteNode(N);
1130     } else {
1131       AddToWorklist(N);
1132     }
1133   } while (!Nodes.empty());
1134   return true;
1135 }
1136
1137 //===----------------------------------------------------------------------===//
1138 //  Main DAG Combiner implementation
1139 //===----------------------------------------------------------------------===//
1140
1141 void DAGCombiner::Run(CombineLevel AtLevel) {
1142   // set the instance variables, so that the various visit routines may use it.
1143   Level = AtLevel;
1144   LegalOperations = Level >= AfterLegalizeVectorOps;
1145   LegalTypes = Level >= AfterLegalizeTypes;
1146
1147   // Add all the dag nodes to the worklist.
1148   for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
1149        E = DAG.allnodes_end(); I != E; ++I)
1150     AddToWorklist(I);
1151
1152   // Create a dummy node (which is not added to allnodes), that adds a reference
1153   // to the root node, preventing it from being deleted, and tracking any
1154   // changes of the root.
1155   HandleSDNode Dummy(DAG.getRoot());
1156
1157   // while the worklist isn't empty, find a node and
1158   // try and combine it.
1159   while (!WorklistMap.empty()) {
1160     SDNode *N;
1161     // The Worklist holds the SDNodes in order, but it may contain null entries.
1162     do {
1163       N = Worklist.pop_back_val();
1164     } while (!N);
1165
1166     bool GoodWorklistEntry = WorklistMap.erase(N);
1167     (void)GoodWorklistEntry;
1168     assert(GoodWorklistEntry &&
1169            "Found a worklist entry without a corresponding map entry!");
1170
1171     // If N has no uses, it is dead.  Make sure to revisit all N's operands once
1172     // N is deleted from the DAG, since they too may now be dead or may have a
1173     // reduced number of uses, allowing other xforms.
1174     if (recursivelyDeleteUnusedNodes(N))
1175       continue;
1176
1177     WorklistRemover DeadNodes(*this);
1178
1179     // If this combine is running after legalizing the DAG, re-legalize any
1180     // nodes pulled off the worklist.
1181     if (Level == AfterLegalizeDAG) {
1182       SmallSetVector<SDNode *, 16> UpdatedNodes;
1183       bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes);
1184
1185       for (SDNode *LN : UpdatedNodes) {
1186         AddToWorklist(LN);
1187         AddUsersToWorklist(LN);
1188       }
1189       if (!NIsValid)
1190         continue;
1191     }
1192
1193     DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG));
1194
1195     // Add any operands of the new node which have not yet been combined to the
1196     // worklist as well. Because the worklist uniques things already, this
1197     // won't repeatedly process the same operand.
1198     CombinedNodes.insert(N);
1199     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1200       if (!CombinedNodes.count(N->getOperand(i).getNode()))
1201         AddToWorklist(N->getOperand(i).getNode());
1202
1203     SDValue RV = combine(N);
1204
1205     if (!RV.getNode())
1206       continue;
1207
1208     ++NodesCombined;
1209
1210     // If we get back the same node we passed in, rather than a new node or
1211     // zero, we know that the node must have defined multiple values and
1212     // CombineTo was used.  Since CombineTo takes care of the worklist
1213     // mechanics for us, we have no work to do in this case.
1214     if (RV.getNode() == N)
1215       continue;
1216
1217     assert(N->getOpcode() != ISD::DELETED_NODE &&
1218            RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1219            "Node was deleted but visit returned new node!");
1220
1221     DEBUG(dbgs() << " ... into: ";
1222           RV.getNode()->dump(&DAG));
1223
1224     // Transfer debug value.
1225     DAG.TransferDbgValues(SDValue(N, 0), RV);
1226     if (N->getNumValues() == RV.getNode()->getNumValues())
1227       DAG.ReplaceAllUsesWith(N, RV.getNode());
1228     else {
1229       assert(N->getValueType(0) == RV.getValueType() &&
1230              N->getNumValues() == 1 && "Type mismatch");
1231       SDValue OpV = RV;
1232       DAG.ReplaceAllUsesWith(N, &OpV);
1233     }
1234
1235     // Push the new node and any users onto the worklist
1236     AddToWorklist(RV.getNode());
1237     AddUsersToWorklist(RV.getNode());
1238
1239     // Finally, if the node is now dead, remove it from the graph.  The node
1240     // may not be dead if the replacement process recursively simplified to
1241     // something else needing this node. This will also take care of adding any
1242     // operands which have lost a user to the worklist.
1243     recursivelyDeleteUnusedNodes(N);
1244   }
1245
1246   // If the root changed (e.g. it was a dead load, update the root).
1247   DAG.setRoot(Dummy.getValue());
1248   DAG.RemoveDeadNodes();
1249 }
1250
1251 SDValue DAGCombiner::visit(SDNode *N) {
1252   switch (N->getOpcode()) {
1253   default: break;
1254   case ISD::TokenFactor:        return visitTokenFactor(N);
1255   case ISD::MERGE_VALUES:       return visitMERGE_VALUES(N);
1256   case ISD::ADD:                return visitADD(N);
1257   case ISD::SUB:                return visitSUB(N);
1258   case ISD::ADDC:               return visitADDC(N);
1259   case ISD::SUBC:               return visitSUBC(N);
1260   case ISD::ADDE:               return visitADDE(N);
1261   case ISD::SUBE:               return visitSUBE(N);
1262   case ISD::MUL:                return visitMUL(N);
1263   case ISD::SDIV:               return visitSDIV(N);
1264   case ISD::UDIV:               return visitUDIV(N);
1265   case ISD::SREM:               return visitSREM(N);
1266   case ISD::UREM:               return visitUREM(N);
1267   case ISD::MULHU:              return visitMULHU(N);
1268   case ISD::MULHS:              return visitMULHS(N);
1269   case ISD::SMUL_LOHI:          return visitSMUL_LOHI(N);
1270   case ISD::UMUL_LOHI:          return visitUMUL_LOHI(N);
1271   case ISD::SMULO:              return visitSMULO(N);
1272   case ISD::UMULO:              return visitUMULO(N);
1273   case ISD::SDIVREM:            return visitSDIVREM(N);
1274   case ISD::UDIVREM:            return visitUDIVREM(N);
1275   case ISD::AND:                return visitAND(N);
1276   case ISD::OR:                 return visitOR(N);
1277   case ISD::XOR:                return visitXOR(N);
1278   case ISD::SHL:                return visitSHL(N);
1279   case ISD::SRA:                return visitSRA(N);
1280   case ISD::SRL:                return visitSRL(N);
1281   case ISD::ROTR:
1282   case ISD::ROTL:               return visitRotate(N);
1283   case ISD::CTLZ:               return visitCTLZ(N);
1284   case ISD::CTLZ_ZERO_UNDEF:    return visitCTLZ_ZERO_UNDEF(N);
1285   case ISD::CTTZ:               return visitCTTZ(N);
1286   case ISD::CTTZ_ZERO_UNDEF:    return visitCTTZ_ZERO_UNDEF(N);
1287   case ISD::CTPOP:              return visitCTPOP(N);
1288   case ISD::SELECT:             return visitSELECT(N);
1289   case ISD::VSELECT:            return visitVSELECT(N);
1290   case ISD::SELECT_CC:          return visitSELECT_CC(N);
1291   case ISD::SETCC:              return visitSETCC(N);
1292   case ISD::SIGN_EXTEND:        return visitSIGN_EXTEND(N);
1293   case ISD::ZERO_EXTEND:        return visitZERO_EXTEND(N);
1294   case ISD::ANY_EXTEND:         return visitANY_EXTEND(N);
1295   case ISD::SIGN_EXTEND_INREG:  return visitSIGN_EXTEND_INREG(N);
1296   case ISD::TRUNCATE:           return visitTRUNCATE(N);
1297   case ISD::BITCAST:            return visitBITCAST(N);
1298   case ISD::BUILD_PAIR:         return visitBUILD_PAIR(N);
1299   case ISD::FADD:               return visitFADD(N);
1300   case ISD::FSUB:               return visitFSUB(N);
1301   case ISD::FMUL:               return visitFMUL(N);
1302   case ISD::FMA:                return visitFMA(N);
1303   case ISD::FDIV:               return visitFDIV(N);
1304   case ISD::FREM:               return visitFREM(N);
1305   case ISD::FCOPYSIGN:          return visitFCOPYSIGN(N);
1306   case ISD::SINT_TO_FP:         return visitSINT_TO_FP(N);
1307   case ISD::UINT_TO_FP:         return visitUINT_TO_FP(N);
1308   case ISD::FP_TO_SINT:         return visitFP_TO_SINT(N);
1309   case ISD::FP_TO_UINT:         return visitFP_TO_UINT(N);
1310   case ISD::FP_ROUND:           return visitFP_ROUND(N);
1311   case ISD::FP_ROUND_INREG:     return visitFP_ROUND_INREG(N);
1312   case ISD::FP_EXTEND:          return visitFP_EXTEND(N);
1313   case ISD::FNEG:               return visitFNEG(N);
1314   case ISD::FABS:               return visitFABS(N);
1315   case ISD::FFLOOR:             return visitFFLOOR(N);
1316   case ISD::FCEIL:              return visitFCEIL(N);
1317   case ISD::FTRUNC:             return visitFTRUNC(N);
1318   case ISD::BRCOND:             return visitBRCOND(N);
1319   case ISD::BR_CC:              return visitBR_CC(N);
1320   case ISD::LOAD:               return visitLOAD(N);
1321   case ISD::STORE:              return visitSTORE(N);
1322   case ISD::INSERT_VECTOR_ELT:  return visitINSERT_VECTOR_ELT(N);
1323   case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1324   case ISD::BUILD_VECTOR:       return visitBUILD_VECTOR(N);
1325   case ISD::CONCAT_VECTORS:     return visitCONCAT_VECTORS(N);
1326   case ISD::EXTRACT_SUBVECTOR:  return visitEXTRACT_SUBVECTOR(N);
1327   case ISD::VECTOR_SHUFFLE:     return visitVECTOR_SHUFFLE(N);
1328   case ISD::INSERT_SUBVECTOR:   return visitINSERT_SUBVECTOR(N);
1329   }
1330   return SDValue();
1331 }
1332
1333 SDValue DAGCombiner::combine(SDNode *N) {
1334   SDValue RV = visit(N);
1335
1336   // If nothing happened, try a target-specific DAG combine.
1337   if (!RV.getNode()) {
1338     assert(N->getOpcode() != ISD::DELETED_NODE &&
1339            "Node was deleted but visit returned NULL!");
1340
1341     if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1342         TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1343
1344       // Expose the DAG combiner to the target combiner impls.
1345       TargetLowering::DAGCombinerInfo
1346         DagCombineInfo(DAG, Level, false, this);
1347
1348       RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1349     }
1350   }
1351
1352   // If nothing happened still, try promoting the operation.
1353   if (!RV.getNode()) {
1354     switch (N->getOpcode()) {
1355     default: break;
1356     case ISD::ADD:
1357     case ISD::SUB:
1358     case ISD::MUL:
1359     case ISD::AND:
1360     case ISD::OR:
1361     case ISD::XOR:
1362       RV = PromoteIntBinOp(SDValue(N, 0));
1363       break;
1364     case ISD::SHL:
1365     case ISD::SRA:
1366     case ISD::SRL:
1367       RV = PromoteIntShiftOp(SDValue(N, 0));
1368       break;
1369     case ISD::SIGN_EXTEND:
1370     case ISD::ZERO_EXTEND:
1371     case ISD::ANY_EXTEND:
1372       RV = PromoteExtend(SDValue(N, 0));
1373       break;
1374     case ISD::LOAD:
1375       if (PromoteLoad(SDValue(N, 0)))
1376         RV = SDValue(N, 0);
1377       break;
1378     }
1379   }
1380
1381   // If N is a commutative binary node, try commuting it to enable more
1382   // sdisel CSE.
1383   if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1384       N->getNumValues() == 1) {
1385     SDValue N0 = N->getOperand(0);
1386     SDValue N1 = N->getOperand(1);
1387
1388     // Constant operands are canonicalized to RHS.
1389     if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1390       SDValue Ops[] = {N1, N0};
1391       SDNode *CSENode;
1392       if (const BinaryWithFlagsSDNode *BinNode =
1393               dyn_cast<BinaryWithFlagsSDNode>(N)) {
1394         CSENode = DAG.getNodeIfExists(
1395             N->getOpcode(), N->getVTList(), Ops, BinNode->hasNoUnsignedWrap(),
1396             BinNode->hasNoSignedWrap(), BinNode->isExact());
1397       } else {
1398         CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops);
1399       }
1400       if (CSENode)
1401         return SDValue(CSENode, 0);
1402     }
1403   }
1404
1405   return RV;
1406 }
1407
1408 /// Given a node, return its input chain if it has one, otherwise return a null
1409 /// sd operand.
1410 static SDValue getInputChainForNode(SDNode *N) {
1411   if (unsigned NumOps = N->getNumOperands()) {
1412     if (N->getOperand(0).getValueType() == MVT::Other)
1413       return N->getOperand(0);
1414     if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1415       return N->getOperand(NumOps-1);
1416     for (unsigned i = 1; i < NumOps-1; ++i)
1417       if (N->getOperand(i).getValueType() == MVT::Other)
1418         return N->getOperand(i);
1419   }
1420   return SDValue();
1421 }
1422
1423 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1424   // If N has two operands, where one has an input chain equal to the other,
1425   // the 'other' chain is redundant.
1426   if (N->getNumOperands() == 2) {
1427     if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1428       return N->getOperand(0);
1429     if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1430       return N->getOperand(1);
1431   }
1432
1433   SmallVector<SDNode *, 8> TFs;     // List of token factors to visit.
1434   SmallVector<SDValue, 8> Ops;    // Ops for replacing token factor.
1435   SmallPtrSet<SDNode*, 16> SeenOps;
1436   bool Changed = false;             // If we should replace this token factor.
1437
1438   // Start out with this token factor.
1439   TFs.push_back(N);
1440
1441   // Iterate through token factors.  The TFs grows when new token factors are
1442   // encountered.
1443   for (unsigned i = 0; i < TFs.size(); ++i) {
1444     SDNode *TF = TFs[i];
1445
1446     // Check each of the operands.
1447     for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
1448       SDValue Op = TF->getOperand(i);
1449
1450       switch (Op.getOpcode()) {
1451       case ISD::EntryToken:
1452         // Entry tokens don't need to be added to the list. They are
1453         // rededundant.
1454         Changed = true;
1455         break;
1456
1457       case ISD::TokenFactor:
1458         if (Op.hasOneUse() &&
1459             std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1460           // Queue up for processing.
1461           TFs.push_back(Op.getNode());
1462           // Clean up in case the token factor is removed.
1463           AddToWorklist(Op.getNode());
1464           Changed = true;
1465           break;
1466         }
1467         // Fall thru
1468
1469       default:
1470         // Only add if it isn't already in the list.
1471         if (SeenOps.insert(Op.getNode()))
1472           Ops.push_back(Op);
1473         else
1474           Changed = true;
1475         break;
1476       }
1477     }
1478   }
1479
1480   SDValue Result;
1481
1482   // If we've change things around then replace token factor.
1483   if (Changed) {
1484     if (Ops.empty()) {
1485       // The entry token is the only possible outcome.
1486       Result = DAG.getEntryNode();
1487     } else {
1488       // New and improved token factor.
1489       Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
1490     }
1491
1492     // Don't add users to work list.
1493     return CombineTo(N, Result, false);
1494   }
1495
1496   return Result;
1497 }
1498
1499 /// MERGE_VALUES can always be eliminated.
1500 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1501   WorklistRemover DeadNodes(*this);
1502   // Replacing results may cause a different MERGE_VALUES to suddenly
1503   // be CSE'd with N, and carry its uses with it. Iterate until no
1504   // uses remain, to ensure that the node can be safely deleted.
1505   // First add the users of this node to the work list so that they
1506   // can be tried again once they have new operands.
1507   AddUsersToWorklist(N);
1508   do {
1509     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1510       DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1511   } while (!N->use_empty());
1512   deleteAndRecombine(N);
1513   return SDValue(N, 0);   // Return N so it doesn't get rechecked!
1514 }
1515
1516 static
1517 SDValue combineShlAddConstant(SDLoc DL, SDValue N0, SDValue N1,
1518                               SelectionDAG &DAG) {
1519   EVT VT = N0.getValueType();
1520   SDValue N00 = N0.getOperand(0);
1521   SDValue N01 = N0.getOperand(1);
1522   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N01);
1523
1524   if (N01C && N00.getOpcode() == ISD::ADD && N00.getNode()->hasOneUse() &&
1525       isa<ConstantSDNode>(N00.getOperand(1))) {
1526     // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1527     N0 = DAG.getNode(ISD::ADD, SDLoc(N0), VT,
1528                      DAG.getNode(ISD::SHL, SDLoc(N00), VT,
1529                                  N00.getOperand(0), N01),
1530                      DAG.getNode(ISD::SHL, SDLoc(N01), VT,
1531                                  N00.getOperand(1), N01));
1532     return DAG.getNode(ISD::ADD, DL, VT, N0, N1);
1533   }
1534
1535   return SDValue();
1536 }
1537
1538 SDValue DAGCombiner::visitADD(SDNode *N) {
1539   SDValue N0 = N->getOperand(0);
1540   SDValue N1 = N->getOperand(1);
1541   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1542   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1543   EVT VT = N0.getValueType();
1544
1545   // fold vector ops
1546   if (VT.isVector()) {
1547     SDValue FoldedVOp = SimplifyVBinOp(N);
1548     if (FoldedVOp.getNode()) return FoldedVOp;
1549
1550     // fold (add x, 0) -> x, vector edition
1551     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1552       return N0;
1553     if (ISD::isBuildVectorAllZeros(N0.getNode()))
1554       return N1;
1555   }
1556
1557   // fold (add x, undef) -> undef
1558   if (N0.getOpcode() == ISD::UNDEF)
1559     return N0;
1560   if (N1.getOpcode() == ISD::UNDEF)
1561     return N1;
1562   // fold (add c1, c2) -> c1+c2
1563   if (N0C && N1C)
1564     return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C);
1565   // canonicalize constant to RHS
1566   if (N0C && !N1C)
1567     return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
1568   // fold (add x, 0) -> x
1569   if (N1C && N1C->isNullValue())
1570     return N0;
1571   // fold (add Sym, c) -> Sym+c
1572   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1573     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1574         GA->getOpcode() == ISD::GlobalAddress)
1575       return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1576                                   GA->getOffset() +
1577                                     (uint64_t)N1C->getSExtValue());
1578   // fold ((c1-A)+c2) -> (c1+c2)-A
1579   if (N1C && N0.getOpcode() == ISD::SUB)
1580     if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
1581       return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1582                          DAG.getConstant(N1C->getAPIntValue()+
1583                                          N0C->getAPIntValue(), VT),
1584                          N0.getOperand(1));
1585   // reassociate add
1586   SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1);
1587   if (RADD.getNode())
1588     return RADD;
1589   // fold ((0-A) + B) -> B-A
1590   if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
1591       cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
1592     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
1593   // fold (A + (0-B)) -> A-B
1594   if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1595       cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
1596     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
1597   // fold (A+(B-A)) -> B
1598   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1599     return N1.getOperand(0);
1600   // fold ((B-A)+A) -> B
1601   if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1602     return N0.getOperand(0);
1603   // fold (A+(B-(A+C))) to (B-C)
1604   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1605       N0 == N1.getOperand(1).getOperand(0))
1606     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1607                        N1.getOperand(1).getOperand(1));
1608   // fold (A+(B-(C+A))) to (B-C)
1609   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1610       N0 == N1.getOperand(1).getOperand(1))
1611     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1612                        N1.getOperand(1).getOperand(0));
1613   // fold (A+((B-A)+or-C)) to (B+or-C)
1614   if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1615       N1.getOperand(0).getOpcode() == ISD::SUB &&
1616       N0 == N1.getOperand(0).getOperand(1))
1617     return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
1618                        N1.getOperand(0).getOperand(0), N1.getOperand(1));
1619
1620   // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1621   if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1622     SDValue N00 = N0.getOperand(0);
1623     SDValue N01 = N0.getOperand(1);
1624     SDValue N10 = N1.getOperand(0);
1625     SDValue N11 = N1.getOperand(1);
1626
1627     if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1628       return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1629                          DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1630                          DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1631   }
1632
1633   if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1634     return SDValue(N, 0);
1635
1636   // fold (a+b) -> (a|b) iff a and b share no bits.
1637   if (VT.isInteger() && !VT.isVector()) {
1638     APInt LHSZero, LHSOne;
1639     APInt RHSZero, RHSOne;
1640     DAG.computeKnownBits(N0, LHSZero, LHSOne);
1641
1642     if (LHSZero.getBoolValue()) {
1643       DAG.computeKnownBits(N1, RHSZero, RHSOne);
1644
1645       // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1646       // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1647       if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){
1648         if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT))
1649           return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1650       }
1651     }
1652   }
1653
1654   // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1655   if (N0.getOpcode() == ISD::SHL && N0.getNode()->hasOneUse()) {
1656     SDValue Result = combineShlAddConstant(SDLoc(N), N0, N1, DAG);
1657     if (Result.getNode()) return Result;
1658   }
1659   if (N1.getOpcode() == ISD::SHL && N1.getNode()->hasOneUse()) {
1660     SDValue Result = combineShlAddConstant(SDLoc(N), N1, N0, DAG);
1661     if (Result.getNode()) return Result;
1662   }
1663
1664   // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1665   if (N1.getOpcode() == ISD::SHL &&
1666       N1.getOperand(0).getOpcode() == ISD::SUB)
1667     if (ConstantSDNode *C =
1668           dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
1669       if (C->getAPIntValue() == 0)
1670         return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1671                            DAG.getNode(ISD::SHL, SDLoc(N), VT,
1672                                        N1.getOperand(0).getOperand(1),
1673                                        N1.getOperand(1)));
1674   if (N0.getOpcode() == ISD::SHL &&
1675       N0.getOperand(0).getOpcode() == ISD::SUB)
1676     if (ConstantSDNode *C =
1677           dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
1678       if (C->getAPIntValue() == 0)
1679         return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1680                            DAG.getNode(ISD::SHL, SDLoc(N), VT,
1681                                        N0.getOperand(0).getOperand(1),
1682                                        N0.getOperand(1)));
1683
1684   if (N1.getOpcode() == ISD::AND) {
1685     SDValue AndOp0 = N1.getOperand(0);
1686     ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1));
1687     unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1688     unsigned DestBits = VT.getScalarType().getSizeInBits();
1689
1690     // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1691     // and similar xforms where the inner op is either ~0 or 0.
1692     if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) {
1693       SDLoc DL(N);
1694       return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1695     }
1696   }
1697
1698   // add (sext i1), X -> sub X, (zext i1)
1699   if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1700       N0.getOperand(0).getValueType() == MVT::i1 &&
1701       !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1702     SDLoc DL(N);
1703     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1704     return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1705   }
1706
1707   return SDValue();
1708 }
1709
1710 SDValue DAGCombiner::visitADDC(SDNode *N) {
1711   SDValue N0 = N->getOperand(0);
1712   SDValue N1 = N->getOperand(1);
1713   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1714   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1715   EVT VT = N0.getValueType();
1716
1717   // If the flag result is dead, turn this into an ADD.
1718   if (!N->hasAnyUseOfValue(1))
1719     return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1720                      DAG.getNode(ISD::CARRY_FALSE,
1721                                  SDLoc(N), MVT::Glue));
1722
1723   // canonicalize constant to RHS.
1724   if (N0C && !N1C)
1725     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1726
1727   // fold (addc x, 0) -> x + no carry out
1728   if (N1C && N1C->isNullValue())
1729     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1730                                         SDLoc(N), MVT::Glue));
1731
1732   // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1733   APInt LHSZero, LHSOne;
1734   APInt RHSZero, RHSOne;
1735   DAG.computeKnownBits(N0, LHSZero, LHSOne);
1736
1737   if (LHSZero.getBoolValue()) {
1738     DAG.computeKnownBits(N1, RHSZero, RHSOne);
1739
1740     // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1741     // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1742     if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1743       return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1744                        DAG.getNode(ISD::CARRY_FALSE,
1745                                    SDLoc(N), MVT::Glue));
1746   }
1747
1748   return SDValue();
1749 }
1750
1751 SDValue DAGCombiner::visitADDE(SDNode *N) {
1752   SDValue N0 = N->getOperand(0);
1753   SDValue N1 = N->getOperand(1);
1754   SDValue CarryIn = N->getOperand(2);
1755   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1756   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1757
1758   // canonicalize constant to RHS
1759   if (N0C && !N1C)
1760     return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1761                        N1, N0, CarryIn);
1762
1763   // fold (adde x, y, false) -> (addc x, y)
1764   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1765     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1766
1767   return SDValue();
1768 }
1769
1770 // Since it may not be valid to emit a fold to zero for vector initializers
1771 // check if we can before folding.
1772 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
1773                              SelectionDAG &DAG,
1774                              bool LegalOperations, bool LegalTypes) {
1775   if (!VT.isVector())
1776     return DAG.getConstant(0, VT);
1777   if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1778     return DAG.getConstant(0, VT);
1779   return SDValue();
1780 }
1781
1782 SDValue DAGCombiner::visitSUB(SDNode *N) {
1783   SDValue N0 = N->getOperand(0);
1784   SDValue N1 = N->getOperand(1);
1785   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1786   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1787   ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr :
1788     dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1789   EVT VT = N0.getValueType();
1790
1791   // fold vector ops
1792   if (VT.isVector()) {
1793     SDValue FoldedVOp = SimplifyVBinOp(N);
1794     if (FoldedVOp.getNode()) return FoldedVOp;
1795
1796     // fold (sub x, 0) -> x, vector edition
1797     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1798       return N0;
1799   }
1800
1801   // fold (sub x, x) -> 0
1802   // FIXME: Refactor this and xor and other similar operations together.
1803   if (N0 == N1)
1804     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
1805   // fold (sub c1, c2) -> c1-c2
1806   if (N0C && N1C)
1807     return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C);
1808   // fold (sub x, c) -> (add x, -c)
1809   if (N1C)
1810     return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0,
1811                        DAG.getConstant(-N1C->getAPIntValue(), VT));
1812   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1813   if (N0C && N0C->isAllOnesValue())
1814     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
1815   // fold A-(A-B) -> B
1816   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1817     return N1.getOperand(1);
1818   // fold (A+B)-A -> B
1819   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1820     return N0.getOperand(1);
1821   // fold (A+B)-B -> A
1822   if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1823     return N0.getOperand(0);
1824   // fold C2-(A+C1) -> (C2-C1)-A
1825   if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1826     SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1827                                    VT);
1828     return DAG.getNode(ISD::SUB, SDLoc(N), VT, NewC,
1829                        N1.getOperand(0));
1830   }
1831   // fold ((A+(B+or-C))-B) -> A+or-C
1832   if (N0.getOpcode() == ISD::ADD &&
1833       (N0.getOperand(1).getOpcode() == ISD::SUB ||
1834        N0.getOperand(1).getOpcode() == ISD::ADD) &&
1835       N0.getOperand(1).getOperand(0) == N1)
1836     return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
1837                        N0.getOperand(0), N0.getOperand(1).getOperand(1));
1838   // fold ((A+(C+B))-B) -> A+C
1839   if (N0.getOpcode() == ISD::ADD &&
1840       N0.getOperand(1).getOpcode() == ISD::ADD &&
1841       N0.getOperand(1).getOperand(1) == N1)
1842     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1843                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1844   // fold ((A-(B-C))-C) -> A-B
1845   if (N0.getOpcode() == ISD::SUB &&
1846       N0.getOperand(1).getOpcode() == ISD::SUB &&
1847       N0.getOperand(1).getOperand(1) == N1)
1848     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1849                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1850
1851   // If either operand of a sub is undef, the result is undef
1852   if (N0.getOpcode() == ISD::UNDEF)
1853     return N0;
1854   if (N1.getOpcode() == ISD::UNDEF)
1855     return N1;
1856
1857   // If the relocation model supports it, consider symbol offsets.
1858   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1859     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1860       // fold (sub Sym, c) -> Sym-c
1861       if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1862         return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1863                                     GA->getOffset() -
1864                                       (uint64_t)N1C->getSExtValue());
1865       // fold (sub Sym+c1, Sym+c2) -> c1-c2
1866       if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1867         if (GA->getGlobal() == GB->getGlobal())
1868           return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1869                                  VT);
1870     }
1871
1872   return SDValue();
1873 }
1874
1875 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1876   SDValue N0 = N->getOperand(0);
1877   SDValue N1 = N->getOperand(1);
1878   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1879   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1880   EVT VT = N0.getValueType();
1881
1882   // If the flag result is dead, turn this into an SUB.
1883   if (!N->hasAnyUseOfValue(1))
1884     return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1885                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1886                                  MVT::Glue));
1887
1888   // fold (subc x, x) -> 0 + no borrow
1889   if (N0 == N1)
1890     return CombineTo(N, DAG.getConstant(0, VT),
1891                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1892                                  MVT::Glue));
1893
1894   // fold (subc x, 0) -> x + no borrow
1895   if (N1C && N1C->isNullValue())
1896     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1897                                         MVT::Glue));
1898
1899   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1900   if (N0C && N0C->isAllOnesValue())
1901     return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
1902                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1903                                  MVT::Glue));
1904
1905   return SDValue();
1906 }
1907
1908 SDValue DAGCombiner::visitSUBE(SDNode *N) {
1909   SDValue N0 = N->getOperand(0);
1910   SDValue N1 = N->getOperand(1);
1911   SDValue CarryIn = N->getOperand(2);
1912
1913   // fold (sube x, y, false) -> (subc x, y)
1914   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1915     return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
1916
1917   return SDValue();
1918 }
1919
1920 SDValue DAGCombiner::visitMUL(SDNode *N) {
1921   SDValue N0 = N->getOperand(0);
1922   SDValue N1 = N->getOperand(1);
1923   EVT VT = N0.getValueType();
1924
1925   // fold (mul x, undef) -> 0
1926   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1927     return DAG.getConstant(0, VT);
1928
1929   bool N0IsConst = false;
1930   bool N1IsConst = false;
1931   APInt ConstValue0, ConstValue1;
1932   // fold vector ops
1933   if (VT.isVector()) {
1934     SDValue FoldedVOp = SimplifyVBinOp(N);
1935     if (FoldedVOp.getNode()) return FoldedVOp;
1936
1937     N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
1938     N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
1939   } else {
1940     N0IsConst = dyn_cast<ConstantSDNode>(N0) != nullptr;
1941     ConstValue0 = N0IsConst ? (dyn_cast<ConstantSDNode>(N0))->getAPIntValue()
1942                             : APInt();
1943     N1IsConst = dyn_cast<ConstantSDNode>(N1) != nullptr;
1944     ConstValue1 = N1IsConst ? (dyn_cast<ConstantSDNode>(N1))->getAPIntValue()
1945                             : APInt();
1946   }
1947
1948   // fold (mul c1, c2) -> c1*c2
1949   if (N0IsConst && N1IsConst)
1950     return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0.getNode(), N1.getNode());
1951
1952   // canonicalize constant to RHS
1953   if (N0IsConst && !N1IsConst)
1954     return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
1955   // fold (mul x, 0) -> 0
1956   if (N1IsConst && ConstValue1 == 0)
1957     return N1;
1958   // We require a splat of the entire scalar bit width for non-contiguous
1959   // bit patterns.
1960   bool IsFullSplat =
1961     ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
1962   // fold (mul x, 1) -> x
1963   if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
1964     return N0;
1965   // fold (mul x, -1) -> 0-x
1966   if (N1IsConst && ConstValue1.isAllOnesValue())
1967     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1968                        DAG.getConstant(0, VT), N0);
1969   // fold (mul x, (1 << c)) -> x << c
1970   if (N1IsConst && ConstValue1.isPowerOf2() && IsFullSplat)
1971     return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1972                        DAG.getConstant(ConstValue1.logBase2(),
1973                                        getShiftAmountTy(N0.getValueType())));
1974   // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
1975   if (N1IsConst && (-ConstValue1).isPowerOf2() && IsFullSplat) {
1976     unsigned Log2Val = (-ConstValue1).logBase2();
1977     // FIXME: If the input is something that is easily negated (e.g. a
1978     // single-use add), we should put the negate there.
1979     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1980                        DAG.getConstant(0, VT),
1981                        DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1982                             DAG.getConstant(Log2Val,
1983                                       getShiftAmountTy(N0.getValueType()))));
1984   }
1985
1986   APInt Val;
1987   // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
1988   if (N1IsConst && N0.getOpcode() == ISD::SHL &&
1989       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1990                      isa<ConstantSDNode>(N0.getOperand(1)))) {
1991     SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
1992                              N1, N0.getOperand(1));
1993     AddToWorklist(C3.getNode());
1994     return DAG.getNode(ISD::MUL, SDLoc(N), VT,
1995                        N0.getOperand(0), C3);
1996   }
1997
1998   // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
1999   // use.
2000   {
2001     SDValue Sh(nullptr,0), Y(nullptr,0);
2002     // Check for both (mul (shl X, C), Y)  and  (mul Y, (shl X, C)).
2003     if (N0.getOpcode() == ISD::SHL &&
2004         (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2005                        isa<ConstantSDNode>(N0.getOperand(1))) &&
2006         N0.getNode()->hasOneUse()) {
2007       Sh = N0; Y = N1;
2008     } else if (N1.getOpcode() == ISD::SHL &&
2009                isa<ConstantSDNode>(N1.getOperand(1)) &&
2010                N1.getNode()->hasOneUse()) {
2011       Sh = N1; Y = N0;
2012     }
2013
2014     if (Sh.getNode()) {
2015       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2016                                 Sh.getOperand(0), Y);
2017       return DAG.getNode(ISD::SHL, SDLoc(N), VT,
2018                          Mul, Sh.getOperand(1));
2019     }
2020   }
2021
2022   // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
2023   if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
2024       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2025                      isa<ConstantSDNode>(N0.getOperand(1))))
2026     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
2027                        DAG.getNode(ISD::MUL, SDLoc(N0), VT,
2028                                    N0.getOperand(0), N1),
2029                        DAG.getNode(ISD::MUL, SDLoc(N1), VT,
2030                                    N0.getOperand(1), N1));
2031
2032   // reassociate mul
2033   SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1);
2034   if (RMUL.getNode())
2035     return RMUL;
2036
2037   return SDValue();
2038 }
2039
2040 SDValue DAGCombiner::visitSDIV(SDNode *N) {
2041   SDValue N0 = N->getOperand(0);
2042   SDValue N1 = N->getOperand(1);
2043   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2044   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2045   EVT VT = N->getValueType(0);
2046
2047   // fold vector ops
2048   if (VT.isVector()) {
2049     SDValue FoldedVOp = SimplifyVBinOp(N);
2050     if (FoldedVOp.getNode()) return FoldedVOp;
2051   }
2052
2053   // fold (sdiv c1, c2) -> c1/c2
2054   if (N0C && N1C && !N1C->isNullValue())
2055     return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C);
2056   // fold (sdiv X, 1) -> X
2057   if (N1C && N1C->getAPIntValue() == 1LL)
2058     return N0;
2059   // fold (sdiv X, -1) -> 0-X
2060   if (N1C && N1C->isAllOnesValue())
2061     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
2062                        DAG.getConstant(0, VT), N0);
2063   // If we know the sign bits of both operands are zero, strength reduce to a
2064   // udiv instead.  Handles (X&15) /s 4 -> X&15 >> 2
2065   if (!VT.isVector()) {
2066     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2067       return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
2068                          N0, N1);
2069   }
2070
2071   // fold (sdiv X, pow2) -> simple ops after legalize
2072   if (N1C && !N1C->isNullValue() && (N1C->getAPIntValue().isPowerOf2() ||
2073                                      (-N1C->getAPIntValue()).isPowerOf2())) {
2074     // If dividing by powers of two is cheap, then don't perform the following
2075     // fold.
2076     if (TLI.isPow2SDivCheap())
2077       return SDValue();
2078
2079     // Target-specific implementation of sdiv x, pow2.
2080     SDValue Res = BuildSDIVPow2(N);
2081     if (Res.getNode())
2082       return Res;
2083
2084     unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
2085
2086     // Splat the sign bit into the register
2087     SDValue SGN =
2088         DAG.getNode(ISD::SRA, SDLoc(N), VT, N0,
2089                     DAG.getConstant(VT.getScalarSizeInBits() - 1,
2090                                     getShiftAmountTy(N0.getValueType())));
2091     AddToWorklist(SGN.getNode());
2092
2093     // Add (N0 < 0) ? abs2 - 1 : 0;
2094     SDValue SRL =
2095         DAG.getNode(ISD::SRL, SDLoc(N), VT, SGN,
2096                     DAG.getConstant(VT.getScalarSizeInBits() - lg2,
2097                                     getShiftAmountTy(SGN.getValueType())));
2098     SDValue ADD = DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, SRL);
2099     AddToWorklist(SRL.getNode());
2100     AddToWorklist(ADD.getNode());    // Divide by pow2
2101     SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), VT, ADD,
2102                   DAG.getConstant(lg2, getShiftAmountTy(ADD.getValueType())));
2103
2104     // If we're dividing by a positive value, we're done.  Otherwise, we must
2105     // negate the result.
2106     if (N1C->getAPIntValue().isNonNegative())
2107       return SRA;
2108
2109     AddToWorklist(SRA.getNode());
2110     return DAG.getNode(ISD::SUB, SDLoc(N), VT, DAG.getConstant(0, VT), SRA);
2111   }
2112
2113   // if integer divide is expensive and we satisfy the requirements, emit an
2114   // alternate sequence.
2115   if (N1C && !TLI.isIntDivCheap()) {
2116     SDValue Op = BuildSDIV(N);
2117     if (Op.getNode()) return Op;
2118   }
2119
2120   // undef / X -> 0
2121   if (N0.getOpcode() == ISD::UNDEF)
2122     return DAG.getConstant(0, VT);
2123   // X / undef -> undef
2124   if (N1.getOpcode() == ISD::UNDEF)
2125     return N1;
2126
2127   return SDValue();
2128 }
2129
2130 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2131   SDValue N0 = N->getOperand(0);
2132   SDValue N1 = N->getOperand(1);
2133   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2134   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2135   EVT VT = N->getValueType(0);
2136
2137   // fold vector ops
2138   if (VT.isVector()) {
2139     SDValue FoldedVOp = SimplifyVBinOp(N);
2140     if (FoldedVOp.getNode()) return FoldedVOp;
2141   }
2142
2143   // fold (udiv c1, c2) -> c1/c2
2144   if (N0C && N1C && !N1C->isNullValue())
2145     return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C);
2146   // fold (udiv x, (1 << c)) -> x >>u c
2147   if (N1C && N1C->getAPIntValue().isPowerOf2())
2148     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0,
2149                        DAG.getConstant(N1C->getAPIntValue().logBase2(),
2150                                        getShiftAmountTy(N0.getValueType())));
2151   // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2152   if (N1.getOpcode() == ISD::SHL) {
2153     if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2154       if (SHC->getAPIntValue().isPowerOf2()) {
2155         EVT ADDVT = N1.getOperand(1).getValueType();
2156         SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N), ADDVT,
2157                                   N1.getOperand(1),
2158                                   DAG.getConstant(SHC->getAPIntValue()
2159                                                                   .logBase2(),
2160                                                   ADDVT));
2161         AddToWorklist(Add.getNode());
2162         return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, Add);
2163       }
2164     }
2165   }
2166   // fold (udiv x, c) -> alternate
2167   if (N1C && !TLI.isIntDivCheap()) {
2168     SDValue Op = BuildUDIV(N);
2169     if (Op.getNode()) return Op;
2170   }
2171
2172   // undef / X -> 0
2173   if (N0.getOpcode() == ISD::UNDEF)
2174     return DAG.getConstant(0, VT);
2175   // X / undef -> undef
2176   if (N1.getOpcode() == ISD::UNDEF)
2177     return N1;
2178
2179   return SDValue();
2180 }
2181
2182 SDValue DAGCombiner::visitSREM(SDNode *N) {
2183   SDValue N0 = N->getOperand(0);
2184   SDValue N1 = N->getOperand(1);
2185   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2186   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2187   EVT VT = N->getValueType(0);
2188
2189   // fold (srem c1, c2) -> c1%c2
2190   if (N0C && N1C && !N1C->isNullValue())
2191     return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C);
2192   // If we know the sign bits of both operands are zero, strength reduce to a
2193   // urem instead.  Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2194   if (!VT.isVector()) {
2195     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2196       return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
2197   }
2198
2199   // If X/C can be simplified by the division-by-constant logic, lower
2200   // X%C to the equivalent of X-X/C*C.
2201   if (N1C && !N1C->isNullValue()) {
2202     SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
2203     AddToWorklist(Div.getNode());
2204     SDValue OptimizedDiv = combine(Div.getNode());
2205     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2206       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2207                                 OptimizedDiv, N1);
2208       SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2209       AddToWorklist(Mul.getNode());
2210       return Sub;
2211     }
2212   }
2213
2214   // undef % X -> 0
2215   if (N0.getOpcode() == ISD::UNDEF)
2216     return DAG.getConstant(0, VT);
2217   // X % undef -> undef
2218   if (N1.getOpcode() == ISD::UNDEF)
2219     return N1;
2220
2221   return SDValue();
2222 }
2223
2224 SDValue DAGCombiner::visitUREM(SDNode *N) {
2225   SDValue N0 = N->getOperand(0);
2226   SDValue N1 = N->getOperand(1);
2227   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2228   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2229   EVT VT = N->getValueType(0);
2230
2231   // fold (urem c1, c2) -> c1%c2
2232   if (N0C && N1C && !N1C->isNullValue())
2233     return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C);
2234   // fold (urem x, pow2) -> (and x, pow2-1)
2235   if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
2236     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0,
2237                        DAG.getConstant(N1C->getAPIntValue()-1,VT));
2238   // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2239   if (N1.getOpcode() == ISD::SHL) {
2240     if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2241       if (SHC->getAPIntValue().isPowerOf2()) {
2242         SDValue Add =
2243           DAG.getNode(ISD::ADD, SDLoc(N), VT, N1,
2244                  DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
2245                                  VT));
2246         AddToWorklist(Add.getNode());
2247         return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, Add);
2248       }
2249     }
2250   }
2251
2252   // If X/C can be simplified by the division-by-constant logic, lower
2253   // X%C to the equivalent of X-X/C*C.
2254   if (N1C && !N1C->isNullValue()) {
2255     SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
2256     AddToWorklist(Div.getNode());
2257     SDValue OptimizedDiv = combine(Div.getNode());
2258     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2259       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2260                                 OptimizedDiv, N1);
2261       SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2262       AddToWorklist(Mul.getNode());
2263       return Sub;
2264     }
2265   }
2266
2267   // undef % X -> 0
2268   if (N0.getOpcode() == ISD::UNDEF)
2269     return DAG.getConstant(0, VT);
2270   // X % undef -> undef
2271   if (N1.getOpcode() == ISD::UNDEF)
2272     return N1;
2273
2274   return SDValue();
2275 }
2276
2277 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2278   SDValue N0 = N->getOperand(0);
2279   SDValue N1 = N->getOperand(1);
2280   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2281   EVT VT = N->getValueType(0);
2282   SDLoc DL(N);
2283
2284   // fold (mulhs x, 0) -> 0
2285   if (N1C && N1C->isNullValue())
2286     return N1;
2287   // fold (mulhs x, 1) -> (sra x, size(x)-1)
2288   if (N1C && N1C->getAPIntValue() == 1)
2289     return DAG.getNode(ISD::SRA, SDLoc(N), N0.getValueType(), N0,
2290                        DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2291                                        getShiftAmountTy(N0.getValueType())));
2292   // fold (mulhs x, undef) -> 0
2293   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2294     return DAG.getConstant(0, VT);
2295
2296   // If the type twice as wide is legal, transform the mulhs to a wider multiply
2297   // plus a shift.
2298   if (VT.isSimple() && !VT.isVector()) {
2299     MVT Simple = VT.getSimpleVT();
2300     unsigned SimpleSize = Simple.getSizeInBits();
2301     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2302     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2303       N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2304       N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2305       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2306       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2307             DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2308       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2309     }
2310   }
2311
2312   return SDValue();
2313 }
2314
2315 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2316   SDValue N0 = N->getOperand(0);
2317   SDValue N1 = N->getOperand(1);
2318   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2319   EVT VT = N->getValueType(0);
2320   SDLoc DL(N);
2321
2322   // fold (mulhu x, 0) -> 0
2323   if (N1C && N1C->isNullValue())
2324     return N1;
2325   // fold (mulhu x, 1) -> 0
2326   if (N1C && N1C->getAPIntValue() == 1)
2327     return DAG.getConstant(0, N0.getValueType());
2328   // fold (mulhu x, undef) -> 0
2329   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2330     return DAG.getConstant(0, VT);
2331
2332   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2333   // plus a shift.
2334   if (VT.isSimple() && !VT.isVector()) {
2335     MVT Simple = VT.getSimpleVT();
2336     unsigned SimpleSize = Simple.getSizeInBits();
2337     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2338     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2339       N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2340       N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2341       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2342       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2343             DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2344       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2345     }
2346   }
2347
2348   return SDValue();
2349 }
2350
2351 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp
2352 /// give the opcodes for the two computations that are being performed. Return
2353 /// true if a simplification was made.
2354 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2355                                                 unsigned HiOp) {
2356   // If the high half is not needed, just compute the low half.
2357   bool HiExists = N->hasAnyUseOfValue(1);
2358   if (!HiExists &&
2359       (!LegalOperations ||
2360        TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
2361     SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2362     return CombineTo(N, Res, Res);
2363   }
2364
2365   // If the low half is not needed, just compute the high half.
2366   bool LoExists = N->hasAnyUseOfValue(0);
2367   if (!LoExists &&
2368       (!LegalOperations ||
2369        TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2370     SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2371     return CombineTo(N, Res, Res);
2372   }
2373
2374   // If both halves are used, return as it is.
2375   if (LoExists && HiExists)
2376     return SDValue();
2377
2378   // If the two computed results can be simplified separately, separate them.
2379   if (LoExists) {
2380     SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2381     AddToWorklist(Lo.getNode());
2382     SDValue LoOpt = combine(Lo.getNode());
2383     if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2384         (!LegalOperations ||
2385          TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2386       return CombineTo(N, LoOpt, LoOpt);
2387   }
2388
2389   if (HiExists) {
2390     SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2391     AddToWorklist(Hi.getNode());
2392     SDValue HiOpt = combine(Hi.getNode());
2393     if (HiOpt.getNode() && HiOpt != Hi &&
2394         (!LegalOperations ||
2395          TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2396       return CombineTo(N, HiOpt, HiOpt);
2397   }
2398
2399   return SDValue();
2400 }
2401
2402 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2403   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
2404   if (Res.getNode()) return Res;
2405
2406   EVT VT = N->getValueType(0);
2407   SDLoc DL(N);
2408
2409   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2410   // plus a shift.
2411   if (VT.isSimple() && !VT.isVector()) {
2412     MVT Simple = VT.getSimpleVT();
2413     unsigned SimpleSize = Simple.getSizeInBits();
2414     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2415     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2416       SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2417       SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2418       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2419       // Compute the high part as N1.
2420       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2421             DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2422       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2423       // Compute the low part as N0.
2424       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2425       return CombineTo(N, Lo, Hi);
2426     }
2427   }
2428
2429   return SDValue();
2430 }
2431
2432 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2433   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
2434   if (Res.getNode()) return Res;
2435
2436   EVT VT = N->getValueType(0);
2437   SDLoc DL(N);
2438
2439   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2440   // plus a shift.
2441   if (VT.isSimple() && !VT.isVector()) {
2442     MVT Simple = VT.getSimpleVT();
2443     unsigned SimpleSize = Simple.getSizeInBits();
2444     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2445     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2446       SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2447       SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2448       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2449       // Compute the high part as N1.
2450       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2451             DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2452       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2453       // Compute the low part as N0.
2454       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2455       return CombineTo(N, Lo, Hi);
2456     }
2457   }
2458
2459   return SDValue();
2460 }
2461
2462 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2463   // (smulo x, 2) -> (saddo x, x)
2464   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2465     if (C2->getAPIntValue() == 2)
2466       return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2467                          N->getOperand(0), N->getOperand(0));
2468
2469   return SDValue();
2470 }
2471
2472 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2473   // (umulo x, 2) -> (uaddo x, x)
2474   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2475     if (C2->getAPIntValue() == 2)
2476       return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2477                          N->getOperand(0), N->getOperand(0));
2478
2479   return SDValue();
2480 }
2481
2482 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2483   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
2484   if (Res.getNode()) return Res;
2485
2486   return SDValue();
2487 }
2488
2489 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2490   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
2491   if (Res.getNode()) return Res;
2492
2493   return SDValue();
2494 }
2495
2496 /// If this is a binary operator with two operands of the same opcode, try to
2497 /// simplify it.
2498 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2499   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2500   EVT VT = N0.getValueType();
2501   assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2502
2503   // Bail early if none of these transforms apply.
2504   if (N0.getNode()->getNumOperands() == 0) return SDValue();
2505
2506   // For each of OP in AND/OR/XOR:
2507   // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2508   // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2509   // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2510   // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2511   //
2512   // do not sink logical op inside of a vector extend, since it may combine
2513   // into a vsetcc.
2514   EVT Op0VT = N0.getOperand(0).getValueType();
2515   if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2516        N0.getOpcode() == ISD::SIGN_EXTEND ||
2517        // Avoid infinite looping with PromoteIntBinOp.
2518        (N0.getOpcode() == ISD::ANY_EXTEND &&
2519         (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2520        (N0.getOpcode() == ISD::TRUNCATE &&
2521         (!TLI.isZExtFree(VT, Op0VT) ||
2522          !TLI.isTruncateFree(Op0VT, VT)) &&
2523         TLI.isTypeLegal(Op0VT))) &&
2524       !VT.isVector() &&
2525       Op0VT == N1.getOperand(0).getValueType() &&
2526       (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2527     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2528                                  N0.getOperand(0).getValueType(),
2529                                  N0.getOperand(0), N1.getOperand(0));
2530     AddToWorklist(ORNode.getNode());
2531     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2532   }
2533
2534   // For each of OP in SHL/SRL/SRA/AND...
2535   //   fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2536   //   fold (or  (OP x, z), (OP y, z)) -> (OP (or  x, y), z)
2537   //   fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2538   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2539        N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2540       N0.getOperand(1) == N1.getOperand(1)) {
2541     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2542                                  N0.getOperand(0).getValueType(),
2543                                  N0.getOperand(0), N1.getOperand(0));
2544     AddToWorklist(ORNode.getNode());
2545     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2546                        ORNode, N0.getOperand(1));
2547   }
2548
2549   // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2550   // Only perform this optimization after type legalization and before
2551   // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2552   // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2553   // we don't want to undo this promotion.
2554   // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2555   // on scalars.
2556   if ((N0.getOpcode() == ISD::BITCAST ||
2557        N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2558       Level == AfterLegalizeTypes) {
2559     SDValue In0 = N0.getOperand(0);
2560     SDValue In1 = N1.getOperand(0);
2561     EVT In0Ty = In0.getValueType();
2562     EVT In1Ty = In1.getValueType();
2563     SDLoc DL(N);
2564     // If both incoming values are integers, and the original types are the
2565     // same.
2566     if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2567       SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2568       SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2569       AddToWorklist(Op.getNode());
2570       return BC;
2571     }
2572   }
2573
2574   // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2575   // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2576   // If both shuffles use the same mask, and both shuffle within a single
2577   // vector, then it is worthwhile to move the swizzle after the operation.
2578   // The type-legalizer generates this pattern when loading illegal
2579   // vector types from memory. In many cases this allows additional shuffle
2580   // optimizations.
2581   // There are other cases where moving the shuffle after the xor/and/or
2582   // is profitable even if shuffles don't perform a swizzle.
2583   // If both shuffles use the same mask, and both shuffles have the same first
2584   // or second operand, then it might still be profitable to move the shuffle
2585   // after the xor/and/or operation.
2586   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
2587     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2588     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2589
2590     assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
2591            "Inputs to shuffles are not the same type");
2592
2593     // Check that both shuffles use the same mask. The masks are known to be of
2594     // the same length because the result vector type is the same.
2595     // Check also that shuffles have only one use to avoid introducing extra
2596     // instructions.
2597     if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2598         SVN0->getMask().equals(SVN1->getMask())) {
2599       SDValue ShOp = N0->getOperand(1);
2600
2601       // Don't try to fold this node if it requires introducing a
2602       // build vector of all zeros that might be illegal at this stage.
2603       if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2604         if (!LegalTypes)
2605           ShOp = DAG.getConstant(0, VT);
2606         else
2607           ShOp = SDValue();
2608       }
2609
2610       // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2611       // (OR  (shuf (A, C), shuf (B, C)) -> shuf (OR  (A, B), C)
2612       // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2613       if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2614         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2615                                       N0->getOperand(0), N1->getOperand(0));
2616         AddToWorklist(NewNode.getNode());
2617         return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2618                                     &SVN0->getMask()[0]);
2619       }
2620
2621       // Don't try to fold this node if it requires introducing a
2622       // build vector of all zeros that might be illegal at this stage.
2623       ShOp = N0->getOperand(0);
2624       if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2625         if (!LegalTypes)
2626           ShOp = DAG.getConstant(0, VT);
2627         else
2628           ShOp = SDValue();
2629       }
2630
2631       // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2632       // (OR  (shuf (C, A), shuf (C, B)) -> shuf (C, OR  (A, B))
2633       // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2634       if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2635         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2636                                       N0->getOperand(1), N1->getOperand(1));
2637         AddToWorklist(NewNode.getNode());
2638         return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2639                                     &SVN0->getMask()[0]);
2640       }
2641     }
2642   }
2643
2644   return SDValue();
2645 }
2646
2647 SDValue DAGCombiner::visitAND(SDNode *N) {
2648   SDValue N0 = N->getOperand(0);
2649   SDValue N1 = N->getOperand(1);
2650   SDValue LL, LR, RL, RR, CC0, CC1;
2651   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2652   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2653   EVT VT = N1.getValueType();
2654   unsigned BitWidth = VT.getScalarType().getSizeInBits();
2655
2656   // fold vector ops
2657   if (VT.isVector()) {
2658     SDValue FoldedVOp = SimplifyVBinOp(N);
2659     if (FoldedVOp.getNode()) return FoldedVOp;
2660
2661     // fold (and x, 0) -> 0, vector edition
2662     if (ISD::isBuildVectorAllZeros(N0.getNode()))
2663       return N0;
2664     if (ISD::isBuildVectorAllZeros(N1.getNode()))
2665       return N1;
2666
2667     // fold (and x, -1) -> x, vector edition
2668     if (ISD::isBuildVectorAllOnes(N0.getNode()))
2669       return N1;
2670     if (ISD::isBuildVectorAllOnes(N1.getNode()))
2671       return N0;
2672   }
2673
2674   // fold (and x, undef) -> 0
2675   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2676     return DAG.getConstant(0, VT);
2677   // fold (and c1, c2) -> c1&c2
2678   if (N0C && N1C)
2679     return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C);
2680   // canonicalize constant to RHS
2681   if (N0C && !N1C)
2682     return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
2683   // fold (and x, -1) -> x
2684   if (N1C && N1C->isAllOnesValue())
2685     return N0;
2686   // if (and x, c) is known to be zero, return 0
2687   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2688                                    APInt::getAllOnesValue(BitWidth)))
2689     return DAG.getConstant(0, VT);
2690   // reassociate and
2691   SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1);
2692   if (RAND.getNode())
2693     return RAND;
2694   // fold (and (or x, C), D) -> D if (C & D) == D
2695   if (N1C && N0.getOpcode() == ISD::OR)
2696     if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2697       if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2698         return N1;
2699   // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2700   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2701     SDValue N0Op0 = N0.getOperand(0);
2702     APInt Mask = ~N1C->getAPIntValue();
2703     Mask = Mask.trunc(N0Op0.getValueSizeInBits());
2704     if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2705       SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
2706                                  N0.getValueType(), N0Op0);
2707
2708       // Replace uses of the AND with uses of the Zero extend node.
2709       CombineTo(N, Zext);
2710
2711       // We actually want to replace all uses of the any_extend with the
2712       // zero_extend, to avoid duplicating things.  This will later cause this
2713       // AND to be folded.
2714       CombineTo(N0.getNode(), Zext);
2715       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2716     }
2717   }
2718   // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
2719   // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2720   // already be zero by virtue of the width of the base type of the load.
2721   //
2722   // the 'X' node here can either be nothing or an extract_vector_elt to catch
2723   // more cases.
2724   if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2725        N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2726       N0.getOpcode() == ISD::LOAD) {
2727     LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2728                                          N0 : N0.getOperand(0) );
2729
2730     // Get the constant (if applicable) the zero'th operand is being ANDed with.
2731     // This can be a pure constant or a vector splat, in which case we treat the
2732     // vector as a scalar and use the splat value.
2733     APInt Constant = APInt::getNullValue(1);
2734     if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2735       Constant = C->getAPIntValue();
2736     } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2737       APInt SplatValue, SplatUndef;
2738       unsigned SplatBitSize;
2739       bool HasAnyUndefs;
2740       bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2741                                              SplatBitSize, HasAnyUndefs);
2742       if (IsSplat) {
2743         // Undef bits can contribute to a possible optimisation if set, so
2744         // set them.
2745         SplatValue |= SplatUndef;
2746
2747         // The splat value may be something like "0x00FFFFFF", which means 0 for
2748         // the first vector value and FF for the rest, repeating. We need a mask
2749         // that will apply equally to all members of the vector, so AND all the
2750         // lanes of the constant together.
2751         EVT VT = Vector->getValueType(0);
2752         unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
2753
2754         // If the splat value has been compressed to a bitlength lower
2755         // than the size of the vector lane, we need to re-expand it to
2756         // the lane size.
2757         if (BitWidth > SplatBitSize)
2758           for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
2759                SplatBitSize < BitWidth;
2760                SplatBitSize = SplatBitSize * 2)
2761             SplatValue |= SplatValue.shl(SplatBitSize);
2762
2763         Constant = APInt::getAllOnesValue(BitWidth);
2764         for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
2765           Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
2766       }
2767     }
2768
2769     // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
2770     // actually legal and isn't going to get expanded, else this is a false
2771     // optimisation.
2772     bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
2773                                                     Load->getMemoryVT());
2774
2775     // Resize the constant to the same size as the original memory access before
2776     // extension. If it is still the AllOnesValue then this AND is completely
2777     // unneeded.
2778     Constant =
2779       Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
2780
2781     bool B;
2782     switch (Load->getExtensionType()) {
2783     default: B = false; break;
2784     case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
2785     case ISD::ZEXTLOAD:
2786     case ISD::NON_EXTLOAD: B = true; break;
2787     }
2788
2789     if (B && Constant.isAllOnesValue()) {
2790       // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
2791       // preserve semantics once we get rid of the AND.
2792       SDValue NewLoad(Load, 0);
2793       if (Load->getExtensionType() == ISD::EXTLOAD) {
2794         NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
2795                               Load->getValueType(0), SDLoc(Load),
2796                               Load->getChain(), Load->getBasePtr(),
2797                               Load->getOffset(), Load->getMemoryVT(),
2798                               Load->getMemOperand());
2799         // Replace uses of the EXTLOAD with the new ZEXTLOAD.
2800         if (Load->getNumValues() == 3) {
2801           // PRE/POST_INC loads have 3 values.
2802           SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
2803                            NewLoad.getValue(2) };
2804           CombineTo(Load, To, 3, true);
2805         } else {
2806           CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
2807         }
2808       }
2809
2810       // Fold the AND away, taking care not to fold to the old load node if we
2811       // replaced it.
2812       CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
2813
2814       return SDValue(N, 0); // Return N so it doesn't get rechecked!
2815     }
2816   }
2817   // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2818   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2819     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2820     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2821
2822     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2823         LL.getValueType().isInteger()) {
2824       // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2825       if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
2826         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2827                                      LR.getValueType(), LL, RL);
2828         AddToWorklist(ORNode.getNode());
2829         return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2830       }
2831       // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2832       if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
2833         SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2834                                       LR.getValueType(), LL, RL);
2835         AddToWorklist(ANDNode.getNode());
2836         return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
2837       }
2838       // fold (and (setgt X,  -1), (setgt Y,  -1)) -> (setgt (or X, Y), -1)
2839       if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
2840         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2841                                      LR.getValueType(), LL, RL);
2842         AddToWorklist(ORNode.getNode());
2843         return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2844       }
2845     }
2846     // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2847     if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2848         Op0 == Op1 && LL.getValueType().isInteger() &&
2849       Op0 == ISD::SETNE && ((cast<ConstantSDNode>(LR)->isNullValue() &&
2850                                  cast<ConstantSDNode>(RR)->isAllOnesValue()) ||
2851                                 (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
2852                                  cast<ConstantSDNode>(RR)->isNullValue()))) {
2853       SDValue ADDNode = DAG.getNode(ISD::ADD, SDLoc(N0), LL.getValueType(),
2854                                     LL, DAG.getConstant(1, LL.getValueType()));
2855       AddToWorklist(ADDNode.getNode());
2856       return DAG.getSetCC(SDLoc(N), VT, ADDNode,
2857                           DAG.getConstant(2, LL.getValueType()), ISD::SETUGE);
2858     }
2859     // canonicalize equivalent to ll == rl
2860     if (LL == RR && LR == RL) {
2861       Op1 = ISD::getSetCCSwappedOperands(Op1);
2862       std::swap(RL, RR);
2863     }
2864     if (LL == RL && LR == RR) {
2865       bool isInteger = LL.getValueType().isInteger();
2866       ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2867       if (Result != ISD::SETCC_INVALID &&
2868           (!LegalOperations ||
2869            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2870             TLI.isOperationLegal(ISD::SETCC,
2871                             getSetCCResultType(N0.getSimpleValueType())))))
2872         return DAG.getSetCC(SDLoc(N), N0.getValueType(),
2873                             LL, LR, Result);
2874     }
2875   }
2876
2877   // Simplify: (and (op x...), (op y...))  -> (op (and x, y))
2878   if (N0.getOpcode() == N1.getOpcode()) {
2879     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
2880     if (Tmp.getNode()) return Tmp;
2881   }
2882
2883   // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
2884   // fold (and (sra)) -> (and (srl)) when possible.
2885   if (!VT.isVector() &&
2886       SimplifyDemandedBits(SDValue(N, 0)))
2887     return SDValue(N, 0);
2888
2889   // fold (zext_inreg (extload x)) -> (zextload x)
2890   if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
2891     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2892     EVT MemVT = LN0->getMemoryVT();
2893     // If we zero all the possible extended bits, then we can turn this into
2894     // a zextload if we are running before legalize or the operation is legal.
2895     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2896     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2897                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2898         ((!LegalOperations && !LN0->isVolatile()) ||
2899          TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2900       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2901                                        LN0->getChain(), LN0->getBasePtr(),
2902                                        MemVT, LN0->getMemOperand());
2903       AddToWorklist(N);
2904       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2905       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2906     }
2907   }
2908   // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
2909   if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
2910       N0.hasOneUse()) {
2911     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2912     EVT MemVT = LN0->getMemoryVT();
2913     // If we zero all the possible extended bits, then we can turn this into
2914     // a zextload if we are running before legalize or the operation is legal.
2915     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2916     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2917                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2918         ((!LegalOperations && !LN0->isVolatile()) ||
2919          TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2920       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2921                                        LN0->getChain(), LN0->getBasePtr(),
2922                                        MemVT, LN0->getMemOperand());
2923       AddToWorklist(N);
2924       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2925       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2926     }
2927   }
2928
2929   // fold (and (load x), 255) -> (zextload x, i8)
2930   // fold (and (extload x, i16), 255) -> (zextload x, i8)
2931   // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
2932   if (N1C && (N0.getOpcode() == ISD::LOAD ||
2933               (N0.getOpcode() == ISD::ANY_EXTEND &&
2934                N0.getOperand(0).getOpcode() == ISD::LOAD))) {
2935     bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
2936     LoadSDNode *LN0 = HasAnyExt
2937       ? cast<LoadSDNode>(N0.getOperand(0))
2938       : cast<LoadSDNode>(N0);
2939     if (LN0->getExtensionType() != ISD::SEXTLOAD &&
2940         LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
2941       uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
2942       if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
2943         EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
2944         EVT LoadedVT = LN0->getMemoryVT();
2945
2946         if (ExtVT == LoadedVT &&
2947             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2948           EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2949
2950           SDValue NewLoad =
2951             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2952                            LN0->getChain(), LN0->getBasePtr(), ExtVT,
2953                            LN0->getMemOperand());
2954           AddToWorklist(N);
2955           CombineTo(LN0, NewLoad, NewLoad.getValue(1));
2956           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2957         }
2958
2959         // Do not change the width of a volatile load.
2960         // Do not generate loads of non-round integer types since these can
2961         // be expensive (and would be wrong if the type is not byte sized).
2962         if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
2963             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2964           EVT PtrType = LN0->getOperand(1).getValueType();
2965
2966           unsigned Alignment = LN0->getAlignment();
2967           SDValue NewPtr = LN0->getBasePtr();
2968
2969           // For big endian targets, we need to add an offset to the pointer
2970           // to load the correct bytes.  For little endian systems, we merely
2971           // need to read fewer bytes from the same pointer.
2972           if (TLI.isBigEndian()) {
2973             unsigned LVTStoreBytes = LoadedVT.getStoreSize();
2974             unsigned EVTStoreBytes = ExtVT.getStoreSize();
2975             unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
2976             NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0), PtrType,
2977                                  NewPtr, DAG.getConstant(PtrOff, PtrType));
2978             Alignment = MinAlign(Alignment, PtrOff);
2979           }
2980
2981           AddToWorklist(NewPtr.getNode());
2982
2983           EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2984           SDValue Load =
2985             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2986                            LN0->getChain(), NewPtr,
2987                            LN0->getPointerInfo(),
2988                            ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
2989                            LN0->isInvariant(), Alignment, LN0->getAAInfo());
2990           AddToWorklist(N);
2991           CombineTo(LN0, Load, Load.getValue(1));
2992           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2993         }
2994       }
2995     }
2996   }
2997
2998   if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2999       VT.getSizeInBits() <= 64) {
3000     if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3001       APInt ADDC = ADDI->getAPIntValue();
3002       if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
3003         // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
3004         // immediate for an add, but it is legal if its top c2 bits are set,
3005         // transform the ADD so the immediate doesn't need to be materialized
3006         // in a register.
3007         if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
3008           APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
3009                                              SRLI->getZExtValue());
3010           if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
3011             ADDC |= Mask;
3012             if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
3013               SDValue NewAdd =
3014                 DAG.getNode(ISD::ADD, SDLoc(N0), VT,
3015                             N0.getOperand(0), DAG.getConstant(ADDC, VT));
3016               CombineTo(N0.getNode(), NewAdd);
3017               return SDValue(N, 0); // Return N so it doesn't get rechecked!
3018             }
3019           }
3020         }
3021       }
3022     }
3023   }
3024
3025   // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
3026   if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
3027     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
3028                                        N0.getOperand(1), false);
3029     if (BSwap.getNode())
3030       return BSwap;
3031   }
3032
3033   return SDValue();
3034 }
3035
3036 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16.
3037 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
3038                                         bool DemandHighBits) {
3039   if (!LegalOperations)
3040     return SDValue();
3041
3042   EVT VT = N->getValueType(0);
3043   if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
3044     return SDValue();
3045   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3046     return SDValue();
3047
3048   // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
3049   bool LookPassAnd0 = false;
3050   bool LookPassAnd1 = false;
3051   if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
3052       std::swap(N0, N1);
3053   if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
3054       std::swap(N0, N1);
3055   if (N0.getOpcode() == ISD::AND) {
3056     if (!N0.getNode()->hasOneUse())
3057       return SDValue();
3058     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3059     if (!N01C || N01C->getZExtValue() != 0xFF00)
3060       return SDValue();
3061     N0 = N0.getOperand(0);
3062     LookPassAnd0 = true;
3063   }
3064
3065   if (N1.getOpcode() == ISD::AND) {
3066     if (!N1.getNode()->hasOneUse())
3067       return SDValue();
3068     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3069     if (!N11C || N11C->getZExtValue() != 0xFF)
3070       return SDValue();
3071     N1 = N1.getOperand(0);
3072     LookPassAnd1 = true;
3073   }
3074
3075   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3076     std::swap(N0, N1);
3077   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3078     return SDValue();
3079   if (!N0.getNode()->hasOneUse() ||
3080       !N1.getNode()->hasOneUse())
3081     return SDValue();
3082
3083   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3084   ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3085   if (!N01C || !N11C)
3086     return SDValue();
3087   if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3088     return SDValue();
3089
3090   // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3091   SDValue N00 = N0->getOperand(0);
3092   if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3093     if (!N00.getNode()->hasOneUse())
3094       return SDValue();
3095     ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3096     if (!N001C || N001C->getZExtValue() != 0xFF)
3097       return SDValue();
3098     N00 = N00.getOperand(0);
3099     LookPassAnd0 = true;
3100   }
3101
3102   SDValue N10 = N1->getOperand(0);
3103   if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3104     if (!N10.getNode()->hasOneUse())
3105       return SDValue();
3106     ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3107     if (!N101C || N101C->getZExtValue() != 0xFF00)
3108       return SDValue();
3109     N10 = N10.getOperand(0);
3110     LookPassAnd1 = true;
3111   }
3112
3113   if (N00 != N10)
3114     return SDValue();
3115
3116   // Make sure everything beyond the low halfword gets set to zero since the SRL
3117   // 16 will clear the top bits.
3118   unsigned OpSizeInBits = VT.getSizeInBits();
3119   if (DemandHighBits && OpSizeInBits > 16) {
3120     // If the left-shift isn't masked out then the only way this is a bswap is
3121     // if all bits beyond the low 8 are 0. In that case the entire pattern
3122     // reduces to a left shift anyway: leave it for other parts of the combiner.
3123     if (!LookPassAnd0)
3124       return SDValue();
3125
3126     // However, if the right shift isn't masked out then it might be because
3127     // it's not needed. See if we can spot that too.
3128     if (!LookPassAnd1 &&
3129         !DAG.MaskedValueIsZero(
3130             N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3131       return SDValue();
3132   }
3133
3134   SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
3135   if (OpSizeInBits > 16)
3136     Res = DAG.getNode(ISD::SRL, SDLoc(N), VT, Res,
3137                       DAG.getConstant(OpSizeInBits-16, getShiftAmountTy(VT)));
3138   return Res;
3139 }
3140
3141 /// Return true if the specified node is an element that makes up a 32-bit
3142 /// packed halfword byteswap.
3143 /// ((x & 0x000000ff) << 8) |
3144 /// ((x & 0x0000ff00) >> 8) |
3145 /// ((x & 0x00ff0000) << 8) |
3146 /// ((x & 0xff000000) >> 8)
3147 static bool isBSwapHWordElement(SDValue N, SmallVectorImpl<SDNode *> &Parts) {
3148   if (!N.getNode()->hasOneUse())
3149     return false;
3150
3151   unsigned Opc = N.getOpcode();
3152   if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3153     return false;
3154
3155   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3156   if (!N1C)
3157     return false;
3158
3159   unsigned Num;
3160   switch (N1C->getZExtValue()) {
3161   default:
3162     return false;
3163   case 0xFF:       Num = 0; break;
3164   case 0xFF00:     Num = 1; break;
3165   case 0xFF0000:   Num = 2; break;
3166   case 0xFF000000: Num = 3; break;
3167   }
3168
3169   // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3170   SDValue N0 = N.getOperand(0);
3171   if (Opc == ISD::AND) {
3172     if (Num == 0 || Num == 2) {
3173       // (x >> 8) & 0xff
3174       // (x >> 8) & 0xff0000
3175       if (N0.getOpcode() != ISD::SRL)
3176         return false;
3177       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3178       if (!C || C->getZExtValue() != 8)
3179         return false;
3180     } else {
3181       // (x << 8) & 0xff00
3182       // (x << 8) & 0xff000000
3183       if (N0.getOpcode() != ISD::SHL)
3184         return false;
3185       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3186       if (!C || C->getZExtValue() != 8)
3187         return false;
3188     }
3189   } else if (Opc == ISD::SHL) {
3190     // (x & 0xff) << 8
3191     // (x & 0xff0000) << 8
3192     if (Num != 0 && Num != 2)
3193       return false;
3194     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3195     if (!C || C->getZExtValue() != 8)
3196       return false;
3197   } else { // Opc == ISD::SRL
3198     // (x & 0xff00) >> 8
3199     // (x & 0xff000000) >> 8
3200     if (Num != 1 && Num != 3)
3201       return false;
3202     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3203     if (!C || C->getZExtValue() != 8)
3204       return false;
3205   }
3206
3207   if (Parts[Num])
3208     return false;
3209
3210   Parts[Num] = N0.getOperand(0).getNode();
3211   return true;
3212 }
3213
3214 /// Match a 32-bit packed halfword bswap. That is
3215 /// ((x & 0x000000ff) << 8) |
3216 /// ((x & 0x0000ff00) >> 8) |
3217 /// ((x & 0x00ff0000) << 8) |
3218 /// ((x & 0xff000000) >> 8)
3219 /// => (rotl (bswap x), 16)
3220 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3221   if (!LegalOperations)
3222     return SDValue();
3223
3224   EVT VT = N->getValueType(0);
3225   if (VT != MVT::i32)
3226     return SDValue();
3227   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3228     return SDValue();
3229
3230   SmallVector<SDNode*,4> Parts(4, (SDNode*)nullptr);
3231   // Look for either
3232   // (or (or (and), (and)), (or (and), (and)))
3233   // (or (or (or (and), (and)), (and)), (and))
3234   if (N0.getOpcode() != ISD::OR)
3235     return SDValue();
3236   SDValue N00 = N0.getOperand(0);
3237   SDValue N01 = N0.getOperand(1);
3238
3239   if (N1.getOpcode() == ISD::OR &&
3240       N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3241     // (or (or (and), (and)), (or (and), (and)))
3242     SDValue N000 = N00.getOperand(0);
3243     if (!isBSwapHWordElement(N000, Parts))
3244       return SDValue();
3245
3246     SDValue N001 = N00.getOperand(1);
3247     if (!isBSwapHWordElement(N001, Parts))
3248       return SDValue();
3249     SDValue N010 = N01.getOperand(0);
3250     if (!isBSwapHWordElement(N010, Parts))
3251       return SDValue();
3252     SDValue N011 = N01.getOperand(1);
3253     if (!isBSwapHWordElement(N011, Parts))
3254       return SDValue();
3255   } else {
3256     // (or (or (or (and), (and)), (and)), (and))
3257     if (!isBSwapHWordElement(N1, Parts))
3258       return SDValue();
3259     if (!isBSwapHWordElement(N01, Parts))
3260       return SDValue();
3261     if (N00.getOpcode() != ISD::OR)
3262       return SDValue();
3263     SDValue N000 = N00.getOperand(0);
3264     if (!isBSwapHWordElement(N000, Parts))
3265       return SDValue();
3266     SDValue N001 = N00.getOperand(1);
3267     if (!isBSwapHWordElement(N001, Parts))
3268       return SDValue();
3269   }
3270
3271   // Make sure the parts are all coming from the same node.
3272   if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3273     return SDValue();
3274
3275   SDValue BSwap = DAG.getNode(ISD::BSWAP, SDLoc(N), VT,
3276                               SDValue(Parts[0],0));
3277
3278   // Result of the bswap should be rotated by 16. If it's not legal, then
3279   // do  (x << 16) | (x >> 16).
3280   SDValue ShAmt = DAG.getConstant(16, getShiftAmountTy(VT));
3281   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3282     return DAG.getNode(ISD::ROTL, SDLoc(N), VT, BSwap, ShAmt);
3283   if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3284     return DAG.getNode(ISD::ROTR, SDLoc(N), VT, BSwap, ShAmt);
3285   return DAG.getNode(ISD::OR, SDLoc(N), VT,
3286                      DAG.getNode(ISD::SHL, SDLoc(N), VT, BSwap, ShAmt),
3287                      DAG.getNode(ISD::SRL, SDLoc(N), VT, BSwap, ShAmt));
3288 }
3289
3290 SDValue DAGCombiner::visitOR(SDNode *N) {
3291   SDValue N0 = N->getOperand(0);
3292   SDValue N1 = N->getOperand(1);
3293   SDValue LL, LR, RL, RR, CC0, CC1;
3294   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3295   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3296   EVT VT = N1.getValueType();
3297
3298   // fold vector ops
3299   if (VT.isVector()) {
3300     SDValue FoldedVOp = SimplifyVBinOp(N);
3301     if (FoldedVOp.getNode()) return FoldedVOp;
3302
3303     // fold (or x, 0) -> x, vector edition
3304     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3305       return N1;
3306     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3307       return N0;
3308
3309     // fold (or x, -1) -> -1, vector edition
3310     if (ISD::isBuildVectorAllOnes(N0.getNode()))
3311       return N0;
3312     if (ISD::isBuildVectorAllOnes(N1.getNode()))
3313       return N1;
3314
3315     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
3316     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
3317     // Do this only if the resulting shuffle is legal.
3318     if (isa<ShuffleVectorSDNode>(N0) &&
3319         isa<ShuffleVectorSDNode>(N1) &&
3320         // Avoid folding a node with illegal type.
3321         TLI.isTypeLegal(VT) &&
3322         N0->getOperand(1) == N1->getOperand(1) &&
3323         ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
3324       bool CanFold = true;
3325       unsigned NumElts = VT.getVectorNumElements();
3326       const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3327       const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3328       // We construct two shuffle masks:
3329       // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
3330       // and N1 as the second operand.
3331       // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
3332       // and N0 as the second operand.
3333       // We do this because OR is commutable and therefore there might be
3334       // two ways to fold this node into a shuffle.
3335       SmallVector<int,4> Mask1;
3336       SmallVector<int,4> Mask2;
3337
3338       for (unsigned i = 0; i != NumElts && CanFold; ++i) {
3339         int M0 = SV0->getMaskElt(i);
3340         int M1 = SV1->getMaskElt(i);
3341
3342         // Both shuffle indexes are undef. Propagate Undef.
3343         if (M0 < 0 && M1 < 0) {
3344           Mask1.push_back(M0);
3345           Mask2.push_back(M0);
3346           continue;
3347         }
3348
3349         if (M0 < 0 || M1 < 0 ||
3350             (M0 < (int)NumElts && M1 < (int)NumElts) ||
3351             (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
3352           CanFold = false;
3353           break;
3354         }
3355
3356         Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
3357         Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
3358       }
3359
3360       if (CanFold) {
3361         // Fold this sequence only if the resulting shuffle is 'legal'.
3362         if (TLI.isShuffleMaskLegal(Mask1, VT))
3363           return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
3364                                       N1->getOperand(0), &Mask1[0]);
3365         if (TLI.isShuffleMaskLegal(Mask2, VT))
3366           return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
3367                                       N0->getOperand(0), &Mask2[0]);
3368       }
3369     }
3370   }
3371
3372   // fold (or x, undef) -> -1
3373   if (!LegalOperations &&
3374       (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3375     EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3376     return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
3377   }
3378   // fold (or c1, c2) -> c1|c2
3379   if (N0C && N1C)
3380     return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C);
3381   // canonicalize constant to RHS
3382   if (N0C && !N1C)
3383     return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3384   // fold (or x, 0) -> x
3385   if (N1C && N1C->isNullValue())
3386     return N0;
3387   // fold (or x, -1) -> -1
3388   if (N1C && N1C->isAllOnesValue())
3389     return N1;
3390   // fold (or x, c) -> c iff (x & ~c) == 0
3391   if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3392     return N1;
3393
3394   // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3395   SDValue BSwap = MatchBSwapHWord(N, N0, N1);
3396   if (BSwap.getNode())
3397     return BSwap;
3398   BSwap = MatchBSwapHWordLow(N, N0, N1);
3399   if (BSwap.getNode())
3400     return BSwap;
3401
3402   // reassociate or
3403   SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1);
3404   if (ROR.getNode())
3405     return ROR;
3406   // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3407   // iff (c1 & c2) == 0.
3408   if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3409              isa<ConstantSDNode>(N0.getOperand(1))) {
3410     ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3411     if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3412       SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1);
3413       if (!COR.getNode())
3414         return SDValue();
3415       return DAG.getNode(ISD::AND, SDLoc(N), VT,
3416                          DAG.getNode(ISD::OR, SDLoc(N0), VT,
3417                                      N0.getOperand(0), N1), COR);
3418     }
3419   }
3420   // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3421   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3422     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3423     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3424
3425     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
3426         LL.getValueType().isInteger()) {
3427       // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3428       // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3429       if (cast<ConstantSDNode>(LR)->isNullValue() &&
3430           (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3431         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3432                                      LR.getValueType(), LL, RL);
3433         AddToWorklist(ORNode.getNode());
3434         return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
3435       }
3436       // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3437       // fold (or (setgt X, -1), (setgt Y  -1)) -> (setgt (and X, Y), -1)
3438       if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
3439           (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3440         SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3441                                       LR.getValueType(), LL, RL);
3442         AddToWorklist(ANDNode.getNode());
3443         return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
3444       }
3445     }
3446     // canonicalize equivalent to ll == rl
3447     if (LL == RR && LR == RL) {
3448       Op1 = ISD::getSetCCSwappedOperands(Op1);
3449       std::swap(RL, RR);
3450     }
3451     if (LL == RL && LR == RR) {
3452       bool isInteger = LL.getValueType().isInteger();
3453       ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3454       if (Result != ISD::SETCC_INVALID &&
3455           (!LegalOperations ||
3456            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3457             TLI.isOperationLegal(ISD::SETCC,
3458               getSetCCResultType(N0.getValueType())))))
3459         return DAG.getSetCC(SDLoc(N), N0.getValueType(),
3460                             LL, LR, Result);
3461     }
3462   }
3463
3464   // Simplify: (or (op x...), (op y...))  -> (op (or x, y))
3465   if (N0.getOpcode() == N1.getOpcode()) {
3466     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3467     if (Tmp.getNode()) return Tmp;
3468   }
3469
3470   // (or (and X, C1), (and Y, C2))  -> (and (or X, Y), C3) if possible.
3471   if (N0.getOpcode() == ISD::AND &&
3472       N1.getOpcode() == ISD::AND &&
3473       N0.getOperand(1).getOpcode() == ISD::Constant &&
3474       N1.getOperand(1).getOpcode() == ISD::Constant &&
3475       // Don't increase # computations.
3476       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3477     // We can only do this xform if we know that bits from X that are set in C2
3478     // but not in C1 are already zero.  Likewise for Y.
3479     const APInt &LHSMask =
3480       cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3481     const APInt &RHSMask =
3482       cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
3483
3484     if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3485         DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3486       SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3487                               N0.getOperand(0), N1.getOperand(0));
3488       return DAG.getNode(ISD::AND, SDLoc(N), VT, X,
3489                          DAG.getConstant(LHSMask | RHSMask, VT));
3490     }
3491   }
3492
3493   // See if this is some rotate idiom.
3494   if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3495     return SDValue(Rot, 0);
3496
3497   // Simplify the operands using demanded-bits information.
3498   if (!VT.isVector() &&
3499       SimplifyDemandedBits(SDValue(N, 0)))
3500     return SDValue(N, 0);
3501
3502   return SDValue();
3503 }
3504
3505 /// Match "(X shl/srl V1) & V2" where V2 may not be present.
3506 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3507   if (Op.getOpcode() == ISD::AND) {
3508     if (isa<ConstantSDNode>(Op.getOperand(1))) {
3509       Mask = Op.getOperand(1);
3510       Op = Op.getOperand(0);
3511     } else {
3512       return false;
3513     }
3514   }
3515
3516   if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3517     Shift = Op;
3518     return true;
3519   }
3520
3521   return false;
3522 }
3523
3524 // Return true if we can prove that, whenever Neg and Pos are both in the
3525 // range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos).  This means that
3526 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3527 //
3528 //     (or (shift1 X, Neg), (shift2 X, Pos))
3529 //
3530 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3531 // in direction shift1 by Neg.  The range [0, OpSize) means that we only need
3532 // to consider shift amounts with defined behavior.
3533 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) {
3534   // If OpSize is a power of 2 then:
3535   //
3536   //  (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1)
3537   //  (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize).
3538   //
3539   // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check
3540   // for the stronger condition:
3541   //
3542   //     Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1)    [A]
3543   //
3544   // for all Neg and Pos.  Since Neg & (OpSize - 1) == Neg' & (OpSize - 1)
3545   // we can just replace Neg with Neg' for the rest of the function.
3546   //
3547   // In other cases we check for the even stronger condition:
3548   //
3549   //     Neg == OpSize - Pos                                    [B]
3550   //
3551   // for all Neg and Pos.  Note that the (or ...) then invokes undefined
3552   // behavior if Pos == 0 (and consequently Neg == OpSize).
3553   //
3554   // We could actually use [A] whenever OpSize is a power of 2, but the
3555   // only extra cases that it would match are those uninteresting ones
3556   // where Neg and Pos are never in range at the same time.  E.g. for
3557   // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3558   // as well as (sub 32, Pos), but:
3559   //
3560   //     (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3561   //
3562   // always invokes undefined behavior for 32-bit X.
3563   //
3564   // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise.
3565   unsigned MaskLoBits = 0;
3566   if (Neg.getOpcode() == ISD::AND &&
3567       isPowerOf2_64(OpSize) &&
3568       Neg.getOperand(1).getOpcode() == ISD::Constant &&
3569       cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) {
3570     Neg = Neg.getOperand(0);
3571     MaskLoBits = Log2_64(OpSize);
3572   }
3573
3574   // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3575   if (Neg.getOpcode() != ISD::SUB)
3576     return 0;
3577   ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0));
3578   if (!NegC)
3579     return 0;
3580   SDValue NegOp1 = Neg.getOperand(1);
3581
3582   // On the RHS of [A], if Pos is Pos' & (OpSize - 1), just replace Pos with
3583   // Pos'.  The truncation is redundant for the purpose of the equality.
3584   if (MaskLoBits &&
3585       Pos.getOpcode() == ISD::AND &&
3586       Pos.getOperand(1).getOpcode() == ISD::Constant &&
3587       cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() == OpSize - 1)
3588     Pos = Pos.getOperand(0);
3589
3590   // The condition we need is now:
3591   //
3592   //     (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask
3593   //
3594   // If NegOp1 == Pos then we need:
3595   //
3596   //              OpSize & Mask == NegC & Mask
3597   //
3598   // (because "x & Mask" is a truncation and distributes through subtraction).
3599   APInt Width;
3600   if (Pos == NegOp1)
3601     Width = NegC->getAPIntValue();
3602   // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3603   // Then the condition we want to prove becomes:
3604   //
3605   //     (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask
3606   //
3607   // which, again because "x & Mask" is a truncation, becomes:
3608   //
3609   //                NegC & Mask == (OpSize - PosC) & Mask
3610   //              OpSize & Mask == (NegC + PosC) & Mask
3611   else if (Pos.getOpcode() == ISD::ADD &&
3612            Pos.getOperand(0) == NegOp1 &&
3613            Pos.getOperand(1).getOpcode() == ISD::Constant)
3614     Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() +
3615              NegC->getAPIntValue());
3616   else
3617     return false;
3618
3619   // Now we just need to check that OpSize & Mask == Width & Mask.
3620   if (MaskLoBits)
3621     // Opsize & Mask is 0 since Mask is Opsize - 1.
3622     return Width.getLoBits(MaskLoBits) == 0;
3623   return Width == OpSize;
3624 }
3625
3626 // A subroutine of MatchRotate used once we have found an OR of two opposite
3627 // shifts of Shifted.  If Neg == <operand size> - Pos then the OR reduces
3628 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3629 // former being preferred if supported.  InnerPos and InnerNeg are Pos and
3630 // Neg with outer conversions stripped away.
3631 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3632                                        SDValue Neg, SDValue InnerPos,
3633                                        SDValue InnerNeg, unsigned PosOpcode,
3634                                        unsigned NegOpcode, SDLoc DL) {
3635   // fold (or (shl x, (*ext y)),
3636   //          (srl x, (*ext (sub 32, y)))) ->
3637   //   (rotl x, y) or (rotr x, (sub 32, y))
3638   //
3639   // fold (or (shl x, (*ext (sub 32, y))),
3640   //          (srl x, (*ext y))) ->
3641   //   (rotr x, y) or (rotl x, (sub 32, y))
3642   EVT VT = Shifted.getValueType();
3643   if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) {
3644     bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3645     return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3646                        HasPos ? Pos : Neg).getNode();
3647   }
3648
3649   return nullptr;
3650 }
3651
3652 // MatchRotate - Handle an 'or' of two operands.  If this is one of the many
3653 // idioms for rotate, and if the target supports rotation instructions, generate
3654 // a rot[lr].
3655 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
3656   // Must be a legal type.  Expanded 'n promoted things won't work with rotates.
3657   EVT VT = LHS.getValueType();
3658   if (!TLI.isTypeLegal(VT)) return nullptr;
3659
3660   // The target must have at least one rotate flavor.
3661   bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3662   bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3663   if (!HasROTL && !HasROTR) return nullptr;
3664
3665   // Match "(X shl/srl V1) & V2" where V2 may not be present.
3666   SDValue LHSShift;   // The shift.
3667   SDValue LHSMask;    // AND value if any.
3668   if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3669     return nullptr; // Not part of a rotate.
3670
3671   SDValue RHSShift;   // The shift.
3672   SDValue RHSMask;    // AND value if any.
3673   if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3674     return nullptr; // Not part of a rotate.
3675
3676   if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3677     return nullptr;   // Not shifting the same value.
3678
3679   if (LHSShift.getOpcode() == RHSShift.getOpcode())
3680     return nullptr;   // Shifts must disagree.
3681
3682   // Canonicalize shl to left side in a shl/srl pair.
3683   if (RHSShift.getOpcode() == ISD::SHL) {
3684     std::swap(LHS, RHS);
3685     std::swap(LHSShift, RHSShift);
3686     std::swap(LHSMask , RHSMask );
3687   }
3688
3689   unsigned OpSizeInBits = VT.getSizeInBits();
3690   SDValue LHSShiftArg = LHSShift.getOperand(0);
3691   SDValue LHSShiftAmt = LHSShift.getOperand(1);
3692   SDValue RHSShiftArg = RHSShift.getOperand(0);
3693   SDValue RHSShiftAmt = RHSShift.getOperand(1);
3694
3695   // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3696   // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
3697   if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3698       RHSShiftAmt.getOpcode() == ISD::Constant) {
3699     uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3700     uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
3701     if ((LShVal + RShVal) != OpSizeInBits)
3702       return nullptr;
3703
3704     SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3705                               LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3706
3707     // If there is an AND of either shifted operand, apply it to the result.
3708     if (LHSMask.getNode() || RHSMask.getNode()) {
3709       APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
3710
3711       if (LHSMask.getNode()) {
3712         APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3713         Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
3714       }
3715       if (RHSMask.getNode()) {
3716         APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3717         Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
3718       }
3719
3720       Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT));
3721     }
3722
3723     return Rot.getNode();
3724   }
3725
3726   // If there is a mask here, and we have a variable shift, we can't be sure
3727   // that we're masking out the right stuff.
3728   if (LHSMask.getNode() || RHSMask.getNode())
3729     return nullptr;
3730
3731   // If the shift amount is sign/zext/any-extended just peel it off.
3732   SDValue LExtOp0 = LHSShiftAmt;
3733   SDValue RExtOp0 = RHSShiftAmt;
3734   if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3735        LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3736        LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3737        LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3738       (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3739        RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3740        RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3741        RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
3742     LExtOp0 = LHSShiftAmt.getOperand(0);
3743     RExtOp0 = RHSShiftAmt.getOperand(0);
3744   }
3745
3746   SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
3747                                    LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
3748   if (TryL)
3749     return TryL;
3750
3751   SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
3752                                    RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
3753   if (TryR)
3754     return TryR;
3755
3756   return nullptr;
3757 }
3758
3759 SDValue DAGCombiner::visitXOR(SDNode *N) {
3760   SDValue N0 = N->getOperand(0);
3761   SDValue N1 = N->getOperand(1);
3762   SDValue LHS, RHS, CC;
3763   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3764   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3765   EVT VT = N0.getValueType();
3766
3767   // fold vector ops
3768   if (VT.isVector()) {
3769     SDValue FoldedVOp = SimplifyVBinOp(N);
3770     if (FoldedVOp.getNode()) return FoldedVOp;
3771
3772     // fold (xor x, 0) -> x, vector edition
3773     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3774       return N1;
3775     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3776       return N0;
3777   }
3778
3779   // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3780   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3781     return DAG.getConstant(0, VT);
3782   // fold (xor x, undef) -> undef
3783   if (N0.getOpcode() == ISD::UNDEF)
3784     return N0;
3785   if (N1.getOpcode() == ISD::UNDEF)
3786     return N1;
3787   // fold (xor c1, c2) -> c1^c2
3788   if (N0C && N1C)
3789     return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
3790   // canonicalize constant to RHS
3791   if (N0C && !N1C)
3792     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
3793   // fold (xor x, 0) -> x
3794   if (N1C && N1C->isNullValue())
3795     return N0;
3796   // reassociate xor
3797   SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1);
3798   if (RXOR.getNode())
3799     return RXOR;
3800
3801   // fold !(x cc y) -> (x !cc y)
3802   if (N1C && N1C->getAPIntValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) {
3803     bool isInt = LHS.getValueType().isInteger();
3804     ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3805                                                isInt);
3806
3807     if (!LegalOperations ||
3808         TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
3809       switch (N0.getOpcode()) {
3810       default:
3811         llvm_unreachable("Unhandled SetCC Equivalent!");
3812       case ISD::SETCC:
3813         return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
3814       case ISD::SELECT_CC:
3815         return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
3816                                N0.getOperand(3), NotCC);
3817       }
3818     }
3819   }
3820
3821   // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
3822   if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
3823       N0.getNode()->hasOneUse() &&
3824       isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
3825     SDValue V = N0.getOperand(0);
3826     V = DAG.getNode(ISD::XOR, SDLoc(N0), V.getValueType(), V,
3827                     DAG.getConstant(1, V.getValueType()));
3828     AddToWorklist(V.getNode());
3829     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
3830   }
3831
3832   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
3833   if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
3834       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3835     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3836     if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
3837       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3838       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3839       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3840       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
3841       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3842     }
3843   }
3844   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
3845   if (N1C && N1C->isAllOnesValue() &&
3846       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3847     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3848     if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
3849       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3850       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3851       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3852       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
3853       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3854     }
3855   }
3856   // fold (xor (and x, y), y) -> (and (not x), y)
3857   if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3858       N0->getOperand(1) == N1) {
3859     SDValue X = N0->getOperand(0);
3860     SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
3861     AddToWorklist(NotX.getNode());
3862     return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
3863   }
3864   // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
3865   if (N1C && N0.getOpcode() == ISD::XOR) {
3866     ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
3867     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3868     if (N00C)
3869       return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(1),
3870                          DAG.getConstant(N1C->getAPIntValue() ^
3871                                          N00C->getAPIntValue(), VT));
3872     if (N01C)
3873       return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(0),
3874                          DAG.getConstant(N1C->getAPIntValue() ^
3875                                          N01C->getAPIntValue(), VT));
3876   }
3877   // fold (xor x, x) -> 0
3878   if (N0 == N1)
3879     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
3880
3881   // Simplify: xor (op x...), (op y...)  -> (op (xor x, y))
3882   if (N0.getOpcode() == N1.getOpcode()) {
3883     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3884     if (Tmp.getNode()) return Tmp;
3885   }
3886
3887   // Simplify the expression using non-local knowledge.
3888   if (!VT.isVector() &&
3889       SimplifyDemandedBits(SDValue(N, 0)))
3890     return SDValue(N, 0);
3891
3892   return SDValue();
3893 }
3894
3895 /// Handle transforms common to the three shifts, when the shift amount is a
3896 /// constant.
3897 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
3898   // We can't and shouldn't fold opaque constants.
3899   if (Amt->isOpaque())
3900     return SDValue();
3901
3902   SDNode *LHS = N->getOperand(0).getNode();
3903   if (!LHS->hasOneUse()) return SDValue();
3904
3905   // We want to pull some binops through shifts, so that we have (and (shift))
3906   // instead of (shift (and)), likewise for add, or, xor, etc.  This sort of
3907   // thing happens with address calculations, so it's important to canonicalize
3908   // it.
3909   bool HighBitSet = false;  // Can we transform this if the high bit is set?
3910
3911   switch (LHS->getOpcode()) {
3912   default: return SDValue();
3913   case ISD::OR:
3914   case ISD::XOR:
3915     HighBitSet = false; // We can only transform sra if the high bit is clear.
3916     break;
3917   case ISD::AND:
3918     HighBitSet = true;  // We can only transform sra if the high bit is set.
3919     break;
3920   case ISD::ADD:
3921     if (N->getOpcode() != ISD::SHL)
3922       return SDValue(); // only shl(add) not sr[al](add).
3923     HighBitSet = false; // We can only transform sra if the high bit is clear.
3924     break;
3925   }
3926
3927   // We require the RHS of the binop to be a constant and not opaque as well.
3928   ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
3929   if (!BinOpCst || BinOpCst->isOpaque()) return SDValue();
3930
3931   // FIXME: disable this unless the input to the binop is a shift by a constant.
3932   // If it is not a shift, it pessimizes some common cases like:
3933   //
3934   //    void foo(int *X, int i) { X[i & 1235] = 1; }
3935   //    int bar(int *X, int i) { return X[i & 255]; }
3936   SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
3937   if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
3938        BinOpLHSVal->getOpcode() != ISD::SRA &&
3939        BinOpLHSVal->getOpcode() != ISD::SRL) ||
3940       !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
3941     return SDValue();
3942
3943   EVT VT = N->getValueType(0);
3944
3945   // If this is a signed shift right, and the high bit is modified by the
3946   // logical operation, do not perform the transformation. The highBitSet
3947   // boolean indicates the value of the high bit of the constant which would
3948   // cause it to be modified for this operation.
3949   if (N->getOpcode() == ISD::SRA) {
3950     bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
3951     if (BinOpRHSSignSet != HighBitSet)
3952       return SDValue();
3953   }
3954
3955   if (!TLI.isDesirableToCommuteWithShift(LHS))
3956     return SDValue();
3957
3958   // Fold the constants, shifting the binop RHS by the shift amount.
3959   SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
3960                                N->getValueType(0),
3961                                LHS->getOperand(1), N->getOperand(1));
3962   assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
3963
3964   // Create the new shift.
3965   SDValue NewShift = DAG.getNode(N->getOpcode(),
3966                                  SDLoc(LHS->getOperand(0)),
3967                                  VT, LHS->getOperand(0), N->getOperand(1));
3968
3969   // Create the new binop.
3970   return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
3971 }
3972
3973 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
3974   assert(N->getOpcode() == ISD::TRUNCATE);
3975   assert(N->getOperand(0).getOpcode() == ISD::AND);
3976
3977   // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
3978   if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
3979     SDValue N01 = N->getOperand(0).getOperand(1);
3980
3981     if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
3982       EVT TruncVT = N->getValueType(0);
3983       SDValue N00 = N->getOperand(0).getOperand(0);
3984       APInt TruncC = N01C->getAPIntValue();
3985       TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
3986
3987       return DAG.getNode(ISD::AND, SDLoc(N), TruncVT,
3988                          DAG.getNode(ISD::TRUNCATE, SDLoc(N), TruncVT, N00),
3989                          DAG.getConstant(TruncC, TruncVT));
3990     }
3991   }
3992
3993   return SDValue();
3994 }
3995
3996 SDValue DAGCombiner::visitRotate(SDNode *N) {
3997   // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
3998   if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
3999       N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
4000     SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode());
4001     if (NewOp1.getNode())
4002       return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
4003                          N->getOperand(0), NewOp1);
4004   }
4005   return SDValue();
4006 }
4007
4008 SDValue DAGCombiner::visitSHL(SDNode *N) {
4009   SDValue N0 = N->getOperand(0);
4010   SDValue N1 = N->getOperand(1);
4011   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4012   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4013   EVT VT = N0.getValueType();
4014   unsigned OpSizeInBits = VT.getScalarSizeInBits();
4015
4016   // fold vector ops
4017   if (VT.isVector()) {
4018     SDValue FoldedVOp = SimplifyVBinOp(N);
4019     if (FoldedVOp.getNode()) return FoldedVOp;
4020
4021     BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
4022     // If setcc produces all-one true value then:
4023     // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
4024     if (N1CV && N1CV->isConstant()) {
4025       if (N0.getOpcode() == ISD::AND) {
4026         SDValue N00 = N0->getOperand(0);
4027         SDValue N01 = N0->getOperand(1);
4028         BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
4029
4030         if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
4031             TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
4032                 TargetLowering::ZeroOrNegativeOneBooleanContent) {
4033           SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, VT, N01CV, N1CV);
4034           if (C.getNode())
4035             return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
4036         }
4037       } else {
4038         N1C = isConstOrConstSplat(N1);
4039       }
4040     }
4041   }
4042
4043   // fold (shl c1, c2) -> c1<<c2
4044   if (N0C && N1C)
4045     return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
4046   // fold (shl 0, x) -> 0
4047   if (N0C && N0C->isNullValue())
4048     return N0;
4049   // fold (shl x, c >= size(x)) -> undef
4050   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4051     return DAG.getUNDEF(VT);
4052   // fold (shl x, 0) -> x
4053   if (N1C && N1C->isNullValue())
4054     return N0;
4055   // fold (shl undef, x) -> 0
4056   if (N0.getOpcode() == ISD::UNDEF)
4057     return DAG.getConstant(0, VT);
4058   // if (shl x, c) is known to be zero, return 0
4059   if (DAG.MaskedValueIsZero(SDValue(N, 0),
4060                             APInt::getAllOnesValue(OpSizeInBits)))
4061     return DAG.getConstant(0, VT);
4062   // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
4063   if (N1.getOpcode() == ISD::TRUNCATE &&
4064       N1.getOperand(0).getOpcode() == ISD::AND) {
4065     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4066     if (NewOp1.getNode())
4067       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
4068   }
4069
4070   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4071     return SDValue(N, 0);
4072
4073   // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
4074   if (N1C && N0.getOpcode() == ISD::SHL) {
4075     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4076       uint64_t c1 = N0C1->getZExtValue();
4077       uint64_t c2 = N1C->getZExtValue();
4078       if (c1 + c2 >= OpSizeInBits)
4079         return DAG.getConstant(0, VT);
4080       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4081                          DAG.getConstant(c1 + c2, N1.getValueType()));
4082     }
4083   }
4084
4085   // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4086   // For this to be valid, the second form must not preserve any of the bits
4087   // that are shifted out by the inner shift in the first form.  This means
4088   // the outer shift size must be >= the number of bits added by the ext.
4089   // As a corollary, we don't care what kind of ext it is.
4090   if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4091               N0.getOpcode() == ISD::ANY_EXTEND ||
4092               N0.getOpcode() == ISD::SIGN_EXTEND) &&
4093       N0.getOperand(0).getOpcode() == ISD::SHL) {
4094     SDValue N0Op0 = N0.getOperand(0);
4095     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4096       uint64_t c1 = N0Op0C1->getZExtValue();
4097       uint64_t c2 = N1C->getZExtValue();
4098       EVT InnerShiftVT = N0Op0.getValueType();
4099       uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4100       if (c2 >= OpSizeInBits - InnerShiftSize) {
4101         if (c1 + c2 >= OpSizeInBits)
4102           return DAG.getConstant(0, VT);
4103         return DAG.getNode(ISD::SHL, SDLoc(N0), VT,
4104                            DAG.getNode(N0.getOpcode(), SDLoc(N0), VT,
4105                                        N0Op0->getOperand(0)),
4106                            DAG.getConstant(c1 + c2, N1.getValueType()));
4107       }
4108     }
4109   }
4110
4111   // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4112   // Only fold this if the inner zext has no other uses to avoid increasing
4113   // the total number of instructions.
4114   if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
4115       N0.getOperand(0).getOpcode() == ISD::SRL) {
4116     SDValue N0Op0 = N0.getOperand(0);
4117     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4118       uint64_t c1 = N0Op0C1->getZExtValue();
4119       if (c1 < VT.getScalarSizeInBits()) {
4120         uint64_t c2 = N1C->getZExtValue();
4121         if (c1 == c2) {
4122           SDValue NewOp0 = N0.getOperand(0);
4123           EVT CountVT = NewOp0.getOperand(1).getValueType();
4124           SDValue NewSHL = DAG.getNode(ISD::SHL, SDLoc(N), NewOp0.getValueType(),
4125                                        NewOp0, DAG.getConstant(c2, CountVT));
4126           AddToWorklist(NewSHL.getNode());
4127           return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4128         }
4129       }
4130     }
4131   }
4132
4133   // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4134   //                               (and (srl x, (sub c1, c2), MASK)
4135   // Only fold this if the inner shift has no other uses -- if it does, folding
4136   // this will increase the total number of instructions.
4137   if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4138     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4139       uint64_t c1 = N0C1->getZExtValue();
4140       if (c1 < OpSizeInBits) {
4141         uint64_t c2 = N1C->getZExtValue();
4142         APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4143         SDValue Shift;
4144         if (c2 > c1) {
4145           Mask = Mask.shl(c2 - c1);
4146           Shift = DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4147                               DAG.getConstant(c2 - c1, N1.getValueType()));
4148         } else {
4149           Mask = Mask.lshr(c1 - c2);
4150           Shift = DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4151                               DAG.getConstant(c1 - c2, N1.getValueType()));
4152         }
4153         return DAG.getNode(ISD::AND, SDLoc(N0), VT, Shift,
4154                            DAG.getConstant(Mask, VT));
4155       }
4156     }
4157   }
4158   // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
4159   if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
4160     unsigned BitSize = VT.getScalarSizeInBits();
4161     SDValue HiBitsMask =
4162       DAG.getConstant(APInt::getHighBitsSet(BitSize,
4163                                             BitSize - N1C->getZExtValue()), VT);
4164     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4165                        HiBitsMask);
4166   }
4167
4168   if (N1C) {
4169     SDValue NewSHL = visitShiftByConstant(N, N1C);
4170     if (NewSHL.getNode())
4171       return NewSHL;
4172   }
4173
4174   return SDValue();
4175 }
4176
4177 SDValue DAGCombiner::visitSRA(SDNode *N) {
4178   SDValue N0 = N->getOperand(0);
4179   SDValue N1 = N->getOperand(1);
4180   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4181   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4182   EVT VT = N0.getValueType();
4183   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4184
4185   // fold vector ops
4186   if (VT.isVector()) {
4187     SDValue FoldedVOp = SimplifyVBinOp(N);
4188     if (FoldedVOp.getNode()) return FoldedVOp;
4189
4190     N1C = isConstOrConstSplat(N1);
4191   }
4192
4193   // fold (sra c1, c2) -> (sra c1, c2)
4194   if (N0C && N1C)
4195     return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
4196   // fold (sra 0, x) -> 0
4197   if (N0C && N0C->isNullValue())
4198     return N0;
4199   // fold (sra -1, x) -> -1
4200   if (N0C && N0C->isAllOnesValue())
4201     return N0;
4202   // fold (sra x, (setge c, size(x))) -> undef
4203   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4204     return DAG.getUNDEF(VT);
4205   // fold (sra x, 0) -> x
4206   if (N1C && N1C->isNullValue())
4207     return N0;
4208   // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4209   // sext_inreg.
4210   if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
4211     unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
4212     EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4213     if (VT.isVector())
4214       ExtVT = EVT::getVectorVT(*DAG.getContext(),
4215                                ExtVT, VT.getVectorNumElements());
4216     if ((!LegalOperations ||
4217          TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
4218       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
4219                          N0.getOperand(0), DAG.getValueType(ExtVT));
4220   }
4221
4222   // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
4223   if (N1C && N0.getOpcode() == ISD::SRA) {
4224     if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
4225       unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
4226       if (Sum >= OpSizeInBits)
4227         Sum = OpSizeInBits - 1;
4228       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0.getOperand(0),
4229                          DAG.getConstant(Sum, N1.getValueType()));
4230     }
4231   }
4232
4233   // fold (sra (shl X, m), (sub result_size, n))
4234   // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
4235   // result_size - n != m.
4236   // If truncate is free for the target sext(shl) is likely to result in better
4237   // code.
4238   if (N0.getOpcode() == ISD::SHL && N1C) {
4239     // Get the two constanst of the shifts, CN0 = m, CN = n.
4240     const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4241     if (N01C) {
4242       LLVMContext &Ctx = *DAG.getContext();
4243       // Determine what the truncate's result bitsize and type would be.
4244       EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4245
4246       if (VT.isVector())
4247         TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4248
4249       // Determine the residual right-shift amount.
4250       signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
4251
4252       // If the shift is not a no-op (in which case this should be just a sign
4253       // extend already), the truncated to type is legal, sign_extend is legal
4254       // on that type, and the truncate to that type is both legal and free,
4255       // perform the transform.
4256       if ((ShiftAmt > 0) &&
4257           TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4258           TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
4259           TLI.isTruncateFree(VT, TruncVT)) {
4260
4261           SDValue Amt = DAG.getConstant(ShiftAmt,
4262               getShiftAmountTy(N0.getOperand(0).getValueType()));
4263           SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), VT,
4264                                       N0.getOperand(0), Amt);
4265           SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), TruncVT,
4266                                       Shift);
4267           return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N),
4268                              N->getValueType(0), Trunc);
4269       }
4270     }
4271   }
4272
4273   // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
4274   if (N1.getOpcode() == ISD::TRUNCATE &&
4275       N1.getOperand(0).getOpcode() == ISD::AND) {
4276     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4277     if (NewOp1.getNode())
4278       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
4279   }
4280
4281   // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
4282   //      if c1 is equal to the number of bits the trunc removes
4283   if (N0.getOpcode() == ISD::TRUNCATE &&
4284       (N0.getOperand(0).getOpcode() == ISD::SRL ||
4285        N0.getOperand(0).getOpcode() == ISD::SRA) &&
4286       N0.getOperand(0).hasOneUse() &&
4287       N0.getOperand(0).getOperand(1).hasOneUse() &&
4288       N1C) {
4289     SDValue N0Op0 = N0.getOperand(0);
4290     if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4291       unsigned LargeShiftVal = LargeShift->getZExtValue();
4292       EVT LargeVT = N0Op0.getValueType();
4293
4294       if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4295         SDValue Amt =
4296           DAG.getConstant(LargeShiftVal + N1C->getZExtValue(),
4297                           getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4298         SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), LargeVT,
4299                                   N0Op0.getOperand(0), Amt);
4300         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, SRA);
4301       }
4302     }
4303   }
4304
4305   // Simplify, based on bits shifted out of the LHS.
4306   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4307     return SDValue(N, 0);
4308
4309
4310   // If the sign bit is known to be zero, switch this to a SRL.
4311   if (DAG.SignBitIsZero(N0))
4312     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
4313
4314   if (N1C) {
4315     SDValue NewSRA = visitShiftByConstant(N, N1C);
4316     if (NewSRA.getNode())
4317       return NewSRA;
4318   }
4319
4320   return SDValue();
4321 }
4322
4323 SDValue DAGCombiner::visitSRL(SDNode *N) {
4324   SDValue N0 = N->getOperand(0);
4325   SDValue N1 = N->getOperand(1);
4326   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4327   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4328   EVT VT = N0.getValueType();
4329   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4330
4331   // fold vector ops
4332   if (VT.isVector()) {
4333     SDValue FoldedVOp = SimplifyVBinOp(N);
4334     if (FoldedVOp.getNode()) return FoldedVOp;
4335
4336     N1C = isConstOrConstSplat(N1);
4337   }
4338
4339   // fold (srl c1, c2) -> c1 >>u c2
4340   if (N0C && N1C)
4341     return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C);
4342   // fold (srl 0, x) -> 0
4343   if (N0C && N0C->isNullValue())
4344     return N0;
4345   // fold (srl x, c >= size(x)) -> undef
4346   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4347     return DAG.getUNDEF(VT);
4348   // fold (srl x, 0) -> x
4349   if (N1C && N1C->isNullValue())
4350     return N0;
4351   // if (srl x, c) is known to be zero, return 0
4352   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4353                                    APInt::getAllOnesValue(OpSizeInBits)))
4354     return DAG.getConstant(0, VT);
4355
4356   // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
4357   if (N1C && N0.getOpcode() == ISD::SRL) {
4358     if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
4359       uint64_t c1 = N01C->getZExtValue();
4360       uint64_t c2 = N1C->getZExtValue();
4361       if (c1 + c2 >= OpSizeInBits)
4362         return DAG.getConstant(0, VT);
4363       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4364                          DAG.getConstant(c1 + c2, N1.getValueType()));
4365     }
4366   }
4367
4368   // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4369   if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4370       N0.getOperand(0).getOpcode() == ISD::SRL &&
4371       isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4372     uint64_t c1 =
4373       cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4374     uint64_t c2 = N1C->getZExtValue();
4375     EVT InnerShiftVT = N0.getOperand(0).getValueType();
4376     EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4377     uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
4378     // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4379     if (c1 + OpSizeInBits == InnerShiftSize) {
4380       if (c1 + c2 >= InnerShiftSize)
4381         return DAG.getConstant(0, VT);
4382       return DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT,
4383                          DAG.getNode(ISD::SRL, SDLoc(N0), InnerShiftVT,
4384                                      N0.getOperand(0)->getOperand(0),
4385                                      DAG.getConstant(c1 + c2, ShiftCountVT)));
4386     }
4387   }
4388
4389   // fold (srl (shl x, c), c) -> (and x, cst2)
4390   if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4391     unsigned BitSize = N0.getScalarValueSizeInBits();
4392     if (BitSize <= 64) {
4393       uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4394       return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4395                          DAG.getConstant(~0ULL >> ShAmt, VT));
4396     }
4397   }
4398
4399   // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4400   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4401     // Shifting in all undef bits?
4402     EVT SmallVT = N0.getOperand(0).getValueType();
4403     unsigned BitSize = SmallVT.getScalarSizeInBits();
4404     if (N1C->getZExtValue() >= BitSize)
4405       return DAG.getUNDEF(VT);
4406
4407     if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4408       uint64_t ShiftAmt = N1C->getZExtValue();
4409       SDValue SmallShift = DAG.getNode(ISD::SRL, SDLoc(N0), SmallVT,
4410                                        N0.getOperand(0),
4411                           DAG.getConstant(ShiftAmt, getShiftAmountTy(SmallVT)));
4412       AddToWorklist(SmallShift.getNode());
4413       APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
4414       return DAG.getNode(ISD::AND, SDLoc(N), VT,
4415                          DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, SmallShift),
4416                          DAG.getConstant(Mask, VT));
4417     }
4418   }
4419
4420   // fold (srl (sra X, Y), 31) -> (srl X, 31).  This srl only looks at the sign
4421   // bit, which is unmodified by sra.
4422   if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
4423     if (N0.getOpcode() == ISD::SRA)
4424       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4425   }
4426
4427   // fold (srl (ctlz x), "5") -> x  iff x has one bit set (the low bit).
4428   if (N1C && N0.getOpcode() == ISD::CTLZ &&
4429       N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
4430     APInt KnownZero, KnownOne;
4431     DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne);
4432
4433     // If any of the input bits are KnownOne, then the input couldn't be all
4434     // zeros, thus the result of the srl will always be zero.
4435     if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
4436
4437     // If all of the bits input the to ctlz node are known to be zero, then
4438     // the result of the ctlz is "32" and the result of the shift is one.
4439     APInt UnknownBits = ~KnownZero;
4440     if (UnknownBits == 0) return DAG.getConstant(1, VT);
4441
4442     // Otherwise, check to see if there is exactly one bit input to the ctlz.
4443     if ((UnknownBits & (UnknownBits - 1)) == 0) {
4444       // Okay, we know that only that the single bit specified by UnknownBits
4445       // could be set on input to the CTLZ node. If this bit is set, the SRL
4446       // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4447       // to an SRL/XOR pair, which is likely to simplify more.
4448       unsigned ShAmt = UnknownBits.countTrailingZeros();
4449       SDValue Op = N0.getOperand(0);
4450
4451       if (ShAmt) {
4452         Op = DAG.getNode(ISD::SRL, SDLoc(N0), VT, Op,
4453                   DAG.getConstant(ShAmt, getShiftAmountTy(Op.getValueType())));
4454         AddToWorklist(Op.getNode());
4455       }
4456
4457       return DAG.getNode(ISD::XOR, SDLoc(N), VT,
4458                          Op, DAG.getConstant(1, VT));
4459     }
4460   }
4461
4462   // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4463   if (N1.getOpcode() == ISD::TRUNCATE &&
4464       N1.getOperand(0).getOpcode() == ISD::AND) {
4465     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4466     if (NewOp1.getNode())
4467       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
4468   }
4469
4470   // fold operands of srl based on knowledge that the low bits are not
4471   // demanded.
4472   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4473     return SDValue(N, 0);
4474
4475   if (N1C) {
4476     SDValue NewSRL = visitShiftByConstant(N, N1C);
4477     if (NewSRL.getNode())
4478       return NewSRL;
4479   }
4480
4481   // Attempt to convert a srl of a load into a narrower zero-extending load.
4482   SDValue NarrowLoad = ReduceLoadWidth(N);
4483   if (NarrowLoad.getNode())
4484     return NarrowLoad;
4485
4486   // Here is a common situation. We want to optimize:
4487   //
4488   //   %a = ...
4489   //   %b = and i32 %a, 2
4490   //   %c = srl i32 %b, 1
4491   //   brcond i32 %c ...
4492   //
4493   // into
4494   //
4495   //   %a = ...
4496   //   %b = and %a, 2
4497   //   %c = setcc eq %b, 0
4498   //   brcond %c ...
4499   //
4500   // However when after the source operand of SRL is optimized into AND, the SRL
4501   // itself may not be optimized further. Look for it and add the BRCOND into
4502   // the worklist.
4503   if (N->hasOneUse()) {
4504     SDNode *Use = *N->use_begin();
4505     if (Use->getOpcode() == ISD::BRCOND)
4506       AddToWorklist(Use);
4507     else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4508       // Also look pass the truncate.
4509       Use = *Use->use_begin();
4510       if (Use->getOpcode() == ISD::BRCOND)
4511         AddToWorklist(Use);
4512     }
4513   }
4514
4515   return SDValue();
4516 }
4517
4518 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4519   SDValue N0 = N->getOperand(0);
4520   EVT VT = N->getValueType(0);
4521
4522   // fold (ctlz c1) -> c2
4523   if (isa<ConstantSDNode>(N0))
4524     return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
4525   return SDValue();
4526 }
4527
4528 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4529   SDValue N0 = N->getOperand(0);
4530   EVT VT = N->getValueType(0);
4531
4532   // fold (ctlz_zero_undef c1) -> c2
4533   if (isa<ConstantSDNode>(N0))
4534     return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4535   return SDValue();
4536 }
4537
4538 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4539   SDValue N0 = N->getOperand(0);
4540   EVT VT = N->getValueType(0);
4541
4542   // fold (cttz c1) -> c2
4543   if (isa<ConstantSDNode>(N0))
4544     return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
4545   return SDValue();
4546 }
4547
4548 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4549   SDValue N0 = N->getOperand(0);
4550   EVT VT = N->getValueType(0);
4551
4552   // fold (cttz_zero_undef c1) -> c2
4553   if (isa<ConstantSDNode>(N0))
4554     return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4555   return SDValue();
4556 }
4557
4558 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4559   SDValue N0 = N->getOperand(0);
4560   EVT VT = N->getValueType(0);
4561
4562   // fold (ctpop c1) -> c2
4563   if (isa<ConstantSDNode>(N0))
4564     return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
4565   return SDValue();
4566 }
4567
4568 SDValue DAGCombiner::visitSELECT(SDNode *N) {
4569   SDValue N0 = N->getOperand(0);
4570   SDValue N1 = N->getOperand(1);
4571   SDValue N2 = N->getOperand(2);
4572   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4573   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4574   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
4575   EVT VT = N->getValueType(0);
4576   EVT VT0 = N0.getValueType();
4577
4578   // fold (select C, X, X) -> X
4579   if (N1 == N2)
4580     return N1;
4581   // fold (select true, X, Y) -> X
4582   if (N0C && !N0C->isNullValue())
4583     return N1;
4584   // fold (select false, X, Y) -> Y
4585   if (N0C && N0C->isNullValue())
4586     return N2;
4587   // fold (select C, 1, X) -> (or C, X)
4588   if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
4589     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4590   // fold (select C, 0, 1) -> (xor C, 1)
4591   // We can't do this reliably if integer based booleans have different contents
4592   // to floating point based booleans. This is because we can't tell whether we
4593   // have an integer-based boolean or a floating-point-based boolean unless we
4594   // can find the SETCC that produced it and inspect its operands. This is
4595   // fairly easy if C is the SETCC node, but it can potentially be
4596   // undiscoverable (or not reasonably discoverable). For example, it could be
4597   // in another basic block or it could require searching a complicated
4598   // expression.
4599   if (VT.isInteger() &&
4600       (VT0 == MVT::i1 || (VT0.isInteger() &&
4601                           TLI.getBooleanContents(false, false) ==
4602                               TLI.getBooleanContents(false, true) &&
4603                           TLI.getBooleanContents(false, false) ==
4604                               TargetLowering::ZeroOrOneBooleanContent)) &&
4605       N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
4606     SDValue XORNode;
4607     if (VT == VT0)
4608       return DAG.getNode(ISD::XOR, SDLoc(N), VT0,
4609                          N0, DAG.getConstant(1, VT0));
4610     XORNode = DAG.getNode(ISD::XOR, SDLoc(N0), VT0,
4611                           N0, DAG.getConstant(1, VT0));
4612     AddToWorklist(XORNode.getNode());
4613     if (VT.bitsGT(VT0))
4614       return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4615     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
4616   }
4617   // fold (select C, 0, X) -> (and (not C), X)
4618   if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
4619     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4620     AddToWorklist(NOTNode.getNode());
4621     return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
4622   }
4623   // fold (select C, X, 1) -> (or (not C), X)
4624   if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
4625     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4626     AddToWorklist(NOTNode.getNode());
4627     return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
4628   }
4629   // fold (select C, X, 0) -> (and C, X)
4630   if (VT == MVT::i1 && N2C && N2C->isNullValue())
4631     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4632   // fold (select X, X, Y) -> (or X, Y)
4633   // fold (select X, 1, Y) -> (or X, Y)
4634   if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
4635     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4636   // fold (select X, Y, X) -> (and X, Y)
4637   // fold (select X, Y, 0) -> (and X, Y)
4638   if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
4639     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4640
4641   // If we can fold this based on the true/false value, do so.
4642   if (SimplifySelectOps(N, N1, N2))
4643     return SDValue(N, 0);  // Don't revisit N.
4644
4645   // fold selects based on a setcc into other things, such as min/max/abs
4646   if (N0.getOpcode() == ISD::SETCC) {
4647     if ((!LegalOperations &&
4648          TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
4649         TLI.isOperationLegal(ISD::SELECT_CC, VT))
4650       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
4651                          N0.getOperand(0), N0.getOperand(1),
4652                          N1, N2, N0.getOperand(2));
4653     return SimplifySelect(SDLoc(N), N0, N1, N2);
4654   }
4655
4656   return SDValue();
4657 }
4658
4659 static
4660 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
4661   SDLoc DL(N);
4662   EVT LoVT, HiVT;
4663   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
4664
4665   // Split the inputs.
4666   SDValue Lo, Hi, LL, LH, RL, RH;
4667   std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
4668   std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
4669
4670   Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
4671   Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
4672
4673   return std::make_pair(Lo, Hi);
4674 }
4675
4676 // This function assumes all the vselect's arguments are CONCAT_VECTOR
4677 // nodes and that the condition is a BV of ConstantSDNodes (or undefs).
4678 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
4679   SDLoc dl(N);
4680   SDValue Cond = N->getOperand(0);
4681   SDValue LHS = N->getOperand(1);
4682   SDValue RHS = N->getOperand(2);
4683   EVT VT = N->getValueType(0);
4684   int NumElems = VT.getVectorNumElements();
4685   assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
4686          RHS.getOpcode() == ISD::CONCAT_VECTORS &&
4687          Cond.getOpcode() == ISD::BUILD_VECTOR);
4688
4689   // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about
4690   // binary ones here.
4691   if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2)
4692     return SDValue();
4693
4694   // We're sure we have an even number of elements due to the
4695   // concat_vectors we have as arguments to vselect.
4696   // Skip BV elements until we find one that's not an UNDEF
4697   // After we find an UNDEF element, keep looping until we get to half the
4698   // length of the BV and see if all the non-undef nodes are the same.
4699   ConstantSDNode *BottomHalf = nullptr;
4700   for (int i = 0; i < NumElems / 2; ++i) {
4701     if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
4702       continue;
4703
4704     if (BottomHalf == nullptr)
4705       BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
4706     else if (Cond->getOperand(i).getNode() != BottomHalf)
4707       return SDValue();
4708   }
4709
4710   // Do the same for the second half of the BuildVector
4711   ConstantSDNode *TopHalf = nullptr;
4712   for (int i = NumElems / 2; i < NumElems; ++i) {
4713     if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
4714       continue;
4715
4716     if (TopHalf == nullptr)
4717       TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
4718     else if (Cond->getOperand(i).getNode() != TopHalf)
4719       return SDValue();
4720   }
4721
4722   assert(TopHalf && BottomHalf &&
4723          "One half of the selector was all UNDEFs and the other was all the "
4724          "same value. This should have been addressed before this function.");
4725   return DAG.getNode(
4726       ISD::CONCAT_VECTORS, dl, VT,
4727       BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
4728       TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
4729 }
4730
4731 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
4732   SDValue N0 = N->getOperand(0);
4733   SDValue N1 = N->getOperand(1);
4734   SDValue N2 = N->getOperand(2);
4735   SDLoc DL(N);
4736
4737   // Canonicalize integer abs.
4738   // vselect (setg[te] X,  0),  X, -X ->
4739   // vselect (setgt    X, -1),  X, -X ->
4740   // vselect (setl[te] X,  0), -X,  X ->
4741   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
4742   if (N0.getOpcode() == ISD::SETCC) {
4743     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4744     ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4745     bool isAbs = false;
4746     bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
4747
4748     if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
4749          (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
4750         N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
4751       isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
4752     else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
4753              N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
4754       isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
4755
4756     if (isAbs) {
4757       EVT VT = LHS.getValueType();
4758       SDValue Shift = DAG.getNode(
4759           ISD::SRA, DL, VT, LHS,
4760           DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, VT));
4761       SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
4762       AddToWorklist(Shift.getNode());
4763       AddToWorklist(Add.getNode());
4764       return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
4765     }
4766   }
4767
4768   // If the VSELECT result requires splitting and the mask is provided by a
4769   // SETCC, then split both nodes and its operands before legalization. This
4770   // prevents the type legalizer from unrolling SETCC into scalar comparisons
4771   // and enables future optimizations (e.g. min/max pattern matching on X86).
4772   if (N0.getOpcode() == ISD::SETCC) {
4773     EVT VT = N->getValueType(0);
4774
4775     // Check if any splitting is required.
4776     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
4777         TargetLowering::TypeSplitVector)
4778       return SDValue();
4779
4780     SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
4781     std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
4782     std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
4783     std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
4784
4785     Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
4786     Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
4787
4788     // Add the new VSELECT nodes to the work list in case they need to be split
4789     // again.
4790     AddToWorklist(Lo.getNode());
4791     AddToWorklist(Hi.getNode());
4792
4793     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
4794   }
4795
4796   // Fold (vselect (build_vector all_ones), N1, N2) -> N1
4797   if (ISD::isBuildVectorAllOnes(N0.getNode()))
4798     return N1;
4799   // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
4800   if (ISD::isBuildVectorAllZeros(N0.getNode()))
4801     return N2;
4802
4803   // The ConvertSelectToConcatVector function is assuming both the above
4804   // checks for (vselect (build_vector all{ones,zeros) ...) have been made
4805   // and addressed.
4806   if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
4807       N2.getOpcode() == ISD::CONCAT_VECTORS &&
4808       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
4809     SDValue CV = ConvertSelectToConcatVector(N, DAG);
4810     if (CV.getNode())
4811       return CV;
4812   }
4813
4814   return SDValue();
4815 }
4816
4817 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
4818   SDValue N0 = N->getOperand(0);
4819   SDValue N1 = N->getOperand(1);
4820   SDValue N2 = N->getOperand(2);
4821   SDValue N3 = N->getOperand(3);
4822   SDValue N4 = N->getOperand(4);
4823   ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
4824
4825   // fold select_cc lhs, rhs, x, x, cc -> x
4826   if (N2 == N3)
4827     return N2;
4828
4829   // Determine if the condition we're dealing with is constant
4830   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
4831                               N0, N1, CC, SDLoc(N), false);
4832   if (SCC.getNode()) {
4833     AddToWorklist(SCC.getNode());
4834
4835     if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
4836       if (!SCCC->isNullValue())
4837         return N2;    // cond always true -> true val
4838       else
4839         return N3;    // cond always false -> false val
4840     }
4841
4842     // Fold to a simpler select_cc
4843     if (SCC.getOpcode() == ISD::SETCC)
4844       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
4845                          SCC.getOperand(0), SCC.getOperand(1), N2, N3,
4846                          SCC.getOperand(2));
4847   }
4848
4849   // If we can fold this based on the true/false value, do so.
4850   if (SimplifySelectOps(N, N2, N3))
4851     return SDValue(N, 0);  // Don't revisit N.
4852
4853   // fold select_cc into other things, such as min/max/abs
4854   return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
4855 }
4856
4857 SDValue DAGCombiner::visitSETCC(SDNode *N) {
4858   return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
4859                        cast<CondCodeSDNode>(N->getOperand(2))->get(),
4860                        SDLoc(N));
4861 }
4862
4863 // tryToFoldExtendOfConstant - Try to fold a sext/zext/aext
4864 // dag node into a ConstantSDNode or a build_vector of constants.
4865 // This function is called by the DAGCombiner when visiting sext/zext/aext
4866 // dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
4867 // Vector extends are not folded if operations are legal; this is to
4868 // avoid introducing illegal build_vector dag nodes.
4869 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
4870                                          SelectionDAG &DAG, bool LegalTypes,
4871                                          bool LegalOperations) {
4872   unsigned Opcode = N->getOpcode();
4873   SDValue N0 = N->getOperand(0);
4874   EVT VT = N->getValueType(0);
4875
4876   assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
4877          Opcode == ISD::ANY_EXTEND) && "Expected EXTEND dag node in input!");
4878
4879   // fold (sext c1) -> c1
4880   // fold (zext c1) -> c1
4881   // fold (aext c1) -> c1
4882   if (isa<ConstantSDNode>(N0))
4883     return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
4884
4885   // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
4886   // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
4887   // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
4888   EVT SVT = VT.getScalarType();
4889   if (!(VT.isVector() &&
4890       (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
4891       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
4892     return nullptr;
4893
4894   // We can fold this node into a build_vector.
4895   unsigned VTBits = SVT.getSizeInBits();
4896   unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
4897   unsigned ShAmt = VTBits - EVTBits;
4898   SmallVector<SDValue, 8> Elts;
4899   unsigned NumElts = N0->getNumOperands();
4900   SDLoc DL(N);
4901
4902   for (unsigned i=0; i != NumElts; ++i) {
4903     SDValue Op = N0->getOperand(i);
4904     if (Op->getOpcode() == ISD::UNDEF) {
4905       Elts.push_back(DAG.getUNDEF(SVT));
4906       continue;
4907     }
4908
4909     ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
4910     const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
4911     if (Opcode == ISD::SIGN_EXTEND)
4912       Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
4913                                      SVT));
4914     else
4915       Elts.push_back(DAG.getConstant(C.shl(ShAmt).lshr(ShAmt).getZExtValue(),
4916                                      SVT));
4917   }
4918
4919   return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts).getNode();
4920 }
4921
4922 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
4923 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
4924 // transformation. Returns true if extension are possible and the above
4925 // mentioned transformation is profitable.
4926 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
4927                                     unsigned ExtOpc,
4928                                     SmallVectorImpl<SDNode *> &ExtendNodes,
4929                                     const TargetLowering &TLI) {
4930   bool HasCopyToRegUses = false;
4931   bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
4932   for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
4933                             UE = N0.getNode()->use_end();
4934        UI != UE; ++UI) {
4935     SDNode *User = *UI;
4936     if (User == N)
4937       continue;
4938     if (UI.getUse().getResNo() != N0.getResNo())
4939       continue;
4940     // FIXME: Only extend SETCC N, N and SETCC N, c for now.
4941     if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
4942       ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
4943       if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
4944         // Sign bits will be lost after a zext.
4945         return false;
4946       bool Add = false;
4947       for (unsigned i = 0; i != 2; ++i) {
4948         SDValue UseOp = User->getOperand(i);
4949         if (UseOp == N0)
4950           continue;
4951         if (!isa<ConstantSDNode>(UseOp))
4952           return false;
4953         Add = true;
4954       }
4955       if (Add)
4956         ExtendNodes.push_back(User);
4957       continue;
4958     }
4959     // If truncates aren't free and there are users we can't
4960     // extend, it isn't worthwhile.
4961     if (!isTruncFree)
4962       return false;
4963     // Remember if this value is live-out.
4964     if (User->getOpcode() == ISD::CopyToReg)
4965       HasCopyToRegUses = true;
4966   }
4967
4968   if (HasCopyToRegUses) {
4969     bool BothLiveOut = false;
4970     for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
4971          UI != UE; ++UI) {
4972       SDUse &Use = UI.getUse();
4973       if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
4974         BothLiveOut = true;
4975         break;
4976       }
4977     }
4978     if (BothLiveOut)
4979       // Both unextended and extended values are live out. There had better be
4980       // a good reason for the transformation.
4981       return ExtendNodes.size();
4982   }
4983   return true;
4984 }
4985
4986 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
4987                                   SDValue Trunc, SDValue ExtLoad, SDLoc DL,
4988                                   ISD::NodeType ExtType) {
4989   // Extend SetCC uses if necessary.
4990   for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
4991     SDNode *SetCC = SetCCs[i];
4992     SmallVector<SDValue, 4> Ops;
4993
4994     for (unsigned j = 0; j != 2; ++j) {
4995       SDValue SOp = SetCC->getOperand(j);
4996       if (SOp == Trunc)
4997         Ops.push_back(ExtLoad);
4998       else
4999         Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
5000     }
5001
5002     Ops.push_back(SetCC->getOperand(2));
5003     CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
5004   }
5005 }
5006
5007 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
5008   SDValue N0 = N->getOperand(0);
5009   EVT VT = N->getValueType(0);
5010
5011   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5012                                               LegalOperations))
5013     return SDValue(Res, 0);
5014
5015   // fold (sext (sext x)) -> (sext x)
5016   // fold (sext (aext x)) -> (sext x)
5017   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5018     return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
5019                        N0.getOperand(0));
5020
5021   if (N0.getOpcode() == ISD::TRUNCATE) {
5022     // fold (sext (truncate (load x))) -> (sext (smaller load x))
5023     // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
5024     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5025     if (NarrowLoad.getNode()) {
5026       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5027       if (NarrowLoad.getNode() != N0.getNode()) {
5028         CombineTo(N0.getNode(), NarrowLoad);
5029         // CombineTo deleted the truncate, if needed, but not what's under it.
5030         AddToWorklist(oye);
5031       }
5032       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5033     }
5034
5035     // See if the value being truncated is already sign extended.  If so, just
5036     // eliminate the trunc/sext pair.
5037     SDValue Op = N0.getOperand(0);
5038     unsigned OpBits   = Op.getValueType().getScalarType().getSizeInBits();
5039     unsigned MidBits  = N0.getValueType().getScalarType().getSizeInBits();
5040     unsigned DestBits = VT.getScalarType().getSizeInBits();
5041     unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
5042
5043     if (OpBits == DestBits) {
5044       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
5045       // bits, it is already ready.
5046       if (NumSignBits > DestBits-MidBits)
5047         return Op;
5048     } else if (OpBits < DestBits) {
5049       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
5050       // bits, just sext from i32.
5051       if (NumSignBits > OpBits-MidBits)
5052         return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
5053     } else {
5054       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
5055       // bits, just truncate to i32.
5056       if (NumSignBits > OpBits-MidBits)
5057         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5058     }
5059
5060     // fold (sext (truncate x)) -> (sextinreg x).
5061     if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
5062                                                  N0.getValueType())) {
5063       if (OpBits < DestBits)
5064         Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
5065       else if (OpBits > DestBits)
5066         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
5067       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
5068                          DAG.getValueType(N0.getValueType()));
5069     }
5070   }
5071
5072   // fold (sext (load x)) -> (sext (truncate (sextload x)))
5073   // None of the supported targets knows how to perform load and sign extend
5074   // on vectors in one instruction.  We only perform this transformation on
5075   // scalars.
5076   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5077       ISD::isUNINDEXEDLoad(N0.getNode()) &&
5078       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5079        TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()))) {
5080     bool DoXform = true;
5081     SmallVector<SDNode*, 4> SetCCs;
5082     if (!N0.hasOneUse())
5083       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
5084     if (DoXform) {
5085       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5086       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5087                                        LN0->getChain(),
5088                                        LN0->getBasePtr(), N0.getValueType(),
5089                                        LN0->getMemOperand());
5090       CombineTo(N, ExtLoad);
5091       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5092                                   N0.getValueType(), ExtLoad);
5093       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5094       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5095                       ISD::SIGN_EXTEND);
5096       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5097     }
5098   }
5099
5100   // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
5101   // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
5102   if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5103       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5104     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5105     EVT MemVT = LN0->getMemoryVT();
5106     if ((!LegalOperations && !LN0->isVolatile()) ||
5107         TLI.isLoadExtLegal(ISD::SEXTLOAD, MemVT)) {
5108       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5109                                        LN0->getChain(),
5110                                        LN0->getBasePtr(), MemVT,
5111                                        LN0->getMemOperand());
5112       CombineTo(N, ExtLoad);
5113       CombineTo(N0.getNode(),
5114                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5115                             N0.getValueType(), ExtLoad),
5116                 ExtLoad.getValue(1));
5117       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5118     }
5119   }
5120
5121   // fold (sext (and/or/xor (load x), cst)) ->
5122   //      (and/or/xor (sextload x), (sext cst))
5123   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5124        N0.getOpcode() == ISD::XOR) &&
5125       isa<LoadSDNode>(N0.getOperand(0)) &&
5126       N0.getOperand(1).getOpcode() == ISD::Constant &&
5127       TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()) &&
5128       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5129     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5130     if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
5131       bool DoXform = true;
5132       SmallVector<SDNode*, 4> SetCCs;
5133       if (!N0.hasOneUse())
5134         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
5135                                           SetCCs, TLI);
5136       if (DoXform) {
5137         SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
5138                                          LN0->getChain(), LN0->getBasePtr(),
5139                                          LN0->getMemoryVT(),
5140                                          LN0->getMemOperand());
5141         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5142         Mask = Mask.sext(VT.getSizeInBits());
5143         SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5144                                   ExtLoad, DAG.getConstant(Mask, VT));
5145         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5146                                     SDLoc(N0.getOperand(0)),
5147                                     N0.getOperand(0).getValueType(), ExtLoad);
5148         CombineTo(N, And);
5149         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5150         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5151                         ISD::SIGN_EXTEND);
5152         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5153       }
5154     }
5155   }
5156
5157   if (N0.getOpcode() == ISD::SETCC) {
5158     EVT N0VT = N0.getOperand(0).getValueType();
5159     // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
5160     // Only do this before legalize for now.
5161     if (VT.isVector() && !LegalOperations &&
5162         TLI.getBooleanContents(N0VT) ==
5163             TargetLowering::ZeroOrNegativeOneBooleanContent) {
5164       // On some architectures (such as SSE/NEON/etc) the SETCC result type is
5165       // of the same size as the compared operands. Only optimize sext(setcc())
5166       // if this is the case.
5167       EVT SVT = getSetCCResultType(N0VT);
5168
5169       // We know that the # elements of the results is the same as the
5170       // # elements of the compare (and the # elements of the compare result
5171       // for that matter).  Check to see that they are the same size.  If so,
5172       // we know that the element size of the sext'd result matches the
5173       // element size of the compare operands.
5174       if (VT.getSizeInBits() == SVT.getSizeInBits())
5175         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5176                              N0.getOperand(1),
5177                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
5178
5179       // If the desired elements are smaller or larger than the source
5180       // elements we can use a matching integer vector type and then
5181       // truncate/sign extend
5182       EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5183       if (SVT == MatchingVectorType) {
5184         SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
5185                                N0.getOperand(0), N0.getOperand(1),
5186                                cast<CondCodeSDNode>(N0.getOperand(2))->get());
5187         return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
5188       }
5189     }
5190
5191     // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
5192     unsigned ElementWidth = VT.getScalarType().getSizeInBits();
5193     SDValue NegOne =
5194       DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT);
5195     SDValue SCC =
5196       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5197                        NegOne, DAG.getConstant(0, VT),
5198                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5199     if (SCC.getNode()) return SCC;
5200
5201     if (!VT.isVector()) {
5202       EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
5203       if (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, SetCCVT)) {
5204         SDLoc DL(N);
5205         ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5206         SDValue SetCC = DAG.getSetCC(DL,
5207                                      SetCCVT,
5208                                      N0.getOperand(0), N0.getOperand(1), CC);
5209         EVT SelectVT = getSetCCResultType(VT);
5210         return DAG.getSelect(DL, VT,
5211                              DAG.getSExtOrTrunc(SetCC, DL, SelectVT),
5212                              NegOne, DAG.getConstant(0, VT));
5213
5214       }
5215     }
5216   }
5217
5218   // fold (sext x) -> (zext x) if the sign bit is known zero.
5219   if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
5220       DAG.SignBitIsZero(N0))
5221     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
5222
5223   return SDValue();
5224 }
5225
5226 // isTruncateOf - If N is a truncate of some other value, return true, record
5227 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
5228 // This function computes KnownZero to avoid a duplicated call to
5229 // computeKnownBits in the caller.
5230 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
5231                          APInt &KnownZero) {
5232   APInt KnownOne;
5233   if (N->getOpcode() == ISD::TRUNCATE) {
5234     Op = N->getOperand(0);
5235     DAG.computeKnownBits(Op, KnownZero, KnownOne);
5236     return true;
5237   }
5238
5239   if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
5240       cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
5241     return false;
5242
5243   SDValue Op0 = N->getOperand(0);
5244   SDValue Op1 = N->getOperand(1);
5245   assert(Op0.getValueType() == Op1.getValueType());
5246
5247   ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0);
5248   ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
5249   if (COp0 && COp0->isNullValue())
5250     Op = Op1;
5251   else if (COp1 && COp1->isNullValue())
5252     Op = Op0;
5253   else
5254     return false;
5255
5256   DAG.computeKnownBits(Op, KnownZero, KnownOne);
5257
5258   if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
5259     return false;
5260
5261   return true;
5262 }
5263
5264 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
5265   SDValue N0 = N->getOperand(0);
5266   EVT VT = N->getValueType(0);
5267
5268   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5269                                               LegalOperations))
5270     return SDValue(Res, 0);
5271
5272   // fold (zext (zext x)) -> (zext x)
5273   // fold (zext (aext x)) -> (zext x)
5274   if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5275     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
5276                        N0.getOperand(0));
5277
5278   // fold (zext (truncate x)) -> (zext x) or
5279   //      (zext (truncate x)) -> (truncate x)
5280   // This is valid when the truncated bits of x are already zero.
5281   // FIXME: We should extend this to work for vectors too.
5282   SDValue Op;
5283   APInt KnownZero;
5284   if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
5285     APInt TruncatedBits =
5286       (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
5287       APInt(Op.getValueSizeInBits(), 0) :
5288       APInt::getBitsSet(Op.getValueSizeInBits(),
5289                         N0.getValueSizeInBits(),
5290                         std::min(Op.getValueSizeInBits(),
5291                                  VT.getSizeInBits()));
5292     if (TruncatedBits == (KnownZero & TruncatedBits)) {
5293       if (VT.bitsGT(Op.getValueType()))
5294         return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
5295       if (VT.bitsLT(Op.getValueType()))
5296         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5297
5298       return Op;
5299     }
5300   }
5301
5302   // fold (zext (truncate (load x))) -> (zext (smaller load x))
5303   // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
5304   if (N0.getOpcode() == ISD::TRUNCATE) {
5305     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5306     if (NarrowLoad.getNode()) {
5307       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5308       if (NarrowLoad.getNode() != N0.getNode()) {
5309         CombineTo(N0.getNode(), NarrowLoad);
5310         // CombineTo deleted the truncate, if needed, but not what's under it.
5311         AddToWorklist(oye);
5312       }
5313       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5314     }
5315   }
5316
5317   // fold (zext (truncate x)) -> (and x, mask)
5318   if (N0.getOpcode() == ISD::TRUNCATE &&
5319       (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
5320
5321     // fold (zext (truncate (load x))) -> (zext (smaller load x))
5322     // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
5323     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5324     if (NarrowLoad.getNode()) {
5325       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5326       if (NarrowLoad.getNode() != N0.getNode()) {
5327         CombineTo(N0.getNode(), NarrowLoad);
5328         // CombineTo deleted the truncate, if needed, but not what's under it.
5329         AddToWorklist(oye);
5330       }
5331       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5332     }
5333
5334     SDValue Op = N0.getOperand(0);
5335     if (Op.getValueType().bitsLT(VT)) {
5336       Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
5337       AddToWorklist(Op.getNode());
5338     } else if (Op.getValueType().bitsGT(VT)) {
5339       Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5340       AddToWorklist(Op.getNode());
5341     }
5342     return DAG.getZeroExtendInReg(Op, SDLoc(N),
5343                                   N0.getValueType().getScalarType());
5344   }
5345
5346   // Fold (zext (and (trunc x), cst)) -> (and x, cst),
5347   // if either of the casts is not free.
5348   if (N0.getOpcode() == ISD::AND &&
5349       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5350       N0.getOperand(1).getOpcode() == ISD::Constant &&
5351       (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5352                            N0.getValueType()) ||
5353        !TLI.isZExtFree(N0.getValueType(), VT))) {
5354     SDValue X = N0.getOperand(0).getOperand(0);
5355     if (X.getValueType().bitsLT(VT)) {
5356       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
5357     } else if (X.getValueType().bitsGT(VT)) {
5358       X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
5359     }
5360     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5361     Mask = Mask.zext(VT.getSizeInBits());
5362     return DAG.getNode(ISD::AND, SDLoc(N), VT,
5363                        X, DAG.getConstant(Mask, VT));
5364   }
5365
5366   // fold (zext (load x)) -> (zext (truncate (zextload x)))
5367   // None of the supported targets knows how to perform load and vector_zext
5368   // on vectors in one instruction.  We only perform this transformation on
5369   // scalars.
5370   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5371       ISD::isUNINDEXEDLoad(N0.getNode()) &&
5372       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5373        TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()))) {
5374     bool DoXform = true;
5375     SmallVector<SDNode*, 4> SetCCs;
5376     if (!N0.hasOneUse())
5377       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
5378     if (DoXform) {
5379       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5380       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5381                                        LN0->getChain(),
5382                                        LN0->getBasePtr(), N0.getValueType(),
5383                                        LN0->getMemOperand());
5384       CombineTo(N, ExtLoad);
5385       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5386                                   N0.getValueType(), ExtLoad);
5387       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5388
5389       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5390                       ISD::ZERO_EXTEND);
5391       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5392     }
5393   }
5394
5395   // fold (zext (and/or/xor (load x), cst)) ->
5396   //      (and/or/xor (zextload x), (zext cst))
5397   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5398        N0.getOpcode() == ISD::XOR) &&
5399       isa<LoadSDNode>(N0.getOperand(0)) &&
5400       N0.getOperand(1).getOpcode() == ISD::Constant &&
5401       TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()) &&
5402       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5403     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5404     if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
5405       bool DoXform = true;
5406       SmallVector<SDNode*, 4> SetCCs;
5407       if (!N0.hasOneUse())
5408         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
5409                                           SetCCs, TLI);
5410       if (DoXform) {
5411         SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
5412                                          LN0->getChain(), LN0->getBasePtr(),
5413                                          LN0->getMemoryVT(),
5414                                          LN0->getMemOperand());
5415         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5416         Mask = Mask.zext(VT.getSizeInBits());
5417         SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5418                                   ExtLoad, DAG.getConstant(Mask, VT));
5419         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5420                                     SDLoc(N0.getOperand(0)),
5421                                     N0.getOperand(0).getValueType(), ExtLoad);
5422         CombineTo(N, And);
5423         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5424         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5425                         ISD::ZERO_EXTEND);
5426         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5427       }
5428     }
5429   }
5430
5431   // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
5432   // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
5433   if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5434       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5435     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5436     EVT MemVT = LN0->getMemoryVT();
5437     if ((!LegalOperations && !LN0->isVolatile()) ||
5438         TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT)) {
5439       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5440                                        LN0->getChain(),
5441                                        LN0->getBasePtr(), MemVT,
5442                                        LN0->getMemOperand());
5443       CombineTo(N, ExtLoad);
5444       CombineTo(N0.getNode(),
5445                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
5446                             ExtLoad),
5447                 ExtLoad.getValue(1));
5448       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5449     }
5450   }
5451
5452   if (N0.getOpcode() == ISD::SETCC) {
5453     if (!LegalOperations && VT.isVector() &&
5454         N0.getValueType().getVectorElementType() == MVT::i1) {
5455       EVT N0VT = N0.getOperand(0).getValueType();
5456       if (getSetCCResultType(N0VT) == N0.getValueType())
5457         return SDValue();
5458
5459       // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
5460       // Only do this before legalize for now.
5461       EVT EltVT = VT.getVectorElementType();
5462       SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
5463                                     DAG.getConstant(1, EltVT));
5464       if (VT.getSizeInBits() == N0VT.getSizeInBits())
5465         // We know that the # elements of the results is the same as the
5466         // # elements of the compare (and the # elements of the compare result
5467         // for that matter).  Check to see that they are the same size.  If so,
5468         // we know that the element size of the sext'd result matches the
5469         // element size of the compare operands.
5470         return DAG.getNode(ISD::AND, SDLoc(N), VT,
5471                            DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5472                                          N0.getOperand(1),
5473                                  cast<CondCodeSDNode>(N0.getOperand(2))->get()),
5474                            DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
5475                                        OneOps));
5476
5477       // If the desired elements are smaller or larger than the source
5478       // elements we can use a matching integer vector type and then
5479       // truncate/sign extend
5480       EVT MatchingElementType =
5481         EVT::getIntegerVT(*DAG.getContext(),
5482                           N0VT.getScalarType().getSizeInBits());
5483       EVT MatchingVectorType =
5484         EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
5485                          N0VT.getVectorNumElements());
5486       SDValue VsetCC =
5487         DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5488                       N0.getOperand(1),
5489                       cast<CondCodeSDNode>(N0.getOperand(2))->get());
5490       return DAG.getNode(ISD::AND, SDLoc(N), VT,
5491                          DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT),
5492                          DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, OneOps));
5493     }
5494
5495     // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5496     SDValue SCC =
5497       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5498                        DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5499                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5500     if (SCC.getNode()) return SCC;
5501   }
5502
5503   // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
5504   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
5505       isa<ConstantSDNode>(N0.getOperand(1)) &&
5506       N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
5507       N0.hasOneUse()) {
5508     SDValue ShAmt = N0.getOperand(1);
5509     unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
5510     if (N0.getOpcode() == ISD::SHL) {
5511       SDValue InnerZExt = N0.getOperand(0);
5512       // If the original shl may be shifting out bits, do not perform this
5513       // transformation.
5514       unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
5515         InnerZExt.getOperand(0).getValueType().getSizeInBits();
5516       if (ShAmtVal > KnownZeroBits)
5517         return SDValue();
5518     }
5519
5520     SDLoc DL(N);
5521
5522     // Ensure that the shift amount is wide enough for the shifted value.
5523     if (VT.getSizeInBits() >= 256)
5524       ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
5525
5526     return DAG.getNode(N0.getOpcode(), DL, VT,
5527                        DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
5528                        ShAmt);
5529   }
5530
5531   return SDValue();
5532 }
5533
5534 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
5535   SDValue N0 = N->getOperand(0);
5536   EVT VT = N->getValueType(0);
5537
5538   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5539                                               LegalOperations))
5540     return SDValue(Res, 0);
5541
5542   // fold (aext (aext x)) -> (aext x)
5543   // fold (aext (zext x)) -> (zext x)
5544   // fold (aext (sext x)) -> (sext x)
5545   if (N0.getOpcode() == ISD::ANY_EXTEND  ||
5546       N0.getOpcode() == ISD::ZERO_EXTEND ||
5547       N0.getOpcode() == ISD::SIGN_EXTEND)
5548     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
5549
5550   // fold (aext (truncate (load x))) -> (aext (smaller load x))
5551   // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
5552   if (N0.getOpcode() == ISD::TRUNCATE) {
5553     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5554     if (NarrowLoad.getNode()) {
5555       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5556       if (NarrowLoad.getNode() != N0.getNode()) {
5557         CombineTo(N0.getNode(), NarrowLoad);
5558         // CombineTo deleted the truncate, if needed, but not what's under it.
5559         AddToWorklist(oye);
5560       }
5561       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5562     }
5563   }
5564
5565   // fold (aext (truncate x))
5566   if (N0.getOpcode() == ISD::TRUNCATE) {
5567     SDValue TruncOp = N0.getOperand(0);
5568     if (TruncOp.getValueType() == VT)
5569       return TruncOp; // x iff x size == zext size.
5570     if (TruncOp.getValueType().bitsGT(VT))
5571       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
5572     return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
5573   }
5574
5575   // Fold (aext (and (trunc x), cst)) -> (and x, cst)
5576   // if the trunc is not free.
5577   if (N0.getOpcode() == ISD::AND &&
5578       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5579       N0.getOperand(1).getOpcode() == ISD::Constant &&
5580       !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5581                           N0.getValueType())) {
5582     SDValue X = N0.getOperand(0).getOperand(0);
5583     if (X.getValueType().bitsLT(VT)) {
5584       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
5585     } else if (X.getValueType().bitsGT(VT)) {
5586       X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
5587     }
5588     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5589     Mask = Mask.zext(VT.getSizeInBits());
5590     return DAG.getNode(ISD::AND, SDLoc(N), VT,
5591                        X, DAG.getConstant(Mask, VT));
5592   }
5593
5594   // fold (aext (load x)) -> (aext (truncate (extload x)))
5595   // None of the supported targets knows how to perform load and any_ext
5596   // on vectors in one instruction.  We only perform this transformation on
5597   // scalars.
5598   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5599       ISD::isUNINDEXEDLoad(N0.getNode()) &&
5600       TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType())) {
5601     bool DoXform = true;
5602     SmallVector<SDNode*, 4> SetCCs;
5603     if (!N0.hasOneUse())
5604       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
5605     if (DoXform) {
5606       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5607       SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
5608                                        LN0->getChain(),
5609                                        LN0->getBasePtr(), N0.getValueType(),
5610                                        LN0->getMemOperand());
5611       CombineTo(N, ExtLoad);
5612       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5613                                   N0.getValueType(), ExtLoad);
5614       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5615       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5616                       ISD::ANY_EXTEND);
5617       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5618     }
5619   }
5620
5621   // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
5622   // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
5623   // fold (aext ( extload x)) -> (aext (truncate (extload  x)))
5624   if (N0.getOpcode() == ISD::LOAD &&
5625       !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5626       N0.hasOneUse()) {
5627     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5628     ISD::LoadExtType ExtType = LN0->getExtensionType();
5629     EVT MemVT = LN0->getMemoryVT();
5630     if (!LegalOperations || TLI.isLoadExtLegal(ExtType, MemVT)) {
5631       SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
5632                                        VT, LN0->getChain(), LN0->getBasePtr(),
5633                                        MemVT, LN0->getMemOperand());
5634       CombineTo(N, ExtLoad);
5635       CombineTo(N0.getNode(),
5636                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5637                             N0.getValueType(), ExtLoad),
5638                 ExtLoad.getValue(1));
5639       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5640     }
5641   }
5642
5643   if (N0.getOpcode() == ISD::SETCC) {
5644     // For vectors:
5645     // aext(setcc) -> vsetcc
5646     // aext(setcc) -> truncate(vsetcc)
5647     // aext(setcc) -> aext(vsetcc)
5648     // Only do this before legalize for now.
5649     if (VT.isVector() && !LegalOperations) {
5650       EVT N0VT = N0.getOperand(0).getValueType();
5651         // We know that the # elements of the results is the same as the
5652         // # elements of the compare (and the # elements of the compare result
5653         // for that matter).  Check to see that they are the same size.  If so,
5654         // we know that the element size of the sext'd result matches the
5655         // element size of the compare operands.
5656       if (VT.getSizeInBits() == N0VT.getSizeInBits())
5657         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5658                              N0.getOperand(1),
5659                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
5660       // If the desired elements are smaller or larger than the source
5661       // elements we can use a matching integer vector type and then
5662       // truncate/any extend
5663       else {
5664         EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5665         SDValue VsetCC =
5666           DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5667                         N0.getOperand(1),
5668                         cast<CondCodeSDNode>(N0.getOperand(2))->get());
5669         return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
5670       }
5671     }
5672
5673     // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5674     SDValue SCC =
5675       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5676                        DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5677                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5678     if (SCC.getNode())
5679       return SCC;
5680   }
5681
5682   return SDValue();
5683 }
5684
5685 /// See if the specified operand can be simplified with the knowledge that only
5686 /// the bits specified by Mask are used.  If so, return the simpler operand,
5687 /// otherwise return a null SDValue.
5688 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
5689   switch (V.getOpcode()) {
5690   default: break;
5691   case ISD::Constant: {
5692     const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
5693     assert(CV && "Const value should be ConstSDNode.");
5694     const APInt &CVal = CV->getAPIntValue();
5695     APInt NewVal = CVal & Mask;
5696     if (NewVal != CVal)
5697       return DAG.getConstant(NewVal, V.getValueType());
5698     break;
5699   }
5700   case ISD::OR:
5701   case ISD::XOR:
5702     // If the LHS or RHS don't contribute bits to the or, drop them.
5703     if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
5704       return V.getOperand(1);
5705     if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
5706       return V.getOperand(0);
5707     break;
5708   case ISD::SRL:
5709     // Only look at single-use SRLs.
5710     if (!V.getNode()->hasOneUse())
5711       break;
5712     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
5713       // See if we can recursively simplify the LHS.
5714       unsigned Amt = RHSC->getZExtValue();
5715
5716       // Watch out for shift count overflow though.
5717       if (Amt >= Mask.getBitWidth()) break;
5718       APInt NewMask = Mask << Amt;
5719       SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
5720       if (SimplifyLHS.getNode())
5721         return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
5722                            SimplifyLHS, V.getOperand(1));
5723     }
5724   }
5725   return SDValue();
5726 }
5727
5728 /// If the result of a wider load is shifted to right of N  bits and then
5729 /// truncated to a narrower type and where N is a multiple of number of bits of
5730 /// the narrower type, transform it to a narrower load from address + N / num of
5731 /// bits of new type. If the result is to be extended, also fold the extension
5732 /// to form a extending load.
5733 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
5734   unsigned Opc = N->getOpcode();
5735
5736   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
5737   SDValue N0 = N->getOperand(0);
5738   EVT VT = N->getValueType(0);
5739   EVT ExtVT = VT;
5740
5741   // This transformation isn't valid for vector loads.
5742   if (VT.isVector())
5743     return SDValue();
5744
5745   // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
5746   // extended to VT.
5747   if (Opc == ISD::SIGN_EXTEND_INREG) {
5748     ExtType = ISD::SEXTLOAD;
5749     ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
5750   } else if (Opc == ISD::SRL) {
5751     // Another special-case: SRL is basically zero-extending a narrower value.
5752     ExtType = ISD::ZEXTLOAD;
5753     N0 = SDValue(N, 0);
5754     ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
5755     if (!N01) return SDValue();
5756     ExtVT = EVT::getIntegerVT(*DAG.getContext(),
5757                               VT.getSizeInBits() - N01->getZExtValue());
5758   }
5759   if (LegalOperations && !TLI.isLoadExtLegal(ExtType, ExtVT))
5760     return SDValue();
5761
5762   unsigned EVTBits = ExtVT.getSizeInBits();
5763
5764   // Do not generate loads of non-round integer types since these can
5765   // be expensive (and would be wrong if the type is not byte sized).
5766   if (!ExtVT.isRound())
5767     return SDValue();
5768
5769   unsigned ShAmt = 0;
5770   if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
5771     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5772       ShAmt = N01->getZExtValue();
5773       // Is the shift amount a multiple of size of VT?
5774       if ((ShAmt & (EVTBits-1)) == 0) {
5775         N0 = N0.getOperand(0);
5776         // Is the load width a multiple of size of VT?
5777         if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
5778           return SDValue();
5779       }
5780
5781       // At this point, we must have a load or else we can't do the transform.
5782       if (!isa<LoadSDNode>(N0)) return SDValue();
5783
5784       // Because a SRL must be assumed to *need* to zero-extend the high bits
5785       // (as opposed to anyext the high bits), we can't combine the zextload
5786       // lowering of SRL and an sextload.
5787       if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
5788         return SDValue();
5789
5790       // If the shift amount is larger than the input type then we're not
5791       // accessing any of the loaded bytes.  If the load was a zextload/extload
5792       // then the result of the shift+trunc is zero/undef (handled elsewhere).
5793       if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
5794         return SDValue();
5795     }
5796   }
5797
5798   // If the load is shifted left (and the result isn't shifted back right),
5799   // we can fold the truncate through the shift.
5800   unsigned ShLeftAmt = 0;
5801   if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
5802       ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
5803     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5804       ShLeftAmt = N01->getZExtValue();
5805       N0 = N0.getOperand(0);
5806     }
5807   }
5808
5809   // If we haven't found a load, we can't narrow it.  Don't transform one with
5810   // multiple uses, this would require adding a new load.
5811   if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
5812     return SDValue();
5813
5814   // Don't change the width of a volatile load.
5815   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5816   if (LN0->isVolatile())
5817     return SDValue();
5818
5819   // Verify that we are actually reducing a load width here.
5820   if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
5821     return SDValue();
5822
5823   // For the transform to be legal, the load must produce only two values
5824   // (the value loaded and the chain).  Don't transform a pre-increment
5825   // load, for example, which produces an extra value.  Otherwise the
5826   // transformation is not equivalent, and the downstream logic to replace
5827   // uses gets things wrong.
5828   if (LN0->getNumValues() > 2)
5829     return SDValue();
5830
5831   // If the load that we're shrinking is an extload and we're not just
5832   // discarding the extension we can't simply shrink the load. Bail.
5833   // TODO: It would be possible to merge the extensions in some cases.
5834   if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
5835       LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
5836     return SDValue();
5837
5838   EVT PtrType = N0.getOperand(1).getValueType();
5839
5840   if (PtrType == MVT::Untyped || PtrType.isExtended())
5841     // It's not possible to generate a constant of extended or untyped type.
5842     return SDValue();
5843
5844   // For big endian targets, we need to adjust the offset to the pointer to
5845   // load the correct bytes.
5846   if (TLI.isBigEndian()) {
5847     unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
5848     unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
5849     ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
5850   }
5851
5852   uint64_t PtrOff = ShAmt / 8;
5853   unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
5854   SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0),
5855                                PtrType, LN0->getBasePtr(),
5856                                DAG.getConstant(PtrOff, PtrType));
5857   AddToWorklist(NewPtr.getNode());
5858
5859   SDValue Load;
5860   if (ExtType == ISD::NON_EXTLOAD)
5861     Load =  DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
5862                         LN0->getPointerInfo().getWithOffset(PtrOff),
5863                         LN0->isVolatile(), LN0->isNonTemporal(),
5864                         LN0->isInvariant(), NewAlign, LN0->getAAInfo());
5865   else
5866     Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
5867                           LN0->getPointerInfo().getWithOffset(PtrOff),
5868                           ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
5869                           LN0->isInvariant(), NewAlign, LN0->getAAInfo());
5870
5871   // Replace the old load's chain with the new load's chain.
5872   WorklistRemover DeadNodes(*this);
5873   DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
5874
5875   // Shift the result left, if we've swallowed a left shift.
5876   SDValue Result = Load;
5877   if (ShLeftAmt != 0) {
5878     EVT ShImmTy = getShiftAmountTy(Result.getValueType());
5879     if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
5880       ShImmTy = VT;
5881     // If the shift amount is as large as the result size (but, presumably,
5882     // no larger than the source) then the useful bits of the result are
5883     // zero; we can't simply return the shortened shift, because the result
5884     // of that operation is undefined.
5885     if (ShLeftAmt >= VT.getSizeInBits())
5886       Result = DAG.getConstant(0, VT);
5887     else
5888       Result = DAG.getNode(ISD::SHL, SDLoc(N0), VT,
5889                           Result, DAG.getConstant(ShLeftAmt, ShImmTy));
5890   }
5891
5892   // Return the new loaded value.
5893   return Result;
5894 }
5895
5896 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
5897   SDValue N0 = N->getOperand(0);
5898   SDValue N1 = N->getOperand(1);
5899   EVT VT = N->getValueType(0);
5900   EVT EVT = cast<VTSDNode>(N1)->getVT();
5901   unsigned VTBits = VT.getScalarType().getSizeInBits();
5902   unsigned EVTBits = EVT.getScalarType().getSizeInBits();
5903
5904   // fold (sext_in_reg c1) -> c1
5905   if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
5906     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
5907
5908   // If the input is already sign extended, just drop the extension.
5909   if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
5910     return N0;
5911
5912   // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
5913   if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
5914       EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
5915     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5916                        N0.getOperand(0), N1);
5917
5918   // fold (sext_in_reg (sext x)) -> (sext x)
5919   // fold (sext_in_reg (aext x)) -> (sext x)
5920   // if x is small enough.
5921   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
5922     SDValue N00 = N0.getOperand(0);
5923     if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
5924         (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
5925       return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
5926   }
5927
5928   // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
5929   if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
5930     return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
5931
5932   // fold operands of sext_in_reg based on knowledge that the top bits are not
5933   // demanded.
5934   if (SimplifyDemandedBits(SDValue(N, 0)))
5935     return SDValue(N, 0);
5936
5937   // fold (sext_in_reg (load x)) -> (smaller sextload x)
5938   // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
5939   SDValue NarrowLoad = ReduceLoadWidth(N);
5940   if (NarrowLoad.getNode())
5941     return NarrowLoad;
5942
5943   // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
5944   // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
5945   // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
5946   if (N0.getOpcode() == ISD::SRL) {
5947     if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
5948       if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
5949         // We can turn this into an SRA iff the input to the SRL is already sign
5950         // extended enough.
5951         unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
5952         if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
5953           return DAG.getNode(ISD::SRA, SDLoc(N), VT,
5954                              N0.getOperand(0), N0.getOperand(1));
5955       }
5956   }
5957
5958   // fold (sext_inreg (extload x)) -> (sextload x)
5959   if (ISD::isEXTLoad(N0.getNode()) &&
5960       ISD::isUNINDEXEDLoad(N0.getNode()) &&
5961       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5962       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5963        TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5964     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5965     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5966                                      LN0->getChain(),
5967                                      LN0->getBasePtr(), EVT,
5968                                      LN0->getMemOperand());
5969     CombineTo(N, ExtLoad);
5970     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5971     AddToWorklist(ExtLoad.getNode());
5972     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5973   }
5974   // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
5975   if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5976       N0.hasOneUse() &&
5977       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5978       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5979        TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5980     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5981     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5982                                      LN0->getChain(),
5983                                      LN0->getBasePtr(), EVT,
5984                                      LN0->getMemOperand());
5985     CombineTo(N, ExtLoad);
5986     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5987     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5988   }
5989
5990   // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
5991   if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
5992     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
5993                                        N0.getOperand(1), false);
5994     if (BSwap.getNode())
5995       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5996                          BSwap, N1);
5997   }
5998
5999   // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs
6000   // into a build_vector.
6001   if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
6002     SmallVector<SDValue, 8> Elts;
6003     unsigned NumElts = N0->getNumOperands();
6004     unsigned ShAmt = VTBits - EVTBits;
6005
6006     for (unsigned i = 0; i != NumElts; ++i) {
6007       SDValue Op = N0->getOperand(i);
6008       if (Op->getOpcode() == ISD::UNDEF) {
6009         Elts.push_back(Op);
6010         continue;
6011       }
6012
6013       ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
6014       const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
6015       Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
6016                                      Op.getValueType()));
6017     }
6018
6019     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Elts);
6020   }
6021
6022   return SDValue();
6023 }
6024
6025 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
6026   SDValue N0 = N->getOperand(0);
6027   EVT VT = N->getValueType(0);
6028   bool isLE = TLI.isLittleEndian();
6029
6030   // noop truncate
6031   if (N0.getValueType() == N->getValueType(0))
6032     return N0;
6033   // fold (truncate c1) -> c1
6034   if (isa<ConstantSDNode>(N0))
6035     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
6036   // fold (truncate (truncate x)) -> (truncate x)
6037   if (N0.getOpcode() == ISD::TRUNCATE)
6038     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6039   // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
6040   if (N0.getOpcode() == ISD::ZERO_EXTEND ||
6041       N0.getOpcode() == ISD::SIGN_EXTEND ||
6042       N0.getOpcode() == ISD::ANY_EXTEND) {
6043     if (N0.getOperand(0).getValueType().bitsLT(VT))
6044       // if the source is smaller than the dest, we still need an extend
6045       return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
6046                          N0.getOperand(0));
6047     if (N0.getOperand(0).getValueType().bitsGT(VT))
6048       // if the source is larger than the dest, than we just need the truncate
6049       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6050     // if the source and dest are the same type, we can drop both the extend
6051     // and the truncate.
6052     return N0.getOperand(0);
6053   }
6054
6055   // Fold extract-and-trunc into a narrow extract. For example:
6056   //   i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
6057   //   i32 y = TRUNCATE(i64 x)
6058   //        -- becomes --
6059   //   v16i8 b = BITCAST (v2i64 val)
6060   //   i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
6061   //
6062   // Note: We only run this optimization after type legalization (which often
6063   // creates this pattern) and before operation legalization after which
6064   // we need to be more careful about the vector instructions that we generate.
6065   if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6066       LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
6067
6068     EVT VecTy = N0.getOperand(0).getValueType();
6069     EVT ExTy = N0.getValueType();
6070     EVT TrTy = N->getValueType(0);
6071
6072     unsigned NumElem = VecTy.getVectorNumElements();
6073     unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
6074
6075     EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
6076     assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
6077
6078     SDValue EltNo = N0->getOperand(1);
6079     if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
6080       int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
6081       EVT IndexTy = TLI.getVectorIdxTy();
6082       int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
6083
6084       SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
6085                               NVT, N0.getOperand(0));
6086
6087       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
6088                          SDLoc(N), TrTy, V,
6089                          DAG.getConstant(Index, IndexTy));
6090     }
6091   }
6092
6093   // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
6094   if (N0.getOpcode() == ISD::SELECT) {
6095     EVT SrcVT = N0.getValueType();
6096     if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
6097         TLI.isTruncateFree(SrcVT, VT)) {
6098       SDLoc SL(N0);
6099       SDValue Cond = N0.getOperand(0);
6100       SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
6101       SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
6102       return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
6103     }
6104   }
6105
6106   // Fold a series of buildvector, bitcast, and truncate if possible.
6107   // For example fold
6108   //   (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
6109   //   (2xi32 (buildvector x, y)).
6110   if (Level == AfterLegalizeVectorOps && VT.isVector() &&
6111       N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
6112       N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
6113       N0.getOperand(0).hasOneUse()) {
6114
6115     SDValue BuildVect = N0.getOperand(0);
6116     EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
6117     EVT TruncVecEltTy = VT.getVectorElementType();
6118
6119     // Check that the element types match.
6120     if (BuildVectEltTy == TruncVecEltTy) {
6121       // Now we only need to compute the offset of the truncated elements.
6122       unsigned BuildVecNumElts =  BuildVect.getNumOperands();
6123       unsigned TruncVecNumElts = VT.getVectorNumElements();
6124       unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
6125
6126       assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
6127              "Invalid number of elements");
6128
6129       SmallVector<SDValue, 8> Opnds;
6130       for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
6131         Opnds.push_back(BuildVect.getOperand(i));
6132
6133       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
6134     }
6135   }
6136
6137   // See if we can simplify the input to this truncate through knowledge that
6138   // only the low bits are being used.
6139   // For example "trunc (or (shl x, 8), y)" // -> trunc y
6140   // Currently we only perform this optimization on scalars because vectors
6141   // may have different active low bits.
6142   if (!VT.isVector()) {
6143     SDValue Shorter =
6144       GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
6145                                                VT.getSizeInBits()));
6146     if (Shorter.getNode())
6147       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
6148   }
6149   // fold (truncate (load x)) -> (smaller load x)
6150   // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
6151   if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
6152     SDValue Reduced = ReduceLoadWidth(N);
6153     if (Reduced.getNode())
6154       return Reduced;
6155     // Handle the case where the load remains an extending load even
6156     // after truncation.
6157     if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
6158       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6159       if (!LN0->isVolatile() &&
6160           LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
6161         SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
6162                                          VT, LN0->getChain(), LN0->getBasePtr(),
6163                                          LN0->getMemoryVT(),
6164                                          LN0->getMemOperand());
6165         DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
6166         return NewLoad;
6167       }
6168     }
6169   }
6170   // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
6171   // where ... are all 'undef'.
6172   if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
6173     SmallVector<EVT, 8> VTs;
6174     SDValue V;
6175     unsigned Idx = 0;
6176     unsigned NumDefs = 0;
6177
6178     for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
6179       SDValue X = N0.getOperand(i);
6180       if (X.getOpcode() != ISD::UNDEF) {
6181         V = X;
6182         Idx = i;
6183         NumDefs++;
6184       }
6185       // Stop if more than one members are non-undef.
6186       if (NumDefs > 1)
6187         break;
6188       VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
6189                                      VT.getVectorElementType(),
6190                                      X.getValueType().getVectorNumElements()));
6191     }
6192
6193     if (NumDefs == 0)
6194       return DAG.getUNDEF(VT);
6195
6196     if (NumDefs == 1) {
6197       assert(V.getNode() && "The single defined operand is empty!");
6198       SmallVector<SDValue, 8> Opnds;
6199       for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
6200         if (i != Idx) {
6201           Opnds.push_back(DAG.getUNDEF(VTs[i]));
6202           continue;
6203         }
6204         SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
6205         AddToWorklist(NV.getNode());
6206         Opnds.push_back(NV);
6207       }
6208       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
6209     }
6210   }
6211
6212   // Simplify the operands using demanded-bits information.
6213   if (!VT.isVector() &&
6214       SimplifyDemandedBits(SDValue(N, 0)))
6215     return SDValue(N, 0);
6216
6217   return SDValue();
6218 }
6219
6220 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
6221   SDValue Elt = N->getOperand(i);
6222   if (Elt.getOpcode() != ISD::MERGE_VALUES)
6223     return Elt.getNode();
6224   return Elt.getOperand(Elt.getResNo()).getNode();
6225 }
6226
6227 /// build_pair (load, load) -> load
6228 /// if load locations are consecutive.
6229 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
6230   assert(N->getOpcode() == ISD::BUILD_PAIR);
6231
6232   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
6233   LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
6234   if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
6235       LD1->getAddressSpace() != LD2->getAddressSpace())
6236     return SDValue();
6237   EVT LD1VT = LD1->getValueType(0);
6238
6239   if (ISD::isNON_EXTLoad(LD2) &&
6240       LD2->hasOneUse() &&
6241       // If both are volatile this would reduce the number of volatile loads.
6242       // If one is volatile it might be ok, but play conservative and bail out.
6243       !LD1->isVolatile() &&
6244       !LD2->isVolatile() &&
6245       DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
6246     unsigned Align = LD1->getAlignment();
6247     unsigned NewAlign = TLI.getDataLayout()->
6248       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6249
6250     if (NewAlign <= Align &&
6251         (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
6252       return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
6253                          LD1->getBasePtr(), LD1->getPointerInfo(),
6254                          false, false, false, Align);
6255   }
6256
6257   return SDValue();
6258 }
6259
6260 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
6261   SDValue N0 = N->getOperand(0);
6262   EVT VT = N->getValueType(0);
6263
6264   // If the input is a BUILD_VECTOR with all constant elements, fold this now.
6265   // Only do this before legalize, since afterward the target may be depending
6266   // on the bitconvert.
6267   // First check to see if this is all constant.
6268   if (!LegalTypes &&
6269       N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
6270       VT.isVector()) {
6271     bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
6272
6273     EVT DestEltVT = N->getValueType(0).getVectorElementType();
6274     assert(!DestEltVT.isVector() &&
6275            "Element type of vector ValueType must not be vector!");
6276     if (isSimple)
6277       return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
6278   }
6279
6280   // If the input is a constant, let getNode fold it.
6281   if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
6282     SDValue Res = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
6283     if (Res.getNode() != N) {
6284       if (!LegalOperations ||
6285           TLI.isOperationLegal(Res.getNode()->getOpcode(), VT))
6286         return Res;
6287
6288       // Folding it resulted in an illegal node, and it's too late to
6289       // do that. Clean up the old node and forego the transformation.
6290       // Ideally this won't happen very often, because instcombine
6291       // and the earlier dagcombine runs (where illegal nodes are
6292       // permitted) should have folded most of them already.
6293       deleteAndRecombine(Res.getNode());
6294     }
6295   }
6296
6297   // (conv (conv x, t1), t2) -> (conv x, t2)
6298   if (N0.getOpcode() == ISD::BITCAST)
6299     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
6300                        N0.getOperand(0));
6301
6302   // fold (conv (load x)) -> (load (conv*)x)
6303   // If the resultant load doesn't need a higher alignment than the original!
6304   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
6305       // Do not change the width of a volatile load.
6306       !cast<LoadSDNode>(N0)->isVolatile() &&
6307       // Do not remove the cast if the types differ in endian layout.
6308       TLI.hasBigEndianPartOrdering(N0.getValueType()) ==
6309       TLI.hasBigEndianPartOrdering(VT) &&
6310       (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
6311       TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
6312     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6313     unsigned Align = TLI.getDataLayout()->
6314       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6315     unsigned OrigAlign = LN0->getAlignment();
6316
6317     if (Align <= OrigAlign) {
6318       SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
6319                                  LN0->getBasePtr(), LN0->getPointerInfo(),
6320                                  LN0->isVolatile(), LN0->isNonTemporal(),
6321                                  LN0->isInvariant(), OrigAlign,
6322                                  LN0->getAAInfo());
6323       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
6324       return Load;
6325     }
6326   }
6327
6328   // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
6329   // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
6330   // This often reduces constant pool loads.
6331   if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
6332        (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
6333       N0.getNode()->hasOneUse() && VT.isInteger() &&
6334       !VT.isVector() && !N0.getValueType().isVector()) {
6335     SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
6336                                   N0.getOperand(0));
6337     AddToWorklist(NewConv.getNode());
6338
6339     APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6340     if (N0.getOpcode() == ISD::FNEG)
6341       return DAG.getNode(ISD::XOR, SDLoc(N), VT,
6342                          NewConv, DAG.getConstant(SignBit, VT));
6343     assert(N0.getOpcode() == ISD::FABS);
6344     return DAG.getNode(ISD::AND, SDLoc(N), VT,
6345                        NewConv, DAG.getConstant(~SignBit, VT));
6346   }
6347
6348   // fold (bitconvert (fcopysign cst, x)) ->
6349   //         (or (and (bitconvert x), sign), (and cst, (not sign)))
6350   // Note that we don't handle (copysign x, cst) because this can always be
6351   // folded to an fneg or fabs.
6352   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
6353       isa<ConstantFPSDNode>(N0.getOperand(0)) &&
6354       VT.isInteger() && !VT.isVector()) {
6355     unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
6356     EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
6357     if (isTypeLegal(IntXVT)) {
6358       SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6359                               IntXVT, N0.getOperand(1));
6360       AddToWorklist(X.getNode());
6361
6362       // If X has a different width than the result/lhs, sext it or truncate it.
6363       unsigned VTWidth = VT.getSizeInBits();
6364       if (OrigXWidth < VTWidth) {
6365         X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
6366         AddToWorklist(X.getNode());
6367       } else if (OrigXWidth > VTWidth) {
6368         // To get the sign bit in the right place, we have to shift it right
6369         // before truncating.
6370         X = DAG.getNode(ISD::SRL, SDLoc(X),
6371                         X.getValueType(), X,
6372                         DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
6373         AddToWorklist(X.getNode());
6374         X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
6375         AddToWorklist(X.getNode());
6376       }
6377
6378       APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6379       X = DAG.getNode(ISD::AND, SDLoc(X), VT,
6380                       X, DAG.getConstant(SignBit, VT));
6381       AddToWorklist(X.getNode());
6382
6383       SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6384                                 VT, N0.getOperand(0));
6385       Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
6386                         Cst, DAG.getConstant(~SignBit, VT));
6387       AddToWorklist(Cst.getNode());
6388
6389       return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
6390     }
6391   }
6392
6393   // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
6394   if (N0.getOpcode() == ISD::BUILD_PAIR) {
6395     SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
6396     if (CombineLD.getNode())
6397       return CombineLD;
6398   }
6399
6400   return SDValue();
6401 }
6402
6403 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
6404   EVT VT = N->getValueType(0);
6405   return CombineConsecutiveLoads(N, VT);
6406 }
6407
6408 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef
6409 /// operands. DstEltVT indicates the destination element value type.
6410 SDValue DAGCombiner::
6411 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
6412   EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
6413
6414   // If this is already the right type, we're done.
6415   if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
6416
6417   unsigned SrcBitSize = SrcEltVT.getSizeInBits();
6418   unsigned DstBitSize = DstEltVT.getSizeInBits();
6419
6420   // If this is a conversion of N elements of one type to N elements of another
6421   // type, convert each element.  This handles FP<->INT cases.
6422   if (SrcBitSize == DstBitSize) {
6423     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6424                               BV->getValueType(0).getVectorNumElements());
6425
6426     // Due to the FP element handling below calling this routine recursively,
6427     // we can end up with a scalar-to-vector node here.
6428     if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
6429       return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6430                          DAG.getNode(ISD::BITCAST, SDLoc(BV),
6431                                      DstEltVT, BV->getOperand(0)));
6432
6433     SmallVector<SDValue, 8> Ops;
6434     for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6435       SDValue Op = BV->getOperand(i);
6436       // If the vector element type is not legal, the BUILD_VECTOR operands
6437       // are promoted and implicitly truncated.  Make that explicit here.
6438       if (Op.getValueType() != SrcEltVT)
6439         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
6440       Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
6441                                 DstEltVT, Op));
6442       AddToWorklist(Ops.back().getNode());
6443     }
6444     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6445   }
6446
6447   // Otherwise, we're growing or shrinking the elements.  To avoid having to
6448   // handle annoying details of growing/shrinking FP values, we convert them to
6449   // int first.
6450   if (SrcEltVT.isFloatingPoint()) {
6451     // Convert the input float vector to a int vector where the elements are the
6452     // same sizes.
6453     assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!");
6454     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
6455     BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
6456     SrcEltVT = IntVT;
6457   }
6458
6459   // Now we know the input is an integer vector.  If the output is a FP type,
6460   // convert to integer first, then to FP of the right size.
6461   if (DstEltVT.isFloatingPoint()) {
6462     assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!");
6463     EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
6464     SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
6465
6466     // Next, convert to FP elements of the same size.
6467     return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
6468   }
6469
6470   // Okay, we know the src/dst types are both integers of differing types.
6471   // Handling growing first.
6472   assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
6473   if (SrcBitSize < DstBitSize) {
6474     unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
6475
6476     SmallVector<SDValue, 8> Ops;
6477     for (unsigned i = 0, e = BV->getNumOperands(); i != e;
6478          i += NumInputsPerOutput) {
6479       bool isLE = TLI.isLittleEndian();
6480       APInt NewBits = APInt(DstBitSize, 0);
6481       bool EltIsUndef = true;
6482       for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
6483         // Shift the previously computed bits over.
6484         NewBits <<= SrcBitSize;
6485         SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
6486         if (Op.getOpcode() == ISD::UNDEF) continue;
6487         EltIsUndef = false;
6488
6489         NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
6490                    zextOrTrunc(SrcBitSize).zext(DstBitSize);
6491       }
6492
6493       if (EltIsUndef)
6494         Ops.push_back(DAG.getUNDEF(DstEltVT));
6495       else
6496         Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
6497     }
6498
6499     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
6500     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6501   }
6502
6503   // Finally, this must be the case where we are shrinking elements: each input
6504   // turns into multiple outputs.
6505   bool isS2V = ISD::isScalarToVector(BV);
6506   unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
6507   EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6508                             NumOutputsPerInput*BV->getNumOperands());
6509   SmallVector<SDValue, 8> Ops;
6510
6511   for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6512     if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
6513       for (unsigned j = 0; j != NumOutputsPerInput; ++j)
6514         Ops.push_back(DAG.getUNDEF(DstEltVT));
6515       continue;
6516     }
6517
6518     APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
6519                   getAPIntValue().zextOrTrunc(SrcBitSize);
6520
6521     for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
6522       APInt ThisVal = OpVal.trunc(DstBitSize);
6523       Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
6524       if (isS2V && i == 0 && j == 0 && ThisVal.zext(SrcBitSize) == OpVal)
6525         // Simply turn this into a SCALAR_TO_VECTOR of the new type.
6526         return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6527                            Ops[0]);
6528       OpVal = OpVal.lshr(DstBitSize);
6529     }
6530
6531     // For big endian targets, swap the order of the pieces of each element.
6532     if (TLI.isBigEndian())
6533       std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
6534   }
6535
6536   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6537 }
6538
6539 SDValue DAGCombiner::visitFADD(SDNode *N) {
6540   SDValue N0 = N->getOperand(0);
6541   SDValue N1 = N->getOperand(1);
6542   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6543   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6544   EVT VT = N->getValueType(0);
6545   const TargetOptions &Options = DAG.getTarget().Options;
6546   
6547   // fold vector ops
6548   if (VT.isVector()) {
6549     SDValue FoldedVOp = SimplifyVBinOp(N);
6550     if (FoldedVOp.getNode()) return FoldedVOp;
6551   }
6552
6553   // fold (fadd c1, c2) -> c1 + c2
6554   if (N0CFP && N1CFP)
6555     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N1);
6556   // canonicalize constant to RHS
6557   if (N0CFP && !N1CFP)
6558     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N0);
6559   // fold (fadd A, 0) -> A
6560   if (Options.UnsafeFPMath && N1CFP && N1CFP->getValueAPF().isZero())
6561     return N0;
6562   // fold (fadd A, (fneg B)) -> (fsub A, B)
6563   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6564     isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2)
6565     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0,
6566                        GetNegatedExpression(N1, DAG, LegalOperations));
6567   // fold (fadd (fneg A), B) -> (fsub B, A)
6568   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6569     isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2)
6570     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N1,
6571                        GetNegatedExpression(N0, DAG, LegalOperations));
6572
6573   // If allowed, fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
6574   if (Options.UnsafeFPMath && N1CFP &&
6575       N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
6576       isa<ConstantFPSDNode>(N0.getOperand(1)))
6577     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0.getOperand(0),
6578                        DAG.getNode(ISD::FADD, SDLoc(N), VT,
6579                                    N0.getOperand(1), N1));
6580
6581   // No FP constant should be created after legalization as Instruction
6582   // Selection pass has hard time in dealing with FP constant.
6583   //
6584   // We don't need test this condition for transformation like following, as
6585   // the DAG being transformed implies it is legal to take FP constant as
6586   // operand.
6587   //
6588   //  (fadd (fmul c, x), x) -> (fmul c+1, x)
6589   //
6590   bool AllowNewFpConst = (Level < AfterLegalizeDAG);
6591
6592   // If allow, fold (fadd (fneg x), x) -> 0.0
6593   if (AllowNewFpConst && Options.UnsafeFPMath &&
6594       N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
6595     return DAG.getConstantFP(0.0, VT);
6596
6597   // If allow, fold (fadd x, (fneg x)) -> 0.0
6598   if (AllowNewFpConst && Options.UnsafeFPMath &&
6599       N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
6600     return DAG.getConstantFP(0.0, VT);
6601
6602   // In unsafe math mode, we can fold chains of FADD's of the same value
6603   // into multiplications.  This transform is not safe in general because
6604   // we are reducing the number of rounding steps.
6605   if (Options.UnsafeFPMath && TLI.isOperationLegalOrCustom(ISD::FMUL, VT) &&
6606       !N0CFP && !N1CFP) {
6607     if (N0.getOpcode() == ISD::FMUL) {
6608       ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6609       ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
6610
6611       // (fadd (fmul c, x), x) -> (fmul x, c+1)
6612       if (CFP00 && !CFP01 && N0.getOperand(1) == N1) {
6613         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6614                                      SDValue(CFP00, 0),
6615                                      DAG.getConstantFP(1.0, VT));
6616         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6617                            N1, NewCFP);
6618       }
6619
6620       // (fadd (fmul x, c), x) -> (fmul x, c+1)
6621       if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
6622         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6623                                      SDValue(CFP01, 0),
6624                                      DAG.getConstantFP(1.0, VT));
6625         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6626                            N1, NewCFP);
6627       }
6628
6629       // (fadd (fmul c, x), (fadd x, x)) -> (fmul x, c+2)
6630       if (CFP00 && !CFP01 && N1.getOpcode() == ISD::FADD &&
6631           N1.getOperand(0) == N1.getOperand(1) &&
6632           N0.getOperand(1) == N1.getOperand(0)) {
6633         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6634                                      SDValue(CFP00, 0),
6635                                      DAG.getConstantFP(2.0, VT));
6636         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6637                            N0.getOperand(1), NewCFP);
6638       }
6639
6640       // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
6641       if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
6642           N1.getOperand(0) == N1.getOperand(1) &&
6643           N0.getOperand(0) == N1.getOperand(0)) {
6644         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6645                                      SDValue(CFP01, 0),
6646                                      DAG.getConstantFP(2.0, VT));
6647         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6648                            N0.getOperand(0), NewCFP);
6649       }
6650     }
6651
6652     if (N1.getOpcode() == ISD::FMUL) {
6653       ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6654       ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
6655
6656       // (fadd x, (fmul c, x)) -> (fmul x, c+1)
6657       if (CFP10 && !CFP11 && N1.getOperand(1) == N0) {
6658         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6659                                      SDValue(CFP10, 0),
6660                                      DAG.getConstantFP(1.0, VT));
6661         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6662                            N0, NewCFP);
6663       }
6664
6665       // (fadd x, (fmul x, c)) -> (fmul x, c+1)
6666       if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
6667         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6668                                      SDValue(CFP11, 0),
6669                                      DAG.getConstantFP(1.0, VT));
6670         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6671                            N0, NewCFP);
6672       }
6673
6674
6675       // (fadd (fadd x, x), (fmul c, x)) -> (fmul x, c+2)
6676       if (CFP10 && !CFP11 && N0.getOpcode() == ISD::FADD &&
6677           N0.getOperand(0) == N0.getOperand(1) &&
6678           N1.getOperand(1) == N0.getOperand(0)) {
6679         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6680                                      SDValue(CFP10, 0),
6681                                      DAG.getConstantFP(2.0, VT));
6682         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6683                            N1.getOperand(1), NewCFP);
6684       }
6685
6686       // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
6687       if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
6688           N0.getOperand(0) == N0.getOperand(1) &&
6689           N1.getOperand(0) == N0.getOperand(0)) {
6690         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6691                                      SDValue(CFP11, 0),
6692                                      DAG.getConstantFP(2.0, VT));
6693         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6694                            N1.getOperand(0), NewCFP);
6695       }
6696     }
6697
6698     if (N0.getOpcode() == ISD::FADD && AllowNewFpConst) {
6699       ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6700       // (fadd (fadd x, x), x) -> (fmul x, 3.0)
6701       if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
6702           (N0.getOperand(0) == N1))
6703         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6704                            N1, DAG.getConstantFP(3.0, VT));
6705     }
6706
6707     if (N1.getOpcode() == ISD::FADD && AllowNewFpConst) {
6708       ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6709       // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
6710       if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
6711           N1.getOperand(0) == N0)
6712         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6713                            N0, DAG.getConstantFP(3.0, VT));
6714     }
6715
6716     // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
6717     if (AllowNewFpConst &&
6718         N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
6719         N0.getOperand(0) == N0.getOperand(1) &&
6720         N1.getOperand(0) == N1.getOperand(1) &&
6721         N0.getOperand(0) == N1.getOperand(0))
6722       return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6723                          N0.getOperand(0),
6724                          DAG.getConstantFP(4.0, VT));
6725   }
6726
6727   // FADD -> FMA combines:
6728   if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath) &&
6729       DAG.getTarget()
6730           .getSubtargetImpl()
6731           ->getTargetLowering()
6732           ->isFMAFasterThanFMulAndFAdd(VT) &&
6733       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6734
6735     // fold (fadd (fmul x, y), z) -> (fma x, y, z)
6736     if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
6737       return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6738                          N0.getOperand(0), N0.getOperand(1), N1);
6739
6740     // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
6741     // Note: Commutes FADD operands.
6742     if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
6743       return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6744                          N1.getOperand(0), N1.getOperand(1), N0);
6745   }
6746
6747   return SDValue();
6748 }
6749
6750 SDValue DAGCombiner::visitFSUB(SDNode *N) {
6751   SDValue N0 = N->getOperand(0);
6752   SDValue N1 = N->getOperand(1);
6753   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6754   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6755   EVT VT = N->getValueType(0);
6756   SDLoc dl(N);
6757   const TargetOptions &Options = DAG.getTarget().Options;
6758
6759   // fold vector ops
6760   if (VT.isVector()) {
6761     SDValue FoldedVOp = SimplifyVBinOp(N);
6762     if (FoldedVOp.getNode()) return FoldedVOp;
6763   }
6764
6765   // fold (fsub c1, c2) -> c1-c2
6766   if (N0CFP && N1CFP)
6767     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0, N1);
6768
6769   // fold (fsub A, (fneg B)) -> (fadd A, B)
6770   if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
6771     return DAG.getNode(ISD::FADD, dl, VT, N0,
6772                        GetNegatedExpression(N1, DAG, LegalOperations));
6773
6774   // If 'unsafe math' is enabled, fold lots of things.
6775   if (Options.UnsafeFPMath) {
6776     // (fsub A, 0) -> A
6777     if (N1CFP && N1CFP->getValueAPF().isZero())
6778       return N0;
6779
6780     // (fsub 0, B) -> -B
6781     if (N0CFP && N0CFP->getValueAPF().isZero()) {
6782       if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
6783         return GetNegatedExpression(N1, DAG, LegalOperations);
6784       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6785         return DAG.getNode(ISD::FNEG, dl, VT, N1);
6786     }
6787
6788     // (fsub x, x) -> 0.0
6789     if (N0 == N1)
6790       return DAG.getConstantFP(0.0f, VT);
6791
6792     // (fsub x, (fadd x, y)) -> (fneg y)
6793     // (fsub x, (fadd y, x)) -> (fneg y)
6794     if (N1.getOpcode() == ISD::FADD) {
6795       SDValue N10 = N1->getOperand(0);
6796       SDValue N11 = N1->getOperand(1);
6797
6798       if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options))
6799         return GetNegatedExpression(N11, DAG, LegalOperations);
6800
6801       if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options))
6802         return GetNegatedExpression(N10, DAG, LegalOperations);
6803     }
6804   }
6805
6806   // FSUB -> FMA combines:
6807   if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath) &&
6808       DAG.getTarget().getSubtargetImpl()
6809           ->getTargetLowering()
6810           ->isFMAFasterThanFMulAndFAdd(VT) &&
6811       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6812
6813     // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
6814     if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
6815       return DAG.getNode(ISD::FMA, dl, VT,
6816                          N0.getOperand(0), N0.getOperand(1),
6817                          DAG.getNode(ISD::FNEG, dl, VT, N1));
6818
6819     // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
6820     // Note: Commutes FSUB operands.
6821     if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
6822       return DAG.getNode(ISD::FMA, dl, VT,
6823                          DAG.getNode(ISD::FNEG, dl, VT,
6824                          N1.getOperand(0)),
6825                          N1.getOperand(1), N0);
6826
6827     // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
6828     if (N0.getOpcode() == ISD::FNEG &&
6829         N0.getOperand(0).getOpcode() == ISD::FMUL &&
6830         N0->hasOneUse() && N0.getOperand(0).hasOneUse()) {
6831       SDValue N00 = N0.getOperand(0).getOperand(0);
6832       SDValue N01 = N0.getOperand(0).getOperand(1);
6833       return DAG.getNode(ISD::FMA, dl, VT,
6834                          DAG.getNode(ISD::FNEG, dl, VT, N00), N01,
6835                          DAG.getNode(ISD::FNEG, dl, VT, N1));
6836     }
6837   }
6838
6839   return SDValue();
6840 }
6841
6842 SDValue DAGCombiner::visitFMUL(SDNode *N) {
6843   SDValue N0 = N->getOperand(0);
6844   SDValue N1 = N->getOperand(1);
6845   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
6846   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
6847   EVT VT = N->getValueType(0);
6848   const TargetOptions &Options = DAG.getTarget().Options;
6849
6850   // fold vector ops
6851   if (VT.isVector()) {
6852     SDValue FoldedVOp = SimplifyVBinOp(N);
6853     if (FoldedVOp.getNode()) return FoldedVOp;
6854   }
6855
6856   // fold (fmul c1, c2) -> c1*c2
6857   if (N0CFP && N1CFP)
6858     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, N1);
6859   // canonicalize constant to RHS
6860   if (N0CFP && !N1CFP)
6861     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, N0);
6862   // fold (fmul A, 0) -> 0
6863   if (Options.UnsafeFPMath && N1CFP && N1CFP->getValueAPF().isZero())
6864     return N1;
6865   // fold (fmul A, 1.0) -> A
6866   if (N1CFP && N1CFP->isExactlyValue(1.0))
6867     return N0;
6868
6869   // fold (fmul X, 2.0) -> (fadd X, X)
6870   if (N1CFP && N1CFP->isExactlyValue(+2.0))
6871     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N0);
6872   // fold (fmul X, -1.0) -> (fneg X)
6873   if (N1CFP && N1CFP->isExactlyValue(-1.0))
6874     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6875       return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
6876
6877   // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
6878   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
6879     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
6880       // Both can be negated for free, check to see if at least one is cheaper
6881       // negated.
6882       if (LHSNeg == 2 || RHSNeg == 2)
6883         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6884                            GetNegatedExpression(N0, DAG, LegalOperations),
6885                            GetNegatedExpression(N1, DAG, LegalOperations));
6886     }
6887   }
6888
6889   // If allowed, fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
6890   if (Options.UnsafeFPMath && N1CFP && N0.getOpcode() == ISD::FMUL &&
6891       N0.getNode()->hasOneUse() && isConstOrConstSplatFP(N0.getOperand(1))) {
6892     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
6893                        DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6894                                    N0.getOperand(1), N1));
6895   }
6896
6897   return SDValue();
6898 }
6899
6900 SDValue DAGCombiner::visitFMA(SDNode *N) {
6901   SDValue N0 = N->getOperand(0);
6902   SDValue N1 = N->getOperand(1);
6903   SDValue N2 = N->getOperand(2);
6904   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6905   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6906   EVT VT = N->getValueType(0);
6907   SDLoc dl(N);
6908   const TargetOptions &Options = DAG.getTarget().Options;
6909
6910   // Constant fold FMA.
6911   if (isa<ConstantFPSDNode>(N0) &&
6912       isa<ConstantFPSDNode>(N1) &&
6913       isa<ConstantFPSDNode>(N2)) {
6914     return DAG.getNode(ISD::FMA, dl, VT, N0, N1, N2);
6915   }
6916
6917   if (Options.UnsafeFPMath) {
6918     if (N0CFP && N0CFP->isZero())
6919       return N2;
6920     if (N1CFP && N1CFP->isZero())
6921       return N2;
6922   }
6923   if (N0CFP && N0CFP->isExactlyValue(1.0))
6924     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
6925   if (N1CFP && N1CFP->isExactlyValue(1.0))
6926     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
6927
6928   // Canonicalize (fma c, x, y) -> (fma x, c, y)
6929   if (N0CFP && !N1CFP)
6930     return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
6931
6932   // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
6933   if (Options.UnsafeFPMath && N1CFP &&
6934       N2.getOpcode() == ISD::FMUL &&
6935       N0 == N2.getOperand(0) &&
6936       N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
6937     return DAG.getNode(ISD::FMUL, dl, VT, N0,
6938                        DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
6939   }
6940
6941
6942   // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
6943   if (Options.UnsafeFPMath &&
6944       N0.getOpcode() == ISD::FMUL && N1CFP &&
6945       N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
6946     return DAG.getNode(ISD::FMA, dl, VT,
6947                        N0.getOperand(0),
6948                        DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
6949                        N2);
6950   }
6951
6952   // (fma x, 1, y) -> (fadd x, y)
6953   // (fma x, -1, y) -> (fadd (fneg x), y)
6954   if (N1CFP) {
6955     if (N1CFP->isExactlyValue(1.0))
6956       return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
6957
6958     if (N1CFP->isExactlyValue(-1.0) &&
6959         (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
6960       SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
6961       AddToWorklist(RHSNeg.getNode());
6962       return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
6963     }
6964   }
6965
6966   // (fma x, c, x) -> (fmul x, (c+1))
6967   if (Options.UnsafeFPMath && N1CFP && N0 == N2)
6968     return DAG.getNode(ISD::FMUL, dl, VT, N0,
6969                        DAG.getNode(ISD::FADD, dl, VT,
6970                                    N1, DAG.getConstantFP(1.0, VT)));
6971
6972   // (fma x, c, (fneg x)) -> (fmul x, (c-1))
6973   if (Options.UnsafeFPMath && N1CFP &&
6974       N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
6975     return DAG.getNode(ISD::FMUL, dl, VT, N0,
6976                        DAG.getNode(ISD::FADD, dl, VT,
6977                                    N1, DAG.getConstantFP(-1.0, VT)));
6978
6979
6980   return SDValue();
6981 }
6982
6983 SDValue DAGCombiner::visitFDIV(SDNode *N) {
6984   SDValue N0 = N->getOperand(0);
6985   SDValue N1 = N->getOperand(1);
6986   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6987   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6988   EVT VT = N->getValueType(0);
6989   const TargetOptions &Options = DAG.getTarget().Options;
6990
6991   // fold vector ops
6992   if (VT.isVector()) {
6993     SDValue FoldedVOp = SimplifyVBinOp(N);
6994     if (FoldedVOp.getNode()) return FoldedVOp;
6995   }
6996
6997   // fold (fdiv c1, c2) -> c1/c2
6998   if (N0CFP && N1CFP)
6999     return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
7000
7001   // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
7002   if (N1CFP && Options.UnsafeFPMath) {
7003     // Compute the reciprocal 1.0 / c2.
7004     APFloat N1APF = N1CFP->getValueAPF();
7005     APFloat Recip(N1APF.getSemantics(), 1); // 1.0
7006     APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
7007     // Only do the transform if the reciprocal is a legal fp immediate that
7008     // isn't too nasty (eg NaN, denormal, ...).
7009     if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
7010         (!LegalOperations ||
7011          // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
7012          // backend)... we should handle this gracefully after Legalize.
7013          // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
7014          TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
7015          TLI.isFPImmLegal(Recip, VT)))
7016       return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0,
7017                          DAG.getConstantFP(Recip, VT));
7018   }
7019
7020   // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
7021   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
7022     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
7023       // Both can be negated for free, check to see if at least one is cheaper
7024       // negated.
7025       if (LHSNeg == 2 || RHSNeg == 2)
7026         return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
7027                            GetNegatedExpression(N0, DAG, LegalOperations),
7028                            GetNegatedExpression(N1, DAG, LegalOperations));
7029     }
7030   }
7031
7032   return SDValue();
7033 }
7034
7035 SDValue DAGCombiner::visitFREM(SDNode *N) {
7036   SDValue N0 = N->getOperand(0);
7037   SDValue N1 = N->getOperand(1);
7038   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7039   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7040   EVT VT = N->getValueType(0);
7041
7042   // fold (frem c1, c2) -> fmod(c1,c2)
7043   if (N0CFP && N1CFP)
7044     return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
7045
7046   return SDValue();
7047 }
7048
7049 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
7050   SDValue N0 = N->getOperand(0);
7051   SDValue N1 = N->getOperand(1);
7052   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7053   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7054   EVT VT = N->getValueType(0);
7055
7056   if (N0CFP && N1CFP)  // Constant fold
7057     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
7058
7059   if (N1CFP) {
7060     const APFloat& V = N1CFP->getValueAPF();
7061     // copysign(x, c1) -> fabs(x)       iff ispos(c1)
7062     // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
7063     if (!V.isNegative()) {
7064       if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
7065         return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7066     } else {
7067       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
7068         return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
7069                            DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
7070     }
7071   }
7072
7073   // copysign(fabs(x), y) -> copysign(x, y)
7074   // copysign(fneg(x), y) -> copysign(x, y)
7075   // copysign(copysign(x,z), y) -> copysign(x, y)
7076   if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
7077       N0.getOpcode() == ISD::FCOPYSIGN)
7078     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7079                        N0.getOperand(0), N1);
7080
7081   // copysign(x, abs(y)) -> abs(x)
7082   if (N1.getOpcode() == ISD::FABS)
7083     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7084
7085   // copysign(x, copysign(y,z)) -> copysign(x, z)
7086   if (N1.getOpcode() == ISD::FCOPYSIGN)
7087     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7088                        N0, N1.getOperand(1));
7089
7090   // copysign(x, fp_extend(y)) -> copysign(x, y)
7091   // copysign(x, fp_round(y)) -> copysign(x, y)
7092   if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
7093     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7094                        N0, N1.getOperand(0));
7095
7096   return SDValue();
7097 }
7098
7099 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
7100   SDValue N0 = N->getOperand(0);
7101   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
7102   EVT VT = N->getValueType(0);
7103   EVT OpVT = N0.getValueType();
7104
7105   // fold (sint_to_fp c1) -> c1fp
7106   if (N0C &&
7107       // ...but only if the target supports immediate floating-point values
7108       (!LegalOperations ||
7109        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
7110     return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
7111
7112   // If the input is a legal type, and SINT_TO_FP is not legal on this target,
7113   // but UINT_TO_FP is legal on this target, try to convert.
7114   if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
7115       TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
7116     // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
7117     if (DAG.SignBitIsZero(N0))
7118       return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
7119   }
7120
7121   // The next optimizations are desirable only if SELECT_CC can be lowered.
7122   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
7123     // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
7124     if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
7125         !VT.isVector() &&
7126         (!LegalOperations ||
7127          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7128       SDValue Ops[] =
7129         { N0.getOperand(0), N0.getOperand(1),
7130           DAG.getConstantFP(-1.0, VT) , DAG.getConstantFP(0.0, VT),
7131           N0.getOperand(2) };
7132       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7133     }
7134
7135     // fold (sint_to_fp (zext (setcc x, y, cc))) ->
7136     //      (select_cc x, y, 1.0, 0.0,, cc)
7137     if (N0.getOpcode() == ISD::ZERO_EXTEND &&
7138         N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
7139         (!LegalOperations ||
7140          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7141       SDValue Ops[] =
7142         { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
7143           DAG.getConstantFP(1.0, VT) , DAG.getConstantFP(0.0, VT),
7144           N0.getOperand(0).getOperand(2) };
7145       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7146     }
7147   }
7148
7149   return SDValue();
7150 }
7151
7152 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
7153   SDValue N0 = N->getOperand(0);
7154   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
7155   EVT VT = N->getValueType(0);
7156   EVT OpVT = N0.getValueType();
7157
7158   // fold (uint_to_fp c1) -> c1fp
7159   if (N0C &&
7160       // ...but only if the target supports immediate floating-point values
7161       (!LegalOperations ||
7162        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
7163     return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
7164
7165   // If the input is a legal type, and UINT_TO_FP is not legal on this target,
7166   // but SINT_TO_FP is legal on this target, try to convert.
7167   if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
7168       TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
7169     // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
7170     if (DAG.SignBitIsZero(N0))
7171       return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
7172   }
7173
7174   // The next optimizations are desirable only if SELECT_CC can be lowered.
7175   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
7176     // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
7177
7178     if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
7179         (!LegalOperations ||
7180          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7181       SDValue Ops[] =
7182         { N0.getOperand(0), N0.getOperand(1),
7183           DAG.getConstantFP(1.0, VT),  DAG.getConstantFP(0.0, VT),
7184           N0.getOperand(2) };
7185       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7186     }
7187   }
7188
7189   return SDValue();
7190 }
7191
7192 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
7193   SDValue N0 = N->getOperand(0);
7194   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7195   EVT VT = N->getValueType(0);
7196
7197   // fold (fp_to_sint c1fp) -> c1
7198   if (N0CFP)
7199     return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
7200
7201   return SDValue();
7202 }
7203
7204 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
7205   SDValue N0 = N->getOperand(0);
7206   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7207   EVT VT = N->getValueType(0);
7208
7209   // fold (fp_to_uint c1fp) -> c1
7210   if (N0CFP)
7211     return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
7212
7213   return SDValue();
7214 }
7215
7216 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
7217   SDValue N0 = N->getOperand(0);
7218   SDValue N1 = N->getOperand(1);
7219   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7220   EVT VT = N->getValueType(0);
7221
7222   // fold (fp_round c1fp) -> c1fp
7223   if (N0CFP)
7224     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
7225
7226   // fold (fp_round (fp_extend x)) -> x
7227   if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
7228     return N0.getOperand(0);
7229
7230   // fold (fp_round (fp_round x)) -> (fp_round x)
7231   if (N0.getOpcode() == ISD::FP_ROUND) {
7232     // This is a value preserving truncation if both round's are.
7233     bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
7234                    N0.getNode()->getConstantOperandVal(1) == 1;
7235     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0.getOperand(0),
7236                        DAG.getIntPtrConstant(IsTrunc));
7237   }
7238
7239   // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
7240   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
7241     SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
7242                               N0.getOperand(0), N1);
7243     AddToWorklist(Tmp.getNode());
7244     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7245                        Tmp, N0.getOperand(1));
7246   }
7247
7248   return SDValue();
7249 }
7250
7251 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
7252   SDValue N0 = N->getOperand(0);
7253   EVT VT = N->getValueType(0);
7254   EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
7255   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7256
7257   // fold (fp_round_inreg c1fp) -> c1fp
7258   if (N0CFP && isTypeLegal(EVT)) {
7259     SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
7260     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, Round);
7261   }
7262
7263   return SDValue();
7264 }
7265
7266 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
7267   SDValue N0 = N->getOperand(0);
7268   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7269   EVT VT = N->getValueType(0);
7270
7271   // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
7272   if (N->hasOneUse() &&
7273       N->use_begin()->getOpcode() == ISD::FP_ROUND)
7274     return SDValue();
7275
7276   // fold (fp_extend c1fp) -> c1fp
7277   if (N0CFP)
7278     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
7279
7280   // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
7281   // value of X.
7282   if (N0.getOpcode() == ISD::FP_ROUND
7283       && N0.getNode()->getConstantOperandVal(1) == 1) {
7284     SDValue In = N0.getOperand(0);
7285     if (In.getValueType() == VT) return In;
7286     if (VT.bitsLT(In.getValueType()))
7287       return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
7288                          In, N0.getOperand(1));
7289     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
7290   }
7291
7292   // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
7293   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7294        TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType())) {
7295     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7296     SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
7297                                      LN0->getChain(),
7298                                      LN0->getBasePtr(), N0.getValueType(),
7299                                      LN0->getMemOperand());
7300     CombineTo(N, ExtLoad);
7301     CombineTo(N0.getNode(),
7302               DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
7303                           N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
7304               ExtLoad.getValue(1));
7305     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7306   }
7307
7308   return SDValue();
7309 }
7310
7311 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
7312   SDValue N0 = N->getOperand(0);
7313   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7314   EVT VT = N->getValueType(0);
7315
7316   // fold (fceil c1) -> fceil(c1)
7317   if (N0CFP)
7318     return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
7319
7320   return SDValue();
7321 }
7322
7323 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
7324   SDValue N0 = N->getOperand(0);
7325   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7326   EVT VT = N->getValueType(0);
7327
7328   // fold (ftrunc c1) -> ftrunc(c1)
7329   if (N0CFP)
7330     return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
7331
7332   return SDValue();
7333 }
7334
7335 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
7336   SDValue N0 = N->getOperand(0);
7337   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7338   EVT VT = N->getValueType(0);
7339
7340   // fold (ffloor c1) -> ffloor(c1)
7341   if (N0CFP)
7342     return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
7343
7344   return SDValue();
7345 }
7346
7347 // FIXME: FNEG and FABS have a lot in common; refactor.
7348 SDValue DAGCombiner::visitFNEG(SDNode *N) {
7349   SDValue N0 = N->getOperand(0);
7350   EVT VT = N->getValueType(0);
7351
7352   if (VT.isVector()) {
7353     SDValue FoldedVOp = SimplifyVUnaryOp(N);
7354     if (FoldedVOp.getNode()) return FoldedVOp;
7355   }
7356
7357   // Constant fold FNEG.
7358   if (isa<ConstantFPSDNode>(N0))
7359     return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N->getOperand(0));
7360
7361   if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
7362                          &DAG.getTarget().Options))
7363     return GetNegatedExpression(N0, DAG, LegalOperations);
7364
7365   // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading
7366   // constant pool values.
7367   if (!TLI.isFNegFree(VT) &&
7368       N0.getOpcode() == ISD::BITCAST &&
7369       N0.getNode()->hasOneUse()) {
7370     SDValue Int = N0.getOperand(0);
7371     EVT IntVT = Int.getValueType();
7372     if (IntVT.isInteger() && !IntVT.isVector()) {
7373       APInt SignMask;
7374       if (N0.getValueType().isVector()) {
7375         // For a vector, get a mask such as 0x80... per scalar element
7376         // and splat it.
7377         SignMask = APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
7378         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
7379       } else {
7380         // For a scalar, just generate 0x80...
7381         SignMask = APInt::getSignBit(IntVT.getSizeInBits());
7382       }
7383       Int = DAG.getNode(ISD::XOR, SDLoc(N0), IntVT, Int,
7384                         DAG.getConstant(SignMask, IntVT));
7385       AddToWorklist(Int.getNode());
7386       return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Int);
7387     }
7388   }
7389
7390   // (fneg (fmul c, x)) -> (fmul -c, x)
7391   if (N0.getOpcode() == ISD::FMUL) {
7392     ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
7393     if (CFP1) {
7394       APFloat CVal = CFP1->getValueAPF();
7395       CVal.changeSign();
7396       if (Level >= AfterLegalizeDAG &&
7397           (TLI.isFPImmLegal(CVal, N->getValueType(0)) ||
7398            TLI.isOperationLegal(ISD::ConstantFP, N->getValueType(0))))
7399         return DAG.getNode(
7400             ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
7401             DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0.getOperand(1)));
7402     }
7403   }
7404
7405   return SDValue();
7406 }
7407
7408 SDValue DAGCombiner::visitFABS(SDNode *N) {
7409   SDValue N0 = N->getOperand(0);
7410   EVT VT = N->getValueType(0);
7411
7412   if (VT.isVector()) {
7413     SDValue FoldedVOp = SimplifyVUnaryOp(N);
7414     if (FoldedVOp.getNode()) return FoldedVOp;
7415   }
7416
7417   // fold (fabs c1) -> fabs(c1)
7418   if (isa<ConstantFPSDNode>(N0))
7419     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7420   
7421   // fold (fabs (fabs x)) -> (fabs x)
7422   if (N0.getOpcode() == ISD::FABS)
7423     return N->getOperand(0);
7424
7425   // fold (fabs (fneg x)) -> (fabs x)
7426   // fold (fabs (fcopysign x, y)) -> (fabs x)
7427   if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
7428     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
7429
7430   // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading
7431   // constant pool values.
7432   if (!TLI.isFAbsFree(VT) &&
7433       N0.getOpcode() == ISD::BITCAST &&
7434       N0.getNode()->hasOneUse()) {
7435     SDValue Int = N0.getOperand(0);
7436     EVT IntVT = Int.getValueType();
7437     if (IntVT.isInteger() && !IntVT.isVector()) {
7438       APInt SignMask;
7439       if (N0.getValueType().isVector()) {
7440         // For a vector, get a mask such as 0x7f... per scalar element
7441         // and splat it.
7442         SignMask = ~APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
7443         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
7444       } else {
7445         // For a scalar, just generate 0x7f...
7446         SignMask = ~APInt::getSignBit(IntVT.getSizeInBits());
7447       }
7448       Int = DAG.getNode(ISD::AND, SDLoc(N0), IntVT, Int,
7449                         DAG.getConstant(SignMask, IntVT));
7450       AddToWorklist(Int.getNode());
7451       return DAG.getNode(ISD::BITCAST, SDLoc(N), N->getValueType(0), Int);
7452     }
7453   }
7454
7455   return SDValue();
7456 }
7457
7458 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
7459   SDValue Chain = N->getOperand(0);
7460   SDValue N1 = N->getOperand(1);
7461   SDValue N2 = N->getOperand(2);
7462
7463   // If N is a constant we could fold this into a fallthrough or unconditional
7464   // branch. However that doesn't happen very often in normal code, because
7465   // Instcombine/SimplifyCFG should have handled the available opportunities.
7466   // If we did this folding here, it would be necessary to update the
7467   // MachineBasicBlock CFG, which is awkward.
7468
7469   // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
7470   // on the target.
7471   if (N1.getOpcode() == ISD::SETCC &&
7472       TLI.isOperationLegalOrCustom(ISD::BR_CC,
7473                                    N1.getOperand(0).getValueType())) {
7474     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7475                        Chain, N1.getOperand(2),
7476                        N1.getOperand(0), N1.getOperand(1), N2);
7477   }
7478
7479   if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
7480       ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
7481        (N1.getOperand(0).hasOneUse() &&
7482         N1.getOperand(0).getOpcode() == ISD::SRL))) {
7483     SDNode *Trunc = nullptr;
7484     if (N1.getOpcode() == ISD::TRUNCATE) {
7485       // Look pass the truncate.
7486       Trunc = N1.getNode();
7487       N1 = N1.getOperand(0);
7488     }
7489
7490     // Match this pattern so that we can generate simpler code:
7491     //
7492     //   %a = ...
7493     //   %b = and i32 %a, 2
7494     //   %c = srl i32 %b, 1
7495     //   brcond i32 %c ...
7496     //
7497     // into
7498     //
7499     //   %a = ...
7500     //   %b = and i32 %a, 2
7501     //   %c = setcc eq %b, 0
7502     //   brcond %c ...
7503     //
7504     // This applies only when the AND constant value has one bit set and the
7505     // SRL constant is equal to the log2 of the AND constant. The back-end is
7506     // smart enough to convert the result into a TEST/JMP sequence.
7507     SDValue Op0 = N1.getOperand(0);
7508     SDValue Op1 = N1.getOperand(1);
7509
7510     if (Op0.getOpcode() == ISD::AND &&
7511         Op1.getOpcode() == ISD::Constant) {
7512       SDValue AndOp1 = Op0.getOperand(1);
7513
7514       if (AndOp1.getOpcode() == ISD::Constant) {
7515         const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
7516
7517         if (AndConst.isPowerOf2() &&
7518             cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
7519           SDValue SetCC =
7520             DAG.getSetCC(SDLoc(N),
7521                          getSetCCResultType(Op0.getValueType()),
7522                          Op0, DAG.getConstant(0, Op0.getValueType()),
7523                          ISD::SETNE);
7524
7525           SDValue NewBRCond = DAG.getNode(ISD::BRCOND, SDLoc(N),
7526                                           MVT::Other, Chain, SetCC, N2);
7527           // Don't add the new BRCond into the worklist or else SimplifySelectCC
7528           // will convert it back to (X & C1) >> C2.
7529           CombineTo(N, NewBRCond, false);
7530           // Truncate is dead.
7531           if (Trunc)
7532             deleteAndRecombine(Trunc);
7533           // Replace the uses of SRL with SETCC
7534           WorklistRemover DeadNodes(*this);
7535           DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
7536           deleteAndRecombine(N1.getNode());
7537           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7538         }
7539       }
7540     }
7541
7542     if (Trunc)
7543       // Restore N1 if the above transformation doesn't match.
7544       N1 = N->getOperand(1);
7545   }
7546
7547   // Transform br(xor(x, y)) -> br(x != y)
7548   // Transform br(xor(xor(x,y), 1)) -> br (x == y)
7549   if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
7550     SDNode *TheXor = N1.getNode();
7551     SDValue Op0 = TheXor->getOperand(0);
7552     SDValue Op1 = TheXor->getOperand(1);
7553     if (Op0.getOpcode() == Op1.getOpcode()) {
7554       // Avoid missing important xor optimizations.
7555       SDValue Tmp = visitXOR(TheXor);
7556       if (Tmp.getNode()) {
7557         if (Tmp.getNode() != TheXor) {
7558           DEBUG(dbgs() << "\nReplacing.8 ";
7559                 TheXor->dump(&DAG);
7560                 dbgs() << "\nWith: ";
7561                 Tmp.getNode()->dump(&DAG);
7562                 dbgs() << '\n');
7563           WorklistRemover DeadNodes(*this);
7564           DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
7565           deleteAndRecombine(TheXor);
7566           return DAG.getNode(ISD::BRCOND, SDLoc(N),
7567                              MVT::Other, Chain, Tmp, N2);
7568         }
7569
7570         // visitXOR has changed XOR's operands or replaced the XOR completely,
7571         // bail out.
7572         return SDValue(N, 0);
7573       }
7574     }
7575
7576     if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
7577       bool Equal = false;
7578       if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
7579         if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
7580             Op0.getOpcode() == ISD::XOR) {
7581           TheXor = Op0.getNode();
7582           Equal = true;
7583         }
7584
7585       EVT SetCCVT = N1.getValueType();
7586       if (LegalTypes)
7587         SetCCVT = getSetCCResultType(SetCCVT);
7588       SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
7589                                    SetCCVT,
7590                                    Op0, Op1,
7591                                    Equal ? ISD::SETEQ : ISD::SETNE);
7592       // Replace the uses of XOR with SETCC
7593       WorklistRemover DeadNodes(*this);
7594       DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
7595       deleteAndRecombine(N1.getNode());
7596       return DAG.getNode(ISD::BRCOND, SDLoc(N),
7597                          MVT::Other, Chain, SetCC, N2);
7598     }
7599   }
7600
7601   return SDValue();
7602 }
7603
7604 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
7605 //
7606 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
7607   CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
7608   SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
7609
7610   // If N is a constant we could fold this into a fallthrough or unconditional
7611   // branch. However that doesn't happen very often in normal code, because
7612   // Instcombine/SimplifyCFG should have handled the available opportunities.
7613   // If we did this folding here, it would be necessary to update the
7614   // MachineBasicBlock CFG, which is awkward.
7615
7616   // Use SimplifySetCC to simplify SETCC's.
7617   SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
7618                                CondLHS, CondRHS, CC->get(), SDLoc(N),
7619                                false);
7620   if (Simp.getNode()) AddToWorklist(Simp.getNode());
7621
7622   // fold to a simpler setcc
7623   if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
7624     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7625                        N->getOperand(0), Simp.getOperand(2),
7626                        Simp.getOperand(0), Simp.getOperand(1),
7627                        N->getOperand(4));
7628
7629   return SDValue();
7630 }
7631
7632 /// Return true if 'Use' is a load or a store that uses N as its base pointer
7633 /// and that N may be folded in the load / store addressing mode.
7634 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
7635                                     SelectionDAG &DAG,
7636                                     const TargetLowering &TLI) {
7637   EVT VT;
7638   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(Use)) {
7639     if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
7640       return false;
7641     VT = Use->getValueType(0);
7642   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(Use)) {
7643     if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
7644       return false;
7645     VT = ST->getValue().getValueType();
7646   } else
7647     return false;
7648
7649   TargetLowering::AddrMode AM;
7650   if (N->getOpcode() == ISD::ADD) {
7651     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7652     if (Offset)
7653       // [reg +/- imm]
7654       AM.BaseOffs = Offset->getSExtValue();
7655     else
7656       // [reg +/- reg]
7657       AM.Scale = 1;
7658   } else if (N->getOpcode() == ISD::SUB) {
7659     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7660     if (Offset)
7661       // [reg +/- imm]
7662       AM.BaseOffs = -Offset->getSExtValue();
7663     else
7664       // [reg +/- reg]
7665       AM.Scale = 1;
7666   } else
7667     return false;
7668
7669   return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
7670 }
7671
7672 /// Try turning a load/store into a pre-indexed load/store when the base
7673 /// pointer is an add or subtract and it has other uses besides the load/store.
7674 /// After the transformation, the new indexed load/store has effectively folded
7675 /// the add/subtract in and all of its other uses are redirected to the
7676 /// new load/store.
7677 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
7678   if (Level < AfterLegalizeDAG)
7679     return false;
7680
7681   bool isLoad = true;
7682   SDValue Ptr;
7683   EVT VT;
7684   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
7685     if (LD->isIndexed())
7686       return false;
7687     VT = LD->getMemoryVT();
7688     if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
7689         !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
7690       return false;
7691     Ptr = LD->getBasePtr();
7692   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
7693     if (ST->isIndexed())
7694       return false;
7695     VT = ST->getMemoryVT();
7696     if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
7697         !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
7698       return false;
7699     Ptr = ST->getBasePtr();
7700     isLoad = false;
7701   } else {
7702     return false;
7703   }
7704
7705   // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
7706   // out.  There is no reason to make this a preinc/predec.
7707   if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
7708       Ptr.getNode()->hasOneUse())
7709     return false;
7710
7711   // Ask the target to do addressing mode selection.
7712   SDValue BasePtr;
7713   SDValue Offset;
7714   ISD::MemIndexedMode AM = ISD::UNINDEXED;
7715   if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
7716     return false;
7717
7718   // Backends without true r+i pre-indexed forms may need to pass a
7719   // constant base with a variable offset so that constant coercion
7720   // will work with the patterns in canonical form.
7721   bool Swapped = false;
7722   if (isa<ConstantSDNode>(BasePtr)) {
7723     std::swap(BasePtr, Offset);
7724     Swapped = true;
7725   }
7726
7727   // Don't create a indexed load / store with zero offset.
7728   if (isa<ConstantSDNode>(Offset) &&
7729       cast<ConstantSDNode>(Offset)->isNullValue())
7730     return false;
7731
7732   // Try turning it into a pre-indexed load / store except when:
7733   // 1) The new base ptr is a frame index.
7734   // 2) If N is a store and the new base ptr is either the same as or is a
7735   //    predecessor of the value being stored.
7736   // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
7737   //    that would create a cycle.
7738   // 4) All uses are load / store ops that use it as old base ptr.
7739
7740   // Check #1.  Preinc'ing a frame index would require copying the stack pointer
7741   // (plus the implicit offset) to a register to preinc anyway.
7742   if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7743     return false;
7744
7745   // Check #2.
7746   if (!isLoad) {
7747     SDValue Val = cast<StoreSDNode>(N)->getValue();
7748     if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
7749       return false;
7750   }
7751
7752   // If the offset is a constant, there may be other adds of constants that
7753   // can be folded with this one. We should do this to avoid having to keep
7754   // a copy of the original base pointer.
7755   SmallVector<SDNode *, 16> OtherUses;
7756   if (isa<ConstantSDNode>(Offset))
7757     for (SDNode *Use : BasePtr.getNode()->uses()) {
7758       if (Use == Ptr.getNode())
7759         continue;
7760
7761       if (Use->isPredecessorOf(N))
7762         continue;
7763
7764       if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) {
7765         OtherUses.clear();
7766         break;
7767       }
7768
7769       SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1);
7770       if (Op1.getNode() == BasePtr.getNode())
7771         std::swap(Op0, Op1);
7772       assert(Op0.getNode() == BasePtr.getNode() &&
7773              "Use of ADD/SUB but not an operand");
7774
7775       if (!isa<ConstantSDNode>(Op1)) {
7776         OtherUses.clear();
7777         break;
7778       }
7779
7780       // FIXME: In some cases, we can be smarter about this.
7781       if (Op1.getValueType() != Offset.getValueType()) {
7782         OtherUses.clear();
7783         break;
7784       }
7785
7786       OtherUses.push_back(Use);
7787     }
7788
7789   if (Swapped)
7790     std::swap(BasePtr, Offset);
7791
7792   // Now check for #3 and #4.
7793   bool RealUse = false;
7794
7795   // Caches for hasPredecessorHelper
7796   SmallPtrSet<const SDNode *, 32> Visited;
7797   SmallVector<const SDNode *, 16> Worklist;
7798
7799   for (SDNode *Use : Ptr.getNode()->uses()) {
7800     if (Use == N)
7801       continue;
7802     if (N->hasPredecessorHelper(Use, Visited, Worklist))
7803       return false;
7804
7805     // If Ptr may be folded in addressing mode of other use, then it's
7806     // not profitable to do this transformation.
7807     if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
7808       RealUse = true;
7809   }
7810
7811   if (!RealUse)
7812     return false;
7813
7814   SDValue Result;
7815   if (isLoad)
7816     Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
7817                                 BasePtr, Offset, AM);
7818   else
7819     Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
7820                                  BasePtr, Offset, AM);
7821   ++PreIndexedNodes;
7822   ++NodesCombined;
7823   DEBUG(dbgs() << "\nReplacing.4 ";
7824         N->dump(&DAG);
7825         dbgs() << "\nWith: ";
7826         Result.getNode()->dump(&DAG);
7827         dbgs() << '\n');
7828   WorklistRemover DeadNodes(*this);
7829   if (isLoad) {
7830     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7831     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
7832   } else {
7833     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
7834   }
7835
7836   // Finally, since the node is now dead, remove it from the graph.
7837   deleteAndRecombine(N);
7838
7839   if (Swapped)
7840     std::swap(BasePtr, Offset);
7841
7842   // Replace other uses of BasePtr that can be updated to use Ptr
7843   for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
7844     unsigned OffsetIdx = 1;
7845     if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
7846       OffsetIdx = 0;
7847     assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
7848            BasePtr.getNode() && "Expected BasePtr operand");
7849
7850     // We need to replace ptr0 in the following expression:
7851     //   x0 * offset0 + y0 * ptr0 = t0
7852     // knowing that
7853     //   x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
7854     //
7855     // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
7856     // indexed load/store and the expresion that needs to be re-written.
7857     //
7858     // Therefore, we have:
7859     //   t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
7860
7861     ConstantSDNode *CN =
7862       cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
7863     int X0, X1, Y0, Y1;
7864     APInt Offset0 = CN->getAPIntValue();
7865     APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
7866
7867     X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
7868     Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
7869     X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
7870     Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
7871
7872     unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
7873
7874     APInt CNV = Offset0;
7875     if (X0 < 0) CNV = -CNV;
7876     if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
7877     else CNV = CNV - Offset1;
7878
7879     // We can now generate the new expression.
7880     SDValue NewOp1 = DAG.getConstant(CNV, CN->getValueType(0));
7881     SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
7882
7883     SDValue NewUse = DAG.getNode(Opcode,
7884                                  SDLoc(OtherUses[i]),
7885                                  OtherUses[i]->getValueType(0), NewOp1, NewOp2);
7886     DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
7887     deleteAndRecombine(OtherUses[i]);
7888   }
7889
7890   // Replace the uses of Ptr with uses of the updated base value.
7891   DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
7892   deleteAndRecombine(Ptr.getNode());
7893
7894   return true;
7895 }
7896
7897 /// Try to combine a load/store with a add/sub of the base pointer node into a
7898 /// post-indexed load/store. The transformation folded the add/subtract into the
7899 /// new indexed load/store effectively and all of its uses are redirected to the
7900 /// new load/store.
7901 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
7902   if (Level < AfterLegalizeDAG)
7903     return false;
7904
7905   bool isLoad = true;
7906   SDValue Ptr;
7907   EVT VT;
7908   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
7909     if (LD->isIndexed())
7910       return false;
7911     VT = LD->getMemoryVT();
7912     if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
7913         !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
7914       return false;
7915     Ptr = LD->getBasePtr();
7916   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
7917     if (ST->isIndexed())
7918       return false;
7919     VT = ST->getMemoryVT();
7920     if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
7921         !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
7922       return false;
7923     Ptr = ST->getBasePtr();
7924     isLoad = false;
7925   } else {
7926     return false;
7927   }
7928
7929   if (Ptr.getNode()->hasOneUse())
7930     return false;
7931
7932   for (SDNode *Op : Ptr.getNode()->uses()) {
7933     if (Op == N ||
7934         (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
7935       continue;
7936
7937     SDValue BasePtr;
7938     SDValue Offset;
7939     ISD::MemIndexedMode AM = ISD::UNINDEXED;
7940     if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
7941       // Don't create a indexed load / store with zero offset.
7942       if (isa<ConstantSDNode>(Offset) &&
7943           cast<ConstantSDNode>(Offset)->isNullValue())
7944         continue;
7945
7946       // Try turning it into a post-indexed load / store except when
7947       // 1) All uses are load / store ops that use it as base ptr (and
7948       //    it may be folded as addressing mmode).
7949       // 2) Op must be independent of N, i.e. Op is neither a predecessor
7950       //    nor a successor of N. Otherwise, if Op is folded that would
7951       //    create a cycle.
7952
7953       if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7954         continue;
7955
7956       // Check for #1.
7957       bool TryNext = false;
7958       for (SDNode *Use : BasePtr.getNode()->uses()) {
7959         if (Use == Ptr.getNode())
7960           continue;
7961
7962         // If all the uses are load / store addresses, then don't do the
7963         // transformation.
7964         if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
7965           bool RealUse = false;
7966           for (SDNode *UseUse : Use->uses()) {
7967             if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
7968               RealUse = true;
7969           }
7970
7971           if (!RealUse) {
7972             TryNext = true;
7973             break;
7974           }
7975         }
7976       }
7977
7978       if (TryNext)
7979         continue;
7980
7981       // Check for #2
7982       if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
7983         SDValue Result = isLoad
7984           ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
7985                                BasePtr, Offset, AM)
7986           : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
7987                                 BasePtr, Offset, AM);
7988         ++PostIndexedNodes;
7989         ++NodesCombined;
7990         DEBUG(dbgs() << "\nReplacing.5 ";
7991               N->dump(&DAG);
7992               dbgs() << "\nWith: ";
7993               Result.getNode()->dump(&DAG);
7994               dbgs() << '\n');
7995         WorklistRemover DeadNodes(*this);
7996         if (isLoad) {
7997           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7998           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
7999         } else {
8000           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
8001         }
8002
8003         // Finally, since the node is now dead, remove it from the graph.
8004         deleteAndRecombine(N);
8005
8006         // Replace the uses of Use with uses of the updated base value.
8007         DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
8008                                       Result.getValue(isLoad ? 1 : 0));
8009         deleteAndRecombine(Op);
8010         return true;
8011       }
8012     }
8013   }
8014
8015   return false;
8016 }
8017
8018 SDValue DAGCombiner::visitLOAD(SDNode *N) {
8019   LoadSDNode *LD  = cast<LoadSDNode>(N);
8020   SDValue Chain = LD->getChain();
8021   SDValue Ptr   = LD->getBasePtr();
8022
8023   // If load is not volatile and there are no uses of the loaded value (and
8024   // the updated indexed value in case of indexed loads), change uses of the
8025   // chain value into uses of the chain input (i.e. delete the dead load).
8026   if (!LD->isVolatile()) {
8027     if (N->getValueType(1) == MVT::Other) {
8028       // Unindexed loads.
8029       if (!N->hasAnyUseOfValue(0)) {
8030         // It's not safe to use the two value CombineTo variant here. e.g.
8031         // v1, chain2 = load chain1, loc
8032         // v2, chain3 = load chain2, loc
8033         // v3         = add v2, c
8034         // Now we replace use of chain2 with chain1.  This makes the second load
8035         // isomorphic to the one we are deleting, and thus makes this load live.
8036         DEBUG(dbgs() << "\nReplacing.6 ";
8037               N->dump(&DAG);
8038               dbgs() << "\nWith chain: ";
8039               Chain.getNode()->dump(&DAG);
8040               dbgs() << "\n");
8041         WorklistRemover DeadNodes(*this);
8042         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
8043
8044         if (N->use_empty())
8045           deleteAndRecombine(N);
8046
8047         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
8048       }
8049     } else {
8050       // Indexed loads.
8051       assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
8052       if (!N->hasAnyUseOfValue(0) && !N->hasAnyUseOfValue(1)) {
8053         SDValue Undef = DAG.getUNDEF(N->getValueType(0));
8054         DEBUG(dbgs() << "\nReplacing.7 ";
8055               N->dump(&DAG);
8056               dbgs() << "\nWith: ";
8057               Undef.getNode()->dump(&DAG);
8058               dbgs() << " and 2 other values\n");
8059         WorklistRemover DeadNodes(*this);
8060         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
8061         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1),
8062                                       DAG.getUNDEF(N->getValueType(1)));
8063         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
8064         deleteAndRecombine(N);
8065         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
8066       }
8067     }
8068   }
8069
8070   // If this load is directly stored, replace the load value with the stored
8071   // value.
8072   // TODO: Handle store large -> read small portion.
8073   // TODO: Handle TRUNCSTORE/LOADEXT
8074   if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
8075     if (ISD::isNON_TRUNCStore(Chain.getNode())) {
8076       StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
8077       if (PrevST->getBasePtr() == Ptr &&
8078           PrevST->getValue().getValueType() == N->getValueType(0))
8079       return CombineTo(N, Chain.getOperand(1), Chain);
8080     }
8081   }
8082
8083   // Try to infer better alignment information than the load already has.
8084   if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
8085     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
8086       if (Align > LD->getMemOperand()->getBaseAlignment()) {
8087         SDValue NewLoad =
8088                DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
8089                               LD->getValueType(0),
8090                               Chain, Ptr, LD->getPointerInfo(),
8091                               LD->getMemoryVT(),
8092                               LD->isVolatile(), LD->isNonTemporal(),
8093                               LD->isInvariant(), Align, LD->getAAInfo());
8094         return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
8095       }
8096     }
8097   }
8098
8099   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
8100     TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
8101 #ifndef NDEBUG
8102   if (CombinerAAOnlyFunc.getNumOccurrences() &&
8103       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
8104     UseAA = false;
8105 #endif
8106   if (UseAA && LD->isUnindexed()) {
8107     // Walk up chain skipping non-aliasing memory nodes.
8108     SDValue BetterChain = FindBetterChain(N, Chain);
8109
8110     // If there is a better chain.
8111     if (Chain != BetterChain) {
8112       SDValue ReplLoad;
8113
8114       // Replace the chain to void dependency.
8115       if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
8116         ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
8117                                BetterChain, Ptr, LD->getMemOperand());
8118       } else {
8119         ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
8120                                   LD->getValueType(0),
8121                                   BetterChain, Ptr, LD->getMemoryVT(),
8122                                   LD->getMemOperand());
8123       }
8124
8125       // Create token factor to keep old chain connected.
8126       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
8127                                   MVT::Other, Chain, ReplLoad.getValue(1));
8128
8129       // Make sure the new and old chains are cleaned up.
8130       AddToWorklist(Token.getNode());
8131
8132       // Replace uses with load result and token factor. Don't add users
8133       // to work list.
8134       return CombineTo(N, ReplLoad.getValue(0), Token, false);
8135     }
8136   }
8137
8138   // Try transforming N to an indexed load.
8139   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
8140     return SDValue(N, 0);
8141
8142   // Try to slice up N to more direct loads if the slices are mapped to
8143   // different register banks or pairing can take place.
8144   if (SliceUpLoad(N))
8145     return SDValue(N, 0);
8146
8147   return SDValue();
8148 }
8149
8150 namespace {
8151 /// \brief Helper structure used to slice a load in smaller loads.
8152 /// Basically a slice is obtained from the following sequence:
8153 /// Origin = load Ty1, Base
8154 /// Shift = srl Ty1 Origin, CstTy Amount
8155 /// Inst = trunc Shift to Ty2
8156 ///
8157 /// Then, it will be rewriten into:
8158 /// Slice = load SliceTy, Base + SliceOffset
8159 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
8160 ///
8161 /// SliceTy is deduced from the number of bits that are actually used to
8162 /// build Inst.
8163 struct LoadedSlice {
8164   /// \brief Helper structure used to compute the cost of a slice.
8165   struct Cost {
8166     /// Are we optimizing for code size.
8167     bool ForCodeSize;
8168     /// Various cost.
8169     unsigned Loads;
8170     unsigned Truncates;
8171     unsigned CrossRegisterBanksCopies;
8172     unsigned ZExts;
8173     unsigned Shift;
8174
8175     Cost(bool ForCodeSize = false)
8176         : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
8177           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
8178
8179     /// \brief Get the cost of one isolated slice.
8180     Cost(const LoadedSlice &LS, bool ForCodeSize = false)
8181         : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
8182           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
8183       EVT TruncType = LS.Inst->getValueType(0);
8184       EVT LoadedType = LS.getLoadedType();
8185       if (TruncType != LoadedType &&
8186           !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
8187         ZExts = 1;
8188     }
8189
8190     /// \brief Account for slicing gain in the current cost.
8191     /// Slicing provide a few gains like removing a shift or a
8192     /// truncate. This method allows to grow the cost of the original
8193     /// load with the gain from this slice.
8194     void addSliceGain(const LoadedSlice &LS) {
8195       // Each slice saves a truncate.
8196       const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
8197       if (!TLI.isTruncateFree(LS.Inst->getValueType(0),
8198                               LS.Inst->getOperand(0).getValueType()))
8199         ++Truncates;
8200       // If there is a shift amount, this slice gets rid of it.
8201       if (LS.Shift)
8202         ++Shift;
8203       // If this slice can merge a cross register bank copy, account for it.
8204       if (LS.canMergeExpensiveCrossRegisterBankCopy())
8205         ++CrossRegisterBanksCopies;
8206     }
8207
8208     Cost &operator+=(const Cost &RHS) {
8209       Loads += RHS.Loads;
8210       Truncates += RHS.Truncates;
8211       CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
8212       ZExts += RHS.ZExts;
8213       Shift += RHS.Shift;
8214       return *this;
8215     }
8216
8217     bool operator==(const Cost &RHS) const {
8218       return Loads == RHS.Loads && Truncates == RHS.Truncates &&
8219              CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
8220              ZExts == RHS.ZExts && Shift == RHS.Shift;
8221     }
8222
8223     bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
8224
8225     bool operator<(const Cost &RHS) const {
8226       // Assume cross register banks copies are as expensive as loads.
8227       // FIXME: Do we want some more target hooks?
8228       unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
8229       unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
8230       // Unless we are optimizing for code size, consider the
8231       // expensive operation first.
8232       if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
8233         return ExpensiveOpsLHS < ExpensiveOpsRHS;
8234       return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
8235              (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
8236     }
8237
8238     bool operator>(const Cost &RHS) const { return RHS < *this; }
8239
8240     bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
8241
8242     bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
8243   };
8244   // The last instruction that represent the slice. This should be a
8245   // truncate instruction.
8246   SDNode *Inst;
8247   // The original load instruction.
8248   LoadSDNode *Origin;
8249   // The right shift amount in bits from the original load.
8250   unsigned Shift;
8251   // The DAG from which Origin came from.
8252   // This is used to get some contextual information about legal types, etc.
8253   SelectionDAG *DAG;
8254
8255   LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
8256               unsigned Shift = 0, SelectionDAG *DAG = nullptr)
8257       : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
8258
8259   LoadedSlice(const LoadedSlice &LS)
8260       : Inst(LS.Inst), Origin(LS.Origin), Shift(LS.Shift), DAG(LS.DAG) {}
8261
8262   /// \brief Get the bits used in a chunk of bits \p BitWidth large.
8263   /// \return Result is \p BitWidth and has used bits set to 1 and
8264   ///         not used bits set to 0.
8265   APInt getUsedBits() const {
8266     // Reproduce the trunc(lshr) sequence:
8267     // - Start from the truncated value.
8268     // - Zero extend to the desired bit width.
8269     // - Shift left.
8270     assert(Origin && "No original load to compare against.");
8271     unsigned BitWidth = Origin->getValueSizeInBits(0);
8272     assert(Inst && "This slice is not bound to an instruction");
8273     assert(Inst->getValueSizeInBits(0) <= BitWidth &&
8274            "Extracted slice is bigger than the whole type!");
8275     APInt UsedBits(Inst->getValueSizeInBits(0), 0);
8276     UsedBits.setAllBits();
8277     UsedBits = UsedBits.zext(BitWidth);
8278     UsedBits <<= Shift;
8279     return UsedBits;
8280   }
8281
8282   /// \brief Get the size of the slice to be loaded in bytes.
8283   unsigned getLoadedSize() const {
8284     unsigned SliceSize = getUsedBits().countPopulation();
8285     assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
8286     return SliceSize / 8;
8287   }
8288
8289   /// \brief Get the type that will be loaded for this slice.
8290   /// Note: This may not be the final type for the slice.
8291   EVT getLoadedType() const {
8292     assert(DAG && "Missing context");
8293     LLVMContext &Ctxt = *DAG->getContext();
8294     return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
8295   }
8296
8297   /// \brief Get the alignment of the load used for this slice.
8298   unsigned getAlignment() const {
8299     unsigned Alignment = Origin->getAlignment();
8300     unsigned Offset = getOffsetFromBase();
8301     if (Offset != 0)
8302       Alignment = MinAlign(Alignment, Alignment + Offset);
8303     return Alignment;
8304   }
8305
8306   /// \brief Check if this slice can be rewritten with legal operations.
8307   bool isLegal() const {
8308     // An invalid slice is not legal.
8309     if (!Origin || !Inst || !DAG)
8310       return false;
8311
8312     // Offsets are for indexed load only, we do not handle that.
8313     if (Origin->getOffset().getOpcode() != ISD::UNDEF)
8314       return false;
8315
8316     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8317
8318     // Check that the type is legal.
8319     EVT SliceType = getLoadedType();
8320     if (!TLI.isTypeLegal(SliceType))
8321       return false;
8322
8323     // Check that the load is legal for this type.
8324     if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
8325       return false;
8326
8327     // Check that the offset can be computed.
8328     // 1. Check its type.
8329     EVT PtrType = Origin->getBasePtr().getValueType();
8330     if (PtrType == MVT::Untyped || PtrType.isExtended())
8331       return false;
8332
8333     // 2. Check that it fits in the immediate.
8334     if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
8335       return false;
8336
8337     // 3. Check that the computation is legal.
8338     if (!TLI.isOperationLegal(ISD::ADD, PtrType))
8339       return false;
8340
8341     // Check that the zext is legal if it needs one.
8342     EVT TruncateType = Inst->getValueType(0);
8343     if (TruncateType != SliceType &&
8344         !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
8345       return false;
8346
8347     return true;
8348   }
8349
8350   /// \brief Get the offset in bytes of this slice in the original chunk of
8351   /// bits.
8352   /// \pre DAG != nullptr.
8353   uint64_t getOffsetFromBase() const {
8354     assert(DAG && "Missing context.");
8355     bool IsBigEndian =
8356         DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian();
8357     assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
8358     uint64_t Offset = Shift / 8;
8359     unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
8360     assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
8361            "The size of the original loaded type is not a multiple of a"
8362            " byte.");
8363     // If Offset is bigger than TySizeInBytes, it means we are loading all
8364     // zeros. This should have been optimized before in the process.
8365     assert(TySizeInBytes > Offset &&
8366            "Invalid shift amount for given loaded size");
8367     if (IsBigEndian)
8368       Offset = TySizeInBytes - Offset - getLoadedSize();
8369     return Offset;
8370   }
8371
8372   /// \brief Generate the sequence of instructions to load the slice
8373   /// represented by this object and redirect the uses of this slice to
8374   /// this new sequence of instructions.
8375   /// \pre this->Inst && this->Origin are valid Instructions and this
8376   /// object passed the legal check: LoadedSlice::isLegal returned true.
8377   /// \return The last instruction of the sequence used to load the slice.
8378   SDValue loadSlice() const {
8379     assert(Inst && Origin && "Unable to replace a non-existing slice.");
8380     const SDValue &OldBaseAddr = Origin->getBasePtr();
8381     SDValue BaseAddr = OldBaseAddr;
8382     // Get the offset in that chunk of bytes w.r.t. the endianess.
8383     int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
8384     assert(Offset >= 0 && "Offset too big to fit in int64_t!");
8385     if (Offset) {
8386       // BaseAddr = BaseAddr + Offset.
8387       EVT ArithType = BaseAddr.getValueType();
8388       BaseAddr = DAG->getNode(ISD::ADD, SDLoc(Origin), ArithType, BaseAddr,
8389                               DAG->getConstant(Offset, ArithType));
8390     }
8391
8392     // Create the type of the loaded slice according to its size.
8393     EVT SliceType = getLoadedType();
8394
8395     // Create the load for the slice.
8396     SDValue LastInst = DAG->getLoad(
8397         SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
8398         Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
8399         Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
8400     // If the final type is not the same as the loaded type, this means that
8401     // we have to pad with zero. Create a zero extend for that.
8402     EVT FinalType = Inst->getValueType(0);
8403     if (SliceType != FinalType)
8404       LastInst =
8405           DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
8406     return LastInst;
8407   }
8408
8409   /// \brief Check if this slice can be merged with an expensive cross register
8410   /// bank copy. E.g.,
8411   /// i = load i32
8412   /// f = bitcast i32 i to float
8413   bool canMergeExpensiveCrossRegisterBankCopy() const {
8414     if (!Inst || !Inst->hasOneUse())
8415       return false;
8416     SDNode *Use = *Inst->use_begin();
8417     if (Use->getOpcode() != ISD::BITCAST)
8418       return false;
8419     assert(DAG && "Missing context");
8420     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8421     EVT ResVT = Use->getValueType(0);
8422     const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
8423     const TargetRegisterClass *ArgRC =
8424         TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
8425     if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
8426       return false;
8427
8428     // At this point, we know that we perform a cross-register-bank copy.
8429     // Check if it is expensive.
8430     const TargetRegisterInfo *TRI =
8431         TLI.getTargetMachine().getSubtargetImpl()->getRegisterInfo();
8432     // Assume bitcasts are cheap, unless both register classes do not
8433     // explicitly share a common sub class.
8434     if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
8435       return false;
8436
8437     // Check if it will be merged with the load.
8438     // 1. Check the alignment constraint.
8439     unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment(
8440         ResVT.getTypeForEVT(*DAG->getContext()));
8441
8442     if (RequiredAlignment > getAlignment())
8443       return false;
8444
8445     // 2. Check that the load is a legal operation for that type.
8446     if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
8447       return false;
8448
8449     // 3. Check that we do not have a zext in the way.
8450     if (Inst->getValueType(0) != getLoadedType())
8451       return false;
8452
8453     return true;
8454   }
8455 };
8456 }
8457
8458 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
8459 /// \p UsedBits looks like 0..0 1..1 0..0.
8460 static bool areUsedBitsDense(const APInt &UsedBits) {
8461   // If all the bits are one, this is dense!
8462   if (UsedBits.isAllOnesValue())
8463     return true;
8464
8465   // Get rid of the unused bits on the right.
8466   APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
8467   // Get rid of the unused bits on the left.
8468   if (NarrowedUsedBits.countLeadingZeros())
8469     NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
8470   // Check that the chunk of bits is completely used.
8471   return NarrowedUsedBits.isAllOnesValue();
8472 }
8473
8474 /// \brief Check whether or not \p First and \p Second are next to each other
8475 /// in memory. This means that there is no hole between the bits loaded
8476 /// by \p First and the bits loaded by \p Second.
8477 static bool areSlicesNextToEachOther(const LoadedSlice &First,
8478                                      const LoadedSlice &Second) {
8479   assert(First.Origin == Second.Origin && First.Origin &&
8480          "Unable to match different memory origins.");
8481   APInt UsedBits = First.getUsedBits();
8482   assert((UsedBits & Second.getUsedBits()) == 0 &&
8483          "Slices are not supposed to overlap.");
8484   UsedBits |= Second.getUsedBits();
8485   return areUsedBitsDense(UsedBits);
8486 }
8487
8488 /// \brief Adjust the \p GlobalLSCost according to the target
8489 /// paring capabilities and the layout of the slices.
8490 /// \pre \p GlobalLSCost should account for at least as many loads as
8491 /// there is in the slices in \p LoadedSlices.
8492 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8493                                  LoadedSlice::Cost &GlobalLSCost) {
8494   unsigned NumberOfSlices = LoadedSlices.size();
8495   // If there is less than 2 elements, no pairing is possible.
8496   if (NumberOfSlices < 2)
8497     return;
8498
8499   // Sort the slices so that elements that are likely to be next to each
8500   // other in memory are next to each other in the list.
8501   std::sort(LoadedSlices.begin(), LoadedSlices.end(),
8502             [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
8503     assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
8504     return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
8505   });
8506   const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
8507   // First (resp. Second) is the first (resp. Second) potentially candidate
8508   // to be placed in a paired load.
8509   const LoadedSlice *First = nullptr;
8510   const LoadedSlice *Second = nullptr;
8511   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
8512                 // Set the beginning of the pair.
8513                                                            First = Second) {
8514
8515     Second = &LoadedSlices[CurrSlice];
8516
8517     // If First is NULL, it means we start a new pair.
8518     // Get to the next slice.
8519     if (!First)
8520       continue;
8521
8522     EVT LoadedType = First->getLoadedType();
8523
8524     // If the types of the slices are different, we cannot pair them.
8525     if (LoadedType != Second->getLoadedType())
8526       continue;
8527
8528     // Check if the target supplies paired loads for this type.
8529     unsigned RequiredAlignment = 0;
8530     if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
8531       // move to the next pair, this type is hopeless.
8532       Second = nullptr;
8533       continue;
8534     }
8535     // Check if we meet the alignment requirement.
8536     if (RequiredAlignment > First->getAlignment())
8537       continue;
8538
8539     // Check that both loads are next to each other in memory.
8540     if (!areSlicesNextToEachOther(*First, *Second))
8541       continue;
8542
8543     assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
8544     --GlobalLSCost.Loads;
8545     // Move to the next pair.
8546     Second = nullptr;
8547   }
8548 }
8549
8550 /// \brief Check the profitability of all involved LoadedSlice.
8551 /// Currently, it is considered profitable if there is exactly two
8552 /// involved slices (1) which are (2) next to each other in memory, and
8553 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
8554 ///
8555 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
8556 /// the elements themselves.
8557 ///
8558 /// FIXME: When the cost model will be mature enough, we can relax
8559 /// constraints (1) and (2).
8560 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8561                                 const APInt &UsedBits, bool ForCodeSize) {
8562   unsigned NumberOfSlices = LoadedSlices.size();
8563   if (StressLoadSlicing)
8564     return NumberOfSlices > 1;
8565
8566   // Check (1).
8567   if (NumberOfSlices != 2)
8568     return false;
8569
8570   // Check (2).
8571   if (!areUsedBitsDense(UsedBits))
8572     return false;
8573
8574   // Check (3).
8575   LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
8576   // The original code has one big load.
8577   OrigCost.Loads = 1;
8578   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
8579     const LoadedSlice &LS = LoadedSlices[CurrSlice];
8580     // Accumulate the cost of all the slices.
8581     LoadedSlice::Cost SliceCost(LS, ForCodeSize);
8582     GlobalSlicingCost += SliceCost;
8583
8584     // Account as cost in the original configuration the gain obtained
8585     // with the current slices.
8586     OrigCost.addSliceGain(LS);
8587   }
8588
8589   // If the target supports paired load, adjust the cost accordingly.
8590   adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
8591   return OrigCost > GlobalSlicingCost;
8592 }
8593
8594 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
8595 /// operations, split it in the various pieces being extracted.
8596 ///
8597 /// This sort of thing is introduced by SROA.
8598 /// This slicing takes care not to insert overlapping loads.
8599 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
8600 bool DAGCombiner::SliceUpLoad(SDNode *N) {
8601   if (Level < AfterLegalizeDAG)
8602     return false;
8603
8604   LoadSDNode *LD = cast<LoadSDNode>(N);
8605   if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
8606       !LD->getValueType(0).isInteger())
8607     return false;
8608
8609   // Keep track of already used bits to detect overlapping values.
8610   // In that case, we will just abort the transformation.
8611   APInt UsedBits(LD->getValueSizeInBits(0), 0);
8612
8613   SmallVector<LoadedSlice, 4> LoadedSlices;
8614
8615   // Check if this load is used as several smaller chunks of bits.
8616   // Basically, look for uses in trunc or trunc(lshr) and record a new chain
8617   // of computation for each trunc.
8618   for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
8619        UI != UIEnd; ++UI) {
8620     // Skip the uses of the chain.
8621     if (UI.getUse().getResNo() != 0)
8622       continue;
8623
8624     SDNode *User = *UI;
8625     unsigned Shift = 0;
8626
8627     // Check if this is a trunc(lshr).
8628     if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
8629         isa<ConstantSDNode>(User->getOperand(1))) {
8630       Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
8631       User = *User->use_begin();
8632     }
8633
8634     // At this point, User is a Truncate, iff we encountered, trunc or
8635     // trunc(lshr).
8636     if (User->getOpcode() != ISD::TRUNCATE)
8637       return false;
8638
8639     // The width of the type must be a power of 2 and greater than 8-bits.
8640     // Otherwise the load cannot be represented in LLVM IR.
8641     // Moreover, if we shifted with a non-8-bits multiple, the slice
8642     // will be across several bytes. We do not support that.
8643     unsigned Width = User->getValueSizeInBits(0);
8644     if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
8645       return 0;
8646
8647     // Build the slice for this chain of computations.
8648     LoadedSlice LS(User, LD, Shift, &DAG);
8649     APInt CurrentUsedBits = LS.getUsedBits();
8650
8651     // Check if this slice overlaps with another.
8652     if ((CurrentUsedBits & UsedBits) != 0)
8653       return false;
8654     // Update the bits used globally.
8655     UsedBits |= CurrentUsedBits;
8656
8657     // Check if the new slice would be legal.
8658     if (!LS.isLegal())
8659       return false;
8660
8661     // Record the slice.
8662     LoadedSlices.push_back(LS);
8663   }
8664
8665   // Abort slicing if it does not seem to be profitable.
8666   if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
8667     return false;
8668
8669   ++SlicedLoads;
8670
8671   // Rewrite each chain to use an independent load.
8672   // By construction, each chain can be represented by a unique load.
8673
8674   // Prepare the argument for the new token factor for all the slices.
8675   SmallVector<SDValue, 8> ArgChains;
8676   for (SmallVectorImpl<LoadedSlice>::const_iterator
8677            LSIt = LoadedSlices.begin(),
8678            LSItEnd = LoadedSlices.end();
8679        LSIt != LSItEnd; ++LSIt) {
8680     SDValue SliceInst = LSIt->loadSlice();
8681     CombineTo(LSIt->Inst, SliceInst, true);
8682     if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
8683       SliceInst = SliceInst.getOperand(0);
8684     assert(SliceInst->getOpcode() == ISD::LOAD &&
8685            "It takes more than a zext to get to the loaded slice!!");
8686     ArgChains.push_back(SliceInst.getValue(1));
8687   }
8688
8689   SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
8690                               ArgChains);
8691   DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
8692   return true;
8693 }
8694
8695 /// Check to see if V is (and load (ptr), imm), where the load is having
8696 /// specific bytes cleared out.  If so, return the byte size being masked out
8697 /// and the shift amount.
8698 static std::pair<unsigned, unsigned>
8699 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
8700   std::pair<unsigned, unsigned> Result(0, 0);
8701
8702   // Check for the structure we're looking for.
8703   if (V->getOpcode() != ISD::AND ||
8704       !isa<ConstantSDNode>(V->getOperand(1)) ||
8705       !ISD::isNormalLoad(V->getOperand(0).getNode()))
8706     return Result;
8707
8708   // Check the chain and pointer.
8709   LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
8710   if (LD->getBasePtr() != Ptr) return Result;  // Not from same pointer.
8711
8712   // The store should be chained directly to the load or be an operand of a
8713   // tokenfactor.
8714   if (LD == Chain.getNode())
8715     ; // ok.
8716   else if (Chain->getOpcode() != ISD::TokenFactor)
8717     return Result; // Fail.
8718   else {
8719     bool isOk = false;
8720     for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
8721       if (Chain->getOperand(i).getNode() == LD) {
8722         isOk = true;
8723         break;
8724       }
8725     if (!isOk) return Result;
8726   }
8727
8728   // This only handles simple types.
8729   if (V.getValueType() != MVT::i16 &&
8730       V.getValueType() != MVT::i32 &&
8731       V.getValueType() != MVT::i64)
8732     return Result;
8733
8734   // Check the constant mask.  Invert it so that the bits being masked out are
8735   // 0 and the bits being kept are 1.  Use getSExtValue so that leading bits
8736   // follow the sign bit for uniformity.
8737   uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
8738   unsigned NotMaskLZ = countLeadingZeros(NotMask);
8739   if (NotMaskLZ & 7) return Result;  // Must be multiple of a byte.
8740   unsigned NotMaskTZ = countTrailingZeros(NotMask);
8741   if (NotMaskTZ & 7) return Result;  // Must be multiple of a byte.
8742   if (NotMaskLZ == 64) return Result;  // All zero mask.
8743
8744   // See if we have a continuous run of bits.  If so, we have 0*1+0*
8745   if (CountTrailingOnes_64(NotMask >> NotMaskTZ)+NotMaskTZ+NotMaskLZ != 64)
8746     return Result;
8747
8748   // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
8749   if (V.getValueType() != MVT::i64 && NotMaskLZ)
8750     NotMaskLZ -= 64-V.getValueSizeInBits();
8751
8752   unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
8753   switch (MaskedBytes) {
8754   case 1:
8755   case 2:
8756   case 4: break;
8757   default: return Result; // All one mask, or 5-byte mask.
8758   }
8759
8760   // Verify that the first bit starts at a multiple of mask so that the access
8761   // is aligned the same as the access width.
8762   if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
8763
8764   Result.first = MaskedBytes;
8765   Result.second = NotMaskTZ/8;
8766   return Result;
8767 }
8768
8769
8770 /// Check to see if IVal is something that provides a value as specified by
8771 /// MaskInfo. If so, replace the specified store with a narrower store of
8772 /// truncated IVal.
8773 static SDNode *
8774 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
8775                                 SDValue IVal, StoreSDNode *St,
8776                                 DAGCombiner *DC) {
8777   unsigned NumBytes = MaskInfo.first;
8778   unsigned ByteShift = MaskInfo.second;
8779   SelectionDAG &DAG = DC->getDAG();
8780
8781   // Check to see if IVal is all zeros in the part being masked in by the 'or'
8782   // that uses this.  If not, this is not a replacement.
8783   APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
8784                                   ByteShift*8, (ByteShift+NumBytes)*8);
8785   if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
8786
8787   // Check that it is legal on the target to do this.  It is legal if the new
8788   // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
8789   // legalization.
8790   MVT VT = MVT::getIntegerVT(NumBytes*8);
8791   if (!DC->isTypeLegal(VT))
8792     return nullptr;
8793
8794   // Okay, we can do this!  Replace the 'St' store with a store of IVal that is
8795   // shifted by ByteShift and truncated down to NumBytes.
8796   if (ByteShift)
8797     IVal = DAG.getNode(ISD::SRL, SDLoc(IVal), IVal.getValueType(), IVal,
8798                        DAG.getConstant(ByteShift*8,
8799                                     DC->getShiftAmountTy(IVal.getValueType())));
8800
8801   // Figure out the offset for the store and the alignment of the access.
8802   unsigned StOffset;
8803   unsigned NewAlign = St->getAlignment();
8804
8805   if (DAG.getTargetLoweringInfo().isLittleEndian())
8806     StOffset = ByteShift;
8807   else
8808     StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
8809
8810   SDValue Ptr = St->getBasePtr();
8811   if (StOffset) {
8812     Ptr = DAG.getNode(ISD::ADD, SDLoc(IVal), Ptr.getValueType(),
8813                       Ptr, DAG.getConstant(StOffset, Ptr.getValueType()));
8814     NewAlign = MinAlign(NewAlign, StOffset);
8815   }
8816
8817   // Truncate down to the new size.
8818   IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
8819
8820   ++OpsNarrowed;
8821   return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
8822                       St->getPointerInfo().getWithOffset(StOffset),
8823                       false, false, NewAlign).getNode();
8824 }
8825
8826
8827 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and
8828 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try
8829 /// narrowing the load and store if it would end up being a win for performance
8830 /// or code size.
8831 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
8832   StoreSDNode *ST  = cast<StoreSDNode>(N);
8833   if (ST->isVolatile())
8834     return SDValue();
8835
8836   SDValue Chain = ST->getChain();
8837   SDValue Value = ST->getValue();
8838   SDValue Ptr   = ST->getBasePtr();
8839   EVT VT = Value.getValueType();
8840
8841   if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
8842     return SDValue();
8843
8844   unsigned Opc = Value.getOpcode();
8845
8846   // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
8847   // is a byte mask indicating a consecutive number of bytes, check to see if
8848   // Y is known to provide just those bytes.  If so, we try to replace the
8849   // load + replace + store sequence with a single (narrower) store, which makes
8850   // the load dead.
8851   if (Opc == ISD::OR) {
8852     std::pair<unsigned, unsigned> MaskedLoad;
8853     MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
8854     if (MaskedLoad.first)
8855       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8856                                                   Value.getOperand(1), ST,this))
8857         return SDValue(NewST, 0);
8858
8859     // Or is commutative, so try swapping X and Y.
8860     MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
8861     if (MaskedLoad.first)
8862       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8863                                                   Value.getOperand(0), ST,this))
8864         return SDValue(NewST, 0);
8865   }
8866
8867   if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
8868       Value.getOperand(1).getOpcode() != ISD::Constant)
8869     return SDValue();
8870
8871   SDValue N0 = Value.getOperand(0);
8872   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8873       Chain == SDValue(N0.getNode(), 1)) {
8874     LoadSDNode *LD = cast<LoadSDNode>(N0);
8875     if (LD->getBasePtr() != Ptr ||
8876         LD->getPointerInfo().getAddrSpace() !=
8877         ST->getPointerInfo().getAddrSpace())
8878       return SDValue();
8879
8880     // Find the type to narrow it the load / op / store to.
8881     SDValue N1 = Value.getOperand(1);
8882     unsigned BitWidth = N1.getValueSizeInBits();
8883     APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
8884     if (Opc == ISD::AND)
8885       Imm ^= APInt::getAllOnesValue(BitWidth);
8886     if (Imm == 0 || Imm.isAllOnesValue())
8887       return SDValue();
8888     unsigned ShAmt = Imm.countTrailingZeros();
8889     unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
8890     unsigned NewBW = NextPowerOf2(MSB - ShAmt);
8891     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
8892     while (NewBW < BitWidth &&
8893            !(TLI.isOperationLegalOrCustom(Opc, NewVT) &&
8894              TLI.isNarrowingProfitable(VT, NewVT))) {
8895       NewBW = NextPowerOf2(NewBW);
8896       NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
8897     }
8898     if (NewBW >= BitWidth)
8899       return SDValue();
8900
8901     // If the lsb changed does not start at the type bitwidth boundary,
8902     // start at the previous one.
8903     if (ShAmt % NewBW)
8904       ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
8905     APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
8906                                    std::min(BitWidth, ShAmt + NewBW));
8907     if ((Imm & Mask) == Imm) {
8908       APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
8909       if (Opc == ISD::AND)
8910         NewImm ^= APInt::getAllOnesValue(NewBW);
8911       uint64_t PtrOff = ShAmt / 8;
8912       // For big endian targets, we need to adjust the offset to the pointer to
8913       // load the correct bytes.
8914       if (TLI.isBigEndian())
8915         PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
8916
8917       unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
8918       Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
8919       if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
8920         return SDValue();
8921
8922       SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
8923                                    Ptr.getValueType(), Ptr,
8924                                    DAG.getConstant(PtrOff, Ptr.getValueType()));
8925       SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
8926                                   LD->getChain(), NewPtr,
8927                                   LD->getPointerInfo().getWithOffset(PtrOff),
8928                                   LD->isVolatile(), LD->isNonTemporal(),
8929                                   LD->isInvariant(), NewAlign,
8930                                   LD->getAAInfo());
8931       SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
8932                                    DAG.getConstant(NewImm, NewVT));
8933       SDValue NewST = DAG.getStore(Chain, SDLoc(N),
8934                                    NewVal, NewPtr,
8935                                    ST->getPointerInfo().getWithOffset(PtrOff),
8936                                    false, false, NewAlign);
8937
8938       AddToWorklist(NewPtr.getNode());
8939       AddToWorklist(NewLD.getNode());
8940       AddToWorklist(NewVal.getNode());
8941       WorklistRemover DeadNodes(*this);
8942       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
8943       ++OpsNarrowed;
8944       return NewST;
8945     }
8946   }
8947
8948   return SDValue();
8949 }
8950
8951 /// For a given floating point load / store pair, if the load value isn't used
8952 /// by any other operations, then consider transforming the pair to integer
8953 /// load / store operations if the target deems the transformation profitable.
8954 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
8955   StoreSDNode *ST  = cast<StoreSDNode>(N);
8956   SDValue Chain = ST->getChain();
8957   SDValue Value = ST->getValue();
8958   if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
8959       Value.hasOneUse() &&
8960       Chain == SDValue(Value.getNode(), 1)) {
8961     LoadSDNode *LD = cast<LoadSDNode>(Value);
8962     EVT VT = LD->getMemoryVT();
8963     if (!VT.isFloatingPoint() ||
8964         VT != ST->getMemoryVT() ||
8965         LD->isNonTemporal() ||
8966         ST->isNonTemporal() ||
8967         LD->getPointerInfo().getAddrSpace() != 0 ||
8968         ST->getPointerInfo().getAddrSpace() != 0)
8969       return SDValue();
8970
8971     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
8972     if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
8973         !TLI.isOperationLegal(ISD::STORE, IntVT) ||
8974         !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
8975         !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
8976       return SDValue();
8977
8978     unsigned LDAlign = LD->getAlignment();
8979     unsigned STAlign = ST->getAlignment();
8980     Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
8981     unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
8982     if (LDAlign < ABIAlign || STAlign < ABIAlign)
8983       return SDValue();
8984
8985     SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
8986                                 LD->getChain(), LD->getBasePtr(),
8987                                 LD->getPointerInfo(),
8988                                 false, false, false, LDAlign);
8989
8990     SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
8991                                  NewLD, ST->getBasePtr(),
8992                                  ST->getPointerInfo(),
8993                                  false, false, STAlign);
8994
8995     AddToWorklist(NewLD.getNode());
8996     AddToWorklist(NewST.getNode());
8997     WorklistRemover DeadNodes(*this);
8998     DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
8999     ++LdStFP2Int;
9000     return NewST;
9001   }
9002
9003   return SDValue();
9004 }
9005
9006 /// Helper struct to parse and store a memory address as base + index + offset.
9007 /// We ignore sign extensions when it is safe to do so.
9008 /// The following two expressions are not equivalent. To differentiate we need
9009 /// to store whether there was a sign extension involved in the index
9010 /// computation.
9011 ///  (load (i64 add (i64 copyfromreg %c)
9012 ///                 (i64 signextend (add (i8 load %index)
9013 ///                                      (i8 1))))
9014 /// vs
9015 ///
9016 /// (load (i64 add (i64 copyfromreg %c)
9017 ///                (i64 signextend (i32 add (i32 signextend (i8 load %index))
9018 ///                                         (i32 1)))))
9019 struct BaseIndexOffset {
9020   SDValue Base;
9021   SDValue Index;
9022   int64_t Offset;
9023   bool IsIndexSignExt;
9024
9025   BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
9026
9027   BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
9028                   bool IsIndexSignExt) :
9029     Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
9030
9031   bool equalBaseIndex(const BaseIndexOffset &Other) {
9032     return Other.Base == Base && Other.Index == Index &&
9033       Other.IsIndexSignExt == IsIndexSignExt;
9034   }
9035
9036   /// Parses tree in Ptr for base, index, offset addresses.
9037   static BaseIndexOffset match(SDValue Ptr) {
9038     bool IsIndexSignExt = false;
9039
9040     // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
9041     // instruction, then it could be just the BASE or everything else we don't
9042     // know how to handle. Just use Ptr as BASE and give up.
9043     if (Ptr->getOpcode() != ISD::ADD)
9044       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9045
9046     // We know that we have at least an ADD instruction. Try to pattern match
9047     // the simple case of BASE + OFFSET.
9048     if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
9049       int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
9050       return  BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
9051                               IsIndexSignExt);
9052     }
9053
9054     // Inside a loop the current BASE pointer is calculated using an ADD and a
9055     // MUL instruction. In this case Ptr is the actual BASE pointer.
9056     // (i64 add (i64 %array_ptr)
9057     //          (i64 mul (i64 %induction_var)
9058     //                   (i64 %element_size)))
9059     if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
9060       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9061
9062     // Look at Base + Index + Offset cases.
9063     SDValue Base = Ptr->getOperand(0);
9064     SDValue IndexOffset = Ptr->getOperand(1);
9065
9066     // Skip signextends.
9067     if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
9068       IndexOffset = IndexOffset->getOperand(0);
9069       IsIndexSignExt = true;
9070     }
9071
9072     // Either the case of Base + Index (no offset) or something else.
9073     if (IndexOffset->getOpcode() != ISD::ADD)
9074       return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
9075
9076     // Now we have the case of Base + Index + offset.
9077     SDValue Index = IndexOffset->getOperand(0);
9078     SDValue Offset = IndexOffset->getOperand(1);
9079
9080     if (!isa<ConstantSDNode>(Offset))
9081       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9082
9083     // Ignore signextends.
9084     if (Index->getOpcode() == ISD::SIGN_EXTEND) {
9085       Index = Index->getOperand(0);
9086       IsIndexSignExt = true;
9087     } else IsIndexSignExt = false;
9088
9089     int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
9090     return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
9091   }
9092 };
9093
9094 /// Holds a pointer to an LSBaseSDNode as well as information on where it
9095 /// is located in a sequence of memory operations connected by a chain.
9096 struct MemOpLink {
9097   MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
9098     MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
9099   // Ptr to the mem node.
9100   LSBaseSDNode *MemNode;
9101   // Offset from the base ptr.
9102   int64_t OffsetFromBase;
9103   // What is the sequence number of this mem node.
9104   // Lowest mem operand in the DAG starts at zero.
9105   unsigned SequenceNum;
9106 };
9107
9108 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
9109   EVT MemVT = St->getMemoryVT();
9110   int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
9111   bool NoVectors = DAG.getMachineFunction().getFunction()->getAttributes().
9112     hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
9113
9114   // Don't merge vectors into wider inputs.
9115   if (MemVT.isVector() || !MemVT.isSimple())
9116     return false;
9117
9118   // Perform an early exit check. Do not bother looking at stored values that
9119   // are not constants or loads.
9120   SDValue StoredVal = St->getValue();
9121   bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
9122   if (!isa<ConstantSDNode>(StoredVal) && !isa<ConstantFPSDNode>(StoredVal) &&
9123       !IsLoadSrc)
9124     return false;
9125
9126   // Only look at ends of store sequences.
9127   SDValue Chain = SDValue(St, 0);
9128   if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
9129     return false;
9130
9131   // This holds the base pointer, index, and the offset in bytes from the base
9132   // pointer.
9133   BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
9134
9135   // We must have a base and an offset.
9136   if (!BasePtr.Base.getNode())
9137     return false;
9138
9139   // Do not handle stores to undef base pointers.
9140   if (BasePtr.Base.getOpcode() == ISD::UNDEF)
9141     return false;
9142
9143   // Save the LoadSDNodes that we find in the chain.
9144   // We need to make sure that these nodes do not interfere with
9145   // any of the store nodes.
9146   SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
9147
9148   // Save the StoreSDNodes that we find in the chain.
9149   SmallVector<MemOpLink, 8> StoreNodes;
9150
9151   // Walk up the chain and look for nodes with offsets from the same
9152   // base pointer. Stop when reaching an instruction with a different kind
9153   // or instruction which has a different base pointer.
9154   unsigned Seq = 0;
9155   StoreSDNode *Index = St;
9156   while (Index) {
9157     // If the chain has more than one use, then we can't reorder the mem ops.
9158     if (Index != St && !SDValue(Index, 0)->hasOneUse())
9159       break;
9160
9161     // Find the base pointer and offset for this memory node.
9162     BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
9163
9164     // Check that the base pointer is the same as the original one.
9165     if (!Ptr.equalBaseIndex(BasePtr))
9166       break;
9167
9168     // Check that the alignment is the same.
9169     if (Index->getAlignment() != St->getAlignment())
9170       break;
9171
9172     // The memory operands must not be volatile.
9173     if (Index->isVolatile() || Index->isIndexed())
9174       break;
9175
9176     // No truncation.
9177     if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
9178       if (St->isTruncatingStore())
9179         break;
9180
9181     // The stored memory type must be the same.
9182     if (Index->getMemoryVT() != MemVT)
9183       break;
9184
9185     // We do not allow unaligned stores because we want to prevent overriding
9186     // stores.
9187     if (Index->getAlignment()*8 != MemVT.getSizeInBits())
9188       break;
9189
9190     // We found a potential memory operand to merge.
9191     StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
9192
9193     // Find the next memory operand in the chain. If the next operand in the
9194     // chain is a store then move up and continue the scan with the next
9195     // memory operand. If the next operand is a load save it and use alias
9196     // information to check if it interferes with anything.
9197     SDNode *NextInChain = Index->getChain().getNode();
9198     while (1) {
9199       if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
9200         // We found a store node. Use it for the next iteration.
9201         Index = STn;
9202         break;
9203       } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
9204         if (Ldn->isVolatile()) {
9205           Index = nullptr;
9206           break;
9207         }
9208
9209         // Save the load node for later. Continue the scan.
9210         AliasLoadNodes.push_back(Ldn);
9211         NextInChain = Ldn->getChain().getNode();
9212         continue;
9213       } else {
9214         Index = nullptr;
9215         break;
9216       }
9217     }
9218   }
9219
9220   // Check if there is anything to merge.
9221   if (StoreNodes.size() < 2)
9222     return false;
9223
9224   // Sort the memory operands according to their distance from the base pointer.
9225   std::sort(StoreNodes.begin(), StoreNodes.end(),
9226             [](MemOpLink LHS, MemOpLink RHS) {
9227     return LHS.OffsetFromBase < RHS.OffsetFromBase ||
9228            (LHS.OffsetFromBase == RHS.OffsetFromBase &&
9229             LHS.SequenceNum > RHS.SequenceNum);
9230   });
9231
9232   // Scan the memory operations on the chain and find the first non-consecutive
9233   // store memory address.
9234   unsigned LastConsecutiveStore = 0;
9235   int64_t StartAddress = StoreNodes[0].OffsetFromBase;
9236   for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
9237
9238     // Check that the addresses are consecutive starting from the second
9239     // element in the list of stores.
9240     if (i > 0) {
9241       int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
9242       if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9243         break;
9244     }
9245
9246     bool Alias = false;
9247     // Check if this store interferes with any of the loads that we found.
9248     for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
9249       if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
9250         Alias = true;
9251         break;
9252       }
9253     // We found a load that alias with this store. Stop the sequence.
9254     if (Alias)
9255       break;
9256
9257     // Mark this node as useful.
9258     LastConsecutiveStore = i;
9259   }
9260
9261   // The node with the lowest store address.
9262   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
9263
9264   // Store the constants into memory as one consecutive store.
9265   if (!IsLoadSrc) {
9266     unsigned LastLegalType = 0;
9267     unsigned LastLegalVectorType = 0;
9268     bool NonZero = false;
9269     for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9270       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
9271       SDValue StoredVal = St->getValue();
9272
9273       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
9274         NonZero |= !C->isNullValue();
9275       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
9276         NonZero |= !C->getConstantFPValue()->isNullValue();
9277       } else {
9278         // Non-constant.
9279         break;
9280       }
9281
9282       // Find a legal type for the constant store.
9283       unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9284       EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9285       if (TLI.isTypeLegal(StoreTy))
9286         LastLegalType = i+1;
9287       // Or check whether a truncstore is legal.
9288       else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9289                TargetLowering::TypePromoteInteger) {
9290         EVT LegalizedStoredValueTy =
9291           TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
9292         if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy))
9293           LastLegalType = i+1;
9294       }
9295
9296       // Find a legal type for the vector store.
9297       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9298       if (TLI.isTypeLegal(Ty))
9299         LastLegalVectorType = i + 1;
9300     }
9301
9302     // We only use vectors if the constant is known to be zero and the
9303     // function is not marked with the noimplicitfloat attribute.
9304     if (NonZero || NoVectors)
9305       LastLegalVectorType = 0;
9306
9307     // Check if we found a legal integer type to store.
9308     if (LastLegalType == 0 && LastLegalVectorType == 0)
9309       return false;
9310
9311     bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
9312     unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
9313
9314     // Make sure we have something to merge.
9315     if (NumElem < 2)
9316       return false;
9317
9318     unsigned EarliestNodeUsed = 0;
9319     for (unsigned i=0; i < NumElem; ++i) {
9320       // Find a chain for the new wide-store operand. Notice that some
9321       // of the store nodes that we found may not be selected for inclusion
9322       // in the wide store. The chain we use needs to be the chain of the
9323       // earliest store node which is *used* and replaced by the wide store.
9324       if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9325         EarliestNodeUsed = i;
9326     }
9327
9328     // The earliest Node in the DAG.
9329     LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9330     SDLoc DL(StoreNodes[0].MemNode);
9331
9332     SDValue StoredVal;
9333     if (UseVector) {
9334       // Find a legal type for the vector store.
9335       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9336       assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
9337       StoredVal = DAG.getConstant(0, Ty);
9338     } else {
9339       unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9340       APInt StoreInt(StoreBW, 0);
9341
9342       // Construct a single integer constant which is made of the smaller
9343       // constant inputs.
9344       bool IsLE = TLI.isLittleEndian();
9345       for (unsigned i = 0; i < NumElem ; ++i) {
9346         unsigned Idx = IsLE ?(NumElem - 1 - i) : i;
9347         StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
9348         SDValue Val = St->getValue();
9349         StoreInt<<=ElementSizeBytes*8;
9350         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
9351           StoreInt|=C->getAPIntValue().zext(StoreBW);
9352         } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
9353           StoreInt|= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
9354         } else {
9355           assert(false && "Invalid constant element type");
9356         }
9357       }
9358
9359       // Create the new Load and Store operations.
9360       EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9361       StoredVal = DAG.getConstant(StoreInt, StoreTy);
9362     }
9363
9364     SDValue NewStore = DAG.getStore(EarliestOp->getChain(), DL, StoredVal,
9365                                     FirstInChain->getBasePtr(),
9366                                     FirstInChain->getPointerInfo(),
9367                                     false, false,
9368                                     FirstInChain->getAlignment());
9369
9370     // Replace the first store with the new store
9371     CombineTo(EarliestOp, NewStore);
9372     // Erase all other stores.
9373     for (unsigned i = 0; i < NumElem ; ++i) {
9374       if (StoreNodes[i].MemNode == EarliestOp)
9375         continue;
9376       StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9377       // ReplaceAllUsesWith will replace all uses that existed when it was
9378       // called, but graph optimizations may cause new ones to appear. For
9379       // example, the case in pr14333 looks like
9380       //
9381       //  St's chain -> St -> another store -> X
9382       //
9383       // And the only difference from St to the other store is the chain.
9384       // When we change it's chain to be St's chain they become identical,
9385       // get CSEed and the net result is that X is now a use of St.
9386       // Since we know that St is redundant, just iterate.
9387       while (!St->use_empty())
9388         DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
9389       deleteAndRecombine(St);
9390     }
9391
9392     return true;
9393   }
9394
9395   // Below we handle the case of multiple consecutive stores that
9396   // come from multiple consecutive loads. We merge them into a single
9397   // wide load and a single wide store.
9398
9399   // Look for load nodes which are used by the stored values.
9400   SmallVector<MemOpLink, 8> LoadNodes;
9401
9402   // Find acceptable loads. Loads need to have the same chain (token factor),
9403   // must not be zext, volatile, indexed, and they must be consecutive.
9404   BaseIndexOffset LdBasePtr;
9405   for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9406     StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
9407     LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
9408     if (!Ld) break;
9409
9410     // Loads must only have one use.
9411     if (!Ld->hasNUsesOfValue(1, 0))
9412       break;
9413
9414     // Check that the alignment is the same as the stores.
9415     if (Ld->getAlignment() != St->getAlignment())
9416       break;
9417
9418     // The memory operands must not be volatile.
9419     if (Ld->isVolatile() || Ld->isIndexed())
9420       break;
9421
9422     // We do not accept ext loads.
9423     if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
9424       break;
9425
9426     // The stored memory type must be the same.
9427     if (Ld->getMemoryVT() != MemVT)
9428       break;
9429
9430     BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
9431     // If this is not the first ptr that we check.
9432     if (LdBasePtr.Base.getNode()) {
9433       // The base ptr must be the same.
9434       if (!LdPtr.equalBaseIndex(LdBasePtr))
9435         break;
9436     } else {
9437       // Check that all other base pointers are the same as this one.
9438       LdBasePtr = LdPtr;
9439     }
9440
9441     // We found a potential memory operand to merge.
9442     LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
9443   }
9444
9445   if (LoadNodes.size() < 2)
9446     return false;
9447
9448   // If we have load/store pair instructions and we only have two values,
9449   // don't bother.
9450   unsigned RequiredAlignment;
9451   if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) &&
9452       St->getAlignment() >= RequiredAlignment)
9453     return false;
9454
9455   // Scan the memory operations on the chain and find the first non-consecutive
9456   // load memory address. These variables hold the index in the store node
9457   // array.
9458   unsigned LastConsecutiveLoad = 0;
9459   // This variable refers to the size and not index in the array.
9460   unsigned LastLegalVectorType = 0;
9461   unsigned LastLegalIntegerType = 0;
9462   StartAddress = LoadNodes[0].OffsetFromBase;
9463   SDValue FirstChain = LoadNodes[0].MemNode->getChain();
9464   for (unsigned i = 1; i < LoadNodes.size(); ++i) {
9465     // All loads much share the same chain.
9466     if (LoadNodes[i].MemNode->getChain() != FirstChain)
9467       break;
9468
9469     int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
9470     if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9471       break;
9472     LastConsecutiveLoad = i;
9473
9474     // Find a legal type for the vector store.
9475     EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9476     if (TLI.isTypeLegal(StoreTy))
9477       LastLegalVectorType = i + 1;
9478
9479     // Find a legal type for the integer store.
9480     unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9481     StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9482     if (TLI.isTypeLegal(StoreTy))
9483       LastLegalIntegerType = i + 1;
9484     // Or check whether a truncstore and extload is legal.
9485     else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9486              TargetLowering::TypePromoteInteger) {
9487       EVT LegalizedStoredValueTy =
9488         TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
9489       if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
9490           TLI.isLoadExtLegal(ISD::ZEXTLOAD, StoreTy) &&
9491           TLI.isLoadExtLegal(ISD::SEXTLOAD, StoreTy) &&
9492           TLI.isLoadExtLegal(ISD::EXTLOAD, StoreTy))
9493         LastLegalIntegerType = i+1;
9494     }
9495   }
9496
9497   // Only use vector types if the vector type is larger than the integer type.
9498   // If they are the same, use integers.
9499   bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
9500   unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
9501
9502   // We add +1 here because the LastXXX variables refer to location while
9503   // the NumElem refers to array/index size.
9504   unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
9505   NumElem = std::min(LastLegalType, NumElem);
9506
9507   if (NumElem < 2)
9508     return false;
9509
9510   // The earliest Node in the DAG.
9511   unsigned EarliestNodeUsed = 0;
9512   LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9513   for (unsigned i=1; i<NumElem; ++i) {
9514     // Find a chain for the new wide-store operand. Notice that some
9515     // of the store nodes that we found may not be selected for inclusion
9516     // in the wide store. The chain we use needs to be the chain of the
9517     // earliest store node which is *used* and replaced by the wide store.
9518     if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9519       EarliestNodeUsed = i;
9520   }
9521
9522   // Find if it is better to use vectors or integers to load and store
9523   // to memory.
9524   EVT JointMemOpVT;
9525   if (UseVectorTy) {
9526     JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9527   } else {
9528     unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9529     JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9530   }
9531
9532   SDLoc LoadDL(LoadNodes[0].MemNode);
9533   SDLoc StoreDL(StoreNodes[0].MemNode);
9534
9535   LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
9536   SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL,
9537                                 FirstLoad->getChain(),
9538                                 FirstLoad->getBasePtr(),
9539                                 FirstLoad->getPointerInfo(),
9540                                 false, false, false,
9541                                 FirstLoad->getAlignment());
9542
9543   SDValue NewStore = DAG.getStore(EarliestOp->getChain(), StoreDL, NewLoad,
9544                                   FirstInChain->getBasePtr(),
9545                                   FirstInChain->getPointerInfo(), false, false,
9546                                   FirstInChain->getAlignment());
9547
9548   // Replace one of the loads with the new load.
9549   LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
9550   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
9551                                 SDValue(NewLoad.getNode(), 1));
9552
9553   // Remove the rest of the load chains.
9554   for (unsigned i = 1; i < NumElem ; ++i) {
9555     // Replace all chain users of the old load nodes with the chain of the new
9556     // load node.
9557     LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
9558     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
9559   }
9560
9561   // Replace the first store with the new store.
9562   CombineTo(EarliestOp, NewStore);
9563   // Erase all other stores.
9564   for (unsigned i = 0; i < NumElem ; ++i) {
9565     // Remove all Store nodes.
9566     if (StoreNodes[i].MemNode == EarliestOp)
9567       continue;
9568     StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9569     DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
9570     deleteAndRecombine(St);
9571   }
9572
9573   return true;
9574 }
9575
9576 SDValue DAGCombiner::visitSTORE(SDNode *N) {
9577   StoreSDNode *ST  = cast<StoreSDNode>(N);
9578   SDValue Chain = ST->getChain();
9579   SDValue Value = ST->getValue();
9580   SDValue Ptr   = ST->getBasePtr();
9581
9582   // If this is a store of a bit convert, store the input value if the
9583   // resultant store does not need a higher alignment than the original.
9584   if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
9585       ST->isUnindexed()) {
9586     unsigned OrigAlign = ST->getAlignment();
9587     EVT SVT = Value.getOperand(0).getValueType();
9588     unsigned Align = TLI.getDataLayout()->
9589       getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
9590     if (Align <= OrigAlign &&
9591         ((!LegalOperations && !ST->isVolatile()) ||
9592          TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
9593       return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
9594                           Ptr, ST->getPointerInfo(), ST->isVolatile(),
9595                           ST->isNonTemporal(), OrigAlign,
9596                           ST->getAAInfo());
9597   }
9598
9599   // Turn 'store undef, Ptr' -> nothing.
9600   if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
9601     return Chain;
9602
9603   // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
9604   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
9605     // NOTE: If the original store is volatile, this transform must not increase
9606     // the number of stores.  For example, on x86-32 an f64 can be stored in one
9607     // processor operation but an i64 (which is not legal) requires two.  So the
9608     // transform should not be done in this case.
9609     if (Value.getOpcode() != ISD::TargetConstantFP) {
9610       SDValue Tmp;
9611       switch (CFP->getSimpleValueType(0).SimpleTy) {
9612       default: llvm_unreachable("Unknown FP type");
9613       case MVT::f16:    // We don't do this for these yet.
9614       case MVT::f80:
9615       case MVT::f128:
9616       case MVT::ppcf128:
9617         break;
9618       case MVT::f32:
9619         if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
9620             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
9621           Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
9622                               bitcastToAPInt().getZExtValue(), MVT::i32);
9623           return DAG.getStore(Chain, SDLoc(N), Tmp,
9624                               Ptr, ST->getMemOperand());
9625         }
9626         break;
9627       case MVT::f64:
9628         if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
9629              !ST->isVolatile()) ||
9630             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
9631           Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
9632                                 getZExtValue(), MVT::i64);
9633           return DAG.getStore(Chain, SDLoc(N), Tmp,
9634                               Ptr, ST->getMemOperand());
9635         }
9636
9637         if (!ST->isVolatile() &&
9638             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
9639           // Many FP stores are not made apparent until after legalize, e.g. for
9640           // argument passing.  Since this is so common, custom legalize the
9641           // 64-bit integer store into two 32-bit stores.
9642           uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
9643           SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
9644           SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
9645           if (TLI.isBigEndian()) std::swap(Lo, Hi);
9646
9647           unsigned Alignment = ST->getAlignment();
9648           bool isVolatile = ST->isVolatile();
9649           bool isNonTemporal = ST->isNonTemporal();
9650           AAMDNodes AAInfo = ST->getAAInfo();
9651
9652           SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
9653                                      Ptr, ST->getPointerInfo(),
9654                                      isVolatile, isNonTemporal,
9655                                      ST->getAlignment(), AAInfo);
9656           Ptr = DAG.getNode(ISD::ADD, SDLoc(N), Ptr.getValueType(), Ptr,
9657                             DAG.getConstant(4, Ptr.getValueType()));
9658           Alignment = MinAlign(Alignment, 4U);
9659           SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
9660                                      Ptr, ST->getPointerInfo().getWithOffset(4),
9661                                      isVolatile, isNonTemporal,
9662                                      Alignment, AAInfo);
9663           return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
9664                              St0, St1);
9665         }
9666
9667         break;
9668       }
9669     }
9670   }
9671
9672   // Try to infer better alignment information than the store already has.
9673   if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
9674     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
9675       if (Align > ST->getAlignment())
9676         return DAG.getTruncStore(Chain, SDLoc(N), Value,
9677                                  Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
9678                                  ST->isVolatile(), ST->isNonTemporal(), Align,
9679                                  ST->getAAInfo());
9680     }
9681   }
9682
9683   // Try transforming a pair floating point load / store ops to integer
9684   // load / store ops.
9685   SDValue NewST = TransformFPLoadStorePair(N);
9686   if (NewST.getNode())
9687     return NewST;
9688
9689   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
9690     TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
9691 #ifndef NDEBUG
9692   if (CombinerAAOnlyFunc.getNumOccurrences() &&
9693       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
9694     UseAA = false;
9695 #endif
9696   if (UseAA && ST->isUnindexed()) {
9697     // Walk up chain skipping non-aliasing memory nodes.
9698     SDValue BetterChain = FindBetterChain(N, Chain);
9699
9700     // If there is a better chain.
9701     if (Chain != BetterChain) {
9702       SDValue ReplStore;
9703
9704       // Replace the chain to avoid dependency.
9705       if (ST->isTruncatingStore()) {
9706         ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
9707                                       ST->getMemoryVT(), ST->getMemOperand());
9708       } else {
9709         ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
9710                                  ST->getMemOperand());
9711       }
9712
9713       // Create token to keep both nodes around.
9714       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
9715                                   MVT::Other, Chain, ReplStore);
9716
9717       // Make sure the new and old chains are cleaned up.
9718       AddToWorklist(Token.getNode());
9719
9720       // Don't add users to work list.
9721       return CombineTo(N, Token, false);
9722     }
9723   }
9724
9725   // Try transforming N to an indexed store.
9726   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
9727     return SDValue(N, 0);
9728
9729   // FIXME: is there such a thing as a truncating indexed store?
9730   if (ST->isTruncatingStore() && ST->isUnindexed() &&
9731       Value.getValueType().isInteger()) {
9732     // See if we can simplify the input to this truncstore with knowledge that
9733     // only the low bits are being used.  For example:
9734     // "truncstore (or (shl x, 8), y), i8"  -> "truncstore y, i8"
9735     SDValue Shorter =
9736       GetDemandedBits(Value,
9737                       APInt::getLowBitsSet(
9738                         Value.getValueType().getScalarType().getSizeInBits(),
9739                         ST->getMemoryVT().getScalarType().getSizeInBits()));
9740     AddToWorklist(Value.getNode());
9741     if (Shorter.getNode())
9742       return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
9743                                Ptr, ST->getMemoryVT(), ST->getMemOperand());
9744
9745     // Otherwise, see if we can simplify the operation with
9746     // SimplifyDemandedBits, which only works if the value has a single use.
9747     if (SimplifyDemandedBits(Value,
9748                         APInt::getLowBitsSet(
9749                           Value.getValueType().getScalarType().getSizeInBits(),
9750                           ST->getMemoryVT().getScalarType().getSizeInBits())))
9751       return SDValue(N, 0);
9752   }
9753
9754   // If this is a load followed by a store to the same location, then the store
9755   // is dead/noop.
9756   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
9757     if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
9758         ST->isUnindexed() && !ST->isVolatile() &&
9759         // There can't be any side effects between the load and store, such as
9760         // a call or store.
9761         Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
9762       // The store is dead, remove it.
9763       return Chain;
9764     }
9765   }
9766
9767   // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
9768   // truncating store.  We can do this even if this is already a truncstore.
9769   if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
9770       && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
9771       TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
9772                             ST->getMemoryVT())) {
9773     return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
9774                              Ptr, ST->getMemoryVT(), ST->getMemOperand());
9775   }
9776
9777   // Only perform this optimization before the types are legal, because we
9778   // don't want to perform this optimization on every DAGCombine invocation.
9779   if (!LegalTypes) {
9780     bool EverChanged = false;
9781
9782     do {
9783       // There can be multiple store sequences on the same chain.
9784       // Keep trying to merge store sequences until we are unable to do so
9785       // or until we merge the last store on the chain.
9786       bool Changed = MergeConsecutiveStores(ST);
9787       EverChanged |= Changed;
9788       if (!Changed) break;
9789     } while (ST->getOpcode() != ISD::DELETED_NODE);
9790
9791     if (EverChanged)
9792       return SDValue(N, 0);
9793   }
9794
9795   return ReduceLoadOpStoreWidth(N);
9796 }
9797
9798 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
9799   SDValue InVec = N->getOperand(0);
9800   SDValue InVal = N->getOperand(1);
9801   SDValue EltNo = N->getOperand(2);
9802   SDLoc dl(N);
9803
9804   // If the inserted element is an UNDEF, just use the input vector.
9805   if (InVal.getOpcode() == ISD::UNDEF)
9806     return InVec;
9807
9808   EVT VT = InVec.getValueType();
9809
9810   // If we can't generate a legal BUILD_VECTOR, exit
9811   if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
9812     return SDValue();
9813
9814   // Check that we know which element is being inserted
9815   if (!isa<ConstantSDNode>(EltNo))
9816     return SDValue();
9817   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9818
9819   // Canonicalize insert_vector_elt dag nodes.
9820   // Example:
9821   // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
9822   // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
9823   //
9824   // Do this only if the child insert_vector node has one use; also
9825   // do this only if indices are both constants and Idx1 < Idx0.
9826   if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
9827       && isa<ConstantSDNode>(InVec.getOperand(2))) {
9828     unsigned OtherElt =
9829       cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue();
9830     if (Elt < OtherElt) {
9831       // Swap nodes.
9832       SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT,
9833                                   InVec.getOperand(0), InVal, EltNo);
9834       AddToWorklist(NewOp.getNode());
9835       return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
9836                          VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
9837     }
9838   }
9839
9840   // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
9841   // be converted to a BUILD_VECTOR).  Fill in the Ops vector with the
9842   // vector elements.
9843   SmallVector<SDValue, 8> Ops;
9844   // Do not combine these two vectors if the output vector will not replace
9845   // the input vector.
9846   if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
9847     Ops.append(InVec.getNode()->op_begin(),
9848                InVec.getNode()->op_end());
9849   } else if (InVec.getOpcode() == ISD::UNDEF) {
9850     unsigned NElts = VT.getVectorNumElements();
9851     Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
9852   } else {
9853     return SDValue();
9854   }
9855
9856   // Insert the element
9857   if (Elt < Ops.size()) {
9858     // All the operands of BUILD_VECTOR must have the same type;
9859     // we enforce that here.
9860     EVT OpVT = Ops[0].getValueType();
9861     if (InVal.getValueType() != OpVT)
9862       InVal = OpVT.bitsGT(InVal.getValueType()) ?
9863                 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
9864                 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
9865     Ops[Elt] = InVal;
9866   }
9867
9868   // Return the new vector
9869   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
9870 }
9871
9872 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
9873     SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) {
9874   EVT ResultVT = EVE->getValueType(0);
9875   EVT VecEltVT = InVecVT.getVectorElementType();
9876   unsigned Align = OriginalLoad->getAlignment();
9877   unsigned NewAlign = TLI.getDataLayout()->getABITypeAlignment(
9878       VecEltVT.getTypeForEVT(*DAG.getContext()));
9879
9880   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
9881     return SDValue();
9882
9883   Align = NewAlign;
9884
9885   SDValue NewPtr = OriginalLoad->getBasePtr();
9886   SDValue Offset;
9887   EVT PtrType = NewPtr.getValueType();
9888   MachinePointerInfo MPI;
9889   if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
9890     int Elt = ConstEltNo->getZExtValue();
9891     unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
9892     if (TLI.isBigEndian())
9893       PtrOff = InVecVT.getSizeInBits() / 8 - PtrOff;
9894     Offset = DAG.getConstant(PtrOff, PtrType);
9895     MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
9896   } else {
9897     Offset = DAG.getNode(
9898         ISD::MUL, SDLoc(EVE), EltNo.getValueType(), EltNo,
9899         DAG.getConstant(VecEltVT.getStoreSize(), EltNo.getValueType()));
9900     if (TLI.isBigEndian())
9901       Offset = DAG.getNode(
9902           ISD::SUB, SDLoc(EVE), EltNo.getValueType(),
9903           DAG.getConstant(InVecVT.getStoreSize(), EltNo.getValueType()), Offset);
9904     MPI = OriginalLoad->getPointerInfo();
9905   }
9906   NewPtr = DAG.getNode(ISD::ADD, SDLoc(EVE), PtrType, NewPtr, Offset);
9907
9908   // The replacement we need to do here is a little tricky: we need to
9909   // replace an extractelement of a load with a load.
9910   // Use ReplaceAllUsesOfValuesWith to do the replacement.
9911   // Note that this replacement assumes that the extractvalue is the only
9912   // use of the load; that's okay because we don't want to perform this
9913   // transformation in other cases anyway.
9914   SDValue Load;
9915   SDValue Chain;
9916   if (ResultVT.bitsGT(VecEltVT)) {
9917     // If the result type of vextract is wider than the load, then issue an
9918     // extending load instead.
9919     ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, VecEltVT)
9920                                    ? ISD::ZEXTLOAD
9921                                    : ISD::EXTLOAD;
9922     Load = DAG.getExtLoad(
9923         ExtType, SDLoc(EVE), ResultVT, OriginalLoad->getChain(), NewPtr, MPI,
9924         VecEltVT, OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
9925         OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
9926     Chain = Load.getValue(1);
9927   } else {
9928     Load = DAG.getLoad(
9929         VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, MPI,
9930         OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
9931         OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
9932     Chain = Load.getValue(1);
9933     if (ResultVT.bitsLT(VecEltVT))
9934       Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
9935     else
9936       Load = DAG.getNode(ISD::BITCAST, SDLoc(EVE), ResultVT, Load);
9937   }
9938   WorklistRemover DeadNodes(*this);
9939   SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
9940   SDValue To[] = { Load, Chain };
9941   DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
9942   // Since we're explicitly calling ReplaceAllUses, add the new node to the
9943   // worklist explicitly as well.
9944   AddToWorklist(Load.getNode());
9945   AddUsersToWorklist(Load.getNode()); // Add users too
9946   // Make sure to revisit this node to clean it up; it will usually be dead.
9947   AddToWorklist(EVE);
9948   ++OpsNarrowed;
9949   return SDValue(EVE, 0);
9950 }
9951
9952 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
9953   // (vextract (scalar_to_vector val, 0) -> val
9954   SDValue InVec = N->getOperand(0);
9955   EVT VT = InVec.getValueType();
9956   EVT NVT = N->getValueType(0);
9957
9958   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
9959     // Check if the result type doesn't match the inserted element type. A
9960     // SCALAR_TO_VECTOR may truncate the inserted element and the
9961     // EXTRACT_VECTOR_ELT may widen the extracted vector.
9962     SDValue InOp = InVec.getOperand(0);
9963     if (InOp.getValueType() != NVT) {
9964       assert(InOp.getValueType().isInteger() && NVT.isInteger());
9965       return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
9966     }
9967     return InOp;
9968   }
9969
9970   SDValue EltNo = N->getOperand(1);
9971   bool ConstEltNo = isa<ConstantSDNode>(EltNo);
9972
9973   // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
9974   // We only perform this optimization before the op legalization phase because
9975   // we may introduce new vector instructions which are not backed by TD
9976   // patterns. For example on AVX, extracting elements from a wide vector
9977   // without using extract_subvector. However, if we can find an underlying
9978   // scalar value, then we can always use that.
9979   if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
9980       && ConstEltNo) {
9981     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9982     int NumElem = VT.getVectorNumElements();
9983     ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
9984     // Find the new index to extract from.
9985     int OrigElt = SVOp->getMaskElt(Elt);
9986
9987     // Extracting an undef index is undef.
9988     if (OrigElt == -1)
9989       return DAG.getUNDEF(NVT);
9990
9991     // Select the right vector half to extract from.
9992     SDValue SVInVec;
9993     if (OrigElt < NumElem) {
9994       SVInVec = InVec->getOperand(0);
9995     } else {
9996       SVInVec = InVec->getOperand(1);
9997       OrigElt -= NumElem;
9998     }
9999
10000     if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
10001       SDValue InOp = SVInVec.getOperand(OrigElt);
10002       if (InOp.getValueType() != NVT) {
10003         assert(InOp.getValueType().isInteger() && NVT.isInteger());
10004         InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
10005       }
10006
10007       return InOp;
10008     }
10009
10010     // FIXME: We should handle recursing on other vector shuffles and
10011     // scalar_to_vector here as well.
10012
10013     if (!LegalOperations) {
10014       EVT IndexTy = TLI.getVectorIdxTy();
10015       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT,
10016                          SVInVec, DAG.getConstant(OrigElt, IndexTy));
10017     }
10018   }
10019
10020   bool BCNumEltsChanged = false;
10021   EVT ExtVT = VT.getVectorElementType();
10022   EVT LVT = ExtVT;
10023
10024   // If the result of load has to be truncated, then it's not necessarily
10025   // profitable.
10026   if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
10027     return SDValue();
10028
10029   if (InVec.getOpcode() == ISD::BITCAST) {
10030     // Don't duplicate a load with other uses.
10031     if (!InVec.hasOneUse())
10032       return SDValue();
10033
10034     EVT BCVT = InVec.getOperand(0).getValueType();
10035     if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
10036       return SDValue();
10037     if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
10038       BCNumEltsChanged = true;
10039     InVec = InVec.getOperand(0);
10040     ExtVT = BCVT.getVectorElementType();
10041   }
10042
10043   // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size)
10044   if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() &&
10045       ISD::isNormalLoad(InVec.getNode()) &&
10046       !N->getOperand(1)->hasPredecessor(InVec.getNode())) {
10047     SDValue Index = N->getOperand(1);
10048     if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec))
10049       return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index,
10050                                                            OrigLoad);
10051   }
10052
10053   // Perform only after legalization to ensure build_vector / vector_shuffle
10054   // optimizations have already been done.
10055   if (!LegalOperations) return SDValue();
10056
10057   // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
10058   // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
10059   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
10060
10061   if (ConstEltNo) {
10062     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
10063
10064     LoadSDNode *LN0 = nullptr;
10065     const ShuffleVectorSDNode *SVN = nullptr;
10066     if (ISD::isNormalLoad(InVec.getNode())) {
10067       LN0 = cast<LoadSDNode>(InVec);
10068     } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
10069                InVec.getOperand(0).getValueType() == ExtVT &&
10070                ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
10071       // Don't duplicate a load with other uses.
10072       if (!InVec.hasOneUse())
10073         return SDValue();
10074
10075       LN0 = cast<LoadSDNode>(InVec.getOperand(0));
10076     } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
10077       // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
10078       // =>
10079       // (load $addr+1*size)
10080
10081       // Don't duplicate a load with other uses.
10082       if (!InVec.hasOneUse())
10083         return SDValue();
10084
10085       // If the bit convert changed the number of elements, it is unsafe
10086       // to examine the mask.
10087       if (BCNumEltsChanged)
10088         return SDValue();
10089
10090       // Select the input vector, guarding against out of range extract vector.
10091       unsigned NumElems = VT.getVectorNumElements();
10092       int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
10093       InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
10094
10095       if (InVec.getOpcode() == ISD::BITCAST) {
10096         // Don't duplicate a load with other uses.
10097         if (!InVec.hasOneUse())
10098           return SDValue();
10099
10100         InVec = InVec.getOperand(0);
10101       }
10102       if (ISD::isNormalLoad(InVec.getNode())) {
10103         LN0 = cast<LoadSDNode>(InVec);
10104         Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
10105         EltNo = DAG.getConstant(Elt, EltNo.getValueType());
10106       }
10107     }
10108
10109     // Make sure we found a non-volatile load and the extractelement is
10110     // the only use.
10111     if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
10112       return SDValue();
10113
10114     // If Idx was -1 above, Elt is going to be -1, so just return undef.
10115     if (Elt == -1)
10116       return DAG.getUNDEF(LVT);
10117
10118     return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0);
10119   }
10120
10121   return SDValue();
10122 }
10123
10124 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
10125 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
10126   // We perform this optimization post type-legalization because
10127   // the type-legalizer often scalarizes integer-promoted vectors.
10128   // Performing this optimization before may create bit-casts which
10129   // will be type-legalized to complex code sequences.
10130   // We perform this optimization only before the operation legalizer because we
10131   // may introduce illegal operations.
10132   if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
10133     return SDValue();
10134
10135   unsigned NumInScalars = N->getNumOperands();
10136   SDLoc dl(N);
10137   EVT VT = N->getValueType(0);
10138
10139   // Check to see if this is a BUILD_VECTOR of a bunch of values
10140   // which come from any_extend or zero_extend nodes. If so, we can create
10141   // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
10142   // optimizations. We do not handle sign-extend because we can't fill the sign
10143   // using shuffles.
10144   EVT SourceType = MVT::Other;
10145   bool AllAnyExt = true;
10146
10147   for (unsigned i = 0; i != NumInScalars; ++i) {
10148     SDValue In = N->getOperand(i);
10149     // Ignore undef inputs.
10150     if (In.getOpcode() == ISD::UNDEF) continue;
10151
10152     bool AnyExt  = In.getOpcode() == ISD::ANY_EXTEND;
10153     bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
10154
10155     // Abort if the element is not an extension.
10156     if (!ZeroExt && !AnyExt) {
10157       SourceType = MVT::Other;
10158       break;
10159     }
10160
10161     // The input is a ZeroExt or AnyExt. Check the original type.
10162     EVT InTy = In.getOperand(0).getValueType();
10163
10164     // Check that all of the widened source types are the same.
10165     if (SourceType == MVT::Other)
10166       // First time.
10167       SourceType = InTy;
10168     else if (InTy != SourceType) {
10169       // Multiple income types. Abort.
10170       SourceType = MVT::Other;
10171       break;
10172     }
10173
10174     // Check if all of the extends are ANY_EXTENDs.
10175     AllAnyExt &= AnyExt;
10176   }
10177
10178   // In order to have valid types, all of the inputs must be extended from the
10179   // same source type and all of the inputs must be any or zero extend.
10180   // Scalar sizes must be a power of two.
10181   EVT OutScalarTy = VT.getScalarType();
10182   bool ValidTypes = SourceType != MVT::Other &&
10183                  isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
10184                  isPowerOf2_32(SourceType.getSizeInBits());
10185
10186   // Create a new simpler BUILD_VECTOR sequence which other optimizations can
10187   // turn into a single shuffle instruction.
10188   if (!ValidTypes)
10189     return SDValue();
10190
10191   bool isLE = TLI.isLittleEndian();
10192   unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
10193   assert(ElemRatio > 1 && "Invalid element size ratio");
10194   SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
10195                                DAG.getConstant(0, SourceType);
10196
10197   unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
10198   SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
10199
10200   // Populate the new build_vector
10201   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
10202     SDValue Cast = N->getOperand(i);
10203     assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
10204             Cast.getOpcode() == ISD::ZERO_EXTEND ||
10205             Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
10206     SDValue In;
10207     if (Cast.getOpcode() == ISD::UNDEF)
10208       In = DAG.getUNDEF(SourceType);
10209     else
10210       In = Cast->getOperand(0);
10211     unsigned Index = isLE ? (i * ElemRatio) :
10212                             (i * ElemRatio + (ElemRatio - 1));
10213
10214     assert(Index < Ops.size() && "Invalid index");
10215     Ops[Index] = In;
10216   }
10217
10218   // The type of the new BUILD_VECTOR node.
10219   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
10220   assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
10221          "Invalid vector size");
10222   // Check if the new vector type is legal.
10223   if (!isTypeLegal(VecVT)) return SDValue();
10224
10225   // Make the new BUILD_VECTOR.
10226   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
10227
10228   // The new BUILD_VECTOR node has the potential to be further optimized.
10229   AddToWorklist(BV.getNode());
10230   // Bitcast to the desired type.
10231   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
10232 }
10233
10234 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
10235   EVT VT = N->getValueType(0);
10236
10237   unsigned NumInScalars = N->getNumOperands();
10238   SDLoc dl(N);
10239
10240   EVT SrcVT = MVT::Other;
10241   unsigned Opcode = ISD::DELETED_NODE;
10242   unsigned NumDefs = 0;
10243
10244   for (unsigned i = 0; i != NumInScalars; ++i) {
10245     SDValue In = N->getOperand(i);
10246     unsigned Opc = In.getOpcode();
10247
10248     if (Opc == ISD::UNDEF)
10249       continue;
10250
10251     // If all scalar values are floats and converted from integers.
10252     if (Opcode == ISD::DELETED_NODE &&
10253         (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
10254       Opcode = Opc;
10255     }
10256
10257     if (Opc != Opcode)
10258       return SDValue();
10259
10260     EVT InVT = In.getOperand(0).getValueType();
10261
10262     // If all scalar values are typed differently, bail out. It's chosen to
10263     // simplify BUILD_VECTOR of integer types.
10264     if (SrcVT == MVT::Other)
10265       SrcVT = InVT;
10266     if (SrcVT != InVT)
10267       return SDValue();
10268     NumDefs++;
10269   }
10270
10271   // If the vector has just one element defined, it's not worth to fold it into
10272   // a vectorized one.
10273   if (NumDefs < 2)
10274     return SDValue();
10275
10276   assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
10277          && "Should only handle conversion from integer to float.");
10278   assert(SrcVT != MVT::Other && "Cannot determine source type!");
10279
10280   EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
10281
10282   if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
10283     return SDValue();
10284
10285   SmallVector<SDValue, 8> Opnds;
10286   for (unsigned i = 0; i != NumInScalars; ++i) {
10287     SDValue In = N->getOperand(i);
10288
10289     if (In.getOpcode() == ISD::UNDEF)
10290       Opnds.push_back(DAG.getUNDEF(SrcVT));
10291     else
10292       Opnds.push_back(In.getOperand(0));
10293   }
10294   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds);
10295   AddToWorklist(BV.getNode());
10296
10297   return DAG.getNode(Opcode, dl, VT, BV);
10298 }
10299
10300 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
10301   unsigned NumInScalars = N->getNumOperands();
10302   SDLoc dl(N);
10303   EVT VT = N->getValueType(0);
10304
10305   // A vector built entirely of undefs is undef.
10306   if (ISD::allOperandsUndef(N))
10307     return DAG.getUNDEF(VT);
10308
10309   SDValue V = reduceBuildVecExtToExtBuildVec(N);
10310   if (V.getNode())
10311     return V;
10312
10313   V = reduceBuildVecConvertToConvertBuildVec(N);
10314   if (V.getNode())
10315     return V;
10316
10317   // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
10318   // operations.  If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
10319   // at most two distinct vectors, turn this into a shuffle node.
10320
10321   // May only combine to shuffle after legalize if shuffle is legal.
10322   if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT))
10323     return SDValue();
10324
10325   SDValue VecIn1, VecIn2;
10326   for (unsigned i = 0; i != NumInScalars; ++i) {
10327     // Ignore undef inputs.
10328     if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
10329
10330     // If this input is something other than a EXTRACT_VECTOR_ELT with a
10331     // constant index, bail out.
10332     if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10333         !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) {
10334       VecIn1 = VecIn2 = SDValue(nullptr, 0);
10335       break;
10336     }
10337
10338     // We allow up to two distinct input vectors.
10339     SDValue ExtractedFromVec = N->getOperand(i).getOperand(0);
10340     if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
10341       continue;
10342
10343     if (!VecIn1.getNode()) {
10344       VecIn1 = ExtractedFromVec;
10345     } else if (!VecIn2.getNode()) {
10346       VecIn2 = ExtractedFromVec;
10347     } else {
10348       // Too many inputs.
10349       VecIn1 = VecIn2 = SDValue(nullptr, 0);
10350       break;
10351     }
10352   }
10353
10354   // If everything is good, we can make a shuffle operation.
10355   if (VecIn1.getNode()) {
10356     SmallVector<int, 8> Mask;
10357     for (unsigned i = 0; i != NumInScalars; ++i) {
10358       if (N->getOperand(i).getOpcode() == ISD::UNDEF) {
10359         Mask.push_back(-1);
10360         continue;
10361       }
10362
10363       // If extracting from the first vector, just use the index directly.
10364       SDValue Extract = N->getOperand(i);
10365       SDValue ExtVal = Extract.getOperand(1);
10366       if (Extract.getOperand(0) == VecIn1) {
10367         unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
10368         if (ExtIndex > VT.getVectorNumElements())
10369           return SDValue();
10370
10371         Mask.push_back(ExtIndex);
10372         continue;
10373       }
10374
10375       // Otherwise, use InIdx + VecSize
10376       unsigned Idx = cast<ConstantSDNode>(ExtVal)->getZExtValue();
10377       Mask.push_back(Idx+NumInScalars);
10378     }
10379
10380     // We can't generate a shuffle node with mismatched input and output types.
10381     // Attempt to transform a single input vector to the correct type.
10382     if ((VT != VecIn1.getValueType())) {
10383       // We don't support shuffeling between TWO values of different types.
10384       if (VecIn2.getNode())
10385         return SDValue();
10386
10387       // We only support widening of vectors which are half the size of the
10388       // output registers. For example XMM->YMM widening on X86 with AVX.
10389       if (VecIn1.getValueType().getSizeInBits()*2 != VT.getSizeInBits())
10390         return SDValue();
10391
10392       // If the input vector type has a different base type to the output
10393       // vector type, bail out.
10394       if (VecIn1.getValueType().getVectorElementType() !=
10395           VT.getVectorElementType())
10396         return SDValue();
10397
10398       // Widen the input vector by adding undef values.
10399       VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10400                            VecIn1, DAG.getUNDEF(VecIn1.getValueType()));
10401     }
10402
10403     // If VecIn2 is unused then change it to undef.
10404     VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
10405
10406     // Check that we were able to transform all incoming values to the same
10407     // type.
10408     if (VecIn2.getValueType() != VecIn1.getValueType() ||
10409         VecIn1.getValueType() != VT)
10410           return SDValue();
10411
10412     // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
10413     if (!isTypeLegal(VT))
10414       return SDValue();
10415
10416     // Return the new VECTOR_SHUFFLE node.
10417     SDValue Ops[2];
10418     Ops[0] = VecIn1;
10419     Ops[1] = VecIn2;
10420     return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
10421   }
10422
10423   return SDValue();
10424 }
10425
10426 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
10427   // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
10428   // EXTRACT_SUBVECTOR operations.  If so, and if the EXTRACT_SUBVECTOR vector
10429   // inputs come from at most two distinct vectors, turn this into a shuffle
10430   // node.
10431
10432   // If we only have one input vector, we don't need to do any concatenation.
10433   if (N->getNumOperands() == 1)
10434     return N->getOperand(0);
10435
10436   // Check if all of the operands are undefs.
10437   EVT VT = N->getValueType(0);
10438   if (ISD::allOperandsUndef(N))
10439     return DAG.getUNDEF(VT);
10440
10441   // Optimize concat_vectors where one of the vectors is undef.
10442   if (N->getNumOperands() == 2 &&
10443       N->getOperand(1)->getOpcode() == ISD::UNDEF) {
10444     SDValue In = N->getOperand(0);
10445     assert(In.getValueType().isVector() && "Must concat vectors");
10446
10447     // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
10448     if (In->getOpcode() == ISD::BITCAST &&
10449         !In->getOperand(0)->getValueType(0).isVector()) {
10450       SDValue Scalar = In->getOperand(0);
10451       EVT SclTy = Scalar->getValueType(0);
10452
10453       if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
10454         return SDValue();
10455
10456       EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
10457                                  VT.getSizeInBits() / SclTy.getSizeInBits());
10458       if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
10459         return SDValue();
10460
10461       SDLoc dl = SDLoc(N);
10462       SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
10463       return DAG.getNode(ISD::BITCAST, dl, VT, Res);
10464     }
10465   }
10466
10467   // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
10468   // -> (BUILD_VECTOR A, B, ..., C, D, ...)
10469   if (N->getNumOperands() == 2 &&
10470       N->getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
10471       N->getOperand(1).getOpcode() == ISD::BUILD_VECTOR) {
10472     EVT VT = N->getValueType(0);
10473     SDValue N0 = N->getOperand(0);
10474     SDValue N1 = N->getOperand(1);
10475     SmallVector<SDValue, 8> Opnds;
10476     unsigned BuildVecNumElts =  N0.getNumOperands();
10477
10478     EVT SclTy0 = N0.getOperand(0)->getValueType(0);
10479     EVT SclTy1 = N1.getOperand(0)->getValueType(0);
10480     if (SclTy0.isFloatingPoint()) {
10481       for (unsigned i = 0; i != BuildVecNumElts; ++i)
10482         Opnds.push_back(N0.getOperand(i));
10483       for (unsigned i = 0; i != BuildVecNumElts; ++i)
10484         Opnds.push_back(N1.getOperand(i));
10485     } else {
10486       // If BUILD_VECTOR are from built from integer, they may have different
10487       // operand types. Get the smaller type and truncate all operands to it.
10488       EVT MinTy = SclTy0.bitsLE(SclTy1) ? SclTy0 : SclTy1;
10489       for (unsigned i = 0; i != BuildVecNumElts; ++i)
10490         Opnds.push_back(DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinTy,
10491                         N0.getOperand(i)));
10492       for (unsigned i = 0; i != BuildVecNumElts; ++i)
10493         Opnds.push_back(DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinTy,
10494                         N1.getOperand(i)));
10495     }
10496
10497     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
10498   }
10499
10500   // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
10501   // nodes often generate nop CONCAT_VECTOR nodes.
10502   // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
10503   // place the incoming vectors at the exact same location.
10504   SDValue SingleSource = SDValue();
10505   unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
10506
10507   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
10508     SDValue Op = N->getOperand(i);
10509
10510     if (Op.getOpcode() == ISD::UNDEF)
10511       continue;
10512
10513     // Check if this is the identity extract:
10514     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
10515       return SDValue();
10516
10517     // Find the single incoming vector for the extract_subvector.
10518     if (SingleSource.getNode()) {
10519       if (Op.getOperand(0) != SingleSource)
10520         return SDValue();
10521     } else {
10522       SingleSource = Op.getOperand(0);
10523
10524       // Check the source type is the same as the type of the result.
10525       // If not, this concat may extend the vector, so we can not
10526       // optimize it away.
10527       if (SingleSource.getValueType() != N->getValueType(0))
10528         return SDValue();
10529     }
10530
10531     unsigned IdentityIndex = i * PartNumElem;
10532     ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
10533     // The extract index must be constant.
10534     if (!CS)
10535       return SDValue();
10536
10537     // Check that we are reading from the identity index.
10538     if (CS->getZExtValue() != IdentityIndex)
10539       return SDValue();
10540   }
10541
10542   if (SingleSource.getNode())
10543     return SingleSource;
10544
10545   return SDValue();
10546 }
10547
10548 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
10549   EVT NVT = N->getValueType(0);
10550   SDValue V = N->getOperand(0);
10551
10552   if (V->getOpcode() == ISD::CONCAT_VECTORS) {
10553     // Combine:
10554     //    (extract_subvec (concat V1, V2, ...), i)
10555     // Into:
10556     //    Vi if possible
10557     // Only operand 0 is checked as 'concat' assumes all inputs of the same
10558     // type.
10559     if (V->getOperand(0).getValueType() != NVT)
10560       return SDValue();
10561     unsigned Idx = dyn_cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
10562     unsigned NumElems = NVT.getVectorNumElements();
10563     assert((Idx % NumElems) == 0 &&
10564            "IDX in concat is not a multiple of the result vector length.");
10565     return V->getOperand(Idx / NumElems);
10566   }
10567
10568   // Skip bitcasting
10569   if (V->getOpcode() == ISD::BITCAST)
10570     V = V.getOperand(0);
10571
10572   if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
10573     SDLoc dl(N);
10574     // Handle only simple case where vector being inserted and vector
10575     // being extracted are of same type, and are half size of larger vectors.
10576     EVT BigVT = V->getOperand(0).getValueType();
10577     EVT SmallVT = V->getOperand(1).getValueType();
10578     if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
10579       return SDValue();
10580
10581     // Only handle cases where both indexes are constants with the same type.
10582     ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
10583     ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
10584
10585     if (InsIdx && ExtIdx &&
10586         InsIdx->getValueType(0).getSizeInBits() <= 64 &&
10587         ExtIdx->getValueType(0).getSizeInBits() <= 64) {
10588       // Combine:
10589       //    (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
10590       // Into:
10591       //    indices are equal or bit offsets are equal => V1
10592       //    otherwise => (extract_subvec V1, ExtIdx)
10593       if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
10594           ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
10595         return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
10596       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
10597                          DAG.getNode(ISD::BITCAST, dl,
10598                                      N->getOperand(0).getValueType(),
10599                                      V->getOperand(0)), N->getOperand(1));
10600     }
10601   }
10602
10603   return SDValue();
10604 }
10605
10606 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat.
10607 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
10608   EVT VT = N->getValueType(0);
10609   unsigned NumElts = VT.getVectorNumElements();
10610
10611   SDValue N0 = N->getOperand(0);
10612   SDValue N1 = N->getOperand(1);
10613   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10614
10615   SmallVector<SDValue, 4> Ops;
10616   EVT ConcatVT = N0.getOperand(0).getValueType();
10617   unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
10618   unsigned NumConcats = NumElts / NumElemsPerConcat;
10619
10620   // Look at every vector that's inserted. We're looking for exact
10621   // subvector-sized copies from a concatenated vector
10622   for (unsigned I = 0; I != NumConcats; ++I) {
10623     // Make sure we're dealing with a copy.
10624     unsigned Begin = I * NumElemsPerConcat;
10625     bool AllUndef = true, NoUndef = true;
10626     for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
10627       if (SVN->getMaskElt(J) >= 0)
10628         AllUndef = false;
10629       else
10630         NoUndef = false;
10631     }
10632
10633     if (NoUndef) {
10634       if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
10635         return SDValue();
10636
10637       for (unsigned J = 1; J != NumElemsPerConcat; ++J)
10638         if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
10639           return SDValue();
10640
10641       unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
10642       if (FirstElt < N0.getNumOperands())
10643         Ops.push_back(N0.getOperand(FirstElt));
10644       else
10645         Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
10646
10647     } else if (AllUndef) {
10648       Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
10649     } else { // Mixed with general masks and undefs, can't do optimization.
10650       return SDValue();
10651     }
10652   }
10653
10654   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
10655 }
10656
10657 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
10658   EVT VT = N->getValueType(0);
10659   unsigned NumElts = VT.getVectorNumElements();
10660
10661   SDValue N0 = N->getOperand(0);
10662   SDValue N1 = N->getOperand(1);
10663
10664   assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
10665
10666   // Canonicalize shuffle undef, undef -> undef
10667   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
10668     return DAG.getUNDEF(VT);
10669
10670   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10671
10672   // Canonicalize shuffle v, v -> v, undef
10673   if (N0 == N1) {
10674     SmallVector<int, 8> NewMask;
10675     for (unsigned i = 0; i != NumElts; ++i) {
10676       int Idx = SVN->getMaskElt(i);
10677       if (Idx >= (int)NumElts) Idx -= NumElts;
10678       NewMask.push_back(Idx);
10679     }
10680     return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
10681                                 &NewMask[0]);
10682   }
10683
10684   // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
10685   if (N0.getOpcode() == ISD::UNDEF) {
10686     SmallVector<int, 8> NewMask;
10687     for (unsigned i = 0; i != NumElts; ++i) {
10688       int Idx = SVN->getMaskElt(i);
10689       if (Idx >= 0) {
10690         if (Idx >= (int)NumElts)
10691           Idx -= NumElts;
10692         else
10693           Idx = -1; // remove reference to lhs
10694       }
10695       NewMask.push_back(Idx);
10696     }
10697     return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
10698                                 &NewMask[0]);
10699   }
10700
10701   // Remove references to rhs if it is undef
10702   if (N1.getOpcode() == ISD::UNDEF) {
10703     bool Changed = false;
10704     SmallVector<int, 8> NewMask;
10705     for (unsigned i = 0; i != NumElts; ++i) {
10706       int Idx = SVN->getMaskElt(i);
10707       if (Idx >= (int)NumElts) {
10708         Idx = -1;
10709         Changed = true;
10710       }
10711       NewMask.push_back(Idx);
10712     }
10713     if (Changed)
10714       return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
10715   }
10716
10717   // If it is a splat, check if the argument vector is another splat or a
10718   // build_vector with all scalar elements the same.
10719   if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
10720     SDNode *V = N0.getNode();
10721
10722     // If this is a bit convert that changes the element type of the vector but
10723     // not the number of vector elements, look through it.  Be careful not to
10724     // look though conversions that change things like v4f32 to v2f64.
10725     if (V->getOpcode() == ISD::BITCAST) {
10726       SDValue ConvInput = V->getOperand(0);
10727       if (ConvInput.getValueType().isVector() &&
10728           ConvInput.getValueType().getVectorNumElements() == NumElts)
10729         V = ConvInput.getNode();
10730     }
10731
10732     if (V->getOpcode() == ISD::BUILD_VECTOR) {
10733       assert(V->getNumOperands() == NumElts &&
10734              "BUILD_VECTOR has wrong number of operands");
10735       SDValue Base;
10736       bool AllSame = true;
10737       for (unsigned i = 0; i != NumElts; ++i) {
10738         if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
10739           Base = V->getOperand(i);
10740           break;
10741         }
10742       }
10743       // Splat of <u, u, u, u>, return <u, u, u, u>
10744       if (!Base.getNode())
10745         return N0;
10746       for (unsigned i = 0; i != NumElts; ++i) {
10747         if (V->getOperand(i) != Base) {
10748           AllSame = false;
10749           break;
10750         }
10751       }
10752       // Splat of <x, x, x, x>, return <x, x, x, x>
10753       if (AllSame)
10754         return N0;
10755     }
10756   }
10757
10758   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
10759       Level < AfterLegalizeVectorOps &&
10760       (N1.getOpcode() == ISD::UNDEF ||
10761       (N1.getOpcode() == ISD::CONCAT_VECTORS &&
10762        N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
10763     SDValue V = partitionShuffleOfConcats(N, DAG);
10764
10765     if (V.getNode())
10766       return V;
10767   }
10768
10769   // If this shuffle node is simply a swizzle of another shuffle node,
10770   // then try to simplify it.
10771   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
10772       N1.getOpcode() == ISD::UNDEF) {
10773
10774     ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
10775
10776     // The incoming shuffle must be of the same type as the result of the
10777     // current shuffle.
10778     assert(OtherSV->getOperand(0).getValueType() == VT &&
10779            "Shuffle types don't match");
10780
10781     SmallVector<int, 4> Mask;
10782     // Compute the combined shuffle mask.
10783     for (unsigned i = 0; i != NumElts; ++i) {
10784       int Idx = SVN->getMaskElt(i);
10785       assert(Idx < (int)NumElts && "Index references undef operand");
10786       // Next, this index comes from the first value, which is the incoming
10787       // shuffle. Adopt the incoming index.
10788       if (Idx >= 0)
10789         Idx = OtherSV->getMaskElt(Idx);
10790       Mask.push_back(Idx);
10791     }
10792
10793     // Check if all indices in Mask are Undef. In case, propagate Undef.
10794     bool isUndefMask = true;
10795     for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
10796       isUndefMask &= Mask[i] < 0;
10797
10798     if (isUndefMask)
10799       return DAG.getUNDEF(VT);
10800     
10801     bool CommuteOperands = false;
10802     if (N0.getOperand(1).getOpcode() != ISD::UNDEF) {
10803       // To be valid, the combine shuffle mask should only reference elements
10804       // from one of the two vectors in input to the inner shufflevector.
10805       bool IsValidMask = true;
10806       for (unsigned i = 0; i != NumElts && IsValidMask; ++i)
10807         // See if the combined mask only reference undefs or elements coming
10808         // from the first shufflevector operand.
10809         IsValidMask = Mask[i] < 0 || (unsigned)Mask[i] < NumElts;
10810
10811       if (!IsValidMask) {
10812         IsValidMask = true;
10813         for (unsigned i = 0; i != NumElts && IsValidMask; ++i)
10814           // Check that all the elements come from the second shuffle operand.
10815           IsValidMask = Mask[i] < 0 || (unsigned)Mask[i] >= NumElts;
10816         CommuteOperands = IsValidMask;
10817       }
10818
10819       // Early exit if the combined shuffle mask is not valid.
10820       if (!IsValidMask)
10821         return SDValue();
10822     }
10823
10824     // See if this pair of shuffles can be safely folded according to either
10825     // of the following rules:
10826     //   shuffle(shuffle(x, y), undef) -> x
10827     //   shuffle(shuffle(x, undef), undef) -> x
10828     //   shuffle(shuffle(x, y), undef) -> y
10829     bool IsIdentityMask = true;
10830     unsigned BaseMaskIndex = CommuteOperands ? NumElts : 0;
10831     for (unsigned i = 0; i != NumElts && IsIdentityMask; ++i) {
10832       // Skip Undefs.
10833       if (Mask[i] < 0)
10834         continue;
10835
10836       // The combined shuffle must map each index to itself.
10837       IsIdentityMask = (unsigned)Mask[i] == i + BaseMaskIndex;
10838     }
10839     
10840     if (IsIdentityMask) {
10841       if (CommuteOperands)
10842         // optimize shuffle(shuffle(x, y), undef) -> y.
10843         return OtherSV->getOperand(1);
10844       
10845       // optimize shuffle(shuffle(x, undef), undef) -> x
10846       // optimize shuffle(shuffle(x, y), undef) -> x
10847       return OtherSV->getOperand(0);
10848     }
10849
10850     // It may still be beneficial to combine the two shuffles if the
10851     // resulting shuffle is legal.
10852     if (TLI.isTypeLegal(VT)) {
10853       if (!CommuteOperands) {
10854         if (TLI.isShuffleMaskLegal(Mask, VT))
10855           // shuffle(shuffle(x, undef, M1), undef, M2) -> shuffle(x, undef, M3).
10856           // shuffle(shuffle(x, y, M1), undef, M2) -> shuffle(x, undef, M3)
10857           return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0), N1,
10858                                       &Mask[0]);
10859       } else {
10860         // Compute the commuted shuffle mask.
10861         for (unsigned i = 0; i != NumElts; ++i) {
10862           int idx = Mask[i];
10863           if (idx < 0)
10864             continue;
10865           else if (idx < (int)NumElts)
10866             Mask[i] = idx + NumElts;
10867           else
10868             Mask[i] = idx - NumElts;
10869         }
10870
10871         if (TLI.isShuffleMaskLegal(Mask, VT))
10872           //   shuffle(shuffle(x, y, M1), undef, M2) -> shuffle(y, undef, M3)
10873           return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(1), N1,
10874                                       &Mask[0]);
10875       }
10876     }
10877   }
10878
10879   // Canonicalize shuffles according to rules:
10880   //  shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
10881   //  shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
10882   //  shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
10883   if (N1.getOpcode() == ISD::VECTOR_SHUFFLE && N0.getOpcode() != ISD::UNDEF &&
10884       N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
10885       TLI.isTypeLegal(VT)) {
10886     // The incoming shuffle must be of the same type as the result of the
10887     // current shuffle.
10888     assert(N1->getOperand(0).getValueType() == VT &&
10889            "Shuffle types don't match");
10890
10891     SDValue SV0 = N1->getOperand(0);
10892     SDValue SV1 = N1->getOperand(1);
10893     bool HasSameOp0 = N0 == SV0;
10894     bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
10895     if (HasSameOp0 || IsSV1Undef || N0 == SV1)
10896       // Commute the operands of this shuffle so that next rule
10897       // will trigger.
10898       return DAG.getCommutedVectorShuffle(*SVN);
10899   }
10900
10901   // Try to fold according to rules:
10902   //   shuffle(shuffle(A, B, M0), B, M1) -> shuffle(A, B, M2)
10903   //   shuffle(shuffle(A, B, M0), A, M1) -> shuffle(A, B, M2)
10904   //   shuffle(shuffle(A, Undef, M0), B, M1) -> shuffle(A, B, M2)
10905   //   shuffle(shuffle(A, Undef, M0), A, M1) -> shuffle(A, Undef, M2)
10906   // Don't try to fold shuffles with illegal type.
10907   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
10908       N1.getOpcode() != ISD::UNDEF && TLI.isTypeLegal(VT)) {
10909     ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
10910
10911     // The incoming shuffle must be of the same type as the result of the
10912     // current shuffle.
10913     assert(OtherSV->getOperand(0).getValueType() == VT &&
10914            "Shuffle types don't match");
10915
10916     SDValue SV0 = OtherSV->getOperand(0);
10917     SDValue SV1 = OtherSV->getOperand(1);
10918     bool HasSameOp0 = N1 == SV0;
10919     bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
10920     if (!HasSameOp0 && !IsSV1Undef && N1 != SV1)
10921       // Early exit.
10922       return SDValue();
10923
10924     SmallVector<int, 4> Mask;
10925     // Compute the combined shuffle mask for a shuffle with SV0 as the first
10926     // operand, and SV1 as the second operand.
10927     for (unsigned i = 0; i != NumElts; ++i) {
10928       int Idx = SVN->getMaskElt(i);
10929       if (Idx < 0) {
10930         // Propagate Undef.
10931         Mask.push_back(Idx);
10932         continue;
10933       }
10934
10935       if (Idx < (int)NumElts) {
10936         Idx = OtherSV->getMaskElt(Idx);
10937         if (IsSV1Undef && Idx >= (int) NumElts)
10938           Idx = -1;  // Propagate Undef.
10939       } else
10940         Idx = HasSameOp0 ? Idx - NumElts : Idx;
10941
10942       Mask.push_back(Idx);
10943     }
10944
10945     // Check if all indices in Mask are Undef. In case, propagate Undef.
10946     bool isUndefMask = true;
10947     for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
10948       isUndefMask &= Mask[i] < 0;
10949
10950     if (isUndefMask)
10951       return DAG.getUNDEF(VT);
10952
10953     // Avoid introducing shuffles with illegal mask.
10954     if (TLI.isShuffleMaskLegal(Mask, VT)) {
10955       if (IsSV1Undef)
10956         //   shuffle(shuffle(A, Undef, M0), B, M1) -> shuffle(A, B, M2)
10957         //   shuffle(shuffle(A, Undef, M0), A, M1) -> shuffle(A, Undef, M2)
10958         return DAG.getVectorShuffle(VT, SDLoc(N), SV0, N1, &Mask[0]);
10959       return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, &Mask[0]);
10960     }
10961   }
10962
10963   return SDValue();
10964 }
10965
10966 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
10967   SDValue N0 = N->getOperand(0);
10968   SDValue N2 = N->getOperand(2);
10969
10970   // If the input vector is a concatenation, and the insert replaces
10971   // one of the halves, we can optimize into a single concat_vectors.
10972   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
10973       N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
10974     APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
10975     EVT VT = N->getValueType(0);
10976
10977     // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
10978     // (concat_vectors Z, Y)
10979     if (InsIdx == 0)
10980       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
10981                          N->getOperand(1), N0.getOperand(1));
10982
10983     // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
10984     // (concat_vectors X, Z)
10985     if (InsIdx == VT.getVectorNumElements()/2)
10986       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
10987                          N0.getOperand(0), N->getOperand(1));
10988   }
10989
10990   return SDValue();
10991 }
10992
10993 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle
10994 /// with the destination vector and a zero vector.
10995 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
10996 ///      vector_shuffle V, Zero, <0, 4, 2, 4>
10997 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
10998   EVT VT = N->getValueType(0);
10999   SDLoc dl(N);
11000   SDValue LHS = N->getOperand(0);
11001   SDValue RHS = N->getOperand(1);
11002   if (N->getOpcode() == ISD::AND) {
11003     if (RHS.getOpcode() == ISD::BITCAST)
11004       RHS = RHS.getOperand(0);
11005     if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
11006       SmallVector<int, 8> Indices;
11007       unsigned NumElts = RHS.getNumOperands();
11008       for (unsigned i = 0; i != NumElts; ++i) {
11009         SDValue Elt = RHS.getOperand(i);
11010         if (!isa<ConstantSDNode>(Elt))
11011           return SDValue();
11012
11013         if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
11014           Indices.push_back(i);
11015         else if (cast<ConstantSDNode>(Elt)->isNullValue())
11016           Indices.push_back(NumElts);
11017         else
11018           return SDValue();
11019       }
11020
11021       // Let's see if the target supports this vector_shuffle.
11022       EVT RVT = RHS.getValueType();
11023       if (!TLI.isVectorClearMaskLegal(Indices, RVT))
11024         return SDValue();
11025
11026       // Return the new VECTOR_SHUFFLE node.
11027       EVT EltVT = RVT.getVectorElementType();
11028       SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
11029                                      DAG.getConstant(0, EltVT));
11030       SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), RVT, ZeroOps);
11031       LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
11032       SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
11033       return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
11034     }
11035   }
11036
11037   return SDValue();
11038 }
11039
11040 /// Visit a binary vector operation, like ADD.
11041 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
11042   assert(N->getValueType(0).isVector() &&
11043          "SimplifyVBinOp only works on vectors!");
11044
11045   SDValue LHS = N->getOperand(0);
11046   SDValue RHS = N->getOperand(1);
11047   SDValue Shuffle = XformToShuffleWithZero(N);
11048   if (Shuffle.getNode()) return Shuffle;
11049
11050   // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
11051   // this operation.
11052   if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
11053       RHS.getOpcode() == ISD::BUILD_VECTOR) {
11054     // Check if both vectors are constants. If not bail out.
11055     if (!(cast<BuildVectorSDNode>(LHS)->isConstant() &&
11056           cast<BuildVectorSDNode>(RHS)->isConstant()))
11057       return SDValue();
11058
11059     SmallVector<SDValue, 8> Ops;
11060     for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
11061       SDValue LHSOp = LHS.getOperand(i);
11062       SDValue RHSOp = RHS.getOperand(i);
11063
11064       // Can't fold divide by zero.
11065       if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
11066           N->getOpcode() == ISD::FDIV) {
11067         if ((RHSOp.getOpcode() == ISD::Constant &&
11068              cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
11069             (RHSOp.getOpcode() == ISD::ConstantFP &&
11070              cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
11071           break;
11072       }
11073
11074       EVT VT = LHSOp.getValueType();
11075       EVT RVT = RHSOp.getValueType();
11076       if (RVT != VT) {
11077         // Integer BUILD_VECTOR operands may have types larger than the element
11078         // size (e.g., when the element type is not legal).  Prior to type
11079         // legalization, the types may not match between the two BUILD_VECTORS.
11080         // Truncate one of the operands to make them match.
11081         if (RVT.getSizeInBits() > VT.getSizeInBits()) {
11082           RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
11083         } else {
11084           LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
11085           VT = RVT;
11086         }
11087       }
11088       SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
11089                                    LHSOp, RHSOp);
11090       if (FoldOp.getOpcode() != ISD::UNDEF &&
11091           FoldOp.getOpcode() != ISD::Constant &&
11092           FoldOp.getOpcode() != ISD::ConstantFP)
11093         break;
11094       Ops.push_back(FoldOp);
11095       AddToWorklist(FoldOp.getNode());
11096     }
11097
11098     if (Ops.size() == LHS.getNumOperands())
11099       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), LHS.getValueType(), Ops);
11100   }
11101
11102   // Type legalization might introduce new shuffles in the DAG.
11103   // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
11104   //   -> (shuffle (VBinOp (A, B)), Undef, Mask).
11105   if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
11106       isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
11107       LHS.getOperand(1).getOpcode() == ISD::UNDEF &&
11108       RHS.getOperand(1).getOpcode() == ISD::UNDEF) {
11109     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
11110     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
11111
11112     if (SVN0->getMask().equals(SVN1->getMask())) {
11113       EVT VT = N->getValueType(0);
11114       SDValue UndefVector = LHS.getOperand(1);
11115       SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
11116                                      LHS.getOperand(0), RHS.getOperand(0));
11117       AddUsersToWorklist(N);
11118       return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
11119                                   &SVN0->getMask()[0]);
11120     }
11121   }
11122
11123   return SDValue();
11124 }
11125
11126 /// Visit a binary vector operation, like FABS/FNEG.
11127 SDValue DAGCombiner::SimplifyVUnaryOp(SDNode *N) {
11128   assert(N->getValueType(0).isVector() &&
11129          "SimplifyVUnaryOp only works on vectors!");
11130
11131   SDValue N0 = N->getOperand(0);
11132
11133   if (N0.getOpcode() != ISD::BUILD_VECTOR)
11134     return SDValue();
11135
11136   // Operand is a BUILD_VECTOR node, see if we can constant fold it.
11137   SmallVector<SDValue, 8> Ops;
11138   for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
11139     SDValue Op = N0.getOperand(i);
11140     if (Op.getOpcode() != ISD::UNDEF &&
11141         Op.getOpcode() != ISD::ConstantFP)
11142       break;
11143     EVT EltVT = Op.getValueType();
11144     SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(N0), EltVT, Op);
11145     if (FoldOp.getOpcode() != ISD::UNDEF &&
11146         FoldOp.getOpcode() != ISD::ConstantFP)
11147       break;
11148     Ops.push_back(FoldOp);
11149     AddToWorklist(FoldOp.getNode());
11150   }
11151
11152   if (Ops.size() != N0.getNumOperands())
11153     return SDValue();
11154
11155   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), N0.getValueType(), Ops);
11156 }
11157
11158 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
11159                                     SDValue N1, SDValue N2){
11160   assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
11161
11162   SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
11163                                  cast<CondCodeSDNode>(N0.getOperand(2))->get());
11164
11165   // If we got a simplified select_cc node back from SimplifySelectCC, then
11166   // break it down into a new SETCC node, and a new SELECT node, and then return
11167   // the SELECT node, since we were called with a SELECT node.
11168   if (SCC.getNode()) {
11169     // Check to see if we got a select_cc back (to turn into setcc/select).
11170     // Otherwise, just return whatever node we got back, like fabs.
11171     if (SCC.getOpcode() == ISD::SELECT_CC) {
11172       SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
11173                                   N0.getValueType(),
11174                                   SCC.getOperand(0), SCC.getOperand(1),
11175                                   SCC.getOperand(4));
11176       AddToWorklist(SETCC.getNode());
11177       return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC,
11178                            SCC.getOperand(2), SCC.getOperand(3));
11179     }
11180
11181     return SCC;
11182   }
11183   return SDValue();
11184 }
11185
11186 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values
11187 /// being selected between, see if we can simplify the select.  Callers of this
11188 /// should assume that TheSelect is deleted if this returns true.  As such, they
11189 /// should return the appropriate thing (e.g. the node) back to the top-level of
11190 /// the DAG combiner loop to avoid it being looked at.
11191 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
11192                                     SDValue RHS) {
11193
11194   // Cannot simplify select with vector condition
11195   if (TheSelect->getOperand(0).getValueType().isVector()) return false;
11196
11197   // If this is a select from two identical things, try to pull the operation
11198   // through the select.
11199   if (LHS.getOpcode() != RHS.getOpcode() ||
11200       !LHS.hasOneUse() || !RHS.hasOneUse())
11201     return false;
11202
11203   // If this is a load and the token chain is identical, replace the select
11204   // of two loads with a load through a select of the address to load from.
11205   // This triggers in things like "select bool X, 10.0, 123.0" after the FP
11206   // constants have been dropped into the constant pool.
11207   if (LHS.getOpcode() == ISD::LOAD) {
11208     LoadSDNode *LLD = cast<LoadSDNode>(LHS);
11209     LoadSDNode *RLD = cast<LoadSDNode>(RHS);
11210
11211     // Token chains must be identical.
11212     if (LHS.getOperand(0) != RHS.getOperand(0) ||
11213         // Do not let this transformation reduce the number of volatile loads.
11214         LLD->isVolatile() || RLD->isVolatile() ||
11215         // If this is an EXTLOAD, the VT's must match.
11216         LLD->getMemoryVT() != RLD->getMemoryVT() ||
11217         // If this is an EXTLOAD, the kind of extension must match.
11218         (LLD->getExtensionType() != RLD->getExtensionType() &&
11219          // The only exception is if one of the extensions is anyext.
11220          LLD->getExtensionType() != ISD::EXTLOAD &&
11221          RLD->getExtensionType() != ISD::EXTLOAD) ||
11222         // FIXME: this discards src value information.  This is
11223         // over-conservative. It would be beneficial to be able to remember
11224         // both potential memory locations.  Since we are discarding
11225         // src value info, don't do the transformation if the memory
11226         // locations are not in the default address space.
11227         LLD->getPointerInfo().getAddrSpace() != 0 ||
11228         RLD->getPointerInfo().getAddrSpace() != 0 ||
11229         !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
11230                                       LLD->getBasePtr().getValueType()))
11231       return false;
11232
11233     // Check that the select condition doesn't reach either load.  If so,
11234     // folding this will induce a cycle into the DAG.  If not, this is safe to
11235     // xform, so create a select of the addresses.
11236     SDValue Addr;
11237     if (TheSelect->getOpcode() == ISD::SELECT) {
11238       SDNode *CondNode = TheSelect->getOperand(0).getNode();
11239       if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
11240           (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
11241         return false;
11242       // The loads must not depend on one another.
11243       if (LLD->isPredecessorOf(RLD) ||
11244           RLD->isPredecessorOf(LLD))
11245         return false;
11246       Addr = DAG.getSelect(SDLoc(TheSelect),
11247                            LLD->getBasePtr().getValueType(),
11248                            TheSelect->getOperand(0), LLD->getBasePtr(),
11249                            RLD->getBasePtr());
11250     } else {  // Otherwise SELECT_CC
11251       SDNode *CondLHS = TheSelect->getOperand(0).getNode();
11252       SDNode *CondRHS = TheSelect->getOperand(1).getNode();
11253
11254       if ((LLD->hasAnyUseOfValue(1) &&
11255            (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
11256           (RLD->hasAnyUseOfValue(1) &&
11257            (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
11258         return false;
11259
11260       Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
11261                          LLD->getBasePtr().getValueType(),
11262                          TheSelect->getOperand(0),
11263                          TheSelect->getOperand(1),
11264                          LLD->getBasePtr(), RLD->getBasePtr(),
11265                          TheSelect->getOperand(4));
11266     }
11267
11268     SDValue Load;
11269     // It is safe to replace the two loads if they have different alignments,
11270     // but the new load must be the minimum (most restrictive) alignment of the
11271     // inputs.
11272     bool isInvariant = LLD->getAlignment() & RLD->getAlignment();
11273     unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment());
11274     if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
11275       Load = DAG.getLoad(TheSelect->getValueType(0),
11276                          SDLoc(TheSelect),
11277                          // FIXME: Discards pointer and AA info.
11278                          LLD->getChain(), Addr, MachinePointerInfo(),
11279                          LLD->isVolatile(), LLD->isNonTemporal(),
11280                          isInvariant, Alignment);
11281     } else {
11282       Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
11283                             RLD->getExtensionType() : LLD->getExtensionType(),
11284                             SDLoc(TheSelect),
11285                             TheSelect->getValueType(0),
11286                             // FIXME: Discards pointer and AA info.
11287                             LLD->getChain(), Addr, MachinePointerInfo(),
11288                             LLD->getMemoryVT(), LLD->isVolatile(),
11289                             LLD->isNonTemporal(), isInvariant, Alignment);
11290     }
11291
11292     // Users of the select now use the result of the load.
11293     CombineTo(TheSelect, Load);
11294
11295     // Users of the old loads now use the new load's chain.  We know the
11296     // old-load value is dead now.
11297     CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
11298     CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
11299     return true;
11300   }
11301
11302   return false;
11303 }
11304
11305 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3
11306 /// where 'cond' is the comparison specified by CC.
11307 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
11308                                       SDValue N2, SDValue N3,
11309                                       ISD::CondCode CC, bool NotExtCompare) {
11310   // (x ? y : y) -> y.
11311   if (N2 == N3) return N2;
11312
11313   EVT VT = N2.getValueType();
11314   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
11315   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
11316   ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
11317
11318   // Determine if the condition we're dealing with is constant
11319   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
11320                               N0, N1, CC, DL, false);
11321   if (SCC.getNode()) AddToWorklist(SCC.getNode());
11322   ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
11323
11324   // fold select_cc true, x, y -> x
11325   if (SCCC && !SCCC->isNullValue())
11326     return N2;
11327   // fold select_cc false, x, y -> y
11328   if (SCCC && SCCC->isNullValue())
11329     return N3;
11330
11331   // Check to see if we can simplify the select into an fabs node
11332   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
11333     // Allow either -0.0 or 0.0
11334     if (CFP->getValueAPF().isZero()) {
11335       // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
11336       if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
11337           N0 == N2 && N3.getOpcode() == ISD::FNEG &&
11338           N2 == N3.getOperand(0))
11339         return DAG.getNode(ISD::FABS, DL, VT, N0);
11340
11341       // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
11342       if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
11343           N0 == N3 && N2.getOpcode() == ISD::FNEG &&
11344           N2.getOperand(0) == N3)
11345         return DAG.getNode(ISD::FABS, DL, VT, N3);
11346     }
11347   }
11348
11349   // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
11350   // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
11351   // in it.  This is a win when the constant is not otherwise available because
11352   // it replaces two constant pool loads with one.  We only do this if the FP
11353   // type is known to be legal, because if it isn't, then we are before legalize
11354   // types an we want the other legalization to happen first (e.g. to avoid
11355   // messing with soft float) and if the ConstantFP is not legal, because if
11356   // it is legal, we may not need to store the FP constant in a constant pool.
11357   if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
11358     if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
11359       if (TLI.isTypeLegal(N2.getValueType()) &&
11360           (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
11361                TargetLowering::Legal &&
11362            !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
11363            !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
11364           // If both constants have multiple uses, then we won't need to do an
11365           // extra load, they are likely around in registers for other users.
11366           (TV->hasOneUse() || FV->hasOneUse())) {
11367         Constant *Elts[] = {
11368           const_cast<ConstantFP*>(FV->getConstantFPValue()),
11369           const_cast<ConstantFP*>(TV->getConstantFPValue())
11370         };
11371         Type *FPTy = Elts[0]->getType();
11372         const DataLayout &TD = *TLI.getDataLayout();
11373
11374         // Create a ConstantArray of the two constants.
11375         Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
11376         SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
11377                                             TD.getPrefTypeAlignment(FPTy));
11378         unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
11379
11380         // Get the offsets to the 0 and 1 element of the array so that we can
11381         // select between them.
11382         SDValue Zero = DAG.getIntPtrConstant(0);
11383         unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
11384         SDValue One = DAG.getIntPtrConstant(EltSize);
11385
11386         SDValue Cond = DAG.getSetCC(DL,
11387                                     getSetCCResultType(N0.getValueType()),
11388                                     N0, N1, CC);
11389         AddToWorklist(Cond.getNode());
11390         SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
11391                                           Cond, One, Zero);
11392         AddToWorklist(CstOffset.getNode());
11393         CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
11394                             CstOffset);
11395         AddToWorklist(CPIdx.getNode());
11396         return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
11397                            MachinePointerInfo::getConstantPool(), false,
11398                            false, false, Alignment);
11399
11400       }
11401     }
11402
11403   // Check to see if we can perform the "gzip trick", transforming
11404   // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
11405   if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
11406       (N1C->isNullValue() ||                         // (a < 0) ? b : 0
11407        (N1C->getAPIntValue() == 1 && N0 == N2))) {   // (a < 1) ? a : 0
11408     EVT XType = N0.getValueType();
11409     EVT AType = N2.getValueType();
11410     if (XType.bitsGE(AType)) {
11411       // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
11412       // single-bit constant.
11413       if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
11414         unsigned ShCtV = N2C->getAPIntValue().logBase2();
11415         ShCtV = XType.getSizeInBits()-ShCtV-1;
11416         SDValue ShCt = DAG.getConstant(ShCtV,
11417                                        getShiftAmountTy(N0.getValueType()));
11418         SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
11419                                     XType, N0, ShCt);
11420         AddToWorklist(Shift.getNode());
11421
11422         if (XType.bitsGT(AType)) {
11423           Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
11424           AddToWorklist(Shift.getNode());
11425         }
11426
11427         return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
11428       }
11429
11430       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
11431                                   XType, N0,
11432                                   DAG.getConstant(XType.getSizeInBits()-1,
11433                                          getShiftAmountTy(N0.getValueType())));
11434       AddToWorklist(Shift.getNode());
11435
11436       if (XType.bitsGT(AType)) {
11437         Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
11438         AddToWorklist(Shift.getNode());
11439       }
11440
11441       return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
11442     }
11443   }
11444
11445   // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
11446   // where y is has a single bit set.
11447   // A plaintext description would be, we can turn the SELECT_CC into an AND
11448   // when the condition can be materialized as an all-ones register.  Any
11449   // single bit-test can be materialized as an all-ones register with
11450   // shift-left and shift-right-arith.
11451   if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
11452       N0->getValueType(0) == VT &&
11453       N1C && N1C->isNullValue() &&
11454       N2C && N2C->isNullValue()) {
11455     SDValue AndLHS = N0->getOperand(0);
11456     ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
11457     if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
11458       // Shift the tested bit over the sign bit.
11459       APInt AndMask = ConstAndRHS->getAPIntValue();
11460       SDValue ShlAmt =
11461         DAG.getConstant(AndMask.countLeadingZeros(),
11462                         getShiftAmountTy(AndLHS.getValueType()));
11463       SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
11464
11465       // Now arithmetic right shift it all the way over, so the result is either
11466       // all-ones, or zero.
11467       SDValue ShrAmt =
11468         DAG.getConstant(AndMask.getBitWidth()-1,
11469                         getShiftAmountTy(Shl.getValueType()));
11470       SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
11471
11472       return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
11473     }
11474   }
11475
11476   // fold select C, 16, 0 -> shl C, 4
11477   if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
11478       TLI.getBooleanContents(N0.getValueType()) ==
11479           TargetLowering::ZeroOrOneBooleanContent) {
11480
11481     // If the caller doesn't want us to simplify this into a zext of a compare,
11482     // don't do it.
11483     if (NotExtCompare && N2C->getAPIntValue() == 1)
11484       return SDValue();
11485
11486     // Get a SetCC of the condition
11487     // NOTE: Don't create a SETCC if it's not legal on this target.
11488     if (!LegalOperations ||
11489         TLI.isOperationLegal(ISD::SETCC,
11490           LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
11491       SDValue Temp, SCC;
11492       // cast from setcc result type to select result type
11493       if (LegalTypes) {
11494         SCC  = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
11495                             N0, N1, CC);
11496         if (N2.getValueType().bitsLT(SCC.getValueType()))
11497           Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
11498                                         N2.getValueType());
11499         else
11500           Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
11501                              N2.getValueType(), SCC);
11502       } else {
11503         SCC  = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
11504         Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
11505                            N2.getValueType(), SCC);
11506       }
11507
11508       AddToWorklist(SCC.getNode());
11509       AddToWorklist(Temp.getNode());
11510
11511       if (N2C->getAPIntValue() == 1)
11512         return Temp;
11513
11514       // shl setcc result by log2 n2c
11515       return DAG.getNode(
11516           ISD::SHL, DL, N2.getValueType(), Temp,
11517           DAG.getConstant(N2C->getAPIntValue().logBase2(),
11518                           getShiftAmountTy(Temp.getValueType())));
11519     }
11520   }
11521
11522   // Check to see if this is the equivalent of setcc
11523   // FIXME: Turn all of these into setcc if setcc if setcc is legal
11524   // otherwise, go ahead with the folds.
11525   if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
11526     EVT XType = N0.getValueType();
11527     if (!LegalOperations ||
11528         TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
11529       SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
11530       if (Res.getValueType() != VT)
11531         Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
11532       return Res;
11533     }
11534
11535     // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
11536     if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
11537         (!LegalOperations ||
11538          TLI.isOperationLegal(ISD::CTLZ, XType))) {
11539       SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
11540       return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
11541                          DAG.getConstant(Log2_32(XType.getSizeInBits()),
11542                                        getShiftAmountTy(Ctlz.getValueType())));
11543     }
11544     // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
11545     if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
11546       SDValue NegN0 = DAG.getNode(ISD::SUB, SDLoc(N0),
11547                                   XType, DAG.getConstant(0, XType), N0);
11548       SDValue NotN0 = DAG.getNOT(SDLoc(N0), N0, XType);
11549       return DAG.getNode(ISD::SRL, DL, XType,
11550                          DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
11551                          DAG.getConstant(XType.getSizeInBits()-1,
11552                                          getShiftAmountTy(XType)));
11553     }
11554     // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
11555     if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
11556       SDValue Sign = DAG.getNode(ISD::SRL, SDLoc(N0), XType, N0,
11557                                  DAG.getConstant(XType.getSizeInBits()-1,
11558                                          getShiftAmountTy(N0.getValueType())));
11559       return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
11560     }
11561   }
11562
11563   // Check to see if this is an integer abs.
11564   // select_cc setg[te] X,  0,  X, -X ->
11565   // select_cc setgt    X, -1,  X, -X ->
11566   // select_cc setl[te] X,  0, -X,  X ->
11567   // select_cc setlt    X,  1, -X,  X ->
11568   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
11569   if (N1C) {
11570     ConstantSDNode *SubC = nullptr;
11571     if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
11572          (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
11573         N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
11574       SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
11575     else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
11576               (N1C->isOne() && CC == ISD::SETLT)) &&
11577              N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
11578       SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
11579
11580     EVT XType = N0.getValueType();
11581     if (SubC && SubC->isNullValue() && XType.isInteger()) {
11582       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), XType,
11583                                   N0,
11584                                   DAG.getConstant(XType.getSizeInBits()-1,
11585                                          getShiftAmountTy(N0.getValueType())));
11586       SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0),
11587                                 XType, N0, Shift);
11588       AddToWorklist(Shift.getNode());
11589       AddToWorklist(Add.getNode());
11590       return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
11591     }
11592   }
11593
11594   return SDValue();
11595 }
11596
11597 /// This is a stub for TargetLowering::SimplifySetCC.
11598 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
11599                                    SDValue N1, ISD::CondCode Cond,
11600                                    SDLoc DL, bool foldBooleans) {
11601   TargetLowering::DAGCombinerInfo
11602     DagCombineInfo(DAG, Level, false, this);
11603   return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
11604 }
11605
11606 /// Given an ISD::SDIV node expressing a divide by constant, return
11607 /// a DAG expression to select that will generate the same value by multiplying
11608 /// by a magic number.  See:
11609 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
11610 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
11611   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
11612   if (!C)
11613     return SDValue();
11614
11615   // Avoid division by zero.
11616   if (!C->getAPIntValue())
11617     return SDValue();
11618
11619   std::vector<SDNode*> Built;
11620   SDValue S =
11621       TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
11622
11623   for (SDNode *N : Built)
11624     AddToWorklist(N);
11625   return S;
11626 }
11627
11628 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a
11629 /// DAG expression that will generate the same value by right shifting.
11630 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
11631   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
11632   if (!C)
11633     return SDValue();
11634
11635   // Avoid division by zero.
11636   if (!C->getAPIntValue())
11637     return SDValue();
11638
11639   std::vector<SDNode *> Built;
11640   SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
11641
11642   for (SDNode *N : Built)
11643     AddToWorklist(N);
11644   return S;
11645 }
11646
11647 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG
11648 /// expression that will generate the same value by multiplying by a magic
11649 /// number. See:
11650 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
11651 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
11652   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
11653   if (!C)
11654     return SDValue();
11655
11656   // Avoid division by zero.
11657   if (!C->getAPIntValue())
11658     return SDValue();
11659
11660   std::vector<SDNode*> Built;
11661   SDValue S =
11662       TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
11663
11664   for (SDNode *N : Built)
11665     AddToWorklist(N);
11666   return S;
11667 }
11668
11669 /// Return true if base is a frame index, which is known not to alias with
11670 /// anything but itself.  Provides base object and offset as results.
11671 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
11672                            const GlobalValue *&GV, const void *&CV) {
11673   // Assume it is a primitive operation.
11674   Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
11675
11676   // If it's an adding a simple constant then integrate the offset.
11677   if (Base.getOpcode() == ISD::ADD) {
11678     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
11679       Base = Base.getOperand(0);
11680       Offset += C->getZExtValue();
11681     }
11682   }
11683
11684   // Return the underlying GlobalValue, and update the Offset.  Return false
11685   // for GlobalAddressSDNode since the same GlobalAddress may be represented
11686   // by multiple nodes with different offsets.
11687   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
11688     GV = G->getGlobal();
11689     Offset += G->getOffset();
11690     return false;
11691   }
11692
11693   // Return the underlying Constant value, and update the Offset.  Return false
11694   // for ConstantSDNodes since the same constant pool entry may be represented
11695   // by multiple nodes with different offsets.
11696   if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
11697     CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
11698                                          : (const void *)C->getConstVal();
11699     Offset += C->getOffset();
11700     return false;
11701   }
11702   // If it's any of the following then it can't alias with anything but itself.
11703   return isa<FrameIndexSDNode>(Base);
11704 }
11705
11706 /// Return true if there is any possibility that the two addresses overlap.
11707 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
11708   // If they are the same then they must be aliases.
11709   if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
11710
11711   // If they are both volatile then they cannot be reordered.
11712   if (Op0->isVolatile() && Op1->isVolatile()) return true;
11713
11714   // Gather base node and offset information.
11715   SDValue Base1, Base2;
11716   int64_t Offset1, Offset2;
11717   const GlobalValue *GV1, *GV2;
11718   const void *CV1, *CV2;
11719   bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
11720                                       Base1, Offset1, GV1, CV1);
11721   bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
11722                                       Base2, Offset2, GV2, CV2);
11723
11724   // If they have a same base address then check to see if they overlap.
11725   if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
11726     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
11727              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
11728
11729   // It is possible for different frame indices to alias each other, mostly
11730   // when tail call optimization reuses return address slots for arguments.
11731   // To catch this case, look up the actual index of frame indices to compute
11732   // the real alias relationship.
11733   if (isFrameIndex1 && isFrameIndex2) {
11734     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11735     Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
11736     Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
11737     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
11738              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
11739   }
11740
11741   // Otherwise, if we know what the bases are, and they aren't identical, then
11742   // we know they cannot alias.
11743   if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
11744     return false;
11745
11746   // If we know required SrcValue1 and SrcValue2 have relatively large alignment
11747   // compared to the size and offset of the access, we may be able to prove they
11748   // do not alias.  This check is conservative for now to catch cases created by
11749   // splitting vector types.
11750   if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
11751       (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
11752       (Op0->getMemoryVT().getSizeInBits() >> 3 ==
11753        Op1->getMemoryVT().getSizeInBits() >> 3) &&
11754       (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) {
11755     int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
11756     int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
11757
11758     // There is no overlap between these relatively aligned accesses of similar
11759     // size, return no alias.
11760     if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
11761         (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
11762       return false;
11763   }
11764
11765   bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0 ? CombinerGlobalAA :
11766     TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
11767 #ifndef NDEBUG
11768   if (CombinerAAOnlyFunc.getNumOccurrences() &&
11769       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
11770     UseAA = false;
11771 #endif
11772   if (UseAA &&
11773       Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
11774     // Use alias analysis information.
11775     int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
11776                                  Op1->getSrcValueOffset());
11777     int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
11778         Op0->getSrcValueOffset() - MinOffset;
11779     int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
11780         Op1->getSrcValueOffset() - MinOffset;
11781     AliasAnalysis::AliasResult AAResult =
11782         AA.alias(AliasAnalysis::Location(Op0->getMemOperand()->getValue(),
11783                                          Overlap1,
11784                                          UseTBAA ? Op0->getAAInfo() : AAMDNodes()),
11785                  AliasAnalysis::Location(Op1->getMemOperand()->getValue(),
11786                                          Overlap2,
11787                                          UseTBAA ? Op1->getAAInfo() : AAMDNodes()));
11788     if (AAResult == AliasAnalysis::NoAlias)
11789       return false;
11790   }
11791
11792   // Otherwise we have to assume they alias.
11793   return true;
11794 }
11795
11796 /// Walk up chain skipping non-aliasing memory nodes,
11797 /// looking for aliasing nodes and adding them to the Aliases vector.
11798 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
11799                                    SmallVectorImpl<SDValue> &Aliases) {
11800   SmallVector<SDValue, 8> Chains;     // List of chains to visit.
11801   SmallPtrSet<SDNode *, 16> Visited;  // Visited node set.
11802
11803   // Get alias information for node.
11804   bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
11805
11806   // Starting off.
11807   Chains.push_back(OriginalChain);
11808   unsigned Depth = 0;
11809
11810   // Look at each chain and determine if it is an alias.  If so, add it to the
11811   // aliases list.  If not, then continue up the chain looking for the next
11812   // candidate.
11813   while (!Chains.empty()) {
11814     SDValue Chain = Chains.back();
11815     Chains.pop_back();
11816
11817     // For TokenFactor nodes, look at each operand and only continue up the
11818     // chain until we find two aliases.  If we've seen two aliases, assume we'll
11819     // find more and revert to original chain since the xform is unlikely to be
11820     // profitable.
11821     //
11822     // FIXME: The depth check could be made to return the last non-aliasing
11823     // chain we found before we hit a tokenfactor rather than the original
11824     // chain.
11825     if (Depth > 6 || Aliases.size() == 2) {
11826       Aliases.clear();
11827       Aliases.push_back(OriginalChain);
11828       return;
11829     }
11830
11831     // Don't bother if we've been before.
11832     if (!Visited.insert(Chain.getNode()))
11833       continue;
11834
11835     switch (Chain.getOpcode()) {
11836     case ISD::EntryToken:
11837       // Entry token is ideal chain operand, but handled in FindBetterChain.
11838       break;
11839
11840     case ISD::LOAD:
11841     case ISD::STORE: {
11842       // Get alias information for Chain.
11843       bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
11844           !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
11845
11846       // If chain is alias then stop here.
11847       if (!(IsLoad && IsOpLoad) &&
11848           isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
11849         Aliases.push_back(Chain);
11850       } else {
11851         // Look further up the chain.
11852         Chains.push_back(Chain.getOperand(0));
11853         ++Depth;
11854       }
11855       break;
11856     }
11857
11858     case ISD::TokenFactor:
11859       // We have to check each of the operands of the token factor for "small"
11860       // token factors, so we queue them up.  Adding the operands to the queue
11861       // (stack) in reverse order maintains the original order and increases the
11862       // likelihood that getNode will find a matching token factor (CSE.)
11863       if (Chain.getNumOperands() > 16) {
11864         Aliases.push_back(Chain);
11865         break;
11866       }
11867       for (unsigned n = Chain.getNumOperands(); n;)
11868         Chains.push_back(Chain.getOperand(--n));
11869       ++Depth;
11870       break;
11871
11872     default:
11873       // For all other instructions we will just have to take what we can get.
11874       Aliases.push_back(Chain);
11875       break;
11876     }
11877   }
11878
11879   // We need to be careful here to also search for aliases through the
11880   // value operand of a store, etc. Consider the following situation:
11881   //   Token1 = ...
11882   //   L1 = load Token1, %52
11883   //   S1 = store Token1, L1, %51
11884   //   L2 = load Token1, %52+8
11885   //   S2 = store Token1, L2, %51+8
11886   //   Token2 = Token(S1, S2)
11887   //   L3 = load Token2, %53
11888   //   S3 = store Token2, L3, %52
11889   //   L4 = load Token2, %53+8
11890   //   S4 = store Token2, L4, %52+8
11891   // If we search for aliases of S3 (which loads address %52), and we look
11892   // only through the chain, then we'll miss the trivial dependence on L1
11893   // (which also loads from %52). We then might change all loads and
11894   // stores to use Token1 as their chain operand, which could result in
11895   // copying %53 into %52 before copying %52 into %51 (which should
11896   // happen first).
11897   //
11898   // The problem is, however, that searching for such data dependencies
11899   // can become expensive, and the cost is not directly related to the
11900   // chain depth. Instead, we'll rule out such configurations here by
11901   // insisting that we've visited all chain users (except for users
11902   // of the original chain, which is not necessary). When doing this,
11903   // we need to look through nodes we don't care about (otherwise, things
11904   // like register copies will interfere with trivial cases).
11905
11906   SmallVector<const SDNode *, 16> Worklist;
11907   for (const SDNode *N : Visited)
11908     if (N != OriginalChain.getNode())
11909       Worklist.push_back(N);
11910
11911   while (!Worklist.empty()) {
11912     const SDNode *M = Worklist.pop_back_val();
11913
11914     // We have already visited M, and want to make sure we've visited any uses
11915     // of M that we care about. For uses that we've not visisted, and don't
11916     // care about, queue them to the worklist.
11917
11918     for (SDNode::use_iterator UI = M->use_begin(),
11919          UIE = M->use_end(); UI != UIE; ++UI)
11920       if (UI.getUse().getValueType() == MVT::Other && Visited.insert(*UI)) {
11921         if (isa<MemIntrinsicSDNode>(*UI) || isa<MemSDNode>(*UI)) {
11922           // We've not visited this use, and we care about it (it could have an
11923           // ordering dependency with the original node).
11924           Aliases.clear();
11925           Aliases.push_back(OriginalChain);
11926           return;
11927         }
11928
11929         // We've not visited this use, but we don't care about it. Mark it as
11930         // visited and enqueue it to the worklist.
11931         Worklist.push_back(*UI);
11932       }
11933   }
11934 }
11935
11936 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain
11937 /// (aliasing node.)
11938 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
11939   SmallVector<SDValue, 8> Aliases;  // Ops for replacing token factor.
11940
11941   // Accumulate all the aliases to this node.
11942   GatherAllAliases(N, OldChain, Aliases);
11943
11944   // If no operands then chain to entry token.
11945   if (Aliases.size() == 0)
11946     return DAG.getEntryNode();
11947
11948   // If a single operand then chain to it.  We don't need to revisit it.
11949   if (Aliases.size() == 1)
11950     return Aliases[0];
11951
11952   // Construct a custom tailored token factor.
11953   return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
11954 }
11955
11956 /// This is the entry point for the file.
11957 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
11958                            CodeGenOpt::Level OptLevel) {
11959   /// This is the main entry point to this class.
11960   DAGCombiner(*this, AA, OptLevel).Run(Level);
11961 }