Build correct vector filled with undef nodes
[oota-llvm.git] / lib / CodeGen / SelectionDAG / DAGCombiner.cpp
1 //===-- DAGCombiner.cpp - Implement a DAG node combiner -------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This pass combines dag nodes to form fewer, simpler DAG nodes.  It can be run
11 // both before and after the DAG is legalized.
12 //
13 // This pass is not a substitute for the LLVM IR instcombine pass. This pass is
14 // primarily intended to handle simplification opportunities that are implicit
15 // in the LLVM IR and exposed by the various codegen lowering phases.
16 //
17 //===----------------------------------------------------------------------===//
18
19 #include "llvm/CodeGen/SelectionDAG.h"
20 #include "llvm/ADT/SmallPtrSet.h"
21 #include "llvm/ADT/SetVector.h"
22 #include "llvm/ADT/Statistic.h"
23 #include "llvm/Analysis/AliasAnalysis.h"
24 #include "llvm/CodeGen/MachineFrameInfo.h"
25 #include "llvm/CodeGen/MachineFunction.h"
26 #include "llvm/IR/DataLayout.h"
27 #include "llvm/IR/DerivedTypes.h"
28 #include "llvm/IR/Function.h"
29 #include "llvm/IR/LLVMContext.h"
30 #include "llvm/Support/CommandLine.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/Support/ErrorHandling.h"
33 #include "llvm/Support/MathExtras.h"
34 #include "llvm/Support/raw_ostream.h"
35 #include "llvm/Target/TargetLowering.h"
36 #include "llvm/Target/TargetMachine.h"
37 #include "llvm/Target/TargetOptions.h"
38 #include "llvm/Target/TargetRegisterInfo.h"
39 #include "llvm/Target/TargetSubtargetInfo.h"
40 #include <algorithm>
41 using namespace llvm;
42
43 #define DEBUG_TYPE "dagcombine"
44
45 STATISTIC(NodesCombined   , "Number of dag nodes combined");
46 STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created");
47 STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created");
48 STATISTIC(OpsNarrowed     , "Number of load/op/store narrowed");
49 STATISTIC(LdStFP2Int      , "Number of fp load/store pairs transformed to int");
50 STATISTIC(SlicedLoads, "Number of load sliced");
51
52 namespace {
53   static cl::opt<bool>
54     CombinerAA("combiner-alias-analysis", cl::Hidden,
55                cl::desc("Enable DAG combiner alias-analysis heuristics"));
56
57   static cl::opt<bool>
58     CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
59                cl::desc("Enable DAG combiner's use of IR alias analysis"));
60
61   static cl::opt<bool>
62     UseTBAA("combiner-use-tbaa", cl::Hidden, cl::init(true),
63                cl::desc("Enable DAG combiner's use of TBAA"));
64
65 #ifndef NDEBUG
66   static cl::opt<std::string>
67     CombinerAAOnlyFunc("combiner-aa-only-func", cl::Hidden,
68                cl::desc("Only use DAG-combiner alias analysis in this"
69                         " function"));
70 #endif
71
72   /// Hidden option to stress test load slicing, i.e., when this option
73   /// is enabled, load slicing bypasses most of its profitability guards.
74   static cl::opt<bool>
75   StressLoadSlicing("combiner-stress-load-slicing", cl::Hidden,
76                     cl::desc("Bypass the profitability model of load "
77                              "slicing"),
78                     cl::init(false));
79
80   static cl::opt<bool>
81     MaySplitLoadIndex("combiner-split-load-index", cl::Hidden, cl::init(true),
82                       cl::desc("DAG combiner may split indexing from loads"));
83
84 //------------------------------ DAGCombiner ---------------------------------//
85
86   class DAGCombiner {
87     SelectionDAG &DAG;
88     const TargetLowering &TLI;
89     CombineLevel Level;
90     CodeGenOpt::Level OptLevel;
91     bool LegalOperations;
92     bool LegalTypes;
93     bool ForCodeSize;
94
95     /// \brief Worklist of all of the nodes that need to be simplified.
96     ///
97     /// This must behave as a stack -- new nodes to process are pushed onto the
98     /// back and when processing we pop off of the back.
99     ///
100     /// The worklist will not contain duplicates but may contain null entries
101     /// due to nodes being deleted from the underlying DAG.
102     SmallVector<SDNode *, 64> Worklist;
103
104     /// \brief Mapping from an SDNode to its position on the worklist.
105     ///
106     /// This is used to find and remove nodes from the worklist (by nulling
107     /// them) when they are deleted from the underlying DAG. It relies on
108     /// stable indices of nodes within the worklist.
109     DenseMap<SDNode *, unsigned> WorklistMap;
110
111     /// \brief Set of nodes which have been combined (at least once).
112     ///
113     /// This is used to allow us to reliably add any operands of a DAG node
114     /// which have not yet been combined to the worklist.
115     SmallPtrSet<SDNode *, 64> CombinedNodes;
116
117     // AA - Used for DAG load/store alias analysis.
118     AliasAnalysis &AA;
119
120     /// When an instruction is simplified, add all users of the instruction to
121     /// the work lists because they might get more simplified now.
122     void AddUsersToWorklist(SDNode *N) {
123       for (SDNode *Node : N->uses())
124         AddToWorklist(Node);
125     }
126
127     /// Call the node-specific routine that folds each particular type of node.
128     SDValue visit(SDNode *N);
129
130   public:
131     /// Add to the worklist making sure its instance is at the back (next to be
132     /// processed.)
133     void AddToWorklist(SDNode *N) {
134       // Skip handle nodes as they can't usefully be combined and confuse the
135       // zero-use deletion strategy.
136       if (N->getOpcode() == ISD::HANDLENODE)
137         return;
138
139       if (WorklistMap.insert(std::make_pair(N, Worklist.size())).second)
140         Worklist.push_back(N);
141     }
142
143     /// Remove all instances of N from the worklist.
144     void removeFromWorklist(SDNode *N) {
145       CombinedNodes.erase(N);
146
147       auto It = WorklistMap.find(N);
148       if (It == WorklistMap.end())
149         return; // Not in the worklist.
150
151       // Null out the entry rather than erasing it to avoid a linear operation.
152       Worklist[It->second] = nullptr;
153       WorklistMap.erase(It);
154     }
155
156     void deleteAndRecombine(SDNode *N);
157     bool recursivelyDeleteUnusedNodes(SDNode *N);
158
159     SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
160                       bool AddTo = true);
161
162     SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
163       return CombineTo(N, &Res, 1, AddTo);
164     }
165
166     SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
167                       bool AddTo = true) {
168       SDValue To[] = { Res0, Res1 };
169       return CombineTo(N, To, 2, AddTo);
170     }
171
172     void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
173
174   private:
175
176     /// Check the specified integer node value to see if it can be simplified or
177     /// if things it uses can be simplified by bit propagation.
178     /// If so, return true.
179     bool SimplifyDemandedBits(SDValue Op) {
180       unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits();
181       APInt Demanded = APInt::getAllOnesValue(BitWidth);
182       return SimplifyDemandedBits(Op, Demanded);
183     }
184
185     bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded);
186
187     bool CombineToPreIndexedLoadStore(SDNode *N);
188     bool CombineToPostIndexedLoadStore(SDNode *N);
189     SDValue SplitIndexingFromLoad(LoadSDNode *LD);
190     bool SliceUpLoad(SDNode *N);
191
192     /// \brief Replace an ISD::EXTRACT_VECTOR_ELT of a load with a narrowed
193     ///   load.
194     ///
195     /// \param EVE ISD::EXTRACT_VECTOR_ELT to be replaced.
196     /// \param InVecVT type of the input vector to EVE with bitcasts resolved.
197     /// \param EltNo index of the vector element to load.
198     /// \param OriginalLoad load that EVE came from to be replaced.
199     /// \returns EVE on success SDValue() on failure.
200     SDValue ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
201         SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad);
202     void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
203     SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
204     SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
205     SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
206     SDValue PromoteIntBinOp(SDValue Op);
207     SDValue PromoteIntShiftOp(SDValue Op);
208     SDValue PromoteExtend(SDValue Op);
209     bool PromoteLoad(SDValue Op);
210
211     void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
212                          SDValue Trunc, SDValue ExtLoad, SDLoc DL,
213                          ISD::NodeType ExtType);
214
215     /// Call the node-specific routine that knows how to fold each
216     /// particular type of node. If that doesn't do anything, try the
217     /// target-specific DAG combines.
218     SDValue combine(SDNode *N);
219
220     // Visitation implementation - Implement dag node combining for different
221     // node types.  The semantics are as follows:
222     // Return Value:
223     //   SDValue.getNode() == 0 - No change was made
224     //   SDValue.getNode() == N - N was replaced, is dead and has been handled.
225     //   otherwise              - N should be replaced by the returned Operand.
226     //
227     SDValue visitTokenFactor(SDNode *N);
228     SDValue visitMERGE_VALUES(SDNode *N);
229     SDValue visitADD(SDNode *N);
230     SDValue visitSUB(SDNode *N);
231     SDValue visitADDC(SDNode *N);
232     SDValue visitSUBC(SDNode *N);
233     SDValue visitADDE(SDNode *N);
234     SDValue visitSUBE(SDNode *N);
235     SDValue visitMUL(SDNode *N);
236     SDValue visitSDIV(SDNode *N);
237     SDValue visitUDIV(SDNode *N);
238     SDValue visitSREM(SDNode *N);
239     SDValue visitUREM(SDNode *N);
240     SDValue visitMULHU(SDNode *N);
241     SDValue visitMULHS(SDNode *N);
242     SDValue visitSMUL_LOHI(SDNode *N);
243     SDValue visitUMUL_LOHI(SDNode *N);
244     SDValue visitSMULO(SDNode *N);
245     SDValue visitUMULO(SDNode *N);
246     SDValue visitSDIVREM(SDNode *N);
247     SDValue visitUDIVREM(SDNode *N);
248     SDValue visitAND(SDNode *N);
249     SDValue visitOR(SDNode *N);
250     SDValue visitXOR(SDNode *N);
251     SDValue SimplifyVBinOp(SDNode *N);
252     SDValue SimplifyVUnaryOp(SDNode *N);
253     SDValue visitSHL(SDNode *N);
254     SDValue visitSRA(SDNode *N);
255     SDValue visitSRL(SDNode *N);
256     SDValue visitRotate(SDNode *N);
257     SDValue visitCTLZ(SDNode *N);
258     SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
259     SDValue visitCTTZ(SDNode *N);
260     SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
261     SDValue visitCTPOP(SDNode *N);
262     SDValue visitSELECT(SDNode *N);
263     SDValue visitVSELECT(SDNode *N);
264     SDValue visitSELECT_CC(SDNode *N);
265     SDValue visitSETCC(SDNode *N);
266     SDValue visitSIGN_EXTEND(SDNode *N);
267     SDValue visitZERO_EXTEND(SDNode *N);
268     SDValue visitANY_EXTEND(SDNode *N);
269     SDValue visitSIGN_EXTEND_INREG(SDNode *N);
270     SDValue visitTRUNCATE(SDNode *N);
271     SDValue visitBITCAST(SDNode *N);
272     SDValue visitBUILD_PAIR(SDNode *N);
273     SDValue visitFADD(SDNode *N);
274     SDValue visitFSUB(SDNode *N);
275     SDValue visitFMUL(SDNode *N);
276     SDValue visitFMA(SDNode *N);
277     SDValue visitFDIV(SDNode *N);
278     SDValue visitFREM(SDNode *N);
279     SDValue visitFCOPYSIGN(SDNode *N);
280     SDValue visitSINT_TO_FP(SDNode *N);
281     SDValue visitUINT_TO_FP(SDNode *N);
282     SDValue visitFP_TO_SINT(SDNode *N);
283     SDValue visitFP_TO_UINT(SDNode *N);
284     SDValue visitFP_ROUND(SDNode *N);
285     SDValue visitFP_ROUND_INREG(SDNode *N);
286     SDValue visitFP_EXTEND(SDNode *N);
287     SDValue visitFNEG(SDNode *N);
288     SDValue visitFABS(SDNode *N);
289     SDValue visitFCEIL(SDNode *N);
290     SDValue visitFTRUNC(SDNode *N);
291     SDValue visitFFLOOR(SDNode *N);
292     SDValue visitBRCOND(SDNode *N);
293     SDValue visitBR_CC(SDNode *N);
294     SDValue visitLOAD(SDNode *N);
295     SDValue visitSTORE(SDNode *N);
296     SDValue visitINSERT_VECTOR_ELT(SDNode *N);
297     SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
298     SDValue visitBUILD_VECTOR(SDNode *N);
299     SDValue visitCONCAT_VECTORS(SDNode *N);
300     SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
301     SDValue visitVECTOR_SHUFFLE(SDNode *N);
302     SDValue visitINSERT_SUBVECTOR(SDNode *N);
303
304     SDValue XformToShuffleWithZero(SDNode *N);
305     SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS);
306
307     SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt);
308
309     bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
310     SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
311     SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2);
312     SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2,
313                              SDValue N3, ISD::CondCode CC,
314                              bool NotExtCompare = false);
315     SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
316                           SDLoc DL, bool foldBooleans = true);
317
318     bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
319                            SDValue &CC) const;
320     bool isOneUseSetCC(SDValue N) const;
321
322     SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
323                                          unsigned HiOp);
324     SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
325     SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
326     SDValue BuildSDIV(SDNode *N);
327     SDValue BuildSDIVPow2(SDNode *N);
328     SDValue BuildUDIV(SDNode *N);
329     SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
330                                bool DemandHighBits = true);
331     SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
332     SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
333                               SDValue InnerPos, SDValue InnerNeg,
334                               unsigned PosOpcode, unsigned NegOpcode,
335                               SDLoc DL);
336     SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL);
337     SDValue ReduceLoadWidth(SDNode *N);
338     SDValue ReduceLoadOpStoreWidth(SDNode *N);
339     SDValue TransformFPLoadStorePair(SDNode *N);
340     SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
341     SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
342
343     SDValue GetDemandedBits(SDValue V, const APInt &Mask);
344
345     /// Walk up chain skipping non-aliasing memory nodes,
346     /// looking for aliasing nodes and adding them to the Aliases vector.
347     void GatherAllAliases(SDNode *N, SDValue OriginalChain,
348                           SmallVectorImpl<SDValue> &Aliases);
349
350     /// Return true if there is any possibility that the two addresses overlap.
351     bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const;
352
353     /// Walk up chain skipping non-aliasing memory nodes, looking for a better
354     /// chain (aliasing node.)
355     SDValue FindBetterChain(SDNode *N, SDValue Chain);
356
357     /// Merge consecutive store operations into a wide store.
358     /// This optimization uses wide integers or vectors when possible.
359     /// \return True if some memory operations were changed.
360     bool MergeConsecutiveStores(StoreSDNode *N);
361
362     /// \brief Try to transform a truncation where C is a constant:
363     ///     (trunc (and X, C)) -> (and (trunc X), (trunc C))
364     ///
365     /// \p N needs to be a truncation and its first operand an AND. Other
366     /// requirements are checked by the function (e.g. that trunc is
367     /// single-use) and if missed an empty SDValue is returned.
368     SDValue distributeTruncateThroughAnd(SDNode *N);
369
370   public:
371     DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
372         : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
373           OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
374       AttributeSet FnAttrs =
375           DAG.getMachineFunction().getFunction()->getAttributes();
376       ForCodeSize =
377           FnAttrs.hasAttribute(AttributeSet::FunctionIndex,
378                                Attribute::OptimizeForSize) ||
379           FnAttrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::MinSize);
380     }
381
382     /// Runs the dag combiner on all nodes in the work list
383     void Run(CombineLevel AtLevel);
384
385     SelectionDAG &getDAG() const { return DAG; }
386
387     /// Returns a type large enough to hold any valid shift amount - before type
388     /// legalization these can be huge.
389     EVT getShiftAmountTy(EVT LHSTy) {
390       assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
391       if (LHSTy.isVector())
392         return LHSTy;
393       return LegalTypes ? TLI.getScalarShiftAmountTy(LHSTy)
394                         : TLI.getPointerTy();
395     }
396
397     /// This method returns true if we are running before type legalization or
398     /// if the specified VT is legal.
399     bool isTypeLegal(const EVT &VT) {
400       if (!LegalTypes) return true;
401       return TLI.isTypeLegal(VT);
402     }
403
404     /// Convenience wrapper around TargetLowering::getSetCCResultType
405     EVT getSetCCResultType(EVT VT) const {
406       return TLI.getSetCCResultType(*DAG.getContext(), VT);
407     }
408   };
409 }
410
411
412 namespace {
413 /// This class is a DAGUpdateListener that removes any deleted
414 /// nodes from the worklist.
415 class WorklistRemover : public SelectionDAG::DAGUpdateListener {
416   DAGCombiner &DC;
417 public:
418   explicit WorklistRemover(DAGCombiner &dc)
419     : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
420
421   void NodeDeleted(SDNode *N, SDNode *E) override {
422     DC.removeFromWorklist(N);
423   }
424 };
425 }
426
427 //===----------------------------------------------------------------------===//
428 //  TargetLowering::DAGCombinerInfo implementation
429 //===----------------------------------------------------------------------===//
430
431 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
432   ((DAGCombiner*)DC)->AddToWorklist(N);
433 }
434
435 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
436   ((DAGCombiner*)DC)->removeFromWorklist(N);
437 }
438
439 SDValue TargetLowering::DAGCombinerInfo::
440 CombineTo(SDNode *N, const std::vector<SDValue> &To, bool AddTo) {
441   return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
442 }
443
444 SDValue TargetLowering::DAGCombinerInfo::
445 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
446   return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
447 }
448
449
450 SDValue TargetLowering::DAGCombinerInfo::
451 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
452   return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
453 }
454
455 void TargetLowering::DAGCombinerInfo::
456 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
457   return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
458 }
459
460 //===----------------------------------------------------------------------===//
461 // Helper Functions
462 //===----------------------------------------------------------------------===//
463
464 void DAGCombiner::deleteAndRecombine(SDNode *N) {
465   removeFromWorklist(N);
466
467   // If the operands of this node are only used by the node, they will now be
468   // dead. Make sure to re-visit them and recursively delete dead nodes.
469   for (const SDValue &Op : N->ops())
470     // For an operand generating multiple values, one of the values may
471     // become dead allowing further simplification (e.g. split index
472     // arithmetic from an indexed load).
473     if (Op->hasOneUse() || Op->getNumValues() > 1)
474       AddToWorklist(Op.getNode());
475
476   DAG.DeleteNode(N);
477 }
478
479 /// Return 1 if we can compute the negated form of the specified expression for
480 /// the same cost as the expression itself, or 2 if we can compute the negated
481 /// form more cheaply than the expression itself.
482 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
483                                const TargetLowering &TLI,
484                                const TargetOptions *Options,
485                                unsigned Depth = 0) {
486   // fneg is removable even if it has multiple uses.
487   if (Op.getOpcode() == ISD::FNEG) return 2;
488
489   // Don't allow anything with multiple uses.
490   if (!Op.hasOneUse()) return 0;
491
492   // Don't recurse exponentially.
493   if (Depth > 6) return 0;
494
495   switch (Op.getOpcode()) {
496   default: return false;
497   case ISD::ConstantFP:
498     // Don't invert constant FP values after legalize.  The negated constant
499     // isn't necessarily legal.
500     return LegalOperations ? 0 : 1;
501   case ISD::FADD:
502     // FIXME: determine better conditions for this xform.
503     if (!Options->UnsafeFPMath) return 0;
504
505     // After operation legalization, it might not be legal to create new FSUBs.
506     if (LegalOperations &&
507         !TLI.isOperationLegalOrCustom(ISD::FSUB,  Op.getValueType()))
508       return 0;
509
510     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
511     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
512                                     Options, Depth + 1))
513       return V;
514     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
515     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
516                               Depth + 1);
517   case ISD::FSUB:
518     // We can't turn -(A-B) into B-A when we honor signed zeros.
519     if (!Options->UnsafeFPMath) return 0;
520
521     // fold (fneg (fsub A, B)) -> (fsub B, A)
522     return 1;
523
524   case ISD::FMUL:
525   case ISD::FDIV:
526     if (Options->HonorSignDependentRoundingFPMath()) return 0;
527
528     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
529     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
530                                     Options, Depth + 1))
531       return V;
532
533     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
534                               Depth + 1);
535
536   case ISD::FP_EXTEND:
537   case ISD::FP_ROUND:
538   case ISD::FSIN:
539     return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
540                               Depth + 1);
541   }
542 }
543
544 /// If isNegatibleForFree returns true, return the newly negated expression.
545 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
546                                     bool LegalOperations, unsigned Depth = 0) {
547   const TargetOptions &Options = DAG.getTarget().Options;
548   // fneg is removable even if it has multiple uses.
549   if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
550
551   // Don't allow anything with multiple uses.
552   assert(Op.hasOneUse() && "Unknown reuse!");
553
554   assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
555   switch (Op.getOpcode()) {
556   default: llvm_unreachable("Unknown code");
557   case ISD::ConstantFP: {
558     APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
559     V.changeSign();
560     return DAG.getConstantFP(V, Op.getValueType());
561   }
562   case ISD::FADD:
563     // FIXME: determine better conditions for this xform.
564     assert(Options.UnsafeFPMath);
565
566     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
567     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
568                            DAG.getTargetLoweringInfo(), &Options, Depth+1))
569       return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
570                          GetNegatedExpression(Op.getOperand(0), DAG,
571                                               LegalOperations, Depth+1),
572                          Op.getOperand(1));
573     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
574     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
575                        GetNegatedExpression(Op.getOperand(1), DAG,
576                                             LegalOperations, Depth+1),
577                        Op.getOperand(0));
578   case ISD::FSUB:
579     // We can't turn -(A-B) into B-A when we honor signed zeros.
580     assert(Options.UnsafeFPMath);
581
582     // fold (fneg (fsub 0, B)) -> B
583     if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
584       if (N0CFP->getValueAPF().isZero())
585         return Op.getOperand(1);
586
587     // fold (fneg (fsub A, B)) -> (fsub B, A)
588     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
589                        Op.getOperand(1), Op.getOperand(0));
590
591   case ISD::FMUL:
592   case ISD::FDIV:
593     assert(!Options.HonorSignDependentRoundingFPMath());
594
595     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
596     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
597                            DAG.getTargetLoweringInfo(), &Options, Depth+1))
598       return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
599                          GetNegatedExpression(Op.getOperand(0), DAG,
600                                               LegalOperations, Depth+1),
601                          Op.getOperand(1));
602
603     // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
604     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
605                        Op.getOperand(0),
606                        GetNegatedExpression(Op.getOperand(1), DAG,
607                                             LegalOperations, Depth+1));
608
609   case ISD::FP_EXTEND:
610   case ISD::FSIN:
611     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
612                        GetNegatedExpression(Op.getOperand(0), DAG,
613                                             LegalOperations, Depth+1));
614   case ISD::FP_ROUND:
615       return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
616                          GetNegatedExpression(Op.getOperand(0), DAG,
617                                               LegalOperations, Depth+1),
618                          Op.getOperand(1));
619   }
620 }
621
622 // Return true if this node is a setcc, or is a select_cc
623 // that selects between the target values used for true and false, making it
624 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
625 // the appropriate nodes based on the type of node we are checking. This
626 // simplifies life a bit for the callers.
627 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
628                                     SDValue &CC) const {
629   if (N.getOpcode() == ISD::SETCC) {
630     LHS = N.getOperand(0);
631     RHS = N.getOperand(1);
632     CC  = N.getOperand(2);
633     return true;
634   }
635
636   if (N.getOpcode() != ISD::SELECT_CC ||
637       !TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
638       !TLI.isConstFalseVal(N.getOperand(3).getNode()))
639     return false;
640
641   LHS = N.getOperand(0);
642   RHS = N.getOperand(1);
643   CC  = N.getOperand(4);
644   return true;
645 }
646
647 /// Return true if this is a SetCC-equivalent operation with only one use.
648 /// If this is true, it allows the users to invert the operation for free when
649 /// it is profitable to do so.
650 bool DAGCombiner::isOneUseSetCC(SDValue N) const {
651   SDValue N0, N1, N2;
652   if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
653     return true;
654   return false;
655 }
656
657 /// Returns true if N is a BUILD_VECTOR node whose
658 /// elements are all the same constant or undefined.
659 static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
660   BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
661   if (!C)
662     return false;
663
664   APInt SplatUndef;
665   unsigned SplatBitSize;
666   bool HasAnyUndefs;
667   EVT EltVT = N->getValueType(0).getVectorElementType();
668   return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
669                              HasAnyUndefs) &&
670           EltVT.getSizeInBits() >= SplatBitSize);
671 }
672
673 // \brief Returns the SDNode if it is a constant BuildVector or constant.
674 static SDNode *isConstantBuildVectorOrConstantInt(SDValue N) {
675   if (isa<ConstantSDNode>(N))
676     return N.getNode();
677   BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N);
678   if (BV && BV->isConstant())
679     return BV;
680   return nullptr;
681 }
682
683 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
684 // int.
685 static ConstantSDNode *isConstOrConstSplat(SDValue N) {
686   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
687     return CN;
688
689   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
690     BitVector UndefElements;
691     ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
692
693     // BuildVectors can truncate their operands. Ignore that case here.
694     // FIXME: We blindly ignore splats which include undef which is overly
695     // pessimistic.
696     if (CN && UndefElements.none() &&
697         CN->getValueType(0) == N.getValueType().getScalarType())
698       return CN;
699   }
700
701   return nullptr;
702 }
703
704 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
705 // float.
706 static ConstantFPSDNode *isConstOrConstSplatFP(SDValue N) {
707   if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
708     return CN;
709
710   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
711     BitVector UndefElements;
712     ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements);
713
714     if (CN && UndefElements.none())
715       return CN;
716   }
717
718   return nullptr;
719 }
720
721 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
722                                     SDValue N0, SDValue N1) {
723   EVT VT = N0.getValueType();
724   if (N0.getOpcode() == Opc) {
725     if (SDNode *L = isConstantBuildVectorOrConstantInt(N0.getOperand(1))) {
726       if (SDNode *R = isConstantBuildVectorOrConstantInt(N1)) {
727         // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
728         SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, L, R);
729         if (!OpNode.getNode())
730           return SDValue();
731         return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
732       }
733       if (N0.hasOneUse()) {
734         // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
735         // use
736         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
737         if (!OpNode.getNode())
738           return SDValue();
739         AddToWorklist(OpNode.getNode());
740         return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
741       }
742     }
743   }
744
745   if (N1.getOpcode() == Opc) {
746     if (SDNode *R = isConstantBuildVectorOrConstantInt(N1.getOperand(1))) {
747       if (SDNode *L = isConstantBuildVectorOrConstantInt(N0)) {
748         // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
749         SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, R, L);
750         if (!OpNode.getNode())
751           return SDValue();
752         return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
753       }
754       if (N1.hasOneUse()) {
755         // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one
756         // use
757         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0);
758         if (!OpNode.getNode())
759           return SDValue();
760         AddToWorklist(OpNode.getNode());
761         return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
762       }
763     }
764   }
765
766   return SDValue();
767 }
768
769 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
770                                bool AddTo) {
771   assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
772   ++NodesCombined;
773   DEBUG(dbgs() << "\nReplacing.1 ";
774         N->dump(&DAG);
775         dbgs() << "\nWith: ";
776         To[0].getNode()->dump(&DAG);
777         dbgs() << " and " << NumTo-1 << " other values\n";
778         for (unsigned i = 0, e = NumTo; i != e; ++i)
779           assert((!To[i].getNode() ||
780                   N->getValueType(i) == To[i].getValueType()) &&
781                  "Cannot combine value to value of different type!"));
782   WorklistRemover DeadNodes(*this);
783   DAG.ReplaceAllUsesWith(N, To);
784   if (AddTo) {
785     // Push the new nodes and any users onto the worklist
786     for (unsigned i = 0, e = NumTo; i != e; ++i) {
787       if (To[i].getNode()) {
788         AddToWorklist(To[i].getNode());
789         AddUsersToWorklist(To[i].getNode());
790       }
791     }
792   }
793
794   // Finally, if the node is now dead, remove it from the graph.  The node
795   // may not be dead if the replacement process recursively simplified to
796   // something else needing this node.
797   if (N->use_empty())
798     deleteAndRecombine(N);
799   return SDValue(N, 0);
800 }
801
802 void DAGCombiner::
803 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
804   // Replace all uses.  If any nodes become isomorphic to other nodes and
805   // are deleted, make sure to remove them from our worklist.
806   WorklistRemover DeadNodes(*this);
807   DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
808
809   // Push the new node and any (possibly new) users onto the worklist.
810   AddToWorklist(TLO.New.getNode());
811   AddUsersToWorklist(TLO.New.getNode());
812
813   // Finally, if the node is now dead, remove it from the graph.  The node
814   // may not be dead if the replacement process recursively simplified to
815   // something else needing this node.
816   if (TLO.Old.getNode()->use_empty())
817     deleteAndRecombine(TLO.Old.getNode());
818 }
819
820 /// Check the specified integer node value to see if it can be simplified or if
821 /// things it uses can be simplified by bit propagation. If so, return true.
822 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
823   TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
824   APInt KnownZero, KnownOne;
825   if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
826     return false;
827
828   // Revisit the node.
829   AddToWorklist(Op.getNode());
830
831   // Replace the old value with the new one.
832   ++NodesCombined;
833   DEBUG(dbgs() << "\nReplacing.2 ";
834         TLO.Old.getNode()->dump(&DAG);
835         dbgs() << "\nWith: ";
836         TLO.New.getNode()->dump(&DAG);
837         dbgs() << '\n');
838
839   CommitTargetLoweringOpt(TLO);
840   return true;
841 }
842
843 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
844   SDLoc dl(Load);
845   EVT VT = Load->getValueType(0);
846   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
847
848   DEBUG(dbgs() << "\nReplacing.9 ";
849         Load->dump(&DAG);
850         dbgs() << "\nWith: ";
851         Trunc.getNode()->dump(&DAG);
852         dbgs() << '\n');
853   WorklistRemover DeadNodes(*this);
854   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
855   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
856   deleteAndRecombine(Load);
857   AddToWorklist(Trunc.getNode());
858 }
859
860 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
861   Replace = false;
862   SDLoc dl(Op);
863   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
864     EVT MemVT = LD->getMemoryVT();
865     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
866       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
867                                                   : ISD::EXTLOAD)
868       : LD->getExtensionType();
869     Replace = true;
870     return DAG.getExtLoad(ExtType, dl, PVT,
871                           LD->getChain(), LD->getBasePtr(),
872                           MemVT, LD->getMemOperand());
873   }
874
875   unsigned Opc = Op.getOpcode();
876   switch (Opc) {
877   default: break;
878   case ISD::AssertSext:
879     return DAG.getNode(ISD::AssertSext, dl, PVT,
880                        SExtPromoteOperand(Op.getOperand(0), PVT),
881                        Op.getOperand(1));
882   case ISD::AssertZext:
883     return DAG.getNode(ISD::AssertZext, dl, PVT,
884                        ZExtPromoteOperand(Op.getOperand(0), PVT),
885                        Op.getOperand(1));
886   case ISD::Constant: {
887     unsigned ExtOpc =
888       Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
889     return DAG.getNode(ExtOpc, dl, PVT, Op);
890   }
891   }
892
893   if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
894     return SDValue();
895   return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
896 }
897
898 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
899   if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
900     return SDValue();
901   EVT OldVT = Op.getValueType();
902   SDLoc dl(Op);
903   bool Replace = false;
904   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
905   if (!NewOp.getNode())
906     return SDValue();
907   AddToWorklist(NewOp.getNode());
908
909   if (Replace)
910     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
911   return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
912                      DAG.getValueType(OldVT));
913 }
914
915 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
916   EVT OldVT = Op.getValueType();
917   SDLoc dl(Op);
918   bool Replace = false;
919   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
920   if (!NewOp.getNode())
921     return SDValue();
922   AddToWorklist(NewOp.getNode());
923
924   if (Replace)
925     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
926   return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
927 }
928
929 /// Promote the specified integer binary operation if the target indicates it is
930 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
931 /// i32 since i16 instructions are longer.
932 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
933   if (!LegalOperations)
934     return SDValue();
935
936   EVT VT = Op.getValueType();
937   if (VT.isVector() || !VT.isInteger())
938     return SDValue();
939
940   // If operation type is 'undesirable', e.g. i16 on x86, consider
941   // promoting it.
942   unsigned Opc = Op.getOpcode();
943   if (TLI.isTypeDesirableForOp(Opc, VT))
944     return SDValue();
945
946   EVT PVT = VT;
947   // Consult target whether it is a good idea to promote this operation and
948   // what's the right type to promote it to.
949   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
950     assert(PVT != VT && "Don't know what type to promote to!");
951
952     bool Replace0 = false;
953     SDValue N0 = Op.getOperand(0);
954     SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
955     if (!NN0.getNode())
956       return SDValue();
957
958     bool Replace1 = false;
959     SDValue N1 = Op.getOperand(1);
960     SDValue NN1;
961     if (N0 == N1)
962       NN1 = NN0;
963     else {
964       NN1 = PromoteOperand(N1, PVT, Replace1);
965       if (!NN1.getNode())
966         return SDValue();
967     }
968
969     AddToWorklist(NN0.getNode());
970     if (NN1.getNode())
971       AddToWorklist(NN1.getNode());
972
973     if (Replace0)
974       ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
975     if (Replace1)
976       ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
977
978     DEBUG(dbgs() << "\nPromoting ";
979           Op.getNode()->dump(&DAG));
980     SDLoc dl(Op);
981     return DAG.getNode(ISD::TRUNCATE, dl, VT,
982                        DAG.getNode(Opc, dl, PVT, NN0, NN1));
983   }
984   return SDValue();
985 }
986
987 /// Promote the specified integer shift operation if the target indicates it is
988 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
989 /// i32 since i16 instructions are longer.
990 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
991   if (!LegalOperations)
992     return SDValue();
993
994   EVT VT = Op.getValueType();
995   if (VT.isVector() || !VT.isInteger())
996     return SDValue();
997
998   // If operation type is 'undesirable', e.g. i16 on x86, consider
999   // promoting it.
1000   unsigned Opc = Op.getOpcode();
1001   if (TLI.isTypeDesirableForOp(Opc, VT))
1002     return SDValue();
1003
1004   EVT PVT = VT;
1005   // Consult target whether it is a good idea to promote this operation and
1006   // what's the right type to promote it to.
1007   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1008     assert(PVT != VT && "Don't know what type to promote to!");
1009
1010     bool Replace = false;
1011     SDValue N0 = Op.getOperand(0);
1012     if (Opc == ISD::SRA)
1013       N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
1014     else if (Opc == ISD::SRL)
1015       N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
1016     else
1017       N0 = PromoteOperand(N0, PVT, Replace);
1018     if (!N0.getNode())
1019       return SDValue();
1020
1021     AddToWorklist(N0.getNode());
1022     if (Replace)
1023       ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
1024
1025     DEBUG(dbgs() << "\nPromoting ";
1026           Op.getNode()->dump(&DAG));
1027     SDLoc dl(Op);
1028     return DAG.getNode(ISD::TRUNCATE, dl, VT,
1029                        DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
1030   }
1031   return SDValue();
1032 }
1033
1034 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
1035   if (!LegalOperations)
1036     return SDValue();
1037
1038   EVT VT = Op.getValueType();
1039   if (VT.isVector() || !VT.isInteger())
1040     return SDValue();
1041
1042   // If operation type is 'undesirable', e.g. i16 on x86, consider
1043   // promoting it.
1044   unsigned Opc = Op.getOpcode();
1045   if (TLI.isTypeDesirableForOp(Opc, VT))
1046     return SDValue();
1047
1048   EVT PVT = VT;
1049   // Consult target whether it is a good idea to promote this operation and
1050   // what's the right type to promote it to.
1051   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1052     assert(PVT != VT && "Don't know what type to promote to!");
1053     // fold (aext (aext x)) -> (aext x)
1054     // fold (aext (zext x)) -> (zext x)
1055     // fold (aext (sext x)) -> (sext x)
1056     DEBUG(dbgs() << "\nPromoting ";
1057           Op.getNode()->dump(&DAG));
1058     return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1059   }
1060   return SDValue();
1061 }
1062
1063 bool DAGCombiner::PromoteLoad(SDValue Op) {
1064   if (!LegalOperations)
1065     return false;
1066
1067   EVT VT = Op.getValueType();
1068   if (VT.isVector() || !VT.isInteger())
1069     return false;
1070
1071   // If operation type is 'undesirable', e.g. i16 on x86, consider
1072   // promoting it.
1073   unsigned Opc = Op.getOpcode();
1074   if (TLI.isTypeDesirableForOp(Opc, VT))
1075     return false;
1076
1077   EVT PVT = VT;
1078   // Consult target whether it is a good idea to promote this operation and
1079   // what's the right type to promote it to.
1080   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1081     assert(PVT != VT && "Don't know what type to promote to!");
1082
1083     SDLoc dl(Op);
1084     SDNode *N = Op.getNode();
1085     LoadSDNode *LD = cast<LoadSDNode>(N);
1086     EVT MemVT = LD->getMemoryVT();
1087     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1088       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
1089                                                   : ISD::EXTLOAD)
1090       : LD->getExtensionType();
1091     SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
1092                                    LD->getChain(), LD->getBasePtr(),
1093                                    MemVT, LD->getMemOperand());
1094     SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
1095
1096     DEBUG(dbgs() << "\nPromoting ";
1097           N->dump(&DAG);
1098           dbgs() << "\nTo: ";
1099           Result.getNode()->dump(&DAG);
1100           dbgs() << '\n');
1101     WorklistRemover DeadNodes(*this);
1102     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1103     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1104     deleteAndRecombine(N);
1105     AddToWorklist(Result.getNode());
1106     return true;
1107   }
1108   return false;
1109 }
1110
1111 /// \brief Recursively delete a node which has no uses and any operands for
1112 /// which it is the only use.
1113 ///
1114 /// Note that this both deletes the nodes and removes them from the worklist.
1115 /// It also adds any nodes who have had a user deleted to the worklist as they
1116 /// may now have only one use and subject to other combines.
1117 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) {
1118   if (!N->use_empty())
1119     return false;
1120
1121   SmallSetVector<SDNode *, 16> Nodes;
1122   Nodes.insert(N);
1123   do {
1124     N = Nodes.pop_back_val();
1125     if (!N)
1126       continue;
1127
1128     if (N->use_empty()) {
1129       for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1130         Nodes.insert(N->getOperand(i).getNode());
1131
1132       removeFromWorklist(N);
1133       DAG.DeleteNode(N);
1134     } else {
1135       AddToWorklist(N);
1136     }
1137   } while (!Nodes.empty());
1138   return true;
1139 }
1140
1141 //===----------------------------------------------------------------------===//
1142 //  Main DAG Combiner implementation
1143 //===----------------------------------------------------------------------===//
1144
1145 void DAGCombiner::Run(CombineLevel AtLevel) {
1146   // set the instance variables, so that the various visit routines may use it.
1147   Level = AtLevel;
1148   LegalOperations = Level >= AfterLegalizeVectorOps;
1149   LegalTypes = Level >= AfterLegalizeTypes;
1150
1151   // Add all the dag nodes to the worklist.
1152   for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
1153        E = DAG.allnodes_end(); I != E; ++I)
1154     AddToWorklist(I);
1155
1156   // Create a dummy node (which is not added to allnodes), that adds a reference
1157   // to the root node, preventing it from being deleted, and tracking any
1158   // changes of the root.
1159   HandleSDNode Dummy(DAG.getRoot());
1160
1161   // while the worklist isn't empty, find a node and
1162   // try and combine it.
1163   while (!WorklistMap.empty()) {
1164     SDNode *N;
1165     // The Worklist holds the SDNodes in order, but it may contain null entries.
1166     do {
1167       N = Worklist.pop_back_val();
1168     } while (!N);
1169
1170     bool GoodWorklistEntry = WorklistMap.erase(N);
1171     (void)GoodWorklistEntry;
1172     assert(GoodWorklistEntry &&
1173            "Found a worklist entry without a corresponding map entry!");
1174
1175     // If N has no uses, it is dead.  Make sure to revisit all N's operands once
1176     // N is deleted from the DAG, since they too may now be dead or may have a
1177     // reduced number of uses, allowing other xforms.
1178     if (recursivelyDeleteUnusedNodes(N))
1179       continue;
1180
1181     WorklistRemover DeadNodes(*this);
1182
1183     // If this combine is running after legalizing the DAG, re-legalize any
1184     // nodes pulled off the worklist.
1185     if (Level == AfterLegalizeDAG) {
1186       SmallSetVector<SDNode *, 16> UpdatedNodes;
1187       bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes);
1188
1189       for (SDNode *LN : UpdatedNodes) {
1190         AddToWorklist(LN);
1191         AddUsersToWorklist(LN);
1192       }
1193       if (!NIsValid)
1194         continue;
1195     }
1196
1197     DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG));
1198
1199     // Add any operands of the new node which have not yet been combined to the
1200     // worklist as well. Because the worklist uniques things already, this
1201     // won't repeatedly process the same operand.
1202     CombinedNodes.insert(N);
1203     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1204       if (!CombinedNodes.count(N->getOperand(i).getNode()))
1205         AddToWorklist(N->getOperand(i).getNode());
1206
1207     SDValue RV = combine(N);
1208
1209     if (!RV.getNode())
1210       continue;
1211
1212     ++NodesCombined;
1213
1214     // If we get back the same node we passed in, rather than a new node or
1215     // zero, we know that the node must have defined multiple values and
1216     // CombineTo was used.  Since CombineTo takes care of the worklist
1217     // mechanics for us, we have no work to do in this case.
1218     if (RV.getNode() == N)
1219       continue;
1220
1221     assert(N->getOpcode() != ISD::DELETED_NODE &&
1222            RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1223            "Node was deleted but visit returned new node!");
1224
1225     DEBUG(dbgs() << " ... into: ";
1226           RV.getNode()->dump(&DAG));
1227
1228     // Transfer debug value.
1229     DAG.TransferDbgValues(SDValue(N, 0), RV);
1230     if (N->getNumValues() == RV.getNode()->getNumValues())
1231       DAG.ReplaceAllUsesWith(N, RV.getNode());
1232     else {
1233       assert(N->getValueType(0) == RV.getValueType() &&
1234              N->getNumValues() == 1 && "Type mismatch");
1235       SDValue OpV = RV;
1236       DAG.ReplaceAllUsesWith(N, &OpV);
1237     }
1238
1239     // Push the new node and any users onto the worklist
1240     AddToWorklist(RV.getNode());
1241     AddUsersToWorklist(RV.getNode());
1242
1243     // Finally, if the node is now dead, remove it from the graph.  The node
1244     // may not be dead if the replacement process recursively simplified to
1245     // something else needing this node. This will also take care of adding any
1246     // operands which have lost a user to the worklist.
1247     recursivelyDeleteUnusedNodes(N);
1248   }
1249
1250   // If the root changed (e.g. it was a dead load, update the root).
1251   DAG.setRoot(Dummy.getValue());
1252   DAG.RemoveDeadNodes();
1253 }
1254
1255 SDValue DAGCombiner::visit(SDNode *N) {
1256   switch (N->getOpcode()) {
1257   default: break;
1258   case ISD::TokenFactor:        return visitTokenFactor(N);
1259   case ISD::MERGE_VALUES:       return visitMERGE_VALUES(N);
1260   case ISD::ADD:                return visitADD(N);
1261   case ISD::SUB:                return visitSUB(N);
1262   case ISD::ADDC:               return visitADDC(N);
1263   case ISD::SUBC:               return visitSUBC(N);
1264   case ISD::ADDE:               return visitADDE(N);
1265   case ISD::SUBE:               return visitSUBE(N);
1266   case ISD::MUL:                return visitMUL(N);
1267   case ISD::SDIV:               return visitSDIV(N);
1268   case ISD::UDIV:               return visitUDIV(N);
1269   case ISD::SREM:               return visitSREM(N);
1270   case ISD::UREM:               return visitUREM(N);
1271   case ISD::MULHU:              return visitMULHU(N);
1272   case ISD::MULHS:              return visitMULHS(N);
1273   case ISD::SMUL_LOHI:          return visitSMUL_LOHI(N);
1274   case ISD::UMUL_LOHI:          return visitUMUL_LOHI(N);
1275   case ISD::SMULO:              return visitSMULO(N);
1276   case ISD::UMULO:              return visitUMULO(N);
1277   case ISD::SDIVREM:            return visitSDIVREM(N);
1278   case ISD::UDIVREM:            return visitUDIVREM(N);
1279   case ISD::AND:                return visitAND(N);
1280   case ISD::OR:                 return visitOR(N);
1281   case ISD::XOR:                return visitXOR(N);
1282   case ISD::SHL:                return visitSHL(N);
1283   case ISD::SRA:                return visitSRA(N);
1284   case ISD::SRL:                return visitSRL(N);
1285   case ISD::ROTR:
1286   case ISD::ROTL:               return visitRotate(N);
1287   case ISD::CTLZ:               return visitCTLZ(N);
1288   case ISD::CTLZ_ZERO_UNDEF:    return visitCTLZ_ZERO_UNDEF(N);
1289   case ISD::CTTZ:               return visitCTTZ(N);
1290   case ISD::CTTZ_ZERO_UNDEF:    return visitCTTZ_ZERO_UNDEF(N);
1291   case ISD::CTPOP:              return visitCTPOP(N);
1292   case ISD::SELECT:             return visitSELECT(N);
1293   case ISD::VSELECT:            return visitVSELECT(N);
1294   case ISD::SELECT_CC:          return visitSELECT_CC(N);
1295   case ISD::SETCC:              return visitSETCC(N);
1296   case ISD::SIGN_EXTEND:        return visitSIGN_EXTEND(N);
1297   case ISD::ZERO_EXTEND:        return visitZERO_EXTEND(N);
1298   case ISD::ANY_EXTEND:         return visitANY_EXTEND(N);
1299   case ISD::SIGN_EXTEND_INREG:  return visitSIGN_EXTEND_INREG(N);
1300   case ISD::TRUNCATE:           return visitTRUNCATE(N);
1301   case ISD::BITCAST:            return visitBITCAST(N);
1302   case ISD::BUILD_PAIR:         return visitBUILD_PAIR(N);
1303   case ISD::FADD:               return visitFADD(N);
1304   case ISD::FSUB:               return visitFSUB(N);
1305   case ISD::FMUL:               return visitFMUL(N);
1306   case ISD::FMA:                return visitFMA(N);
1307   case ISD::FDIV:               return visitFDIV(N);
1308   case ISD::FREM:               return visitFREM(N);
1309   case ISD::FCOPYSIGN:          return visitFCOPYSIGN(N);
1310   case ISD::SINT_TO_FP:         return visitSINT_TO_FP(N);
1311   case ISD::UINT_TO_FP:         return visitUINT_TO_FP(N);
1312   case ISD::FP_TO_SINT:         return visitFP_TO_SINT(N);
1313   case ISD::FP_TO_UINT:         return visitFP_TO_UINT(N);
1314   case ISD::FP_ROUND:           return visitFP_ROUND(N);
1315   case ISD::FP_ROUND_INREG:     return visitFP_ROUND_INREG(N);
1316   case ISD::FP_EXTEND:          return visitFP_EXTEND(N);
1317   case ISD::FNEG:               return visitFNEG(N);
1318   case ISD::FABS:               return visitFABS(N);
1319   case ISD::FFLOOR:             return visitFFLOOR(N);
1320   case ISD::FCEIL:              return visitFCEIL(N);
1321   case ISD::FTRUNC:             return visitFTRUNC(N);
1322   case ISD::BRCOND:             return visitBRCOND(N);
1323   case ISD::BR_CC:              return visitBR_CC(N);
1324   case ISD::LOAD:               return visitLOAD(N);
1325   case ISD::STORE:              return visitSTORE(N);
1326   case ISD::INSERT_VECTOR_ELT:  return visitINSERT_VECTOR_ELT(N);
1327   case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1328   case ISD::BUILD_VECTOR:       return visitBUILD_VECTOR(N);
1329   case ISD::CONCAT_VECTORS:     return visitCONCAT_VECTORS(N);
1330   case ISD::EXTRACT_SUBVECTOR:  return visitEXTRACT_SUBVECTOR(N);
1331   case ISD::VECTOR_SHUFFLE:     return visitVECTOR_SHUFFLE(N);
1332   case ISD::INSERT_SUBVECTOR:   return visitINSERT_SUBVECTOR(N);
1333   }
1334   return SDValue();
1335 }
1336
1337 SDValue DAGCombiner::combine(SDNode *N) {
1338   SDValue RV = visit(N);
1339
1340   // If nothing happened, try a target-specific DAG combine.
1341   if (!RV.getNode()) {
1342     assert(N->getOpcode() != ISD::DELETED_NODE &&
1343            "Node was deleted but visit returned NULL!");
1344
1345     if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1346         TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1347
1348       // Expose the DAG combiner to the target combiner impls.
1349       TargetLowering::DAGCombinerInfo
1350         DagCombineInfo(DAG, Level, false, this);
1351
1352       RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1353     }
1354   }
1355
1356   // If nothing happened still, try promoting the operation.
1357   if (!RV.getNode()) {
1358     switch (N->getOpcode()) {
1359     default: break;
1360     case ISD::ADD:
1361     case ISD::SUB:
1362     case ISD::MUL:
1363     case ISD::AND:
1364     case ISD::OR:
1365     case ISD::XOR:
1366       RV = PromoteIntBinOp(SDValue(N, 0));
1367       break;
1368     case ISD::SHL:
1369     case ISD::SRA:
1370     case ISD::SRL:
1371       RV = PromoteIntShiftOp(SDValue(N, 0));
1372       break;
1373     case ISD::SIGN_EXTEND:
1374     case ISD::ZERO_EXTEND:
1375     case ISD::ANY_EXTEND:
1376       RV = PromoteExtend(SDValue(N, 0));
1377       break;
1378     case ISD::LOAD:
1379       if (PromoteLoad(SDValue(N, 0)))
1380         RV = SDValue(N, 0);
1381       break;
1382     }
1383   }
1384
1385   // If N is a commutative binary node, try commuting it to enable more
1386   // sdisel CSE.
1387   if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1388       N->getNumValues() == 1) {
1389     SDValue N0 = N->getOperand(0);
1390     SDValue N1 = N->getOperand(1);
1391
1392     // Constant operands are canonicalized to RHS.
1393     if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1394       SDValue Ops[] = {N1, N0};
1395       SDNode *CSENode;
1396       if (const BinaryWithFlagsSDNode *BinNode =
1397               dyn_cast<BinaryWithFlagsSDNode>(N)) {
1398         CSENode = DAG.getNodeIfExists(
1399             N->getOpcode(), N->getVTList(), Ops, BinNode->hasNoUnsignedWrap(),
1400             BinNode->hasNoSignedWrap(), BinNode->isExact());
1401       } else {
1402         CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops);
1403       }
1404       if (CSENode)
1405         return SDValue(CSENode, 0);
1406     }
1407   }
1408
1409   return RV;
1410 }
1411
1412 /// Given a node, return its input chain if it has one, otherwise return a null
1413 /// sd operand.
1414 static SDValue getInputChainForNode(SDNode *N) {
1415   if (unsigned NumOps = N->getNumOperands()) {
1416     if (N->getOperand(0).getValueType() == MVT::Other)
1417       return N->getOperand(0);
1418     if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1419       return N->getOperand(NumOps-1);
1420     for (unsigned i = 1; i < NumOps-1; ++i)
1421       if (N->getOperand(i).getValueType() == MVT::Other)
1422         return N->getOperand(i);
1423   }
1424   return SDValue();
1425 }
1426
1427 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1428   // If N has two operands, where one has an input chain equal to the other,
1429   // the 'other' chain is redundant.
1430   if (N->getNumOperands() == 2) {
1431     if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1432       return N->getOperand(0);
1433     if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1434       return N->getOperand(1);
1435   }
1436
1437   SmallVector<SDNode *, 8> TFs;     // List of token factors to visit.
1438   SmallVector<SDValue, 8> Ops;    // Ops for replacing token factor.
1439   SmallPtrSet<SDNode*, 16> SeenOps;
1440   bool Changed = false;             // If we should replace this token factor.
1441
1442   // Start out with this token factor.
1443   TFs.push_back(N);
1444
1445   // Iterate through token factors.  The TFs grows when new token factors are
1446   // encountered.
1447   for (unsigned i = 0; i < TFs.size(); ++i) {
1448     SDNode *TF = TFs[i];
1449
1450     // Check each of the operands.
1451     for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
1452       SDValue Op = TF->getOperand(i);
1453
1454       switch (Op.getOpcode()) {
1455       case ISD::EntryToken:
1456         // Entry tokens don't need to be added to the list. They are
1457         // rededundant.
1458         Changed = true;
1459         break;
1460
1461       case ISD::TokenFactor:
1462         if (Op.hasOneUse() &&
1463             std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1464           // Queue up for processing.
1465           TFs.push_back(Op.getNode());
1466           // Clean up in case the token factor is removed.
1467           AddToWorklist(Op.getNode());
1468           Changed = true;
1469           break;
1470         }
1471         // Fall thru
1472
1473       default:
1474         // Only add if it isn't already in the list.
1475         if (SeenOps.insert(Op.getNode()))
1476           Ops.push_back(Op);
1477         else
1478           Changed = true;
1479         break;
1480       }
1481     }
1482   }
1483
1484   SDValue Result;
1485
1486   // If we've change things around then replace token factor.
1487   if (Changed) {
1488     if (Ops.empty()) {
1489       // The entry token is the only possible outcome.
1490       Result = DAG.getEntryNode();
1491     } else {
1492       // New and improved token factor.
1493       Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
1494     }
1495
1496     // Don't add users to work list.
1497     return CombineTo(N, Result, false);
1498   }
1499
1500   return Result;
1501 }
1502
1503 /// MERGE_VALUES can always be eliminated.
1504 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1505   WorklistRemover DeadNodes(*this);
1506   // Replacing results may cause a different MERGE_VALUES to suddenly
1507   // be CSE'd with N, and carry its uses with it. Iterate until no
1508   // uses remain, to ensure that the node can be safely deleted.
1509   // First add the users of this node to the work list so that they
1510   // can be tried again once they have new operands.
1511   AddUsersToWorklist(N);
1512   do {
1513     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1514       DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1515   } while (!N->use_empty());
1516   deleteAndRecombine(N);
1517   return SDValue(N, 0);   // Return N so it doesn't get rechecked!
1518 }
1519
1520 static
1521 SDValue combineShlAddConstant(SDLoc DL, SDValue N0, SDValue N1,
1522                               SelectionDAG &DAG) {
1523   EVT VT = N0.getValueType();
1524   SDValue N00 = N0.getOperand(0);
1525   SDValue N01 = N0.getOperand(1);
1526   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N01);
1527
1528   if (N01C && N00.getOpcode() == ISD::ADD && N00.getNode()->hasOneUse() &&
1529       isa<ConstantSDNode>(N00.getOperand(1))) {
1530     // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1531     N0 = DAG.getNode(ISD::ADD, SDLoc(N0), VT,
1532                      DAG.getNode(ISD::SHL, SDLoc(N00), VT,
1533                                  N00.getOperand(0), N01),
1534                      DAG.getNode(ISD::SHL, SDLoc(N01), VT,
1535                                  N00.getOperand(1), N01));
1536     return DAG.getNode(ISD::ADD, DL, VT, N0, N1);
1537   }
1538
1539   return SDValue();
1540 }
1541
1542 SDValue DAGCombiner::visitADD(SDNode *N) {
1543   SDValue N0 = N->getOperand(0);
1544   SDValue N1 = N->getOperand(1);
1545   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1546   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1547   EVT VT = N0.getValueType();
1548
1549   // fold vector ops
1550   if (VT.isVector()) {
1551     SDValue FoldedVOp = SimplifyVBinOp(N);
1552     if (FoldedVOp.getNode()) return FoldedVOp;
1553
1554     // fold (add x, 0) -> x, vector edition
1555     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1556       return N0;
1557     if (ISD::isBuildVectorAllZeros(N0.getNode()))
1558       return N1;
1559   }
1560
1561   // fold (add x, undef) -> undef
1562   if (N0.getOpcode() == ISD::UNDEF)
1563     return N0;
1564   if (N1.getOpcode() == ISD::UNDEF)
1565     return N1;
1566   // fold (add c1, c2) -> c1+c2
1567   if (N0C && N1C)
1568     return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C);
1569   // canonicalize constant to RHS
1570   if (N0C && !N1C)
1571     return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
1572   // fold (add x, 0) -> x
1573   if (N1C && N1C->isNullValue())
1574     return N0;
1575   // fold (add Sym, c) -> Sym+c
1576   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1577     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1578         GA->getOpcode() == ISD::GlobalAddress)
1579       return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1580                                   GA->getOffset() +
1581                                     (uint64_t)N1C->getSExtValue());
1582   // fold ((c1-A)+c2) -> (c1+c2)-A
1583   if (N1C && N0.getOpcode() == ISD::SUB)
1584     if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
1585       return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1586                          DAG.getConstant(N1C->getAPIntValue()+
1587                                          N0C->getAPIntValue(), VT),
1588                          N0.getOperand(1));
1589   // reassociate add
1590   SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1);
1591   if (RADD.getNode())
1592     return RADD;
1593   // fold ((0-A) + B) -> B-A
1594   if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
1595       cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
1596     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
1597   // fold (A + (0-B)) -> A-B
1598   if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1599       cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
1600     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
1601   // fold (A+(B-A)) -> B
1602   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1603     return N1.getOperand(0);
1604   // fold ((B-A)+A) -> B
1605   if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1606     return N0.getOperand(0);
1607   // fold (A+(B-(A+C))) to (B-C)
1608   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1609       N0 == N1.getOperand(1).getOperand(0))
1610     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1611                        N1.getOperand(1).getOperand(1));
1612   // fold (A+(B-(C+A))) to (B-C)
1613   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1614       N0 == N1.getOperand(1).getOperand(1))
1615     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1616                        N1.getOperand(1).getOperand(0));
1617   // fold (A+((B-A)+or-C)) to (B+or-C)
1618   if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1619       N1.getOperand(0).getOpcode() == ISD::SUB &&
1620       N0 == N1.getOperand(0).getOperand(1))
1621     return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
1622                        N1.getOperand(0).getOperand(0), N1.getOperand(1));
1623
1624   // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1625   if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1626     SDValue N00 = N0.getOperand(0);
1627     SDValue N01 = N0.getOperand(1);
1628     SDValue N10 = N1.getOperand(0);
1629     SDValue N11 = N1.getOperand(1);
1630
1631     if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1632       return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1633                          DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1634                          DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1635   }
1636
1637   if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1638     return SDValue(N, 0);
1639
1640   // fold (a+b) -> (a|b) iff a and b share no bits.
1641   if (VT.isInteger() && !VT.isVector()) {
1642     APInt LHSZero, LHSOne;
1643     APInt RHSZero, RHSOne;
1644     DAG.computeKnownBits(N0, LHSZero, LHSOne);
1645
1646     if (LHSZero.getBoolValue()) {
1647       DAG.computeKnownBits(N1, RHSZero, RHSOne);
1648
1649       // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1650       // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1651       if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){
1652         if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT))
1653           return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1654       }
1655     }
1656   }
1657
1658   // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1659   if (N0.getOpcode() == ISD::SHL && N0.getNode()->hasOneUse()) {
1660     SDValue Result = combineShlAddConstant(SDLoc(N), N0, N1, DAG);
1661     if (Result.getNode()) return Result;
1662   }
1663   if (N1.getOpcode() == ISD::SHL && N1.getNode()->hasOneUse()) {
1664     SDValue Result = combineShlAddConstant(SDLoc(N), N1, N0, DAG);
1665     if (Result.getNode()) return Result;
1666   }
1667
1668   // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1669   if (N1.getOpcode() == ISD::SHL &&
1670       N1.getOperand(0).getOpcode() == ISD::SUB)
1671     if (ConstantSDNode *C =
1672           dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
1673       if (C->getAPIntValue() == 0)
1674         return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1675                            DAG.getNode(ISD::SHL, SDLoc(N), VT,
1676                                        N1.getOperand(0).getOperand(1),
1677                                        N1.getOperand(1)));
1678   if (N0.getOpcode() == ISD::SHL &&
1679       N0.getOperand(0).getOpcode() == ISD::SUB)
1680     if (ConstantSDNode *C =
1681           dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
1682       if (C->getAPIntValue() == 0)
1683         return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1684                            DAG.getNode(ISD::SHL, SDLoc(N), VT,
1685                                        N0.getOperand(0).getOperand(1),
1686                                        N0.getOperand(1)));
1687
1688   if (N1.getOpcode() == ISD::AND) {
1689     SDValue AndOp0 = N1.getOperand(0);
1690     ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1));
1691     unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1692     unsigned DestBits = VT.getScalarType().getSizeInBits();
1693
1694     // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1695     // and similar xforms where the inner op is either ~0 or 0.
1696     if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) {
1697       SDLoc DL(N);
1698       return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1699     }
1700   }
1701
1702   // add (sext i1), X -> sub X, (zext i1)
1703   if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1704       N0.getOperand(0).getValueType() == MVT::i1 &&
1705       !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1706     SDLoc DL(N);
1707     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1708     return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1709   }
1710
1711   return SDValue();
1712 }
1713
1714 SDValue DAGCombiner::visitADDC(SDNode *N) {
1715   SDValue N0 = N->getOperand(0);
1716   SDValue N1 = N->getOperand(1);
1717   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1718   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1719   EVT VT = N0.getValueType();
1720
1721   // If the flag result is dead, turn this into an ADD.
1722   if (!N->hasAnyUseOfValue(1))
1723     return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1724                      DAG.getNode(ISD::CARRY_FALSE,
1725                                  SDLoc(N), MVT::Glue));
1726
1727   // canonicalize constant to RHS.
1728   if (N0C && !N1C)
1729     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1730
1731   // fold (addc x, 0) -> x + no carry out
1732   if (N1C && N1C->isNullValue())
1733     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1734                                         SDLoc(N), MVT::Glue));
1735
1736   // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1737   APInt LHSZero, LHSOne;
1738   APInt RHSZero, RHSOne;
1739   DAG.computeKnownBits(N0, LHSZero, LHSOne);
1740
1741   if (LHSZero.getBoolValue()) {
1742     DAG.computeKnownBits(N1, RHSZero, RHSOne);
1743
1744     // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1745     // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1746     if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1747       return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1748                        DAG.getNode(ISD::CARRY_FALSE,
1749                                    SDLoc(N), MVT::Glue));
1750   }
1751
1752   return SDValue();
1753 }
1754
1755 SDValue DAGCombiner::visitADDE(SDNode *N) {
1756   SDValue N0 = N->getOperand(0);
1757   SDValue N1 = N->getOperand(1);
1758   SDValue CarryIn = N->getOperand(2);
1759   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1760   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1761
1762   // canonicalize constant to RHS
1763   if (N0C && !N1C)
1764     return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1765                        N1, N0, CarryIn);
1766
1767   // fold (adde x, y, false) -> (addc x, y)
1768   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1769     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1770
1771   return SDValue();
1772 }
1773
1774 // Since it may not be valid to emit a fold to zero for vector initializers
1775 // check if we can before folding.
1776 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
1777                              SelectionDAG &DAG,
1778                              bool LegalOperations, bool LegalTypes) {
1779   if (!VT.isVector())
1780     return DAG.getConstant(0, VT);
1781   if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1782     return DAG.getConstant(0, VT);
1783   return SDValue();
1784 }
1785
1786 SDValue DAGCombiner::visitSUB(SDNode *N) {
1787   SDValue N0 = N->getOperand(0);
1788   SDValue N1 = N->getOperand(1);
1789   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1790   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1791   ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr :
1792     dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1793   EVT VT = N0.getValueType();
1794
1795   // fold vector ops
1796   if (VT.isVector()) {
1797     SDValue FoldedVOp = SimplifyVBinOp(N);
1798     if (FoldedVOp.getNode()) return FoldedVOp;
1799
1800     // fold (sub x, 0) -> x, vector edition
1801     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1802       return N0;
1803   }
1804
1805   // fold (sub x, x) -> 0
1806   // FIXME: Refactor this and xor and other similar operations together.
1807   if (N0 == N1)
1808     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
1809   // fold (sub c1, c2) -> c1-c2
1810   if (N0C && N1C)
1811     return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C);
1812   // fold (sub x, c) -> (add x, -c)
1813   if (N1C)
1814     return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0,
1815                        DAG.getConstant(-N1C->getAPIntValue(), VT));
1816   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1817   if (N0C && N0C->isAllOnesValue())
1818     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
1819   // fold A-(A-B) -> B
1820   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1821     return N1.getOperand(1);
1822   // fold (A+B)-A -> B
1823   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1824     return N0.getOperand(1);
1825   // fold (A+B)-B -> A
1826   if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1827     return N0.getOperand(0);
1828   // fold C2-(A+C1) -> (C2-C1)-A
1829   if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1830     SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1831                                    VT);
1832     return DAG.getNode(ISD::SUB, SDLoc(N), VT, NewC,
1833                        N1.getOperand(0));
1834   }
1835   // fold ((A+(B+or-C))-B) -> A+or-C
1836   if (N0.getOpcode() == ISD::ADD &&
1837       (N0.getOperand(1).getOpcode() == ISD::SUB ||
1838        N0.getOperand(1).getOpcode() == ISD::ADD) &&
1839       N0.getOperand(1).getOperand(0) == N1)
1840     return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
1841                        N0.getOperand(0), N0.getOperand(1).getOperand(1));
1842   // fold ((A+(C+B))-B) -> A+C
1843   if (N0.getOpcode() == ISD::ADD &&
1844       N0.getOperand(1).getOpcode() == ISD::ADD &&
1845       N0.getOperand(1).getOperand(1) == N1)
1846     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1847                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1848   // fold ((A-(B-C))-C) -> A-B
1849   if (N0.getOpcode() == ISD::SUB &&
1850       N0.getOperand(1).getOpcode() == ISD::SUB &&
1851       N0.getOperand(1).getOperand(1) == N1)
1852     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1853                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1854
1855   // If either operand of a sub is undef, the result is undef
1856   if (N0.getOpcode() == ISD::UNDEF)
1857     return N0;
1858   if (N1.getOpcode() == ISD::UNDEF)
1859     return N1;
1860
1861   // If the relocation model supports it, consider symbol offsets.
1862   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1863     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1864       // fold (sub Sym, c) -> Sym-c
1865       if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1866         return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1867                                     GA->getOffset() -
1868                                       (uint64_t)N1C->getSExtValue());
1869       // fold (sub Sym+c1, Sym+c2) -> c1-c2
1870       if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1871         if (GA->getGlobal() == GB->getGlobal())
1872           return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1873                                  VT);
1874     }
1875
1876   return SDValue();
1877 }
1878
1879 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1880   SDValue N0 = N->getOperand(0);
1881   SDValue N1 = N->getOperand(1);
1882   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1883   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1884   EVT VT = N0.getValueType();
1885
1886   // If the flag result is dead, turn this into an SUB.
1887   if (!N->hasAnyUseOfValue(1))
1888     return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1889                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1890                                  MVT::Glue));
1891
1892   // fold (subc x, x) -> 0 + no borrow
1893   if (N0 == N1)
1894     return CombineTo(N, DAG.getConstant(0, VT),
1895                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1896                                  MVT::Glue));
1897
1898   // fold (subc x, 0) -> x + no borrow
1899   if (N1C && N1C->isNullValue())
1900     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1901                                         MVT::Glue));
1902
1903   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1904   if (N0C && N0C->isAllOnesValue())
1905     return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
1906                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1907                                  MVT::Glue));
1908
1909   return SDValue();
1910 }
1911
1912 SDValue DAGCombiner::visitSUBE(SDNode *N) {
1913   SDValue N0 = N->getOperand(0);
1914   SDValue N1 = N->getOperand(1);
1915   SDValue CarryIn = N->getOperand(2);
1916
1917   // fold (sube x, y, false) -> (subc x, y)
1918   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1919     return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
1920
1921   return SDValue();
1922 }
1923
1924 SDValue DAGCombiner::visitMUL(SDNode *N) {
1925   SDValue N0 = N->getOperand(0);
1926   SDValue N1 = N->getOperand(1);
1927   EVT VT = N0.getValueType();
1928
1929   // fold (mul x, undef) -> 0
1930   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1931     return DAG.getConstant(0, VT);
1932
1933   bool N0IsConst = false;
1934   bool N1IsConst = false;
1935   APInt ConstValue0, ConstValue1;
1936   // fold vector ops
1937   if (VT.isVector()) {
1938     SDValue FoldedVOp = SimplifyVBinOp(N);
1939     if (FoldedVOp.getNode()) return FoldedVOp;
1940
1941     N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
1942     N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
1943   } else {
1944     N0IsConst = dyn_cast<ConstantSDNode>(N0) != nullptr;
1945     ConstValue0 = N0IsConst ? (dyn_cast<ConstantSDNode>(N0))->getAPIntValue()
1946                             : APInt();
1947     N1IsConst = dyn_cast<ConstantSDNode>(N1) != nullptr;
1948     ConstValue1 = N1IsConst ? (dyn_cast<ConstantSDNode>(N1))->getAPIntValue()
1949                             : APInt();
1950   }
1951
1952   // fold (mul c1, c2) -> c1*c2
1953   if (N0IsConst && N1IsConst)
1954     return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0.getNode(), N1.getNode());
1955
1956   // canonicalize constant to RHS
1957   if (N0IsConst && !N1IsConst)
1958     return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
1959   // fold (mul x, 0) -> 0
1960   if (N1IsConst && ConstValue1 == 0)
1961     return N1;
1962   // We require a splat of the entire scalar bit width for non-contiguous
1963   // bit patterns.
1964   bool IsFullSplat =
1965     ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
1966   // fold (mul x, 1) -> x
1967   if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
1968     return N0;
1969   // fold (mul x, -1) -> 0-x
1970   if (N1IsConst && ConstValue1.isAllOnesValue())
1971     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1972                        DAG.getConstant(0, VT), N0);
1973   // fold (mul x, (1 << c)) -> x << c
1974   if (N1IsConst && ConstValue1.isPowerOf2() && IsFullSplat)
1975     return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1976                        DAG.getConstant(ConstValue1.logBase2(),
1977                                        getShiftAmountTy(N0.getValueType())));
1978   // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
1979   if (N1IsConst && (-ConstValue1).isPowerOf2() && IsFullSplat) {
1980     unsigned Log2Val = (-ConstValue1).logBase2();
1981     // FIXME: If the input is something that is easily negated (e.g. a
1982     // single-use add), we should put the negate there.
1983     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1984                        DAG.getConstant(0, VT),
1985                        DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1986                             DAG.getConstant(Log2Val,
1987                                       getShiftAmountTy(N0.getValueType()))));
1988   }
1989
1990   APInt Val;
1991   // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
1992   if (N1IsConst && N0.getOpcode() == ISD::SHL &&
1993       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1994                      isa<ConstantSDNode>(N0.getOperand(1)))) {
1995     SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
1996                              N1, N0.getOperand(1));
1997     AddToWorklist(C3.getNode());
1998     return DAG.getNode(ISD::MUL, SDLoc(N), VT,
1999                        N0.getOperand(0), C3);
2000   }
2001
2002   // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
2003   // use.
2004   {
2005     SDValue Sh(nullptr,0), Y(nullptr,0);
2006     // Check for both (mul (shl X, C), Y)  and  (mul Y, (shl X, C)).
2007     if (N0.getOpcode() == ISD::SHL &&
2008         (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2009                        isa<ConstantSDNode>(N0.getOperand(1))) &&
2010         N0.getNode()->hasOneUse()) {
2011       Sh = N0; Y = N1;
2012     } else if (N1.getOpcode() == ISD::SHL &&
2013                isa<ConstantSDNode>(N1.getOperand(1)) &&
2014                N1.getNode()->hasOneUse()) {
2015       Sh = N1; Y = N0;
2016     }
2017
2018     if (Sh.getNode()) {
2019       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2020                                 Sh.getOperand(0), Y);
2021       return DAG.getNode(ISD::SHL, SDLoc(N), VT,
2022                          Mul, Sh.getOperand(1));
2023     }
2024   }
2025
2026   // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
2027   if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
2028       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2029                      isa<ConstantSDNode>(N0.getOperand(1))))
2030     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
2031                        DAG.getNode(ISD::MUL, SDLoc(N0), VT,
2032                                    N0.getOperand(0), N1),
2033                        DAG.getNode(ISD::MUL, SDLoc(N1), VT,
2034                                    N0.getOperand(1), N1));
2035
2036   // reassociate mul
2037   SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1);
2038   if (RMUL.getNode())
2039     return RMUL;
2040
2041   return SDValue();
2042 }
2043
2044 SDValue DAGCombiner::visitSDIV(SDNode *N) {
2045   SDValue N0 = N->getOperand(0);
2046   SDValue N1 = N->getOperand(1);
2047   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2048   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2049   EVT VT = N->getValueType(0);
2050
2051   // fold vector ops
2052   if (VT.isVector()) {
2053     SDValue FoldedVOp = SimplifyVBinOp(N);
2054     if (FoldedVOp.getNode()) return FoldedVOp;
2055   }
2056
2057   // fold (sdiv c1, c2) -> c1/c2
2058   if (N0C && N1C && !N1C->isNullValue())
2059     return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C);
2060   // fold (sdiv X, 1) -> X
2061   if (N1C && N1C->getAPIntValue() == 1LL)
2062     return N0;
2063   // fold (sdiv X, -1) -> 0-X
2064   if (N1C && N1C->isAllOnesValue())
2065     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
2066                        DAG.getConstant(0, VT), N0);
2067   // If we know the sign bits of both operands are zero, strength reduce to a
2068   // udiv instead.  Handles (X&15) /s 4 -> X&15 >> 2
2069   if (!VT.isVector()) {
2070     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2071       return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
2072                          N0, N1);
2073   }
2074
2075   // fold (sdiv X, pow2) -> simple ops after legalize
2076   if (N1C && !N1C->isNullValue() && (N1C->getAPIntValue().isPowerOf2() ||
2077                                      (-N1C->getAPIntValue()).isPowerOf2())) {
2078     // If dividing by powers of two is cheap, then don't perform the following
2079     // fold.
2080     if (TLI.isPow2SDivCheap())
2081       return SDValue();
2082
2083     // Target-specific implementation of sdiv x, pow2.
2084     SDValue Res = BuildSDIVPow2(N);
2085     if (Res.getNode())
2086       return Res;
2087
2088     unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
2089
2090     // Splat the sign bit into the register
2091     SDValue SGN =
2092         DAG.getNode(ISD::SRA, SDLoc(N), VT, N0,
2093                     DAG.getConstant(VT.getScalarSizeInBits() - 1,
2094                                     getShiftAmountTy(N0.getValueType())));
2095     AddToWorklist(SGN.getNode());
2096
2097     // Add (N0 < 0) ? abs2 - 1 : 0;
2098     SDValue SRL =
2099         DAG.getNode(ISD::SRL, SDLoc(N), VT, SGN,
2100                     DAG.getConstant(VT.getScalarSizeInBits() - lg2,
2101                                     getShiftAmountTy(SGN.getValueType())));
2102     SDValue ADD = DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, SRL);
2103     AddToWorklist(SRL.getNode());
2104     AddToWorklist(ADD.getNode());    // Divide by pow2
2105     SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), VT, ADD,
2106                   DAG.getConstant(lg2, getShiftAmountTy(ADD.getValueType())));
2107
2108     // If we're dividing by a positive value, we're done.  Otherwise, we must
2109     // negate the result.
2110     if (N1C->getAPIntValue().isNonNegative())
2111       return SRA;
2112
2113     AddToWorklist(SRA.getNode());
2114     return DAG.getNode(ISD::SUB, SDLoc(N), VT, DAG.getConstant(0, VT), SRA);
2115   }
2116
2117   // if integer divide is expensive and we satisfy the requirements, emit an
2118   // alternate sequence.
2119   if (N1C && !TLI.isIntDivCheap()) {
2120     SDValue Op = BuildSDIV(N);
2121     if (Op.getNode()) return Op;
2122   }
2123
2124   // undef / X -> 0
2125   if (N0.getOpcode() == ISD::UNDEF)
2126     return DAG.getConstant(0, VT);
2127   // X / undef -> undef
2128   if (N1.getOpcode() == ISD::UNDEF)
2129     return N1;
2130
2131   return SDValue();
2132 }
2133
2134 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2135   SDValue N0 = N->getOperand(0);
2136   SDValue N1 = N->getOperand(1);
2137   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2138   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2139   EVT VT = N->getValueType(0);
2140
2141   // fold vector ops
2142   if (VT.isVector()) {
2143     SDValue FoldedVOp = SimplifyVBinOp(N);
2144     if (FoldedVOp.getNode()) return FoldedVOp;
2145   }
2146
2147   // fold (udiv c1, c2) -> c1/c2
2148   if (N0C && N1C && !N1C->isNullValue())
2149     return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C);
2150   // fold (udiv x, (1 << c)) -> x >>u c
2151   if (N1C && N1C->getAPIntValue().isPowerOf2())
2152     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0,
2153                        DAG.getConstant(N1C->getAPIntValue().logBase2(),
2154                                        getShiftAmountTy(N0.getValueType())));
2155   // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2156   if (N1.getOpcode() == ISD::SHL) {
2157     if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2158       if (SHC->getAPIntValue().isPowerOf2()) {
2159         EVT ADDVT = N1.getOperand(1).getValueType();
2160         SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N), ADDVT,
2161                                   N1.getOperand(1),
2162                                   DAG.getConstant(SHC->getAPIntValue()
2163                                                                   .logBase2(),
2164                                                   ADDVT));
2165         AddToWorklist(Add.getNode());
2166         return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, Add);
2167       }
2168     }
2169   }
2170   // fold (udiv x, c) -> alternate
2171   if (N1C && !TLI.isIntDivCheap()) {
2172     SDValue Op = BuildUDIV(N);
2173     if (Op.getNode()) return Op;
2174   }
2175
2176   // undef / X -> 0
2177   if (N0.getOpcode() == ISD::UNDEF)
2178     return DAG.getConstant(0, VT);
2179   // X / undef -> undef
2180   if (N1.getOpcode() == ISD::UNDEF)
2181     return N1;
2182
2183   return SDValue();
2184 }
2185
2186 SDValue DAGCombiner::visitSREM(SDNode *N) {
2187   SDValue N0 = N->getOperand(0);
2188   SDValue N1 = N->getOperand(1);
2189   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2190   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2191   EVT VT = N->getValueType(0);
2192
2193   // fold (srem c1, c2) -> c1%c2
2194   if (N0C && N1C && !N1C->isNullValue())
2195     return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C);
2196   // If we know the sign bits of both operands are zero, strength reduce to a
2197   // urem instead.  Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2198   if (!VT.isVector()) {
2199     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2200       return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
2201   }
2202
2203   // If X/C can be simplified by the division-by-constant logic, lower
2204   // X%C to the equivalent of X-X/C*C.
2205   if (N1C && !N1C->isNullValue()) {
2206     SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
2207     AddToWorklist(Div.getNode());
2208     SDValue OptimizedDiv = combine(Div.getNode());
2209     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2210       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2211                                 OptimizedDiv, N1);
2212       SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2213       AddToWorklist(Mul.getNode());
2214       return Sub;
2215     }
2216   }
2217
2218   // undef % X -> 0
2219   if (N0.getOpcode() == ISD::UNDEF)
2220     return DAG.getConstant(0, VT);
2221   // X % undef -> undef
2222   if (N1.getOpcode() == ISD::UNDEF)
2223     return N1;
2224
2225   return SDValue();
2226 }
2227
2228 SDValue DAGCombiner::visitUREM(SDNode *N) {
2229   SDValue N0 = N->getOperand(0);
2230   SDValue N1 = N->getOperand(1);
2231   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2232   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2233   EVT VT = N->getValueType(0);
2234
2235   // fold (urem c1, c2) -> c1%c2
2236   if (N0C && N1C && !N1C->isNullValue())
2237     return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C);
2238   // fold (urem x, pow2) -> (and x, pow2-1)
2239   if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
2240     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0,
2241                        DAG.getConstant(N1C->getAPIntValue()-1,VT));
2242   // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2243   if (N1.getOpcode() == ISD::SHL) {
2244     if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2245       if (SHC->getAPIntValue().isPowerOf2()) {
2246         SDValue Add =
2247           DAG.getNode(ISD::ADD, SDLoc(N), VT, N1,
2248                  DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
2249                                  VT));
2250         AddToWorklist(Add.getNode());
2251         return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, Add);
2252       }
2253     }
2254   }
2255
2256   // If X/C can be simplified by the division-by-constant logic, lower
2257   // X%C to the equivalent of X-X/C*C.
2258   if (N1C && !N1C->isNullValue()) {
2259     SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
2260     AddToWorklist(Div.getNode());
2261     SDValue OptimizedDiv = combine(Div.getNode());
2262     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2263       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2264                                 OptimizedDiv, N1);
2265       SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2266       AddToWorklist(Mul.getNode());
2267       return Sub;
2268     }
2269   }
2270
2271   // undef % X -> 0
2272   if (N0.getOpcode() == ISD::UNDEF)
2273     return DAG.getConstant(0, VT);
2274   // X % undef -> undef
2275   if (N1.getOpcode() == ISD::UNDEF)
2276     return N1;
2277
2278   return SDValue();
2279 }
2280
2281 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2282   SDValue N0 = N->getOperand(0);
2283   SDValue N1 = N->getOperand(1);
2284   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2285   EVT VT = N->getValueType(0);
2286   SDLoc DL(N);
2287
2288   // fold (mulhs x, 0) -> 0
2289   if (N1C && N1C->isNullValue())
2290     return N1;
2291   // fold (mulhs x, 1) -> (sra x, size(x)-1)
2292   if (N1C && N1C->getAPIntValue() == 1)
2293     return DAG.getNode(ISD::SRA, SDLoc(N), N0.getValueType(), N0,
2294                        DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2295                                        getShiftAmountTy(N0.getValueType())));
2296   // fold (mulhs x, undef) -> 0
2297   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2298     return DAG.getConstant(0, VT);
2299
2300   // If the type twice as wide is legal, transform the mulhs to a wider multiply
2301   // plus a shift.
2302   if (VT.isSimple() && !VT.isVector()) {
2303     MVT Simple = VT.getSimpleVT();
2304     unsigned SimpleSize = Simple.getSizeInBits();
2305     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2306     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2307       N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2308       N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2309       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2310       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2311             DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2312       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2313     }
2314   }
2315
2316   return SDValue();
2317 }
2318
2319 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2320   SDValue N0 = N->getOperand(0);
2321   SDValue N1 = N->getOperand(1);
2322   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2323   EVT VT = N->getValueType(0);
2324   SDLoc DL(N);
2325
2326   // fold (mulhu x, 0) -> 0
2327   if (N1C && N1C->isNullValue())
2328     return N1;
2329   // fold (mulhu x, 1) -> 0
2330   if (N1C && N1C->getAPIntValue() == 1)
2331     return DAG.getConstant(0, N0.getValueType());
2332   // fold (mulhu x, undef) -> 0
2333   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2334     return DAG.getConstant(0, VT);
2335
2336   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2337   // plus a shift.
2338   if (VT.isSimple() && !VT.isVector()) {
2339     MVT Simple = VT.getSimpleVT();
2340     unsigned SimpleSize = Simple.getSizeInBits();
2341     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2342     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2343       N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2344       N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2345       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2346       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2347             DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2348       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2349     }
2350   }
2351
2352   return SDValue();
2353 }
2354
2355 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp
2356 /// give the opcodes for the two computations that are being performed. Return
2357 /// true if a simplification was made.
2358 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2359                                                 unsigned HiOp) {
2360   // If the high half is not needed, just compute the low half.
2361   bool HiExists = N->hasAnyUseOfValue(1);
2362   if (!HiExists &&
2363       (!LegalOperations ||
2364        TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
2365     SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2366     return CombineTo(N, Res, Res);
2367   }
2368
2369   // If the low half is not needed, just compute the high half.
2370   bool LoExists = N->hasAnyUseOfValue(0);
2371   if (!LoExists &&
2372       (!LegalOperations ||
2373        TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2374     SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2375     return CombineTo(N, Res, Res);
2376   }
2377
2378   // If both halves are used, return as it is.
2379   if (LoExists && HiExists)
2380     return SDValue();
2381
2382   // If the two computed results can be simplified separately, separate them.
2383   if (LoExists) {
2384     SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2385     AddToWorklist(Lo.getNode());
2386     SDValue LoOpt = combine(Lo.getNode());
2387     if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2388         (!LegalOperations ||
2389          TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2390       return CombineTo(N, LoOpt, LoOpt);
2391   }
2392
2393   if (HiExists) {
2394     SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2395     AddToWorklist(Hi.getNode());
2396     SDValue HiOpt = combine(Hi.getNode());
2397     if (HiOpt.getNode() && HiOpt != Hi &&
2398         (!LegalOperations ||
2399          TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2400       return CombineTo(N, HiOpt, HiOpt);
2401   }
2402
2403   return SDValue();
2404 }
2405
2406 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2407   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
2408   if (Res.getNode()) return Res;
2409
2410   EVT VT = N->getValueType(0);
2411   SDLoc DL(N);
2412
2413   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2414   // plus a shift.
2415   if (VT.isSimple() && !VT.isVector()) {
2416     MVT Simple = VT.getSimpleVT();
2417     unsigned SimpleSize = Simple.getSizeInBits();
2418     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2419     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2420       SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2421       SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2422       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2423       // Compute the high part as N1.
2424       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2425             DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2426       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2427       // Compute the low part as N0.
2428       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2429       return CombineTo(N, Lo, Hi);
2430     }
2431   }
2432
2433   return SDValue();
2434 }
2435
2436 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2437   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
2438   if (Res.getNode()) return Res;
2439
2440   EVT VT = N->getValueType(0);
2441   SDLoc DL(N);
2442
2443   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2444   // plus a shift.
2445   if (VT.isSimple() && !VT.isVector()) {
2446     MVT Simple = VT.getSimpleVT();
2447     unsigned SimpleSize = Simple.getSizeInBits();
2448     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2449     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2450       SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2451       SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2452       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2453       // Compute the high part as N1.
2454       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2455             DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2456       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2457       // Compute the low part as N0.
2458       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2459       return CombineTo(N, Lo, Hi);
2460     }
2461   }
2462
2463   return SDValue();
2464 }
2465
2466 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2467   // (smulo x, 2) -> (saddo x, x)
2468   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2469     if (C2->getAPIntValue() == 2)
2470       return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2471                          N->getOperand(0), N->getOperand(0));
2472
2473   return SDValue();
2474 }
2475
2476 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2477   // (umulo x, 2) -> (uaddo x, x)
2478   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2479     if (C2->getAPIntValue() == 2)
2480       return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2481                          N->getOperand(0), N->getOperand(0));
2482
2483   return SDValue();
2484 }
2485
2486 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2487   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
2488   if (Res.getNode()) return Res;
2489
2490   return SDValue();
2491 }
2492
2493 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2494   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
2495   if (Res.getNode()) return Res;
2496
2497   return SDValue();
2498 }
2499
2500 /// If this is a binary operator with two operands of the same opcode, try to
2501 /// simplify it.
2502 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2503   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2504   EVT VT = N0.getValueType();
2505   assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2506
2507   // Bail early if none of these transforms apply.
2508   if (N0.getNode()->getNumOperands() == 0) return SDValue();
2509
2510   // For each of OP in AND/OR/XOR:
2511   // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2512   // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2513   // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2514   // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2515   //
2516   // do not sink logical op inside of a vector extend, since it may combine
2517   // into a vsetcc.
2518   EVT Op0VT = N0.getOperand(0).getValueType();
2519   if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2520        N0.getOpcode() == ISD::SIGN_EXTEND ||
2521        // Avoid infinite looping with PromoteIntBinOp.
2522        (N0.getOpcode() == ISD::ANY_EXTEND &&
2523         (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2524        (N0.getOpcode() == ISD::TRUNCATE &&
2525         (!TLI.isZExtFree(VT, Op0VT) ||
2526          !TLI.isTruncateFree(Op0VT, VT)) &&
2527         TLI.isTypeLegal(Op0VT))) &&
2528       !VT.isVector() &&
2529       Op0VT == N1.getOperand(0).getValueType() &&
2530       (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2531     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2532                                  N0.getOperand(0).getValueType(),
2533                                  N0.getOperand(0), N1.getOperand(0));
2534     AddToWorklist(ORNode.getNode());
2535     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2536   }
2537
2538   // For each of OP in SHL/SRL/SRA/AND...
2539   //   fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2540   //   fold (or  (OP x, z), (OP y, z)) -> (OP (or  x, y), z)
2541   //   fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2542   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2543        N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2544       N0.getOperand(1) == N1.getOperand(1)) {
2545     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2546                                  N0.getOperand(0).getValueType(),
2547                                  N0.getOperand(0), N1.getOperand(0));
2548     AddToWorklist(ORNode.getNode());
2549     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2550                        ORNode, N0.getOperand(1));
2551   }
2552
2553   // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2554   // Only perform this optimization after type legalization and before
2555   // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2556   // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2557   // we don't want to undo this promotion.
2558   // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2559   // on scalars.
2560   if ((N0.getOpcode() == ISD::BITCAST ||
2561        N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2562       Level == AfterLegalizeTypes) {
2563     SDValue In0 = N0.getOperand(0);
2564     SDValue In1 = N1.getOperand(0);
2565     EVT In0Ty = In0.getValueType();
2566     EVT In1Ty = In1.getValueType();
2567     SDLoc DL(N);
2568     // If both incoming values are integers, and the original types are the
2569     // same.
2570     if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2571       SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2572       SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2573       AddToWorklist(Op.getNode());
2574       return BC;
2575     }
2576   }
2577
2578   // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2579   // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2580   // If both shuffles use the same mask, and both shuffle within a single
2581   // vector, then it is worthwhile to move the swizzle after the operation.
2582   // The type-legalizer generates this pattern when loading illegal
2583   // vector types from memory. In many cases this allows additional shuffle
2584   // optimizations.
2585   // There are other cases where moving the shuffle after the xor/and/or
2586   // is profitable even if shuffles don't perform a swizzle.
2587   // If both shuffles use the same mask, and both shuffles have the same first
2588   // or second operand, then it might still be profitable to move the shuffle
2589   // after the xor/and/or operation.
2590   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
2591     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2592     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2593
2594     assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
2595            "Inputs to shuffles are not the same type");
2596
2597     // Check that both shuffles use the same mask. The masks are known to be of
2598     // the same length because the result vector type is the same.
2599     // Check also that shuffles have only one use to avoid introducing extra
2600     // instructions.
2601     if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2602         SVN0->getMask().equals(SVN1->getMask())) {
2603       SDValue ShOp = N0->getOperand(1);
2604
2605       // Don't try to fold this node if it requires introducing a
2606       // build vector of all zeros that might be illegal at this stage.
2607       if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2608         if (!LegalTypes)
2609           ShOp = DAG.getConstant(0, VT);
2610         else
2611           ShOp = SDValue();
2612       }
2613
2614       // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2615       // (OR  (shuf (A, C), shuf (B, C)) -> shuf (OR  (A, B), C)
2616       // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2617       if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2618         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2619                                       N0->getOperand(0), N1->getOperand(0));
2620         AddToWorklist(NewNode.getNode());
2621         return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2622                                     &SVN0->getMask()[0]);
2623       }
2624
2625       // Don't try to fold this node if it requires introducing a
2626       // build vector of all zeros that might be illegal at this stage.
2627       ShOp = N0->getOperand(0);
2628       if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2629         if (!LegalTypes)
2630           ShOp = DAG.getConstant(0, VT);
2631         else
2632           ShOp = SDValue();
2633       }
2634
2635       // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2636       // (OR  (shuf (C, A), shuf (C, B)) -> shuf (C, OR  (A, B))
2637       // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2638       if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2639         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2640                                       N0->getOperand(1), N1->getOperand(1));
2641         AddToWorklist(NewNode.getNode());
2642         return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2643                                     &SVN0->getMask()[0]);
2644       }
2645     }
2646   }
2647
2648   return SDValue();
2649 }
2650
2651 SDValue DAGCombiner::visitAND(SDNode *N) {
2652   SDValue N0 = N->getOperand(0);
2653   SDValue N1 = N->getOperand(1);
2654   SDValue LL, LR, RL, RR, CC0, CC1;
2655   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2656   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2657   EVT VT = N1.getValueType();
2658   unsigned BitWidth = VT.getScalarType().getSizeInBits();
2659
2660   // fold vector ops
2661   if (VT.isVector()) {
2662     SDValue FoldedVOp = SimplifyVBinOp(N);
2663     if (FoldedVOp.getNode()) return FoldedVOp;
2664
2665     // fold (and x, 0) -> 0, vector edition
2666     if (ISD::isBuildVectorAllZeros(N0.getNode()))
2667       // do not return N0, because undef node may exist in N0
2668       return DAG.getConstant(
2669           APInt::getNullValue(
2670               N0.getValueType().getScalarType().getSizeInBits()),
2671           N0.getValueType());
2672     if (ISD::isBuildVectorAllZeros(N1.getNode()))
2673       // do not return N1, because undef node may exist in N1
2674       return DAG.getConstant(
2675           APInt::getNullValue(
2676               N1.getValueType().getScalarType().getSizeInBits()),
2677           N1.getValueType());
2678
2679     // fold (and x, -1) -> x, vector edition
2680     if (ISD::isBuildVectorAllOnes(N0.getNode()))
2681       return N1;
2682     if (ISD::isBuildVectorAllOnes(N1.getNode()))
2683       return N0;
2684   }
2685
2686   // fold (and x, undef) -> 0
2687   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2688     return DAG.getConstant(0, VT);
2689   // fold (and c1, c2) -> c1&c2
2690   if (N0C && N1C)
2691     return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C);
2692   // canonicalize constant to RHS
2693   if (N0C && !N1C)
2694     return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
2695   // fold (and x, -1) -> x
2696   if (N1C && N1C->isAllOnesValue())
2697     return N0;
2698   // if (and x, c) is known to be zero, return 0
2699   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2700                                    APInt::getAllOnesValue(BitWidth)))
2701     return DAG.getConstant(0, VT);
2702   // reassociate and
2703   SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1);
2704   if (RAND.getNode())
2705     return RAND;
2706   // fold (and (or x, C), D) -> D if (C & D) == D
2707   if (N1C && N0.getOpcode() == ISD::OR)
2708     if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2709       if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2710         return N1;
2711   // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2712   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2713     SDValue N0Op0 = N0.getOperand(0);
2714     APInt Mask = ~N1C->getAPIntValue();
2715     Mask = Mask.trunc(N0Op0.getValueSizeInBits());
2716     if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2717       SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
2718                                  N0.getValueType(), N0Op0);
2719
2720       // Replace uses of the AND with uses of the Zero extend node.
2721       CombineTo(N, Zext);
2722
2723       // We actually want to replace all uses of the any_extend with the
2724       // zero_extend, to avoid duplicating things.  This will later cause this
2725       // AND to be folded.
2726       CombineTo(N0.getNode(), Zext);
2727       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2728     }
2729   }
2730   // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
2731   // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2732   // already be zero by virtue of the width of the base type of the load.
2733   //
2734   // the 'X' node here can either be nothing or an extract_vector_elt to catch
2735   // more cases.
2736   if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2737        N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2738       N0.getOpcode() == ISD::LOAD) {
2739     LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2740                                          N0 : N0.getOperand(0) );
2741
2742     // Get the constant (if applicable) the zero'th operand is being ANDed with.
2743     // This can be a pure constant or a vector splat, in which case we treat the
2744     // vector as a scalar and use the splat value.
2745     APInt Constant = APInt::getNullValue(1);
2746     if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2747       Constant = C->getAPIntValue();
2748     } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2749       APInt SplatValue, SplatUndef;
2750       unsigned SplatBitSize;
2751       bool HasAnyUndefs;
2752       bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2753                                              SplatBitSize, HasAnyUndefs);
2754       if (IsSplat) {
2755         // Undef bits can contribute to a possible optimisation if set, so
2756         // set them.
2757         SplatValue |= SplatUndef;
2758
2759         // The splat value may be something like "0x00FFFFFF", which means 0 for
2760         // the first vector value and FF for the rest, repeating. We need a mask
2761         // that will apply equally to all members of the vector, so AND all the
2762         // lanes of the constant together.
2763         EVT VT = Vector->getValueType(0);
2764         unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
2765
2766         // If the splat value has been compressed to a bitlength lower
2767         // than the size of the vector lane, we need to re-expand it to
2768         // the lane size.
2769         if (BitWidth > SplatBitSize)
2770           for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
2771                SplatBitSize < BitWidth;
2772                SplatBitSize = SplatBitSize * 2)
2773             SplatValue |= SplatValue.shl(SplatBitSize);
2774
2775         Constant = APInt::getAllOnesValue(BitWidth);
2776         for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
2777           Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
2778       }
2779     }
2780
2781     // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
2782     // actually legal and isn't going to get expanded, else this is a false
2783     // optimisation.
2784     bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
2785                                                     Load->getMemoryVT());
2786
2787     // Resize the constant to the same size as the original memory access before
2788     // extension. If it is still the AllOnesValue then this AND is completely
2789     // unneeded.
2790     Constant =
2791       Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
2792
2793     bool B;
2794     switch (Load->getExtensionType()) {
2795     default: B = false; break;
2796     case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
2797     case ISD::ZEXTLOAD:
2798     case ISD::NON_EXTLOAD: B = true; break;
2799     }
2800
2801     if (B && Constant.isAllOnesValue()) {
2802       // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
2803       // preserve semantics once we get rid of the AND.
2804       SDValue NewLoad(Load, 0);
2805       if (Load->getExtensionType() == ISD::EXTLOAD) {
2806         NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
2807                               Load->getValueType(0), SDLoc(Load),
2808                               Load->getChain(), Load->getBasePtr(),
2809                               Load->getOffset(), Load->getMemoryVT(),
2810                               Load->getMemOperand());
2811         // Replace uses of the EXTLOAD with the new ZEXTLOAD.
2812         if (Load->getNumValues() == 3) {
2813           // PRE/POST_INC loads have 3 values.
2814           SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
2815                            NewLoad.getValue(2) };
2816           CombineTo(Load, To, 3, true);
2817         } else {
2818           CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
2819         }
2820       }
2821
2822       // Fold the AND away, taking care not to fold to the old load node if we
2823       // replaced it.
2824       CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
2825
2826       return SDValue(N, 0); // Return N so it doesn't get rechecked!
2827     }
2828   }
2829   // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2830   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2831     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2832     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2833
2834     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2835         LL.getValueType().isInteger()) {
2836       // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2837       if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
2838         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2839                                      LR.getValueType(), LL, RL);
2840         AddToWorklist(ORNode.getNode());
2841         return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2842       }
2843       // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2844       if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
2845         SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2846                                       LR.getValueType(), LL, RL);
2847         AddToWorklist(ANDNode.getNode());
2848         return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
2849       }
2850       // fold (and (setgt X,  -1), (setgt Y,  -1)) -> (setgt (or X, Y), -1)
2851       if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
2852         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2853                                      LR.getValueType(), LL, RL);
2854         AddToWorklist(ORNode.getNode());
2855         return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2856       }
2857     }
2858     // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2859     if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2860         Op0 == Op1 && LL.getValueType().isInteger() &&
2861       Op0 == ISD::SETNE && ((cast<ConstantSDNode>(LR)->isNullValue() &&
2862                                  cast<ConstantSDNode>(RR)->isAllOnesValue()) ||
2863                                 (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
2864                                  cast<ConstantSDNode>(RR)->isNullValue()))) {
2865       SDValue ADDNode = DAG.getNode(ISD::ADD, SDLoc(N0), LL.getValueType(),
2866                                     LL, DAG.getConstant(1, LL.getValueType()));
2867       AddToWorklist(ADDNode.getNode());
2868       return DAG.getSetCC(SDLoc(N), VT, ADDNode,
2869                           DAG.getConstant(2, LL.getValueType()), ISD::SETUGE);
2870     }
2871     // canonicalize equivalent to ll == rl
2872     if (LL == RR && LR == RL) {
2873       Op1 = ISD::getSetCCSwappedOperands(Op1);
2874       std::swap(RL, RR);
2875     }
2876     if (LL == RL && LR == RR) {
2877       bool isInteger = LL.getValueType().isInteger();
2878       ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2879       if (Result != ISD::SETCC_INVALID &&
2880           (!LegalOperations ||
2881            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2882             TLI.isOperationLegal(ISD::SETCC,
2883                             getSetCCResultType(N0.getSimpleValueType())))))
2884         return DAG.getSetCC(SDLoc(N), N0.getValueType(),
2885                             LL, LR, Result);
2886     }
2887   }
2888
2889   // Simplify: (and (op x...), (op y...))  -> (op (and x, y))
2890   if (N0.getOpcode() == N1.getOpcode()) {
2891     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
2892     if (Tmp.getNode()) return Tmp;
2893   }
2894
2895   // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
2896   // fold (and (sra)) -> (and (srl)) when possible.
2897   if (!VT.isVector() &&
2898       SimplifyDemandedBits(SDValue(N, 0)))
2899     return SDValue(N, 0);
2900
2901   // fold (zext_inreg (extload x)) -> (zextload x)
2902   if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
2903     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2904     EVT MemVT = LN0->getMemoryVT();
2905     // If we zero all the possible extended bits, then we can turn this into
2906     // a zextload if we are running before legalize or the operation is legal.
2907     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2908     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2909                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2910         ((!LegalOperations && !LN0->isVolatile()) ||
2911          TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2912       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2913                                        LN0->getChain(), LN0->getBasePtr(),
2914                                        MemVT, LN0->getMemOperand());
2915       AddToWorklist(N);
2916       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2917       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2918     }
2919   }
2920   // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
2921   if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
2922       N0.hasOneUse()) {
2923     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2924     EVT MemVT = LN0->getMemoryVT();
2925     // If we zero all the possible extended bits, then we can turn this into
2926     // a zextload if we are running before legalize or the operation is legal.
2927     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2928     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2929                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2930         ((!LegalOperations && !LN0->isVolatile()) ||
2931          TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2932       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2933                                        LN0->getChain(), LN0->getBasePtr(),
2934                                        MemVT, LN0->getMemOperand());
2935       AddToWorklist(N);
2936       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2937       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2938     }
2939   }
2940
2941   // fold (and (load x), 255) -> (zextload x, i8)
2942   // fold (and (extload x, i16), 255) -> (zextload x, i8)
2943   // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
2944   if (N1C && (N0.getOpcode() == ISD::LOAD ||
2945               (N0.getOpcode() == ISD::ANY_EXTEND &&
2946                N0.getOperand(0).getOpcode() == ISD::LOAD))) {
2947     bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
2948     LoadSDNode *LN0 = HasAnyExt
2949       ? cast<LoadSDNode>(N0.getOperand(0))
2950       : cast<LoadSDNode>(N0);
2951     if (LN0->getExtensionType() != ISD::SEXTLOAD &&
2952         LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
2953       uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
2954       if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
2955         EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
2956         EVT LoadedVT = LN0->getMemoryVT();
2957
2958         if (ExtVT == LoadedVT &&
2959             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2960           EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2961
2962           SDValue NewLoad =
2963             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2964                            LN0->getChain(), LN0->getBasePtr(), ExtVT,
2965                            LN0->getMemOperand());
2966           AddToWorklist(N);
2967           CombineTo(LN0, NewLoad, NewLoad.getValue(1));
2968           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2969         }
2970
2971         // Do not change the width of a volatile load.
2972         // Do not generate loads of non-round integer types since these can
2973         // be expensive (and would be wrong if the type is not byte sized).
2974         if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
2975             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2976           EVT PtrType = LN0->getOperand(1).getValueType();
2977
2978           unsigned Alignment = LN0->getAlignment();
2979           SDValue NewPtr = LN0->getBasePtr();
2980
2981           // For big endian targets, we need to add an offset to the pointer
2982           // to load the correct bytes.  For little endian systems, we merely
2983           // need to read fewer bytes from the same pointer.
2984           if (TLI.isBigEndian()) {
2985             unsigned LVTStoreBytes = LoadedVT.getStoreSize();
2986             unsigned EVTStoreBytes = ExtVT.getStoreSize();
2987             unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
2988             NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0), PtrType,
2989                                  NewPtr, DAG.getConstant(PtrOff, PtrType));
2990             Alignment = MinAlign(Alignment, PtrOff);
2991           }
2992
2993           AddToWorklist(NewPtr.getNode());
2994
2995           EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2996           SDValue Load =
2997             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2998                            LN0->getChain(), NewPtr,
2999                            LN0->getPointerInfo(),
3000                            ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
3001                            LN0->isInvariant(), Alignment, LN0->getAAInfo());
3002           AddToWorklist(N);
3003           CombineTo(LN0, Load, Load.getValue(1));
3004           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3005         }
3006       }
3007     }
3008   }
3009
3010   if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
3011       VT.getSizeInBits() <= 64) {
3012     if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3013       APInt ADDC = ADDI->getAPIntValue();
3014       if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
3015         // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
3016         // immediate for an add, but it is legal if its top c2 bits are set,
3017         // transform the ADD so the immediate doesn't need to be materialized
3018         // in a register.
3019         if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
3020           APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
3021                                              SRLI->getZExtValue());
3022           if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
3023             ADDC |= Mask;
3024             if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
3025               SDValue NewAdd =
3026                 DAG.getNode(ISD::ADD, SDLoc(N0), VT,
3027                             N0.getOperand(0), DAG.getConstant(ADDC, VT));
3028               CombineTo(N0.getNode(), NewAdd);
3029               return SDValue(N, 0); // Return N so it doesn't get rechecked!
3030             }
3031           }
3032         }
3033       }
3034     }
3035   }
3036
3037   // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
3038   if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
3039     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
3040                                        N0.getOperand(1), false);
3041     if (BSwap.getNode())
3042       return BSwap;
3043   }
3044
3045   return SDValue();
3046 }
3047
3048 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16.
3049 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
3050                                         bool DemandHighBits) {
3051   if (!LegalOperations)
3052     return SDValue();
3053
3054   EVT VT = N->getValueType(0);
3055   if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
3056     return SDValue();
3057   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3058     return SDValue();
3059
3060   // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
3061   bool LookPassAnd0 = false;
3062   bool LookPassAnd1 = false;
3063   if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
3064       std::swap(N0, N1);
3065   if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
3066       std::swap(N0, N1);
3067   if (N0.getOpcode() == ISD::AND) {
3068     if (!N0.getNode()->hasOneUse())
3069       return SDValue();
3070     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3071     if (!N01C || N01C->getZExtValue() != 0xFF00)
3072       return SDValue();
3073     N0 = N0.getOperand(0);
3074     LookPassAnd0 = true;
3075   }
3076
3077   if (N1.getOpcode() == ISD::AND) {
3078     if (!N1.getNode()->hasOneUse())
3079       return SDValue();
3080     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3081     if (!N11C || N11C->getZExtValue() != 0xFF)
3082       return SDValue();
3083     N1 = N1.getOperand(0);
3084     LookPassAnd1 = true;
3085   }
3086
3087   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3088     std::swap(N0, N1);
3089   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3090     return SDValue();
3091   if (!N0.getNode()->hasOneUse() ||
3092       !N1.getNode()->hasOneUse())
3093     return SDValue();
3094
3095   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3096   ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3097   if (!N01C || !N11C)
3098     return SDValue();
3099   if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3100     return SDValue();
3101
3102   // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3103   SDValue N00 = N0->getOperand(0);
3104   if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3105     if (!N00.getNode()->hasOneUse())
3106       return SDValue();
3107     ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3108     if (!N001C || N001C->getZExtValue() != 0xFF)
3109       return SDValue();
3110     N00 = N00.getOperand(0);
3111     LookPassAnd0 = true;
3112   }
3113
3114   SDValue N10 = N1->getOperand(0);
3115   if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3116     if (!N10.getNode()->hasOneUse())
3117       return SDValue();
3118     ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3119     if (!N101C || N101C->getZExtValue() != 0xFF00)
3120       return SDValue();
3121     N10 = N10.getOperand(0);
3122     LookPassAnd1 = true;
3123   }
3124
3125   if (N00 != N10)
3126     return SDValue();
3127
3128   // Make sure everything beyond the low halfword gets set to zero since the SRL
3129   // 16 will clear the top bits.
3130   unsigned OpSizeInBits = VT.getSizeInBits();
3131   if (DemandHighBits && OpSizeInBits > 16) {
3132     // If the left-shift isn't masked out then the only way this is a bswap is
3133     // if all bits beyond the low 8 are 0. In that case the entire pattern
3134     // reduces to a left shift anyway: leave it for other parts of the combiner.
3135     if (!LookPassAnd0)
3136       return SDValue();
3137
3138     // However, if the right shift isn't masked out then it might be because
3139     // it's not needed. See if we can spot that too.
3140     if (!LookPassAnd1 &&
3141         !DAG.MaskedValueIsZero(
3142             N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3143       return SDValue();
3144   }
3145
3146   SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
3147   if (OpSizeInBits > 16)
3148     Res = DAG.getNode(ISD::SRL, SDLoc(N), VT, Res,
3149                       DAG.getConstant(OpSizeInBits-16, getShiftAmountTy(VT)));
3150   return Res;
3151 }
3152
3153 /// Return true if the specified node is an element that makes up a 32-bit
3154 /// packed halfword byteswap.
3155 /// ((x & 0x000000ff) << 8) |
3156 /// ((x & 0x0000ff00) >> 8) |
3157 /// ((x & 0x00ff0000) << 8) |
3158 /// ((x & 0xff000000) >> 8)
3159 static bool isBSwapHWordElement(SDValue N, SmallVectorImpl<SDNode *> &Parts) {
3160   if (!N.getNode()->hasOneUse())
3161     return false;
3162
3163   unsigned Opc = N.getOpcode();
3164   if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3165     return false;
3166
3167   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3168   if (!N1C)
3169     return false;
3170
3171   unsigned Num;
3172   switch (N1C->getZExtValue()) {
3173   default:
3174     return false;
3175   case 0xFF:       Num = 0; break;
3176   case 0xFF00:     Num = 1; break;
3177   case 0xFF0000:   Num = 2; break;
3178   case 0xFF000000: Num = 3; break;
3179   }
3180
3181   // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3182   SDValue N0 = N.getOperand(0);
3183   if (Opc == ISD::AND) {
3184     if (Num == 0 || Num == 2) {
3185       // (x >> 8) & 0xff
3186       // (x >> 8) & 0xff0000
3187       if (N0.getOpcode() != ISD::SRL)
3188         return false;
3189       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3190       if (!C || C->getZExtValue() != 8)
3191         return false;
3192     } else {
3193       // (x << 8) & 0xff00
3194       // (x << 8) & 0xff000000
3195       if (N0.getOpcode() != ISD::SHL)
3196         return false;
3197       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3198       if (!C || C->getZExtValue() != 8)
3199         return false;
3200     }
3201   } else if (Opc == ISD::SHL) {
3202     // (x & 0xff) << 8
3203     // (x & 0xff0000) << 8
3204     if (Num != 0 && Num != 2)
3205       return false;
3206     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3207     if (!C || C->getZExtValue() != 8)
3208       return false;
3209   } else { // Opc == ISD::SRL
3210     // (x & 0xff00) >> 8
3211     // (x & 0xff000000) >> 8
3212     if (Num != 1 && Num != 3)
3213       return false;
3214     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3215     if (!C || C->getZExtValue() != 8)
3216       return false;
3217   }
3218
3219   if (Parts[Num])
3220     return false;
3221
3222   Parts[Num] = N0.getOperand(0).getNode();
3223   return true;
3224 }
3225
3226 /// Match a 32-bit packed halfword bswap. That is
3227 /// ((x & 0x000000ff) << 8) |
3228 /// ((x & 0x0000ff00) >> 8) |
3229 /// ((x & 0x00ff0000) << 8) |
3230 /// ((x & 0xff000000) >> 8)
3231 /// => (rotl (bswap x), 16)
3232 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3233   if (!LegalOperations)
3234     return SDValue();
3235
3236   EVT VT = N->getValueType(0);
3237   if (VT != MVT::i32)
3238     return SDValue();
3239   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3240     return SDValue();
3241
3242   SmallVector<SDNode*,4> Parts(4, (SDNode*)nullptr);
3243   // Look for either
3244   // (or (or (and), (and)), (or (and), (and)))
3245   // (or (or (or (and), (and)), (and)), (and))
3246   if (N0.getOpcode() != ISD::OR)
3247     return SDValue();
3248   SDValue N00 = N0.getOperand(0);
3249   SDValue N01 = N0.getOperand(1);
3250
3251   if (N1.getOpcode() == ISD::OR &&
3252       N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3253     // (or (or (and), (and)), (or (and), (and)))
3254     SDValue N000 = N00.getOperand(0);
3255     if (!isBSwapHWordElement(N000, Parts))
3256       return SDValue();
3257
3258     SDValue N001 = N00.getOperand(1);
3259     if (!isBSwapHWordElement(N001, Parts))
3260       return SDValue();
3261     SDValue N010 = N01.getOperand(0);
3262     if (!isBSwapHWordElement(N010, Parts))
3263       return SDValue();
3264     SDValue N011 = N01.getOperand(1);
3265     if (!isBSwapHWordElement(N011, Parts))
3266       return SDValue();
3267   } else {
3268     // (or (or (or (and), (and)), (and)), (and))
3269     if (!isBSwapHWordElement(N1, Parts))
3270       return SDValue();
3271     if (!isBSwapHWordElement(N01, Parts))
3272       return SDValue();
3273     if (N00.getOpcode() != ISD::OR)
3274       return SDValue();
3275     SDValue N000 = N00.getOperand(0);
3276     if (!isBSwapHWordElement(N000, Parts))
3277       return SDValue();
3278     SDValue N001 = N00.getOperand(1);
3279     if (!isBSwapHWordElement(N001, Parts))
3280       return SDValue();
3281   }
3282
3283   // Make sure the parts are all coming from the same node.
3284   if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3285     return SDValue();
3286
3287   SDValue BSwap = DAG.getNode(ISD::BSWAP, SDLoc(N), VT,
3288                               SDValue(Parts[0],0));
3289
3290   // Result of the bswap should be rotated by 16. If it's not legal, then
3291   // do  (x << 16) | (x >> 16).
3292   SDValue ShAmt = DAG.getConstant(16, getShiftAmountTy(VT));
3293   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3294     return DAG.getNode(ISD::ROTL, SDLoc(N), VT, BSwap, ShAmt);
3295   if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3296     return DAG.getNode(ISD::ROTR, SDLoc(N), VT, BSwap, ShAmt);
3297   return DAG.getNode(ISD::OR, SDLoc(N), VT,
3298                      DAG.getNode(ISD::SHL, SDLoc(N), VT, BSwap, ShAmt),
3299                      DAG.getNode(ISD::SRL, SDLoc(N), VT, BSwap, ShAmt));
3300 }
3301
3302 SDValue DAGCombiner::visitOR(SDNode *N) {
3303   SDValue N0 = N->getOperand(0);
3304   SDValue N1 = N->getOperand(1);
3305   SDValue LL, LR, RL, RR, CC0, CC1;
3306   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3307   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3308   EVT VT = N1.getValueType();
3309
3310   // fold vector ops
3311   if (VT.isVector()) {
3312     SDValue FoldedVOp = SimplifyVBinOp(N);
3313     if (FoldedVOp.getNode()) return FoldedVOp;
3314
3315     // fold (or x, 0) -> x, vector edition
3316     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3317       return N1;
3318     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3319       return N0;
3320
3321     // fold (or x, -1) -> -1, vector edition
3322     if (ISD::isBuildVectorAllOnes(N0.getNode()))
3323       // do not return N0, because undef node may exist in N0
3324       return DAG.getConstant(
3325           APInt::getAllOnesValue(
3326               N0.getValueType().getScalarType().getSizeInBits()),
3327           N0.getValueType());
3328     if (ISD::isBuildVectorAllOnes(N1.getNode()))
3329       // do not return N1, because undef node may exist in N1
3330       return DAG.getConstant(
3331           APInt::getAllOnesValue(
3332               N1.getValueType().getScalarType().getSizeInBits()),
3333           N1.getValueType());
3334
3335     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
3336     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
3337     // Do this only if the resulting shuffle is legal.
3338     if (isa<ShuffleVectorSDNode>(N0) &&
3339         isa<ShuffleVectorSDNode>(N1) &&
3340         // Avoid folding a node with illegal type.
3341         TLI.isTypeLegal(VT) &&
3342         N0->getOperand(1) == N1->getOperand(1) &&
3343         ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
3344       bool CanFold = true;
3345       unsigned NumElts = VT.getVectorNumElements();
3346       const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3347       const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3348       // We construct two shuffle masks:
3349       // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
3350       // and N1 as the second operand.
3351       // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
3352       // and N0 as the second operand.
3353       // We do this because OR is commutable and therefore there might be
3354       // two ways to fold this node into a shuffle.
3355       SmallVector<int,4> Mask1;
3356       SmallVector<int,4> Mask2;
3357
3358       for (unsigned i = 0; i != NumElts && CanFold; ++i) {
3359         int M0 = SV0->getMaskElt(i);
3360         int M1 = SV1->getMaskElt(i);
3361
3362         // Both shuffle indexes are undef. Propagate Undef.
3363         if (M0 < 0 && M1 < 0) {
3364           Mask1.push_back(M0);
3365           Mask2.push_back(M0);
3366           continue;
3367         }
3368
3369         if (M0 < 0 || M1 < 0 ||
3370             (M0 < (int)NumElts && M1 < (int)NumElts) ||
3371             (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
3372           CanFold = false;
3373           break;
3374         }
3375
3376         Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
3377         Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
3378       }
3379
3380       if (CanFold) {
3381         // Fold this sequence only if the resulting shuffle is 'legal'.
3382         if (TLI.isShuffleMaskLegal(Mask1, VT))
3383           return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
3384                                       N1->getOperand(0), &Mask1[0]);
3385         if (TLI.isShuffleMaskLegal(Mask2, VT))
3386           return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
3387                                       N0->getOperand(0), &Mask2[0]);
3388       }
3389     }
3390   }
3391
3392   // fold (or x, undef) -> -1
3393   if (!LegalOperations &&
3394       (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3395     EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3396     return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
3397   }
3398   // fold (or c1, c2) -> c1|c2
3399   if (N0C && N1C)
3400     return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C);
3401   // canonicalize constant to RHS
3402   if (N0C && !N1C)
3403     return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3404   // fold (or x, 0) -> x
3405   if (N1C && N1C->isNullValue())
3406     return N0;
3407   // fold (or x, -1) -> -1
3408   if (N1C && N1C->isAllOnesValue())
3409     return N1;
3410   // fold (or x, c) -> c iff (x & ~c) == 0
3411   if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3412     return N1;
3413
3414   // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3415   SDValue BSwap = MatchBSwapHWord(N, N0, N1);
3416   if (BSwap.getNode())
3417     return BSwap;
3418   BSwap = MatchBSwapHWordLow(N, N0, N1);
3419   if (BSwap.getNode())
3420     return BSwap;
3421
3422   // reassociate or
3423   SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1);
3424   if (ROR.getNode())
3425     return ROR;
3426   // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3427   // iff (c1 & c2) == 0.
3428   if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3429              isa<ConstantSDNode>(N0.getOperand(1))) {
3430     ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3431     if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3432       SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1);
3433       if (!COR.getNode())
3434         return SDValue();
3435       return DAG.getNode(ISD::AND, SDLoc(N), VT,
3436                          DAG.getNode(ISD::OR, SDLoc(N0), VT,
3437                                      N0.getOperand(0), N1), COR);
3438     }
3439   }
3440   // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3441   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3442     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3443     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3444
3445     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
3446         LL.getValueType().isInteger()) {
3447       // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3448       // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3449       if (cast<ConstantSDNode>(LR)->isNullValue() &&
3450           (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3451         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3452                                      LR.getValueType(), LL, RL);
3453         AddToWorklist(ORNode.getNode());
3454         return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
3455       }
3456       // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3457       // fold (or (setgt X, -1), (setgt Y  -1)) -> (setgt (and X, Y), -1)
3458       if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
3459           (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3460         SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3461                                       LR.getValueType(), LL, RL);
3462         AddToWorklist(ANDNode.getNode());
3463         return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
3464       }
3465     }
3466     // canonicalize equivalent to ll == rl
3467     if (LL == RR && LR == RL) {
3468       Op1 = ISD::getSetCCSwappedOperands(Op1);
3469       std::swap(RL, RR);
3470     }
3471     if (LL == RL && LR == RR) {
3472       bool isInteger = LL.getValueType().isInteger();
3473       ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3474       if (Result != ISD::SETCC_INVALID &&
3475           (!LegalOperations ||
3476            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3477             TLI.isOperationLegal(ISD::SETCC,
3478               getSetCCResultType(N0.getValueType())))))
3479         return DAG.getSetCC(SDLoc(N), N0.getValueType(),
3480                             LL, LR, Result);
3481     }
3482   }
3483
3484   // Simplify: (or (op x...), (op y...))  -> (op (or x, y))
3485   if (N0.getOpcode() == N1.getOpcode()) {
3486     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3487     if (Tmp.getNode()) return Tmp;
3488   }
3489
3490   // (or (and X, C1), (and Y, C2))  -> (and (or X, Y), C3) if possible.
3491   if (N0.getOpcode() == ISD::AND &&
3492       N1.getOpcode() == ISD::AND &&
3493       N0.getOperand(1).getOpcode() == ISD::Constant &&
3494       N1.getOperand(1).getOpcode() == ISD::Constant &&
3495       // Don't increase # computations.
3496       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3497     // We can only do this xform if we know that bits from X that are set in C2
3498     // but not in C1 are already zero.  Likewise for Y.
3499     const APInt &LHSMask =
3500       cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3501     const APInt &RHSMask =
3502       cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
3503
3504     if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3505         DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3506       SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3507                               N0.getOperand(0), N1.getOperand(0));
3508       return DAG.getNode(ISD::AND, SDLoc(N), VT, X,
3509                          DAG.getConstant(LHSMask | RHSMask, VT));
3510     }
3511   }
3512
3513   // See if this is some rotate idiom.
3514   if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3515     return SDValue(Rot, 0);
3516
3517   // Simplify the operands using demanded-bits information.
3518   if (!VT.isVector() &&
3519       SimplifyDemandedBits(SDValue(N, 0)))
3520     return SDValue(N, 0);
3521
3522   return SDValue();
3523 }
3524
3525 /// Match "(X shl/srl V1) & V2" where V2 may not be present.
3526 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3527   if (Op.getOpcode() == ISD::AND) {
3528     if (isa<ConstantSDNode>(Op.getOperand(1))) {
3529       Mask = Op.getOperand(1);
3530       Op = Op.getOperand(0);
3531     } else {
3532       return false;
3533     }
3534   }
3535
3536   if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3537     Shift = Op;
3538     return true;
3539   }
3540
3541   return false;
3542 }
3543
3544 // Return true if we can prove that, whenever Neg and Pos are both in the
3545 // range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos).  This means that
3546 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3547 //
3548 //     (or (shift1 X, Neg), (shift2 X, Pos))
3549 //
3550 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3551 // in direction shift1 by Neg.  The range [0, OpSize) means that we only need
3552 // to consider shift amounts with defined behavior.
3553 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) {
3554   // If OpSize is a power of 2 then:
3555   //
3556   //  (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1)
3557   //  (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize).
3558   //
3559   // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check
3560   // for the stronger condition:
3561   //
3562   //     Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1)    [A]
3563   //
3564   // for all Neg and Pos.  Since Neg & (OpSize - 1) == Neg' & (OpSize - 1)
3565   // we can just replace Neg with Neg' for the rest of the function.
3566   //
3567   // In other cases we check for the even stronger condition:
3568   //
3569   //     Neg == OpSize - Pos                                    [B]
3570   //
3571   // for all Neg and Pos.  Note that the (or ...) then invokes undefined
3572   // behavior if Pos == 0 (and consequently Neg == OpSize).
3573   //
3574   // We could actually use [A] whenever OpSize is a power of 2, but the
3575   // only extra cases that it would match are those uninteresting ones
3576   // where Neg and Pos are never in range at the same time.  E.g. for
3577   // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3578   // as well as (sub 32, Pos), but:
3579   //
3580   //     (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3581   //
3582   // always invokes undefined behavior for 32-bit X.
3583   //
3584   // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise.
3585   unsigned MaskLoBits = 0;
3586   if (Neg.getOpcode() == ISD::AND &&
3587       isPowerOf2_64(OpSize) &&
3588       Neg.getOperand(1).getOpcode() == ISD::Constant &&
3589       cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) {
3590     Neg = Neg.getOperand(0);
3591     MaskLoBits = Log2_64(OpSize);
3592   }
3593
3594   // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3595   if (Neg.getOpcode() != ISD::SUB)
3596     return 0;
3597   ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0));
3598   if (!NegC)
3599     return 0;
3600   SDValue NegOp1 = Neg.getOperand(1);
3601
3602   // On the RHS of [A], if Pos is Pos' & (OpSize - 1), just replace Pos with
3603   // Pos'.  The truncation is redundant for the purpose of the equality.
3604   if (MaskLoBits &&
3605       Pos.getOpcode() == ISD::AND &&
3606       Pos.getOperand(1).getOpcode() == ISD::Constant &&
3607       cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() == OpSize - 1)
3608     Pos = Pos.getOperand(0);
3609
3610   // The condition we need is now:
3611   //
3612   //     (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask
3613   //
3614   // If NegOp1 == Pos then we need:
3615   //
3616   //              OpSize & Mask == NegC & Mask
3617   //
3618   // (because "x & Mask" is a truncation and distributes through subtraction).
3619   APInt Width;
3620   if (Pos == NegOp1)
3621     Width = NegC->getAPIntValue();
3622   // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3623   // Then the condition we want to prove becomes:
3624   //
3625   //     (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask
3626   //
3627   // which, again because "x & Mask" is a truncation, becomes:
3628   //
3629   //                NegC & Mask == (OpSize - PosC) & Mask
3630   //              OpSize & Mask == (NegC + PosC) & Mask
3631   else if (Pos.getOpcode() == ISD::ADD &&
3632            Pos.getOperand(0) == NegOp1 &&
3633            Pos.getOperand(1).getOpcode() == ISD::Constant)
3634     Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() +
3635              NegC->getAPIntValue());
3636   else
3637     return false;
3638
3639   // Now we just need to check that OpSize & Mask == Width & Mask.
3640   if (MaskLoBits)
3641     // Opsize & Mask is 0 since Mask is Opsize - 1.
3642     return Width.getLoBits(MaskLoBits) == 0;
3643   return Width == OpSize;
3644 }
3645
3646 // A subroutine of MatchRotate used once we have found an OR of two opposite
3647 // shifts of Shifted.  If Neg == <operand size> - Pos then the OR reduces
3648 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3649 // former being preferred if supported.  InnerPos and InnerNeg are Pos and
3650 // Neg with outer conversions stripped away.
3651 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3652                                        SDValue Neg, SDValue InnerPos,
3653                                        SDValue InnerNeg, unsigned PosOpcode,
3654                                        unsigned NegOpcode, SDLoc DL) {
3655   // fold (or (shl x, (*ext y)),
3656   //          (srl x, (*ext (sub 32, y)))) ->
3657   //   (rotl x, y) or (rotr x, (sub 32, y))
3658   //
3659   // fold (or (shl x, (*ext (sub 32, y))),
3660   //          (srl x, (*ext y))) ->
3661   //   (rotr x, y) or (rotl x, (sub 32, y))
3662   EVT VT = Shifted.getValueType();
3663   if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) {
3664     bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3665     return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3666                        HasPos ? Pos : Neg).getNode();
3667   }
3668
3669   return nullptr;
3670 }
3671
3672 // MatchRotate - Handle an 'or' of two operands.  If this is one of the many
3673 // idioms for rotate, and if the target supports rotation instructions, generate
3674 // a rot[lr].
3675 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
3676   // Must be a legal type.  Expanded 'n promoted things won't work with rotates.
3677   EVT VT = LHS.getValueType();
3678   if (!TLI.isTypeLegal(VT)) return nullptr;
3679
3680   // The target must have at least one rotate flavor.
3681   bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3682   bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3683   if (!HasROTL && !HasROTR) return nullptr;
3684
3685   // Match "(X shl/srl V1) & V2" where V2 may not be present.
3686   SDValue LHSShift;   // The shift.
3687   SDValue LHSMask;    // AND value if any.
3688   if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3689     return nullptr; // Not part of a rotate.
3690
3691   SDValue RHSShift;   // The shift.
3692   SDValue RHSMask;    // AND value if any.
3693   if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3694     return nullptr; // Not part of a rotate.
3695
3696   if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3697     return nullptr;   // Not shifting the same value.
3698
3699   if (LHSShift.getOpcode() == RHSShift.getOpcode())
3700     return nullptr;   // Shifts must disagree.
3701
3702   // Canonicalize shl to left side in a shl/srl pair.
3703   if (RHSShift.getOpcode() == ISD::SHL) {
3704     std::swap(LHS, RHS);
3705     std::swap(LHSShift, RHSShift);
3706     std::swap(LHSMask , RHSMask );
3707   }
3708
3709   unsigned OpSizeInBits = VT.getSizeInBits();
3710   SDValue LHSShiftArg = LHSShift.getOperand(0);
3711   SDValue LHSShiftAmt = LHSShift.getOperand(1);
3712   SDValue RHSShiftArg = RHSShift.getOperand(0);
3713   SDValue RHSShiftAmt = RHSShift.getOperand(1);
3714
3715   // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3716   // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
3717   if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3718       RHSShiftAmt.getOpcode() == ISD::Constant) {
3719     uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3720     uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
3721     if ((LShVal + RShVal) != OpSizeInBits)
3722       return nullptr;
3723
3724     SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3725                               LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3726
3727     // If there is an AND of either shifted operand, apply it to the result.
3728     if (LHSMask.getNode() || RHSMask.getNode()) {
3729       APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
3730
3731       if (LHSMask.getNode()) {
3732         APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3733         Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
3734       }
3735       if (RHSMask.getNode()) {
3736         APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3737         Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
3738       }
3739
3740       Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT));
3741     }
3742
3743     return Rot.getNode();
3744   }
3745
3746   // If there is a mask here, and we have a variable shift, we can't be sure
3747   // that we're masking out the right stuff.
3748   if (LHSMask.getNode() || RHSMask.getNode())
3749     return nullptr;
3750
3751   // If the shift amount is sign/zext/any-extended just peel it off.
3752   SDValue LExtOp0 = LHSShiftAmt;
3753   SDValue RExtOp0 = RHSShiftAmt;
3754   if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3755        LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3756        LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3757        LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3758       (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3759        RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3760        RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3761        RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
3762     LExtOp0 = LHSShiftAmt.getOperand(0);
3763     RExtOp0 = RHSShiftAmt.getOperand(0);
3764   }
3765
3766   SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
3767                                    LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
3768   if (TryL)
3769     return TryL;
3770
3771   SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
3772                                    RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
3773   if (TryR)
3774     return TryR;
3775
3776   return nullptr;
3777 }
3778
3779 SDValue DAGCombiner::visitXOR(SDNode *N) {
3780   SDValue N0 = N->getOperand(0);
3781   SDValue N1 = N->getOperand(1);
3782   SDValue LHS, RHS, CC;
3783   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3784   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3785   EVT VT = N0.getValueType();
3786
3787   // fold vector ops
3788   if (VT.isVector()) {
3789     SDValue FoldedVOp = SimplifyVBinOp(N);
3790     if (FoldedVOp.getNode()) return FoldedVOp;
3791
3792     // fold (xor x, 0) -> x, vector edition
3793     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3794       return N1;
3795     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3796       return N0;
3797   }
3798
3799   // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3800   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3801     return DAG.getConstant(0, VT);
3802   // fold (xor x, undef) -> undef
3803   if (N0.getOpcode() == ISD::UNDEF)
3804     return N0;
3805   if (N1.getOpcode() == ISD::UNDEF)
3806     return N1;
3807   // fold (xor c1, c2) -> c1^c2
3808   if (N0C && N1C)
3809     return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
3810   // canonicalize constant to RHS
3811   if (N0C && !N1C)
3812     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
3813   // fold (xor x, 0) -> x
3814   if (N1C && N1C->isNullValue())
3815     return N0;
3816   // reassociate xor
3817   SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1);
3818   if (RXOR.getNode())
3819     return RXOR;
3820
3821   // fold !(x cc y) -> (x !cc y)
3822   if (N1C && N1C->getAPIntValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) {
3823     bool isInt = LHS.getValueType().isInteger();
3824     ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3825                                                isInt);
3826
3827     if (!LegalOperations ||
3828         TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
3829       switch (N0.getOpcode()) {
3830       default:
3831         llvm_unreachable("Unhandled SetCC Equivalent!");
3832       case ISD::SETCC:
3833         return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
3834       case ISD::SELECT_CC:
3835         return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
3836                                N0.getOperand(3), NotCC);
3837       }
3838     }
3839   }
3840
3841   // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
3842   if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
3843       N0.getNode()->hasOneUse() &&
3844       isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
3845     SDValue V = N0.getOperand(0);
3846     V = DAG.getNode(ISD::XOR, SDLoc(N0), V.getValueType(), V,
3847                     DAG.getConstant(1, V.getValueType()));
3848     AddToWorklist(V.getNode());
3849     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
3850   }
3851
3852   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
3853   if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
3854       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3855     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3856     if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
3857       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3858       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3859       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3860       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
3861       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3862     }
3863   }
3864   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
3865   if (N1C && N1C->isAllOnesValue() &&
3866       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3867     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3868     if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
3869       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3870       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3871       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3872       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
3873       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3874     }
3875   }
3876   // fold (xor (and x, y), y) -> (and (not x), y)
3877   if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3878       N0->getOperand(1) == N1) {
3879     SDValue X = N0->getOperand(0);
3880     SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
3881     AddToWorklist(NotX.getNode());
3882     return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
3883   }
3884   // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
3885   if (N1C && N0.getOpcode() == ISD::XOR) {
3886     ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
3887     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3888     if (N00C)
3889       return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(1),
3890                          DAG.getConstant(N1C->getAPIntValue() ^
3891                                          N00C->getAPIntValue(), VT));
3892     if (N01C)
3893       return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(0),
3894                          DAG.getConstant(N1C->getAPIntValue() ^
3895                                          N01C->getAPIntValue(), VT));
3896   }
3897   // fold (xor x, x) -> 0
3898   if (N0 == N1)
3899     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
3900
3901   // Simplify: xor (op x...), (op y...)  -> (op (xor x, y))
3902   if (N0.getOpcode() == N1.getOpcode()) {
3903     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3904     if (Tmp.getNode()) return Tmp;
3905   }
3906
3907   // Simplify the expression using non-local knowledge.
3908   if (!VT.isVector() &&
3909       SimplifyDemandedBits(SDValue(N, 0)))
3910     return SDValue(N, 0);
3911
3912   return SDValue();
3913 }
3914
3915 /// Handle transforms common to the three shifts, when the shift amount is a
3916 /// constant.
3917 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
3918   // We can't and shouldn't fold opaque constants.
3919   if (Amt->isOpaque())
3920     return SDValue();
3921
3922   SDNode *LHS = N->getOperand(0).getNode();
3923   if (!LHS->hasOneUse()) return SDValue();
3924
3925   // We want to pull some binops through shifts, so that we have (and (shift))
3926   // instead of (shift (and)), likewise for add, or, xor, etc.  This sort of
3927   // thing happens with address calculations, so it's important to canonicalize
3928   // it.
3929   bool HighBitSet = false;  // Can we transform this if the high bit is set?
3930
3931   switch (LHS->getOpcode()) {
3932   default: return SDValue();
3933   case ISD::OR:
3934   case ISD::XOR:
3935     HighBitSet = false; // We can only transform sra if the high bit is clear.
3936     break;
3937   case ISD::AND:
3938     HighBitSet = true;  // We can only transform sra if the high bit is set.
3939     break;
3940   case ISD::ADD:
3941     if (N->getOpcode() != ISD::SHL)
3942       return SDValue(); // only shl(add) not sr[al](add).
3943     HighBitSet = false; // We can only transform sra if the high bit is clear.
3944     break;
3945   }
3946
3947   // We require the RHS of the binop to be a constant and not opaque as well.
3948   ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
3949   if (!BinOpCst || BinOpCst->isOpaque()) return SDValue();
3950
3951   // FIXME: disable this unless the input to the binop is a shift by a constant.
3952   // If it is not a shift, it pessimizes some common cases like:
3953   //
3954   //    void foo(int *X, int i) { X[i & 1235] = 1; }
3955   //    int bar(int *X, int i) { return X[i & 255]; }
3956   SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
3957   if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
3958        BinOpLHSVal->getOpcode() != ISD::SRA &&
3959        BinOpLHSVal->getOpcode() != ISD::SRL) ||
3960       !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
3961     return SDValue();
3962
3963   EVT VT = N->getValueType(0);
3964
3965   // If this is a signed shift right, and the high bit is modified by the
3966   // logical operation, do not perform the transformation. The highBitSet
3967   // boolean indicates the value of the high bit of the constant which would
3968   // cause it to be modified for this operation.
3969   if (N->getOpcode() == ISD::SRA) {
3970     bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
3971     if (BinOpRHSSignSet != HighBitSet)
3972       return SDValue();
3973   }
3974
3975   if (!TLI.isDesirableToCommuteWithShift(LHS))
3976     return SDValue();
3977
3978   // Fold the constants, shifting the binop RHS by the shift amount.
3979   SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
3980                                N->getValueType(0),
3981                                LHS->getOperand(1), N->getOperand(1));
3982   assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
3983
3984   // Create the new shift.
3985   SDValue NewShift = DAG.getNode(N->getOpcode(),
3986                                  SDLoc(LHS->getOperand(0)),
3987                                  VT, LHS->getOperand(0), N->getOperand(1));
3988
3989   // Create the new binop.
3990   return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
3991 }
3992
3993 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
3994   assert(N->getOpcode() == ISD::TRUNCATE);
3995   assert(N->getOperand(0).getOpcode() == ISD::AND);
3996
3997   // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
3998   if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
3999     SDValue N01 = N->getOperand(0).getOperand(1);
4000
4001     if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
4002       EVT TruncVT = N->getValueType(0);
4003       SDValue N00 = N->getOperand(0).getOperand(0);
4004       APInt TruncC = N01C->getAPIntValue();
4005       TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
4006
4007       return DAG.getNode(ISD::AND, SDLoc(N), TruncVT,
4008                          DAG.getNode(ISD::TRUNCATE, SDLoc(N), TruncVT, N00),
4009                          DAG.getConstant(TruncC, TruncVT));
4010     }
4011   }
4012
4013   return SDValue();
4014 }
4015
4016 SDValue DAGCombiner::visitRotate(SDNode *N) {
4017   // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
4018   if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
4019       N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
4020     SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode());
4021     if (NewOp1.getNode())
4022       return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
4023                          N->getOperand(0), NewOp1);
4024   }
4025   return SDValue();
4026 }
4027
4028 SDValue DAGCombiner::visitSHL(SDNode *N) {
4029   SDValue N0 = N->getOperand(0);
4030   SDValue N1 = N->getOperand(1);
4031   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4032   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4033   EVT VT = N0.getValueType();
4034   unsigned OpSizeInBits = VT.getScalarSizeInBits();
4035
4036   // fold vector ops
4037   if (VT.isVector()) {
4038     SDValue FoldedVOp = SimplifyVBinOp(N);
4039     if (FoldedVOp.getNode()) return FoldedVOp;
4040
4041     BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
4042     // If setcc produces all-one true value then:
4043     // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
4044     if (N1CV && N1CV->isConstant()) {
4045       if (N0.getOpcode() == ISD::AND) {
4046         SDValue N00 = N0->getOperand(0);
4047         SDValue N01 = N0->getOperand(1);
4048         BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
4049
4050         if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
4051             TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
4052                 TargetLowering::ZeroOrNegativeOneBooleanContent) {
4053           SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, VT, N01CV, N1CV);
4054           if (C.getNode())
4055             return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
4056         }
4057       } else {
4058         N1C = isConstOrConstSplat(N1);
4059       }
4060     }
4061   }
4062
4063   // fold (shl c1, c2) -> c1<<c2
4064   if (N0C && N1C)
4065     return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
4066   // fold (shl 0, x) -> 0
4067   if (N0C && N0C->isNullValue())
4068     return N0;
4069   // fold (shl x, c >= size(x)) -> undef
4070   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4071     return DAG.getUNDEF(VT);
4072   // fold (shl x, 0) -> x
4073   if (N1C && N1C->isNullValue())
4074     return N0;
4075   // fold (shl undef, x) -> 0
4076   if (N0.getOpcode() == ISD::UNDEF)
4077     return DAG.getConstant(0, VT);
4078   // if (shl x, c) is known to be zero, return 0
4079   if (DAG.MaskedValueIsZero(SDValue(N, 0),
4080                             APInt::getAllOnesValue(OpSizeInBits)))
4081     return DAG.getConstant(0, VT);
4082   // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
4083   if (N1.getOpcode() == ISD::TRUNCATE &&
4084       N1.getOperand(0).getOpcode() == ISD::AND) {
4085     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4086     if (NewOp1.getNode())
4087       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
4088   }
4089
4090   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4091     return SDValue(N, 0);
4092
4093   // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
4094   if (N1C && N0.getOpcode() == ISD::SHL) {
4095     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4096       uint64_t c1 = N0C1->getZExtValue();
4097       uint64_t c2 = N1C->getZExtValue();
4098       if (c1 + c2 >= OpSizeInBits)
4099         return DAG.getConstant(0, VT);
4100       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4101                          DAG.getConstant(c1 + c2, N1.getValueType()));
4102     }
4103   }
4104
4105   // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4106   // For this to be valid, the second form must not preserve any of the bits
4107   // that are shifted out by the inner shift in the first form.  This means
4108   // the outer shift size must be >= the number of bits added by the ext.
4109   // As a corollary, we don't care what kind of ext it is.
4110   if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4111               N0.getOpcode() == ISD::ANY_EXTEND ||
4112               N0.getOpcode() == ISD::SIGN_EXTEND) &&
4113       N0.getOperand(0).getOpcode() == ISD::SHL) {
4114     SDValue N0Op0 = N0.getOperand(0);
4115     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4116       uint64_t c1 = N0Op0C1->getZExtValue();
4117       uint64_t c2 = N1C->getZExtValue();
4118       EVT InnerShiftVT = N0Op0.getValueType();
4119       uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4120       if (c2 >= OpSizeInBits - InnerShiftSize) {
4121         if (c1 + c2 >= OpSizeInBits)
4122           return DAG.getConstant(0, VT);
4123         return DAG.getNode(ISD::SHL, SDLoc(N0), VT,
4124                            DAG.getNode(N0.getOpcode(), SDLoc(N0), VT,
4125                                        N0Op0->getOperand(0)),
4126                            DAG.getConstant(c1 + c2, N1.getValueType()));
4127       }
4128     }
4129   }
4130
4131   // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4132   // Only fold this if the inner zext has no other uses to avoid increasing
4133   // the total number of instructions.
4134   if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
4135       N0.getOperand(0).getOpcode() == ISD::SRL) {
4136     SDValue N0Op0 = N0.getOperand(0);
4137     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4138       uint64_t c1 = N0Op0C1->getZExtValue();
4139       if (c1 < VT.getScalarSizeInBits()) {
4140         uint64_t c2 = N1C->getZExtValue();
4141         if (c1 == c2) {
4142           SDValue NewOp0 = N0.getOperand(0);
4143           EVT CountVT = NewOp0.getOperand(1).getValueType();
4144           SDValue NewSHL = DAG.getNode(ISD::SHL, SDLoc(N), NewOp0.getValueType(),
4145                                        NewOp0, DAG.getConstant(c2, CountVT));
4146           AddToWorklist(NewSHL.getNode());
4147           return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4148         }
4149       }
4150     }
4151   }
4152
4153   // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4154   //                               (and (srl x, (sub c1, c2), MASK)
4155   // Only fold this if the inner shift has no other uses -- if it does, folding
4156   // this will increase the total number of instructions.
4157   if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4158     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4159       uint64_t c1 = N0C1->getZExtValue();
4160       if (c1 < OpSizeInBits) {
4161         uint64_t c2 = N1C->getZExtValue();
4162         APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4163         SDValue Shift;
4164         if (c2 > c1) {
4165           Mask = Mask.shl(c2 - c1);
4166           Shift = DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4167                               DAG.getConstant(c2 - c1, N1.getValueType()));
4168         } else {
4169           Mask = Mask.lshr(c1 - c2);
4170           Shift = DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4171                               DAG.getConstant(c1 - c2, N1.getValueType()));
4172         }
4173         return DAG.getNode(ISD::AND, SDLoc(N0), VT, Shift,
4174                            DAG.getConstant(Mask, VT));
4175       }
4176     }
4177   }
4178   // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
4179   if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
4180     unsigned BitSize = VT.getScalarSizeInBits();
4181     SDValue HiBitsMask =
4182       DAG.getConstant(APInt::getHighBitsSet(BitSize,
4183                                             BitSize - N1C->getZExtValue()), VT);
4184     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4185                        HiBitsMask);
4186   }
4187
4188   if (N1C) {
4189     SDValue NewSHL = visitShiftByConstant(N, N1C);
4190     if (NewSHL.getNode())
4191       return NewSHL;
4192   }
4193
4194   return SDValue();
4195 }
4196
4197 SDValue DAGCombiner::visitSRA(SDNode *N) {
4198   SDValue N0 = N->getOperand(0);
4199   SDValue N1 = N->getOperand(1);
4200   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4201   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4202   EVT VT = N0.getValueType();
4203   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4204
4205   // fold vector ops
4206   if (VT.isVector()) {
4207     SDValue FoldedVOp = SimplifyVBinOp(N);
4208     if (FoldedVOp.getNode()) return FoldedVOp;
4209
4210     N1C = isConstOrConstSplat(N1);
4211   }
4212
4213   // fold (sra c1, c2) -> (sra c1, c2)
4214   if (N0C && N1C)
4215     return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
4216   // fold (sra 0, x) -> 0
4217   if (N0C && N0C->isNullValue())
4218     return N0;
4219   // fold (sra -1, x) -> -1
4220   if (N0C && N0C->isAllOnesValue())
4221     return N0;
4222   // fold (sra x, (setge c, size(x))) -> undef
4223   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4224     return DAG.getUNDEF(VT);
4225   // fold (sra x, 0) -> x
4226   if (N1C && N1C->isNullValue())
4227     return N0;
4228   // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4229   // sext_inreg.
4230   if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
4231     unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
4232     EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4233     if (VT.isVector())
4234       ExtVT = EVT::getVectorVT(*DAG.getContext(),
4235                                ExtVT, VT.getVectorNumElements());
4236     if ((!LegalOperations ||
4237          TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
4238       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
4239                          N0.getOperand(0), DAG.getValueType(ExtVT));
4240   }
4241
4242   // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
4243   if (N1C && N0.getOpcode() == ISD::SRA) {
4244     if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
4245       unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
4246       if (Sum >= OpSizeInBits)
4247         Sum = OpSizeInBits - 1;
4248       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0.getOperand(0),
4249                          DAG.getConstant(Sum, N1.getValueType()));
4250     }
4251   }
4252
4253   // fold (sra (shl X, m), (sub result_size, n))
4254   // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
4255   // result_size - n != m.
4256   // If truncate is free for the target sext(shl) is likely to result in better
4257   // code.
4258   if (N0.getOpcode() == ISD::SHL && N1C) {
4259     // Get the two constanst of the shifts, CN0 = m, CN = n.
4260     const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4261     if (N01C) {
4262       LLVMContext &Ctx = *DAG.getContext();
4263       // Determine what the truncate's result bitsize and type would be.
4264       EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4265
4266       if (VT.isVector())
4267         TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4268
4269       // Determine the residual right-shift amount.
4270       signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
4271
4272       // If the shift is not a no-op (in which case this should be just a sign
4273       // extend already), the truncated to type is legal, sign_extend is legal
4274       // on that type, and the truncate to that type is both legal and free,
4275       // perform the transform.
4276       if ((ShiftAmt > 0) &&
4277           TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4278           TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
4279           TLI.isTruncateFree(VT, TruncVT)) {
4280
4281           SDValue Amt = DAG.getConstant(ShiftAmt,
4282               getShiftAmountTy(N0.getOperand(0).getValueType()));
4283           SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), VT,
4284                                       N0.getOperand(0), Amt);
4285           SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), TruncVT,
4286                                       Shift);
4287           return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N),
4288                              N->getValueType(0), Trunc);
4289       }
4290     }
4291   }
4292
4293   // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
4294   if (N1.getOpcode() == ISD::TRUNCATE &&
4295       N1.getOperand(0).getOpcode() == ISD::AND) {
4296     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4297     if (NewOp1.getNode())
4298       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
4299   }
4300
4301   // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
4302   //      if c1 is equal to the number of bits the trunc removes
4303   if (N0.getOpcode() == ISD::TRUNCATE &&
4304       (N0.getOperand(0).getOpcode() == ISD::SRL ||
4305        N0.getOperand(0).getOpcode() == ISD::SRA) &&
4306       N0.getOperand(0).hasOneUse() &&
4307       N0.getOperand(0).getOperand(1).hasOneUse() &&
4308       N1C) {
4309     SDValue N0Op0 = N0.getOperand(0);
4310     if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4311       unsigned LargeShiftVal = LargeShift->getZExtValue();
4312       EVT LargeVT = N0Op0.getValueType();
4313
4314       if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4315         SDValue Amt =
4316           DAG.getConstant(LargeShiftVal + N1C->getZExtValue(),
4317                           getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4318         SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), LargeVT,
4319                                   N0Op0.getOperand(0), Amt);
4320         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, SRA);
4321       }
4322     }
4323   }
4324
4325   // Simplify, based on bits shifted out of the LHS.
4326   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4327     return SDValue(N, 0);
4328
4329
4330   // If the sign bit is known to be zero, switch this to a SRL.
4331   if (DAG.SignBitIsZero(N0))
4332     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
4333
4334   if (N1C) {
4335     SDValue NewSRA = visitShiftByConstant(N, N1C);
4336     if (NewSRA.getNode())
4337       return NewSRA;
4338   }
4339
4340   return SDValue();
4341 }
4342
4343 SDValue DAGCombiner::visitSRL(SDNode *N) {
4344   SDValue N0 = N->getOperand(0);
4345   SDValue N1 = N->getOperand(1);
4346   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4347   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4348   EVT VT = N0.getValueType();
4349   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4350
4351   // fold vector ops
4352   if (VT.isVector()) {
4353     SDValue FoldedVOp = SimplifyVBinOp(N);
4354     if (FoldedVOp.getNode()) return FoldedVOp;
4355
4356     N1C = isConstOrConstSplat(N1);
4357   }
4358
4359   // fold (srl c1, c2) -> c1 >>u c2
4360   if (N0C && N1C)
4361     return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C);
4362   // fold (srl 0, x) -> 0
4363   if (N0C && N0C->isNullValue())
4364     return N0;
4365   // fold (srl x, c >= size(x)) -> undef
4366   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4367     return DAG.getUNDEF(VT);
4368   // fold (srl x, 0) -> x
4369   if (N1C && N1C->isNullValue())
4370     return N0;
4371   // if (srl x, c) is known to be zero, return 0
4372   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4373                                    APInt::getAllOnesValue(OpSizeInBits)))
4374     return DAG.getConstant(0, VT);
4375
4376   // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
4377   if (N1C && N0.getOpcode() == ISD::SRL) {
4378     if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
4379       uint64_t c1 = N01C->getZExtValue();
4380       uint64_t c2 = N1C->getZExtValue();
4381       if (c1 + c2 >= OpSizeInBits)
4382         return DAG.getConstant(0, VT);
4383       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4384                          DAG.getConstant(c1 + c2, N1.getValueType()));
4385     }
4386   }
4387
4388   // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4389   if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4390       N0.getOperand(0).getOpcode() == ISD::SRL &&
4391       isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4392     uint64_t c1 =
4393       cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4394     uint64_t c2 = N1C->getZExtValue();
4395     EVT InnerShiftVT = N0.getOperand(0).getValueType();
4396     EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4397     uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
4398     // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4399     if (c1 + OpSizeInBits == InnerShiftSize) {
4400       if (c1 + c2 >= InnerShiftSize)
4401         return DAG.getConstant(0, VT);
4402       return DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT,
4403                          DAG.getNode(ISD::SRL, SDLoc(N0), InnerShiftVT,
4404                                      N0.getOperand(0)->getOperand(0),
4405                                      DAG.getConstant(c1 + c2, ShiftCountVT)));
4406     }
4407   }
4408
4409   // fold (srl (shl x, c), c) -> (and x, cst2)
4410   if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4411     unsigned BitSize = N0.getScalarValueSizeInBits();
4412     if (BitSize <= 64) {
4413       uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4414       return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4415                          DAG.getConstant(~0ULL >> ShAmt, VT));
4416     }
4417   }
4418
4419   // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4420   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4421     // Shifting in all undef bits?
4422     EVT SmallVT = N0.getOperand(0).getValueType();
4423     unsigned BitSize = SmallVT.getScalarSizeInBits();
4424     if (N1C->getZExtValue() >= BitSize)
4425       return DAG.getUNDEF(VT);
4426
4427     if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4428       uint64_t ShiftAmt = N1C->getZExtValue();
4429       SDValue SmallShift = DAG.getNode(ISD::SRL, SDLoc(N0), SmallVT,
4430                                        N0.getOperand(0),
4431                           DAG.getConstant(ShiftAmt, getShiftAmountTy(SmallVT)));
4432       AddToWorklist(SmallShift.getNode());
4433       APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
4434       return DAG.getNode(ISD::AND, SDLoc(N), VT,
4435                          DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, SmallShift),
4436                          DAG.getConstant(Mask, VT));
4437     }
4438   }
4439
4440   // fold (srl (sra X, Y), 31) -> (srl X, 31).  This srl only looks at the sign
4441   // bit, which is unmodified by sra.
4442   if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
4443     if (N0.getOpcode() == ISD::SRA)
4444       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4445   }
4446
4447   // fold (srl (ctlz x), "5") -> x  iff x has one bit set (the low bit).
4448   if (N1C && N0.getOpcode() == ISD::CTLZ &&
4449       N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
4450     APInt KnownZero, KnownOne;
4451     DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne);
4452
4453     // If any of the input bits are KnownOne, then the input couldn't be all
4454     // zeros, thus the result of the srl will always be zero.
4455     if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
4456
4457     // If all of the bits input the to ctlz node are known to be zero, then
4458     // the result of the ctlz is "32" and the result of the shift is one.
4459     APInt UnknownBits = ~KnownZero;
4460     if (UnknownBits == 0) return DAG.getConstant(1, VT);
4461
4462     // Otherwise, check to see if there is exactly one bit input to the ctlz.
4463     if ((UnknownBits & (UnknownBits - 1)) == 0) {
4464       // Okay, we know that only that the single bit specified by UnknownBits
4465       // could be set on input to the CTLZ node. If this bit is set, the SRL
4466       // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4467       // to an SRL/XOR pair, which is likely to simplify more.
4468       unsigned ShAmt = UnknownBits.countTrailingZeros();
4469       SDValue Op = N0.getOperand(0);
4470
4471       if (ShAmt) {
4472         Op = DAG.getNode(ISD::SRL, SDLoc(N0), VT, Op,
4473                   DAG.getConstant(ShAmt, getShiftAmountTy(Op.getValueType())));
4474         AddToWorklist(Op.getNode());
4475       }
4476
4477       return DAG.getNode(ISD::XOR, SDLoc(N), VT,
4478                          Op, DAG.getConstant(1, VT));
4479     }
4480   }
4481
4482   // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4483   if (N1.getOpcode() == ISD::TRUNCATE &&
4484       N1.getOperand(0).getOpcode() == ISD::AND) {
4485     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4486     if (NewOp1.getNode())
4487       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
4488   }
4489
4490   // fold operands of srl based on knowledge that the low bits are not
4491   // demanded.
4492   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4493     return SDValue(N, 0);
4494
4495   if (N1C) {
4496     SDValue NewSRL = visitShiftByConstant(N, N1C);
4497     if (NewSRL.getNode())
4498       return NewSRL;
4499   }
4500
4501   // Attempt to convert a srl of a load into a narrower zero-extending load.
4502   SDValue NarrowLoad = ReduceLoadWidth(N);
4503   if (NarrowLoad.getNode())
4504     return NarrowLoad;
4505
4506   // Here is a common situation. We want to optimize:
4507   //
4508   //   %a = ...
4509   //   %b = and i32 %a, 2
4510   //   %c = srl i32 %b, 1
4511   //   brcond i32 %c ...
4512   //
4513   // into
4514   //
4515   //   %a = ...
4516   //   %b = and %a, 2
4517   //   %c = setcc eq %b, 0
4518   //   brcond %c ...
4519   //
4520   // However when after the source operand of SRL is optimized into AND, the SRL
4521   // itself may not be optimized further. Look for it and add the BRCOND into
4522   // the worklist.
4523   if (N->hasOneUse()) {
4524     SDNode *Use = *N->use_begin();
4525     if (Use->getOpcode() == ISD::BRCOND)
4526       AddToWorklist(Use);
4527     else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4528       // Also look pass the truncate.
4529       Use = *Use->use_begin();
4530       if (Use->getOpcode() == ISD::BRCOND)
4531         AddToWorklist(Use);
4532     }
4533   }
4534
4535   return SDValue();
4536 }
4537
4538 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4539   SDValue N0 = N->getOperand(0);
4540   EVT VT = N->getValueType(0);
4541
4542   // fold (ctlz c1) -> c2
4543   if (isa<ConstantSDNode>(N0))
4544     return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
4545   return SDValue();
4546 }
4547
4548 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4549   SDValue N0 = N->getOperand(0);
4550   EVT VT = N->getValueType(0);
4551
4552   // fold (ctlz_zero_undef c1) -> c2
4553   if (isa<ConstantSDNode>(N0))
4554     return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4555   return SDValue();
4556 }
4557
4558 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4559   SDValue N0 = N->getOperand(0);
4560   EVT VT = N->getValueType(0);
4561
4562   // fold (cttz c1) -> c2
4563   if (isa<ConstantSDNode>(N0))
4564     return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
4565   return SDValue();
4566 }
4567
4568 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4569   SDValue N0 = N->getOperand(0);
4570   EVT VT = N->getValueType(0);
4571
4572   // fold (cttz_zero_undef c1) -> c2
4573   if (isa<ConstantSDNode>(N0))
4574     return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4575   return SDValue();
4576 }
4577
4578 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4579   SDValue N0 = N->getOperand(0);
4580   EVT VT = N->getValueType(0);
4581
4582   // fold (ctpop c1) -> c2
4583   if (isa<ConstantSDNode>(N0))
4584     return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
4585   return SDValue();
4586 }
4587
4588 SDValue DAGCombiner::visitSELECT(SDNode *N) {
4589   SDValue N0 = N->getOperand(0);
4590   SDValue N1 = N->getOperand(1);
4591   SDValue N2 = N->getOperand(2);
4592   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4593   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4594   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
4595   EVT VT = N->getValueType(0);
4596   EVT VT0 = N0.getValueType();
4597
4598   // fold (select C, X, X) -> X
4599   if (N1 == N2)
4600     return N1;
4601   // fold (select true, X, Y) -> X
4602   if (N0C && !N0C->isNullValue())
4603     return N1;
4604   // fold (select false, X, Y) -> Y
4605   if (N0C && N0C->isNullValue())
4606     return N2;
4607   // fold (select C, 1, X) -> (or C, X)
4608   if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
4609     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4610   // fold (select C, 0, 1) -> (xor C, 1)
4611   // We can't do this reliably if integer based booleans have different contents
4612   // to floating point based booleans. This is because we can't tell whether we
4613   // have an integer-based boolean or a floating-point-based boolean unless we
4614   // can find the SETCC that produced it and inspect its operands. This is
4615   // fairly easy if C is the SETCC node, but it can potentially be
4616   // undiscoverable (or not reasonably discoverable). For example, it could be
4617   // in another basic block or it could require searching a complicated
4618   // expression.
4619   if (VT.isInteger() &&
4620       (VT0 == MVT::i1 || (VT0.isInteger() &&
4621                           TLI.getBooleanContents(false, false) ==
4622                               TLI.getBooleanContents(false, true) &&
4623                           TLI.getBooleanContents(false, false) ==
4624                               TargetLowering::ZeroOrOneBooleanContent)) &&
4625       N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
4626     SDValue XORNode;
4627     if (VT == VT0)
4628       return DAG.getNode(ISD::XOR, SDLoc(N), VT0,
4629                          N0, DAG.getConstant(1, VT0));
4630     XORNode = DAG.getNode(ISD::XOR, SDLoc(N0), VT0,
4631                           N0, DAG.getConstant(1, VT0));
4632     AddToWorklist(XORNode.getNode());
4633     if (VT.bitsGT(VT0))
4634       return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4635     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
4636   }
4637   // fold (select C, 0, X) -> (and (not C), X)
4638   if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
4639     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4640     AddToWorklist(NOTNode.getNode());
4641     return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
4642   }
4643   // fold (select C, X, 1) -> (or (not C), X)
4644   if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
4645     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4646     AddToWorklist(NOTNode.getNode());
4647     return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
4648   }
4649   // fold (select C, X, 0) -> (and C, X)
4650   if (VT == MVT::i1 && N2C && N2C->isNullValue())
4651     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4652   // fold (select X, X, Y) -> (or X, Y)
4653   // fold (select X, 1, Y) -> (or X, Y)
4654   if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
4655     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4656   // fold (select X, Y, X) -> (and X, Y)
4657   // fold (select X, Y, 0) -> (and X, Y)
4658   if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
4659     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4660
4661   // If we can fold this based on the true/false value, do so.
4662   if (SimplifySelectOps(N, N1, N2))
4663     return SDValue(N, 0);  // Don't revisit N.
4664
4665   // fold selects based on a setcc into other things, such as min/max/abs
4666   if (N0.getOpcode() == ISD::SETCC) {
4667     if ((!LegalOperations &&
4668          TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
4669         TLI.isOperationLegal(ISD::SELECT_CC, VT))
4670       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
4671                          N0.getOperand(0), N0.getOperand(1),
4672                          N1, N2, N0.getOperand(2));
4673     return SimplifySelect(SDLoc(N), N0, N1, N2);
4674   }
4675
4676   return SDValue();
4677 }
4678
4679 static
4680 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
4681   SDLoc DL(N);
4682   EVT LoVT, HiVT;
4683   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
4684
4685   // Split the inputs.
4686   SDValue Lo, Hi, LL, LH, RL, RH;
4687   std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
4688   std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
4689
4690   Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
4691   Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
4692
4693   return std::make_pair(Lo, Hi);
4694 }
4695
4696 // This function assumes all the vselect's arguments are CONCAT_VECTOR
4697 // nodes and that the condition is a BV of ConstantSDNodes (or undefs).
4698 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
4699   SDLoc dl(N);
4700   SDValue Cond = N->getOperand(0);
4701   SDValue LHS = N->getOperand(1);
4702   SDValue RHS = N->getOperand(2);
4703   EVT VT = N->getValueType(0);
4704   int NumElems = VT.getVectorNumElements();
4705   assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
4706          RHS.getOpcode() == ISD::CONCAT_VECTORS &&
4707          Cond.getOpcode() == ISD::BUILD_VECTOR);
4708
4709   // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about
4710   // binary ones here.
4711   if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2)
4712     return SDValue();
4713
4714   // We're sure we have an even number of elements due to the
4715   // concat_vectors we have as arguments to vselect.
4716   // Skip BV elements until we find one that's not an UNDEF
4717   // After we find an UNDEF element, keep looping until we get to half the
4718   // length of the BV and see if all the non-undef nodes are the same.
4719   ConstantSDNode *BottomHalf = nullptr;
4720   for (int i = 0; i < NumElems / 2; ++i) {
4721     if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
4722       continue;
4723
4724     if (BottomHalf == nullptr)
4725       BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
4726     else if (Cond->getOperand(i).getNode() != BottomHalf)
4727       return SDValue();
4728   }
4729
4730   // Do the same for the second half of the BuildVector
4731   ConstantSDNode *TopHalf = nullptr;
4732   for (int i = NumElems / 2; i < NumElems; ++i) {
4733     if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
4734       continue;
4735
4736     if (TopHalf == nullptr)
4737       TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
4738     else if (Cond->getOperand(i).getNode() != TopHalf)
4739       return SDValue();
4740   }
4741
4742   assert(TopHalf && BottomHalf &&
4743          "One half of the selector was all UNDEFs and the other was all the "
4744          "same value. This should have been addressed before this function.");
4745   return DAG.getNode(
4746       ISD::CONCAT_VECTORS, dl, VT,
4747       BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
4748       TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
4749 }
4750
4751 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
4752   SDValue N0 = N->getOperand(0);
4753   SDValue N1 = N->getOperand(1);
4754   SDValue N2 = N->getOperand(2);
4755   SDLoc DL(N);
4756
4757   // Canonicalize integer abs.
4758   // vselect (setg[te] X,  0),  X, -X ->
4759   // vselect (setgt    X, -1),  X, -X ->
4760   // vselect (setl[te] X,  0), -X,  X ->
4761   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
4762   if (N0.getOpcode() == ISD::SETCC) {
4763     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4764     ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4765     bool isAbs = false;
4766     bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
4767
4768     if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
4769          (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
4770         N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
4771       isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
4772     else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
4773              N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
4774       isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
4775
4776     if (isAbs) {
4777       EVT VT = LHS.getValueType();
4778       SDValue Shift = DAG.getNode(
4779           ISD::SRA, DL, VT, LHS,
4780           DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, VT));
4781       SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
4782       AddToWorklist(Shift.getNode());
4783       AddToWorklist(Add.getNode());
4784       return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
4785     }
4786   }
4787
4788   // If the VSELECT result requires splitting and the mask is provided by a
4789   // SETCC, then split both nodes and its operands before legalization. This
4790   // prevents the type legalizer from unrolling SETCC into scalar comparisons
4791   // and enables future optimizations (e.g. min/max pattern matching on X86).
4792   if (N0.getOpcode() == ISD::SETCC) {
4793     EVT VT = N->getValueType(0);
4794
4795     // Check if any splitting is required.
4796     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
4797         TargetLowering::TypeSplitVector)
4798       return SDValue();
4799
4800     SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
4801     std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
4802     std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
4803     std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
4804
4805     Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
4806     Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
4807
4808     // Add the new VSELECT nodes to the work list in case they need to be split
4809     // again.
4810     AddToWorklist(Lo.getNode());
4811     AddToWorklist(Hi.getNode());
4812
4813     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
4814   }
4815
4816   // Fold (vselect (build_vector all_ones), N1, N2) -> N1
4817   if (ISD::isBuildVectorAllOnes(N0.getNode()))
4818     return N1;
4819   // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
4820   if (ISD::isBuildVectorAllZeros(N0.getNode()))
4821     return N2;
4822
4823   // The ConvertSelectToConcatVector function is assuming both the above
4824   // checks for (vselect (build_vector all{ones,zeros) ...) have been made
4825   // and addressed.
4826   if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
4827       N2.getOpcode() == ISD::CONCAT_VECTORS &&
4828       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
4829     SDValue CV = ConvertSelectToConcatVector(N, DAG);
4830     if (CV.getNode())
4831       return CV;
4832   }
4833
4834   return SDValue();
4835 }
4836
4837 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
4838   SDValue N0 = N->getOperand(0);
4839   SDValue N1 = N->getOperand(1);
4840   SDValue N2 = N->getOperand(2);
4841   SDValue N3 = N->getOperand(3);
4842   SDValue N4 = N->getOperand(4);
4843   ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
4844
4845   // fold select_cc lhs, rhs, x, x, cc -> x
4846   if (N2 == N3)
4847     return N2;
4848
4849   // Determine if the condition we're dealing with is constant
4850   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
4851                               N0, N1, CC, SDLoc(N), false);
4852   if (SCC.getNode()) {
4853     AddToWorklist(SCC.getNode());
4854
4855     if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
4856       if (!SCCC->isNullValue())
4857         return N2;    // cond always true -> true val
4858       else
4859         return N3;    // cond always false -> false val
4860     }
4861
4862     // Fold to a simpler select_cc
4863     if (SCC.getOpcode() == ISD::SETCC)
4864       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
4865                          SCC.getOperand(0), SCC.getOperand(1), N2, N3,
4866                          SCC.getOperand(2));
4867   }
4868
4869   // If we can fold this based on the true/false value, do so.
4870   if (SimplifySelectOps(N, N2, N3))
4871     return SDValue(N, 0);  // Don't revisit N.
4872
4873   // fold select_cc into other things, such as min/max/abs
4874   return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
4875 }
4876
4877 SDValue DAGCombiner::visitSETCC(SDNode *N) {
4878   return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
4879                        cast<CondCodeSDNode>(N->getOperand(2))->get(),
4880                        SDLoc(N));
4881 }
4882
4883 // tryToFoldExtendOfConstant - Try to fold a sext/zext/aext
4884 // dag node into a ConstantSDNode or a build_vector of constants.
4885 // This function is called by the DAGCombiner when visiting sext/zext/aext
4886 // dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
4887 // Vector extends are not folded if operations are legal; this is to
4888 // avoid introducing illegal build_vector dag nodes.
4889 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
4890                                          SelectionDAG &DAG, bool LegalTypes,
4891                                          bool LegalOperations) {
4892   unsigned Opcode = N->getOpcode();
4893   SDValue N0 = N->getOperand(0);
4894   EVT VT = N->getValueType(0);
4895
4896   assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
4897          Opcode == ISD::ANY_EXTEND) && "Expected EXTEND dag node in input!");
4898
4899   // fold (sext c1) -> c1
4900   // fold (zext c1) -> c1
4901   // fold (aext c1) -> c1
4902   if (isa<ConstantSDNode>(N0))
4903     return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
4904
4905   // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
4906   // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
4907   // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
4908   EVT SVT = VT.getScalarType();
4909   if (!(VT.isVector() &&
4910       (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
4911       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
4912     return nullptr;
4913
4914   // We can fold this node into a build_vector.
4915   unsigned VTBits = SVT.getSizeInBits();
4916   unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
4917   unsigned ShAmt = VTBits - EVTBits;
4918   SmallVector<SDValue, 8> Elts;
4919   unsigned NumElts = N0->getNumOperands();
4920   SDLoc DL(N);
4921
4922   for (unsigned i=0; i != NumElts; ++i) {
4923     SDValue Op = N0->getOperand(i);
4924     if (Op->getOpcode() == ISD::UNDEF) {
4925       Elts.push_back(DAG.getUNDEF(SVT));
4926       continue;
4927     }
4928
4929     ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
4930     const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
4931     if (Opcode == ISD::SIGN_EXTEND)
4932       Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
4933                                      SVT));
4934     else
4935       Elts.push_back(DAG.getConstant(C.shl(ShAmt).lshr(ShAmt).getZExtValue(),
4936                                      SVT));
4937   }
4938
4939   return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts).getNode();
4940 }
4941
4942 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
4943 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
4944 // transformation. Returns true if extension are possible and the above
4945 // mentioned transformation is profitable.
4946 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
4947                                     unsigned ExtOpc,
4948                                     SmallVectorImpl<SDNode *> &ExtendNodes,
4949                                     const TargetLowering &TLI) {
4950   bool HasCopyToRegUses = false;
4951   bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
4952   for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
4953                             UE = N0.getNode()->use_end();
4954        UI != UE; ++UI) {
4955     SDNode *User = *UI;
4956     if (User == N)
4957       continue;
4958     if (UI.getUse().getResNo() != N0.getResNo())
4959       continue;
4960     // FIXME: Only extend SETCC N, N and SETCC N, c for now.
4961     if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
4962       ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
4963       if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
4964         // Sign bits will be lost after a zext.
4965         return false;
4966       bool Add = false;
4967       for (unsigned i = 0; i != 2; ++i) {
4968         SDValue UseOp = User->getOperand(i);
4969         if (UseOp == N0)
4970           continue;
4971         if (!isa<ConstantSDNode>(UseOp))
4972           return false;
4973         Add = true;
4974       }
4975       if (Add)
4976         ExtendNodes.push_back(User);
4977       continue;
4978     }
4979     // If truncates aren't free and there are users we can't
4980     // extend, it isn't worthwhile.
4981     if (!isTruncFree)
4982       return false;
4983     // Remember if this value is live-out.
4984     if (User->getOpcode() == ISD::CopyToReg)
4985       HasCopyToRegUses = true;
4986   }
4987
4988   if (HasCopyToRegUses) {
4989     bool BothLiveOut = false;
4990     for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
4991          UI != UE; ++UI) {
4992       SDUse &Use = UI.getUse();
4993       if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
4994         BothLiveOut = true;
4995         break;
4996       }
4997     }
4998     if (BothLiveOut)
4999       // Both unextended and extended values are live out. There had better be
5000       // a good reason for the transformation.
5001       return ExtendNodes.size();
5002   }
5003   return true;
5004 }
5005
5006 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
5007                                   SDValue Trunc, SDValue ExtLoad, SDLoc DL,
5008                                   ISD::NodeType ExtType) {
5009   // Extend SetCC uses if necessary.
5010   for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
5011     SDNode *SetCC = SetCCs[i];
5012     SmallVector<SDValue, 4> Ops;
5013
5014     for (unsigned j = 0; j != 2; ++j) {
5015       SDValue SOp = SetCC->getOperand(j);
5016       if (SOp == Trunc)
5017         Ops.push_back(ExtLoad);
5018       else
5019         Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
5020     }
5021
5022     Ops.push_back(SetCC->getOperand(2));
5023     CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
5024   }
5025 }
5026
5027 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
5028   SDValue N0 = N->getOperand(0);
5029   EVT VT = N->getValueType(0);
5030
5031   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5032                                               LegalOperations))
5033     return SDValue(Res, 0);
5034
5035   // fold (sext (sext x)) -> (sext x)
5036   // fold (sext (aext x)) -> (sext x)
5037   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5038     return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
5039                        N0.getOperand(0));
5040
5041   if (N0.getOpcode() == ISD::TRUNCATE) {
5042     // fold (sext (truncate (load x))) -> (sext (smaller load x))
5043     // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
5044     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5045     if (NarrowLoad.getNode()) {
5046       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5047       if (NarrowLoad.getNode() != N0.getNode()) {
5048         CombineTo(N0.getNode(), NarrowLoad);
5049         // CombineTo deleted the truncate, if needed, but not what's under it.
5050         AddToWorklist(oye);
5051       }
5052       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5053     }
5054
5055     // See if the value being truncated is already sign extended.  If so, just
5056     // eliminate the trunc/sext pair.
5057     SDValue Op = N0.getOperand(0);
5058     unsigned OpBits   = Op.getValueType().getScalarType().getSizeInBits();
5059     unsigned MidBits  = N0.getValueType().getScalarType().getSizeInBits();
5060     unsigned DestBits = VT.getScalarType().getSizeInBits();
5061     unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
5062
5063     if (OpBits == DestBits) {
5064       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
5065       // bits, it is already ready.
5066       if (NumSignBits > DestBits-MidBits)
5067         return Op;
5068     } else if (OpBits < DestBits) {
5069       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
5070       // bits, just sext from i32.
5071       if (NumSignBits > OpBits-MidBits)
5072         return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
5073     } else {
5074       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
5075       // bits, just truncate to i32.
5076       if (NumSignBits > OpBits-MidBits)
5077         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5078     }
5079
5080     // fold (sext (truncate x)) -> (sextinreg x).
5081     if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
5082                                                  N0.getValueType())) {
5083       if (OpBits < DestBits)
5084         Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
5085       else if (OpBits > DestBits)
5086         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
5087       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
5088                          DAG.getValueType(N0.getValueType()));
5089     }
5090   }
5091
5092   // fold (sext (load x)) -> (sext (truncate (sextload x)))
5093   // None of the supported targets knows how to perform load and sign extend
5094   // on vectors in one instruction.  We only perform this transformation on
5095   // scalars.
5096   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5097       ISD::isUNINDEXEDLoad(N0.getNode()) &&
5098       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5099        TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()))) {
5100     bool DoXform = true;
5101     SmallVector<SDNode*, 4> SetCCs;
5102     if (!N0.hasOneUse())
5103       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
5104     if (DoXform) {
5105       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5106       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5107                                        LN0->getChain(),
5108                                        LN0->getBasePtr(), N0.getValueType(),
5109                                        LN0->getMemOperand());
5110       CombineTo(N, ExtLoad);
5111       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5112                                   N0.getValueType(), ExtLoad);
5113       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5114       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5115                       ISD::SIGN_EXTEND);
5116       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5117     }
5118   }
5119
5120   // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
5121   // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
5122   if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5123       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5124     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5125     EVT MemVT = LN0->getMemoryVT();
5126     if ((!LegalOperations && !LN0->isVolatile()) ||
5127         TLI.isLoadExtLegal(ISD::SEXTLOAD, MemVT)) {
5128       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5129                                        LN0->getChain(),
5130                                        LN0->getBasePtr(), MemVT,
5131                                        LN0->getMemOperand());
5132       CombineTo(N, ExtLoad);
5133       CombineTo(N0.getNode(),
5134                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5135                             N0.getValueType(), ExtLoad),
5136                 ExtLoad.getValue(1));
5137       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5138     }
5139   }
5140
5141   // fold (sext (and/or/xor (load x), cst)) ->
5142   //      (and/or/xor (sextload x), (sext cst))
5143   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5144        N0.getOpcode() == ISD::XOR) &&
5145       isa<LoadSDNode>(N0.getOperand(0)) &&
5146       N0.getOperand(1).getOpcode() == ISD::Constant &&
5147       TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()) &&
5148       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5149     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5150     if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
5151       bool DoXform = true;
5152       SmallVector<SDNode*, 4> SetCCs;
5153       if (!N0.hasOneUse())
5154         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
5155                                           SetCCs, TLI);
5156       if (DoXform) {
5157         SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
5158                                          LN0->getChain(), LN0->getBasePtr(),
5159                                          LN0->getMemoryVT(),
5160                                          LN0->getMemOperand());
5161         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5162         Mask = Mask.sext(VT.getSizeInBits());
5163         SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5164                                   ExtLoad, DAG.getConstant(Mask, VT));
5165         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5166                                     SDLoc(N0.getOperand(0)),
5167                                     N0.getOperand(0).getValueType(), ExtLoad);
5168         CombineTo(N, And);
5169         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5170         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5171                         ISD::SIGN_EXTEND);
5172         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5173       }
5174     }
5175   }
5176
5177   if (N0.getOpcode() == ISD::SETCC) {
5178     EVT N0VT = N0.getOperand(0).getValueType();
5179     // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
5180     // Only do this before legalize for now.
5181     if (VT.isVector() && !LegalOperations &&
5182         TLI.getBooleanContents(N0VT) ==
5183             TargetLowering::ZeroOrNegativeOneBooleanContent) {
5184       // On some architectures (such as SSE/NEON/etc) the SETCC result type is
5185       // of the same size as the compared operands. Only optimize sext(setcc())
5186       // if this is the case.
5187       EVT SVT = getSetCCResultType(N0VT);
5188
5189       // We know that the # elements of the results is the same as the
5190       // # elements of the compare (and the # elements of the compare result
5191       // for that matter).  Check to see that they are the same size.  If so,
5192       // we know that the element size of the sext'd result matches the
5193       // element size of the compare operands.
5194       if (VT.getSizeInBits() == SVT.getSizeInBits())
5195         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5196                              N0.getOperand(1),
5197                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
5198
5199       // If the desired elements are smaller or larger than the source
5200       // elements we can use a matching integer vector type and then
5201       // truncate/sign extend
5202       EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5203       if (SVT == MatchingVectorType) {
5204         SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
5205                                N0.getOperand(0), N0.getOperand(1),
5206                                cast<CondCodeSDNode>(N0.getOperand(2))->get());
5207         return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
5208       }
5209     }
5210
5211     // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
5212     unsigned ElementWidth = VT.getScalarType().getSizeInBits();
5213     SDValue NegOne =
5214       DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT);
5215     SDValue SCC =
5216       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5217                        NegOne, DAG.getConstant(0, VT),
5218                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5219     if (SCC.getNode()) return SCC;
5220
5221     if (!VT.isVector()) {
5222       EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
5223       if (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, SetCCVT)) {
5224         SDLoc DL(N);
5225         ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5226         SDValue SetCC = DAG.getSetCC(DL,
5227                                      SetCCVT,
5228                                      N0.getOperand(0), N0.getOperand(1), CC);
5229         EVT SelectVT = getSetCCResultType(VT);
5230         return DAG.getSelect(DL, VT,
5231                              DAG.getSExtOrTrunc(SetCC, DL, SelectVT),
5232                              NegOne, DAG.getConstant(0, VT));
5233
5234       }
5235     }
5236   }
5237
5238   // fold (sext x) -> (zext x) if the sign bit is known zero.
5239   if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
5240       DAG.SignBitIsZero(N0))
5241     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
5242
5243   return SDValue();
5244 }
5245
5246 // isTruncateOf - If N is a truncate of some other value, return true, record
5247 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
5248 // This function computes KnownZero to avoid a duplicated call to
5249 // computeKnownBits in the caller.
5250 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
5251                          APInt &KnownZero) {
5252   APInt KnownOne;
5253   if (N->getOpcode() == ISD::TRUNCATE) {
5254     Op = N->getOperand(0);
5255     DAG.computeKnownBits(Op, KnownZero, KnownOne);
5256     return true;
5257   }
5258
5259   if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
5260       cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
5261     return false;
5262
5263   SDValue Op0 = N->getOperand(0);
5264   SDValue Op1 = N->getOperand(1);
5265   assert(Op0.getValueType() == Op1.getValueType());
5266
5267   ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0);
5268   ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
5269   if (COp0 && COp0->isNullValue())
5270     Op = Op1;
5271   else if (COp1 && COp1->isNullValue())
5272     Op = Op0;
5273   else
5274     return false;
5275
5276   DAG.computeKnownBits(Op, KnownZero, KnownOne);
5277
5278   if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
5279     return false;
5280
5281   return true;
5282 }
5283
5284 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
5285   SDValue N0 = N->getOperand(0);
5286   EVT VT = N->getValueType(0);
5287
5288   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5289                                               LegalOperations))
5290     return SDValue(Res, 0);
5291
5292   // fold (zext (zext x)) -> (zext x)
5293   // fold (zext (aext x)) -> (zext x)
5294   if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5295     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
5296                        N0.getOperand(0));
5297
5298   // fold (zext (truncate x)) -> (zext x) or
5299   //      (zext (truncate x)) -> (truncate x)
5300   // This is valid when the truncated bits of x are already zero.
5301   // FIXME: We should extend this to work for vectors too.
5302   SDValue Op;
5303   APInt KnownZero;
5304   if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
5305     APInt TruncatedBits =
5306       (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
5307       APInt(Op.getValueSizeInBits(), 0) :
5308       APInt::getBitsSet(Op.getValueSizeInBits(),
5309                         N0.getValueSizeInBits(),
5310                         std::min(Op.getValueSizeInBits(),
5311                                  VT.getSizeInBits()));
5312     if (TruncatedBits == (KnownZero & TruncatedBits)) {
5313       if (VT.bitsGT(Op.getValueType()))
5314         return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
5315       if (VT.bitsLT(Op.getValueType()))
5316         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5317
5318       return Op;
5319     }
5320   }
5321
5322   // fold (zext (truncate (load x))) -> (zext (smaller load x))
5323   // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
5324   if (N0.getOpcode() == ISD::TRUNCATE) {
5325     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5326     if (NarrowLoad.getNode()) {
5327       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5328       if (NarrowLoad.getNode() != N0.getNode()) {
5329         CombineTo(N0.getNode(), NarrowLoad);
5330         // CombineTo deleted the truncate, if needed, but not what's under it.
5331         AddToWorklist(oye);
5332       }
5333       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5334     }
5335   }
5336
5337   // fold (zext (truncate x)) -> (and x, mask)
5338   if (N0.getOpcode() == ISD::TRUNCATE &&
5339       (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
5340
5341     // fold (zext (truncate (load x))) -> (zext (smaller load x))
5342     // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
5343     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5344     if (NarrowLoad.getNode()) {
5345       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5346       if (NarrowLoad.getNode() != N0.getNode()) {
5347         CombineTo(N0.getNode(), NarrowLoad);
5348         // CombineTo deleted the truncate, if needed, but not what's under it.
5349         AddToWorklist(oye);
5350       }
5351       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5352     }
5353
5354     SDValue Op = N0.getOperand(0);
5355     if (Op.getValueType().bitsLT(VT)) {
5356       Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
5357       AddToWorklist(Op.getNode());
5358     } else if (Op.getValueType().bitsGT(VT)) {
5359       Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5360       AddToWorklist(Op.getNode());
5361     }
5362     return DAG.getZeroExtendInReg(Op, SDLoc(N),
5363                                   N0.getValueType().getScalarType());
5364   }
5365
5366   // Fold (zext (and (trunc x), cst)) -> (and x, cst),
5367   // if either of the casts is not free.
5368   if (N0.getOpcode() == ISD::AND &&
5369       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5370       N0.getOperand(1).getOpcode() == ISD::Constant &&
5371       (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5372                            N0.getValueType()) ||
5373        !TLI.isZExtFree(N0.getValueType(), VT))) {
5374     SDValue X = N0.getOperand(0).getOperand(0);
5375     if (X.getValueType().bitsLT(VT)) {
5376       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
5377     } else if (X.getValueType().bitsGT(VT)) {
5378       X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
5379     }
5380     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5381     Mask = Mask.zext(VT.getSizeInBits());
5382     return DAG.getNode(ISD::AND, SDLoc(N), VT,
5383                        X, DAG.getConstant(Mask, VT));
5384   }
5385
5386   // fold (zext (load x)) -> (zext (truncate (zextload x)))
5387   // None of the supported targets knows how to perform load and vector_zext
5388   // on vectors in one instruction.  We only perform this transformation on
5389   // scalars.
5390   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5391       ISD::isUNINDEXEDLoad(N0.getNode()) &&
5392       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5393        TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()))) {
5394     bool DoXform = true;
5395     SmallVector<SDNode*, 4> SetCCs;
5396     if (!N0.hasOneUse())
5397       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
5398     if (DoXform) {
5399       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5400       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5401                                        LN0->getChain(),
5402                                        LN0->getBasePtr(), N0.getValueType(),
5403                                        LN0->getMemOperand());
5404       CombineTo(N, ExtLoad);
5405       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5406                                   N0.getValueType(), ExtLoad);
5407       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5408
5409       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5410                       ISD::ZERO_EXTEND);
5411       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5412     }
5413   }
5414
5415   // fold (zext (and/or/xor (load x), cst)) ->
5416   //      (and/or/xor (zextload x), (zext cst))
5417   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5418        N0.getOpcode() == ISD::XOR) &&
5419       isa<LoadSDNode>(N0.getOperand(0)) &&
5420       N0.getOperand(1).getOpcode() == ISD::Constant &&
5421       TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()) &&
5422       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5423     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5424     if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
5425       bool DoXform = true;
5426       SmallVector<SDNode*, 4> SetCCs;
5427       if (!N0.hasOneUse())
5428         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
5429                                           SetCCs, TLI);
5430       if (DoXform) {
5431         SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
5432                                          LN0->getChain(), LN0->getBasePtr(),
5433                                          LN0->getMemoryVT(),
5434                                          LN0->getMemOperand());
5435         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5436         Mask = Mask.zext(VT.getSizeInBits());
5437         SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5438                                   ExtLoad, DAG.getConstant(Mask, VT));
5439         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5440                                     SDLoc(N0.getOperand(0)),
5441                                     N0.getOperand(0).getValueType(), ExtLoad);
5442         CombineTo(N, And);
5443         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5444         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5445                         ISD::ZERO_EXTEND);
5446         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5447       }
5448     }
5449   }
5450
5451   // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
5452   // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
5453   if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5454       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5455     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5456     EVT MemVT = LN0->getMemoryVT();
5457     if ((!LegalOperations && !LN0->isVolatile()) ||
5458         TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT)) {
5459       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5460                                        LN0->getChain(),
5461                                        LN0->getBasePtr(), MemVT,
5462                                        LN0->getMemOperand());
5463       CombineTo(N, ExtLoad);
5464       CombineTo(N0.getNode(),
5465                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
5466                             ExtLoad),
5467                 ExtLoad.getValue(1));
5468       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5469     }
5470   }
5471
5472   if (N0.getOpcode() == ISD::SETCC) {
5473     if (!LegalOperations && VT.isVector() &&
5474         N0.getValueType().getVectorElementType() == MVT::i1) {
5475       EVT N0VT = N0.getOperand(0).getValueType();
5476       if (getSetCCResultType(N0VT) == N0.getValueType())
5477         return SDValue();
5478
5479       // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
5480       // Only do this before legalize for now.
5481       EVT EltVT = VT.getVectorElementType();
5482       SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
5483                                     DAG.getConstant(1, EltVT));
5484       if (VT.getSizeInBits() == N0VT.getSizeInBits())
5485         // We know that the # elements of the results is the same as the
5486         // # elements of the compare (and the # elements of the compare result
5487         // for that matter).  Check to see that they are the same size.  If so,
5488         // we know that the element size of the sext'd result matches the
5489         // element size of the compare operands.
5490         return DAG.getNode(ISD::AND, SDLoc(N), VT,
5491                            DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5492                                          N0.getOperand(1),
5493                                  cast<CondCodeSDNode>(N0.getOperand(2))->get()),
5494                            DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
5495                                        OneOps));
5496
5497       // If the desired elements are smaller or larger than the source
5498       // elements we can use a matching integer vector type and then
5499       // truncate/sign extend
5500       EVT MatchingElementType =
5501         EVT::getIntegerVT(*DAG.getContext(),
5502                           N0VT.getScalarType().getSizeInBits());
5503       EVT MatchingVectorType =
5504         EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
5505                          N0VT.getVectorNumElements());
5506       SDValue VsetCC =
5507         DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5508                       N0.getOperand(1),
5509                       cast<CondCodeSDNode>(N0.getOperand(2))->get());
5510       return DAG.getNode(ISD::AND, SDLoc(N), VT,
5511                          DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT),
5512                          DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, OneOps));
5513     }
5514
5515     // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5516     SDValue SCC =
5517       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5518                        DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5519                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5520     if (SCC.getNode()) return SCC;
5521   }
5522
5523   // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
5524   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
5525       isa<ConstantSDNode>(N0.getOperand(1)) &&
5526       N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
5527       N0.hasOneUse()) {
5528     SDValue ShAmt = N0.getOperand(1);
5529     unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
5530     if (N0.getOpcode() == ISD::SHL) {
5531       SDValue InnerZExt = N0.getOperand(0);
5532       // If the original shl may be shifting out bits, do not perform this
5533       // transformation.
5534       unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
5535         InnerZExt.getOperand(0).getValueType().getSizeInBits();
5536       if (ShAmtVal > KnownZeroBits)
5537         return SDValue();
5538     }
5539
5540     SDLoc DL(N);
5541
5542     // Ensure that the shift amount is wide enough for the shifted value.
5543     if (VT.getSizeInBits() >= 256)
5544       ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
5545
5546     return DAG.getNode(N0.getOpcode(), DL, VT,
5547                        DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
5548                        ShAmt);
5549   }
5550
5551   return SDValue();
5552 }
5553
5554 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
5555   SDValue N0 = N->getOperand(0);
5556   EVT VT = N->getValueType(0);
5557
5558   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5559                                               LegalOperations))
5560     return SDValue(Res, 0);
5561
5562   // fold (aext (aext x)) -> (aext x)
5563   // fold (aext (zext x)) -> (zext x)
5564   // fold (aext (sext x)) -> (sext x)
5565   if (N0.getOpcode() == ISD::ANY_EXTEND  ||
5566       N0.getOpcode() == ISD::ZERO_EXTEND ||
5567       N0.getOpcode() == ISD::SIGN_EXTEND)
5568     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
5569
5570   // fold (aext (truncate (load x))) -> (aext (smaller load x))
5571   // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
5572   if (N0.getOpcode() == ISD::TRUNCATE) {
5573     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5574     if (NarrowLoad.getNode()) {
5575       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5576       if (NarrowLoad.getNode() != N0.getNode()) {
5577         CombineTo(N0.getNode(), NarrowLoad);
5578         // CombineTo deleted the truncate, if needed, but not what's under it.
5579         AddToWorklist(oye);
5580       }
5581       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5582     }
5583   }
5584
5585   // fold (aext (truncate x))
5586   if (N0.getOpcode() == ISD::TRUNCATE) {
5587     SDValue TruncOp = N0.getOperand(0);
5588     if (TruncOp.getValueType() == VT)
5589       return TruncOp; // x iff x size == zext size.
5590     if (TruncOp.getValueType().bitsGT(VT))
5591       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
5592     return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
5593   }
5594
5595   // Fold (aext (and (trunc x), cst)) -> (and x, cst)
5596   // if the trunc is not free.
5597   if (N0.getOpcode() == ISD::AND &&
5598       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5599       N0.getOperand(1).getOpcode() == ISD::Constant &&
5600       !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5601                           N0.getValueType())) {
5602     SDValue X = N0.getOperand(0).getOperand(0);
5603     if (X.getValueType().bitsLT(VT)) {
5604       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
5605     } else if (X.getValueType().bitsGT(VT)) {
5606       X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
5607     }
5608     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5609     Mask = Mask.zext(VT.getSizeInBits());
5610     return DAG.getNode(ISD::AND, SDLoc(N), VT,
5611                        X, DAG.getConstant(Mask, VT));
5612   }
5613
5614   // fold (aext (load x)) -> (aext (truncate (extload x)))
5615   // None of the supported targets knows how to perform load and any_ext
5616   // on vectors in one instruction.  We only perform this transformation on
5617   // scalars.
5618   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5619       ISD::isUNINDEXEDLoad(N0.getNode()) &&
5620       TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType())) {
5621     bool DoXform = true;
5622     SmallVector<SDNode*, 4> SetCCs;
5623     if (!N0.hasOneUse())
5624       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
5625     if (DoXform) {
5626       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5627       SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
5628                                        LN0->getChain(),
5629                                        LN0->getBasePtr(), N0.getValueType(),
5630                                        LN0->getMemOperand());
5631       CombineTo(N, ExtLoad);
5632       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5633                                   N0.getValueType(), ExtLoad);
5634       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5635       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5636                       ISD::ANY_EXTEND);
5637       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5638     }
5639   }
5640
5641   // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
5642   // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
5643   // fold (aext ( extload x)) -> (aext (truncate (extload  x)))
5644   if (N0.getOpcode() == ISD::LOAD &&
5645       !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5646       N0.hasOneUse()) {
5647     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5648     ISD::LoadExtType ExtType = LN0->getExtensionType();
5649     EVT MemVT = LN0->getMemoryVT();
5650     if (!LegalOperations || TLI.isLoadExtLegal(ExtType, MemVT)) {
5651       SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
5652                                        VT, LN0->getChain(), LN0->getBasePtr(),
5653                                        MemVT, LN0->getMemOperand());
5654       CombineTo(N, ExtLoad);
5655       CombineTo(N0.getNode(),
5656                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5657                             N0.getValueType(), ExtLoad),
5658                 ExtLoad.getValue(1));
5659       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5660     }
5661   }
5662
5663   if (N0.getOpcode() == ISD::SETCC) {
5664     // For vectors:
5665     // aext(setcc) -> vsetcc
5666     // aext(setcc) -> truncate(vsetcc)
5667     // aext(setcc) -> aext(vsetcc)
5668     // Only do this before legalize for now.
5669     if (VT.isVector() && !LegalOperations) {
5670       EVT N0VT = N0.getOperand(0).getValueType();
5671         // We know that the # elements of the results is the same as the
5672         // # elements of the compare (and the # elements of the compare result
5673         // for that matter).  Check to see that they are the same size.  If so,
5674         // we know that the element size of the sext'd result matches the
5675         // element size of the compare operands.
5676       if (VT.getSizeInBits() == N0VT.getSizeInBits())
5677         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5678                              N0.getOperand(1),
5679                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
5680       // If the desired elements are smaller or larger than the source
5681       // elements we can use a matching integer vector type and then
5682       // truncate/any extend
5683       else {
5684         EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5685         SDValue VsetCC =
5686           DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5687                         N0.getOperand(1),
5688                         cast<CondCodeSDNode>(N0.getOperand(2))->get());
5689         return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
5690       }
5691     }
5692
5693     // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5694     SDValue SCC =
5695       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5696                        DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5697                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5698     if (SCC.getNode())
5699       return SCC;
5700   }
5701
5702   return SDValue();
5703 }
5704
5705 /// See if the specified operand can be simplified with the knowledge that only
5706 /// the bits specified by Mask are used.  If so, return the simpler operand,
5707 /// otherwise return a null SDValue.
5708 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
5709   switch (V.getOpcode()) {
5710   default: break;
5711   case ISD::Constant: {
5712     const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
5713     assert(CV && "Const value should be ConstSDNode.");
5714     const APInt &CVal = CV->getAPIntValue();
5715     APInt NewVal = CVal & Mask;
5716     if (NewVal != CVal)
5717       return DAG.getConstant(NewVal, V.getValueType());
5718     break;
5719   }
5720   case ISD::OR:
5721   case ISD::XOR:
5722     // If the LHS or RHS don't contribute bits to the or, drop them.
5723     if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
5724       return V.getOperand(1);
5725     if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
5726       return V.getOperand(0);
5727     break;
5728   case ISD::SRL:
5729     // Only look at single-use SRLs.
5730     if (!V.getNode()->hasOneUse())
5731       break;
5732     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
5733       // See if we can recursively simplify the LHS.
5734       unsigned Amt = RHSC->getZExtValue();
5735
5736       // Watch out for shift count overflow though.
5737       if (Amt >= Mask.getBitWidth()) break;
5738       APInt NewMask = Mask << Amt;
5739       SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
5740       if (SimplifyLHS.getNode())
5741         return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
5742                            SimplifyLHS, V.getOperand(1));
5743     }
5744   }
5745   return SDValue();
5746 }
5747
5748 /// If the result of a wider load is shifted to right of N  bits and then
5749 /// truncated to a narrower type and where N is a multiple of number of bits of
5750 /// the narrower type, transform it to a narrower load from address + N / num of
5751 /// bits of new type. If the result is to be extended, also fold the extension
5752 /// to form a extending load.
5753 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
5754   unsigned Opc = N->getOpcode();
5755
5756   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
5757   SDValue N0 = N->getOperand(0);
5758   EVT VT = N->getValueType(0);
5759   EVT ExtVT = VT;
5760
5761   // This transformation isn't valid for vector loads.
5762   if (VT.isVector())
5763     return SDValue();
5764
5765   // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
5766   // extended to VT.
5767   if (Opc == ISD::SIGN_EXTEND_INREG) {
5768     ExtType = ISD::SEXTLOAD;
5769     ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
5770   } else if (Opc == ISD::SRL) {
5771     // Another special-case: SRL is basically zero-extending a narrower value.
5772     ExtType = ISD::ZEXTLOAD;
5773     N0 = SDValue(N, 0);
5774     ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
5775     if (!N01) return SDValue();
5776     ExtVT = EVT::getIntegerVT(*DAG.getContext(),
5777                               VT.getSizeInBits() - N01->getZExtValue());
5778   }
5779   if (LegalOperations && !TLI.isLoadExtLegal(ExtType, ExtVT))
5780     return SDValue();
5781
5782   unsigned EVTBits = ExtVT.getSizeInBits();
5783
5784   // Do not generate loads of non-round integer types since these can
5785   // be expensive (and would be wrong if the type is not byte sized).
5786   if (!ExtVT.isRound())
5787     return SDValue();
5788
5789   unsigned ShAmt = 0;
5790   if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
5791     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5792       ShAmt = N01->getZExtValue();
5793       // Is the shift amount a multiple of size of VT?
5794       if ((ShAmt & (EVTBits-1)) == 0) {
5795         N0 = N0.getOperand(0);
5796         // Is the load width a multiple of size of VT?
5797         if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
5798           return SDValue();
5799       }
5800
5801       // At this point, we must have a load or else we can't do the transform.
5802       if (!isa<LoadSDNode>(N0)) return SDValue();
5803
5804       // Because a SRL must be assumed to *need* to zero-extend the high bits
5805       // (as opposed to anyext the high bits), we can't combine the zextload
5806       // lowering of SRL and an sextload.
5807       if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
5808         return SDValue();
5809
5810       // If the shift amount is larger than the input type then we're not
5811       // accessing any of the loaded bytes.  If the load was a zextload/extload
5812       // then the result of the shift+trunc is zero/undef (handled elsewhere).
5813       if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
5814         return SDValue();
5815     }
5816   }
5817
5818   // If the load is shifted left (and the result isn't shifted back right),
5819   // we can fold the truncate through the shift.
5820   unsigned ShLeftAmt = 0;
5821   if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
5822       ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
5823     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5824       ShLeftAmt = N01->getZExtValue();
5825       N0 = N0.getOperand(0);
5826     }
5827   }
5828
5829   // If we haven't found a load, we can't narrow it.  Don't transform one with
5830   // multiple uses, this would require adding a new load.
5831   if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
5832     return SDValue();
5833
5834   // Don't change the width of a volatile load.
5835   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5836   if (LN0->isVolatile())
5837     return SDValue();
5838
5839   // Verify that we are actually reducing a load width here.
5840   if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
5841     return SDValue();
5842
5843   // For the transform to be legal, the load must produce only two values
5844   // (the value loaded and the chain).  Don't transform a pre-increment
5845   // load, for example, which produces an extra value.  Otherwise the
5846   // transformation is not equivalent, and the downstream logic to replace
5847   // uses gets things wrong.
5848   if (LN0->getNumValues() > 2)
5849     return SDValue();
5850
5851   // If the load that we're shrinking is an extload and we're not just
5852   // discarding the extension we can't simply shrink the load. Bail.
5853   // TODO: It would be possible to merge the extensions in some cases.
5854   if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
5855       LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
5856     return SDValue();
5857
5858   EVT PtrType = N0.getOperand(1).getValueType();
5859
5860   if (PtrType == MVT::Untyped || PtrType.isExtended())
5861     // It's not possible to generate a constant of extended or untyped type.
5862     return SDValue();
5863
5864   // For big endian targets, we need to adjust the offset to the pointer to
5865   // load the correct bytes.
5866   if (TLI.isBigEndian()) {
5867     unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
5868     unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
5869     ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
5870   }
5871
5872   uint64_t PtrOff = ShAmt / 8;
5873   unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
5874   SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0),
5875                                PtrType, LN0->getBasePtr(),
5876                                DAG.getConstant(PtrOff, PtrType));
5877   AddToWorklist(NewPtr.getNode());
5878
5879   SDValue Load;
5880   if (ExtType == ISD::NON_EXTLOAD)
5881     Load =  DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
5882                         LN0->getPointerInfo().getWithOffset(PtrOff),
5883                         LN0->isVolatile(), LN0->isNonTemporal(),
5884                         LN0->isInvariant(), NewAlign, LN0->getAAInfo());
5885   else
5886     Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
5887                           LN0->getPointerInfo().getWithOffset(PtrOff),
5888                           ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
5889                           LN0->isInvariant(), NewAlign, LN0->getAAInfo());
5890
5891   // Replace the old load's chain with the new load's chain.
5892   WorklistRemover DeadNodes(*this);
5893   DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
5894
5895   // Shift the result left, if we've swallowed a left shift.
5896   SDValue Result = Load;
5897   if (ShLeftAmt != 0) {
5898     EVT ShImmTy = getShiftAmountTy(Result.getValueType());
5899     if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
5900       ShImmTy = VT;
5901     // If the shift amount is as large as the result size (but, presumably,
5902     // no larger than the source) then the useful bits of the result are
5903     // zero; we can't simply return the shortened shift, because the result
5904     // of that operation is undefined.
5905     if (ShLeftAmt >= VT.getSizeInBits())
5906       Result = DAG.getConstant(0, VT);
5907     else
5908       Result = DAG.getNode(ISD::SHL, SDLoc(N0), VT,
5909                           Result, DAG.getConstant(ShLeftAmt, ShImmTy));
5910   }
5911
5912   // Return the new loaded value.
5913   return Result;
5914 }
5915
5916 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
5917   SDValue N0 = N->getOperand(0);
5918   SDValue N1 = N->getOperand(1);
5919   EVT VT = N->getValueType(0);
5920   EVT EVT = cast<VTSDNode>(N1)->getVT();
5921   unsigned VTBits = VT.getScalarType().getSizeInBits();
5922   unsigned EVTBits = EVT.getScalarType().getSizeInBits();
5923
5924   // fold (sext_in_reg c1) -> c1
5925   if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
5926     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
5927
5928   // If the input is already sign extended, just drop the extension.
5929   if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
5930     return N0;
5931
5932   // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
5933   if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
5934       EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
5935     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5936                        N0.getOperand(0), N1);
5937
5938   // fold (sext_in_reg (sext x)) -> (sext x)
5939   // fold (sext_in_reg (aext x)) -> (sext x)
5940   // if x is small enough.
5941   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
5942     SDValue N00 = N0.getOperand(0);
5943     if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
5944         (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
5945       return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
5946   }
5947
5948   // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
5949   if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
5950     return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
5951
5952   // fold operands of sext_in_reg based on knowledge that the top bits are not
5953   // demanded.
5954   if (SimplifyDemandedBits(SDValue(N, 0)))
5955     return SDValue(N, 0);
5956
5957   // fold (sext_in_reg (load x)) -> (smaller sextload x)
5958   // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
5959   SDValue NarrowLoad = ReduceLoadWidth(N);
5960   if (NarrowLoad.getNode())
5961     return NarrowLoad;
5962
5963   // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
5964   // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
5965   // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
5966   if (N0.getOpcode() == ISD::SRL) {
5967     if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
5968       if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
5969         // We can turn this into an SRA iff the input to the SRL is already sign
5970         // extended enough.
5971         unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
5972         if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
5973           return DAG.getNode(ISD::SRA, SDLoc(N), VT,
5974                              N0.getOperand(0), N0.getOperand(1));
5975       }
5976   }
5977
5978   // fold (sext_inreg (extload x)) -> (sextload x)
5979   if (ISD::isEXTLoad(N0.getNode()) &&
5980       ISD::isUNINDEXEDLoad(N0.getNode()) &&
5981       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5982       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5983        TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5984     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5985     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5986                                      LN0->getChain(),
5987                                      LN0->getBasePtr(), EVT,
5988                                      LN0->getMemOperand());
5989     CombineTo(N, ExtLoad);
5990     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5991     AddToWorklist(ExtLoad.getNode());
5992     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5993   }
5994   // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
5995   if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5996       N0.hasOneUse() &&
5997       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5998       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5999        TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
6000     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6001     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6002                                      LN0->getChain(),
6003                                      LN0->getBasePtr(), EVT,
6004                                      LN0->getMemOperand());
6005     CombineTo(N, ExtLoad);
6006     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6007     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6008   }
6009
6010   // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
6011   if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
6012     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
6013                                        N0.getOperand(1), false);
6014     if (BSwap.getNode())
6015       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6016                          BSwap, N1);
6017   }
6018
6019   // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs
6020   // into a build_vector.
6021   if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
6022     SmallVector<SDValue, 8> Elts;
6023     unsigned NumElts = N0->getNumOperands();
6024     unsigned ShAmt = VTBits - EVTBits;
6025
6026     for (unsigned i = 0; i != NumElts; ++i) {
6027       SDValue Op = N0->getOperand(i);
6028       if (Op->getOpcode() == ISD::UNDEF) {
6029         Elts.push_back(Op);
6030         continue;
6031       }
6032
6033       ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
6034       const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
6035       Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
6036                                      Op.getValueType()));
6037     }
6038
6039     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Elts);
6040   }
6041
6042   return SDValue();
6043 }
6044
6045 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
6046   SDValue N0 = N->getOperand(0);
6047   EVT VT = N->getValueType(0);
6048   bool isLE = TLI.isLittleEndian();
6049
6050   // noop truncate
6051   if (N0.getValueType() == N->getValueType(0))
6052     return N0;
6053   // fold (truncate c1) -> c1
6054   if (isa<ConstantSDNode>(N0))
6055     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
6056   // fold (truncate (truncate x)) -> (truncate x)
6057   if (N0.getOpcode() == ISD::TRUNCATE)
6058     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6059   // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
6060   if (N0.getOpcode() == ISD::ZERO_EXTEND ||
6061       N0.getOpcode() == ISD::SIGN_EXTEND ||
6062       N0.getOpcode() == ISD::ANY_EXTEND) {
6063     if (N0.getOperand(0).getValueType().bitsLT(VT))
6064       // if the source is smaller than the dest, we still need an extend
6065       return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
6066                          N0.getOperand(0));
6067     if (N0.getOperand(0).getValueType().bitsGT(VT))
6068       // if the source is larger than the dest, than we just need the truncate
6069       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6070     // if the source and dest are the same type, we can drop both the extend
6071     // and the truncate.
6072     return N0.getOperand(0);
6073   }
6074
6075   // Fold extract-and-trunc into a narrow extract. For example:
6076   //   i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
6077   //   i32 y = TRUNCATE(i64 x)
6078   //        -- becomes --
6079   //   v16i8 b = BITCAST (v2i64 val)
6080   //   i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
6081   //
6082   // Note: We only run this optimization after type legalization (which often
6083   // creates this pattern) and before operation legalization after which
6084   // we need to be more careful about the vector instructions that we generate.
6085   if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6086       LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
6087
6088     EVT VecTy = N0.getOperand(0).getValueType();
6089     EVT ExTy = N0.getValueType();
6090     EVT TrTy = N->getValueType(0);
6091
6092     unsigned NumElem = VecTy.getVectorNumElements();
6093     unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
6094
6095     EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
6096     assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
6097
6098     SDValue EltNo = N0->getOperand(1);
6099     if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
6100       int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
6101       EVT IndexTy = TLI.getVectorIdxTy();
6102       int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
6103
6104       SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
6105                               NVT, N0.getOperand(0));
6106
6107       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
6108                          SDLoc(N), TrTy, V,
6109                          DAG.getConstant(Index, IndexTy));
6110     }
6111   }
6112
6113   // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
6114   if (N0.getOpcode() == ISD::SELECT) {
6115     EVT SrcVT = N0.getValueType();
6116     if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
6117         TLI.isTruncateFree(SrcVT, VT)) {
6118       SDLoc SL(N0);
6119       SDValue Cond = N0.getOperand(0);
6120       SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
6121       SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
6122       return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
6123     }
6124   }
6125
6126   // Fold a series of buildvector, bitcast, and truncate if possible.
6127   // For example fold
6128   //   (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
6129   //   (2xi32 (buildvector x, y)).
6130   if (Level == AfterLegalizeVectorOps && VT.isVector() &&
6131       N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
6132       N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
6133       N0.getOperand(0).hasOneUse()) {
6134
6135     SDValue BuildVect = N0.getOperand(0);
6136     EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
6137     EVT TruncVecEltTy = VT.getVectorElementType();
6138
6139     // Check that the element types match.
6140     if (BuildVectEltTy == TruncVecEltTy) {
6141       // Now we only need to compute the offset of the truncated elements.
6142       unsigned BuildVecNumElts =  BuildVect.getNumOperands();
6143       unsigned TruncVecNumElts = VT.getVectorNumElements();
6144       unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
6145
6146       assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
6147              "Invalid number of elements");
6148
6149       SmallVector<SDValue, 8> Opnds;
6150       for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
6151         Opnds.push_back(BuildVect.getOperand(i));
6152
6153       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
6154     }
6155   }
6156
6157   // See if we can simplify the input to this truncate through knowledge that
6158   // only the low bits are being used.
6159   // For example "trunc (or (shl x, 8), y)" // -> trunc y
6160   // Currently we only perform this optimization on scalars because vectors
6161   // may have different active low bits.
6162   if (!VT.isVector()) {
6163     SDValue Shorter =
6164       GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
6165                                                VT.getSizeInBits()));
6166     if (Shorter.getNode())
6167       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
6168   }
6169   // fold (truncate (load x)) -> (smaller load x)
6170   // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
6171   if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
6172     SDValue Reduced = ReduceLoadWidth(N);
6173     if (Reduced.getNode())
6174       return Reduced;
6175     // Handle the case where the load remains an extending load even
6176     // after truncation.
6177     if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
6178       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6179       if (!LN0->isVolatile() &&
6180           LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
6181         SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
6182                                          VT, LN0->getChain(), LN0->getBasePtr(),
6183                                          LN0->getMemoryVT(),
6184                                          LN0->getMemOperand());
6185         DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
6186         return NewLoad;
6187       }
6188     }
6189   }
6190   // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
6191   // where ... are all 'undef'.
6192   if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
6193     SmallVector<EVT, 8> VTs;
6194     SDValue V;
6195     unsigned Idx = 0;
6196     unsigned NumDefs = 0;
6197
6198     for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
6199       SDValue X = N0.getOperand(i);
6200       if (X.getOpcode() != ISD::UNDEF) {
6201         V = X;
6202         Idx = i;
6203         NumDefs++;
6204       }
6205       // Stop if more than one members are non-undef.
6206       if (NumDefs > 1)
6207         break;
6208       VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
6209                                      VT.getVectorElementType(),
6210                                      X.getValueType().getVectorNumElements()));
6211     }
6212
6213     if (NumDefs == 0)
6214       return DAG.getUNDEF(VT);
6215
6216     if (NumDefs == 1) {
6217       assert(V.getNode() && "The single defined operand is empty!");
6218       SmallVector<SDValue, 8> Opnds;
6219       for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
6220         if (i != Idx) {
6221           Opnds.push_back(DAG.getUNDEF(VTs[i]));
6222           continue;
6223         }
6224         SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
6225         AddToWorklist(NV.getNode());
6226         Opnds.push_back(NV);
6227       }
6228       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
6229     }
6230   }
6231
6232   // Simplify the operands using demanded-bits information.
6233   if (!VT.isVector() &&
6234       SimplifyDemandedBits(SDValue(N, 0)))
6235     return SDValue(N, 0);
6236
6237   return SDValue();
6238 }
6239
6240 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
6241   SDValue Elt = N->getOperand(i);
6242   if (Elt.getOpcode() != ISD::MERGE_VALUES)
6243     return Elt.getNode();
6244   return Elt.getOperand(Elt.getResNo()).getNode();
6245 }
6246
6247 /// build_pair (load, load) -> load
6248 /// if load locations are consecutive.
6249 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
6250   assert(N->getOpcode() == ISD::BUILD_PAIR);
6251
6252   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
6253   LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
6254   if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
6255       LD1->getAddressSpace() != LD2->getAddressSpace())
6256     return SDValue();
6257   EVT LD1VT = LD1->getValueType(0);
6258
6259   if (ISD::isNON_EXTLoad(LD2) &&
6260       LD2->hasOneUse() &&
6261       // If both are volatile this would reduce the number of volatile loads.
6262       // If one is volatile it might be ok, but play conservative and bail out.
6263       !LD1->isVolatile() &&
6264       !LD2->isVolatile() &&
6265       DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
6266     unsigned Align = LD1->getAlignment();
6267     unsigned NewAlign = TLI.getDataLayout()->
6268       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6269
6270     if (NewAlign <= Align &&
6271         (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
6272       return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
6273                          LD1->getBasePtr(), LD1->getPointerInfo(),
6274                          false, false, false, Align);
6275   }
6276
6277   return SDValue();
6278 }
6279
6280 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
6281   SDValue N0 = N->getOperand(0);
6282   EVT VT = N->getValueType(0);
6283
6284   // If the input is a BUILD_VECTOR with all constant elements, fold this now.
6285   // Only do this before legalize, since afterward the target may be depending
6286   // on the bitconvert.
6287   // First check to see if this is all constant.
6288   if (!LegalTypes &&
6289       N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
6290       VT.isVector()) {
6291     bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
6292
6293     EVT DestEltVT = N->getValueType(0).getVectorElementType();
6294     assert(!DestEltVT.isVector() &&
6295            "Element type of vector ValueType must not be vector!");
6296     if (isSimple)
6297       return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
6298   }
6299
6300   // If the input is a constant, let getNode fold it.
6301   if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
6302     SDValue Res = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
6303     if (Res.getNode() != N) {
6304       if (!LegalOperations ||
6305           TLI.isOperationLegal(Res.getNode()->getOpcode(), VT))
6306         return Res;
6307
6308       // Folding it resulted in an illegal node, and it's too late to
6309       // do that. Clean up the old node and forego the transformation.
6310       // Ideally this won't happen very often, because instcombine
6311       // and the earlier dagcombine runs (where illegal nodes are
6312       // permitted) should have folded most of them already.
6313       deleteAndRecombine(Res.getNode());
6314     }
6315   }
6316
6317   // (conv (conv x, t1), t2) -> (conv x, t2)
6318   if (N0.getOpcode() == ISD::BITCAST)
6319     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
6320                        N0.getOperand(0));
6321
6322   // fold (conv (load x)) -> (load (conv*)x)
6323   // If the resultant load doesn't need a higher alignment than the original!
6324   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
6325       // Do not change the width of a volatile load.
6326       !cast<LoadSDNode>(N0)->isVolatile() &&
6327       // Do not remove the cast if the types differ in endian layout.
6328       TLI.hasBigEndianPartOrdering(N0.getValueType()) ==
6329       TLI.hasBigEndianPartOrdering(VT) &&
6330       (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
6331       TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
6332     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6333     unsigned Align = TLI.getDataLayout()->
6334       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6335     unsigned OrigAlign = LN0->getAlignment();
6336
6337     if (Align <= OrigAlign) {
6338       SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
6339                                  LN0->getBasePtr(), LN0->getPointerInfo(),
6340                                  LN0->isVolatile(), LN0->isNonTemporal(),
6341                                  LN0->isInvariant(), OrigAlign,
6342                                  LN0->getAAInfo());
6343       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
6344       return Load;
6345     }
6346   }
6347
6348   // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
6349   // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
6350   // This often reduces constant pool loads.
6351   if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
6352        (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
6353       N0.getNode()->hasOneUse() && VT.isInteger() &&
6354       !VT.isVector() && !N0.getValueType().isVector()) {
6355     SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
6356                                   N0.getOperand(0));
6357     AddToWorklist(NewConv.getNode());
6358
6359     APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6360     if (N0.getOpcode() == ISD::FNEG)
6361       return DAG.getNode(ISD::XOR, SDLoc(N), VT,
6362                          NewConv, DAG.getConstant(SignBit, VT));
6363     assert(N0.getOpcode() == ISD::FABS);
6364     return DAG.getNode(ISD::AND, SDLoc(N), VT,
6365                        NewConv, DAG.getConstant(~SignBit, VT));
6366   }
6367
6368   // fold (bitconvert (fcopysign cst, x)) ->
6369   //         (or (and (bitconvert x), sign), (and cst, (not sign)))
6370   // Note that we don't handle (copysign x, cst) because this can always be
6371   // folded to an fneg or fabs.
6372   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
6373       isa<ConstantFPSDNode>(N0.getOperand(0)) &&
6374       VT.isInteger() && !VT.isVector()) {
6375     unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
6376     EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
6377     if (isTypeLegal(IntXVT)) {
6378       SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6379                               IntXVT, N0.getOperand(1));
6380       AddToWorklist(X.getNode());
6381
6382       // If X has a different width than the result/lhs, sext it or truncate it.
6383       unsigned VTWidth = VT.getSizeInBits();
6384       if (OrigXWidth < VTWidth) {
6385         X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
6386         AddToWorklist(X.getNode());
6387       } else if (OrigXWidth > VTWidth) {
6388         // To get the sign bit in the right place, we have to shift it right
6389         // before truncating.
6390         X = DAG.getNode(ISD::SRL, SDLoc(X),
6391                         X.getValueType(), X,
6392                         DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
6393         AddToWorklist(X.getNode());
6394         X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
6395         AddToWorklist(X.getNode());
6396       }
6397
6398       APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6399       X = DAG.getNode(ISD::AND, SDLoc(X), VT,
6400                       X, DAG.getConstant(SignBit, VT));
6401       AddToWorklist(X.getNode());
6402
6403       SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6404                                 VT, N0.getOperand(0));
6405       Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
6406                         Cst, DAG.getConstant(~SignBit, VT));
6407       AddToWorklist(Cst.getNode());
6408
6409       return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
6410     }
6411   }
6412
6413   // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
6414   if (N0.getOpcode() == ISD::BUILD_PAIR) {
6415     SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
6416     if (CombineLD.getNode())
6417       return CombineLD;
6418   }
6419
6420   return SDValue();
6421 }
6422
6423 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
6424   EVT VT = N->getValueType(0);
6425   return CombineConsecutiveLoads(N, VT);
6426 }
6427
6428 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef
6429 /// operands. DstEltVT indicates the destination element value type.
6430 SDValue DAGCombiner::
6431 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
6432   EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
6433
6434   // If this is already the right type, we're done.
6435   if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
6436
6437   unsigned SrcBitSize = SrcEltVT.getSizeInBits();
6438   unsigned DstBitSize = DstEltVT.getSizeInBits();
6439
6440   // If this is a conversion of N elements of one type to N elements of another
6441   // type, convert each element.  This handles FP<->INT cases.
6442   if (SrcBitSize == DstBitSize) {
6443     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6444                               BV->getValueType(0).getVectorNumElements());
6445
6446     // Due to the FP element handling below calling this routine recursively,
6447     // we can end up with a scalar-to-vector node here.
6448     if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
6449       return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6450                          DAG.getNode(ISD::BITCAST, SDLoc(BV),
6451                                      DstEltVT, BV->getOperand(0)));
6452
6453     SmallVector<SDValue, 8> Ops;
6454     for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6455       SDValue Op = BV->getOperand(i);
6456       // If the vector element type is not legal, the BUILD_VECTOR operands
6457       // are promoted and implicitly truncated.  Make that explicit here.
6458       if (Op.getValueType() != SrcEltVT)
6459         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
6460       Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
6461                                 DstEltVT, Op));
6462       AddToWorklist(Ops.back().getNode());
6463     }
6464     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6465   }
6466
6467   // Otherwise, we're growing or shrinking the elements.  To avoid having to
6468   // handle annoying details of growing/shrinking FP values, we convert them to
6469   // int first.
6470   if (SrcEltVT.isFloatingPoint()) {
6471     // Convert the input float vector to a int vector where the elements are the
6472     // same sizes.
6473     assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!");
6474     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
6475     BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
6476     SrcEltVT = IntVT;
6477   }
6478
6479   // Now we know the input is an integer vector.  If the output is a FP type,
6480   // convert to integer first, then to FP of the right size.
6481   if (DstEltVT.isFloatingPoint()) {
6482     assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!");
6483     EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
6484     SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
6485
6486     // Next, convert to FP elements of the same size.
6487     return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
6488   }
6489
6490   // Okay, we know the src/dst types are both integers of differing types.
6491   // Handling growing first.
6492   assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
6493   if (SrcBitSize < DstBitSize) {
6494     unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
6495
6496     SmallVector<SDValue, 8> Ops;
6497     for (unsigned i = 0, e = BV->getNumOperands(); i != e;
6498          i += NumInputsPerOutput) {
6499       bool isLE = TLI.isLittleEndian();
6500       APInt NewBits = APInt(DstBitSize, 0);
6501       bool EltIsUndef = true;
6502       for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
6503         // Shift the previously computed bits over.
6504         NewBits <<= SrcBitSize;
6505         SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
6506         if (Op.getOpcode() == ISD::UNDEF) continue;
6507         EltIsUndef = false;
6508
6509         NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
6510                    zextOrTrunc(SrcBitSize).zext(DstBitSize);
6511       }
6512
6513       if (EltIsUndef)
6514         Ops.push_back(DAG.getUNDEF(DstEltVT));
6515       else
6516         Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
6517     }
6518
6519     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
6520     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6521   }
6522
6523   // Finally, this must be the case where we are shrinking elements: each input
6524   // turns into multiple outputs.
6525   bool isS2V = ISD::isScalarToVector(BV);
6526   unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
6527   EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6528                             NumOutputsPerInput*BV->getNumOperands());
6529   SmallVector<SDValue, 8> Ops;
6530
6531   for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6532     if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
6533       for (unsigned j = 0; j != NumOutputsPerInput; ++j)
6534         Ops.push_back(DAG.getUNDEF(DstEltVT));
6535       continue;
6536     }
6537
6538     APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
6539                   getAPIntValue().zextOrTrunc(SrcBitSize);
6540
6541     for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
6542       APInt ThisVal = OpVal.trunc(DstBitSize);
6543       Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
6544       if (isS2V && i == 0 && j == 0 && ThisVal.zext(SrcBitSize) == OpVal)
6545         // Simply turn this into a SCALAR_TO_VECTOR of the new type.
6546         return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6547                            Ops[0]);
6548       OpVal = OpVal.lshr(DstBitSize);
6549     }
6550
6551     // For big endian targets, swap the order of the pieces of each element.
6552     if (TLI.isBigEndian())
6553       std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
6554   }
6555
6556   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6557 }
6558
6559 SDValue DAGCombiner::visitFADD(SDNode *N) {
6560   SDValue N0 = N->getOperand(0);
6561   SDValue N1 = N->getOperand(1);
6562   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6563   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6564   EVT VT = N->getValueType(0);
6565   const TargetOptions &Options = DAG.getTarget().Options;
6566   
6567   // fold vector ops
6568   if (VT.isVector()) {
6569     SDValue FoldedVOp = SimplifyVBinOp(N);
6570     if (FoldedVOp.getNode()) return FoldedVOp;
6571   }
6572
6573   // fold (fadd c1, c2) -> c1 + c2
6574   if (N0CFP && N1CFP)
6575     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N1);
6576
6577   // canonicalize constant to RHS
6578   if (N0CFP && !N1CFP)
6579     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N0);
6580
6581   // fold (fadd A, (fneg B)) -> (fsub A, B)
6582   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6583       isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2)
6584     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0,
6585                        GetNegatedExpression(N1, DAG, LegalOperations));
6586   
6587   // fold (fadd (fneg A), B) -> (fsub B, A)
6588   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6589       isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2)
6590     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N1,
6591                        GetNegatedExpression(N0, DAG, LegalOperations));
6592
6593   // If 'unsafe math' is enabled, fold lots of things.
6594   if (Options.UnsafeFPMath) {
6595     // No FP constant should be created after legalization as Instruction
6596     // Selection pass has a hard time dealing with FP constants.
6597     bool AllowNewConst = (Level < AfterLegalizeDAG);
6598     
6599     // fold (fadd A, 0) -> A
6600     if (N1CFP && N1CFP->getValueAPF().isZero())
6601       return N0;
6602
6603     // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
6604     if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
6605         isa<ConstantFPSDNode>(N0.getOperand(1)))
6606       return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0.getOperand(0),
6607                          DAG.getNode(ISD::FADD, SDLoc(N), VT,
6608                                      N0.getOperand(1), N1));
6609     
6610     // If allowed, fold (fadd (fneg x), x) -> 0.0
6611     if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
6612       return DAG.getConstantFP(0.0, VT);
6613     
6614     // If allowed, fold (fadd x, (fneg x)) -> 0.0
6615     if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
6616       return DAG.getConstantFP(0.0, VT);
6617     
6618     // We can fold chains of FADD's of the same value into multiplications.
6619     // This transform is not safe in general because we are reducing the number
6620     // of rounding steps.
6621     if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) {
6622       if (N0.getOpcode() == ISD::FMUL) {
6623         ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6624         ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
6625         
6626         // (fadd (fmul x, c), x) -> (fmul x, c+1)
6627         if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
6628           SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6629                                        SDValue(CFP01, 0),
6630                                        DAG.getConstantFP(1.0, VT));
6631           return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, NewCFP);
6632         }
6633         
6634         // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
6635         if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
6636             N1.getOperand(0) == N1.getOperand(1) &&
6637             N0.getOperand(0) == N1.getOperand(0)) {
6638           SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6639                                        SDValue(CFP01, 0),
6640                                        DAG.getConstantFP(2.0, VT));
6641           return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6642                              N0.getOperand(0), NewCFP);
6643         }
6644       }
6645       
6646       if (N1.getOpcode() == ISD::FMUL) {
6647         ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6648         ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
6649         
6650         // (fadd x, (fmul x, c)) -> (fmul x, c+1)
6651         if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
6652           SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6653                                        SDValue(CFP11, 0),
6654                                        DAG.getConstantFP(1.0, VT));
6655           return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, NewCFP);
6656         }
6657
6658         // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
6659         if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
6660             N0.getOperand(0) == N0.getOperand(1) &&
6661             N1.getOperand(0) == N0.getOperand(0)) {
6662           SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6663                                        SDValue(CFP11, 0),
6664                                        DAG.getConstantFP(2.0, VT));
6665           return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1.getOperand(0), NewCFP);
6666         }
6667       }
6668
6669       if (N0.getOpcode() == ISD::FADD && AllowNewConst) {
6670         ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6671         // (fadd (fadd x, x), x) -> (fmul x, 3.0)
6672         if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
6673             (N0.getOperand(0) == N1))
6674           return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6675                              N1, DAG.getConstantFP(3.0, VT));
6676       }
6677       
6678       if (N1.getOpcode() == ISD::FADD && AllowNewConst) {
6679         ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6680         // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
6681         if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
6682             N1.getOperand(0) == N0)
6683           return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6684                              N0, DAG.getConstantFP(3.0, VT));
6685       }
6686       
6687       // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
6688       if (AllowNewConst &&
6689           N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
6690           N0.getOperand(0) == N0.getOperand(1) &&
6691           N1.getOperand(0) == N1.getOperand(1) &&
6692           N0.getOperand(0) == N1.getOperand(0))
6693         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6694                            N0.getOperand(0), DAG.getConstantFP(4.0, VT));
6695     }
6696   } // enable-unsafe-fp-math
6697   
6698   // FADD -> FMA combines:
6699   if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath) &&
6700       DAG.getTarget()
6701           .getSubtargetImpl()
6702           ->getTargetLowering()
6703           ->isFMAFasterThanFMulAndFAdd(VT) &&
6704       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6705
6706     // fold (fadd (fmul x, y), z) -> (fma x, y, z)
6707     if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
6708       return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6709                          N0.getOperand(0), N0.getOperand(1), N1);
6710
6711     // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
6712     // Note: Commutes FADD operands.
6713     if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
6714       return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6715                          N1.getOperand(0), N1.getOperand(1), N0);
6716   }
6717
6718   return SDValue();
6719 }
6720
6721 SDValue DAGCombiner::visitFSUB(SDNode *N) {
6722   SDValue N0 = N->getOperand(0);
6723   SDValue N1 = N->getOperand(1);
6724   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
6725   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
6726   EVT VT = N->getValueType(0);
6727   SDLoc dl(N);
6728   const TargetOptions &Options = DAG.getTarget().Options;
6729
6730   // fold vector ops
6731   if (VT.isVector()) {
6732     SDValue FoldedVOp = SimplifyVBinOp(N);
6733     if (FoldedVOp.getNode()) return FoldedVOp;
6734   }
6735
6736   // fold (fsub c1, c2) -> c1-c2
6737   if (N0CFP && N1CFP)
6738     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0, N1);
6739
6740   // fold (fsub A, (fneg B)) -> (fadd A, B)
6741   if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
6742     return DAG.getNode(ISD::FADD, dl, VT, N0,
6743                        GetNegatedExpression(N1, DAG, LegalOperations));
6744
6745   // If 'unsafe math' is enabled, fold lots of things.
6746   if (Options.UnsafeFPMath) {
6747     // (fsub A, 0) -> A
6748     if (N1CFP && N1CFP->getValueAPF().isZero())
6749       return N0;
6750
6751     // (fsub 0, B) -> -B
6752     if (N0CFP && N0CFP->getValueAPF().isZero()) {
6753       if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
6754         return GetNegatedExpression(N1, DAG, LegalOperations);
6755       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6756         return DAG.getNode(ISD::FNEG, dl, VT, N1);
6757     }
6758
6759     // (fsub x, x) -> 0.0
6760     if (N0 == N1)
6761       return DAG.getConstantFP(0.0f, VT);
6762
6763     // (fsub x, (fadd x, y)) -> (fneg y)
6764     // (fsub x, (fadd y, x)) -> (fneg y)
6765     if (N1.getOpcode() == ISD::FADD) {
6766       SDValue N10 = N1->getOperand(0);
6767       SDValue N11 = N1->getOperand(1);
6768
6769       if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options))
6770         return GetNegatedExpression(N11, DAG, LegalOperations);
6771
6772       if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options))
6773         return GetNegatedExpression(N10, DAG, LegalOperations);
6774     }
6775   }
6776
6777   // FSUB -> FMA combines:
6778   if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath) &&
6779       DAG.getTarget().getSubtargetImpl()
6780           ->getTargetLowering()
6781           ->isFMAFasterThanFMulAndFAdd(VT) &&
6782       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6783
6784     // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
6785     if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
6786       return DAG.getNode(ISD::FMA, dl, VT,
6787                          N0.getOperand(0), N0.getOperand(1),
6788                          DAG.getNode(ISD::FNEG, dl, VT, N1));
6789
6790     // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
6791     // Note: Commutes FSUB operands.
6792     if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
6793       return DAG.getNode(ISD::FMA, dl, VT,
6794                          DAG.getNode(ISD::FNEG, dl, VT,
6795                          N1.getOperand(0)),
6796                          N1.getOperand(1), N0);
6797
6798     // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
6799     if (N0.getOpcode() == ISD::FNEG &&
6800         N0.getOperand(0).getOpcode() == ISD::FMUL &&
6801         N0->hasOneUse() && N0.getOperand(0).hasOneUse()) {
6802       SDValue N00 = N0.getOperand(0).getOperand(0);
6803       SDValue N01 = N0.getOperand(0).getOperand(1);
6804       return DAG.getNode(ISD::FMA, dl, VT,
6805                          DAG.getNode(ISD::FNEG, dl, VT, N00), N01,
6806                          DAG.getNode(ISD::FNEG, dl, VT, N1));
6807     }
6808   }
6809
6810   return SDValue();
6811 }
6812
6813 SDValue DAGCombiner::visitFMUL(SDNode *N) {
6814   SDValue N0 = N->getOperand(0);
6815   SDValue N1 = N->getOperand(1);
6816   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
6817   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
6818   EVT VT = N->getValueType(0);
6819   const TargetOptions &Options = DAG.getTarget().Options;
6820
6821   // fold vector ops
6822   if (VT.isVector()) {
6823     SDValue FoldedVOp = SimplifyVBinOp(N);
6824     if (FoldedVOp.getNode()) return FoldedVOp;
6825   }
6826
6827   // fold (fmul c1, c2) -> c1*c2
6828   if (N0CFP && N1CFP)
6829     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, N1);
6830
6831   // canonicalize constant to RHS
6832   if (N0CFP && !N1CFP)
6833     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, N0);
6834
6835   // fold (fmul A, 1.0) -> A
6836   if (N1CFP && N1CFP->isExactlyValue(1.0))
6837     return N0;
6838
6839   if (Options.UnsafeFPMath) {
6840     // fold (fmul A, 0) -> 0
6841     if (N1CFP && N1CFP->getValueAPF().isZero())
6842       return N1;
6843
6844     // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
6845     if (N1CFP && N0.getOpcode() == ISD::FMUL &&
6846         N0.getNode()->hasOneUse() && isConstOrConstSplatFP(N0.getOperand(1))) {
6847       SDLoc SL(N);
6848       SDValue MulConsts = DAG.getNode(ISD::FMUL, SL, VT, N0.getOperand(1), N1);
6849       return DAG.getNode(ISD::FMUL, SL, VT, N0.getOperand(0), MulConsts);
6850     }
6851
6852     // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c))
6853     // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs
6854     // during an early run of DAGCombiner can prevent folding with fmuls
6855     // inserted during lowering.
6856     if (N0.getOpcode() == ISD::FADD && N0.getOperand(0) == N0.getOperand(1)) {
6857       SDLoc SL(N);
6858       const SDValue Two = DAG.getConstantFP(2.0, VT);
6859       SDValue MulConsts = DAG.getNode(ISD::FMUL, SL, VT, Two, N1);
6860       return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0), MulConsts);
6861     }
6862   }
6863
6864   // fold (fmul X, 2.0) -> (fadd X, X)
6865   if (N1CFP && N1CFP->isExactlyValue(+2.0))
6866     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N0);
6867
6868   // fold (fmul X, -1.0) -> (fneg X)
6869   if (N1CFP && N1CFP->isExactlyValue(-1.0))
6870     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6871       return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
6872
6873   // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
6874   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
6875     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
6876       // Both can be negated for free, check to see if at least one is cheaper
6877       // negated.
6878       if (LHSNeg == 2 || RHSNeg == 2)
6879         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6880                            GetNegatedExpression(N0, DAG, LegalOperations),
6881                            GetNegatedExpression(N1, DAG, LegalOperations));
6882     }
6883   }
6884
6885   return SDValue();
6886 }
6887
6888 SDValue DAGCombiner::visitFMA(SDNode *N) {
6889   SDValue N0 = N->getOperand(0);
6890   SDValue N1 = N->getOperand(1);
6891   SDValue N2 = N->getOperand(2);
6892   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6893   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6894   EVT VT = N->getValueType(0);
6895   SDLoc dl(N);
6896   const TargetOptions &Options = DAG.getTarget().Options;
6897
6898   // Constant fold FMA.
6899   if (isa<ConstantFPSDNode>(N0) &&
6900       isa<ConstantFPSDNode>(N1) &&
6901       isa<ConstantFPSDNode>(N2)) {
6902     return DAG.getNode(ISD::FMA, dl, VT, N0, N1, N2);
6903   }
6904
6905   if (Options.UnsafeFPMath) {
6906     if (N0CFP && N0CFP->isZero())
6907       return N2;
6908     if (N1CFP && N1CFP->isZero())
6909       return N2;
6910   }
6911   if (N0CFP && N0CFP->isExactlyValue(1.0))
6912     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
6913   if (N1CFP && N1CFP->isExactlyValue(1.0))
6914     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
6915
6916   // Canonicalize (fma c, x, y) -> (fma x, c, y)
6917   if (N0CFP && !N1CFP)
6918     return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
6919
6920   // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
6921   if (Options.UnsafeFPMath && N1CFP &&
6922       N2.getOpcode() == ISD::FMUL &&
6923       N0 == N2.getOperand(0) &&
6924       N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
6925     return DAG.getNode(ISD::FMUL, dl, VT, N0,
6926                        DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
6927   }
6928
6929
6930   // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
6931   if (Options.UnsafeFPMath &&
6932       N0.getOpcode() == ISD::FMUL && N1CFP &&
6933       N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
6934     return DAG.getNode(ISD::FMA, dl, VT,
6935                        N0.getOperand(0),
6936                        DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
6937                        N2);
6938   }
6939
6940   // (fma x, 1, y) -> (fadd x, y)
6941   // (fma x, -1, y) -> (fadd (fneg x), y)
6942   if (N1CFP) {
6943     if (N1CFP->isExactlyValue(1.0))
6944       return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
6945
6946     if (N1CFP->isExactlyValue(-1.0) &&
6947         (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
6948       SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
6949       AddToWorklist(RHSNeg.getNode());
6950       return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
6951     }
6952   }
6953
6954   // (fma x, c, x) -> (fmul x, (c+1))
6955   if (Options.UnsafeFPMath && N1CFP && N0 == N2)
6956     return DAG.getNode(ISD::FMUL, dl, VT, N0,
6957                        DAG.getNode(ISD::FADD, dl, VT,
6958                                    N1, DAG.getConstantFP(1.0, VT)));
6959
6960   // (fma x, c, (fneg x)) -> (fmul x, (c-1))
6961   if (Options.UnsafeFPMath && N1CFP &&
6962       N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
6963     return DAG.getNode(ISD::FMUL, dl, VT, N0,
6964                        DAG.getNode(ISD::FADD, dl, VT,
6965                                    N1, DAG.getConstantFP(-1.0, VT)));
6966
6967
6968   return SDValue();
6969 }
6970
6971 SDValue DAGCombiner::visitFDIV(SDNode *N) {
6972   SDValue N0 = N->getOperand(0);
6973   SDValue N1 = N->getOperand(1);
6974   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6975   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6976   EVT VT = N->getValueType(0);
6977   const TargetOptions &Options = DAG.getTarget().Options;
6978
6979   // fold vector ops
6980   if (VT.isVector()) {
6981     SDValue FoldedVOp = SimplifyVBinOp(N);
6982     if (FoldedVOp.getNode()) return FoldedVOp;
6983   }
6984
6985   // fold (fdiv c1, c2) -> c1/c2
6986   if (N0CFP && N1CFP)
6987     return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
6988
6989   // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
6990   if (N1CFP && Options.UnsafeFPMath) {
6991     // Compute the reciprocal 1.0 / c2.
6992     APFloat N1APF = N1CFP->getValueAPF();
6993     APFloat Recip(N1APF.getSemantics(), 1); // 1.0
6994     APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
6995     // Only do the transform if the reciprocal is a legal fp immediate that
6996     // isn't too nasty (eg NaN, denormal, ...).
6997     if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
6998         (!LegalOperations ||
6999          // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
7000          // backend)... we should handle this gracefully after Legalize.
7001          // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
7002          TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
7003          TLI.isFPImmLegal(Recip, VT)))
7004       return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0,
7005                          DAG.getConstantFP(Recip, VT));
7006   }
7007
7008   // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
7009   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
7010     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
7011       // Both can be negated for free, check to see if at least one is cheaper
7012       // negated.
7013       if (LHSNeg == 2 || RHSNeg == 2)
7014         return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
7015                            GetNegatedExpression(N0, DAG, LegalOperations),
7016                            GetNegatedExpression(N1, DAG, LegalOperations));
7017     }
7018   }
7019
7020   return SDValue();
7021 }
7022
7023 SDValue DAGCombiner::visitFREM(SDNode *N) {
7024   SDValue N0 = N->getOperand(0);
7025   SDValue N1 = N->getOperand(1);
7026   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7027   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7028   EVT VT = N->getValueType(0);
7029
7030   // fold (frem c1, c2) -> fmod(c1,c2)
7031   if (N0CFP && N1CFP)
7032     return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
7033
7034   return SDValue();
7035 }
7036
7037 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
7038   SDValue N0 = N->getOperand(0);
7039   SDValue N1 = N->getOperand(1);
7040   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7041   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7042   EVT VT = N->getValueType(0);
7043
7044   if (N0CFP && N1CFP)  // Constant fold
7045     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
7046
7047   if (N1CFP) {
7048     const APFloat& V = N1CFP->getValueAPF();
7049     // copysign(x, c1) -> fabs(x)       iff ispos(c1)
7050     // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
7051     if (!V.isNegative()) {
7052       if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
7053         return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7054     } else {
7055       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
7056         return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
7057                            DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
7058     }
7059   }
7060
7061   // copysign(fabs(x), y) -> copysign(x, y)
7062   // copysign(fneg(x), y) -> copysign(x, y)
7063   // copysign(copysign(x,z), y) -> copysign(x, y)
7064   if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
7065       N0.getOpcode() == ISD::FCOPYSIGN)
7066     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7067                        N0.getOperand(0), N1);
7068
7069   // copysign(x, abs(y)) -> abs(x)
7070   if (N1.getOpcode() == ISD::FABS)
7071     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7072
7073   // copysign(x, copysign(y,z)) -> copysign(x, z)
7074   if (N1.getOpcode() == ISD::FCOPYSIGN)
7075     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7076                        N0, N1.getOperand(1));
7077
7078   // copysign(x, fp_extend(y)) -> copysign(x, y)
7079   // copysign(x, fp_round(y)) -> copysign(x, y)
7080   if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
7081     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7082                        N0, N1.getOperand(0));
7083
7084   return SDValue();
7085 }
7086
7087 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
7088   SDValue N0 = N->getOperand(0);
7089   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
7090   EVT VT = N->getValueType(0);
7091   EVT OpVT = N0.getValueType();
7092
7093   // fold (sint_to_fp c1) -> c1fp
7094   if (N0C &&
7095       // ...but only if the target supports immediate floating-point values
7096       (!LegalOperations ||
7097        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
7098     return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
7099
7100   // If the input is a legal type, and SINT_TO_FP is not legal on this target,
7101   // but UINT_TO_FP is legal on this target, try to convert.
7102   if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
7103       TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
7104     // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
7105     if (DAG.SignBitIsZero(N0))
7106       return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
7107   }
7108
7109   // The next optimizations are desirable only if SELECT_CC can be lowered.
7110   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
7111     // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
7112     if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
7113         !VT.isVector() &&
7114         (!LegalOperations ||
7115          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7116       SDValue Ops[] =
7117         { N0.getOperand(0), N0.getOperand(1),
7118           DAG.getConstantFP(-1.0, VT) , DAG.getConstantFP(0.0, VT),
7119           N0.getOperand(2) };
7120       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7121     }
7122
7123     // fold (sint_to_fp (zext (setcc x, y, cc))) ->
7124     //      (select_cc x, y, 1.0, 0.0,, cc)
7125     if (N0.getOpcode() == ISD::ZERO_EXTEND &&
7126         N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
7127         (!LegalOperations ||
7128          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7129       SDValue Ops[] =
7130         { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
7131           DAG.getConstantFP(1.0, VT) , DAG.getConstantFP(0.0, VT),
7132           N0.getOperand(0).getOperand(2) };
7133       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7134     }
7135   }
7136
7137   return SDValue();
7138 }
7139
7140 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
7141   SDValue N0 = N->getOperand(0);
7142   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
7143   EVT VT = N->getValueType(0);
7144   EVT OpVT = N0.getValueType();
7145
7146   // fold (uint_to_fp c1) -> c1fp
7147   if (N0C &&
7148       // ...but only if the target supports immediate floating-point values
7149       (!LegalOperations ||
7150        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
7151     return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
7152
7153   // If the input is a legal type, and UINT_TO_FP is not legal on this target,
7154   // but SINT_TO_FP is legal on this target, try to convert.
7155   if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
7156       TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
7157     // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
7158     if (DAG.SignBitIsZero(N0))
7159       return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
7160   }
7161
7162   // The next optimizations are desirable only if SELECT_CC can be lowered.
7163   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
7164     // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
7165
7166     if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
7167         (!LegalOperations ||
7168          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7169       SDValue Ops[] =
7170         { N0.getOperand(0), N0.getOperand(1),
7171           DAG.getConstantFP(1.0, VT),  DAG.getConstantFP(0.0, VT),
7172           N0.getOperand(2) };
7173       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7174     }
7175   }
7176
7177   return SDValue();
7178 }
7179
7180 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
7181   SDValue N0 = N->getOperand(0);
7182   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7183   EVT VT = N->getValueType(0);
7184
7185   // fold (fp_to_sint c1fp) -> c1
7186   if (N0CFP)
7187     return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
7188
7189   return SDValue();
7190 }
7191
7192 SDValue DAGCombiner::visitFP_TO_UINT(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_uint c1fp) -> c1
7198   if (N0CFP)
7199     return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
7200
7201   return SDValue();
7202 }
7203
7204 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
7205   SDValue N0 = N->getOperand(0);
7206   SDValue N1 = N->getOperand(1);
7207   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7208   EVT VT = N->getValueType(0);
7209
7210   // fold (fp_round c1fp) -> c1fp
7211   if (N0CFP)
7212     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
7213
7214   // fold (fp_round (fp_extend x)) -> x
7215   if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
7216     return N0.getOperand(0);
7217
7218   // fold (fp_round (fp_round x)) -> (fp_round x)
7219   if (N0.getOpcode() == ISD::FP_ROUND) {
7220     // This is a value preserving truncation if both round's are.
7221     bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
7222                    N0.getNode()->getConstantOperandVal(1) == 1;
7223     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0.getOperand(0),
7224                        DAG.getIntPtrConstant(IsTrunc));
7225   }
7226
7227   // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
7228   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
7229     SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
7230                               N0.getOperand(0), N1);
7231     AddToWorklist(Tmp.getNode());
7232     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7233                        Tmp, N0.getOperand(1));
7234   }
7235
7236   return SDValue();
7237 }
7238
7239 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
7240   SDValue N0 = N->getOperand(0);
7241   EVT VT = N->getValueType(0);
7242   EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
7243   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7244
7245   // fold (fp_round_inreg c1fp) -> c1fp
7246   if (N0CFP && isTypeLegal(EVT)) {
7247     SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
7248     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, Round);
7249   }
7250
7251   return SDValue();
7252 }
7253
7254 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
7255   SDValue N0 = N->getOperand(0);
7256   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7257   EVT VT = N->getValueType(0);
7258
7259   // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
7260   if (N->hasOneUse() &&
7261       N->use_begin()->getOpcode() == ISD::FP_ROUND)
7262     return SDValue();
7263
7264   // fold (fp_extend c1fp) -> c1fp
7265   if (N0CFP)
7266     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
7267
7268   // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
7269   // value of X.
7270   if (N0.getOpcode() == ISD::FP_ROUND
7271       && N0.getNode()->getConstantOperandVal(1) == 1) {
7272     SDValue In = N0.getOperand(0);
7273     if (In.getValueType() == VT) return In;
7274     if (VT.bitsLT(In.getValueType()))
7275       return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
7276                          In, N0.getOperand(1));
7277     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
7278   }
7279
7280   // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
7281   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7282        TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType())) {
7283     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7284     SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
7285                                      LN0->getChain(),
7286                                      LN0->getBasePtr(), N0.getValueType(),
7287                                      LN0->getMemOperand());
7288     CombineTo(N, ExtLoad);
7289     CombineTo(N0.getNode(),
7290               DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
7291                           N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
7292               ExtLoad.getValue(1));
7293     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7294   }
7295
7296   return SDValue();
7297 }
7298
7299 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
7300   SDValue N0 = N->getOperand(0);
7301   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7302   EVT VT = N->getValueType(0);
7303
7304   // fold (fceil c1) -> fceil(c1)
7305   if (N0CFP)
7306     return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
7307
7308   return SDValue();
7309 }
7310
7311 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
7312   SDValue N0 = N->getOperand(0);
7313   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7314   EVT VT = N->getValueType(0);
7315
7316   // fold (ftrunc c1) -> ftrunc(c1)
7317   if (N0CFP)
7318     return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
7319
7320   return SDValue();
7321 }
7322
7323 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
7324   SDValue N0 = N->getOperand(0);
7325   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7326   EVT VT = N->getValueType(0);
7327
7328   // fold (ffloor c1) -> ffloor(c1)
7329   if (N0CFP)
7330     return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
7331
7332   return SDValue();
7333 }
7334
7335 // FIXME: FNEG and FABS have a lot in common; refactor.
7336 SDValue DAGCombiner::visitFNEG(SDNode *N) {
7337   SDValue N0 = N->getOperand(0);
7338   EVT VT = N->getValueType(0);
7339
7340   if (VT.isVector()) {
7341     SDValue FoldedVOp = SimplifyVUnaryOp(N);
7342     if (FoldedVOp.getNode()) return FoldedVOp;
7343   }
7344
7345   // Constant fold FNEG.
7346   if (isa<ConstantFPSDNode>(N0))
7347     return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N->getOperand(0));
7348
7349   if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
7350                          &DAG.getTarget().Options))
7351     return GetNegatedExpression(N0, DAG, LegalOperations);
7352
7353   // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading
7354   // constant pool values.
7355   if (!TLI.isFNegFree(VT) &&
7356       N0.getOpcode() == ISD::BITCAST &&
7357       N0.getNode()->hasOneUse()) {
7358     SDValue Int = N0.getOperand(0);
7359     EVT IntVT = Int.getValueType();
7360     if (IntVT.isInteger() && !IntVT.isVector()) {
7361       APInt SignMask;
7362       if (N0.getValueType().isVector()) {
7363         // For a vector, get a mask such as 0x80... per scalar element
7364         // and splat it.
7365         SignMask = APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
7366         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
7367       } else {
7368         // For a scalar, just generate 0x80...
7369         SignMask = APInt::getSignBit(IntVT.getSizeInBits());
7370       }
7371       Int = DAG.getNode(ISD::XOR, SDLoc(N0), IntVT, Int,
7372                         DAG.getConstant(SignMask, IntVT));
7373       AddToWorklist(Int.getNode());
7374       return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Int);
7375     }
7376   }
7377
7378   // (fneg (fmul c, x)) -> (fmul -c, x)
7379   if (N0.getOpcode() == ISD::FMUL) {
7380     ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
7381     if (CFP1) {
7382       APFloat CVal = CFP1->getValueAPF();
7383       CVal.changeSign();
7384       if (Level >= AfterLegalizeDAG &&
7385           (TLI.isFPImmLegal(CVal, N->getValueType(0)) ||
7386            TLI.isOperationLegal(ISD::ConstantFP, N->getValueType(0))))
7387         return DAG.getNode(
7388             ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
7389             DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0.getOperand(1)));
7390     }
7391   }
7392
7393   return SDValue();
7394 }
7395
7396 SDValue DAGCombiner::visitFABS(SDNode *N) {
7397   SDValue N0 = N->getOperand(0);
7398   EVT VT = N->getValueType(0);
7399
7400   if (VT.isVector()) {
7401     SDValue FoldedVOp = SimplifyVUnaryOp(N);
7402     if (FoldedVOp.getNode()) return FoldedVOp;
7403   }
7404
7405   // fold (fabs c1) -> fabs(c1)
7406   if (isa<ConstantFPSDNode>(N0))
7407     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7408   
7409   // fold (fabs (fabs x)) -> (fabs x)
7410   if (N0.getOpcode() == ISD::FABS)
7411     return N->getOperand(0);
7412
7413   // fold (fabs (fneg x)) -> (fabs x)
7414   // fold (fabs (fcopysign x, y)) -> (fabs x)
7415   if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
7416     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
7417
7418   // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading
7419   // constant pool values.
7420   if (!TLI.isFAbsFree(VT) &&
7421       N0.getOpcode() == ISD::BITCAST &&
7422       N0.getNode()->hasOneUse()) {
7423     SDValue Int = N0.getOperand(0);
7424     EVT IntVT = Int.getValueType();
7425     if (IntVT.isInteger() && !IntVT.isVector()) {
7426       APInt SignMask;
7427       if (N0.getValueType().isVector()) {
7428         // For a vector, get a mask such as 0x7f... per scalar element
7429         // and splat it.
7430         SignMask = ~APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
7431         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
7432       } else {
7433         // For a scalar, just generate 0x7f...
7434         SignMask = ~APInt::getSignBit(IntVT.getSizeInBits());
7435       }
7436       Int = DAG.getNode(ISD::AND, SDLoc(N0), IntVT, Int,
7437                         DAG.getConstant(SignMask, IntVT));
7438       AddToWorklist(Int.getNode());
7439       return DAG.getNode(ISD::BITCAST, SDLoc(N), N->getValueType(0), Int);
7440     }
7441   }
7442
7443   return SDValue();
7444 }
7445
7446 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
7447   SDValue Chain = N->getOperand(0);
7448   SDValue N1 = N->getOperand(1);
7449   SDValue N2 = N->getOperand(2);
7450
7451   // If N is a constant we could fold this into a fallthrough or unconditional
7452   // branch. However that doesn't happen very often in normal code, because
7453   // Instcombine/SimplifyCFG should have handled the available opportunities.
7454   // If we did this folding here, it would be necessary to update the
7455   // MachineBasicBlock CFG, which is awkward.
7456
7457   // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
7458   // on the target.
7459   if (N1.getOpcode() == ISD::SETCC &&
7460       TLI.isOperationLegalOrCustom(ISD::BR_CC,
7461                                    N1.getOperand(0).getValueType())) {
7462     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7463                        Chain, N1.getOperand(2),
7464                        N1.getOperand(0), N1.getOperand(1), N2);
7465   }
7466
7467   if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
7468       ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
7469        (N1.getOperand(0).hasOneUse() &&
7470         N1.getOperand(0).getOpcode() == ISD::SRL))) {
7471     SDNode *Trunc = nullptr;
7472     if (N1.getOpcode() == ISD::TRUNCATE) {
7473       // Look pass the truncate.
7474       Trunc = N1.getNode();
7475       N1 = N1.getOperand(0);
7476     }
7477
7478     // Match this pattern so that we can generate simpler code:
7479     //
7480     //   %a = ...
7481     //   %b = and i32 %a, 2
7482     //   %c = srl i32 %b, 1
7483     //   brcond i32 %c ...
7484     //
7485     // into
7486     //
7487     //   %a = ...
7488     //   %b = and i32 %a, 2
7489     //   %c = setcc eq %b, 0
7490     //   brcond %c ...
7491     //
7492     // This applies only when the AND constant value has one bit set and the
7493     // SRL constant is equal to the log2 of the AND constant. The back-end is
7494     // smart enough to convert the result into a TEST/JMP sequence.
7495     SDValue Op0 = N1.getOperand(0);
7496     SDValue Op1 = N1.getOperand(1);
7497
7498     if (Op0.getOpcode() == ISD::AND &&
7499         Op1.getOpcode() == ISD::Constant) {
7500       SDValue AndOp1 = Op0.getOperand(1);
7501
7502       if (AndOp1.getOpcode() == ISD::Constant) {
7503         const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
7504
7505         if (AndConst.isPowerOf2() &&
7506             cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
7507           SDValue SetCC =
7508             DAG.getSetCC(SDLoc(N),
7509                          getSetCCResultType(Op0.getValueType()),
7510                          Op0, DAG.getConstant(0, Op0.getValueType()),
7511                          ISD::SETNE);
7512
7513           SDValue NewBRCond = DAG.getNode(ISD::BRCOND, SDLoc(N),
7514                                           MVT::Other, Chain, SetCC, N2);
7515           // Don't add the new BRCond into the worklist or else SimplifySelectCC
7516           // will convert it back to (X & C1) >> C2.
7517           CombineTo(N, NewBRCond, false);
7518           // Truncate is dead.
7519           if (Trunc)
7520             deleteAndRecombine(Trunc);
7521           // Replace the uses of SRL with SETCC
7522           WorklistRemover DeadNodes(*this);
7523           DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
7524           deleteAndRecombine(N1.getNode());
7525           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7526         }
7527       }
7528     }
7529
7530     if (Trunc)
7531       // Restore N1 if the above transformation doesn't match.
7532       N1 = N->getOperand(1);
7533   }
7534
7535   // Transform br(xor(x, y)) -> br(x != y)
7536   // Transform br(xor(xor(x,y), 1)) -> br (x == y)
7537   if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
7538     SDNode *TheXor = N1.getNode();
7539     SDValue Op0 = TheXor->getOperand(0);
7540     SDValue Op1 = TheXor->getOperand(1);
7541     if (Op0.getOpcode() == Op1.getOpcode()) {
7542       // Avoid missing important xor optimizations.
7543       SDValue Tmp = visitXOR(TheXor);
7544       if (Tmp.getNode()) {
7545         if (Tmp.getNode() != TheXor) {
7546           DEBUG(dbgs() << "\nReplacing.8 ";
7547                 TheXor->dump(&DAG);
7548                 dbgs() << "\nWith: ";
7549                 Tmp.getNode()->dump(&DAG);
7550                 dbgs() << '\n');
7551           WorklistRemover DeadNodes(*this);
7552           DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
7553           deleteAndRecombine(TheXor);
7554           return DAG.getNode(ISD::BRCOND, SDLoc(N),
7555                              MVT::Other, Chain, Tmp, N2);
7556         }
7557
7558         // visitXOR has changed XOR's operands or replaced the XOR completely,
7559         // bail out.
7560         return SDValue(N, 0);
7561       }
7562     }
7563
7564     if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
7565       bool Equal = false;
7566       if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
7567         if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
7568             Op0.getOpcode() == ISD::XOR) {
7569           TheXor = Op0.getNode();
7570           Equal = true;
7571         }
7572
7573       EVT SetCCVT = N1.getValueType();
7574       if (LegalTypes)
7575         SetCCVT = getSetCCResultType(SetCCVT);
7576       SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
7577                                    SetCCVT,
7578                                    Op0, Op1,
7579                                    Equal ? ISD::SETEQ : ISD::SETNE);
7580       // Replace the uses of XOR with SETCC
7581       WorklistRemover DeadNodes(*this);
7582       DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
7583       deleteAndRecombine(N1.getNode());
7584       return DAG.getNode(ISD::BRCOND, SDLoc(N),
7585                          MVT::Other, Chain, SetCC, N2);
7586     }
7587   }
7588
7589   return SDValue();
7590 }
7591
7592 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
7593 //
7594 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
7595   CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
7596   SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
7597
7598   // If N is a constant we could fold this into a fallthrough or unconditional
7599   // branch. However that doesn't happen very often in normal code, because
7600   // Instcombine/SimplifyCFG should have handled the available opportunities.
7601   // If we did this folding here, it would be necessary to update the
7602   // MachineBasicBlock CFG, which is awkward.
7603
7604   // Use SimplifySetCC to simplify SETCC's.
7605   SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
7606                                CondLHS, CondRHS, CC->get(), SDLoc(N),
7607                                false);
7608   if (Simp.getNode()) AddToWorklist(Simp.getNode());
7609
7610   // fold to a simpler setcc
7611   if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
7612     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7613                        N->getOperand(0), Simp.getOperand(2),
7614                        Simp.getOperand(0), Simp.getOperand(1),
7615                        N->getOperand(4));
7616
7617   return SDValue();
7618 }
7619
7620 /// Return true if 'Use' is a load or a store that uses N as its base pointer
7621 /// and that N may be folded in the load / store addressing mode.
7622 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
7623                                     SelectionDAG &DAG,
7624                                     const TargetLowering &TLI) {
7625   EVT VT;
7626   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(Use)) {
7627     if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
7628       return false;
7629     VT = Use->getValueType(0);
7630   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(Use)) {
7631     if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
7632       return false;
7633     VT = ST->getValue().getValueType();
7634   } else
7635     return false;
7636
7637   TargetLowering::AddrMode AM;
7638   if (N->getOpcode() == ISD::ADD) {
7639     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7640     if (Offset)
7641       // [reg +/- imm]
7642       AM.BaseOffs = Offset->getSExtValue();
7643     else
7644       // [reg +/- reg]
7645       AM.Scale = 1;
7646   } else if (N->getOpcode() == ISD::SUB) {
7647     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7648     if (Offset)
7649       // [reg +/- imm]
7650       AM.BaseOffs = -Offset->getSExtValue();
7651     else
7652       // [reg +/- reg]
7653       AM.Scale = 1;
7654   } else
7655     return false;
7656
7657   return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
7658 }
7659
7660 /// Try turning a load/store into a pre-indexed load/store when the base
7661 /// pointer is an add or subtract and it has other uses besides the load/store.
7662 /// After the transformation, the new indexed load/store has effectively folded
7663 /// the add/subtract in and all of its other uses are redirected to the
7664 /// new load/store.
7665 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
7666   if (Level < AfterLegalizeDAG)
7667     return false;
7668
7669   bool isLoad = true;
7670   SDValue Ptr;
7671   EVT VT;
7672   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
7673     if (LD->isIndexed())
7674       return false;
7675     VT = LD->getMemoryVT();
7676     if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
7677         !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
7678       return false;
7679     Ptr = LD->getBasePtr();
7680   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
7681     if (ST->isIndexed())
7682       return false;
7683     VT = ST->getMemoryVT();
7684     if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
7685         !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
7686       return false;
7687     Ptr = ST->getBasePtr();
7688     isLoad = false;
7689   } else {
7690     return false;
7691   }
7692
7693   // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
7694   // out.  There is no reason to make this a preinc/predec.
7695   if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
7696       Ptr.getNode()->hasOneUse())
7697     return false;
7698
7699   // Ask the target to do addressing mode selection.
7700   SDValue BasePtr;
7701   SDValue Offset;
7702   ISD::MemIndexedMode AM = ISD::UNINDEXED;
7703   if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
7704     return false;
7705
7706   // Backends without true r+i pre-indexed forms may need to pass a
7707   // constant base with a variable offset so that constant coercion
7708   // will work with the patterns in canonical form.
7709   bool Swapped = false;
7710   if (isa<ConstantSDNode>(BasePtr)) {
7711     std::swap(BasePtr, Offset);
7712     Swapped = true;
7713   }
7714
7715   // Don't create a indexed load / store with zero offset.
7716   if (isa<ConstantSDNode>(Offset) &&
7717       cast<ConstantSDNode>(Offset)->isNullValue())
7718     return false;
7719
7720   // Try turning it into a pre-indexed load / store except when:
7721   // 1) The new base ptr is a frame index.
7722   // 2) If N is a store and the new base ptr is either the same as or is a
7723   //    predecessor of the value being stored.
7724   // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
7725   //    that would create a cycle.
7726   // 4) All uses are load / store ops that use it as old base ptr.
7727
7728   // Check #1.  Preinc'ing a frame index would require copying the stack pointer
7729   // (plus the implicit offset) to a register to preinc anyway.
7730   if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7731     return false;
7732
7733   // Check #2.
7734   if (!isLoad) {
7735     SDValue Val = cast<StoreSDNode>(N)->getValue();
7736     if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
7737       return false;
7738   }
7739
7740   // If the offset is a constant, there may be other adds of constants that
7741   // can be folded with this one. We should do this to avoid having to keep
7742   // a copy of the original base pointer.
7743   SmallVector<SDNode *, 16> OtherUses;
7744   if (isa<ConstantSDNode>(Offset))
7745     for (SDNode *Use : BasePtr.getNode()->uses()) {
7746       if (Use == Ptr.getNode())
7747         continue;
7748
7749       if (Use->isPredecessorOf(N))
7750         continue;
7751
7752       if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) {
7753         OtherUses.clear();
7754         break;
7755       }
7756
7757       SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1);
7758       if (Op1.getNode() == BasePtr.getNode())
7759         std::swap(Op0, Op1);
7760       assert(Op0.getNode() == BasePtr.getNode() &&
7761              "Use of ADD/SUB but not an operand");
7762
7763       if (!isa<ConstantSDNode>(Op1)) {
7764         OtherUses.clear();
7765         break;
7766       }
7767
7768       // FIXME: In some cases, we can be smarter about this.
7769       if (Op1.getValueType() != Offset.getValueType()) {
7770         OtherUses.clear();
7771         break;
7772       }
7773
7774       OtherUses.push_back(Use);
7775     }
7776
7777   if (Swapped)
7778     std::swap(BasePtr, Offset);
7779
7780   // Now check for #3 and #4.
7781   bool RealUse = false;
7782
7783   // Caches for hasPredecessorHelper
7784   SmallPtrSet<const SDNode *, 32> Visited;
7785   SmallVector<const SDNode *, 16> Worklist;
7786
7787   for (SDNode *Use : Ptr.getNode()->uses()) {
7788     if (Use == N)
7789       continue;
7790     if (N->hasPredecessorHelper(Use, Visited, Worklist))
7791       return false;
7792
7793     // If Ptr may be folded in addressing mode of other use, then it's
7794     // not profitable to do this transformation.
7795     if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
7796       RealUse = true;
7797   }
7798
7799   if (!RealUse)
7800     return false;
7801
7802   SDValue Result;
7803   if (isLoad)
7804     Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
7805                                 BasePtr, Offset, AM);
7806   else
7807     Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
7808                                  BasePtr, Offset, AM);
7809   ++PreIndexedNodes;
7810   ++NodesCombined;
7811   DEBUG(dbgs() << "\nReplacing.4 ";
7812         N->dump(&DAG);
7813         dbgs() << "\nWith: ";
7814         Result.getNode()->dump(&DAG);
7815         dbgs() << '\n');
7816   WorklistRemover DeadNodes(*this);
7817   if (isLoad) {
7818     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7819     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
7820   } else {
7821     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
7822   }
7823
7824   // Finally, since the node is now dead, remove it from the graph.
7825   deleteAndRecombine(N);
7826
7827   if (Swapped)
7828     std::swap(BasePtr, Offset);
7829
7830   // Replace other uses of BasePtr that can be updated to use Ptr
7831   for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
7832     unsigned OffsetIdx = 1;
7833     if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
7834       OffsetIdx = 0;
7835     assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
7836            BasePtr.getNode() && "Expected BasePtr operand");
7837
7838     // We need to replace ptr0 in the following expression:
7839     //   x0 * offset0 + y0 * ptr0 = t0
7840     // knowing that
7841     //   x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
7842     //
7843     // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
7844     // indexed load/store and the expresion that needs to be re-written.
7845     //
7846     // Therefore, we have:
7847     //   t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
7848
7849     ConstantSDNode *CN =
7850       cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
7851     int X0, X1, Y0, Y1;
7852     APInt Offset0 = CN->getAPIntValue();
7853     APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
7854
7855     X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
7856     Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
7857     X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
7858     Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
7859
7860     unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
7861
7862     APInt CNV = Offset0;
7863     if (X0 < 0) CNV = -CNV;
7864     if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
7865     else CNV = CNV - Offset1;
7866
7867     // We can now generate the new expression.
7868     SDValue NewOp1 = DAG.getConstant(CNV, CN->getValueType(0));
7869     SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
7870
7871     SDValue NewUse = DAG.getNode(Opcode,
7872                                  SDLoc(OtherUses[i]),
7873                                  OtherUses[i]->getValueType(0), NewOp1, NewOp2);
7874     DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
7875     deleteAndRecombine(OtherUses[i]);
7876   }
7877
7878   // Replace the uses of Ptr with uses of the updated base value.
7879   DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
7880   deleteAndRecombine(Ptr.getNode());
7881
7882   return true;
7883 }
7884
7885 /// Try to combine a load/store with a add/sub of the base pointer node into a
7886 /// post-indexed load/store. The transformation folded the add/subtract into the
7887 /// new indexed load/store effectively and all of its uses are redirected to the
7888 /// new load/store.
7889 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
7890   if (Level < AfterLegalizeDAG)
7891     return false;
7892
7893   bool isLoad = true;
7894   SDValue Ptr;
7895   EVT VT;
7896   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
7897     if (LD->isIndexed())
7898       return false;
7899     VT = LD->getMemoryVT();
7900     if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
7901         !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
7902       return false;
7903     Ptr = LD->getBasePtr();
7904   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
7905     if (ST->isIndexed())
7906       return false;
7907     VT = ST->getMemoryVT();
7908     if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
7909         !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
7910       return false;
7911     Ptr = ST->getBasePtr();
7912     isLoad = false;
7913   } else {
7914     return false;
7915   }
7916
7917   if (Ptr.getNode()->hasOneUse())
7918     return false;
7919
7920   for (SDNode *Op : Ptr.getNode()->uses()) {
7921     if (Op == N ||
7922         (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
7923       continue;
7924
7925     SDValue BasePtr;
7926     SDValue Offset;
7927     ISD::MemIndexedMode AM = ISD::UNINDEXED;
7928     if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
7929       // Don't create a indexed load / store with zero offset.
7930       if (isa<ConstantSDNode>(Offset) &&
7931           cast<ConstantSDNode>(Offset)->isNullValue())
7932         continue;
7933
7934       // Try turning it into a post-indexed load / store except when
7935       // 1) All uses are load / store ops that use it as base ptr (and
7936       //    it may be folded as addressing mmode).
7937       // 2) Op must be independent of N, i.e. Op is neither a predecessor
7938       //    nor a successor of N. Otherwise, if Op is folded that would
7939       //    create a cycle.
7940
7941       if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7942         continue;
7943
7944       // Check for #1.
7945       bool TryNext = false;
7946       for (SDNode *Use : BasePtr.getNode()->uses()) {
7947         if (Use == Ptr.getNode())
7948           continue;
7949
7950         // If all the uses are load / store addresses, then don't do the
7951         // transformation.
7952         if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
7953           bool RealUse = false;
7954           for (SDNode *UseUse : Use->uses()) {
7955             if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
7956               RealUse = true;
7957           }
7958
7959           if (!RealUse) {
7960             TryNext = true;
7961             break;
7962           }
7963         }
7964       }
7965
7966       if (TryNext)
7967         continue;
7968
7969       // Check for #2
7970       if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
7971         SDValue Result = isLoad
7972           ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
7973                                BasePtr, Offset, AM)
7974           : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
7975                                 BasePtr, Offset, AM);
7976         ++PostIndexedNodes;
7977         ++NodesCombined;
7978         DEBUG(dbgs() << "\nReplacing.5 ";
7979               N->dump(&DAG);
7980               dbgs() << "\nWith: ";
7981               Result.getNode()->dump(&DAG);
7982               dbgs() << '\n');
7983         WorklistRemover DeadNodes(*this);
7984         if (isLoad) {
7985           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7986           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
7987         } else {
7988           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
7989         }
7990
7991         // Finally, since the node is now dead, remove it from the graph.
7992         deleteAndRecombine(N);
7993
7994         // Replace the uses of Use with uses of the updated base value.
7995         DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
7996                                       Result.getValue(isLoad ? 1 : 0));
7997         deleteAndRecombine(Op);
7998         return true;
7999       }
8000     }
8001   }
8002
8003   return false;
8004 }
8005
8006 /// \brief Return the base-pointer arithmetic from an indexed \p LD.
8007 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) {
8008   ISD::MemIndexedMode AM = LD->getAddressingMode();
8009   assert(AM != ISD::UNINDEXED);
8010   SDValue BP = LD->getOperand(1);
8011   SDValue Inc = LD->getOperand(2);
8012
8013   // Some backends use TargetConstants for load offsets, but don't expect
8014   // TargetConstants in general ADD nodes. We can convert these constants into
8015   // regular Constants (if the constant is not opaque).
8016   assert((Inc.getOpcode() != ISD::TargetConstant ||
8017           !cast<ConstantSDNode>(Inc)->isOpaque()) &&
8018          "Cannot split out indexing using opaque target constants");
8019   if (Inc.getOpcode() == ISD::TargetConstant) {
8020     ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc);
8021     Inc = DAG.getConstant(*ConstInc->getConstantIntValue(),
8022                           ConstInc->getValueType(0));
8023   }
8024
8025   unsigned Opc =
8026       (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB);
8027   return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc);
8028 }
8029
8030 SDValue DAGCombiner::visitLOAD(SDNode *N) {
8031   LoadSDNode *LD  = cast<LoadSDNode>(N);
8032   SDValue Chain = LD->getChain();
8033   SDValue Ptr   = LD->getBasePtr();
8034
8035   // If load is not volatile and there are no uses of the loaded value (and
8036   // the updated indexed value in case of indexed loads), change uses of the
8037   // chain value into uses of the chain input (i.e. delete the dead load).
8038   if (!LD->isVolatile()) {
8039     if (N->getValueType(1) == MVT::Other) {
8040       // Unindexed loads.
8041       if (!N->hasAnyUseOfValue(0)) {
8042         // It's not safe to use the two value CombineTo variant here. e.g.
8043         // v1, chain2 = load chain1, loc
8044         // v2, chain3 = load chain2, loc
8045         // v3         = add v2, c
8046         // Now we replace use of chain2 with chain1.  This makes the second load
8047         // isomorphic to the one we are deleting, and thus makes this load live.
8048         DEBUG(dbgs() << "\nReplacing.6 ";
8049               N->dump(&DAG);
8050               dbgs() << "\nWith chain: ";
8051               Chain.getNode()->dump(&DAG);
8052               dbgs() << "\n");
8053         WorklistRemover DeadNodes(*this);
8054         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
8055
8056         if (N->use_empty())
8057           deleteAndRecombine(N);
8058
8059         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
8060       }
8061     } else {
8062       // Indexed loads.
8063       assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
8064
8065       // If this load has an opaque TargetConstant offset, then we cannot split
8066       // the indexing into an add/sub directly (that TargetConstant may not be
8067       // valid for a different type of node, and we cannot convert an opaque
8068       // target constant into a regular constant).
8069       bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant &&
8070                        cast<ConstantSDNode>(LD->getOperand(2))->isOpaque();
8071
8072       if (!N->hasAnyUseOfValue(0) &&
8073           ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) {
8074         SDValue Undef = DAG.getUNDEF(N->getValueType(0));
8075         SDValue Index;
8076         if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) {
8077           Index = SplitIndexingFromLoad(LD);
8078           // Try to fold the base pointer arithmetic into subsequent loads and
8079           // stores.
8080           AddUsersToWorklist(N);
8081         } else
8082           Index = DAG.getUNDEF(N->getValueType(1));
8083         DEBUG(dbgs() << "\nReplacing.7 ";
8084               N->dump(&DAG);
8085               dbgs() << "\nWith: ";
8086               Undef.getNode()->dump(&DAG);
8087               dbgs() << " and 2 other values\n");
8088         WorklistRemover DeadNodes(*this);
8089         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
8090         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index);
8091         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
8092         deleteAndRecombine(N);
8093         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
8094       }
8095     }
8096   }
8097
8098   // If this load is directly stored, replace the load value with the stored
8099   // value.
8100   // TODO: Handle store large -> read small portion.
8101   // TODO: Handle TRUNCSTORE/LOADEXT
8102   if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
8103     if (ISD::isNON_TRUNCStore(Chain.getNode())) {
8104       StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
8105       if (PrevST->getBasePtr() == Ptr &&
8106           PrevST->getValue().getValueType() == N->getValueType(0))
8107       return CombineTo(N, Chain.getOperand(1), Chain);
8108     }
8109   }
8110
8111   // Try to infer better alignment information than the load already has.
8112   if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
8113     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
8114       if (Align > LD->getMemOperand()->getBaseAlignment()) {
8115         SDValue NewLoad =
8116                DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
8117                               LD->getValueType(0),
8118                               Chain, Ptr, LD->getPointerInfo(),
8119                               LD->getMemoryVT(),
8120                               LD->isVolatile(), LD->isNonTemporal(),
8121                               LD->isInvariant(), Align, LD->getAAInfo());
8122         return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
8123       }
8124     }
8125   }
8126
8127   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
8128     TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
8129 #ifndef NDEBUG
8130   if (CombinerAAOnlyFunc.getNumOccurrences() &&
8131       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
8132     UseAA = false;
8133 #endif
8134   if (UseAA && LD->isUnindexed()) {
8135     // Walk up chain skipping non-aliasing memory nodes.
8136     SDValue BetterChain = FindBetterChain(N, Chain);
8137
8138     // If there is a better chain.
8139     if (Chain != BetterChain) {
8140       SDValue ReplLoad;
8141
8142       // Replace the chain to void dependency.
8143       if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
8144         ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
8145                                BetterChain, Ptr, LD->getMemOperand());
8146       } else {
8147         ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
8148                                   LD->getValueType(0),
8149                                   BetterChain, Ptr, LD->getMemoryVT(),
8150                                   LD->getMemOperand());
8151       }
8152
8153       // Create token factor to keep old chain connected.
8154       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
8155                                   MVT::Other, Chain, ReplLoad.getValue(1));
8156
8157       // Make sure the new and old chains are cleaned up.
8158       AddToWorklist(Token.getNode());
8159
8160       // Replace uses with load result and token factor. Don't add users
8161       // to work list.
8162       return CombineTo(N, ReplLoad.getValue(0), Token, false);
8163     }
8164   }
8165
8166   // Try transforming N to an indexed load.
8167   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
8168     return SDValue(N, 0);
8169
8170   // Try to slice up N to more direct loads if the slices are mapped to
8171   // different register banks or pairing can take place.
8172   if (SliceUpLoad(N))
8173     return SDValue(N, 0);
8174
8175   return SDValue();
8176 }
8177
8178 namespace {
8179 /// \brief Helper structure used to slice a load in smaller loads.
8180 /// Basically a slice is obtained from the following sequence:
8181 /// Origin = load Ty1, Base
8182 /// Shift = srl Ty1 Origin, CstTy Amount
8183 /// Inst = trunc Shift to Ty2
8184 ///
8185 /// Then, it will be rewriten into:
8186 /// Slice = load SliceTy, Base + SliceOffset
8187 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
8188 ///
8189 /// SliceTy is deduced from the number of bits that are actually used to
8190 /// build Inst.
8191 struct LoadedSlice {
8192   /// \brief Helper structure used to compute the cost of a slice.
8193   struct Cost {
8194     /// Are we optimizing for code size.
8195     bool ForCodeSize;
8196     /// Various cost.
8197     unsigned Loads;
8198     unsigned Truncates;
8199     unsigned CrossRegisterBanksCopies;
8200     unsigned ZExts;
8201     unsigned Shift;
8202
8203     Cost(bool ForCodeSize = false)
8204         : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
8205           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
8206
8207     /// \brief Get the cost of one isolated slice.
8208     Cost(const LoadedSlice &LS, bool ForCodeSize = false)
8209         : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
8210           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
8211       EVT TruncType = LS.Inst->getValueType(0);
8212       EVT LoadedType = LS.getLoadedType();
8213       if (TruncType != LoadedType &&
8214           !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
8215         ZExts = 1;
8216     }
8217
8218     /// \brief Account for slicing gain in the current cost.
8219     /// Slicing provide a few gains like removing a shift or a
8220     /// truncate. This method allows to grow the cost of the original
8221     /// load with the gain from this slice.
8222     void addSliceGain(const LoadedSlice &LS) {
8223       // Each slice saves a truncate.
8224       const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
8225       if (!TLI.isTruncateFree(LS.Inst->getValueType(0),
8226                               LS.Inst->getOperand(0).getValueType()))
8227         ++Truncates;
8228       // If there is a shift amount, this slice gets rid of it.
8229       if (LS.Shift)
8230         ++Shift;
8231       // If this slice can merge a cross register bank copy, account for it.
8232       if (LS.canMergeExpensiveCrossRegisterBankCopy())
8233         ++CrossRegisterBanksCopies;
8234     }
8235
8236     Cost &operator+=(const Cost &RHS) {
8237       Loads += RHS.Loads;
8238       Truncates += RHS.Truncates;
8239       CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
8240       ZExts += RHS.ZExts;
8241       Shift += RHS.Shift;
8242       return *this;
8243     }
8244
8245     bool operator==(const Cost &RHS) const {
8246       return Loads == RHS.Loads && Truncates == RHS.Truncates &&
8247              CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
8248              ZExts == RHS.ZExts && Shift == RHS.Shift;
8249     }
8250
8251     bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
8252
8253     bool operator<(const Cost &RHS) const {
8254       // Assume cross register banks copies are as expensive as loads.
8255       // FIXME: Do we want some more target hooks?
8256       unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
8257       unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
8258       // Unless we are optimizing for code size, consider the
8259       // expensive operation first.
8260       if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
8261         return ExpensiveOpsLHS < ExpensiveOpsRHS;
8262       return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
8263              (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
8264     }
8265
8266     bool operator>(const Cost &RHS) const { return RHS < *this; }
8267
8268     bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
8269
8270     bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
8271   };
8272   // The last instruction that represent the slice. This should be a
8273   // truncate instruction.
8274   SDNode *Inst;
8275   // The original load instruction.
8276   LoadSDNode *Origin;
8277   // The right shift amount in bits from the original load.
8278   unsigned Shift;
8279   // The DAG from which Origin came from.
8280   // This is used to get some contextual information about legal types, etc.
8281   SelectionDAG *DAG;
8282
8283   LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
8284               unsigned Shift = 0, SelectionDAG *DAG = nullptr)
8285       : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
8286
8287   LoadedSlice(const LoadedSlice &LS)
8288       : Inst(LS.Inst), Origin(LS.Origin), Shift(LS.Shift), DAG(LS.DAG) {}
8289
8290   /// \brief Get the bits used in a chunk of bits \p BitWidth large.
8291   /// \return Result is \p BitWidth and has used bits set to 1 and
8292   ///         not used bits set to 0.
8293   APInt getUsedBits() const {
8294     // Reproduce the trunc(lshr) sequence:
8295     // - Start from the truncated value.
8296     // - Zero extend to the desired bit width.
8297     // - Shift left.
8298     assert(Origin && "No original load to compare against.");
8299     unsigned BitWidth = Origin->getValueSizeInBits(0);
8300     assert(Inst && "This slice is not bound to an instruction");
8301     assert(Inst->getValueSizeInBits(0) <= BitWidth &&
8302            "Extracted slice is bigger than the whole type!");
8303     APInt UsedBits(Inst->getValueSizeInBits(0), 0);
8304     UsedBits.setAllBits();
8305     UsedBits = UsedBits.zext(BitWidth);
8306     UsedBits <<= Shift;
8307     return UsedBits;
8308   }
8309
8310   /// \brief Get the size of the slice to be loaded in bytes.
8311   unsigned getLoadedSize() const {
8312     unsigned SliceSize = getUsedBits().countPopulation();
8313     assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
8314     return SliceSize / 8;
8315   }
8316
8317   /// \brief Get the type that will be loaded for this slice.
8318   /// Note: This may not be the final type for the slice.
8319   EVT getLoadedType() const {
8320     assert(DAG && "Missing context");
8321     LLVMContext &Ctxt = *DAG->getContext();
8322     return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
8323   }
8324
8325   /// \brief Get the alignment of the load used for this slice.
8326   unsigned getAlignment() const {
8327     unsigned Alignment = Origin->getAlignment();
8328     unsigned Offset = getOffsetFromBase();
8329     if (Offset != 0)
8330       Alignment = MinAlign(Alignment, Alignment + Offset);
8331     return Alignment;
8332   }
8333
8334   /// \brief Check if this slice can be rewritten with legal operations.
8335   bool isLegal() const {
8336     // An invalid slice is not legal.
8337     if (!Origin || !Inst || !DAG)
8338       return false;
8339
8340     // Offsets are for indexed load only, we do not handle that.
8341     if (Origin->getOffset().getOpcode() != ISD::UNDEF)
8342       return false;
8343
8344     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8345
8346     // Check that the type is legal.
8347     EVT SliceType = getLoadedType();
8348     if (!TLI.isTypeLegal(SliceType))
8349       return false;
8350
8351     // Check that the load is legal for this type.
8352     if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
8353       return false;
8354
8355     // Check that the offset can be computed.
8356     // 1. Check its type.
8357     EVT PtrType = Origin->getBasePtr().getValueType();
8358     if (PtrType == MVT::Untyped || PtrType.isExtended())
8359       return false;
8360
8361     // 2. Check that it fits in the immediate.
8362     if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
8363       return false;
8364
8365     // 3. Check that the computation is legal.
8366     if (!TLI.isOperationLegal(ISD::ADD, PtrType))
8367       return false;
8368
8369     // Check that the zext is legal if it needs one.
8370     EVT TruncateType = Inst->getValueType(0);
8371     if (TruncateType != SliceType &&
8372         !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
8373       return false;
8374
8375     return true;
8376   }
8377
8378   /// \brief Get the offset in bytes of this slice in the original chunk of
8379   /// bits.
8380   /// \pre DAG != nullptr.
8381   uint64_t getOffsetFromBase() const {
8382     assert(DAG && "Missing context.");
8383     bool IsBigEndian =
8384         DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian();
8385     assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
8386     uint64_t Offset = Shift / 8;
8387     unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
8388     assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
8389            "The size of the original loaded type is not a multiple of a"
8390            " byte.");
8391     // If Offset is bigger than TySizeInBytes, it means we are loading all
8392     // zeros. This should have been optimized before in the process.
8393     assert(TySizeInBytes > Offset &&
8394            "Invalid shift amount for given loaded size");
8395     if (IsBigEndian)
8396       Offset = TySizeInBytes - Offset - getLoadedSize();
8397     return Offset;
8398   }
8399
8400   /// \brief Generate the sequence of instructions to load the slice
8401   /// represented by this object and redirect the uses of this slice to
8402   /// this new sequence of instructions.
8403   /// \pre this->Inst && this->Origin are valid Instructions and this
8404   /// object passed the legal check: LoadedSlice::isLegal returned true.
8405   /// \return The last instruction of the sequence used to load the slice.
8406   SDValue loadSlice() const {
8407     assert(Inst && Origin && "Unable to replace a non-existing slice.");
8408     const SDValue &OldBaseAddr = Origin->getBasePtr();
8409     SDValue BaseAddr = OldBaseAddr;
8410     // Get the offset in that chunk of bytes w.r.t. the endianess.
8411     int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
8412     assert(Offset >= 0 && "Offset too big to fit in int64_t!");
8413     if (Offset) {
8414       // BaseAddr = BaseAddr + Offset.
8415       EVT ArithType = BaseAddr.getValueType();
8416       BaseAddr = DAG->getNode(ISD::ADD, SDLoc(Origin), ArithType, BaseAddr,
8417                               DAG->getConstant(Offset, ArithType));
8418     }
8419
8420     // Create the type of the loaded slice according to its size.
8421     EVT SliceType = getLoadedType();
8422
8423     // Create the load for the slice.
8424     SDValue LastInst = DAG->getLoad(
8425         SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
8426         Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
8427         Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
8428     // If the final type is not the same as the loaded type, this means that
8429     // we have to pad with zero. Create a zero extend for that.
8430     EVT FinalType = Inst->getValueType(0);
8431     if (SliceType != FinalType)
8432       LastInst =
8433           DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
8434     return LastInst;
8435   }
8436
8437   /// \brief Check if this slice can be merged with an expensive cross register
8438   /// bank copy. E.g.,
8439   /// i = load i32
8440   /// f = bitcast i32 i to float
8441   bool canMergeExpensiveCrossRegisterBankCopy() const {
8442     if (!Inst || !Inst->hasOneUse())
8443       return false;
8444     SDNode *Use = *Inst->use_begin();
8445     if (Use->getOpcode() != ISD::BITCAST)
8446       return false;
8447     assert(DAG && "Missing context");
8448     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8449     EVT ResVT = Use->getValueType(0);
8450     const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
8451     const TargetRegisterClass *ArgRC =
8452         TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
8453     if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
8454       return false;
8455
8456     // At this point, we know that we perform a cross-register-bank copy.
8457     // Check if it is expensive.
8458     const TargetRegisterInfo *TRI =
8459         TLI.getTargetMachine().getSubtargetImpl()->getRegisterInfo();
8460     // Assume bitcasts are cheap, unless both register classes do not
8461     // explicitly share a common sub class.
8462     if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
8463       return false;
8464
8465     // Check if it will be merged with the load.
8466     // 1. Check the alignment constraint.
8467     unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment(
8468         ResVT.getTypeForEVT(*DAG->getContext()));
8469
8470     if (RequiredAlignment > getAlignment())
8471       return false;
8472
8473     // 2. Check that the load is a legal operation for that type.
8474     if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
8475       return false;
8476
8477     // 3. Check that we do not have a zext in the way.
8478     if (Inst->getValueType(0) != getLoadedType())
8479       return false;
8480
8481     return true;
8482   }
8483 };
8484 }
8485
8486 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
8487 /// \p UsedBits looks like 0..0 1..1 0..0.
8488 static bool areUsedBitsDense(const APInt &UsedBits) {
8489   // If all the bits are one, this is dense!
8490   if (UsedBits.isAllOnesValue())
8491     return true;
8492
8493   // Get rid of the unused bits on the right.
8494   APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
8495   // Get rid of the unused bits on the left.
8496   if (NarrowedUsedBits.countLeadingZeros())
8497     NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
8498   // Check that the chunk of bits is completely used.
8499   return NarrowedUsedBits.isAllOnesValue();
8500 }
8501
8502 /// \brief Check whether or not \p First and \p Second are next to each other
8503 /// in memory. This means that there is no hole between the bits loaded
8504 /// by \p First and the bits loaded by \p Second.
8505 static bool areSlicesNextToEachOther(const LoadedSlice &First,
8506                                      const LoadedSlice &Second) {
8507   assert(First.Origin == Second.Origin && First.Origin &&
8508          "Unable to match different memory origins.");
8509   APInt UsedBits = First.getUsedBits();
8510   assert((UsedBits & Second.getUsedBits()) == 0 &&
8511          "Slices are not supposed to overlap.");
8512   UsedBits |= Second.getUsedBits();
8513   return areUsedBitsDense(UsedBits);
8514 }
8515
8516 /// \brief Adjust the \p GlobalLSCost according to the target
8517 /// paring capabilities and the layout of the slices.
8518 /// \pre \p GlobalLSCost should account for at least as many loads as
8519 /// there is in the slices in \p LoadedSlices.
8520 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8521                                  LoadedSlice::Cost &GlobalLSCost) {
8522   unsigned NumberOfSlices = LoadedSlices.size();
8523   // If there is less than 2 elements, no pairing is possible.
8524   if (NumberOfSlices < 2)
8525     return;
8526
8527   // Sort the slices so that elements that are likely to be next to each
8528   // other in memory are next to each other in the list.
8529   std::sort(LoadedSlices.begin(), LoadedSlices.end(),
8530             [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
8531     assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
8532     return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
8533   });
8534   const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
8535   // First (resp. Second) is the first (resp. Second) potentially candidate
8536   // to be placed in a paired load.
8537   const LoadedSlice *First = nullptr;
8538   const LoadedSlice *Second = nullptr;
8539   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
8540                 // Set the beginning of the pair.
8541                                                            First = Second) {
8542
8543     Second = &LoadedSlices[CurrSlice];
8544
8545     // If First is NULL, it means we start a new pair.
8546     // Get to the next slice.
8547     if (!First)
8548       continue;
8549
8550     EVT LoadedType = First->getLoadedType();
8551
8552     // If the types of the slices are different, we cannot pair them.
8553     if (LoadedType != Second->getLoadedType())
8554       continue;
8555
8556     // Check if the target supplies paired loads for this type.
8557     unsigned RequiredAlignment = 0;
8558     if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
8559       // move to the next pair, this type is hopeless.
8560       Second = nullptr;
8561       continue;
8562     }
8563     // Check if we meet the alignment requirement.
8564     if (RequiredAlignment > First->getAlignment())
8565       continue;
8566
8567     // Check that both loads are next to each other in memory.
8568     if (!areSlicesNextToEachOther(*First, *Second))
8569       continue;
8570
8571     assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
8572     --GlobalLSCost.Loads;
8573     // Move to the next pair.
8574     Second = nullptr;
8575   }
8576 }
8577
8578 /// \brief Check the profitability of all involved LoadedSlice.
8579 /// Currently, it is considered profitable if there is exactly two
8580 /// involved slices (1) which are (2) next to each other in memory, and
8581 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
8582 ///
8583 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
8584 /// the elements themselves.
8585 ///
8586 /// FIXME: When the cost model will be mature enough, we can relax
8587 /// constraints (1) and (2).
8588 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8589                                 const APInt &UsedBits, bool ForCodeSize) {
8590   unsigned NumberOfSlices = LoadedSlices.size();
8591   if (StressLoadSlicing)
8592     return NumberOfSlices > 1;
8593
8594   // Check (1).
8595   if (NumberOfSlices != 2)
8596     return false;
8597
8598   // Check (2).
8599   if (!areUsedBitsDense(UsedBits))
8600     return false;
8601
8602   // Check (3).
8603   LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
8604   // The original code has one big load.
8605   OrigCost.Loads = 1;
8606   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
8607     const LoadedSlice &LS = LoadedSlices[CurrSlice];
8608     // Accumulate the cost of all the slices.
8609     LoadedSlice::Cost SliceCost(LS, ForCodeSize);
8610     GlobalSlicingCost += SliceCost;
8611
8612     // Account as cost in the original configuration the gain obtained
8613     // with the current slices.
8614     OrigCost.addSliceGain(LS);
8615   }
8616
8617   // If the target supports paired load, adjust the cost accordingly.
8618   adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
8619   return OrigCost > GlobalSlicingCost;
8620 }
8621
8622 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
8623 /// operations, split it in the various pieces being extracted.
8624 ///
8625 /// This sort of thing is introduced by SROA.
8626 /// This slicing takes care not to insert overlapping loads.
8627 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
8628 bool DAGCombiner::SliceUpLoad(SDNode *N) {
8629   if (Level < AfterLegalizeDAG)
8630     return false;
8631
8632   LoadSDNode *LD = cast<LoadSDNode>(N);
8633   if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
8634       !LD->getValueType(0).isInteger())
8635     return false;
8636
8637   // Keep track of already used bits to detect overlapping values.
8638   // In that case, we will just abort the transformation.
8639   APInt UsedBits(LD->getValueSizeInBits(0), 0);
8640
8641   SmallVector<LoadedSlice, 4> LoadedSlices;
8642
8643   // Check if this load is used as several smaller chunks of bits.
8644   // Basically, look for uses in trunc or trunc(lshr) and record a new chain
8645   // of computation for each trunc.
8646   for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
8647        UI != UIEnd; ++UI) {
8648     // Skip the uses of the chain.
8649     if (UI.getUse().getResNo() != 0)
8650       continue;
8651
8652     SDNode *User = *UI;
8653     unsigned Shift = 0;
8654
8655     // Check if this is a trunc(lshr).
8656     if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
8657         isa<ConstantSDNode>(User->getOperand(1))) {
8658       Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
8659       User = *User->use_begin();
8660     }
8661
8662     // At this point, User is a Truncate, iff we encountered, trunc or
8663     // trunc(lshr).
8664     if (User->getOpcode() != ISD::TRUNCATE)
8665       return false;
8666
8667     // The width of the type must be a power of 2 and greater than 8-bits.
8668     // Otherwise the load cannot be represented in LLVM IR.
8669     // Moreover, if we shifted with a non-8-bits multiple, the slice
8670     // will be across several bytes. We do not support that.
8671     unsigned Width = User->getValueSizeInBits(0);
8672     if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
8673       return 0;
8674
8675     // Build the slice for this chain of computations.
8676     LoadedSlice LS(User, LD, Shift, &DAG);
8677     APInt CurrentUsedBits = LS.getUsedBits();
8678
8679     // Check if this slice overlaps with another.
8680     if ((CurrentUsedBits & UsedBits) != 0)
8681       return false;
8682     // Update the bits used globally.
8683     UsedBits |= CurrentUsedBits;
8684
8685     // Check if the new slice would be legal.
8686     if (!LS.isLegal())
8687       return false;
8688
8689     // Record the slice.
8690     LoadedSlices.push_back(LS);
8691   }
8692
8693   // Abort slicing if it does not seem to be profitable.
8694   if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
8695     return false;
8696
8697   ++SlicedLoads;
8698
8699   // Rewrite each chain to use an independent load.
8700   // By construction, each chain can be represented by a unique load.
8701
8702   // Prepare the argument for the new token factor for all the slices.
8703   SmallVector<SDValue, 8> ArgChains;
8704   for (SmallVectorImpl<LoadedSlice>::const_iterator
8705            LSIt = LoadedSlices.begin(),
8706            LSItEnd = LoadedSlices.end();
8707        LSIt != LSItEnd; ++LSIt) {
8708     SDValue SliceInst = LSIt->loadSlice();
8709     CombineTo(LSIt->Inst, SliceInst, true);
8710     if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
8711       SliceInst = SliceInst.getOperand(0);
8712     assert(SliceInst->getOpcode() == ISD::LOAD &&
8713            "It takes more than a zext to get to the loaded slice!!");
8714     ArgChains.push_back(SliceInst.getValue(1));
8715   }
8716
8717   SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
8718                               ArgChains);
8719   DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
8720   return true;
8721 }
8722
8723 /// Check to see if V is (and load (ptr), imm), where the load is having
8724 /// specific bytes cleared out.  If so, return the byte size being masked out
8725 /// and the shift amount.
8726 static std::pair<unsigned, unsigned>
8727 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
8728   std::pair<unsigned, unsigned> Result(0, 0);
8729
8730   // Check for the structure we're looking for.
8731   if (V->getOpcode() != ISD::AND ||
8732       !isa<ConstantSDNode>(V->getOperand(1)) ||
8733       !ISD::isNormalLoad(V->getOperand(0).getNode()))
8734     return Result;
8735
8736   // Check the chain and pointer.
8737   LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
8738   if (LD->getBasePtr() != Ptr) return Result;  // Not from same pointer.
8739
8740   // The store should be chained directly to the load or be an operand of a
8741   // tokenfactor.
8742   if (LD == Chain.getNode())
8743     ; // ok.
8744   else if (Chain->getOpcode() != ISD::TokenFactor)
8745     return Result; // Fail.
8746   else {
8747     bool isOk = false;
8748     for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
8749       if (Chain->getOperand(i).getNode() == LD) {
8750         isOk = true;
8751         break;
8752       }
8753     if (!isOk) return Result;
8754   }
8755
8756   // This only handles simple types.
8757   if (V.getValueType() != MVT::i16 &&
8758       V.getValueType() != MVT::i32 &&
8759       V.getValueType() != MVT::i64)
8760     return Result;
8761
8762   // Check the constant mask.  Invert it so that the bits being masked out are
8763   // 0 and the bits being kept are 1.  Use getSExtValue so that leading bits
8764   // follow the sign bit for uniformity.
8765   uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
8766   unsigned NotMaskLZ = countLeadingZeros(NotMask);
8767   if (NotMaskLZ & 7) return Result;  // Must be multiple of a byte.
8768   unsigned NotMaskTZ = countTrailingZeros(NotMask);
8769   if (NotMaskTZ & 7) return Result;  // Must be multiple of a byte.
8770   if (NotMaskLZ == 64) return Result;  // All zero mask.
8771
8772   // See if we have a continuous run of bits.  If so, we have 0*1+0*
8773   if (CountTrailingOnes_64(NotMask >> NotMaskTZ)+NotMaskTZ+NotMaskLZ != 64)
8774     return Result;
8775
8776   // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
8777   if (V.getValueType() != MVT::i64 && NotMaskLZ)
8778     NotMaskLZ -= 64-V.getValueSizeInBits();
8779
8780   unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
8781   switch (MaskedBytes) {
8782   case 1:
8783   case 2:
8784   case 4: break;
8785   default: return Result; // All one mask, or 5-byte mask.
8786   }
8787
8788   // Verify that the first bit starts at a multiple of mask so that the access
8789   // is aligned the same as the access width.
8790   if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
8791
8792   Result.first = MaskedBytes;
8793   Result.second = NotMaskTZ/8;
8794   return Result;
8795 }
8796
8797
8798 /// Check to see if IVal is something that provides a value as specified by
8799 /// MaskInfo. If so, replace the specified store with a narrower store of
8800 /// truncated IVal.
8801 static SDNode *
8802 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
8803                                 SDValue IVal, StoreSDNode *St,
8804                                 DAGCombiner *DC) {
8805   unsigned NumBytes = MaskInfo.first;
8806   unsigned ByteShift = MaskInfo.second;
8807   SelectionDAG &DAG = DC->getDAG();
8808
8809   // Check to see if IVal is all zeros in the part being masked in by the 'or'
8810   // that uses this.  If not, this is not a replacement.
8811   APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
8812                                   ByteShift*8, (ByteShift+NumBytes)*8);
8813   if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
8814
8815   // Check that it is legal on the target to do this.  It is legal if the new
8816   // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
8817   // legalization.
8818   MVT VT = MVT::getIntegerVT(NumBytes*8);
8819   if (!DC->isTypeLegal(VT))
8820     return nullptr;
8821
8822   // Okay, we can do this!  Replace the 'St' store with a store of IVal that is
8823   // shifted by ByteShift and truncated down to NumBytes.
8824   if (ByteShift)
8825     IVal = DAG.getNode(ISD::SRL, SDLoc(IVal), IVal.getValueType(), IVal,
8826                        DAG.getConstant(ByteShift*8,
8827                                     DC->getShiftAmountTy(IVal.getValueType())));
8828
8829   // Figure out the offset for the store and the alignment of the access.
8830   unsigned StOffset;
8831   unsigned NewAlign = St->getAlignment();
8832
8833   if (DAG.getTargetLoweringInfo().isLittleEndian())
8834     StOffset = ByteShift;
8835   else
8836     StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
8837
8838   SDValue Ptr = St->getBasePtr();
8839   if (StOffset) {
8840     Ptr = DAG.getNode(ISD::ADD, SDLoc(IVal), Ptr.getValueType(),
8841                       Ptr, DAG.getConstant(StOffset, Ptr.getValueType()));
8842     NewAlign = MinAlign(NewAlign, StOffset);
8843   }
8844
8845   // Truncate down to the new size.
8846   IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
8847
8848   ++OpsNarrowed;
8849   return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
8850                       St->getPointerInfo().getWithOffset(StOffset),
8851                       false, false, NewAlign).getNode();
8852 }
8853
8854
8855 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and
8856 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try
8857 /// narrowing the load and store if it would end up being a win for performance
8858 /// or code size.
8859 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
8860   StoreSDNode *ST  = cast<StoreSDNode>(N);
8861   if (ST->isVolatile())
8862     return SDValue();
8863
8864   SDValue Chain = ST->getChain();
8865   SDValue Value = ST->getValue();
8866   SDValue Ptr   = ST->getBasePtr();
8867   EVT VT = Value.getValueType();
8868
8869   if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
8870     return SDValue();
8871
8872   unsigned Opc = Value.getOpcode();
8873
8874   // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
8875   // is a byte mask indicating a consecutive number of bytes, check to see if
8876   // Y is known to provide just those bytes.  If so, we try to replace the
8877   // load + replace + store sequence with a single (narrower) store, which makes
8878   // the load dead.
8879   if (Opc == ISD::OR) {
8880     std::pair<unsigned, unsigned> MaskedLoad;
8881     MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
8882     if (MaskedLoad.first)
8883       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8884                                                   Value.getOperand(1), ST,this))
8885         return SDValue(NewST, 0);
8886
8887     // Or is commutative, so try swapping X and Y.
8888     MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
8889     if (MaskedLoad.first)
8890       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8891                                                   Value.getOperand(0), ST,this))
8892         return SDValue(NewST, 0);
8893   }
8894
8895   if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
8896       Value.getOperand(1).getOpcode() != ISD::Constant)
8897     return SDValue();
8898
8899   SDValue N0 = Value.getOperand(0);
8900   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8901       Chain == SDValue(N0.getNode(), 1)) {
8902     LoadSDNode *LD = cast<LoadSDNode>(N0);
8903     if (LD->getBasePtr() != Ptr ||
8904         LD->getPointerInfo().getAddrSpace() !=
8905         ST->getPointerInfo().getAddrSpace())
8906       return SDValue();
8907
8908     // Find the type to narrow it the load / op / store to.
8909     SDValue N1 = Value.getOperand(1);
8910     unsigned BitWidth = N1.getValueSizeInBits();
8911     APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
8912     if (Opc == ISD::AND)
8913       Imm ^= APInt::getAllOnesValue(BitWidth);
8914     if (Imm == 0 || Imm.isAllOnesValue())
8915       return SDValue();
8916     unsigned ShAmt = Imm.countTrailingZeros();
8917     unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
8918     unsigned NewBW = NextPowerOf2(MSB - ShAmt);
8919     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
8920     while (NewBW < BitWidth &&
8921            !(TLI.isOperationLegalOrCustom(Opc, NewVT) &&
8922              TLI.isNarrowingProfitable(VT, NewVT))) {
8923       NewBW = NextPowerOf2(NewBW);
8924       NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
8925     }
8926     if (NewBW >= BitWidth)
8927       return SDValue();
8928
8929     // If the lsb changed does not start at the type bitwidth boundary,
8930     // start at the previous one.
8931     if (ShAmt % NewBW)
8932       ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
8933     APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
8934                                    std::min(BitWidth, ShAmt + NewBW));
8935     if ((Imm & Mask) == Imm) {
8936       APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
8937       if (Opc == ISD::AND)
8938         NewImm ^= APInt::getAllOnesValue(NewBW);
8939       uint64_t PtrOff = ShAmt / 8;
8940       // For big endian targets, we need to adjust the offset to the pointer to
8941       // load the correct bytes.
8942       if (TLI.isBigEndian())
8943         PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
8944
8945       unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
8946       Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
8947       if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
8948         return SDValue();
8949
8950       SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
8951                                    Ptr.getValueType(), Ptr,
8952                                    DAG.getConstant(PtrOff, Ptr.getValueType()));
8953       SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
8954                                   LD->getChain(), NewPtr,
8955                                   LD->getPointerInfo().getWithOffset(PtrOff),
8956                                   LD->isVolatile(), LD->isNonTemporal(),
8957                                   LD->isInvariant(), NewAlign,
8958                                   LD->getAAInfo());
8959       SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
8960                                    DAG.getConstant(NewImm, NewVT));
8961       SDValue NewST = DAG.getStore(Chain, SDLoc(N),
8962                                    NewVal, NewPtr,
8963                                    ST->getPointerInfo().getWithOffset(PtrOff),
8964                                    false, false, NewAlign);
8965
8966       AddToWorklist(NewPtr.getNode());
8967       AddToWorklist(NewLD.getNode());
8968       AddToWorklist(NewVal.getNode());
8969       WorklistRemover DeadNodes(*this);
8970       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
8971       ++OpsNarrowed;
8972       return NewST;
8973     }
8974   }
8975
8976   return SDValue();
8977 }
8978
8979 /// For a given floating point load / store pair, if the load value isn't used
8980 /// by any other operations, then consider transforming the pair to integer
8981 /// load / store operations if the target deems the transformation profitable.
8982 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
8983   StoreSDNode *ST  = cast<StoreSDNode>(N);
8984   SDValue Chain = ST->getChain();
8985   SDValue Value = ST->getValue();
8986   if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
8987       Value.hasOneUse() &&
8988       Chain == SDValue(Value.getNode(), 1)) {
8989     LoadSDNode *LD = cast<LoadSDNode>(Value);
8990     EVT VT = LD->getMemoryVT();
8991     if (!VT.isFloatingPoint() ||
8992         VT != ST->getMemoryVT() ||
8993         LD->isNonTemporal() ||
8994         ST->isNonTemporal() ||
8995         LD->getPointerInfo().getAddrSpace() != 0 ||
8996         ST->getPointerInfo().getAddrSpace() != 0)
8997       return SDValue();
8998
8999     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
9000     if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
9001         !TLI.isOperationLegal(ISD::STORE, IntVT) ||
9002         !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
9003         !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
9004       return SDValue();
9005
9006     unsigned LDAlign = LD->getAlignment();
9007     unsigned STAlign = ST->getAlignment();
9008     Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
9009     unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
9010     if (LDAlign < ABIAlign || STAlign < ABIAlign)
9011       return SDValue();
9012
9013     SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
9014                                 LD->getChain(), LD->getBasePtr(),
9015                                 LD->getPointerInfo(),
9016                                 false, false, false, LDAlign);
9017
9018     SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
9019                                  NewLD, ST->getBasePtr(),
9020                                  ST->getPointerInfo(),
9021                                  false, false, STAlign);
9022
9023     AddToWorklist(NewLD.getNode());
9024     AddToWorklist(NewST.getNode());
9025     WorklistRemover DeadNodes(*this);
9026     DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
9027     ++LdStFP2Int;
9028     return NewST;
9029   }
9030
9031   return SDValue();
9032 }
9033
9034 /// Helper struct to parse and store a memory address as base + index + offset.
9035 /// We ignore sign extensions when it is safe to do so.
9036 /// The following two expressions are not equivalent. To differentiate we need
9037 /// to store whether there was a sign extension involved in the index
9038 /// computation.
9039 ///  (load (i64 add (i64 copyfromreg %c)
9040 ///                 (i64 signextend (add (i8 load %index)
9041 ///                                      (i8 1))))
9042 /// vs
9043 ///
9044 /// (load (i64 add (i64 copyfromreg %c)
9045 ///                (i64 signextend (i32 add (i32 signextend (i8 load %index))
9046 ///                                         (i32 1)))))
9047 struct BaseIndexOffset {
9048   SDValue Base;
9049   SDValue Index;
9050   int64_t Offset;
9051   bool IsIndexSignExt;
9052
9053   BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
9054
9055   BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
9056                   bool IsIndexSignExt) :
9057     Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
9058
9059   bool equalBaseIndex(const BaseIndexOffset &Other) {
9060     return Other.Base == Base && Other.Index == Index &&
9061       Other.IsIndexSignExt == IsIndexSignExt;
9062   }
9063
9064   /// Parses tree in Ptr for base, index, offset addresses.
9065   static BaseIndexOffset match(SDValue Ptr) {
9066     bool IsIndexSignExt = false;
9067
9068     // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
9069     // instruction, then it could be just the BASE or everything else we don't
9070     // know how to handle. Just use Ptr as BASE and give up.
9071     if (Ptr->getOpcode() != ISD::ADD)
9072       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9073
9074     // We know that we have at least an ADD instruction. Try to pattern match
9075     // the simple case of BASE + OFFSET.
9076     if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
9077       int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
9078       return  BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
9079                               IsIndexSignExt);
9080     }
9081
9082     // Inside a loop the current BASE pointer is calculated using an ADD and a
9083     // MUL instruction. In this case Ptr is the actual BASE pointer.
9084     // (i64 add (i64 %array_ptr)
9085     //          (i64 mul (i64 %induction_var)
9086     //                   (i64 %element_size)))
9087     if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
9088       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9089
9090     // Look at Base + Index + Offset cases.
9091     SDValue Base = Ptr->getOperand(0);
9092     SDValue IndexOffset = Ptr->getOperand(1);
9093
9094     // Skip signextends.
9095     if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
9096       IndexOffset = IndexOffset->getOperand(0);
9097       IsIndexSignExt = true;
9098     }
9099
9100     // Either the case of Base + Index (no offset) or something else.
9101     if (IndexOffset->getOpcode() != ISD::ADD)
9102       return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
9103
9104     // Now we have the case of Base + Index + offset.
9105     SDValue Index = IndexOffset->getOperand(0);
9106     SDValue Offset = IndexOffset->getOperand(1);
9107
9108     if (!isa<ConstantSDNode>(Offset))
9109       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9110
9111     // Ignore signextends.
9112     if (Index->getOpcode() == ISD::SIGN_EXTEND) {
9113       Index = Index->getOperand(0);
9114       IsIndexSignExt = true;
9115     } else IsIndexSignExt = false;
9116
9117     int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
9118     return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
9119   }
9120 };
9121
9122 /// Holds a pointer to an LSBaseSDNode as well as information on where it
9123 /// is located in a sequence of memory operations connected by a chain.
9124 struct MemOpLink {
9125   MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
9126     MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
9127   // Ptr to the mem node.
9128   LSBaseSDNode *MemNode;
9129   // Offset from the base ptr.
9130   int64_t OffsetFromBase;
9131   // What is the sequence number of this mem node.
9132   // Lowest mem operand in the DAG starts at zero.
9133   unsigned SequenceNum;
9134 };
9135
9136 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
9137   EVT MemVT = St->getMemoryVT();
9138   int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
9139   bool NoVectors = DAG.getMachineFunction().getFunction()->getAttributes().
9140     hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
9141
9142   // Don't merge vectors into wider inputs.
9143   if (MemVT.isVector() || !MemVT.isSimple())
9144     return false;
9145
9146   // Perform an early exit check. Do not bother looking at stored values that
9147   // are not constants or loads.
9148   SDValue StoredVal = St->getValue();
9149   bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
9150   if (!isa<ConstantSDNode>(StoredVal) && !isa<ConstantFPSDNode>(StoredVal) &&
9151       !IsLoadSrc)
9152     return false;
9153
9154   // Only look at ends of store sequences.
9155   SDValue Chain = SDValue(St, 0);
9156   if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
9157     return false;
9158
9159   // This holds the base pointer, index, and the offset in bytes from the base
9160   // pointer.
9161   BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
9162
9163   // We must have a base and an offset.
9164   if (!BasePtr.Base.getNode())
9165     return false;
9166
9167   // Do not handle stores to undef base pointers.
9168   if (BasePtr.Base.getOpcode() == ISD::UNDEF)
9169     return false;
9170
9171   // Save the LoadSDNodes that we find in the chain.
9172   // We need to make sure that these nodes do not interfere with
9173   // any of the store nodes.
9174   SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
9175
9176   // Save the StoreSDNodes that we find in the chain.
9177   SmallVector<MemOpLink, 8> StoreNodes;
9178
9179   // Walk up the chain and look for nodes with offsets from the same
9180   // base pointer. Stop when reaching an instruction with a different kind
9181   // or instruction which has a different base pointer.
9182   unsigned Seq = 0;
9183   StoreSDNode *Index = St;
9184   while (Index) {
9185     // If the chain has more than one use, then we can't reorder the mem ops.
9186     if (Index != St && !SDValue(Index, 0)->hasOneUse())
9187       break;
9188
9189     // Find the base pointer and offset for this memory node.
9190     BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
9191
9192     // Check that the base pointer is the same as the original one.
9193     if (!Ptr.equalBaseIndex(BasePtr))
9194       break;
9195
9196     // Check that the alignment is the same.
9197     if (Index->getAlignment() != St->getAlignment())
9198       break;
9199
9200     // The memory operands must not be volatile.
9201     if (Index->isVolatile() || Index->isIndexed())
9202       break;
9203
9204     // No truncation.
9205     if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
9206       if (St->isTruncatingStore())
9207         break;
9208
9209     // The stored memory type must be the same.
9210     if (Index->getMemoryVT() != MemVT)
9211       break;
9212
9213     // We do not allow unaligned stores because we want to prevent overriding
9214     // stores.
9215     if (Index->getAlignment()*8 != MemVT.getSizeInBits())
9216       break;
9217
9218     // We found a potential memory operand to merge.
9219     StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
9220
9221     // Find the next memory operand in the chain. If the next operand in the
9222     // chain is a store then move up and continue the scan with the next
9223     // memory operand. If the next operand is a load save it and use alias
9224     // information to check if it interferes with anything.
9225     SDNode *NextInChain = Index->getChain().getNode();
9226     while (1) {
9227       if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
9228         // We found a store node. Use it for the next iteration.
9229         Index = STn;
9230         break;
9231       } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
9232         if (Ldn->isVolatile()) {
9233           Index = nullptr;
9234           break;
9235         }
9236
9237         // Save the load node for later. Continue the scan.
9238         AliasLoadNodes.push_back(Ldn);
9239         NextInChain = Ldn->getChain().getNode();
9240         continue;
9241       } else {
9242         Index = nullptr;
9243         break;
9244       }
9245     }
9246   }
9247
9248   // Check if there is anything to merge.
9249   if (StoreNodes.size() < 2)
9250     return false;
9251
9252   // Sort the memory operands according to their distance from the base pointer.
9253   std::sort(StoreNodes.begin(), StoreNodes.end(),
9254             [](MemOpLink LHS, MemOpLink RHS) {
9255     return LHS.OffsetFromBase < RHS.OffsetFromBase ||
9256            (LHS.OffsetFromBase == RHS.OffsetFromBase &&
9257             LHS.SequenceNum > RHS.SequenceNum);
9258   });
9259
9260   // Scan the memory operations on the chain and find the first non-consecutive
9261   // store memory address.
9262   unsigned LastConsecutiveStore = 0;
9263   int64_t StartAddress = StoreNodes[0].OffsetFromBase;
9264   for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
9265
9266     // Check that the addresses are consecutive starting from the second
9267     // element in the list of stores.
9268     if (i > 0) {
9269       int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
9270       if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9271         break;
9272     }
9273
9274     bool Alias = false;
9275     // Check if this store interferes with any of the loads that we found.
9276     for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
9277       if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
9278         Alias = true;
9279         break;
9280       }
9281     // We found a load that alias with this store. Stop the sequence.
9282     if (Alias)
9283       break;
9284
9285     // Mark this node as useful.
9286     LastConsecutiveStore = i;
9287   }
9288
9289   // The node with the lowest store address.
9290   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
9291
9292   // Store the constants into memory as one consecutive store.
9293   if (!IsLoadSrc) {
9294     unsigned LastLegalType = 0;
9295     unsigned LastLegalVectorType = 0;
9296     bool NonZero = false;
9297     for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9298       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
9299       SDValue StoredVal = St->getValue();
9300
9301       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
9302         NonZero |= !C->isNullValue();
9303       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
9304         NonZero |= !C->getConstantFPValue()->isNullValue();
9305       } else {
9306         // Non-constant.
9307         break;
9308       }
9309
9310       // Find a legal type for the constant store.
9311       unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9312       EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9313       if (TLI.isTypeLegal(StoreTy))
9314         LastLegalType = i+1;
9315       // Or check whether a truncstore is legal.
9316       else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9317                TargetLowering::TypePromoteInteger) {
9318         EVT LegalizedStoredValueTy =
9319           TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
9320         if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy))
9321           LastLegalType = i+1;
9322       }
9323
9324       // Find a legal type for the vector store.
9325       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9326       if (TLI.isTypeLegal(Ty))
9327         LastLegalVectorType = i + 1;
9328     }
9329
9330     // We only use vectors if the constant is known to be zero and the
9331     // function is not marked with the noimplicitfloat attribute.
9332     if (NonZero || NoVectors)
9333       LastLegalVectorType = 0;
9334
9335     // Check if we found a legal integer type to store.
9336     if (LastLegalType == 0 && LastLegalVectorType == 0)
9337       return false;
9338
9339     bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
9340     unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
9341
9342     // Make sure we have something to merge.
9343     if (NumElem < 2)
9344       return false;
9345
9346     unsigned EarliestNodeUsed = 0;
9347     for (unsigned i=0; i < NumElem; ++i) {
9348       // Find a chain for the new wide-store operand. Notice that some
9349       // of the store nodes that we found may not be selected for inclusion
9350       // in the wide store. The chain we use needs to be the chain of the
9351       // earliest store node which is *used* and replaced by the wide store.
9352       if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9353         EarliestNodeUsed = i;
9354     }
9355
9356     // The earliest Node in the DAG.
9357     LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9358     SDLoc DL(StoreNodes[0].MemNode);
9359
9360     SDValue StoredVal;
9361     if (UseVector) {
9362       // Find a legal type for the vector store.
9363       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9364       assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
9365       StoredVal = DAG.getConstant(0, Ty);
9366     } else {
9367       unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9368       APInt StoreInt(StoreBW, 0);
9369
9370       // Construct a single integer constant which is made of the smaller
9371       // constant inputs.
9372       bool IsLE = TLI.isLittleEndian();
9373       for (unsigned i = 0; i < NumElem ; ++i) {
9374         unsigned Idx = IsLE ?(NumElem - 1 - i) : i;
9375         StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
9376         SDValue Val = St->getValue();
9377         StoreInt<<=ElementSizeBytes*8;
9378         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
9379           StoreInt|=C->getAPIntValue().zext(StoreBW);
9380         } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
9381           StoreInt|= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
9382         } else {
9383           assert(false && "Invalid constant element type");
9384         }
9385       }
9386
9387       // Create the new Load and Store operations.
9388       EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9389       StoredVal = DAG.getConstant(StoreInt, StoreTy);
9390     }
9391
9392     SDValue NewStore = DAG.getStore(EarliestOp->getChain(), DL, StoredVal,
9393                                     FirstInChain->getBasePtr(),
9394                                     FirstInChain->getPointerInfo(),
9395                                     false, false,
9396                                     FirstInChain->getAlignment());
9397
9398     // Replace the first store with the new store
9399     CombineTo(EarliestOp, NewStore);
9400     // Erase all other stores.
9401     for (unsigned i = 0; i < NumElem ; ++i) {
9402       if (StoreNodes[i].MemNode == EarliestOp)
9403         continue;
9404       StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9405       // ReplaceAllUsesWith will replace all uses that existed when it was
9406       // called, but graph optimizations may cause new ones to appear. For
9407       // example, the case in pr14333 looks like
9408       //
9409       //  St's chain -> St -> another store -> X
9410       //
9411       // And the only difference from St to the other store is the chain.
9412       // When we change it's chain to be St's chain they become identical,
9413       // get CSEed and the net result is that X is now a use of St.
9414       // Since we know that St is redundant, just iterate.
9415       while (!St->use_empty())
9416         DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
9417       deleteAndRecombine(St);
9418     }
9419
9420     return true;
9421   }
9422
9423   // Below we handle the case of multiple consecutive stores that
9424   // come from multiple consecutive loads. We merge them into a single
9425   // wide load and a single wide store.
9426
9427   // Look for load nodes which are used by the stored values.
9428   SmallVector<MemOpLink, 8> LoadNodes;
9429
9430   // Find acceptable loads. Loads need to have the same chain (token factor),
9431   // must not be zext, volatile, indexed, and they must be consecutive.
9432   BaseIndexOffset LdBasePtr;
9433   for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9434     StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
9435     LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
9436     if (!Ld) break;
9437
9438     // Loads must only have one use.
9439     if (!Ld->hasNUsesOfValue(1, 0))
9440       break;
9441
9442     // Check that the alignment is the same as the stores.
9443     if (Ld->getAlignment() != St->getAlignment())
9444       break;
9445
9446     // The memory operands must not be volatile.
9447     if (Ld->isVolatile() || Ld->isIndexed())
9448       break;
9449
9450     // We do not accept ext loads.
9451     if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
9452       break;
9453
9454     // The stored memory type must be the same.
9455     if (Ld->getMemoryVT() != MemVT)
9456       break;
9457
9458     BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
9459     // If this is not the first ptr that we check.
9460     if (LdBasePtr.Base.getNode()) {
9461       // The base ptr must be the same.
9462       if (!LdPtr.equalBaseIndex(LdBasePtr))
9463         break;
9464     } else {
9465       // Check that all other base pointers are the same as this one.
9466       LdBasePtr = LdPtr;
9467     }
9468
9469     // We found a potential memory operand to merge.
9470     LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
9471   }
9472
9473   if (LoadNodes.size() < 2)
9474     return false;
9475
9476   // If we have load/store pair instructions and we only have two values,
9477   // don't bother.
9478   unsigned RequiredAlignment;
9479   if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) &&
9480       St->getAlignment() >= RequiredAlignment)
9481     return false;
9482
9483   // Scan the memory operations on the chain and find the first non-consecutive
9484   // load memory address. These variables hold the index in the store node
9485   // array.
9486   unsigned LastConsecutiveLoad = 0;
9487   // This variable refers to the size and not index in the array.
9488   unsigned LastLegalVectorType = 0;
9489   unsigned LastLegalIntegerType = 0;
9490   StartAddress = LoadNodes[0].OffsetFromBase;
9491   SDValue FirstChain = LoadNodes[0].MemNode->getChain();
9492   for (unsigned i = 1; i < LoadNodes.size(); ++i) {
9493     // All loads much share the same chain.
9494     if (LoadNodes[i].MemNode->getChain() != FirstChain)
9495       break;
9496
9497     int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
9498     if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9499       break;
9500     LastConsecutiveLoad = i;
9501
9502     // Find a legal type for the vector store.
9503     EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9504     if (TLI.isTypeLegal(StoreTy))
9505       LastLegalVectorType = i + 1;
9506
9507     // Find a legal type for the integer store.
9508     unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9509     StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9510     if (TLI.isTypeLegal(StoreTy))
9511       LastLegalIntegerType = i + 1;
9512     // Or check whether a truncstore and extload is legal.
9513     else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9514              TargetLowering::TypePromoteInteger) {
9515       EVT LegalizedStoredValueTy =
9516         TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
9517       if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
9518           TLI.isLoadExtLegal(ISD::ZEXTLOAD, StoreTy) &&
9519           TLI.isLoadExtLegal(ISD::SEXTLOAD, StoreTy) &&
9520           TLI.isLoadExtLegal(ISD::EXTLOAD, StoreTy))
9521         LastLegalIntegerType = i+1;
9522     }
9523   }
9524
9525   // Only use vector types if the vector type is larger than the integer type.
9526   // If they are the same, use integers.
9527   bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
9528   unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
9529
9530   // We add +1 here because the LastXXX variables refer to location while
9531   // the NumElem refers to array/index size.
9532   unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
9533   NumElem = std::min(LastLegalType, NumElem);
9534
9535   if (NumElem < 2)
9536     return false;
9537
9538   // The earliest Node in the DAG.
9539   unsigned EarliestNodeUsed = 0;
9540   LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9541   for (unsigned i=1; i<NumElem; ++i) {
9542     // Find a chain for the new wide-store operand. Notice that some
9543     // of the store nodes that we found may not be selected for inclusion
9544     // in the wide store. The chain we use needs to be the chain of the
9545     // earliest store node which is *used* and replaced by the wide store.
9546     if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9547       EarliestNodeUsed = i;
9548   }
9549
9550   // Find if it is better to use vectors or integers to load and store
9551   // to memory.
9552   EVT JointMemOpVT;
9553   if (UseVectorTy) {
9554     JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9555   } else {
9556     unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9557     JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9558   }
9559
9560   SDLoc LoadDL(LoadNodes[0].MemNode);
9561   SDLoc StoreDL(StoreNodes[0].MemNode);
9562
9563   LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
9564   SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL,
9565                                 FirstLoad->getChain(),
9566                                 FirstLoad->getBasePtr(),
9567                                 FirstLoad->getPointerInfo(),
9568                                 false, false, false,
9569                                 FirstLoad->getAlignment());
9570
9571   SDValue NewStore = DAG.getStore(EarliestOp->getChain(), StoreDL, NewLoad,
9572                                   FirstInChain->getBasePtr(),
9573                                   FirstInChain->getPointerInfo(), false, false,
9574                                   FirstInChain->getAlignment());
9575
9576   // Replace one of the loads with the new load.
9577   LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
9578   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
9579                                 SDValue(NewLoad.getNode(), 1));
9580
9581   // Remove the rest of the load chains.
9582   for (unsigned i = 1; i < NumElem ; ++i) {
9583     // Replace all chain users of the old load nodes with the chain of the new
9584     // load node.
9585     LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
9586     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
9587   }
9588
9589   // Replace the first store with the new store.
9590   CombineTo(EarliestOp, NewStore);
9591   // Erase all other stores.
9592   for (unsigned i = 0; i < NumElem ; ++i) {
9593     // Remove all Store nodes.
9594     if (StoreNodes[i].MemNode == EarliestOp)
9595       continue;
9596     StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9597     DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
9598     deleteAndRecombine(St);
9599   }
9600
9601   return true;
9602 }
9603
9604 SDValue DAGCombiner::visitSTORE(SDNode *N) {
9605   StoreSDNode *ST  = cast<StoreSDNode>(N);
9606   SDValue Chain = ST->getChain();
9607   SDValue Value = ST->getValue();
9608   SDValue Ptr   = ST->getBasePtr();
9609
9610   // If this is a store of a bit convert, store the input value if the
9611   // resultant store does not need a higher alignment than the original.
9612   if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
9613       ST->isUnindexed()) {
9614     unsigned OrigAlign = ST->getAlignment();
9615     EVT SVT = Value.getOperand(0).getValueType();
9616     unsigned Align = TLI.getDataLayout()->
9617       getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
9618     if (Align <= OrigAlign &&
9619         ((!LegalOperations && !ST->isVolatile()) ||
9620          TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
9621       return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
9622                           Ptr, ST->getPointerInfo(), ST->isVolatile(),
9623                           ST->isNonTemporal(), OrigAlign,
9624                           ST->getAAInfo());
9625   }
9626
9627   // Turn 'store undef, Ptr' -> nothing.
9628   if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
9629     return Chain;
9630
9631   // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
9632   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
9633     // NOTE: If the original store is volatile, this transform must not increase
9634     // the number of stores.  For example, on x86-32 an f64 can be stored in one
9635     // processor operation but an i64 (which is not legal) requires two.  So the
9636     // transform should not be done in this case.
9637     if (Value.getOpcode() != ISD::TargetConstantFP) {
9638       SDValue Tmp;
9639       switch (CFP->getSimpleValueType(0).SimpleTy) {
9640       default: llvm_unreachable("Unknown FP type");
9641       case MVT::f16:    // We don't do this for these yet.
9642       case MVT::f80:
9643       case MVT::f128:
9644       case MVT::ppcf128:
9645         break;
9646       case MVT::f32:
9647         if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
9648             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
9649           Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
9650                               bitcastToAPInt().getZExtValue(), MVT::i32);
9651           return DAG.getStore(Chain, SDLoc(N), Tmp,
9652                               Ptr, ST->getMemOperand());
9653         }
9654         break;
9655       case MVT::f64:
9656         if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
9657              !ST->isVolatile()) ||
9658             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
9659           Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
9660                                 getZExtValue(), MVT::i64);
9661           return DAG.getStore(Chain, SDLoc(N), Tmp,
9662                               Ptr, ST->getMemOperand());
9663         }
9664
9665         if (!ST->isVolatile() &&
9666             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
9667           // Many FP stores are not made apparent until after legalize, e.g. for
9668           // argument passing.  Since this is so common, custom legalize the
9669           // 64-bit integer store into two 32-bit stores.
9670           uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
9671           SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
9672           SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
9673           if (TLI.isBigEndian()) std::swap(Lo, Hi);
9674
9675           unsigned Alignment = ST->getAlignment();
9676           bool isVolatile = ST->isVolatile();
9677           bool isNonTemporal = ST->isNonTemporal();
9678           AAMDNodes AAInfo = ST->getAAInfo();
9679
9680           SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
9681                                      Ptr, ST->getPointerInfo(),
9682                                      isVolatile, isNonTemporal,
9683                                      ST->getAlignment(), AAInfo);
9684           Ptr = DAG.getNode(ISD::ADD, SDLoc(N), Ptr.getValueType(), Ptr,
9685                             DAG.getConstant(4, Ptr.getValueType()));
9686           Alignment = MinAlign(Alignment, 4U);
9687           SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
9688                                      Ptr, ST->getPointerInfo().getWithOffset(4),
9689                                      isVolatile, isNonTemporal,
9690                                      Alignment, AAInfo);
9691           return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
9692                              St0, St1);
9693         }
9694
9695         break;
9696       }
9697     }
9698   }
9699
9700   // Try to infer better alignment information than the store already has.
9701   if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
9702     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
9703       if (Align > ST->getAlignment())
9704         return DAG.getTruncStore(Chain, SDLoc(N), Value,
9705                                  Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
9706                                  ST->isVolatile(), ST->isNonTemporal(), Align,
9707                                  ST->getAAInfo());
9708     }
9709   }
9710
9711   // Try transforming a pair floating point load / store ops to integer
9712   // load / store ops.
9713   SDValue NewST = TransformFPLoadStorePair(N);
9714   if (NewST.getNode())
9715     return NewST;
9716
9717   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
9718     TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
9719 #ifndef NDEBUG
9720   if (CombinerAAOnlyFunc.getNumOccurrences() &&
9721       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
9722     UseAA = false;
9723 #endif
9724   if (UseAA && ST->isUnindexed()) {
9725     // Walk up chain skipping non-aliasing memory nodes.
9726     SDValue BetterChain = FindBetterChain(N, Chain);
9727
9728     // If there is a better chain.
9729     if (Chain != BetterChain) {
9730       SDValue ReplStore;
9731
9732       // Replace the chain to avoid dependency.
9733       if (ST->isTruncatingStore()) {
9734         ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
9735                                       ST->getMemoryVT(), ST->getMemOperand());
9736       } else {
9737         ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
9738                                  ST->getMemOperand());
9739       }
9740
9741       // Create token to keep both nodes around.
9742       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
9743                                   MVT::Other, Chain, ReplStore);
9744
9745       // Make sure the new and old chains are cleaned up.
9746       AddToWorklist(Token.getNode());
9747
9748       // Don't add users to work list.
9749       return CombineTo(N, Token, false);
9750     }
9751   }
9752
9753   // Try transforming N to an indexed store.
9754   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
9755     return SDValue(N, 0);
9756
9757   // FIXME: is there such a thing as a truncating indexed store?
9758   if (ST->isTruncatingStore() && ST->isUnindexed() &&
9759       Value.getValueType().isInteger()) {
9760     // See if we can simplify the input to this truncstore with knowledge that
9761     // only the low bits are being used.  For example:
9762     // "truncstore (or (shl x, 8), y), i8"  -> "truncstore y, i8"
9763     SDValue Shorter =
9764       GetDemandedBits(Value,
9765                       APInt::getLowBitsSet(
9766                         Value.getValueType().getScalarType().getSizeInBits(),
9767                         ST->getMemoryVT().getScalarType().getSizeInBits()));
9768     AddToWorklist(Value.getNode());
9769     if (Shorter.getNode())
9770       return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
9771                                Ptr, ST->getMemoryVT(), ST->getMemOperand());
9772
9773     // Otherwise, see if we can simplify the operation with
9774     // SimplifyDemandedBits, which only works if the value has a single use.
9775     if (SimplifyDemandedBits(Value,
9776                         APInt::getLowBitsSet(
9777                           Value.getValueType().getScalarType().getSizeInBits(),
9778                           ST->getMemoryVT().getScalarType().getSizeInBits())))
9779       return SDValue(N, 0);
9780   }
9781
9782   // If this is a load followed by a store to the same location, then the store
9783   // is dead/noop.
9784   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
9785     if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
9786         ST->isUnindexed() && !ST->isVolatile() &&
9787         // There can't be any side effects between the load and store, such as
9788         // a call or store.
9789         Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
9790       // The store is dead, remove it.
9791       return Chain;
9792     }
9793   }
9794
9795   // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
9796   // truncating store.  We can do this even if this is already a truncstore.
9797   if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
9798       && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
9799       TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
9800                             ST->getMemoryVT())) {
9801     return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
9802                              Ptr, ST->getMemoryVT(), ST->getMemOperand());
9803   }
9804
9805   // Only perform this optimization before the types are legal, because we
9806   // don't want to perform this optimization on every DAGCombine invocation.
9807   if (!LegalTypes) {
9808     bool EverChanged = false;
9809
9810     do {
9811       // There can be multiple store sequences on the same chain.
9812       // Keep trying to merge store sequences until we are unable to do so
9813       // or until we merge the last store on the chain.
9814       bool Changed = MergeConsecutiveStores(ST);
9815       EverChanged |= Changed;
9816       if (!Changed) break;
9817     } while (ST->getOpcode() != ISD::DELETED_NODE);
9818
9819     if (EverChanged)
9820       return SDValue(N, 0);
9821   }
9822
9823   return ReduceLoadOpStoreWidth(N);
9824 }
9825
9826 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
9827   SDValue InVec = N->getOperand(0);
9828   SDValue InVal = N->getOperand(1);
9829   SDValue EltNo = N->getOperand(2);
9830   SDLoc dl(N);
9831
9832   // If the inserted element is an UNDEF, just use the input vector.
9833   if (InVal.getOpcode() == ISD::UNDEF)
9834     return InVec;
9835
9836   EVT VT = InVec.getValueType();
9837
9838   // If we can't generate a legal BUILD_VECTOR, exit
9839   if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
9840     return SDValue();
9841
9842   // Check that we know which element is being inserted
9843   if (!isa<ConstantSDNode>(EltNo))
9844     return SDValue();
9845   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9846
9847   // Canonicalize insert_vector_elt dag nodes.
9848   // Example:
9849   // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
9850   // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
9851   //
9852   // Do this only if the child insert_vector node has one use; also
9853   // do this only if indices are both constants and Idx1 < Idx0.
9854   if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
9855       && isa<ConstantSDNode>(InVec.getOperand(2))) {
9856     unsigned OtherElt =
9857       cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue();
9858     if (Elt < OtherElt) {
9859       // Swap nodes.
9860       SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT,
9861                                   InVec.getOperand(0), InVal, EltNo);
9862       AddToWorklist(NewOp.getNode());
9863       return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
9864                          VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
9865     }
9866   }
9867
9868   // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
9869   // be converted to a BUILD_VECTOR).  Fill in the Ops vector with the
9870   // vector elements.
9871   SmallVector<SDValue, 8> Ops;
9872   // Do not combine these two vectors if the output vector will not replace
9873   // the input vector.
9874   if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
9875     Ops.append(InVec.getNode()->op_begin(),
9876                InVec.getNode()->op_end());
9877   } else if (InVec.getOpcode() == ISD::UNDEF) {
9878     unsigned NElts = VT.getVectorNumElements();
9879     Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
9880   } else {
9881     return SDValue();
9882   }
9883
9884   // Insert the element
9885   if (Elt < Ops.size()) {
9886     // All the operands of BUILD_VECTOR must have the same type;
9887     // we enforce that here.
9888     EVT OpVT = Ops[0].getValueType();
9889     if (InVal.getValueType() != OpVT)
9890       InVal = OpVT.bitsGT(InVal.getValueType()) ?
9891                 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
9892                 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
9893     Ops[Elt] = InVal;
9894   }
9895
9896   // Return the new vector
9897   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
9898 }
9899
9900 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
9901     SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) {
9902   EVT ResultVT = EVE->getValueType(0);
9903   EVT VecEltVT = InVecVT.getVectorElementType();
9904   unsigned Align = OriginalLoad->getAlignment();
9905   unsigned NewAlign = TLI.getDataLayout()->getABITypeAlignment(
9906       VecEltVT.getTypeForEVT(*DAG.getContext()));
9907
9908   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
9909     return SDValue();
9910
9911   Align = NewAlign;
9912
9913   SDValue NewPtr = OriginalLoad->getBasePtr();
9914   SDValue Offset;
9915   EVT PtrType = NewPtr.getValueType();
9916   MachinePointerInfo MPI;
9917   if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
9918     int Elt = ConstEltNo->getZExtValue();
9919     unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
9920     if (TLI.isBigEndian())
9921       PtrOff = InVecVT.getSizeInBits() / 8 - PtrOff;
9922     Offset = DAG.getConstant(PtrOff, PtrType);
9923     MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
9924   } else {
9925     Offset = DAG.getNode(
9926         ISD::MUL, SDLoc(EVE), EltNo.getValueType(), EltNo,
9927         DAG.getConstant(VecEltVT.getStoreSize(), EltNo.getValueType()));
9928     if (TLI.isBigEndian())
9929       Offset = DAG.getNode(
9930           ISD::SUB, SDLoc(EVE), EltNo.getValueType(),
9931           DAG.getConstant(InVecVT.getStoreSize(), EltNo.getValueType()), Offset);
9932     MPI = OriginalLoad->getPointerInfo();
9933   }
9934   NewPtr = DAG.getNode(ISD::ADD, SDLoc(EVE), PtrType, NewPtr, Offset);
9935
9936   // The replacement we need to do here is a little tricky: we need to
9937   // replace an extractelement of a load with a load.
9938   // Use ReplaceAllUsesOfValuesWith to do the replacement.
9939   // Note that this replacement assumes that the extractvalue is the only
9940   // use of the load; that's okay because we don't want to perform this
9941   // transformation in other cases anyway.
9942   SDValue Load;
9943   SDValue Chain;
9944   if (ResultVT.bitsGT(VecEltVT)) {
9945     // If the result type of vextract is wider than the load, then issue an
9946     // extending load instead.
9947     ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, VecEltVT)
9948                                    ? ISD::ZEXTLOAD
9949                                    : ISD::EXTLOAD;
9950     Load = DAG.getExtLoad(
9951         ExtType, SDLoc(EVE), ResultVT, OriginalLoad->getChain(), NewPtr, MPI,
9952         VecEltVT, OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
9953         OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
9954     Chain = Load.getValue(1);
9955   } else {
9956     Load = DAG.getLoad(
9957         VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, MPI,
9958         OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
9959         OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
9960     Chain = Load.getValue(1);
9961     if (ResultVT.bitsLT(VecEltVT))
9962       Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
9963     else
9964       Load = DAG.getNode(ISD::BITCAST, SDLoc(EVE), ResultVT, Load);
9965   }
9966   WorklistRemover DeadNodes(*this);
9967   SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
9968   SDValue To[] = { Load, Chain };
9969   DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
9970   // Since we're explicitly calling ReplaceAllUses, add the new node to the
9971   // worklist explicitly as well.
9972   AddToWorklist(Load.getNode());
9973   AddUsersToWorklist(Load.getNode()); // Add users too
9974   // Make sure to revisit this node to clean it up; it will usually be dead.
9975   AddToWorklist(EVE);
9976   ++OpsNarrowed;
9977   return SDValue(EVE, 0);
9978 }
9979
9980 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
9981   // (vextract (scalar_to_vector val, 0) -> val
9982   SDValue InVec = N->getOperand(0);
9983   EVT VT = InVec.getValueType();
9984   EVT NVT = N->getValueType(0);
9985
9986   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
9987     // Check if the result type doesn't match the inserted element type. A
9988     // SCALAR_TO_VECTOR may truncate the inserted element and the
9989     // EXTRACT_VECTOR_ELT may widen the extracted vector.
9990     SDValue InOp = InVec.getOperand(0);
9991     if (InOp.getValueType() != NVT) {
9992       assert(InOp.getValueType().isInteger() && NVT.isInteger());
9993       return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
9994     }
9995     return InOp;
9996   }
9997
9998   SDValue EltNo = N->getOperand(1);
9999   bool ConstEltNo = isa<ConstantSDNode>(EltNo);
10000
10001   // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
10002   // We only perform this optimization before the op legalization phase because
10003   // we may introduce new vector instructions which are not backed by TD
10004   // patterns. For example on AVX, extracting elements from a wide vector
10005   // without using extract_subvector. However, if we can find an underlying
10006   // scalar value, then we can always use that.
10007   if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
10008       && ConstEltNo) {
10009     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
10010     int NumElem = VT.getVectorNumElements();
10011     ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
10012     // Find the new index to extract from.
10013     int OrigElt = SVOp->getMaskElt(Elt);
10014
10015     // Extracting an undef index is undef.
10016     if (OrigElt == -1)
10017       return DAG.getUNDEF(NVT);
10018
10019     // Select the right vector half to extract from.
10020     SDValue SVInVec;
10021     if (OrigElt < NumElem) {
10022       SVInVec = InVec->getOperand(0);
10023     } else {
10024       SVInVec = InVec->getOperand(1);
10025       OrigElt -= NumElem;
10026     }
10027
10028     if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
10029       SDValue InOp = SVInVec.getOperand(OrigElt);
10030       if (InOp.getValueType() != NVT) {
10031         assert(InOp.getValueType().isInteger() && NVT.isInteger());
10032         InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
10033       }
10034
10035       return InOp;
10036     }
10037
10038     // FIXME: We should handle recursing on other vector shuffles and
10039     // scalar_to_vector here as well.
10040
10041     if (!LegalOperations) {
10042       EVT IndexTy = TLI.getVectorIdxTy();
10043       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT,
10044                          SVInVec, DAG.getConstant(OrigElt, IndexTy));
10045     }
10046   }
10047
10048   bool BCNumEltsChanged = false;
10049   EVT ExtVT = VT.getVectorElementType();
10050   EVT LVT = ExtVT;
10051
10052   // If the result of load has to be truncated, then it's not necessarily
10053   // profitable.
10054   if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
10055     return SDValue();
10056
10057   if (InVec.getOpcode() == ISD::BITCAST) {
10058     // Don't duplicate a load with other uses.
10059     if (!InVec.hasOneUse())
10060       return SDValue();
10061
10062     EVT BCVT = InVec.getOperand(0).getValueType();
10063     if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
10064       return SDValue();
10065     if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
10066       BCNumEltsChanged = true;
10067     InVec = InVec.getOperand(0);
10068     ExtVT = BCVT.getVectorElementType();
10069   }
10070
10071   // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size)
10072   if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() &&
10073       ISD::isNormalLoad(InVec.getNode()) &&
10074       !N->getOperand(1)->hasPredecessor(InVec.getNode())) {
10075     SDValue Index = N->getOperand(1);
10076     if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec))
10077       return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index,
10078                                                            OrigLoad);
10079   }
10080
10081   // Perform only after legalization to ensure build_vector / vector_shuffle
10082   // optimizations have already been done.
10083   if (!LegalOperations) return SDValue();
10084
10085   // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
10086   // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
10087   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
10088
10089   if (ConstEltNo) {
10090     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
10091
10092     LoadSDNode *LN0 = nullptr;
10093     const ShuffleVectorSDNode *SVN = nullptr;
10094     if (ISD::isNormalLoad(InVec.getNode())) {
10095       LN0 = cast<LoadSDNode>(InVec);
10096     } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
10097                InVec.getOperand(0).getValueType() == ExtVT &&
10098                ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
10099       // Don't duplicate a load with other uses.
10100       if (!InVec.hasOneUse())
10101         return SDValue();
10102
10103       LN0 = cast<LoadSDNode>(InVec.getOperand(0));
10104     } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
10105       // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
10106       // =>
10107       // (load $addr+1*size)
10108
10109       // Don't duplicate a load with other uses.
10110       if (!InVec.hasOneUse())
10111         return SDValue();
10112
10113       // If the bit convert changed the number of elements, it is unsafe
10114       // to examine the mask.
10115       if (BCNumEltsChanged)
10116         return SDValue();
10117
10118       // Select the input vector, guarding against out of range extract vector.
10119       unsigned NumElems = VT.getVectorNumElements();
10120       int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
10121       InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
10122
10123       if (InVec.getOpcode() == ISD::BITCAST) {
10124         // Don't duplicate a load with other uses.
10125         if (!InVec.hasOneUse())
10126           return SDValue();
10127
10128         InVec = InVec.getOperand(0);
10129       }
10130       if (ISD::isNormalLoad(InVec.getNode())) {
10131         LN0 = cast<LoadSDNode>(InVec);
10132         Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
10133         EltNo = DAG.getConstant(Elt, EltNo.getValueType());
10134       }
10135     }
10136
10137     // Make sure we found a non-volatile load and the extractelement is
10138     // the only use.
10139     if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
10140       return SDValue();
10141
10142     // If Idx was -1 above, Elt is going to be -1, so just return undef.
10143     if (Elt == -1)
10144       return DAG.getUNDEF(LVT);
10145
10146     return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0);
10147   }
10148
10149   return SDValue();
10150 }
10151
10152 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
10153 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
10154   // We perform this optimization post type-legalization because
10155   // the type-legalizer often scalarizes integer-promoted vectors.
10156   // Performing this optimization before may create bit-casts which
10157   // will be type-legalized to complex code sequences.
10158   // We perform this optimization only before the operation legalizer because we
10159   // may introduce illegal operations.
10160   if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
10161     return SDValue();
10162
10163   unsigned NumInScalars = N->getNumOperands();
10164   SDLoc dl(N);
10165   EVT VT = N->getValueType(0);
10166
10167   // Check to see if this is a BUILD_VECTOR of a bunch of values
10168   // which come from any_extend or zero_extend nodes. If so, we can create
10169   // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
10170   // optimizations. We do not handle sign-extend because we can't fill the sign
10171   // using shuffles.
10172   EVT SourceType = MVT::Other;
10173   bool AllAnyExt = true;
10174
10175   for (unsigned i = 0; i != NumInScalars; ++i) {
10176     SDValue In = N->getOperand(i);
10177     // Ignore undef inputs.
10178     if (In.getOpcode() == ISD::UNDEF) continue;
10179
10180     bool AnyExt  = In.getOpcode() == ISD::ANY_EXTEND;
10181     bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
10182
10183     // Abort if the element is not an extension.
10184     if (!ZeroExt && !AnyExt) {
10185       SourceType = MVT::Other;
10186       break;
10187     }
10188
10189     // The input is a ZeroExt or AnyExt. Check the original type.
10190     EVT InTy = In.getOperand(0).getValueType();
10191
10192     // Check that all of the widened source types are the same.
10193     if (SourceType == MVT::Other)
10194       // First time.
10195       SourceType = InTy;
10196     else if (InTy != SourceType) {
10197       // Multiple income types. Abort.
10198       SourceType = MVT::Other;
10199       break;
10200     }
10201
10202     // Check if all of the extends are ANY_EXTENDs.
10203     AllAnyExt &= AnyExt;
10204   }
10205
10206   // In order to have valid types, all of the inputs must be extended from the
10207   // same source type and all of the inputs must be any or zero extend.
10208   // Scalar sizes must be a power of two.
10209   EVT OutScalarTy = VT.getScalarType();
10210   bool ValidTypes = SourceType != MVT::Other &&
10211                  isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
10212                  isPowerOf2_32(SourceType.getSizeInBits());
10213
10214   // Create a new simpler BUILD_VECTOR sequence which other optimizations can
10215   // turn into a single shuffle instruction.
10216   if (!ValidTypes)
10217     return SDValue();
10218
10219   bool isLE = TLI.isLittleEndian();
10220   unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
10221   assert(ElemRatio > 1 && "Invalid element size ratio");
10222   SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
10223                                DAG.getConstant(0, SourceType);
10224
10225   unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
10226   SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
10227
10228   // Populate the new build_vector
10229   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
10230     SDValue Cast = N->getOperand(i);
10231     assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
10232             Cast.getOpcode() == ISD::ZERO_EXTEND ||
10233             Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
10234     SDValue In;
10235     if (Cast.getOpcode() == ISD::UNDEF)
10236       In = DAG.getUNDEF(SourceType);
10237     else
10238       In = Cast->getOperand(0);
10239     unsigned Index = isLE ? (i * ElemRatio) :
10240                             (i * ElemRatio + (ElemRatio - 1));
10241
10242     assert(Index < Ops.size() && "Invalid index");
10243     Ops[Index] = In;
10244   }
10245
10246   // The type of the new BUILD_VECTOR node.
10247   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
10248   assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
10249          "Invalid vector size");
10250   // Check if the new vector type is legal.
10251   if (!isTypeLegal(VecVT)) return SDValue();
10252
10253   // Make the new BUILD_VECTOR.
10254   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
10255
10256   // The new BUILD_VECTOR node has the potential to be further optimized.
10257   AddToWorklist(BV.getNode());
10258   // Bitcast to the desired type.
10259   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
10260 }
10261
10262 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
10263   EVT VT = N->getValueType(0);
10264
10265   unsigned NumInScalars = N->getNumOperands();
10266   SDLoc dl(N);
10267
10268   EVT SrcVT = MVT::Other;
10269   unsigned Opcode = ISD::DELETED_NODE;
10270   unsigned NumDefs = 0;
10271
10272   for (unsigned i = 0; i != NumInScalars; ++i) {
10273     SDValue In = N->getOperand(i);
10274     unsigned Opc = In.getOpcode();
10275
10276     if (Opc == ISD::UNDEF)
10277       continue;
10278
10279     // If all scalar values are floats and converted from integers.
10280     if (Opcode == ISD::DELETED_NODE &&
10281         (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
10282       Opcode = Opc;
10283     }
10284
10285     if (Opc != Opcode)
10286       return SDValue();
10287
10288     EVT InVT = In.getOperand(0).getValueType();
10289
10290     // If all scalar values are typed differently, bail out. It's chosen to
10291     // simplify BUILD_VECTOR of integer types.
10292     if (SrcVT == MVT::Other)
10293       SrcVT = InVT;
10294     if (SrcVT != InVT)
10295       return SDValue();
10296     NumDefs++;
10297   }
10298
10299   // If the vector has just one element defined, it's not worth to fold it into
10300   // a vectorized one.
10301   if (NumDefs < 2)
10302     return SDValue();
10303
10304   assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
10305          && "Should only handle conversion from integer to float.");
10306   assert(SrcVT != MVT::Other && "Cannot determine source type!");
10307
10308   EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
10309
10310   if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
10311     return SDValue();
10312
10313   SmallVector<SDValue, 8> Opnds;
10314   for (unsigned i = 0; i != NumInScalars; ++i) {
10315     SDValue In = N->getOperand(i);
10316
10317     if (In.getOpcode() == ISD::UNDEF)
10318       Opnds.push_back(DAG.getUNDEF(SrcVT));
10319     else
10320       Opnds.push_back(In.getOperand(0));
10321   }
10322   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds);
10323   AddToWorklist(BV.getNode());
10324
10325   return DAG.getNode(Opcode, dl, VT, BV);
10326 }
10327
10328 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
10329   unsigned NumInScalars = N->getNumOperands();
10330   SDLoc dl(N);
10331   EVT VT = N->getValueType(0);
10332
10333   // A vector built entirely of undefs is undef.
10334   if (ISD::allOperandsUndef(N))
10335     return DAG.getUNDEF(VT);
10336
10337   SDValue V = reduceBuildVecExtToExtBuildVec(N);
10338   if (V.getNode())
10339     return V;
10340
10341   V = reduceBuildVecConvertToConvertBuildVec(N);
10342   if (V.getNode())
10343     return V;
10344
10345   // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
10346   // operations.  If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
10347   // at most two distinct vectors, turn this into a shuffle node.
10348
10349   // May only combine to shuffle after legalize if shuffle is legal.
10350   if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT))
10351     return SDValue();
10352
10353   SDValue VecIn1, VecIn2;
10354   for (unsigned i = 0; i != NumInScalars; ++i) {
10355     // Ignore undef inputs.
10356     if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
10357
10358     // If this input is something other than a EXTRACT_VECTOR_ELT with a
10359     // constant index, bail out.
10360     if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10361         !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) {
10362       VecIn1 = VecIn2 = SDValue(nullptr, 0);
10363       break;
10364     }
10365
10366     // We allow up to two distinct input vectors.
10367     SDValue ExtractedFromVec = N->getOperand(i).getOperand(0);
10368     if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
10369       continue;
10370
10371     if (!VecIn1.getNode()) {
10372       VecIn1 = ExtractedFromVec;
10373     } else if (!VecIn2.getNode()) {
10374       VecIn2 = ExtractedFromVec;
10375     } else {
10376       // Too many inputs.
10377       VecIn1 = VecIn2 = SDValue(nullptr, 0);
10378       break;
10379     }
10380   }
10381
10382   // If everything is good, we can make a shuffle operation.
10383   if (VecIn1.getNode()) {
10384     SmallVector<int, 8> Mask;
10385     for (unsigned i = 0; i != NumInScalars; ++i) {
10386       if (N->getOperand(i).getOpcode() == ISD::UNDEF) {
10387         Mask.push_back(-1);
10388         continue;
10389       }
10390
10391       // If extracting from the first vector, just use the index directly.
10392       SDValue Extract = N->getOperand(i);
10393       SDValue ExtVal = Extract.getOperand(1);
10394       if (Extract.getOperand(0) == VecIn1) {
10395         unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
10396         if (ExtIndex > VT.getVectorNumElements())
10397           return SDValue();
10398
10399         Mask.push_back(ExtIndex);
10400         continue;
10401       }
10402
10403       // Otherwise, use InIdx + VecSize
10404       unsigned Idx = cast<ConstantSDNode>(ExtVal)->getZExtValue();
10405       Mask.push_back(Idx+NumInScalars);
10406     }
10407
10408     // We can't generate a shuffle node with mismatched input and output types.
10409     // Attempt to transform a single input vector to the correct type.
10410     if ((VT != VecIn1.getValueType())) {
10411       // We don't support shuffeling between TWO values of different types.
10412       if (VecIn2.getNode())
10413         return SDValue();
10414
10415       // We only support widening of vectors which are half the size of the
10416       // output registers. For example XMM->YMM widening on X86 with AVX.
10417       if (VecIn1.getValueType().getSizeInBits()*2 != VT.getSizeInBits())
10418         return SDValue();
10419
10420       // If the input vector type has a different base type to the output
10421       // vector type, bail out.
10422       if (VecIn1.getValueType().getVectorElementType() !=
10423           VT.getVectorElementType())
10424         return SDValue();
10425
10426       // Widen the input vector by adding undef values.
10427       VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10428                            VecIn1, DAG.getUNDEF(VecIn1.getValueType()));
10429     }
10430
10431     // If VecIn2 is unused then change it to undef.
10432     VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
10433
10434     // Check that we were able to transform all incoming values to the same
10435     // type.
10436     if (VecIn2.getValueType() != VecIn1.getValueType() ||
10437         VecIn1.getValueType() != VT)
10438           return SDValue();
10439
10440     // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
10441     if (!isTypeLegal(VT))
10442       return SDValue();
10443
10444     // Return the new VECTOR_SHUFFLE node.
10445     SDValue Ops[2];
10446     Ops[0] = VecIn1;
10447     Ops[1] = VecIn2;
10448     return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
10449   }
10450
10451   return SDValue();
10452 }
10453
10454 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
10455   // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
10456   // EXTRACT_SUBVECTOR operations.  If so, and if the EXTRACT_SUBVECTOR vector
10457   // inputs come from at most two distinct vectors, turn this into a shuffle
10458   // node.
10459
10460   // If we only have one input vector, we don't need to do any concatenation.
10461   if (N->getNumOperands() == 1)
10462     return N->getOperand(0);
10463
10464   // Check if all of the operands are undefs.
10465   EVT VT = N->getValueType(0);
10466   if (ISD::allOperandsUndef(N))
10467     return DAG.getUNDEF(VT);
10468
10469   // Optimize concat_vectors where one of the vectors is undef.
10470   if (N->getNumOperands() == 2 &&
10471       N->getOperand(1)->getOpcode() == ISD::UNDEF) {
10472     SDValue In = N->getOperand(0);
10473     assert(In.getValueType().isVector() && "Must concat vectors");
10474
10475     // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
10476     if (In->getOpcode() == ISD::BITCAST &&
10477         !In->getOperand(0)->getValueType(0).isVector()) {
10478       SDValue Scalar = In->getOperand(0);
10479       EVT SclTy = Scalar->getValueType(0);
10480
10481       if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
10482         return SDValue();
10483
10484       EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
10485                                  VT.getSizeInBits() / SclTy.getSizeInBits());
10486       if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
10487         return SDValue();
10488
10489       SDLoc dl = SDLoc(N);
10490       SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
10491       return DAG.getNode(ISD::BITCAST, dl, VT, Res);
10492     }
10493   }
10494
10495   // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
10496   // -> (BUILD_VECTOR A, B, ..., C, D, ...)
10497   if (N->getNumOperands() == 2 &&
10498       N->getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
10499       N->getOperand(1).getOpcode() == ISD::BUILD_VECTOR) {
10500     EVT VT = N->getValueType(0);
10501     SDValue N0 = N->getOperand(0);
10502     SDValue N1 = N->getOperand(1);
10503     SmallVector<SDValue, 8> Opnds;
10504     unsigned BuildVecNumElts =  N0.getNumOperands();
10505
10506     EVT SclTy0 = N0.getOperand(0)->getValueType(0);
10507     EVT SclTy1 = N1.getOperand(0)->getValueType(0);
10508     if (SclTy0.isFloatingPoint()) {
10509       for (unsigned i = 0; i != BuildVecNumElts; ++i)
10510         Opnds.push_back(N0.getOperand(i));
10511       for (unsigned i = 0; i != BuildVecNumElts; ++i)
10512         Opnds.push_back(N1.getOperand(i));
10513     } else {
10514       // If BUILD_VECTOR are from built from integer, they may have different
10515       // operand types. Get the smaller type and truncate all operands to it.
10516       EVT MinTy = SclTy0.bitsLE(SclTy1) ? SclTy0 : SclTy1;
10517       for (unsigned i = 0; i != BuildVecNumElts; ++i)
10518         Opnds.push_back(DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinTy,
10519                         N0.getOperand(i)));
10520       for (unsigned i = 0; i != BuildVecNumElts; ++i)
10521         Opnds.push_back(DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinTy,
10522                         N1.getOperand(i)));
10523     }
10524
10525     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
10526   }
10527
10528   // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
10529   // nodes often generate nop CONCAT_VECTOR nodes.
10530   // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
10531   // place the incoming vectors at the exact same location.
10532   SDValue SingleSource = SDValue();
10533   unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
10534
10535   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
10536     SDValue Op = N->getOperand(i);
10537
10538     if (Op.getOpcode() == ISD::UNDEF)
10539       continue;
10540
10541     // Check if this is the identity extract:
10542     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
10543       return SDValue();
10544
10545     // Find the single incoming vector for the extract_subvector.
10546     if (SingleSource.getNode()) {
10547       if (Op.getOperand(0) != SingleSource)
10548         return SDValue();
10549     } else {
10550       SingleSource = Op.getOperand(0);
10551
10552       // Check the source type is the same as the type of the result.
10553       // If not, this concat may extend the vector, so we can not
10554       // optimize it away.
10555       if (SingleSource.getValueType() != N->getValueType(0))
10556         return SDValue();
10557     }
10558
10559     unsigned IdentityIndex = i * PartNumElem;
10560     ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
10561     // The extract index must be constant.
10562     if (!CS)
10563       return SDValue();
10564
10565     // Check that we are reading from the identity index.
10566     if (CS->getZExtValue() != IdentityIndex)
10567       return SDValue();
10568   }
10569
10570   if (SingleSource.getNode())
10571     return SingleSource;
10572
10573   return SDValue();
10574 }
10575
10576 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
10577   EVT NVT = N->getValueType(0);
10578   SDValue V = N->getOperand(0);
10579
10580   if (V->getOpcode() == ISD::CONCAT_VECTORS) {
10581     // Combine:
10582     //    (extract_subvec (concat V1, V2, ...), i)
10583     // Into:
10584     //    Vi if possible
10585     // Only operand 0 is checked as 'concat' assumes all inputs of the same
10586     // type.
10587     if (V->getOperand(0).getValueType() != NVT)
10588       return SDValue();
10589     unsigned Idx = dyn_cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
10590     unsigned NumElems = NVT.getVectorNumElements();
10591     assert((Idx % NumElems) == 0 &&
10592            "IDX in concat is not a multiple of the result vector length.");
10593     return V->getOperand(Idx / NumElems);
10594   }
10595
10596   // Skip bitcasting
10597   if (V->getOpcode() == ISD::BITCAST)
10598     V = V.getOperand(0);
10599
10600   if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
10601     SDLoc dl(N);
10602     // Handle only simple case where vector being inserted and vector
10603     // being extracted are of same type, and are half size of larger vectors.
10604     EVT BigVT = V->getOperand(0).getValueType();
10605     EVT SmallVT = V->getOperand(1).getValueType();
10606     if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
10607       return SDValue();
10608
10609     // Only handle cases where both indexes are constants with the same type.
10610     ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
10611     ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
10612
10613     if (InsIdx && ExtIdx &&
10614         InsIdx->getValueType(0).getSizeInBits() <= 64 &&
10615         ExtIdx->getValueType(0).getSizeInBits() <= 64) {
10616       // Combine:
10617       //    (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
10618       // Into:
10619       //    indices are equal or bit offsets are equal => V1
10620       //    otherwise => (extract_subvec V1, ExtIdx)
10621       if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
10622           ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
10623         return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
10624       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
10625                          DAG.getNode(ISD::BITCAST, dl,
10626                                      N->getOperand(0).getValueType(),
10627                                      V->getOperand(0)), N->getOperand(1));
10628     }
10629   }
10630
10631   return SDValue();
10632 }
10633
10634 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat.
10635 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
10636   EVT VT = N->getValueType(0);
10637   unsigned NumElts = VT.getVectorNumElements();
10638
10639   SDValue N0 = N->getOperand(0);
10640   SDValue N1 = N->getOperand(1);
10641   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10642
10643   SmallVector<SDValue, 4> Ops;
10644   EVT ConcatVT = N0.getOperand(0).getValueType();
10645   unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
10646   unsigned NumConcats = NumElts / NumElemsPerConcat;
10647
10648   // Look at every vector that's inserted. We're looking for exact
10649   // subvector-sized copies from a concatenated vector
10650   for (unsigned I = 0; I != NumConcats; ++I) {
10651     // Make sure we're dealing with a copy.
10652     unsigned Begin = I * NumElemsPerConcat;
10653     bool AllUndef = true, NoUndef = true;
10654     for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
10655       if (SVN->getMaskElt(J) >= 0)
10656         AllUndef = false;
10657       else
10658         NoUndef = false;
10659     }
10660
10661     if (NoUndef) {
10662       if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
10663         return SDValue();
10664
10665       for (unsigned J = 1; J != NumElemsPerConcat; ++J)
10666         if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
10667           return SDValue();
10668
10669       unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
10670       if (FirstElt < N0.getNumOperands())
10671         Ops.push_back(N0.getOperand(FirstElt));
10672       else
10673         Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
10674
10675     } else if (AllUndef) {
10676       Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
10677     } else { // Mixed with general masks and undefs, can't do optimization.
10678       return SDValue();
10679     }
10680   }
10681
10682   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
10683 }
10684
10685 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
10686   EVT VT = N->getValueType(0);
10687   unsigned NumElts = VT.getVectorNumElements();
10688
10689   SDValue N0 = N->getOperand(0);
10690   SDValue N1 = N->getOperand(1);
10691
10692   assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
10693
10694   // Canonicalize shuffle undef, undef -> undef
10695   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
10696     return DAG.getUNDEF(VT);
10697
10698   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10699
10700   // Canonicalize shuffle v, v -> v, undef
10701   if (N0 == N1) {
10702     SmallVector<int, 8> NewMask;
10703     for (unsigned i = 0; i != NumElts; ++i) {
10704       int Idx = SVN->getMaskElt(i);
10705       if (Idx >= (int)NumElts) Idx -= NumElts;
10706       NewMask.push_back(Idx);
10707     }
10708     return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
10709                                 &NewMask[0]);
10710   }
10711
10712   // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
10713   if (N0.getOpcode() == ISD::UNDEF) {
10714     SmallVector<int, 8> NewMask;
10715     for (unsigned i = 0; i != NumElts; ++i) {
10716       int Idx = SVN->getMaskElt(i);
10717       if (Idx >= 0) {
10718         if (Idx >= (int)NumElts)
10719           Idx -= NumElts;
10720         else
10721           Idx = -1; // remove reference to lhs
10722       }
10723       NewMask.push_back(Idx);
10724     }
10725     return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
10726                                 &NewMask[0]);
10727   }
10728
10729   // Remove references to rhs if it is undef
10730   if (N1.getOpcode() == ISD::UNDEF) {
10731     bool Changed = false;
10732     SmallVector<int, 8> NewMask;
10733     for (unsigned i = 0; i != NumElts; ++i) {
10734       int Idx = SVN->getMaskElt(i);
10735       if (Idx >= (int)NumElts) {
10736         Idx = -1;
10737         Changed = true;
10738       }
10739       NewMask.push_back(Idx);
10740     }
10741     if (Changed)
10742       return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
10743   }
10744
10745   // If it is a splat, check if the argument vector is another splat or a
10746   // build_vector with all scalar elements the same.
10747   if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
10748     SDNode *V = N0.getNode();
10749
10750     // If this is a bit convert that changes the element type of the vector but
10751     // not the number of vector elements, look through it.  Be careful not to
10752     // look though conversions that change things like v4f32 to v2f64.
10753     if (V->getOpcode() == ISD::BITCAST) {
10754       SDValue ConvInput = V->getOperand(0);
10755       if (ConvInput.getValueType().isVector() &&
10756           ConvInput.getValueType().getVectorNumElements() == NumElts)
10757         V = ConvInput.getNode();
10758     }
10759
10760     if (V->getOpcode() == ISD::BUILD_VECTOR) {
10761       assert(V->getNumOperands() == NumElts &&
10762              "BUILD_VECTOR has wrong number of operands");
10763       SDValue Base;
10764       bool AllSame = true;
10765       for (unsigned i = 0; i != NumElts; ++i) {
10766         if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
10767           Base = V->getOperand(i);
10768           break;
10769         }
10770       }
10771       // Splat of <u, u, u, u>, return <u, u, u, u>
10772       if (!Base.getNode())
10773         return N0;
10774       for (unsigned i = 0; i != NumElts; ++i) {
10775         if (V->getOperand(i) != Base) {
10776           AllSame = false;
10777           break;
10778         }
10779       }
10780       // Splat of <x, x, x, x>, return <x, x, x, x>
10781       if (AllSame)
10782         return N0;
10783     }
10784   }
10785
10786   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
10787       Level < AfterLegalizeVectorOps &&
10788       (N1.getOpcode() == ISD::UNDEF ||
10789       (N1.getOpcode() == ISD::CONCAT_VECTORS &&
10790        N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
10791     SDValue V = partitionShuffleOfConcats(N, DAG);
10792
10793     if (V.getNode())
10794       return V;
10795   }
10796
10797   // If this shuffle node is simply a swizzle of another shuffle node,
10798   // then try to simplify it.
10799   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
10800       N1.getOpcode() == ISD::UNDEF) {
10801
10802     ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
10803
10804     // The incoming shuffle must be of the same type as the result of the
10805     // current shuffle.
10806     assert(OtherSV->getOperand(0).getValueType() == VT &&
10807            "Shuffle types don't match");
10808
10809     SmallVector<int, 4> Mask;
10810     // Compute the combined shuffle mask.
10811     for (unsigned i = 0; i != NumElts; ++i) {
10812       int Idx = SVN->getMaskElt(i);
10813       assert(Idx < (int)NumElts && "Index references undef operand");
10814       // Next, this index comes from the first value, which is the incoming
10815       // shuffle. Adopt the incoming index.
10816       if (Idx >= 0)
10817         Idx = OtherSV->getMaskElt(Idx);
10818       Mask.push_back(Idx);
10819     }
10820
10821     // Check if all indices in Mask are Undef. In case, propagate Undef.
10822     bool isUndefMask = true;
10823     for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
10824       isUndefMask &= Mask[i] < 0;
10825
10826     if (isUndefMask)
10827       return DAG.getUNDEF(VT);
10828     
10829     bool CommuteOperands = false;
10830     if (N0.getOperand(1).getOpcode() != ISD::UNDEF) {
10831       // To be valid, the combine shuffle mask should only reference elements
10832       // from one of the two vectors in input to the inner shufflevector.
10833       bool IsValidMask = true;
10834       for (unsigned i = 0; i != NumElts && IsValidMask; ++i)
10835         // See if the combined mask only reference undefs or elements coming
10836         // from the first shufflevector operand.
10837         IsValidMask = Mask[i] < 0 || (unsigned)Mask[i] < NumElts;
10838
10839       if (!IsValidMask) {
10840         IsValidMask = true;
10841         for (unsigned i = 0; i != NumElts && IsValidMask; ++i)
10842           // Check that all the elements come from the second shuffle operand.
10843           IsValidMask = Mask[i] < 0 || (unsigned)Mask[i] >= NumElts;
10844         CommuteOperands = IsValidMask;
10845       }
10846
10847       // Early exit if the combined shuffle mask is not valid.
10848       if (!IsValidMask)
10849         return SDValue();
10850     }
10851
10852     // See if this pair of shuffles can be safely folded according to either
10853     // of the following rules:
10854     //   shuffle(shuffle(x, y), undef) -> x
10855     //   shuffle(shuffle(x, undef), undef) -> x
10856     //   shuffle(shuffle(x, y), undef) -> y
10857     bool IsIdentityMask = true;
10858     unsigned BaseMaskIndex = CommuteOperands ? NumElts : 0;
10859     for (unsigned i = 0; i != NumElts && IsIdentityMask; ++i) {
10860       // Skip Undefs.
10861       if (Mask[i] < 0)
10862         continue;
10863
10864       // The combined shuffle must map each index to itself.
10865       IsIdentityMask = (unsigned)Mask[i] == i + BaseMaskIndex;
10866     }
10867     
10868     if (IsIdentityMask) {
10869       if (CommuteOperands)
10870         // optimize shuffle(shuffle(x, y), undef) -> y.
10871         return OtherSV->getOperand(1);
10872       
10873       // optimize shuffle(shuffle(x, undef), undef) -> x
10874       // optimize shuffle(shuffle(x, y), undef) -> x
10875       return OtherSV->getOperand(0);
10876     }
10877
10878     // It may still be beneficial to combine the two shuffles if the
10879     // resulting shuffle is legal.
10880     if (TLI.isTypeLegal(VT)) {
10881       if (!CommuteOperands) {
10882         if (TLI.isShuffleMaskLegal(Mask, VT))
10883           // shuffle(shuffle(x, undef, M1), undef, M2) -> shuffle(x, undef, M3).
10884           // shuffle(shuffle(x, y, M1), undef, M2) -> shuffle(x, undef, M3)
10885           return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0), N1,
10886                                       &Mask[0]);
10887       } else {
10888         // Compute the commuted shuffle mask.
10889         for (unsigned i = 0; i != NumElts; ++i) {
10890           int idx = Mask[i];
10891           if (idx < 0)
10892             continue;
10893           else if (idx < (int)NumElts)
10894             Mask[i] = idx + NumElts;
10895           else
10896             Mask[i] = idx - NumElts;
10897         }
10898
10899         if (TLI.isShuffleMaskLegal(Mask, VT))
10900           //   shuffle(shuffle(x, y, M1), undef, M2) -> shuffle(y, undef, M3)
10901           return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(1), N1,
10902                                       &Mask[0]);
10903       }
10904     }
10905   }
10906
10907   // Canonicalize shuffles according to rules:
10908   //  shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
10909   //  shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
10910   //  shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
10911   if (N1.getOpcode() == ISD::VECTOR_SHUFFLE && N0.getOpcode() != ISD::UNDEF &&
10912       N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
10913       TLI.isTypeLegal(VT)) {
10914     // The incoming shuffle must be of the same type as the result of the
10915     // current shuffle.
10916     assert(N1->getOperand(0).getValueType() == VT &&
10917            "Shuffle types don't match");
10918
10919     SDValue SV0 = N1->getOperand(0);
10920     SDValue SV1 = N1->getOperand(1);
10921     bool HasSameOp0 = N0 == SV0;
10922     bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
10923     if (HasSameOp0 || IsSV1Undef || N0 == SV1)
10924       // Commute the operands of this shuffle so that next rule
10925       // will trigger.
10926       return DAG.getCommutedVectorShuffle(*SVN);
10927   }
10928
10929   // Try to fold according to rules:
10930   //   shuffle(shuffle(A, B, M0), B, M1) -> shuffle(A, B, M2)
10931   //   shuffle(shuffle(A, B, M0), A, M1) -> shuffle(A, B, M2)
10932   //   shuffle(shuffle(A, Undef, M0), B, M1) -> shuffle(A, B, M2)
10933   //   shuffle(shuffle(A, Undef, M0), A, M1) -> shuffle(A, Undef, M2)
10934   // Don't try to fold shuffles with illegal type.
10935   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
10936       N1.getOpcode() != ISD::UNDEF && TLI.isTypeLegal(VT)) {
10937     ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
10938
10939     // The incoming shuffle must be of the same type as the result of the
10940     // current shuffle.
10941     assert(OtherSV->getOperand(0).getValueType() == VT &&
10942            "Shuffle types don't match");
10943
10944     SDValue SV0 = OtherSV->getOperand(0);
10945     SDValue SV1 = OtherSV->getOperand(1);
10946     bool HasSameOp0 = N1 == SV0;
10947     bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
10948     if (!HasSameOp0 && !IsSV1Undef && N1 != SV1)
10949       // Early exit.
10950       return SDValue();
10951
10952     SmallVector<int, 4> Mask;
10953     // Compute the combined shuffle mask for a shuffle with SV0 as the first
10954     // operand, and SV1 as the second operand.
10955     for (unsigned i = 0; i != NumElts; ++i) {
10956       int Idx = SVN->getMaskElt(i);
10957       if (Idx < 0) {
10958         // Propagate Undef.
10959         Mask.push_back(Idx);
10960         continue;
10961       }
10962
10963       if (Idx < (int)NumElts) {
10964         Idx = OtherSV->getMaskElt(Idx);
10965         if (IsSV1Undef && Idx >= (int) NumElts)
10966           Idx = -1;  // Propagate Undef.
10967       } else
10968         Idx = HasSameOp0 ? Idx - NumElts : Idx;
10969
10970       Mask.push_back(Idx);
10971     }
10972
10973     // Check if all indices in Mask are Undef. In case, propagate Undef.
10974     bool isUndefMask = true;
10975     for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
10976       isUndefMask &= Mask[i] < 0;
10977
10978     if (isUndefMask)
10979       return DAG.getUNDEF(VT);
10980
10981     // Avoid introducing shuffles with illegal mask.
10982     if (TLI.isShuffleMaskLegal(Mask, VT)) {
10983       if (IsSV1Undef)
10984         //   shuffle(shuffle(A, Undef, M0), B, M1) -> shuffle(A, B, M2)
10985         //   shuffle(shuffle(A, Undef, M0), A, M1) -> shuffle(A, Undef, M2)
10986         return DAG.getVectorShuffle(VT, SDLoc(N), SV0, N1, &Mask[0]);
10987       return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, &Mask[0]);
10988     }
10989   }
10990
10991   return SDValue();
10992 }
10993
10994 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
10995   SDValue N0 = N->getOperand(0);
10996   SDValue N2 = N->getOperand(2);
10997
10998   // If the input vector is a concatenation, and the insert replaces
10999   // one of the halves, we can optimize into a single concat_vectors.
11000   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
11001       N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
11002     APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
11003     EVT VT = N->getValueType(0);
11004
11005     // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
11006     // (concat_vectors Z, Y)
11007     if (InsIdx == 0)
11008       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
11009                          N->getOperand(1), N0.getOperand(1));
11010
11011     // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
11012     // (concat_vectors X, Z)
11013     if (InsIdx == VT.getVectorNumElements()/2)
11014       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
11015                          N0.getOperand(0), N->getOperand(1));
11016   }
11017
11018   return SDValue();
11019 }
11020
11021 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle
11022 /// with the destination vector and a zero vector.
11023 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
11024 ///      vector_shuffle V, Zero, <0, 4, 2, 4>
11025 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
11026   EVT VT = N->getValueType(0);
11027   SDLoc dl(N);
11028   SDValue LHS = N->getOperand(0);
11029   SDValue RHS = N->getOperand(1);
11030   if (N->getOpcode() == ISD::AND) {
11031     if (RHS.getOpcode() == ISD::BITCAST)
11032       RHS = RHS.getOperand(0);
11033     if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
11034       SmallVector<int, 8> Indices;
11035       unsigned NumElts = RHS.getNumOperands();
11036       for (unsigned i = 0; i != NumElts; ++i) {
11037         SDValue Elt = RHS.getOperand(i);
11038         if (!isa<ConstantSDNode>(Elt))
11039           return SDValue();
11040
11041         if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
11042           Indices.push_back(i);
11043         else if (cast<ConstantSDNode>(Elt)->isNullValue())
11044           Indices.push_back(NumElts);
11045         else
11046           return SDValue();
11047       }
11048
11049       // Let's see if the target supports this vector_shuffle.
11050       EVT RVT = RHS.getValueType();
11051       if (!TLI.isVectorClearMaskLegal(Indices, RVT))
11052         return SDValue();
11053
11054       // Return the new VECTOR_SHUFFLE node.
11055       EVT EltVT = RVT.getVectorElementType();
11056       SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
11057                                      DAG.getConstant(0, EltVT));
11058       SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), RVT, ZeroOps);
11059       LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
11060       SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
11061       return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
11062     }
11063   }
11064
11065   return SDValue();
11066 }
11067
11068 /// Visit a binary vector operation, like ADD.
11069 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
11070   assert(N->getValueType(0).isVector() &&
11071          "SimplifyVBinOp only works on vectors!");
11072
11073   SDValue LHS = N->getOperand(0);
11074   SDValue RHS = N->getOperand(1);
11075   SDValue Shuffle = XformToShuffleWithZero(N);
11076   if (Shuffle.getNode()) return Shuffle;
11077
11078   // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
11079   // this operation.
11080   if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
11081       RHS.getOpcode() == ISD::BUILD_VECTOR) {
11082     // Check if both vectors are constants. If not bail out.
11083     if (!(cast<BuildVectorSDNode>(LHS)->isConstant() &&
11084           cast<BuildVectorSDNode>(RHS)->isConstant()))
11085       return SDValue();
11086
11087     SmallVector<SDValue, 8> Ops;
11088     for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
11089       SDValue LHSOp = LHS.getOperand(i);
11090       SDValue RHSOp = RHS.getOperand(i);
11091
11092       // Can't fold divide by zero.
11093       if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
11094           N->getOpcode() == ISD::FDIV) {
11095         if ((RHSOp.getOpcode() == ISD::Constant &&
11096              cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
11097             (RHSOp.getOpcode() == ISD::ConstantFP &&
11098              cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
11099           break;
11100       }
11101
11102       EVT VT = LHSOp.getValueType();
11103       EVT RVT = RHSOp.getValueType();
11104       if (RVT != VT) {
11105         // Integer BUILD_VECTOR operands may have types larger than the element
11106         // size (e.g., when the element type is not legal).  Prior to type
11107         // legalization, the types may not match between the two BUILD_VECTORS.
11108         // Truncate one of the operands to make them match.
11109         if (RVT.getSizeInBits() > VT.getSizeInBits()) {
11110           RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
11111         } else {
11112           LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
11113           VT = RVT;
11114         }
11115       }
11116       SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
11117                                    LHSOp, RHSOp);
11118       if (FoldOp.getOpcode() != ISD::UNDEF &&
11119           FoldOp.getOpcode() != ISD::Constant &&
11120           FoldOp.getOpcode() != ISD::ConstantFP)
11121         break;
11122       Ops.push_back(FoldOp);
11123       AddToWorklist(FoldOp.getNode());
11124     }
11125
11126     if (Ops.size() == LHS.getNumOperands())
11127       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), LHS.getValueType(), Ops);
11128   }
11129
11130   // Type legalization might introduce new shuffles in the DAG.
11131   // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
11132   //   -> (shuffle (VBinOp (A, B)), Undef, Mask).
11133   if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
11134       isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
11135       LHS.getOperand(1).getOpcode() == ISD::UNDEF &&
11136       RHS.getOperand(1).getOpcode() == ISD::UNDEF) {
11137     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
11138     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
11139
11140     if (SVN0->getMask().equals(SVN1->getMask())) {
11141       EVT VT = N->getValueType(0);
11142       SDValue UndefVector = LHS.getOperand(1);
11143       SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
11144                                      LHS.getOperand(0), RHS.getOperand(0));
11145       AddUsersToWorklist(N);
11146       return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
11147                                   &SVN0->getMask()[0]);
11148     }
11149   }
11150
11151   return SDValue();
11152 }
11153
11154 /// Visit a binary vector operation, like FABS/FNEG.
11155 SDValue DAGCombiner::SimplifyVUnaryOp(SDNode *N) {
11156   assert(N->getValueType(0).isVector() &&
11157          "SimplifyVUnaryOp only works on vectors!");
11158
11159   SDValue N0 = N->getOperand(0);
11160
11161   if (N0.getOpcode() != ISD::BUILD_VECTOR)
11162     return SDValue();
11163
11164   // Operand is a BUILD_VECTOR node, see if we can constant fold it.
11165   SmallVector<SDValue, 8> Ops;
11166   for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
11167     SDValue Op = N0.getOperand(i);
11168     if (Op.getOpcode() != ISD::UNDEF &&
11169         Op.getOpcode() != ISD::ConstantFP)
11170       break;
11171     EVT EltVT = Op.getValueType();
11172     SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(N0), EltVT, Op);
11173     if (FoldOp.getOpcode() != ISD::UNDEF &&
11174         FoldOp.getOpcode() != ISD::ConstantFP)
11175       break;
11176     Ops.push_back(FoldOp);
11177     AddToWorklist(FoldOp.getNode());
11178   }
11179
11180   if (Ops.size() != N0.getNumOperands())
11181     return SDValue();
11182
11183   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), N0.getValueType(), Ops);
11184 }
11185
11186 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
11187                                     SDValue N1, SDValue N2){
11188   assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
11189
11190   SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
11191                                  cast<CondCodeSDNode>(N0.getOperand(2))->get());
11192
11193   // If we got a simplified select_cc node back from SimplifySelectCC, then
11194   // break it down into a new SETCC node, and a new SELECT node, and then return
11195   // the SELECT node, since we were called with a SELECT node.
11196   if (SCC.getNode()) {
11197     // Check to see if we got a select_cc back (to turn into setcc/select).
11198     // Otherwise, just return whatever node we got back, like fabs.
11199     if (SCC.getOpcode() == ISD::SELECT_CC) {
11200       SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
11201                                   N0.getValueType(),
11202                                   SCC.getOperand(0), SCC.getOperand(1),
11203                                   SCC.getOperand(4));
11204       AddToWorklist(SETCC.getNode());
11205       return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC,
11206                            SCC.getOperand(2), SCC.getOperand(3));
11207     }
11208
11209     return SCC;
11210   }
11211   return SDValue();
11212 }
11213
11214 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values
11215 /// being selected between, see if we can simplify the select.  Callers of this
11216 /// should assume that TheSelect is deleted if this returns true.  As such, they
11217 /// should return the appropriate thing (e.g. the node) back to the top-level of
11218 /// the DAG combiner loop to avoid it being looked at.
11219 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
11220                                     SDValue RHS) {
11221
11222   // Cannot simplify select with vector condition
11223   if (TheSelect->getOperand(0).getValueType().isVector()) return false;
11224
11225   // If this is a select from two identical things, try to pull the operation
11226   // through the select.
11227   if (LHS.getOpcode() != RHS.getOpcode() ||
11228       !LHS.hasOneUse() || !RHS.hasOneUse())
11229     return false;
11230
11231   // If this is a load and the token chain is identical, replace the select
11232   // of two loads with a load through a select of the address to load from.
11233   // This triggers in things like "select bool X, 10.0, 123.0" after the FP
11234   // constants have been dropped into the constant pool.
11235   if (LHS.getOpcode() == ISD::LOAD) {
11236     LoadSDNode *LLD = cast<LoadSDNode>(LHS);
11237     LoadSDNode *RLD = cast<LoadSDNode>(RHS);
11238
11239     // Token chains must be identical.
11240     if (LHS.getOperand(0) != RHS.getOperand(0) ||
11241         // Do not let this transformation reduce the number of volatile loads.
11242         LLD->isVolatile() || RLD->isVolatile() ||
11243         // If this is an EXTLOAD, the VT's must match.
11244         LLD->getMemoryVT() != RLD->getMemoryVT() ||
11245         // If this is an EXTLOAD, the kind of extension must match.
11246         (LLD->getExtensionType() != RLD->getExtensionType() &&
11247          // The only exception is if one of the extensions is anyext.
11248          LLD->getExtensionType() != ISD::EXTLOAD &&
11249          RLD->getExtensionType() != ISD::EXTLOAD) ||
11250         // FIXME: this discards src value information.  This is
11251         // over-conservative. It would be beneficial to be able to remember
11252         // both potential memory locations.  Since we are discarding
11253         // src value info, don't do the transformation if the memory
11254         // locations are not in the default address space.
11255         LLD->getPointerInfo().getAddrSpace() != 0 ||
11256         RLD->getPointerInfo().getAddrSpace() != 0 ||
11257         !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
11258                                       LLD->getBasePtr().getValueType()))
11259       return false;
11260
11261     // Check that the select condition doesn't reach either load.  If so,
11262     // folding this will induce a cycle into the DAG.  If not, this is safe to
11263     // xform, so create a select of the addresses.
11264     SDValue Addr;
11265     if (TheSelect->getOpcode() == ISD::SELECT) {
11266       SDNode *CondNode = TheSelect->getOperand(0).getNode();
11267       if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
11268           (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
11269         return false;
11270       // The loads must not depend on one another.
11271       if (LLD->isPredecessorOf(RLD) ||
11272           RLD->isPredecessorOf(LLD))
11273         return false;
11274       Addr = DAG.getSelect(SDLoc(TheSelect),
11275                            LLD->getBasePtr().getValueType(),
11276                            TheSelect->getOperand(0), LLD->getBasePtr(),
11277                            RLD->getBasePtr());
11278     } else {  // Otherwise SELECT_CC
11279       SDNode *CondLHS = TheSelect->getOperand(0).getNode();
11280       SDNode *CondRHS = TheSelect->getOperand(1).getNode();
11281
11282       if ((LLD->hasAnyUseOfValue(1) &&
11283            (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
11284           (RLD->hasAnyUseOfValue(1) &&
11285            (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
11286         return false;
11287
11288       Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
11289                          LLD->getBasePtr().getValueType(),
11290                          TheSelect->getOperand(0),
11291                          TheSelect->getOperand(1),
11292                          LLD->getBasePtr(), RLD->getBasePtr(),
11293                          TheSelect->getOperand(4));
11294     }
11295
11296     SDValue Load;
11297     // It is safe to replace the two loads if they have different alignments,
11298     // but the new load must be the minimum (most restrictive) alignment of the
11299     // inputs.
11300     bool isInvariant = LLD->getAlignment() & RLD->getAlignment();
11301     unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment());
11302     if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
11303       Load = DAG.getLoad(TheSelect->getValueType(0),
11304                          SDLoc(TheSelect),
11305                          // FIXME: Discards pointer and AA info.
11306                          LLD->getChain(), Addr, MachinePointerInfo(),
11307                          LLD->isVolatile(), LLD->isNonTemporal(),
11308                          isInvariant, Alignment);
11309     } else {
11310       Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
11311                             RLD->getExtensionType() : LLD->getExtensionType(),
11312                             SDLoc(TheSelect),
11313                             TheSelect->getValueType(0),
11314                             // FIXME: Discards pointer and AA info.
11315                             LLD->getChain(), Addr, MachinePointerInfo(),
11316                             LLD->getMemoryVT(), LLD->isVolatile(),
11317                             LLD->isNonTemporal(), isInvariant, Alignment);
11318     }
11319
11320     // Users of the select now use the result of the load.
11321     CombineTo(TheSelect, Load);
11322
11323     // Users of the old loads now use the new load's chain.  We know the
11324     // old-load value is dead now.
11325     CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
11326     CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
11327     return true;
11328   }
11329
11330   return false;
11331 }
11332
11333 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3
11334 /// where 'cond' is the comparison specified by CC.
11335 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
11336                                       SDValue N2, SDValue N3,
11337                                       ISD::CondCode CC, bool NotExtCompare) {
11338   // (x ? y : y) -> y.
11339   if (N2 == N3) return N2;
11340
11341   EVT VT = N2.getValueType();
11342   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
11343   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
11344   ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
11345
11346   // Determine if the condition we're dealing with is constant
11347   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
11348                               N0, N1, CC, DL, false);
11349   if (SCC.getNode()) AddToWorklist(SCC.getNode());
11350   ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
11351
11352   // fold select_cc true, x, y -> x
11353   if (SCCC && !SCCC->isNullValue())
11354     return N2;
11355   // fold select_cc false, x, y -> y
11356   if (SCCC && SCCC->isNullValue())
11357     return N3;
11358
11359   // Check to see if we can simplify the select into an fabs node
11360   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
11361     // Allow either -0.0 or 0.0
11362     if (CFP->getValueAPF().isZero()) {
11363       // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
11364       if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
11365           N0 == N2 && N3.getOpcode() == ISD::FNEG &&
11366           N2 == N3.getOperand(0))
11367         return DAG.getNode(ISD::FABS, DL, VT, N0);
11368
11369       // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
11370       if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
11371           N0 == N3 && N2.getOpcode() == ISD::FNEG &&
11372           N2.getOperand(0) == N3)
11373         return DAG.getNode(ISD::FABS, DL, VT, N3);
11374     }
11375   }
11376
11377   // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
11378   // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
11379   // in it.  This is a win when the constant is not otherwise available because
11380   // it replaces two constant pool loads with one.  We only do this if the FP
11381   // type is known to be legal, because if it isn't, then we are before legalize
11382   // types an we want the other legalization to happen first (e.g. to avoid
11383   // messing with soft float) and if the ConstantFP is not legal, because if
11384   // it is legal, we may not need to store the FP constant in a constant pool.
11385   if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
11386     if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
11387       if (TLI.isTypeLegal(N2.getValueType()) &&
11388           (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
11389                TargetLowering::Legal &&
11390            !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
11391            !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
11392           // If both constants have multiple uses, then we won't need to do an
11393           // extra load, they are likely around in registers for other users.
11394           (TV->hasOneUse() || FV->hasOneUse())) {
11395         Constant *Elts[] = {
11396           const_cast<ConstantFP*>(FV->getConstantFPValue()),
11397           const_cast<ConstantFP*>(TV->getConstantFPValue())
11398         };
11399         Type *FPTy = Elts[0]->getType();
11400         const DataLayout &TD = *TLI.getDataLayout();
11401
11402         // Create a ConstantArray of the two constants.
11403         Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
11404         SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
11405                                             TD.getPrefTypeAlignment(FPTy));
11406         unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
11407
11408         // Get the offsets to the 0 and 1 element of the array so that we can
11409         // select between them.
11410         SDValue Zero = DAG.getIntPtrConstant(0);
11411         unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
11412         SDValue One = DAG.getIntPtrConstant(EltSize);
11413
11414         SDValue Cond = DAG.getSetCC(DL,
11415                                     getSetCCResultType(N0.getValueType()),
11416                                     N0, N1, CC);
11417         AddToWorklist(Cond.getNode());
11418         SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
11419                                           Cond, One, Zero);
11420         AddToWorklist(CstOffset.getNode());
11421         CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
11422                             CstOffset);
11423         AddToWorklist(CPIdx.getNode());
11424         return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
11425                            MachinePointerInfo::getConstantPool(), false,
11426                            false, false, Alignment);
11427
11428       }
11429     }
11430
11431   // Check to see if we can perform the "gzip trick", transforming
11432   // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
11433   if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
11434       (N1C->isNullValue() ||                         // (a < 0) ? b : 0
11435        (N1C->getAPIntValue() == 1 && N0 == N2))) {   // (a < 1) ? a : 0
11436     EVT XType = N0.getValueType();
11437     EVT AType = N2.getValueType();
11438     if (XType.bitsGE(AType)) {
11439       // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
11440       // single-bit constant.
11441       if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
11442         unsigned ShCtV = N2C->getAPIntValue().logBase2();
11443         ShCtV = XType.getSizeInBits()-ShCtV-1;
11444         SDValue ShCt = DAG.getConstant(ShCtV,
11445                                        getShiftAmountTy(N0.getValueType()));
11446         SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
11447                                     XType, N0, ShCt);
11448         AddToWorklist(Shift.getNode());
11449
11450         if (XType.bitsGT(AType)) {
11451           Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
11452           AddToWorklist(Shift.getNode());
11453         }
11454
11455         return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
11456       }
11457
11458       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
11459                                   XType, N0,
11460                                   DAG.getConstant(XType.getSizeInBits()-1,
11461                                          getShiftAmountTy(N0.getValueType())));
11462       AddToWorklist(Shift.getNode());
11463
11464       if (XType.bitsGT(AType)) {
11465         Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
11466         AddToWorklist(Shift.getNode());
11467       }
11468
11469       return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
11470     }
11471   }
11472
11473   // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
11474   // where y is has a single bit set.
11475   // A plaintext description would be, we can turn the SELECT_CC into an AND
11476   // when the condition can be materialized as an all-ones register.  Any
11477   // single bit-test can be materialized as an all-ones register with
11478   // shift-left and shift-right-arith.
11479   if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
11480       N0->getValueType(0) == VT &&
11481       N1C && N1C->isNullValue() &&
11482       N2C && N2C->isNullValue()) {
11483     SDValue AndLHS = N0->getOperand(0);
11484     ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
11485     if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
11486       // Shift the tested bit over the sign bit.
11487       APInt AndMask = ConstAndRHS->getAPIntValue();
11488       SDValue ShlAmt =
11489         DAG.getConstant(AndMask.countLeadingZeros(),
11490                         getShiftAmountTy(AndLHS.getValueType()));
11491       SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
11492
11493       // Now arithmetic right shift it all the way over, so the result is either
11494       // all-ones, or zero.
11495       SDValue ShrAmt =
11496         DAG.getConstant(AndMask.getBitWidth()-1,
11497                         getShiftAmountTy(Shl.getValueType()));
11498       SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
11499
11500       return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
11501     }
11502   }
11503
11504   // fold select C, 16, 0 -> shl C, 4
11505   if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
11506       TLI.getBooleanContents(N0.getValueType()) ==
11507           TargetLowering::ZeroOrOneBooleanContent) {
11508
11509     // If the caller doesn't want us to simplify this into a zext of a compare,
11510     // don't do it.
11511     if (NotExtCompare && N2C->getAPIntValue() == 1)
11512       return SDValue();
11513
11514     // Get a SetCC of the condition
11515     // NOTE: Don't create a SETCC if it's not legal on this target.
11516     if (!LegalOperations ||
11517         TLI.isOperationLegal(ISD::SETCC,
11518           LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
11519       SDValue Temp, SCC;
11520       // cast from setcc result type to select result type
11521       if (LegalTypes) {
11522         SCC  = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
11523                             N0, N1, CC);
11524         if (N2.getValueType().bitsLT(SCC.getValueType()))
11525           Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
11526                                         N2.getValueType());
11527         else
11528           Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
11529                              N2.getValueType(), SCC);
11530       } else {
11531         SCC  = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
11532         Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
11533                            N2.getValueType(), SCC);
11534       }
11535
11536       AddToWorklist(SCC.getNode());
11537       AddToWorklist(Temp.getNode());
11538
11539       if (N2C->getAPIntValue() == 1)
11540         return Temp;
11541
11542       // shl setcc result by log2 n2c
11543       return DAG.getNode(
11544           ISD::SHL, DL, N2.getValueType(), Temp,
11545           DAG.getConstant(N2C->getAPIntValue().logBase2(),
11546                           getShiftAmountTy(Temp.getValueType())));
11547     }
11548   }
11549
11550   // Check to see if this is the equivalent of setcc
11551   // FIXME: Turn all of these into setcc if setcc if setcc is legal
11552   // otherwise, go ahead with the folds.
11553   if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
11554     EVT XType = N0.getValueType();
11555     if (!LegalOperations ||
11556         TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
11557       SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
11558       if (Res.getValueType() != VT)
11559         Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
11560       return Res;
11561     }
11562
11563     // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
11564     if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
11565         (!LegalOperations ||
11566          TLI.isOperationLegal(ISD::CTLZ, XType))) {
11567       SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
11568       return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
11569                          DAG.getConstant(Log2_32(XType.getSizeInBits()),
11570                                        getShiftAmountTy(Ctlz.getValueType())));
11571     }
11572     // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
11573     if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
11574       SDValue NegN0 = DAG.getNode(ISD::SUB, SDLoc(N0),
11575                                   XType, DAG.getConstant(0, XType), N0);
11576       SDValue NotN0 = DAG.getNOT(SDLoc(N0), N0, XType);
11577       return DAG.getNode(ISD::SRL, DL, XType,
11578                          DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
11579                          DAG.getConstant(XType.getSizeInBits()-1,
11580                                          getShiftAmountTy(XType)));
11581     }
11582     // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
11583     if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
11584       SDValue Sign = DAG.getNode(ISD::SRL, SDLoc(N0), XType, N0,
11585                                  DAG.getConstant(XType.getSizeInBits()-1,
11586                                          getShiftAmountTy(N0.getValueType())));
11587       return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
11588     }
11589   }
11590
11591   // Check to see if this is an integer abs.
11592   // select_cc setg[te] X,  0,  X, -X ->
11593   // select_cc setgt    X, -1,  X, -X ->
11594   // select_cc setl[te] X,  0, -X,  X ->
11595   // select_cc setlt    X,  1, -X,  X ->
11596   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
11597   if (N1C) {
11598     ConstantSDNode *SubC = nullptr;
11599     if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
11600          (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
11601         N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
11602       SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
11603     else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
11604               (N1C->isOne() && CC == ISD::SETLT)) &&
11605              N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
11606       SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
11607
11608     EVT XType = N0.getValueType();
11609     if (SubC && SubC->isNullValue() && XType.isInteger()) {
11610       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), XType,
11611                                   N0,
11612                                   DAG.getConstant(XType.getSizeInBits()-1,
11613                                          getShiftAmountTy(N0.getValueType())));
11614       SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0),
11615                                 XType, N0, Shift);
11616       AddToWorklist(Shift.getNode());
11617       AddToWorklist(Add.getNode());
11618       return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
11619     }
11620   }
11621
11622   return SDValue();
11623 }
11624
11625 /// This is a stub for TargetLowering::SimplifySetCC.
11626 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
11627                                    SDValue N1, ISD::CondCode Cond,
11628                                    SDLoc DL, bool foldBooleans) {
11629   TargetLowering::DAGCombinerInfo
11630     DagCombineInfo(DAG, Level, false, this);
11631   return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
11632 }
11633
11634 /// Given an ISD::SDIV node expressing a divide by constant, return
11635 /// a DAG expression to select that will generate the same value by multiplying
11636 /// by a magic number.  See:
11637 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
11638 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
11639   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
11640   if (!C)
11641     return SDValue();
11642
11643   // Avoid division by zero.
11644   if (!C->getAPIntValue())
11645     return SDValue();
11646
11647   std::vector<SDNode*> Built;
11648   SDValue S =
11649       TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
11650
11651   for (SDNode *N : Built)
11652     AddToWorklist(N);
11653   return S;
11654 }
11655
11656 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a
11657 /// DAG expression that will generate the same value by right shifting.
11658 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
11659   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
11660   if (!C)
11661     return SDValue();
11662
11663   // Avoid division by zero.
11664   if (!C->getAPIntValue())
11665     return SDValue();
11666
11667   std::vector<SDNode *> Built;
11668   SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
11669
11670   for (SDNode *N : Built)
11671     AddToWorklist(N);
11672   return S;
11673 }
11674
11675 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG
11676 /// expression that will generate the same value by multiplying by a magic
11677 /// number. See:
11678 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
11679 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
11680   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
11681   if (!C)
11682     return SDValue();
11683
11684   // Avoid division by zero.
11685   if (!C->getAPIntValue())
11686     return SDValue();
11687
11688   std::vector<SDNode*> Built;
11689   SDValue S =
11690       TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
11691
11692   for (SDNode *N : Built)
11693     AddToWorklist(N);
11694   return S;
11695 }
11696
11697 /// Return true if base is a frame index, which is known not to alias with
11698 /// anything but itself.  Provides base object and offset as results.
11699 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
11700                            const GlobalValue *&GV, const void *&CV) {
11701   // Assume it is a primitive operation.
11702   Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
11703
11704   // If it's an adding a simple constant then integrate the offset.
11705   if (Base.getOpcode() == ISD::ADD) {
11706     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
11707       Base = Base.getOperand(0);
11708       Offset += C->getZExtValue();
11709     }
11710   }
11711
11712   // Return the underlying GlobalValue, and update the Offset.  Return false
11713   // for GlobalAddressSDNode since the same GlobalAddress may be represented
11714   // by multiple nodes with different offsets.
11715   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
11716     GV = G->getGlobal();
11717     Offset += G->getOffset();
11718     return false;
11719   }
11720
11721   // Return the underlying Constant value, and update the Offset.  Return false
11722   // for ConstantSDNodes since the same constant pool entry may be represented
11723   // by multiple nodes with different offsets.
11724   if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
11725     CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
11726                                          : (const void *)C->getConstVal();
11727     Offset += C->getOffset();
11728     return false;
11729   }
11730   // If it's any of the following then it can't alias with anything but itself.
11731   return isa<FrameIndexSDNode>(Base);
11732 }
11733
11734 /// Return true if there is any possibility that the two addresses overlap.
11735 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
11736   // If they are the same then they must be aliases.
11737   if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
11738
11739   // If they are both volatile then they cannot be reordered.
11740   if (Op0->isVolatile() && Op1->isVolatile()) return true;
11741
11742   // Gather base node and offset information.
11743   SDValue Base1, Base2;
11744   int64_t Offset1, Offset2;
11745   const GlobalValue *GV1, *GV2;
11746   const void *CV1, *CV2;
11747   bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
11748                                       Base1, Offset1, GV1, CV1);
11749   bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
11750                                       Base2, Offset2, GV2, CV2);
11751
11752   // If they have a same base address then check to see if they overlap.
11753   if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
11754     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
11755              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
11756
11757   // It is possible for different frame indices to alias each other, mostly
11758   // when tail call optimization reuses return address slots for arguments.
11759   // To catch this case, look up the actual index of frame indices to compute
11760   // the real alias relationship.
11761   if (isFrameIndex1 && isFrameIndex2) {
11762     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11763     Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
11764     Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
11765     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
11766              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
11767   }
11768
11769   // Otherwise, if we know what the bases are, and they aren't identical, then
11770   // we know they cannot alias.
11771   if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
11772     return false;
11773
11774   // If we know required SrcValue1 and SrcValue2 have relatively large alignment
11775   // compared to the size and offset of the access, we may be able to prove they
11776   // do not alias.  This check is conservative for now to catch cases created by
11777   // splitting vector types.
11778   if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
11779       (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
11780       (Op0->getMemoryVT().getSizeInBits() >> 3 ==
11781        Op1->getMemoryVT().getSizeInBits() >> 3) &&
11782       (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) {
11783     int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
11784     int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
11785
11786     // There is no overlap between these relatively aligned accesses of similar
11787     // size, return no alias.
11788     if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
11789         (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
11790       return false;
11791   }
11792
11793   bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0 ? CombinerGlobalAA :
11794     TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
11795 #ifndef NDEBUG
11796   if (CombinerAAOnlyFunc.getNumOccurrences() &&
11797       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
11798     UseAA = false;
11799 #endif
11800   if (UseAA &&
11801       Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
11802     // Use alias analysis information.
11803     int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
11804                                  Op1->getSrcValueOffset());
11805     int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
11806         Op0->getSrcValueOffset() - MinOffset;
11807     int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
11808         Op1->getSrcValueOffset() - MinOffset;
11809     AliasAnalysis::AliasResult AAResult =
11810         AA.alias(AliasAnalysis::Location(Op0->getMemOperand()->getValue(),
11811                                          Overlap1,
11812                                          UseTBAA ? Op0->getAAInfo() : AAMDNodes()),
11813                  AliasAnalysis::Location(Op1->getMemOperand()->getValue(),
11814                                          Overlap2,
11815                                          UseTBAA ? Op1->getAAInfo() : AAMDNodes()));
11816     if (AAResult == AliasAnalysis::NoAlias)
11817       return false;
11818   }
11819
11820   // Otherwise we have to assume they alias.
11821   return true;
11822 }
11823
11824 /// Walk up chain skipping non-aliasing memory nodes,
11825 /// looking for aliasing nodes and adding them to the Aliases vector.
11826 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
11827                                    SmallVectorImpl<SDValue> &Aliases) {
11828   SmallVector<SDValue, 8> Chains;     // List of chains to visit.
11829   SmallPtrSet<SDNode *, 16> Visited;  // Visited node set.
11830
11831   // Get alias information for node.
11832   bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
11833
11834   // Starting off.
11835   Chains.push_back(OriginalChain);
11836   unsigned Depth = 0;
11837
11838   // Look at each chain and determine if it is an alias.  If so, add it to the
11839   // aliases list.  If not, then continue up the chain looking for the next
11840   // candidate.
11841   while (!Chains.empty()) {
11842     SDValue Chain = Chains.back();
11843     Chains.pop_back();
11844
11845     // For TokenFactor nodes, look at each operand and only continue up the
11846     // chain until we find two aliases.  If we've seen two aliases, assume we'll
11847     // find more and revert to original chain since the xform is unlikely to be
11848     // profitable.
11849     //
11850     // FIXME: The depth check could be made to return the last non-aliasing
11851     // chain we found before we hit a tokenfactor rather than the original
11852     // chain.
11853     if (Depth > 6 || Aliases.size() == 2) {
11854       Aliases.clear();
11855       Aliases.push_back(OriginalChain);
11856       return;
11857     }
11858
11859     // Don't bother if we've been before.
11860     if (!Visited.insert(Chain.getNode()))
11861       continue;
11862
11863     switch (Chain.getOpcode()) {
11864     case ISD::EntryToken:
11865       // Entry token is ideal chain operand, but handled in FindBetterChain.
11866       break;
11867
11868     case ISD::LOAD:
11869     case ISD::STORE: {
11870       // Get alias information for Chain.
11871       bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
11872           !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
11873
11874       // If chain is alias then stop here.
11875       if (!(IsLoad && IsOpLoad) &&
11876           isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
11877         Aliases.push_back(Chain);
11878       } else {
11879         // Look further up the chain.
11880         Chains.push_back(Chain.getOperand(0));
11881         ++Depth;
11882       }
11883       break;
11884     }
11885
11886     case ISD::TokenFactor:
11887       // We have to check each of the operands of the token factor for "small"
11888       // token factors, so we queue them up.  Adding the operands to the queue
11889       // (stack) in reverse order maintains the original order and increases the
11890       // likelihood that getNode will find a matching token factor (CSE.)
11891       if (Chain.getNumOperands() > 16) {
11892         Aliases.push_back(Chain);
11893         break;
11894       }
11895       for (unsigned n = Chain.getNumOperands(); n;)
11896         Chains.push_back(Chain.getOperand(--n));
11897       ++Depth;
11898       break;
11899
11900     default:
11901       // For all other instructions we will just have to take what we can get.
11902       Aliases.push_back(Chain);
11903       break;
11904     }
11905   }
11906
11907   // We need to be careful here to also search for aliases through the
11908   // value operand of a store, etc. Consider the following situation:
11909   //   Token1 = ...
11910   //   L1 = load Token1, %52
11911   //   S1 = store Token1, L1, %51
11912   //   L2 = load Token1, %52+8
11913   //   S2 = store Token1, L2, %51+8
11914   //   Token2 = Token(S1, S2)
11915   //   L3 = load Token2, %53
11916   //   S3 = store Token2, L3, %52
11917   //   L4 = load Token2, %53+8
11918   //   S4 = store Token2, L4, %52+8
11919   // If we search for aliases of S3 (which loads address %52), and we look
11920   // only through the chain, then we'll miss the trivial dependence on L1
11921   // (which also loads from %52). We then might change all loads and
11922   // stores to use Token1 as their chain operand, which could result in
11923   // copying %53 into %52 before copying %52 into %51 (which should
11924   // happen first).
11925   //
11926   // The problem is, however, that searching for such data dependencies
11927   // can become expensive, and the cost is not directly related to the
11928   // chain depth. Instead, we'll rule out such configurations here by
11929   // insisting that we've visited all chain users (except for users
11930   // of the original chain, which is not necessary). When doing this,
11931   // we need to look through nodes we don't care about (otherwise, things
11932   // like register copies will interfere with trivial cases).
11933
11934   SmallVector<const SDNode *, 16> Worklist;
11935   for (const SDNode *N : Visited)
11936     if (N != OriginalChain.getNode())
11937       Worklist.push_back(N);
11938
11939   while (!Worklist.empty()) {
11940     const SDNode *M = Worklist.pop_back_val();
11941
11942     // We have already visited M, and want to make sure we've visited any uses
11943     // of M that we care about. For uses that we've not visisted, and don't
11944     // care about, queue them to the worklist.
11945
11946     for (SDNode::use_iterator UI = M->use_begin(),
11947          UIE = M->use_end(); UI != UIE; ++UI)
11948       if (UI.getUse().getValueType() == MVT::Other && Visited.insert(*UI)) {
11949         if (isa<MemIntrinsicSDNode>(*UI) || isa<MemSDNode>(*UI)) {
11950           // We've not visited this use, and we care about it (it could have an
11951           // ordering dependency with the original node).
11952           Aliases.clear();
11953           Aliases.push_back(OriginalChain);
11954           return;
11955         }
11956
11957         // We've not visited this use, but we don't care about it. Mark it as
11958         // visited and enqueue it to the worklist.
11959         Worklist.push_back(*UI);
11960       }
11961   }
11962 }
11963
11964 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain
11965 /// (aliasing node.)
11966 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
11967   SmallVector<SDValue, 8> Aliases;  // Ops for replacing token factor.
11968
11969   // Accumulate all the aliases to this node.
11970   GatherAllAliases(N, OldChain, Aliases);
11971
11972   // If no operands then chain to entry token.
11973   if (Aliases.size() == 0)
11974     return DAG.getEntryNode();
11975
11976   // If a single operand then chain to it.  We don't need to revisit it.
11977   if (Aliases.size() == 1)
11978     return Aliases[0];
11979
11980   // Construct a custom tailored token factor.
11981   return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
11982 }
11983
11984 /// This is the entry point for the file.
11985 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
11986                            CodeGenOpt::Level OptLevel) {
11987   /// This is the main entry point to this class.
11988   DAGCombiner(*this, AA, OptLevel).Run(Level);
11989 }