name change: isPow2DivCheap -> isPow2SDivCheap
[oota-llvm.git] / lib / CodeGen / SelectionDAG / DAGCombiner.cpp
1 //===-- DAGCombiner.cpp - Implement a DAG node combiner -------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This pass combines dag nodes to form fewer, simpler DAG nodes.  It can be run
11 // both before and after the DAG is legalized.
12 //
13 // This pass is not a substitute for the LLVM IR instcombine pass. This pass is
14 // primarily intended to handle simplification opportunities that are implicit
15 // in the LLVM IR and exposed by the various codegen lowering phases.
16 //
17 //===----------------------------------------------------------------------===//
18
19 #include "llvm/CodeGen/SelectionDAG.h"
20 #include "llvm/ADT/SmallPtrSet.h"
21 #include "llvm/ADT/SetVector.h"
22 #include "llvm/ADT/Statistic.h"
23 #include "llvm/Analysis/AliasAnalysis.h"
24 #include "llvm/CodeGen/MachineFrameInfo.h"
25 #include "llvm/CodeGen/MachineFunction.h"
26 #include "llvm/IR/DataLayout.h"
27 #include "llvm/IR/DerivedTypes.h"
28 #include "llvm/IR/Function.h"
29 #include "llvm/IR/LLVMContext.h"
30 #include "llvm/Support/CommandLine.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/Support/ErrorHandling.h"
33 #include "llvm/Support/MathExtras.h"
34 #include "llvm/Support/raw_ostream.h"
35 #include "llvm/Target/TargetLowering.h"
36 #include "llvm/Target/TargetMachine.h"
37 #include "llvm/Target/TargetOptions.h"
38 #include "llvm/Target/TargetRegisterInfo.h"
39 #include "llvm/Target/TargetSubtargetInfo.h"
40 #include <algorithm>
41 using namespace llvm;
42
43 #define DEBUG_TYPE "dagcombine"
44
45 STATISTIC(NodesCombined   , "Number of dag nodes combined");
46 STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created");
47 STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created");
48 STATISTIC(OpsNarrowed     , "Number of load/op/store narrowed");
49 STATISTIC(LdStFP2Int      , "Number of fp load/store pairs transformed to int");
50 STATISTIC(SlicedLoads, "Number of load sliced");
51
52 namespace {
53   static cl::opt<bool>
54     CombinerAA("combiner-alias-analysis", cl::Hidden,
55                cl::desc("Enable DAG combiner alias-analysis heuristics"));
56
57   static cl::opt<bool>
58     CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
59                cl::desc("Enable DAG combiner's use of IR alias analysis"));
60
61   static cl::opt<bool>
62     UseTBAA("combiner-use-tbaa", cl::Hidden, cl::init(true),
63                cl::desc("Enable DAG combiner's use of TBAA"));
64
65 #ifndef NDEBUG
66   static cl::opt<std::string>
67     CombinerAAOnlyFunc("combiner-aa-only-func", cl::Hidden,
68                cl::desc("Only use DAG-combiner alias analysis in this"
69                         " function"));
70 #endif
71
72   /// Hidden option to stress test load slicing, i.e., when this option
73   /// is enabled, load slicing bypasses most of its profitability guards.
74   static cl::opt<bool>
75   StressLoadSlicing("combiner-stress-load-slicing", cl::Hidden,
76                     cl::desc("Bypass the profitability model of load "
77                              "slicing"),
78                     cl::init(false));
79
80 //------------------------------ DAGCombiner ---------------------------------//
81
82   class DAGCombiner {
83     SelectionDAG &DAG;
84     const TargetLowering &TLI;
85     CombineLevel Level;
86     CodeGenOpt::Level OptLevel;
87     bool LegalOperations;
88     bool LegalTypes;
89     bool ForCodeSize;
90
91     /// \brief Worklist of all of the nodes that need to be simplified.
92     ///
93     /// This must behave as a stack -- new nodes to process are pushed onto the
94     /// back and when processing we pop off of the back.
95     ///
96     /// The worklist will not contain duplicates but may contain null entries
97     /// due to nodes being deleted from the underlying DAG.
98     SmallVector<SDNode *, 64> Worklist;
99
100     /// \brief Mapping from an SDNode to its position on the worklist.
101     ///
102     /// This is used to find and remove nodes from the worklist (by nulling
103     /// them) when they are deleted from the underlying DAG. It relies on
104     /// stable indices of nodes within the worklist.
105     DenseMap<SDNode *, unsigned> WorklistMap;
106
107     /// \brief Set of nodes which have been combined (at least once).
108     ///
109     /// This is used to allow us to reliably add any operands of a DAG node
110     /// which have not yet been combined to the worklist.
111     SmallPtrSet<SDNode *, 64> CombinedNodes;
112
113     // AA - Used for DAG load/store alias analysis.
114     AliasAnalysis &AA;
115
116     /// AddUsersToWorklist - When an instruction is simplified, add all users of
117     /// the instruction to the work lists because they might get more simplified
118     /// now.
119     ///
120     void AddUsersToWorklist(SDNode *N) {
121       for (SDNode *Node : N->uses())
122         AddToWorklist(Node);
123     }
124
125     /// visit - call the node-specific routine that knows how to fold each
126     /// particular type of node.
127     SDValue visit(SDNode *N);
128
129   public:
130     /// AddToWorklist - Add to the work list making sure its instance is at the
131     /// back (next to be processed.)
132     void AddToWorklist(SDNode *N) {
133       // Skip handle nodes as they can't usefully be combined and confuse the
134       // zero-use deletion strategy.
135       if (N->getOpcode() == ISD::HANDLENODE)
136         return;
137
138       if (WorklistMap.insert(std::make_pair(N, Worklist.size())).second)
139         Worklist.push_back(N);
140     }
141
142     /// removeFromWorklist - remove all instances of N from the worklist.
143     ///
144     void removeFromWorklist(SDNode *N) {
145       CombinedNodes.erase(N);
146
147       auto It = WorklistMap.find(N);
148       if (It == WorklistMap.end())
149         return; // Not in the worklist.
150
151       // Null out the entry rather than erasing it to avoid a linear operation.
152       Worklist[It->second] = nullptr;
153       WorklistMap.erase(It);
154     }
155
156     void deleteAndRecombine(SDNode *N);
157     bool recursivelyDeleteUnusedNodes(SDNode *N);
158
159     SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
160                       bool AddTo = true);
161
162     SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
163       return CombineTo(N, &Res, 1, AddTo);
164     }
165
166     SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
167                       bool AddTo = true) {
168       SDValue To[] = { Res0, Res1 };
169       return CombineTo(N, To, 2, AddTo);
170     }
171
172     void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
173
174   private:
175
176     /// SimplifyDemandedBits - Check the specified integer node value to see if
177     /// it can be simplified or if things it uses can be simplified by bit
178     /// propagation.  If so, return true.
179     bool SimplifyDemandedBits(SDValue Op) {
180       unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits();
181       APInt Demanded = APInt::getAllOnesValue(BitWidth);
182       return SimplifyDemandedBits(Op, Demanded);
183     }
184
185     bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded);
186
187     bool CombineToPreIndexedLoadStore(SDNode *N);
188     bool CombineToPostIndexedLoadStore(SDNode *N);
189     bool SliceUpLoad(SDNode *N);
190
191     /// \brief Replace an ISD::EXTRACT_VECTOR_ELT of a load with a narrowed
192     ///   load.
193     ///
194     /// \param EVE ISD::EXTRACT_VECTOR_ELT to be replaced.
195     /// \param InVecVT type of the input vector to EVE with bitcasts resolved.
196     /// \param EltNo index of the vector element to load.
197     /// \param OriginalLoad load that EVE came from to be replaced.
198     /// \returns EVE on success SDValue() on failure.
199     SDValue ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
200         SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad);
201     void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
202     SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
203     SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
204     SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
205     SDValue PromoteIntBinOp(SDValue Op);
206     SDValue PromoteIntShiftOp(SDValue Op);
207     SDValue PromoteExtend(SDValue Op);
208     bool PromoteLoad(SDValue Op);
209
210     void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
211                          SDValue Trunc, SDValue ExtLoad, SDLoc DL,
212                          ISD::NodeType ExtType);
213
214     /// combine - call the node-specific routine that knows how to fold each
215     /// particular type of node. If that doesn't do anything, try the
216     /// target-specific DAG combines.
217     SDValue combine(SDNode *N);
218
219     // Visitation implementation - Implement dag node combining for different
220     // node types.  The semantics are as follows:
221     // Return Value:
222     //   SDValue.getNode() == 0 - No change was made
223     //   SDValue.getNode() == N - N was replaced, is dead and has been handled.
224     //   otherwise              - N should be replaced by the returned Operand.
225     //
226     SDValue visitTokenFactor(SDNode *N);
227     SDValue visitMERGE_VALUES(SDNode *N);
228     SDValue visitADD(SDNode *N);
229     SDValue visitSUB(SDNode *N);
230     SDValue visitADDC(SDNode *N);
231     SDValue visitSUBC(SDNode *N);
232     SDValue visitADDE(SDNode *N);
233     SDValue visitSUBE(SDNode *N);
234     SDValue visitMUL(SDNode *N);
235     SDValue visitSDIV(SDNode *N);
236     SDValue visitUDIV(SDNode *N);
237     SDValue visitSREM(SDNode *N);
238     SDValue visitUREM(SDNode *N);
239     SDValue visitMULHU(SDNode *N);
240     SDValue visitMULHS(SDNode *N);
241     SDValue visitSMUL_LOHI(SDNode *N);
242     SDValue visitUMUL_LOHI(SDNode *N);
243     SDValue visitSMULO(SDNode *N);
244     SDValue visitUMULO(SDNode *N);
245     SDValue visitSDIVREM(SDNode *N);
246     SDValue visitUDIVREM(SDNode *N);
247     SDValue visitAND(SDNode *N);
248     SDValue visitOR(SDNode *N);
249     SDValue visitXOR(SDNode *N);
250     SDValue SimplifyVBinOp(SDNode *N);
251     SDValue SimplifyVUnaryOp(SDNode *N);
252     SDValue visitSHL(SDNode *N);
253     SDValue visitSRA(SDNode *N);
254     SDValue visitSRL(SDNode *N);
255     SDValue visitRotate(SDNode *N);
256     SDValue visitCTLZ(SDNode *N);
257     SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
258     SDValue visitCTTZ(SDNode *N);
259     SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
260     SDValue visitCTPOP(SDNode *N);
261     SDValue visitSELECT(SDNode *N);
262     SDValue visitVSELECT(SDNode *N);
263     SDValue visitSELECT_CC(SDNode *N);
264     SDValue visitSETCC(SDNode *N);
265     SDValue visitSIGN_EXTEND(SDNode *N);
266     SDValue visitZERO_EXTEND(SDNode *N);
267     SDValue visitANY_EXTEND(SDNode *N);
268     SDValue visitSIGN_EXTEND_INREG(SDNode *N);
269     SDValue visitTRUNCATE(SDNode *N);
270     SDValue visitBITCAST(SDNode *N);
271     SDValue visitBUILD_PAIR(SDNode *N);
272     SDValue visitFADD(SDNode *N);
273     SDValue visitFSUB(SDNode *N);
274     SDValue visitFMUL(SDNode *N);
275     SDValue visitFMA(SDNode *N);
276     SDValue visitFDIV(SDNode *N);
277     SDValue visitFREM(SDNode *N);
278     SDValue visitFCOPYSIGN(SDNode *N);
279     SDValue visitSINT_TO_FP(SDNode *N);
280     SDValue visitUINT_TO_FP(SDNode *N);
281     SDValue visitFP_TO_SINT(SDNode *N);
282     SDValue visitFP_TO_UINT(SDNode *N);
283     SDValue visitFP_ROUND(SDNode *N);
284     SDValue visitFP_ROUND_INREG(SDNode *N);
285     SDValue visitFP_EXTEND(SDNode *N);
286     SDValue visitFNEG(SDNode *N);
287     SDValue visitFABS(SDNode *N);
288     SDValue visitFCEIL(SDNode *N);
289     SDValue visitFTRUNC(SDNode *N);
290     SDValue visitFFLOOR(SDNode *N);
291     SDValue visitBRCOND(SDNode *N);
292     SDValue visitBR_CC(SDNode *N);
293     SDValue visitLOAD(SDNode *N);
294     SDValue visitSTORE(SDNode *N);
295     SDValue visitINSERT_VECTOR_ELT(SDNode *N);
296     SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
297     SDValue visitBUILD_VECTOR(SDNode *N);
298     SDValue visitCONCAT_VECTORS(SDNode *N);
299     SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
300     SDValue visitVECTOR_SHUFFLE(SDNode *N);
301     SDValue visitINSERT_SUBVECTOR(SDNode *N);
302
303     SDValue XformToShuffleWithZero(SDNode *N);
304     SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS);
305
306     SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt);
307
308     bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
309     SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
310     SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2);
311     SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2,
312                              SDValue N3, ISD::CondCode CC,
313                              bool NotExtCompare = false);
314     SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
315                           SDLoc DL, bool foldBooleans = true);
316
317     bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
318                            SDValue &CC) const;
319     bool isOneUseSetCC(SDValue N) const;
320
321     SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
322                                          unsigned HiOp);
323     SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
324     SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
325     SDValue BuildSDIV(SDNode *N);
326     SDValue BuildSDIVPow2(SDNode *N);
327     SDValue BuildUDIV(SDNode *N);
328     SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
329                                bool DemandHighBits = true);
330     SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
331     SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
332                               SDValue InnerPos, SDValue InnerNeg,
333                               unsigned PosOpcode, unsigned NegOpcode,
334                               SDLoc DL);
335     SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL);
336     SDValue ReduceLoadWidth(SDNode *N);
337     SDValue ReduceLoadOpStoreWidth(SDNode *N);
338     SDValue TransformFPLoadStorePair(SDNode *N);
339     SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
340     SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
341
342     SDValue GetDemandedBits(SDValue V, const APInt &Mask);
343
344     /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
345     /// looking for aliasing nodes and adding them to the Aliases vector.
346     void GatherAllAliases(SDNode *N, SDValue OriginalChain,
347                           SmallVectorImpl<SDValue> &Aliases);
348
349     /// isAlias - Return true if there is any possibility that the two addresses
350     /// overlap.
351     bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const;
352
353     /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes,
354     /// looking for a better 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     /// Run - 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     /// getShiftAmountTy - Returns a type large enough to hold any valid
388     /// shift amount - before type 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     /// isTypeLegal - This method returns true if we are running before type
398     /// legalization or 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     /// getSetCCResultType - Convenience wrapper around
405     /// TargetLowering::getSetCCResultType
406     EVT getSetCCResultType(EVT VT) const {
407       return TLI.getSetCCResultType(*DAG.getContext(), VT);
408     }
409   };
410 }
411
412
413 namespace {
414 /// WorklistRemover - This class is a DAGUpdateListener that removes any deleted
415 /// nodes from the worklist.
416 class WorklistRemover : public SelectionDAG::DAGUpdateListener {
417   DAGCombiner &DC;
418 public:
419   explicit WorklistRemover(DAGCombiner &dc)
420     : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
421
422   void NodeDeleted(SDNode *N, SDNode *E) override {
423     DC.removeFromWorklist(N);
424   }
425 };
426 }
427
428 //===----------------------------------------------------------------------===//
429 //  TargetLowering::DAGCombinerInfo implementation
430 //===----------------------------------------------------------------------===//
431
432 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
433   ((DAGCombiner*)DC)->AddToWorklist(N);
434 }
435
436 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
437   ((DAGCombiner*)DC)->removeFromWorklist(N);
438 }
439
440 SDValue TargetLowering::DAGCombinerInfo::
441 CombineTo(SDNode *N, const std::vector<SDValue> &To, bool AddTo) {
442   return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
443 }
444
445 SDValue TargetLowering::DAGCombinerInfo::
446 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
447   return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
448 }
449
450
451 SDValue TargetLowering::DAGCombinerInfo::
452 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
453   return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
454 }
455
456 void TargetLowering::DAGCombinerInfo::
457 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
458   return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
459 }
460
461 //===----------------------------------------------------------------------===//
462 // Helper Functions
463 //===----------------------------------------------------------------------===//
464
465 void DAGCombiner::deleteAndRecombine(SDNode *N) {
466   removeFromWorklist(N);
467
468   // If the operands of this node are only used by the node, they will now be
469   // dead. Make sure to re-visit them and recursively delete dead nodes.
470   for (const SDValue &Op : N->ops())
471     if (Op->hasOneUse())
472       AddToWorklist(Op.getNode());
473
474   DAG.DeleteNode(N);
475 }
476
477 /// isNegatibleForFree - Return 1 if we can compute the negated form of the
478 /// specified expression for the same cost as the expression itself, or 2 if we
479 /// can compute the negated form more cheaply than the expression itself.
480 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
481                                const TargetLowering &TLI,
482                                const TargetOptions *Options,
483                                unsigned Depth = 0) {
484   // fneg is removable even if it has multiple uses.
485   if (Op.getOpcode() == ISD::FNEG) return 2;
486
487   // Don't allow anything with multiple uses.
488   if (!Op.hasOneUse()) return 0;
489
490   // Don't recurse exponentially.
491   if (Depth > 6) return 0;
492
493   switch (Op.getOpcode()) {
494   default: return false;
495   case ISD::ConstantFP:
496     // Don't invert constant FP values after legalize.  The negated constant
497     // isn't necessarily legal.
498     return LegalOperations ? 0 : 1;
499   case ISD::FADD:
500     // FIXME: determine better conditions for this xform.
501     if (!Options->UnsafeFPMath) return 0;
502
503     // After operation legalization, it might not be legal to create new FSUBs.
504     if (LegalOperations &&
505         !TLI.isOperationLegalOrCustom(ISD::FSUB,  Op.getValueType()))
506       return 0;
507
508     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
509     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
510                                     Options, Depth + 1))
511       return V;
512     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
513     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
514                               Depth + 1);
515   case ISD::FSUB:
516     // We can't turn -(A-B) into B-A when we honor signed zeros.
517     if (!Options->UnsafeFPMath) return 0;
518
519     // fold (fneg (fsub A, B)) -> (fsub B, A)
520     return 1;
521
522   case ISD::FMUL:
523   case ISD::FDIV:
524     if (Options->HonorSignDependentRoundingFPMath()) return 0;
525
526     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
527     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
528                                     Options, Depth + 1))
529       return V;
530
531     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
532                               Depth + 1);
533
534   case ISD::FP_EXTEND:
535   case ISD::FP_ROUND:
536   case ISD::FSIN:
537     return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
538                               Depth + 1);
539   }
540 }
541
542 /// GetNegatedExpression - If isNegatibleForFree returns true, this function
543 /// returns the newly negated expression.
544 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
545                                     bool LegalOperations, unsigned Depth = 0) {
546   // fneg is removable even if it has multiple uses.
547   if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
548
549   // Don't allow anything with multiple uses.
550   assert(Op.hasOneUse() && "Unknown reuse!");
551
552   assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
553   switch (Op.getOpcode()) {
554   default: llvm_unreachable("Unknown code");
555   case ISD::ConstantFP: {
556     APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
557     V.changeSign();
558     return DAG.getConstantFP(V, Op.getValueType());
559   }
560   case ISD::FADD:
561     // FIXME: determine better conditions for this xform.
562     assert(DAG.getTarget().Options.UnsafeFPMath);
563
564     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
565     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
566                            DAG.getTargetLoweringInfo(),
567                            &DAG.getTarget().Options, Depth+1))
568       return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
569                          GetNegatedExpression(Op.getOperand(0), DAG,
570                                               LegalOperations, Depth+1),
571                          Op.getOperand(1));
572     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
573     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
574                        GetNegatedExpression(Op.getOperand(1), DAG,
575                                             LegalOperations, Depth+1),
576                        Op.getOperand(0));
577   case ISD::FSUB:
578     // We can't turn -(A-B) into B-A when we honor signed zeros.
579     assert(DAG.getTarget().Options.UnsafeFPMath);
580
581     // fold (fneg (fsub 0, B)) -> B
582     if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
583       if (N0CFP->getValueAPF().isZero())
584         return Op.getOperand(1);
585
586     // fold (fneg (fsub A, B)) -> (fsub B, A)
587     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
588                        Op.getOperand(1), Op.getOperand(0));
589
590   case ISD::FMUL:
591   case ISD::FDIV:
592     assert(!DAG.getTarget().Options.HonorSignDependentRoundingFPMath());
593
594     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
595     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
596                            DAG.getTargetLoweringInfo(),
597                            &DAG.getTarget().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 // isSetCCEquivalent - 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 // isOneUseSetCC - Return true if this is a SetCC-equivalent operation with only
648 // one use.  If this is true, it allows the users to invert the operation for
649 // free when 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 /// isConstantSplatVector - 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     // BuildVectors can truncate their operands. Ignore that case here.
715     // FIXME: We blindly ignore splats which include undef which is overly
716     // pessimistic.
717     if (CN && UndefElements.none() &&
718         CN->getValueType(0) == N.getValueType().getScalarType())
719       return CN;
720   }
721
722   return nullptr;
723 }
724
725 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
726                                     SDValue N0, SDValue N1) {
727   EVT VT = N0.getValueType();
728   if (N0.getOpcode() == Opc) {
729     if (SDNode *L = isConstantBuildVectorOrConstantInt(N0.getOperand(1))) {
730       if (SDNode *R = isConstantBuildVectorOrConstantInt(N1)) {
731         // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
732         SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, L, R);
733         if (!OpNode.getNode())
734           return SDValue();
735         return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
736       }
737       if (N0.hasOneUse()) {
738         // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
739         // use
740         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
741         if (!OpNode.getNode())
742           return SDValue();
743         AddToWorklist(OpNode.getNode());
744         return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
745       }
746     }
747   }
748
749   if (N1.getOpcode() == Opc) {
750     if (SDNode *R = isConstantBuildVectorOrConstantInt(N1.getOperand(1))) {
751       if (SDNode *L = isConstantBuildVectorOrConstantInt(N0)) {
752         // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
753         SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, R, L);
754         if (!OpNode.getNode())
755           return SDValue();
756         return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
757       }
758       if (N1.hasOneUse()) {
759         // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one
760         // use
761         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0);
762         if (!OpNode.getNode())
763           return SDValue();
764         AddToWorklist(OpNode.getNode());
765         return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
766       }
767     }
768   }
769
770   return SDValue();
771 }
772
773 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
774                                bool AddTo) {
775   assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
776   ++NodesCombined;
777   DEBUG(dbgs() << "\nReplacing.1 ";
778         N->dump(&DAG);
779         dbgs() << "\nWith: ";
780         To[0].getNode()->dump(&DAG);
781         dbgs() << " and " << NumTo-1 << " other values\n";
782         for (unsigned i = 0, e = NumTo; i != e; ++i)
783           assert((!To[i].getNode() ||
784                   N->getValueType(i) == To[i].getValueType()) &&
785                  "Cannot combine value to value of different type!"));
786   WorklistRemover DeadNodes(*this);
787   DAG.ReplaceAllUsesWith(N, To);
788   if (AddTo) {
789     // Push the new nodes and any users onto the worklist
790     for (unsigned i = 0, e = NumTo; i != e; ++i) {
791       if (To[i].getNode()) {
792         AddToWorklist(To[i].getNode());
793         AddUsersToWorklist(To[i].getNode());
794       }
795     }
796   }
797
798   // Finally, if the node is now dead, remove it from the graph.  The node
799   // may not be dead if the replacement process recursively simplified to
800   // something else needing this node.
801   if (N->use_empty())
802     deleteAndRecombine(N);
803   return SDValue(N, 0);
804 }
805
806 void DAGCombiner::
807 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
808   // Replace all uses.  If any nodes become isomorphic to other nodes and
809   // are deleted, make sure to remove them from our worklist.
810   WorklistRemover DeadNodes(*this);
811   DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
812
813   // Push the new node and any (possibly new) users onto the worklist.
814   AddToWorklist(TLO.New.getNode());
815   AddUsersToWorklist(TLO.New.getNode());
816
817   // Finally, if the node is now dead, remove it from the graph.  The node
818   // may not be dead if the replacement process recursively simplified to
819   // something else needing this node.
820   if (TLO.Old.getNode()->use_empty())
821     deleteAndRecombine(TLO.Old.getNode());
822 }
823
824 /// SimplifyDemandedBits - Check the specified integer node value to see if
825 /// it can be simplified or if things it uses can be simplified by bit
826 /// propagation.  If so, return true.
827 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
828   TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
829   APInt KnownZero, KnownOne;
830   if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
831     return false;
832
833   // Revisit the node.
834   AddToWorklist(Op.getNode());
835
836   // Replace the old value with the new one.
837   ++NodesCombined;
838   DEBUG(dbgs() << "\nReplacing.2 ";
839         TLO.Old.getNode()->dump(&DAG);
840         dbgs() << "\nWith: ";
841         TLO.New.getNode()->dump(&DAG);
842         dbgs() << '\n');
843
844   CommitTargetLoweringOpt(TLO);
845   return true;
846 }
847
848 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
849   SDLoc dl(Load);
850   EVT VT = Load->getValueType(0);
851   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
852
853   DEBUG(dbgs() << "\nReplacing.9 ";
854         Load->dump(&DAG);
855         dbgs() << "\nWith: ";
856         Trunc.getNode()->dump(&DAG);
857         dbgs() << '\n');
858   WorklistRemover DeadNodes(*this);
859   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
860   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
861   deleteAndRecombine(Load);
862   AddToWorklist(Trunc.getNode());
863 }
864
865 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
866   Replace = false;
867   SDLoc dl(Op);
868   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
869     EVT MemVT = LD->getMemoryVT();
870     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
871       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
872                                                   : ISD::EXTLOAD)
873       : LD->getExtensionType();
874     Replace = true;
875     return DAG.getExtLoad(ExtType, dl, PVT,
876                           LD->getChain(), LD->getBasePtr(),
877                           MemVT, LD->getMemOperand());
878   }
879
880   unsigned Opc = Op.getOpcode();
881   switch (Opc) {
882   default: break;
883   case ISD::AssertSext:
884     return DAG.getNode(ISD::AssertSext, dl, PVT,
885                        SExtPromoteOperand(Op.getOperand(0), PVT),
886                        Op.getOperand(1));
887   case ISD::AssertZext:
888     return DAG.getNode(ISD::AssertZext, dl, PVT,
889                        ZExtPromoteOperand(Op.getOperand(0), PVT),
890                        Op.getOperand(1));
891   case ISD::Constant: {
892     unsigned ExtOpc =
893       Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
894     return DAG.getNode(ExtOpc, dl, PVT, Op);
895   }
896   }
897
898   if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
899     return SDValue();
900   return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
901 }
902
903 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
904   if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
905     return SDValue();
906   EVT OldVT = Op.getValueType();
907   SDLoc dl(Op);
908   bool Replace = false;
909   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
910   if (!NewOp.getNode())
911     return SDValue();
912   AddToWorklist(NewOp.getNode());
913
914   if (Replace)
915     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
916   return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
917                      DAG.getValueType(OldVT));
918 }
919
920 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
921   EVT OldVT = Op.getValueType();
922   SDLoc dl(Op);
923   bool Replace = false;
924   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
925   if (!NewOp.getNode())
926     return SDValue();
927   AddToWorklist(NewOp.getNode());
928
929   if (Replace)
930     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
931   return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
932 }
933
934 /// PromoteIntBinOp - Promote the specified integer binary operation if the
935 /// target indicates it is beneficial. e.g. On x86, it's usually better to
936 /// promote i16 operations to i32 since i16 instructions are longer.
937 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
938   if (!LegalOperations)
939     return SDValue();
940
941   EVT VT = Op.getValueType();
942   if (VT.isVector() || !VT.isInteger())
943     return SDValue();
944
945   // If operation type is 'undesirable', e.g. i16 on x86, consider
946   // promoting it.
947   unsigned Opc = Op.getOpcode();
948   if (TLI.isTypeDesirableForOp(Opc, VT))
949     return SDValue();
950
951   EVT PVT = VT;
952   // Consult target whether it is a good idea to promote this operation and
953   // what's the right type to promote it to.
954   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
955     assert(PVT != VT && "Don't know what type to promote to!");
956
957     bool Replace0 = false;
958     SDValue N0 = Op.getOperand(0);
959     SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
960     if (!NN0.getNode())
961       return SDValue();
962
963     bool Replace1 = false;
964     SDValue N1 = Op.getOperand(1);
965     SDValue NN1;
966     if (N0 == N1)
967       NN1 = NN0;
968     else {
969       NN1 = PromoteOperand(N1, PVT, Replace1);
970       if (!NN1.getNode())
971         return SDValue();
972     }
973
974     AddToWorklist(NN0.getNode());
975     if (NN1.getNode())
976       AddToWorklist(NN1.getNode());
977
978     if (Replace0)
979       ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
980     if (Replace1)
981       ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
982
983     DEBUG(dbgs() << "\nPromoting ";
984           Op.getNode()->dump(&DAG));
985     SDLoc dl(Op);
986     return DAG.getNode(ISD::TRUNCATE, dl, VT,
987                        DAG.getNode(Opc, dl, PVT, NN0, NN1));
988   }
989   return SDValue();
990 }
991
992 /// PromoteIntShiftOp - Promote the specified integer shift operation if the
993 /// target indicates it is beneficial. e.g. On x86, it's usually better to
994 /// promote i16 operations to i32 since i16 instructions are longer.
995 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
996   if (!LegalOperations)
997     return SDValue();
998
999   EVT VT = Op.getValueType();
1000   if (VT.isVector() || !VT.isInteger())
1001     return SDValue();
1002
1003   // If operation type is 'undesirable', e.g. i16 on x86, consider
1004   // promoting it.
1005   unsigned Opc = Op.getOpcode();
1006   if (TLI.isTypeDesirableForOp(Opc, VT))
1007     return SDValue();
1008
1009   EVT PVT = VT;
1010   // Consult target whether it is a good idea to promote this operation and
1011   // what's the right type to promote it to.
1012   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1013     assert(PVT != VT && "Don't know what type to promote to!");
1014
1015     bool Replace = false;
1016     SDValue N0 = Op.getOperand(0);
1017     if (Opc == ISD::SRA)
1018       N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
1019     else if (Opc == ISD::SRL)
1020       N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
1021     else
1022       N0 = PromoteOperand(N0, PVT, Replace);
1023     if (!N0.getNode())
1024       return SDValue();
1025
1026     AddToWorklist(N0.getNode());
1027     if (Replace)
1028       ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
1029
1030     DEBUG(dbgs() << "\nPromoting ";
1031           Op.getNode()->dump(&DAG));
1032     SDLoc dl(Op);
1033     return DAG.getNode(ISD::TRUNCATE, dl, VT,
1034                        DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
1035   }
1036   return SDValue();
1037 }
1038
1039 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
1040   if (!LegalOperations)
1041     return SDValue();
1042
1043   EVT VT = Op.getValueType();
1044   if (VT.isVector() || !VT.isInteger())
1045     return SDValue();
1046
1047   // If operation type is 'undesirable', e.g. i16 on x86, consider
1048   // promoting it.
1049   unsigned Opc = Op.getOpcode();
1050   if (TLI.isTypeDesirableForOp(Opc, VT))
1051     return SDValue();
1052
1053   EVT PVT = VT;
1054   // Consult target whether it is a good idea to promote this operation and
1055   // what's the right type to promote it to.
1056   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1057     assert(PVT != VT && "Don't know what type to promote to!");
1058     // fold (aext (aext x)) -> (aext x)
1059     // fold (aext (zext x)) -> (zext x)
1060     // fold (aext (sext x)) -> (sext x)
1061     DEBUG(dbgs() << "\nPromoting ";
1062           Op.getNode()->dump(&DAG));
1063     return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1064   }
1065   return SDValue();
1066 }
1067
1068 bool DAGCombiner::PromoteLoad(SDValue Op) {
1069   if (!LegalOperations)
1070     return false;
1071
1072   EVT VT = Op.getValueType();
1073   if (VT.isVector() || !VT.isInteger())
1074     return false;
1075
1076   // If operation type is 'undesirable', e.g. i16 on x86, consider
1077   // promoting it.
1078   unsigned Opc = Op.getOpcode();
1079   if (TLI.isTypeDesirableForOp(Opc, VT))
1080     return false;
1081
1082   EVT PVT = VT;
1083   // Consult target whether it is a good idea to promote this operation and
1084   // what's the right type to promote it to.
1085   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1086     assert(PVT != VT && "Don't know what type to promote to!");
1087
1088     SDLoc dl(Op);
1089     SDNode *N = Op.getNode();
1090     LoadSDNode *LD = cast<LoadSDNode>(N);
1091     EVT MemVT = LD->getMemoryVT();
1092     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1093       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
1094                                                   : ISD::EXTLOAD)
1095       : LD->getExtensionType();
1096     SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
1097                                    LD->getChain(), LD->getBasePtr(),
1098                                    MemVT, LD->getMemOperand());
1099     SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
1100
1101     DEBUG(dbgs() << "\nPromoting ";
1102           N->dump(&DAG);
1103           dbgs() << "\nTo: ";
1104           Result.getNode()->dump(&DAG);
1105           dbgs() << '\n');
1106     WorklistRemover DeadNodes(*this);
1107     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1108     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1109     deleteAndRecombine(N);
1110     AddToWorklist(Result.getNode());
1111     return true;
1112   }
1113   return false;
1114 }
1115
1116 /// \brief Recursively delete a node which has no uses and any operands for
1117 /// which it is the only use.
1118 ///
1119 /// Note that this both deletes the nodes and removes them from the worklist.
1120 /// It also adds any nodes who have had a user deleted to the worklist as they
1121 /// may now have only one use and subject to other combines.
1122 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) {
1123   if (!N->use_empty())
1124     return false;
1125
1126   SmallSetVector<SDNode *, 16> Nodes;
1127   Nodes.insert(N);
1128   do {
1129     N = Nodes.pop_back_val();
1130     if (!N)
1131       continue;
1132
1133     if (N->use_empty()) {
1134       for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1135         Nodes.insert(N->getOperand(i).getNode());
1136
1137       removeFromWorklist(N);
1138       DAG.DeleteNode(N);
1139     } else {
1140       AddToWorklist(N);
1141     }
1142   } while (!Nodes.empty());
1143   return true;
1144 }
1145
1146 //===----------------------------------------------------------------------===//
1147 //  Main DAG Combiner implementation
1148 //===----------------------------------------------------------------------===//
1149
1150 void DAGCombiner::Run(CombineLevel AtLevel) {
1151   // set the instance variables, so that the various visit routines may use it.
1152   Level = AtLevel;
1153   LegalOperations = Level >= AfterLegalizeVectorOps;
1154   LegalTypes = Level >= AfterLegalizeTypes;
1155
1156   // Add all the dag nodes to the worklist.
1157   for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
1158        E = DAG.allnodes_end(); I != E; ++I)
1159     AddToWorklist(I);
1160
1161   // Create a dummy node (which is not added to allnodes), that adds a reference
1162   // to the root node, preventing it from being deleted, and tracking any
1163   // changes of the root.
1164   HandleSDNode Dummy(DAG.getRoot());
1165
1166   // while the worklist isn't empty, find a node and
1167   // try and combine it.
1168   while (!WorklistMap.empty()) {
1169     SDNode *N;
1170     // The Worklist holds the SDNodes in order, but it may contain null entries.
1171     do {
1172       N = Worklist.pop_back_val();
1173     } while (!N);
1174
1175     bool GoodWorklistEntry = WorklistMap.erase(N);
1176     (void)GoodWorklistEntry;
1177     assert(GoodWorklistEntry &&
1178            "Found a worklist entry without a corresponding map entry!");
1179
1180     // If N has no uses, it is dead.  Make sure to revisit all N's operands once
1181     // N is deleted from the DAG, since they too may now be dead or may have a
1182     // reduced number of uses, allowing other xforms.
1183     if (recursivelyDeleteUnusedNodes(N))
1184       continue;
1185
1186     WorklistRemover DeadNodes(*this);
1187
1188     // If this combine is running after legalizing the DAG, re-legalize any
1189     // nodes pulled off the worklist.
1190     if (Level == AfterLegalizeDAG) {
1191       SmallSetVector<SDNode *, 16> UpdatedNodes;
1192       bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes);
1193
1194       for (SDNode *LN : UpdatedNodes) {
1195         AddToWorklist(LN);
1196         AddUsersToWorklist(LN);
1197       }
1198       if (!NIsValid)
1199         continue;
1200     }
1201
1202     DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG));
1203
1204     // Add any operands of the new node which have not yet been combined to the
1205     // worklist as well. Because the worklist uniques things already, this
1206     // won't repeatedly process the same operand.
1207     CombinedNodes.insert(N);
1208     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1209       if (!CombinedNodes.count(N->getOperand(i).getNode()))
1210         AddToWorklist(N->getOperand(i).getNode());
1211
1212     SDValue RV = combine(N);
1213
1214     if (!RV.getNode())
1215       continue;
1216
1217     ++NodesCombined;
1218
1219     // If we get back the same node we passed in, rather than a new node or
1220     // zero, we know that the node must have defined multiple values and
1221     // CombineTo was used.  Since CombineTo takes care of the worklist
1222     // mechanics for us, we have no work to do in this case.
1223     if (RV.getNode() == N)
1224       continue;
1225
1226     assert(N->getOpcode() != ISD::DELETED_NODE &&
1227            RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1228            "Node was deleted but visit returned new node!");
1229
1230     DEBUG(dbgs() << " ... into: ";
1231           RV.getNode()->dump(&DAG));
1232
1233     // Transfer debug value.
1234     DAG.TransferDbgValues(SDValue(N, 0), RV);
1235     if (N->getNumValues() == RV.getNode()->getNumValues())
1236       DAG.ReplaceAllUsesWith(N, RV.getNode());
1237     else {
1238       assert(N->getValueType(0) == RV.getValueType() &&
1239              N->getNumValues() == 1 && "Type mismatch");
1240       SDValue OpV = RV;
1241       DAG.ReplaceAllUsesWith(N, &OpV);
1242     }
1243
1244     // Push the new node and any users onto the worklist
1245     AddToWorklist(RV.getNode());
1246     AddUsersToWorklist(RV.getNode());
1247
1248     // Finally, if the node is now dead, remove it from the graph.  The node
1249     // may not be dead if the replacement process recursively simplified to
1250     // something else needing this node. This will also take care of adding any
1251     // operands which have lost a user to the worklist.
1252     recursivelyDeleteUnusedNodes(N);
1253   }
1254
1255   // If the root changed (e.g. it was a dead load, update the root).
1256   DAG.setRoot(Dummy.getValue());
1257   DAG.RemoveDeadNodes();
1258 }
1259
1260 SDValue DAGCombiner::visit(SDNode *N) {
1261   switch (N->getOpcode()) {
1262   default: break;
1263   case ISD::TokenFactor:        return visitTokenFactor(N);
1264   case ISD::MERGE_VALUES:       return visitMERGE_VALUES(N);
1265   case ISD::ADD:                return visitADD(N);
1266   case ISD::SUB:                return visitSUB(N);
1267   case ISD::ADDC:               return visitADDC(N);
1268   case ISD::SUBC:               return visitSUBC(N);
1269   case ISD::ADDE:               return visitADDE(N);
1270   case ISD::SUBE:               return visitSUBE(N);
1271   case ISD::MUL:                return visitMUL(N);
1272   case ISD::SDIV:               return visitSDIV(N);
1273   case ISD::UDIV:               return visitUDIV(N);
1274   case ISD::SREM:               return visitSREM(N);
1275   case ISD::UREM:               return visitUREM(N);
1276   case ISD::MULHU:              return visitMULHU(N);
1277   case ISD::MULHS:              return visitMULHS(N);
1278   case ISD::SMUL_LOHI:          return visitSMUL_LOHI(N);
1279   case ISD::UMUL_LOHI:          return visitUMUL_LOHI(N);
1280   case ISD::SMULO:              return visitSMULO(N);
1281   case ISD::UMULO:              return visitUMULO(N);
1282   case ISD::SDIVREM:            return visitSDIVREM(N);
1283   case ISD::UDIVREM:            return visitUDIVREM(N);
1284   case ISD::AND:                return visitAND(N);
1285   case ISD::OR:                 return visitOR(N);
1286   case ISD::XOR:                return visitXOR(N);
1287   case ISD::SHL:                return visitSHL(N);
1288   case ISD::SRA:                return visitSRA(N);
1289   case ISD::SRL:                return visitSRL(N);
1290   case ISD::ROTR:
1291   case ISD::ROTL:               return visitRotate(N);
1292   case ISD::CTLZ:               return visitCTLZ(N);
1293   case ISD::CTLZ_ZERO_UNDEF:    return visitCTLZ_ZERO_UNDEF(N);
1294   case ISD::CTTZ:               return visitCTTZ(N);
1295   case ISD::CTTZ_ZERO_UNDEF:    return visitCTTZ_ZERO_UNDEF(N);
1296   case ISD::CTPOP:              return visitCTPOP(N);
1297   case ISD::SELECT:             return visitSELECT(N);
1298   case ISD::VSELECT:            return visitVSELECT(N);
1299   case ISD::SELECT_CC:          return visitSELECT_CC(N);
1300   case ISD::SETCC:              return visitSETCC(N);
1301   case ISD::SIGN_EXTEND:        return visitSIGN_EXTEND(N);
1302   case ISD::ZERO_EXTEND:        return visitZERO_EXTEND(N);
1303   case ISD::ANY_EXTEND:         return visitANY_EXTEND(N);
1304   case ISD::SIGN_EXTEND_INREG:  return visitSIGN_EXTEND_INREG(N);
1305   case ISD::TRUNCATE:           return visitTRUNCATE(N);
1306   case ISD::BITCAST:            return visitBITCAST(N);
1307   case ISD::BUILD_PAIR:         return visitBUILD_PAIR(N);
1308   case ISD::FADD:               return visitFADD(N);
1309   case ISD::FSUB:               return visitFSUB(N);
1310   case ISD::FMUL:               return visitFMUL(N);
1311   case ISD::FMA:                return visitFMA(N);
1312   case ISD::FDIV:               return visitFDIV(N);
1313   case ISD::FREM:               return visitFREM(N);
1314   case ISD::FCOPYSIGN:          return visitFCOPYSIGN(N);
1315   case ISD::SINT_TO_FP:         return visitSINT_TO_FP(N);
1316   case ISD::UINT_TO_FP:         return visitUINT_TO_FP(N);
1317   case ISD::FP_TO_SINT:         return visitFP_TO_SINT(N);
1318   case ISD::FP_TO_UINT:         return visitFP_TO_UINT(N);
1319   case ISD::FP_ROUND:           return visitFP_ROUND(N);
1320   case ISD::FP_ROUND_INREG:     return visitFP_ROUND_INREG(N);
1321   case ISD::FP_EXTEND:          return visitFP_EXTEND(N);
1322   case ISD::FNEG:               return visitFNEG(N);
1323   case ISD::FABS:               return visitFABS(N);
1324   case ISD::FFLOOR:             return visitFFLOOR(N);
1325   case ISD::FCEIL:              return visitFCEIL(N);
1326   case ISD::FTRUNC:             return visitFTRUNC(N);
1327   case ISD::BRCOND:             return visitBRCOND(N);
1328   case ISD::BR_CC:              return visitBR_CC(N);
1329   case ISD::LOAD:               return visitLOAD(N);
1330   case ISD::STORE:              return visitSTORE(N);
1331   case ISD::INSERT_VECTOR_ELT:  return visitINSERT_VECTOR_ELT(N);
1332   case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1333   case ISD::BUILD_VECTOR:       return visitBUILD_VECTOR(N);
1334   case ISD::CONCAT_VECTORS:     return visitCONCAT_VECTORS(N);
1335   case ISD::EXTRACT_SUBVECTOR:  return visitEXTRACT_SUBVECTOR(N);
1336   case ISD::VECTOR_SHUFFLE:     return visitVECTOR_SHUFFLE(N);
1337   case ISD::INSERT_SUBVECTOR:   return visitINSERT_SUBVECTOR(N);
1338   }
1339   return SDValue();
1340 }
1341
1342 SDValue DAGCombiner::combine(SDNode *N) {
1343   SDValue RV = visit(N);
1344
1345   // If nothing happened, try a target-specific DAG combine.
1346   if (!RV.getNode()) {
1347     assert(N->getOpcode() != ISD::DELETED_NODE &&
1348            "Node was deleted but visit returned NULL!");
1349
1350     if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1351         TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1352
1353       // Expose the DAG combiner to the target combiner impls.
1354       TargetLowering::DAGCombinerInfo
1355         DagCombineInfo(DAG, Level, false, this);
1356
1357       RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1358     }
1359   }
1360
1361   // If nothing happened still, try promoting the operation.
1362   if (!RV.getNode()) {
1363     switch (N->getOpcode()) {
1364     default: break;
1365     case ISD::ADD:
1366     case ISD::SUB:
1367     case ISD::MUL:
1368     case ISD::AND:
1369     case ISD::OR:
1370     case ISD::XOR:
1371       RV = PromoteIntBinOp(SDValue(N, 0));
1372       break;
1373     case ISD::SHL:
1374     case ISD::SRA:
1375     case ISD::SRL:
1376       RV = PromoteIntShiftOp(SDValue(N, 0));
1377       break;
1378     case ISD::SIGN_EXTEND:
1379     case ISD::ZERO_EXTEND:
1380     case ISD::ANY_EXTEND:
1381       RV = PromoteExtend(SDValue(N, 0));
1382       break;
1383     case ISD::LOAD:
1384       if (PromoteLoad(SDValue(N, 0)))
1385         RV = SDValue(N, 0);
1386       break;
1387     }
1388   }
1389
1390   // If N is a commutative binary node, try commuting it to enable more
1391   // sdisel CSE.
1392   if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1393       N->getNumValues() == 1) {
1394     SDValue N0 = N->getOperand(0);
1395     SDValue N1 = N->getOperand(1);
1396
1397     // Constant operands are canonicalized to RHS.
1398     if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1399       SDValue Ops[] = {N1, N0};
1400       SDNode *CSENode;
1401       if (const BinaryWithFlagsSDNode *BinNode =
1402               dyn_cast<BinaryWithFlagsSDNode>(N)) {
1403         CSENode = DAG.getNodeIfExists(
1404             N->getOpcode(), N->getVTList(), Ops, BinNode->hasNoUnsignedWrap(),
1405             BinNode->hasNoSignedWrap(), BinNode->isExact());
1406       } else {
1407         CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops);
1408       }
1409       if (CSENode)
1410         return SDValue(CSENode, 0);
1411     }
1412   }
1413
1414   return RV;
1415 }
1416
1417 /// getInputChainForNode - Given a node, return its input chain if it has one,
1418 /// otherwise return a null sd operand.
1419 static SDValue getInputChainForNode(SDNode *N) {
1420   if (unsigned NumOps = N->getNumOperands()) {
1421     if (N->getOperand(0).getValueType() == MVT::Other)
1422       return N->getOperand(0);
1423     if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1424       return N->getOperand(NumOps-1);
1425     for (unsigned i = 1; i < NumOps-1; ++i)
1426       if (N->getOperand(i).getValueType() == MVT::Other)
1427         return N->getOperand(i);
1428   }
1429   return SDValue();
1430 }
1431
1432 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1433   // If N has two operands, where one has an input chain equal to the other,
1434   // the 'other' chain is redundant.
1435   if (N->getNumOperands() == 2) {
1436     if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1437       return N->getOperand(0);
1438     if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1439       return N->getOperand(1);
1440   }
1441
1442   SmallVector<SDNode *, 8> TFs;     // List of token factors to visit.
1443   SmallVector<SDValue, 8> Ops;    // Ops for replacing token factor.
1444   SmallPtrSet<SDNode*, 16> SeenOps;
1445   bool Changed = false;             // If we should replace this token factor.
1446
1447   // Start out with this token factor.
1448   TFs.push_back(N);
1449
1450   // Iterate through token factors.  The TFs grows when new token factors are
1451   // encountered.
1452   for (unsigned i = 0; i < TFs.size(); ++i) {
1453     SDNode *TF = TFs[i];
1454
1455     // Check each of the operands.
1456     for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
1457       SDValue Op = TF->getOperand(i);
1458
1459       switch (Op.getOpcode()) {
1460       case ISD::EntryToken:
1461         // Entry tokens don't need to be added to the list. They are
1462         // rededundant.
1463         Changed = true;
1464         break;
1465
1466       case ISD::TokenFactor:
1467         if (Op.hasOneUse() &&
1468             std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1469           // Queue up for processing.
1470           TFs.push_back(Op.getNode());
1471           // Clean up in case the token factor is removed.
1472           AddToWorklist(Op.getNode());
1473           Changed = true;
1474           break;
1475         }
1476         // Fall thru
1477
1478       default:
1479         // Only add if it isn't already in the list.
1480         if (SeenOps.insert(Op.getNode()))
1481           Ops.push_back(Op);
1482         else
1483           Changed = true;
1484         break;
1485       }
1486     }
1487   }
1488
1489   SDValue Result;
1490
1491   // If we've change things around then replace token factor.
1492   if (Changed) {
1493     if (Ops.empty()) {
1494       // The entry token is the only possible outcome.
1495       Result = DAG.getEntryNode();
1496     } else {
1497       // New and improved token factor.
1498       Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
1499     }
1500
1501     // Don't add users to work list.
1502     return CombineTo(N, Result, false);
1503   }
1504
1505   return Result;
1506 }
1507
1508 /// MERGE_VALUES can always be eliminated.
1509 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1510   WorklistRemover DeadNodes(*this);
1511   // Replacing results may cause a different MERGE_VALUES to suddenly
1512   // be CSE'd with N, and carry its uses with it. Iterate until no
1513   // uses remain, to ensure that the node can be safely deleted.
1514   // First add the users of this node to the work list so that they
1515   // can be tried again once they have new operands.
1516   AddUsersToWorklist(N);
1517   do {
1518     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1519       DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1520   } while (!N->use_empty());
1521   deleteAndRecombine(N);
1522   return SDValue(N, 0);   // Return N so it doesn't get rechecked!
1523 }
1524
1525 static
1526 SDValue combineShlAddConstant(SDLoc DL, SDValue N0, SDValue N1,
1527                               SelectionDAG &DAG) {
1528   EVT VT = N0.getValueType();
1529   SDValue N00 = N0.getOperand(0);
1530   SDValue N01 = N0.getOperand(1);
1531   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N01);
1532
1533   if (N01C && N00.getOpcode() == ISD::ADD && N00.getNode()->hasOneUse() &&
1534       isa<ConstantSDNode>(N00.getOperand(1))) {
1535     // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1536     N0 = DAG.getNode(ISD::ADD, SDLoc(N0), VT,
1537                      DAG.getNode(ISD::SHL, SDLoc(N00), VT,
1538                                  N00.getOperand(0), N01),
1539                      DAG.getNode(ISD::SHL, SDLoc(N01), VT,
1540                                  N00.getOperand(1), N01));
1541     return DAG.getNode(ISD::ADD, DL, VT, N0, N1);
1542   }
1543
1544   return SDValue();
1545 }
1546
1547 SDValue DAGCombiner::visitADD(SDNode *N) {
1548   SDValue N0 = N->getOperand(0);
1549   SDValue N1 = N->getOperand(1);
1550   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1551   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1552   EVT VT = N0.getValueType();
1553
1554   // fold vector ops
1555   if (VT.isVector()) {
1556     SDValue FoldedVOp = SimplifyVBinOp(N);
1557     if (FoldedVOp.getNode()) return FoldedVOp;
1558
1559     // fold (add x, 0) -> x, vector edition
1560     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1561       return N0;
1562     if (ISD::isBuildVectorAllZeros(N0.getNode()))
1563       return N1;
1564   }
1565
1566   // fold (add x, undef) -> undef
1567   if (N0.getOpcode() == ISD::UNDEF)
1568     return N0;
1569   if (N1.getOpcode() == ISD::UNDEF)
1570     return N1;
1571   // fold (add c1, c2) -> c1+c2
1572   if (N0C && N1C)
1573     return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C);
1574   // canonicalize constant to RHS
1575   if (N0C && !N1C)
1576     return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
1577   // fold (add x, 0) -> x
1578   if (N1C && N1C->isNullValue())
1579     return N0;
1580   // fold (add Sym, c) -> Sym+c
1581   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1582     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1583         GA->getOpcode() == ISD::GlobalAddress)
1584       return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1585                                   GA->getOffset() +
1586                                     (uint64_t)N1C->getSExtValue());
1587   // fold ((c1-A)+c2) -> (c1+c2)-A
1588   if (N1C && N0.getOpcode() == ISD::SUB)
1589     if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
1590       return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1591                          DAG.getConstant(N1C->getAPIntValue()+
1592                                          N0C->getAPIntValue(), VT),
1593                          N0.getOperand(1));
1594   // reassociate add
1595   SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1);
1596   if (RADD.getNode())
1597     return RADD;
1598   // fold ((0-A) + B) -> B-A
1599   if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
1600       cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
1601     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
1602   // fold (A + (0-B)) -> A-B
1603   if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1604       cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
1605     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
1606   // fold (A+(B-A)) -> B
1607   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1608     return N1.getOperand(0);
1609   // fold ((B-A)+A) -> B
1610   if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1611     return N0.getOperand(0);
1612   // fold (A+(B-(A+C))) to (B-C)
1613   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1614       N0 == N1.getOperand(1).getOperand(0))
1615     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1616                        N1.getOperand(1).getOperand(1));
1617   // fold (A+(B-(C+A))) to (B-C)
1618   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1619       N0 == N1.getOperand(1).getOperand(1))
1620     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1621                        N1.getOperand(1).getOperand(0));
1622   // fold (A+((B-A)+or-C)) to (B+or-C)
1623   if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1624       N1.getOperand(0).getOpcode() == ISD::SUB &&
1625       N0 == N1.getOperand(0).getOperand(1))
1626     return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
1627                        N1.getOperand(0).getOperand(0), N1.getOperand(1));
1628
1629   // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1630   if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1631     SDValue N00 = N0.getOperand(0);
1632     SDValue N01 = N0.getOperand(1);
1633     SDValue N10 = N1.getOperand(0);
1634     SDValue N11 = N1.getOperand(1);
1635
1636     if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1637       return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1638                          DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1639                          DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1640   }
1641
1642   if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1643     return SDValue(N, 0);
1644
1645   // fold (a+b) -> (a|b) iff a and b share no bits.
1646   if (VT.isInteger() && !VT.isVector()) {
1647     APInt LHSZero, LHSOne;
1648     APInt RHSZero, RHSOne;
1649     DAG.computeKnownBits(N0, LHSZero, LHSOne);
1650
1651     if (LHSZero.getBoolValue()) {
1652       DAG.computeKnownBits(N1, RHSZero, RHSOne);
1653
1654       // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1655       // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1656       if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){
1657         if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT))
1658           return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1659       }
1660     }
1661   }
1662
1663   // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1664   if (N0.getOpcode() == ISD::SHL && N0.getNode()->hasOneUse()) {
1665     SDValue Result = combineShlAddConstant(SDLoc(N), N0, N1, DAG);
1666     if (Result.getNode()) return Result;
1667   }
1668   if (N1.getOpcode() == ISD::SHL && N1.getNode()->hasOneUse()) {
1669     SDValue Result = combineShlAddConstant(SDLoc(N), N1, N0, DAG);
1670     if (Result.getNode()) return Result;
1671   }
1672
1673   // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1674   if (N1.getOpcode() == ISD::SHL &&
1675       N1.getOperand(0).getOpcode() == ISD::SUB)
1676     if (ConstantSDNode *C =
1677           dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
1678       if (C->getAPIntValue() == 0)
1679         return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1680                            DAG.getNode(ISD::SHL, SDLoc(N), VT,
1681                                        N1.getOperand(0).getOperand(1),
1682                                        N1.getOperand(1)));
1683   if (N0.getOpcode() == ISD::SHL &&
1684       N0.getOperand(0).getOpcode() == ISD::SUB)
1685     if (ConstantSDNode *C =
1686           dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
1687       if (C->getAPIntValue() == 0)
1688         return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1689                            DAG.getNode(ISD::SHL, SDLoc(N), VT,
1690                                        N0.getOperand(0).getOperand(1),
1691                                        N0.getOperand(1)));
1692
1693   if (N1.getOpcode() == ISD::AND) {
1694     SDValue AndOp0 = N1.getOperand(0);
1695     ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1));
1696     unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1697     unsigned DestBits = VT.getScalarType().getSizeInBits();
1698
1699     // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1700     // and similar xforms where the inner op is either ~0 or 0.
1701     if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) {
1702       SDLoc DL(N);
1703       return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1704     }
1705   }
1706
1707   // add (sext i1), X -> sub X, (zext i1)
1708   if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1709       N0.getOperand(0).getValueType() == MVT::i1 &&
1710       !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1711     SDLoc DL(N);
1712     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1713     return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1714   }
1715
1716   return SDValue();
1717 }
1718
1719 SDValue DAGCombiner::visitADDC(SDNode *N) {
1720   SDValue N0 = N->getOperand(0);
1721   SDValue N1 = N->getOperand(1);
1722   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1723   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1724   EVT VT = N0.getValueType();
1725
1726   // If the flag result is dead, turn this into an ADD.
1727   if (!N->hasAnyUseOfValue(1))
1728     return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1729                      DAG.getNode(ISD::CARRY_FALSE,
1730                                  SDLoc(N), MVT::Glue));
1731
1732   // canonicalize constant to RHS.
1733   if (N0C && !N1C)
1734     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1735
1736   // fold (addc x, 0) -> x + no carry out
1737   if (N1C && N1C->isNullValue())
1738     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1739                                         SDLoc(N), MVT::Glue));
1740
1741   // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1742   APInt LHSZero, LHSOne;
1743   APInt RHSZero, RHSOne;
1744   DAG.computeKnownBits(N0, LHSZero, LHSOne);
1745
1746   if (LHSZero.getBoolValue()) {
1747     DAG.computeKnownBits(N1, RHSZero, RHSOne);
1748
1749     // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1750     // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1751     if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1752       return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1753                        DAG.getNode(ISD::CARRY_FALSE,
1754                                    SDLoc(N), MVT::Glue));
1755   }
1756
1757   return SDValue();
1758 }
1759
1760 SDValue DAGCombiner::visitADDE(SDNode *N) {
1761   SDValue N0 = N->getOperand(0);
1762   SDValue N1 = N->getOperand(1);
1763   SDValue CarryIn = N->getOperand(2);
1764   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1765   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1766
1767   // canonicalize constant to RHS
1768   if (N0C && !N1C)
1769     return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1770                        N1, N0, CarryIn);
1771
1772   // fold (adde x, y, false) -> (addc x, y)
1773   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1774     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1775
1776   return SDValue();
1777 }
1778
1779 // Since it may not be valid to emit a fold to zero for vector initializers
1780 // check if we can before folding.
1781 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
1782                              SelectionDAG &DAG,
1783                              bool LegalOperations, bool LegalTypes) {
1784   if (!VT.isVector())
1785     return DAG.getConstant(0, VT);
1786   if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1787     return DAG.getConstant(0, VT);
1788   return SDValue();
1789 }
1790
1791 SDValue DAGCombiner::visitSUB(SDNode *N) {
1792   SDValue N0 = N->getOperand(0);
1793   SDValue N1 = N->getOperand(1);
1794   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1795   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1796   ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr :
1797     dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1798   EVT VT = N0.getValueType();
1799
1800   // fold vector ops
1801   if (VT.isVector()) {
1802     SDValue FoldedVOp = SimplifyVBinOp(N);
1803     if (FoldedVOp.getNode()) return FoldedVOp;
1804
1805     // fold (sub x, 0) -> x, vector edition
1806     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1807       return N0;
1808   }
1809
1810   // fold (sub x, x) -> 0
1811   // FIXME: Refactor this and xor and other similar operations together.
1812   if (N0 == N1)
1813     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
1814   // fold (sub c1, c2) -> c1-c2
1815   if (N0C && N1C)
1816     return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C);
1817   // fold (sub x, c) -> (add x, -c)
1818   if (N1C)
1819     return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0,
1820                        DAG.getConstant(-N1C->getAPIntValue(), VT));
1821   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1822   if (N0C && N0C->isAllOnesValue())
1823     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
1824   // fold A-(A-B) -> B
1825   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1826     return N1.getOperand(1);
1827   // fold (A+B)-A -> B
1828   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1829     return N0.getOperand(1);
1830   // fold (A+B)-B -> A
1831   if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1832     return N0.getOperand(0);
1833   // fold C2-(A+C1) -> (C2-C1)-A
1834   if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1835     SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1836                                    VT);
1837     return DAG.getNode(ISD::SUB, SDLoc(N), VT, NewC,
1838                        N1.getOperand(0));
1839   }
1840   // fold ((A+(B+or-C))-B) -> A+or-C
1841   if (N0.getOpcode() == ISD::ADD &&
1842       (N0.getOperand(1).getOpcode() == ISD::SUB ||
1843        N0.getOperand(1).getOpcode() == ISD::ADD) &&
1844       N0.getOperand(1).getOperand(0) == N1)
1845     return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
1846                        N0.getOperand(0), N0.getOperand(1).getOperand(1));
1847   // fold ((A+(C+B))-B) -> A+C
1848   if (N0.getOpcode() == ISD::ADD &&
1849       N0.getOperand(1).getOpcode() == ISD::ADD &&
1850       N0.getOperand(1).getOperand(1) == N1)
1851     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1852                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1853   // fold ((A-(B-C))-C) -> A-B
1854   if (N0.getOpcode() == ISD::SUB &&
1855       N0.getOperand(1).getOpcode() == ISD::SUB &&
1856       N0.getOperand(1).getOperand(1) == N1)
1857     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1858                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1859
1860   // If either operand of a sub is undef, the result is undef
1861   if (N0.getOpcode() == ISD::UNDEF)
1862     return N0;
1863   if (N1.getOpcode() == ISD::UNDEF)
1864     return N1;
1865
1866   // If the relocation model supports it, consider symbol offsets.
1867   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1868     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1869       // fold (sub Sym, c) -> Sym-c
1870       if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1871         return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1872                                     GA->getOffset() -
1873                                       (uint64_t)N1C->getSExtValue());
1874       // fold (sub Sym+c1, Sym+c2) -> c1-c2
1875       if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1876         if (GA->getGlobal() == GB->getGlobal())
1877           return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1878                                  VT);
1879     }
1880
1881   return SDValue();
1882 }
1883
1884 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1885   SDValue N0 = N->getOperand(0);
1886   SDValue N1 = N->getOperand(1);
1887   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1888   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1889   EVT VT = N0.getValueType();
1890
1891   // If the flag result is dead, turn this into an SUB.
1892   if (!N->hasAnyUseOfValue(1))
1893     return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1894                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1895                                  MVT::Glue));
1896
1897   // fold (subc x, x) -> 0 + no borrow
1898   if (N0 == N1)
1899     return CombineTo(N, DAG.getConstant(0, VT),
1900                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1901                                  MVT::Glue));
1902
1903   // fold (subc x, 0) -> x + no borrow
1904   if (N1C && N1C->isNullValue())
1905     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1906                                         MVT::Glue));
1907
1908   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1909   if (N0C && N0C->isAllOnesValue())
1910     return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
1911                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1912                                  MVT::Glue));
1913
1914   return SDValue();
1915 }
1916
1917 SDValue DAGCombiner::visitSUBE(SDNode *N) {
1918   SDValue N0 = N->getOperand(0);
1919   SDValue N1 = N->getOperand(1);
1920   SDValue CarryIn = N->getOperand(2);
1921
1922   // fold (sube x, y, false) -> (subc x, y)
1923   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1924     return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
1925
1926   return SDValue();
1927 }
1928
1929 SDValue DAGCombiner::visitMUL(SDNode *N) {
1930   SDValue N0 = N->getOperand(0);
1931   SDValue N1 = N->getOperand(1);
1932   EVT VT = N0.getValueType();
1933
1934   // fold (mul x, undef) -> 0
1935   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1936     return DAG.getConstant(0, VT);
1937
1938   bool N0IsConst = false;
1939   bool N1IsConst = false;
1940   APInt ConstValue0, ConstValue1;
1941   // fold vector ops
1942   if (VT.isVector()) {
1943     SDValue FoldedVOp = SimplifyVBinOp(N);
1944     if (FoldedVOp.getNode()) return FoldedVOp;
1945
1946     N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
1947     N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
1948   } else {
1949     N0IsConst = dyn_cast<ConstantSDNode>(N0) != nullptr;
1950     ConstValue0 = N0IsConst ? (dyn_cast<ConstantSDNode>(N0))->getAPIntValue()
1951                             : APInt();
1952     N1IsConst = dyn_cast<ConstantSDNode>(N1) != nullptr;
1953     ConstValue1 = N1IsConst ? (dyn_cast<ConstantSDNode>(N1))->getAPIntValue()
1954                             : APInt();
1955   }
1956
1957   // fold (mul c1, c2) -> c1*c2
1958   if (N0IsConst && N1IsConst)
1959     return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0.getNode(), N1.getNode());
1960
1961   // canonicalize constant to RHS
1962   if (N0IsConst && !N1IsConst)
1963     return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
1964   // fold (mul x, 0) -> 0
1965   if (N1IsConst && ConstValue1 == 0)
1966     return N1;
1967   // We require a splat of the entire scalar bit width for non-contiguous
1968   // bit patterns.
1969   bool IsFullSplat =
1970     ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
1971   // fold (mul x, 1) -> x
1972   if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
1973     return N0;
1974   // fold (mul x, -1) -> 0-x
1975   if (N1IsConst && ConstValue1.isAllOnesValue())
1976     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1977                        DAG.getConstant(0, VT), N0);
1978   // fold (mul x, (1 << c)) -> x << c
1979   if (N1IsConst && ConstValue1.isPowerOf2() && IsFullSplat)
1980     return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1981                        DAG.getConstant(ConstValue1.logBase2(),
1982                                        getShiftAmountTy(N0.getValueType())));
1983   // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
1984   if (N1IsConst && (-ConstValue1).isPowerOf2() && IsFullSplat) {
1985     unsigned Log2Val = (-ConstValue1).logBase2();
1986     // FIXME: If the input is something that is easily negated (e.g. a
1987     // single-use add), we should put the negate there.
1988     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1989                        DAG.getConstant(0, VT),
1990                        DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1991                             DAG.getConstant(Log2Val,
1992                                       getShiftAmountTy(N0.getValueType()))));
1993   }
1994
1995   APInt Val;
1996   // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
1997   if (N1IsConst && N0.getOpcode() == ISD::SHL &&
1998       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1999                      isa<ConstantSDNode>(N0.getOperand(1)))) {
2000     SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
2001                              N1, N0.getOperand(1));
2002     AddToWorklist(C3.getNode());
2003     return DAG.getNode(ISD::MUL, SDLoc(N), VT,
2004                        N0.getOperand(0), C3);
2005   }
2006
2007   // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
2008   // use.
2009   {
2010     SDValue Sh(nullptr,0), Y(nullptr,0);
2011     // Check for both (mul (shl X, C), Y)  and  (mul Y, (shl X, C)).
2012     if (N0.getOpcode() == ISD::SHL &&
2013         (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2014                        isa<ConstantSDNode>(N0.getOperand(1))) &&
2015         N0.getNode()->hasOneUse()) {
2016       Sh = N0; Y = N1;
2017     } else if (N1.getOpcode() == ISD::SHL &&
2018                isa<ConstantSDNode>(N1.getOperand(1)) &&
2019                N1.getNode()->hasOneUse()) {
2020       Sh = N1; Y = N0;
2021     }
2022
2023     if (Sh.getNode()) {
2024       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2025                                 Sh.getOperand(0), Y);
2026       return DAG.getNode(ISD::SHL, SDLoc(N), VT,
2027                          Mul, Sh.getOperand(1));
2028     }
2029   }
2030
2031   // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
2032   if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
2033       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2034                      isa<ConstantSDNode>(N0.getOperand(1))))
2035     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
2036                        DAG.getNode(ISD::MUL, SDLoc(N0), VT,
2037                                    N0.getOperand(0), N1),
2038                        DAG.getNode(ISD::MUL, SDLoc(N1), VT,
2039                                    N0.getOperand(1), N1));
2040
2041   // reassociate mul
2042   SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1);
2043   if (RMUL.getNode())
2044     return RMUL;
2045
2046   return SDValue();
2047 }
2048
2049 SDValue DAGCombiner::visitSDIV(SDNode *N) {
2050   SDValue N0 = N->getOperand(0);
2051   SDValue N1 = N->getOperand(1);
2052   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2053   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2054   EVT VT = N->getValueType(0);
2055
2056   // fold vector ops
2057   if (VT.isVector()) {
2058     SDValue FoldedVOp = SimplifyVBinOp(N);
2059     if (FoldedVOp.getNode()) return FoldedVOp;
2060   }
2061
2062   // fold (sdiv c1, c2) -> c1/c2
2063   if (N0C && N1C && !N1C->isNullValue())
2064     return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C);
2065   // fold (sdiv X, 1) -> X
2066   if (N1C && N1C->getAPIntValue() == 1LL)
2067     return N0;
2068   // fold (sdiv X, -1) -> 0-X
2069   if (N1C && N1C->isAllOnesValue())
2070     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
2071                        DAG.getConstant(0, VT), N0);
2072   // If we know the sign bits of both operands are zero, strength reduce to a
2073   // udiv instead.  Handles (X&15) /s 4 -> X&15 >> 2
2074   if (!VT.isVector()) {
2075     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2076       return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
2077                          N0, N1);
2078   }
2079
2080   // fold (sdiv X, pow2) -> simple ops after legalize
2081   if (N1C && !N1C->isNullValue() && (N1C->getAPIntValue().isPowerOf2() ||
2082                                      (-N1C->getAPIntValue()).isPowerOf2())) {
2083     // If dividing by powers of two is cheap, then don't perform the following
2084     // fold.
2085     if (TLI.isPow2SDivCheap())
2086       return SDValue();
2087
2088     // Target-specific implementation of sdiv x, pow2.
2089     SDValue Res = BuildSDIVPow2(N);
2090     if (Res.getNode())
2091       return Res;
2092
2093     unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
2094
2095     // Splat the sign bit into the register
2096     SDValue SGN =
2097         DAG.getNode(ISD::SRA, SDLoc(N), VT, N0,
2098                     DAG.getConstant(VT.getScalarSizeInBits() - 1,
2099                                     getShiftAmountTy(N0.getValueType())));
2100     AddToWorklist(SGN.getNode());
2101
2102     // Add (N0 < 0) ? abs2 - 1 : 0;
2103     SDValue SRL =
2104         DAG.getNode(ISD::SRL, SDLoc(N), VT, SGN,
2105                     DAG.getConstant(VT.getScalarSizeInBits() - lg2,
2106                                     getShiftAmountTy(SGN.getValueType())));
2107     SDValue ADD = DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, SRL);
2108     AddToWorklist(SRL.getNode());
2109     AddToWorklist(ADD.getNode());    // Divide by pow2
2110     SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), VT, ADD,
2111                   DAG.getConstant(lg2, getShiftAmountTy(ADD.getValueType())));
2112
2113     // If we're dividing by a positive value, we're done.  Otherwise, we must
2114     // negate the result.
2115     if (N1C->getAPIntValue().isNonNegative())
2116       return SRA;
2117
2118     AddToWorklist(SRA.getNode());
2119     return DAG.getNode(ISD::SUB, SDLoc(N), VT, DAG.getConstant(0, VT), SRA);
2120   }
2121
2122   // if integer divide is expensive and we satisfy the requirements, emit an
2123   // alternate sequence.
2124   if (N1C && !TLI.isIntDivCheap()) {
2125     SDValue Op = BuildSDIV(N);
2126     if (Op.getNode()) return Op;
2127   }
2128
2129   // undef / X -> 0
2130   if (N0.getOpcode() == ISD::UNDEF)
2131     return DAG.getConstant(0, VT);
2132   // X / undef -> undef
2133   if (N1.getOpcode() == ISD::UNDEF)
2134     return N1;
2135
2136   return SDValue();
2137 }
2138
2139 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2140   SDValue N0 = N->getOperand(0);
2141   SDValue N1 = N->getOperand(1);
2142   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2143   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2144   EVT VT = N->getValueType(0);
2145
2146   // fold vector ops
2147   if (VT.isVector()) {
2148     SDValue FoldedVOp = SimplifyVBinOp(N);
2149     if (FoldedVOp.getNode()) return FoldedVOp;
2150   }
2151
2152   // fold (udiv c1, c2) -> c1/c2
2153   if (N0C && N1C && !N1C->isNullValue())
2154     return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C);
2155   // fold (udiv x, (1 << c)) -> x >>u c
2156   if (N1C && N1C->getAPIntValue().isPowerOf2())
2157     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0,
2158                        DAG.getConstant(N1C->getAPIntValue().logBase2(),
2159                                        getShiftAmountTy(N0.getValueType())));
2160   // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2161   if (N1.getOpcode() == ISD::SHL) {
2162     if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2163       if (SHC->getAPIntValue().isPowerOf2()) {
2164         EVT ADDVT = N1.getOperand(1).getValueType();
2165         SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N), ADDVT,
2166                                   N1.getOperand(1),
2167                                   DAG.getConstant(SHC->getAPIntValue()
2168                                                                   .logBase2(),
2169                                                   ADDVT));
2170         AddToWorklist(Add.getNode());
2171         return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, Add);
2172       }
2173     }
2174   }
2175   // fold (udiv x, c) -> alternate
2176   if (N1C && !TLI.isIntDivCheap()) {
2177     SDValue Op = BuildUDIV(N);
2178     if (Op.getNode()) return Op;
2179   }
2180
2181   // undef / X -> 0
2182   if (N0.getOpcode() == ISD::UNDEF)
2183     return DAG.getConstant(0, VT);
2184   // X / undef -> undef
2185   if (N1.getOpcode() == ISD::UNDEF)
2186     return N1;
2187
2188   return SDValue();
2189 }
2190
2191 SDValue DAGCombiner::visitSREM(SDNode *N) {
2192   SDValue N0 = N->getOperand(0);
2193   SDValue N1 = N->getOperand(1);
2194   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2195   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2196   EVT VT = N->getValueType(0);
2197
2198   // fold (srem c1, c2) -> c1%c2
2199   if (N0C && N1C && !N1C->isNullValue())
2200     return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C);
2201   // If we know the sign bits of both operands are zero, strength reduce to a
2202   // urem instead.  Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2203   if (!VT.isVector()) {
2204     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2205       return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
2206   }
2207
2208   // If X/C can be simplified by the division-by-constant logic, lower
2209   // X%C to the equivalent of X-X/C*C.
2210   if (N1C && !N1C->isNullValue()) {
2211     SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
2212     AddToWorklist(Div.getNode());
2213     SDValue OptimizedDiv = combine(Div.getNode());
2214     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2215       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2216                                 OptimizedDiv, N1);
2217       SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2218       AddToWorklist(Mul.getNode());
2219       return Sub;
2220     }
2221   }
2222
2223   // undef % X -> 0
2224   if (N0.getOpcode() == ISD::UNDEF)
2225     return DAG.getConstant(0, VT);
2226   // X % undef -> undef
2227   if (N1.getOpcode() == ISD::UNDEF)
2228     return N1;
2229
2230   return SDValue();
2231 }
2232
2233 SDValue DAGCombiner::visitUREM(SDNode *N) {
2234   SDValue N0 = N->getOperand(0);
2235   SDValue N1 = N->getOperand(1);
2236   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2237   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2238   EVT VT = N->getValueType(0);
2239
2240   // fold (urem c1, c2) -> c1%c2
2241   if (N0C && N1C && !N1C->isNullValue())
2242     return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C);
2243   // fold (urem x, pow2) -> (and x, pow2-1)
2244   if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
2245     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0,
2246                        DAG.getConstant(N1C->getAPIntValue()-1,VT));
2247   // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2248   if (N1.getOpcode() == ISD::SHL) {
2249     if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2250       if (SHC->getAPIntValue().isPowerOf2()) {
2251         SDValue Add =
2252           DAG.getNode(ISD::ADD, SDLoc(N), VT, N1,
2253                  DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
2254                                  VT));
2255         AddToWorklist(Add.getNode());
2256         return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, Add);
2257       }
2258     }
2259   }
2260
2261   // If X/C can be simplified by the division-by-constant logic, lower
2262   // X%C to the equivalent of X-X/C*C.
2263   if (N1C && !N1C->isNullValue()) {
2264     SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
2265     AddToWorklist(Div.getNode());
2266     SDValue OptimizedDiv = combine(Div.getNode());
2267     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2268       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2269                                 OptimizedDiv, N1);
2270       SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2271       AddToWorklist(Mul.getNode());
2272       return Sub;
2273     }
2274   }
2275
2276   // undef % X -> 0
2277   if (N0.getOpcode() == ISD::UNDEF)
2278     return DAG.getConstant(0, VT);
2279   // X % undef -> undef
2280   if (N1.getOpcode() == ISD::UNDEF)
2281     return N1;
2282
2283   return SDValue();
2284 }
2285
2286 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2287   SDValue N0 = N->getOperand(0);
2288   SDValue N1 = N->getOperand(1);
2289   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2290   EVT VT = N->getValueType(0);
2291   SDLoc DL(N);
2292
2293   // fold (mulhs x, 0) -> 0
2294   if (N1C && N1C->isNullValue())
2295     return N1;
2296   // fold (mulhs x, 1) -> (sra x, size(x)-1)
2297   if (N1C && N1C->getAPIntValue() == 1)
2298     return DAG.getNode(ISD::SRA, SDLoc(N), N0.getValueType(), N0,
2299                        DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2300                                        getShiftAmountTy(N0.getValueType())));
2301   // fold (mulhs x, undef) -> 0
2302   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2303     return DAG.getConstant(0, VT);
2304
2305   // If the type twice as wide is legal, transform the mulhs to a wider multiply
2306   // plus a shift.
2307   if (VT.isSimple() && !VT.isVector()) {
2308     MVT Simple = VT.getSimpleVT();
2309     unsigned SimpleSize = Simple.getSizeInBits();
2310     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2311     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2312       N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2313       N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2314       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2315       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2316             DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2317       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2318     }
2319   }
2320
2321   return SDValue();
2322 }
2323
2324 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2325   SDValue N0 = N->getOperand(0);
2326   SDValue N1 = N->getOperand(1);
2327   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2328   EVT VT = N->getValueType(0);
2329   SDLoc DL(N);
2330
2331   // fold (mulhu x, 0) -> 0
2332   if (N1C && N1C->isNullValue())
2333     return N1;
2334   // fold (mulhu x, 1) -> 0
2335   if (N1C && N1C->getAPIntValue() == 1)
2336     return DAG.getConstant(0, N0.getValueType());
2337   // fold (mulhu x, undef) -> 0
2338   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2339     return DAG.getConstant(0, VT);
2340
2341   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2342   // plus a shift.
2343   if (VT.isSimple() && !VT.isVector()) {
2344     MVT Simple = VT.getSimpleVT();
2345     unsigned SimpleSize = Simple.getSizeInBits();
2346     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2347     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2348       N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2349       N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2350       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2351       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2352             DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2353       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2354     }
2355   }
2356
2357   return SDValue();
2358 }
2359
2360 /// SimplifyNodeWithTwoResults - Perform optimizations common to nodes that
2361 /// compute two values. LoOp and HiOp give the opcodes for the two computations
2362 /// that are being performed. Return true if a simplification was made.
2363 ///
2364 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2365                                                 unsigned HiOp) {
2366   // If the high half is not needed, just compute the low half.
2367   bool HiExists = N->hasAnyUseOfValue(1);
2368   if (!HiExists &&
2369       (!LegalOperations ||
2370        TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
2371     SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0),
2372                               ArrayRef<SDUse>(N->op_begin(), N->op_end()));
2373     return CombineTo(N, Res, Res);
2374   }
2375
2376   // If the low half is not needed, just compute the high half.
2377   bool LoExists = N->hasAnyUseOfValue(0);
2378   if (!LoExists &&
2379       (!LegalOperations ||
2380        TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2381     SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1),
2382                               ArrayRef<SDUse>(N->op_begin(), N->op_end()));
2383     return CombineTo(N, Res, Res);
2384   }
2385
2386   // If both halves are used, return as it is.
2387   if (LoExists && HiExists)
2388     return SDValue();
2389
2390   // If the two computed results can be simplified separately, separate them.
2391   if (LoExists) {
2392     SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0),
2393                              ArrayRef<SDUse>(N->op_begin(), N->op_end()));
2394     AddToWorklist(Lo.getNode());
2395     SDValue LoOpt = combine(Lo.getNode());
2396     if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2397         (!LegalOperations ||
2398          TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2399       return CombineTo(N, LoOpt, LoOpt);
2400   }
2401
2402   if (HiExists) {
2403     SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1),
2404                              ArrayRef<SDUse>(N->op_begin(), N->op_end()));
2405     AddToWorklist(Hi.getNode());
2406     SDValue HiOpt = combine(Hi.getNode());
2407     if (HiOpt.getNode() && HiOpt != Hi &&
2408         (!LegalOperations ||
2409          TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2410       return CombineTo(N, HiOpt, HiOpt);
2411   }
2412
2413   return SDValue();
2414 }
2415
2416 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2417   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
2418   if (Res.getNode()) return Res;
2419
2420   EVT VT = N->getValueType(0);
2421   SDLoc DL(N);
2422
2423   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2424   // plus a shift.
2425   if (VT.isSimple() && !VT.isVector()) {
2426     MVT Simple = VT.getSimpleVT();
2427     unsigned SimpleSize = Simple.getSizeInBits();
2428     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2429     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2430       SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2431       SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2432       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2433       // Compute the high part as N1.
2434       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2435             DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2436       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2437       // Compute the low part as N0.
2438       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2439       return CombineTo(N, Lo, Hi);
2440     }
2441   }
2442
2443   return SDValue();
2444 }
2445
2446 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2447   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
2448   if (Res.getNode()) return Res;
2449
2450   EVT VT = N->getValueType(0);
2451   SDLoc DL(N);
2452
2453   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2454   // plus a shift.
2455   if (VT.isSimple() && !VT.isVector()) {
2456     MVT Simple = VT.getSimpleVT();
2457     unsigned SimpleSize = Simple.getSizeInBits();
2458     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2459     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2460       SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2461       SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2462       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2463       // Compute the high part as N1.
2464       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2465             DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2466       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2467       // Compute the low part as N0.
2468       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2469       return CombineTo(N, Lo, Hi);
2470     }
2471   }
2472
2473   return SDValue();
2474 }
2475
2476 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2477   // (smulo x, 2) -> (saddo x, x)
2478   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2479     if (C2->getAPIntValue() == 2)
2480       return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2481                          N->getOperand(0), N->getOperand(0));
2482
2483   return SDValue();
2484 }
2485
2486 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2487   // (umulo x, 2) -> (uaddo x, x)
2488   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2489     if (C2->getAPIntValue() == 2)
2490       return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2491                          N->getOperand(0), N->getOperand(0));
2492
2493   return SDValue();
2494 }
2495
2496 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2497   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
2498   if (Res.getNode()) return Res;
2499
2500   return SDValue();
2501 }
2502
2503 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2504   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
2505   if (Res.getNode()) return Res;
2506
2507   return SDValue();
2508 }
2509
2510 /// SimplifyBinOpWithSameOpcodeHands - If this is a binary operator with
2511 /// two operands of the same opcode, try to simplify it.
2512 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2513   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2514   EVT VT = N0.getValueType();
2515   assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2516
2517   // Bail early if none of these transforms apply.
2518   if (N0.getNode()->getNumOperands() == 0) return SDValue();
2519
2520   // For each of OP in AND/OR/XOR:
2521   // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2522   // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2523   // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2524   // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2525   //
2526   // do not sink logical op inside of a vector extend, since it may combine
2527   // into a vsetcc.
2528   EVT Op0VT = N0.getOperand(0).getValueType();
2529   if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2530        N0.getOpcode() == ISD::SIGN_EXTEND ||
2531        // Avoid infinite looping with PromoteIntBinOp.
2532        (N0.getOpcode() == ISD::ANY_EXTEND &&
2533         (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2534        (N0.getOpcode() == ISD::TRUNCATE &&
2535         (!TLI.isZExtFree(VT, Op0VT) ||
2536          !TLI.isTruncateFree(Op0VT, VT)) &&
2537         TLI.isTypeLegal(Op0VT))) &&
2538       !VT.isVector() &&
2539       Op0VT == N1.getOperand(0).getValueType() &&
2540       (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2541     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2542                                  N0.getOperand(0).getValueType(),
2543                                  N0.getOperand(0), N1.getOperand(0));
2544     AddToWorklist(ORNode.getNode());
2545     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2546   }
2547
2548   // For each of OP in SHL/SRL/SRA/AND...
2549   //   fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2550   //   fold (or  (OP x, z), (OP y, z)) -> (OP (or  x, y), z)
2551   //   fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2552   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2553        N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2554       N0.getOperand(1) == N1.getOperand(1)) {
2555     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2556                                  N0.getOperand(0).getValueType(),
2557                                  N0.getOperand(0), N1.getOperand(0));
2558     AddToWorklist(ORNode.getNode());
2559     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2560                        ORNode, N0.getOperand(1));
2561   }
2562
2563   // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2564   // Only perform this optimization after type legalization and before
2565   // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2566   // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2567   // we don't want to undo this promotion.
2568   // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2569   // on scalars.
2570   if ((N0.getOpcode() == ISD::BITCAST ||
2571        N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2572       Level == AfterLegalizeTypes) {
2573     SDValue In0 = N0.getOperand(0);
2574     SDValue In1 = N1.getOperand(0);
2575     EVT In0Ty = In0.getValueType();
2576     EVT In1Ty = In1.getValueType();
2577     SDLoc DL(N);
2578     // If both incoming values are integers, and the original types are the
2579     // same.
2580     if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2581       SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2582       SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2583       AddToWorklist(Op.getNode());
2584       return BC;
2585     }
2586   }
2587
2588   // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2589   // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2590   // If both shuffles use the same mask, and both shuffle within a single
2591   // vector, then it is worthwhile to move the swizzle after the operation.
2592   // The type-legalizer generates this pattern when loading illegal
2593   // vector types from memory. In many cases this allows additional shuffle
2594   // optimizations.
2595   // There are other cases where moving the shuffle after the xor/and/or
2596   // is profitable even if shuffles don't perform a swizzle.
2597   // If both shuffles use the same mask, and both shuffles have the same first
2598   // or second operand, then it might still be profitable to move the shuffle
2599   // after the xor/and/or operation.
2600   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
2601     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2602     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2603
2604     assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
2605            "Inputs to shuffles are not the same type");
2606
2607     // Check that both shuffles use the same mask. The masks are known to be of
2608     // the same length because the result vector type is the same.
2609     // Check also that shuffles have only one use to avoid introducing extra
2610     // instructions.
2611     if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2612         SVN0->getMask().equals(SVN1->getMask())) {
2613       SDValue ShOp = N0->getOperand(1);
2614
2615       // Don't try to fold this node if it requires introducing a
2616       // build vector of all zeros that might be illegal at this stage.
2617       if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2618         if (!LegalTypes)
2619           ShOp = DAG.getConstant(0, VT);
2620         else
2621           ShOp = SDValue();
2622       }
2623
2624       // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2625       // (OR  (shuf (A, C), shuf (B, C)) -> shuf (OR  (A, B), C)
2626       // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2627       if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2628         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2629                                       N0->getOperand(0), N1->getOperand(0));
2630         AddToWorklist(NewNode.getNode());
2631         return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2632                                     &SVN0->getMask()[0]);
2633       }
2634
2635       // Don't try to fold this node if it requires introducing a
2636       // build vector of all zeros that might be illegal at this stage.
2637       ShOp = N0->getOperand(0);
2638       if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2639         if (!LegalTypes)
2640           ShOp = DAG.getConstant(0, VT);
2641         else
2642           ShOp = SDValue();
2643       }
2644
2645       // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2646       // (OR  (shuf (C, A), shuf (C, B)) -> shuf (C, OR  (A, B))
2647       // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2648       if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2649         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2650                                       N0->getOperand(1), N1->getOperand(1));
2651         AddToWorklist(NewNode.getNode());
2652         return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2653                                     &SVN0->getMask()[0]);
2654       }
2655     }
2656   }
2657
2658   return SDValue();
2659 }
2660
2661 SDValue DAGCombiner::visitAND(SDNode *N) {
2662   SDValue N0 = N->getOperand(0);
2663   SDValue N1 = N->getOperand(1);
2664   SDValue LL, LR, RL, RR, CC0, CC1;
2665   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2666   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2667   EVT VT = N1.getValueType();
2668   unsigned BitWidth = VT.getScalarType().getSizeInBits();
2669
2670   // fold vector ops
2671   if (VT.isVector()) {
2672     SDValue FoldedVOp = SimplifyVBinOp(N);
2673     if (FoldedVOp.getNode()) return FoldedVOp;
2674
2675     // fold (and x, 0) -> 0, vector edition
2676     if (ISD::isBuildVectorAllZeros(N0.getNode()))
2677       return N0;
2678     if (ISD::isBuildVectorAllZeros(N1.getNode()))
2679       return N1;
2680
2681     // fold (and x, -1) -> x, vector edition
2682     if (ISD::isBuildVectorAllOnes(N0.getNode()))
2683       return N1;
2684     if (ISD::isBuildVectorAllOnes(N1.getNode()))
2685       return N0;
2686   }
2687
2688   // fold (and x, undef) -> 0
2689   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2690     return DAG.getConstant(0, VT);
2691   // fold (and c1, c2) -> c1&c2
2692   if (N0C && N1C)
2693     return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C);
2694   // canonicalize constant to RHS
2695   if (N0C && !N1C)
2696     return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
2697   // fold (and x, -1) -> x
2698   if (N1C && N1C->isAllOnesValue())
2699     return N0;
2700   // if (and x, c) is known to be zero, return 0
2701   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2702                                    APInt::getAllOnesValue(BitWidth)))
2703     return DAG.getConstant(0, VT);
2704   // reassociate and
2705   SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1);
2706   if (RAND.getNode())
2707     return RAND;
2708   // fold (and (or x, C), D) -> D if (C & D) == D
2709   if (N1C && N0.getOpcode() == ISD::OR)
2710     if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2711       if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2712         return N1;
2713   // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2714   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2715     SDValue N0Op0 = N0.getOperand(0);
2716     APInt Mask = ~N1C->getAPIntValue();
2717     Mask = Mask.trunc(N0Op0.getValueSizeInBits());
2718     if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2719       SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
2720                                  N0.getValueType(), N0Op0);
2721
2722       // Replace uses of the AND with uses of the Zero extend node.
2723       CombineTo(N, Zext);
2724
2725       // We actually want to replace all uses of the any_extend with the
2726       // zero_extend, to avoid duplicating things.  This will later cause this
2727       // AND to be folded.
2728       CombineTo(N0.getNode(), Zext);
2729       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2730     }
2731   }
2732   // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
2733   // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2734   // already be zero by virtue of the width of the base type of the load.
2735   //
2736   // the 'X' node here can either be nothing or an extract_vector_elt to catch
2737   // more cases.
2738   if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2739        N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2740       N0.getOpcode() == ISD::LOAD) {
2741     LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2742                                          N0 : N0.getOperand(0) );
2743
2744     // Get the constant (if applicable) the zero'th operand is being ANDed with.
2745     // This can be a pure constant or a vector splat, in which case we treat the
2746     // vector as a scalar and use the splat value.
2747     APInt Constant = APInt::getNullValue(1);
2748     if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2749       Constant = C->getAPIntValue();
2750     } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2751       APInt SplatValue, SplatUndef;
2752       unsigned SplatBitSize;
2753       bool HasAnyUndefs;
2754       bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2755                                              SplatBitSize, HasAnyUndefs);
2756       if (IsSplat) {
2757         // Undef bits can contribute to a possible optimisation if set, so
2758         // set them.
2759         SplatValue |= SplatUndef;
2760
2761         // The splat value may be something like "0x00FFFFFF", which means 0 for
2762         // the first vector value and FF for the rest, repeating. We need a mask
2763         // that will apply equally to all members of the vector, so AND all the
2764         // lanes of the constant together.
2765         EVT VT = Vector->getValueType(0);
2766         unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
2767
2768         // If the splat value has been compressed to a bitlength lower
2769         // than the size of the vector lane, we need to re-expand it to
2770         // the lane size.
2771         if (BitWidth > SplatBitSize)
2772           for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
2773                SplatBitSize < BitWidth;
2774                SplatBitSize = SplatBitSize * 2)
2775             SplatValue |= SplatValue.shl(SplatBitSize);
2776
2777         Constant = APInt::getAllOnesValue(BitWidth);
2778         for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
2779           Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
2780       }
2781     }
2782
2783     // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
2784     // actually legal and isn't going to get expanded, else this is a false
2785     // optimisation.
2786     bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
2787                                                     Load->getMemoryVT());
2788
2789     // Resize the constant to the same size as the original memory access before
2790     // extension. If it is still the AllOnesValue then this AND is completely
2791     // unneeded.
2792     Constant =
2793       Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
2794
2795     bool B;
2796     switch (Load->getExtensionType()) {
2797     default: B = false; break;
2798     case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
2799     case ISD::ZEXTLOAD:
2800     case ISD::NON_EXTLOAD: B = true; break;
2801     }
2802
2803     if (B && Constant.isAllOnesValue()) {
2804       // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
2805       // preserve semantics once we get rid of the AND.
2806       SDValue NewLoad(Load, 0);
2807       if (Load->getExtensionType() == ISD::EXTLOAD) {
2808         NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
2809                               Load->getValueType(0), SDLoc(Load),
2810                               Load->getChain(), Load->getBasePtr(),
2811                               Load->getOffset(), Load->getMemoryVT(),
2812                               Load->getMemOperand());
2813         // Replace uses of the EXTLOAD with the new ZEXTLOAD.
2814         if (Load->getNumValues() == 3) {
2815           // PRE/POST_INC loads have 3 values.
2816           SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
2817                            NewLoad.getValue(2) };
2818           CombineTo(Load, To, 3, true);
2819         } else {
2820           CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
2821         }
2822       }
2823
2824       // Fold the AND away, taking care not to fold to the old load node if we
2825       // replaced it.
2826       CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
2827
2828       return SDValue(N, 0); // Return N so it doesn't get rechecked!
2829     }
2830   }
2831   // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2832   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2833     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2834     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2835
2836     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2837         LL.getValueType().isInteger()) {
2838       // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2839       if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
2840         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2841                                      LR.getValueType(), LL, RL);
2842         AddToWorklist(ORNode.getNode());
2843         return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2844       }
2845       // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2846       if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
2847         SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2848                                       LR.getValueType(), LL, RL);
2849         AddToWorklist(ANDNode.getNode());
2850         return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
2851       }
2852       // fold (and (setgt X,  -1), (setgt Y,  -1)) -> (setgt (or X, Y), -1)
2853       if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
2854         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2855                                      LR.getValueType(), LL, RL);
2856         AddToWorklist(ORNode.getNode());
2857         return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2858       }
2859     }
2860     // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2861     if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2862         Op0 == Op1 && LL.getValueType().isInteger() &&
2863       Op0 == ISD::SETNE && ((cast<ConstantSDNode>(LR)->isNullValue() &&
2864                                  cast<ConstantSDNode>(RR)->isAllOnesValue()) ||
2865                                 (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
2866                                  cast<ConstantSDNode>(RR)->isNullValue()))) {
2867       SDValue ADDNode = DAG.getNode(ISD::ADD, SDLoc(N0), LL.getValueType(),
2868                                     LL, DAG.getConstant(1, LL.getValueType()));
2869       AddToWorklist(ADDNode.getNode());
2870       return DAG.getSetCC(SDLoc(N), VT, ADDNode,
2871                           DAG.getConstant(2, LL.getValueType()), ISD::SETUGE);
2872     }
2873     // canonicalize equivalent to ll == rl
2874     if (LL == RR && LR == RL) {
2875       Op1 = ISD::getSetCCSwappedOperands(Op1);
2876       std::swap(RL, RR);
2877     }
2878     if (LL == RL && LR == RR) {
2879       bool isInteger = LL.getValueType().isInteger();
2880       ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2881       if (Result != ISD::SETCC_INVALID &&
2882           (!LegalOperations ||
2883            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2884             TLI.isOperationLegal(ISD::SETCC,
2885                             getSetCCResultType(N0.getSimpleValueType())))))
2886         return DAG.getSetCC(SDLoc(N), N0.getValueType(),
2887                             LL, LR, Result);
2888     }
2889   }
2890
2891   // Simplify: (and (op x...), (op y...))  -> (op (and x, y))
2892   if (N0.getOpcode() == N1.getOpcode()) {
2893     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
2894     if (Tmp.getNode()) return Tmp;
2895   }
2896
2897   // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
2898   // fold (and (sra)) -> (and (srl)) when possible.
2899   if (!VT.isVector() &&
2900       SimplifyDemandedBits(SDValue(N, 0)))
2901     return SDValue(N, 0);
2902
2903   // fold (zext_inreg (extload x)) -> (zextload x)
2904   if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
2905     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2906     EVT MemVT = LN0->getMemoryVT();
2907     // If we zero all the possible extended bits, then we can turn this into
2908     // a zextload if we are running before legalize or the operation is legal.
2909     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2910     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2911                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2912         ((!LegalOperations && !LN0->isVolatile()) ||
2913          TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2914       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2915                                        LN0->getChain(), LN0->getBasePtr(),
2916                                        MemVT, LN0->getMemOperand());
2917       AddToWorklist(N);
2918       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2919       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2920     }
2921   }
2922   // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
2923   if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
2924       N0.hasOneUse()) {
2925     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2926     EVT MemVT = LN0->getMemoryVT();
2927     // If we zero all the possible extended bits, then we can turn this into
2928     // a zextload if we are running before legalize or the operation is legal.
2929     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2930     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2931                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2932         ((!LegalOperations && !LN0->isVolatile()) ||
2933          TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2934       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2935                                        LN0->getChain(), LN0->getBasePtr(),
2936                                        MemVT, LN0->getMemOperand());
2937       AddToWorklist(N);
2938       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2939       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2940     }
2941   }
2942
2943   // fold (and (load x), 255) -> (zextload x, i8)
2944   // fold (and (extload x, i16), 255) -> (zextload x, i8)
2945   // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
2946   if (N1C && (N0.getOpcode() == ISD::LOAD ||
2947               (N0.getOpcode() == ISD::ANY_EXTEND &&
2948                N0.getOperand(0).getOpcode() == ISD::LOAD))) {
2949     bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
2950     LoadSDNode *LN0 = HasAnyExt
2951       ? cast<LoadSDNode>(N0.getOperand(0))
2952       : cast<LoadSDNode>(N0);
2953     if (LN0->getExtensionType() != ISD::SEXTLOAD &&
2954         LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
2955       uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
2956       if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
2957         EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
2958         EVT LoadedVT = LN0->getMemoryVT();
2959
2960         if (ExtVT == LoadedVT &&
2961             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2962           EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2963
2964           SDValue NewLoad =
2965             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2966                            LN0->getChain(), LN0->getBasePtr(), ExtVT,
2967                            LN0->getMemOperand());
2968           AddToWorklist(N);
2969           CombineTo(LN0, NewLoad, NewLoad.getValue(1));
2970           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2971         }
2972
2973         // Do not change the width of a volatile load.
2974         // Do not generate loads of non-round integer types since these can
2975         // be expensive (and would be wrong if the type is not byte sized).
2976         if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
2977             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2978           EVT PtrType = LN0->getOperand(1).getValueType();
2979
2980           unsigned Alignment = LN0->getAlignment();
2981           SDValue NewPtr = LN0->getBasePtr();
2982
2983           // For big endian targets, we need to add an offset to the pointer
2984           // to load the correct bytes.  For little endian systems, we merely
2985           // need to read fewer bytes from the same pointer.
2986           if (TLI.isBigEndian()) {
2987             unsigned LVTStoreBytes = LoadedVT.getStoreSize();
2988             unsigned EVTStoreBytes = ExtVT.getStoreSize();
2989             unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
2990             NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0), PtrType,
2991                                  NewPtr, DAG.getConstant(PtrOff, PtrType));
2992             Alignment = MinAlign(Alignment, PtrOff);
2993           }
2994
2995           AddToWorklist(NewPtr.getNode());
2996
2997           EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2998           SDValue Load =
2999             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3000                            LN0->getChain(), NewPtr,
3001                            LN0->getPointerInfo(),
3002                            ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
3003                            LN0->isInvariant(), Alignment, LN0->getAAInfo());
3004           AddToWorklist(N);
3005           CombineTo(LN0, Load, Load.getValue(1));
3006           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3007         }
3008       }
3009     }
3010   }
3011
3012   if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
3013       VT.getSizeInBits() <= 64) {
3014     if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3015       APInt ADDC = ADDI->getAPIntValue();
3016       if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
3017         // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
3018         // immediate for an add, but it is legal if its top c2 bits are set,
3019         // transform the ADD so the immediate doesn't need to be materialized
3020         // in a register.
3021         if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
3022           APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
3023                                              SRLI->getZExtValue());
3024           if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
3025             ADDC |= Mask;
3026             if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
3027               SDValue NewAdd =
3028                 DAG.getNode(ISD::ADD, SDLoc(N0), VT,
3029                             N0.getOperand(0), DAG.getConstant(ADDC, VT));
3030               CombineTo(N0.getNode(), NewAdd);
3031               return SDValue(N, 0); // Return N so it doesn't get rechecked!
3032             }
3033           }
3034         }
3035       }
3036     }
3037   }
3038
3039   // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
3040   if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
3041     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
3042                                        N0.getOperand(1), false);
3043     if (BSwap.getNode())
3044       return BSwap;
3045   }
3046
3047   return SDValue();
3048 }
3049
3050 /// MatchBSwapHWord - Match (a >> 8) | (a << 8) as (bswap a) >> 16
3051 ///
3052 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
3053                                         bool DemandHighBits) {
3054   if (!LegalOperations)
3055     return SDValue();
3056
3057   EVT VT = N->getValueType(0);
3058   if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
3059     return SDValue();
3060   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3061     return SDValue();
3062
3063   // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
3064   bool LookPassAnd0 = false;
3065   bool LookPassAnd1 = false;
3066   if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
3067       std::swap(N0, N1);
3068   if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
3069       std::swap(N0, N1);
3070   if (N0.getOpcode() == ISD::AND) {
3071     if (!N0.getNode()->hasOneUse())
3072       return SDValue();
3073     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3074     if (!N01C || N01C->getZExtValue() != 0xFF00)
3075       return SDValue();
3076     N0 = N0.getOperand(0);
3077     LookPassAnd0 = true;
3078   }
3079
3080   if (N1.getOpcode() == ISD::AND) {
3081     if (!N1.getNode()->hasOneUse())
3082       return SDValue();
3083     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3084     if (!N11C || N11C->getZExtValue() != 0xFF)
3085       return SDValue();
3086     N1 = N1.getOperand(0);
3087     LookPassAnd1 = true;
3088   }
3089
3090   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3091     std::swap(N0, N1);
3092   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3093     return SDValue();
3094   if (!N0.getNode()->hasOneUse() ||
3095       !N1.getNode()->hasOneUse())
3096     return SDValue();
3097
3098   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3099   ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3100   if (!N01C || !N11C)
3101     return SDValue();
3102   if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3103     return SDValue();
3104
3105   // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3106   SDValue N00 = N0->getOperand(0);
3107   if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3108     if (!N00.getNode()->hasOneUse())
3109       return SDValue();
3110     ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3111     if (!N001C || N001C->getZExtValue() != 0xFF)
3112       return SDValue();
3113     N00 = N00.getOperand(0);
3114     LookPassAnd0 = true;
3115   }
3116
3117   SDValue N10 = N1->getOperand(0);
3118   if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3119     if (!N10.getNode()->hasOneUse())
3120       return SDValue();
3121     ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3122     if (!N101C || N101C->getZExtValue() != 0xFF00)
3123       return SDValue();
3124     N10 = N10.getOperand(0);
3125     LookPassAnd1 = true;
3126   }
3127
3128   if (N00 != N10)
3129     return SDValue();
3130
3131   // Make sure everything beyond the low halfword gets set to zero since the SRL
3132   // 16 will clear the top bits.
3133   unsigned OpSizeInBits = VT.getSizeInBits();
3134   if (DemandHighBits && OpSizeInBits > 16) {
3135     // If the left-shift isn't masked out then the only way this is a bswap is
3136     // if all bits beyond the low 8 are 0. In that case the entire pattern
3137     // reduces to a left shift anyway: leave it for other parts of the combiner.
3138     if (!LookPassAnd0)
3139       return SDValue();
3140
3141     // However, if the right shift isn't masked out then it might be because
3142     // it's not needed. See if we can spot that too.
3143     if (!LookPassAnd1 &&
3144         !DAG.MaskedValueIsZero(
3145             N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3146       return SDValue();
3147   }
3148
3149   SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
3150   if (OpSizeInBits > 16)
3151     Res = DAG.getNode(ISD::SRL, SDLoc(N), VT, Res,
3152                       DAG.getConstant(OpSizeInBits-16, getShiftAmountTy(VT)));
3153   return Res;
3154 }
3155
3156 /// isBSwapHWordElement - Return true if the specified node is an element
3157 /// that makes up a 32-bit packed halfword byteswap. i.e.
3158 /// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((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 /// MatchBSwapHWord - Match a 32-bit packed halfword bswap. That is
3227 /// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
3228 /// => (rotl (bswap x), 16)
3229 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3230   if (!LegalOperations)
3231     return SDValue();
3232
3233   EVT VT = N->getValueType(0);
3234   if (VT != MVT::i32)
3235     return SDValue();
3236   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3237     return SDValue();
3238
3239   SmallVector<SDNode*,4> Parts(4, (SDNode*)nullptr);
3240   // Look for either
3241   // (or (or (and), (and)), (or (and), (and)))
3242   // (or (or (or (and), (and)), (and)), (and))
3243   if (N0.getOpcode() != ISD::OR)
3244     return SDValue();
3245   SDValue N00 = N0.getOperand(0);
3246   SDValue N01 = N0.getOperand(1);
3247
3248   if (N1.getOpcode() == ISD::OR &&
3249       N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3250     // (or (or (and), (and)), (or (and), (and)))
3251     SDValue N000 = N00.getOperand(0);
3252     if (!isBSwapHWordElement(N000, Parts))
3253       return SDValue();
3254
3255     SDValue N001 = N00.getOperand(1);
3256     if (!isBSwapHWordElement(N001, Parts))
3257       return SDValue();
3258     SDValue N010 = N01.getOperand(0);
3259     if (!isBSwapHWordElement(N010, Parts))
3260       return SDValue();
3261     SDValue N011 = N01.getOperand(1);
3262     if (!isBSwapHWordElement(N011, Parts))
3263       return SDValue();
3264   } else {
3265     // (or (or (or (and), (and)), (and)), (and))
3266     if (!isBSwapHWordElement(N1, Parts))
3267       return SDValue();
3268     if (!isBSwapHWordElement(N01, Parts))
3269       return SDValue();
3270     if (N00.getOpcode() != ISD::OR)
3271       return SDValue();
3272     SDValue N000 = N00.getOperand(0);
3273     if (!isBSwapHWordElement(N000, Parts))
3274       return SDValue();
3275     SDValue N001 = N00.getOperand(1);
3276     if (!isBSwapHWordElement(N001, Parts))
3277       return SDValue();
3278   }
3279
3280   // Make sure the parts are all coming from the same node.
3281   if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3282     return SDValue();
3283
3284   SDValue BSwap = DAG.getNode(ISD::BSWAP, SDLoc(N), VT,
3285                               SDValue(Parts[0],0));
3286
3287   // Result of the bswap should be rotated by 16. If it's not legal, then
3288   // do  (x << 16) | (x >> 16).
3289   SDValue ShAmt = DAG.getConstant(16, getShiftAmountTy(VT));
3290   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3291     return DAG.getNode(ISD::ROTL, SDLoc(N), VT, BSwap, ShAmt);
3292   if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3293     return DAG.getNode(ISD::ROTR, SDLoc(N), VT, BSwap, ShAmt);
3294   return DAG.getNode(ISD::OR, SDLoc(N), VT,
3295                      DAG.getNode(ISD::SHL, SDLoc(N), VT, BSwap, ShAmt),
3296                      DAG.getNode(ISD::SRL, SDLoc(N), VT, BSwap, ShAmt));
3297 }
3298
3299 SDValue DAGCombiner::visitOR(SDNode *N) {
3300   SDValue N0 = N->getOperand(0);
3301   SDValue N1 = N->getOperand(1);
3302   SDValue LL, LR, RL, RR, CC0, CC1;
3303   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3304   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3305   EVT VT = N1.getValueType();
3306
3307   // fold vector ops
3308   if (VT.isVector()) {
3309     SDValue FoldedVOp = SimplifyVBinOp(N);
3310     if (FoldedVOp.getNode()) return FoldedVOp;
3311
3312     // fold (or x, 0) -> x, vector edition
3313     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3314       return N1;
3315     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3316       return N0;
3317
3318     // fold (or x, -1) -> -1, vector edition
3319     if (ISD::isBuildVectorAllOnes(N0.getNode()))
3320       return N0;
3321     if (ISD::isBuildVectorAllOnes(N1.getNode()))
3322       return N1;
3323
3324     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
3325     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
3326     // Do this only if the resulting shuffle is legal.
3327     if (isa<ShuffleVectorSDNode>(N0) &&
3328         isa<ShuffleVectorSDNode>(N1) &&
3329         // Avoid folding a node with illegal type.
3330         TLI.isTypeLegal(VT) &&
3331         N0->getOperand(1) == N1->getOperand(1) &&
3332         ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
3333       bool CanFold = true;
3334       unsigned NumElts = VT.getVectorNumElements();
3335       const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3336       const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3337       // We construct two shuffle masks:
3338       // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
3339       // and N1 as the second operand.
3340       // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
3341       // and N0 as the second operand.
3342       // We do this because OR is commutable and therefore there might be
3343       // two ways to fold this node into a shuffle.
3344       SmallVector<int,4> Mask1;
3345       SmallVector<int,4> Mask2;
3346
3347       for (unsigned i = 0; i != NumElts && CanFold; ++i) {
3348         int M0 = SV0->getMaskElt(i);
3349         int M1 = SV1->getMaskElt(i);
3350
3351         // Both shuffle indexes are undef. Propagate Undef.
3352         if (M0 < 0 && M1 < 0) {
3353           Mask1.push_back(M0);
3354           Mask2.push_back(M0);
3355           continue;
3356         }
3357
3358         if (M0 < 0 || M1 < 0 ||
3359             (M0 < (int)NumElts && M1 < (int)NumElts) ||
3360             (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
3361           CanFold = false;
3362           break;
3363         }
3364
3365         Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
3366         Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
3367       }
3368
3369       if (CanFold) {
3370         // Fold this sequence only if the resulting shuffle is 'legal'.
3371         if (TLI.isShuffleMaskLegal(Mask1, VT))
3372           return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
3373                                       N1->getOperand(0), &Mask1[0]);
3374         if (TLI.isShuffleMaskLegal(Mask2, VT))
3375           return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
3376                                       N0->getOperand(0), &Mask2[0]);
3377       }
3378     }
3379   }
3380
3381   // fold (or x, undef) -> -1
3382   if (!LegalOperations &&
3383       (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3384     EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3385     return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
3386   }
3387   // fold (or c1, c2) -> c1|c2
3388   if (N0C && N1C)
3389     return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C);
3390   // canonicalize constant to RHS
3391   if (N0C && !N1C)
3392     return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3393   // fold (or x, 0) -> x
3394   if (N1C && N1C->isNullValue())
3395     return N0;
3396   // fold (or x, -1) -> -1
3397   if (N1C && N1C->isAllOnesValue())
3398     return N1;
3399   // fold (or x, c) -> c iff (x & ~c) == 0
3400   if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3401     return N1;
3402
3403   // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3404   SDValue BSwap = MatchBSwapHWord(N, N0, N1);
3405   if (BSwap.getNode())
3406     return BSwap;
3407   BSwap = MatchBSwapHWordLow(N, N0, N1);
3408   if (BSwap.getNode())
3409     return BSwap;
3410
3411   // reassociate or
3412   SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1);
3413   if (ROR.getNode())
3414     return ROR;
3415   // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3416   // iff (c1 & c2) == 0.
3417   if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3418              isa<ConstantSDNode>(N0.getOperand(1))) {
3419     ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3420     if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3421       SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1);
3422       if (!COR.getNode())
3423         return SDValue();
3424       return DAG.getNode(ISD::AND, SDLoc(N), VT,
3425                          DAG.getNode(ISD::OR, SDLoc(N0), VT,
3426                                      N0.getOperand(0), N1), COR);
3427     }
3428   }
3429   // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3430   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3431     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3432     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3433
3434     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
3435         LL.getValueType().isInteger()) {
3436       // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3437       // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3438       if (cast<ConstantSDNode>(LR)->isNullValue() &&
3439           (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3440         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3441                                      LR.getValueType(), LL, RL);
3442         AddToWorklist(ORNode.getNode());
3443         return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
3444       }
3445       // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3446       // fold (or (setgt X, -1), (setgt Y  -1)) -> (setgt (and X, Y), -1)
3447       if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
3448           (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3449         SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3450                                       LR.getValueType(), LL, RL);
3451         AddToWorklist(ANDNode.getNode());
3452         return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
3453       }
3454     }
3455     // canonicalize equivalent to ll == rl
3456     if (LL == RR && LR == RL) {
3457       Op1 = ISD::getSetCCSwappedOperands(Op1);
3458       std::swap(RL, RR);
3459     }
3460     if (LL == RL && LR == RR) {
3461       bool isInteger = LL.getValueType().isInteger();
3462       ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3463       if (Result != ISD::SETCC_INVALID &&
3464           (!LegalOperations ||
3465            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3466             TLI.isOperationLegal(ISD::SETCC,
3467               getSetCCResultType(N0.getValueType())))))
3468         return DAG.getSetCC(SDLoc(N), N0.getValueType(),
3469                             LL, LR, Result);
3470     }
3471   }
3472
3473   // Simplify: (or (op x...), (op y...))  -> (op (or x, y))
3474   if (N0.getOpcode() == N1.getOpcode()) {
3475     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3476     if (Tmp.getNode()) return Tmp;
3477   }
3478
3479   // (or (and X, C1), (and Y, C2))  -> (and (or X, Y), C3) if possible.
3480   if (N0.getOpcode() == ISD::AND &&
3481       N1.getOpcode() == ISD::AND &&
3482       N0.getOperand(1).getOpcode() == ISD::Constant &&
3483       N1.getOperand(1).getOpcode() == ISD::Constant &&
3484       // Don't increase # computations.
3485       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3486     // We can only do this xform if we know that bits from X that are set in C2
3487     // but not in C1 are already zero.  Likewise for Y.
3488     const APInt &LHSMask =
3489       cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3490     const APInt &RHSMask =
3491       cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
3492
3493     if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3494         DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3495       SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3496                               N0.getOperand(0), N1.getOperand(0));
3497       return DAG.getNode(ISD::AND, SDLoc(N), VT, X,
3498                          DAG.getConstant(LHSMask | RHSMask, VT));
3499     }
3500   }
3501
3502   // See if this is some rotate idiom.
3503   if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3504     return SDValue(Rot, 0);
3505
3506   // Simplify the operands using demanded-bits information.
3507   if (!VT.isVector() &&
3508       SimplifyDemandedBits(SDValue(N, 0)))
3509     return SDValue(N, 0);
3510
3511   return SDValue();
3512 }
3513
3514 /// MatchRotateHalf - Match "(X shl/srl V1) & V2" where V2 may not be present.
3515 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3516   if (Op.getOpcode() == ISD::AND) {
3517     if (isa<ConstantSDNode>(Op.getOperand(1))) {
3518       Mask = Op.getOperand(1);
3519       Op = Op.getOperand(0);
3520     } else {
3521       return false;
3522     }
3523   }
3524
3525   if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3526     Shift = Op;
3527     return true;
3528   }
3529
3530   return false;
3531 }
3532
3533 // Return true if we can prove that, whenever Neg and Pos are both in the
3534 // range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos).  This means that
3535 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3536 //
3537 //     (or (shift1 X, Neg), (shift2 X, Pos))
3538 //
3539 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3540 // in direction shift1 by Neg.  The range [0, OpSize) means that we only need
3541 // to consider shift amounts with defined behavior.
3542 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) {
3543   // If OpSize is a power of 2 then:
3544   //
3545   //  (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1)
3546   //  (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize).
3547   //
3548   // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check
3549   // for the stronger condition:
3550   //
3551   //     Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1)    [A]
3552   //
3553   // for all Neg and Pos.  Since Neg & (OpSize - 1) == Neg' & (OpSize - 1)
3554   // we can just replace Neg with Neg' for the rest of the function.
3555   //
3556   // In other cases we check for the even stronger condition:
3557   //
3558   //     Neg == OpSize - Pos                                    [B]
3559   //
3560   // for all Neg and Pos.  Note that the (or ...) then invokes undefined
3561   // behavior if Pos == 0 (and consequently Neg == OpSize).
3562   //
3563   // We could actually use [A] whenever OpSize is a power of 2, but the
3564   // only extra cases that it would match are those uninteresting ones
3565   // where Neg and Pos are never in range at the same time.  E.g. for
3566   // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3567   // as well as (sub 32, Pos), but:
3568   //
3569   //     (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3570   //
3571   // always invokes undefined behavior for 32-bit X.
3572   //
3573   // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise.
3574   unsigned MaskLoBits = 0;
3575   if (Neg.getOpcode() == ISD::AND &&
3576       isPowerOf2_64(OpSize) &&
3577       Neg.getOperand(1).getOpcode() == ISD::Constant &&
3578       cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) {
3579     Neg = Neg.getOperand(0);
3580     MaskLoBits = Log2_64(OpSize);
3581   }
3582
3583   // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3584   if (Neg.getOpcode() != ISD::SUB)
3585     return 0;
3586   ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0));
3587   if (!NegC)
3588     return 0;
3589   SDValue NegOp1 = Neg.getOperand(1);
3590
3591   // On the RHS of [A], if Pos is Pos' & (OpSize - 1), just replace Pos with
3592   // Pos'.  The truncation is redundant for the purpose of the equality.
3593   if (MaskLoBits &&
3594       Pos.getOpcode() == ISD::AND &&
3595       Pos.getOperand(1).getOpcode() == ISD::Constant &&
3596       cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() == OpSize - 1)
3597     Pos = Pos.getOperand(0);
3598
3599   // The condition we need is now:
3600   //
3601   //     (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask
3602   //
3603   // If NegOp1 == Pos then we need:
3604   //
3605   //              OpSize & Mask == NegC & Mask
3606   //
3607   // (because "x & Mask" is a truncation and distributes through subtraction).
3608   APInt Width;
3609   if (Pos == NegOp1)
3610     Width = NegC->getAPIntValue();
3611   // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3612   // Then the condition we want to prove becomes:
3613   //
3614   //     (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask
3615   //
3616   // which, again because "x & Mask" is a truncation, becomes:
3617   //
3618   //                NegC & Mask == (OpSize - PosC) & Mask
3619   //              OpSize & Mask == (NegC + PosC) & Mask
3620   else if (Pos.getOpcode() == ISD::ADD &&
3621            Pos.getOperand(0) == NegOp1 &&
3622            Pos.getOperand(1).getOpcode() == ISD::Constant)
3623     Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() +
3624              NegC->getAPIntValue());
3625   else
3626     return false;
3627
3628   // Now we just need to check that OpSize & Mask == Width & Mask.
3629   if (MaskLoBits)
3630     // Opsize & Mask is 0 since Mask is Opsize - 1.
3631     return Width.getLoBits(MaskLoBits) == 0;
3632   return Width == OpSize;
3633 }
3634
3635 // A subroutine of MatchRotate used once we have found an OR of two opposite
3636 // shifts of Shifted.  If Neg == <operand size> - Pos then the OR reduces
3637 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3638 // former being preferred if supported.  InnerPos and InnerNeg are Pos and
3639 // Neg with outer conversions stripped away.
3640 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3641                                        SDValue Neg, SDValue InnerPos,
3642                                        SDValue InnerNeg, unsigned PosOpcode,
3643                                        unsigned NegOpcode, SDLoc DL) {
3644   // fold (or (shl x, (*ext y)),
3645   //          (srl x, (*ext (sub 32, y)))) ->
3646   //   (rotl x, y) or (rotr x, (sub 32, y))
3647   //
3648   // fold (or (shl x, (*ext (sub 32, y))),
3649   //          (srl x, (*ext y))) ->
3650   //   (rotr x, y) or (rotl x, (sub 32, y))
3651   EVT VT = Shifted.getValueType();
3652   if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) {
3653     bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3654     return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3655                        HasPos ? Pos : Neg).getNode();
3656   }
3657
3658   return nullptr;
3659 }
3660
3661 // MatchRotate - Handle an 'or' of two operands.  If this is one of the many
3662 // idioms for rotate, and if the target supports rotation instructions, generate
3663 // a rot[lr].
3664 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
3665   // Must be a legal type.  Expanded 'n promoted things won't work with rotates.
3666   EVT VT = LHS.getValueType();
3667   if (!TLI.isTypeLegal(VT)) return nullptr;
3668
3669   // The target must have at least one rotate flavor.
3670   bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3671   bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3672   if (!HasROTL && !HasROTR) return nullptr;
3673
3674   // Match "(X shl/srl V1) & V2" where V2 may not be present.
3675   SDValue LHSShift;   // The shift.
3676   SDValue LHSMask;    // AND value if any.
3677   if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3678     return nullptr; // Not part of a rotate.
3679
3680   SDValue RHSShift;   // The shift.
3681   SDValue RHSMask;    // AND value if any.
3682   if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3683     return nullptr; // Not part of a rotate.
3684
3685   if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3686     return nullptr;   // Not shifting the same value.
3687
3688   if (LHSShift.getOpcode() == RHSShift.getOpcode())
3689     return nullptr;   // Shifts must disagree.
3690
3691   // Canonicalize shl to left side in a shl/srl pair.
3692   if (RHSShift.getOpcode() == ISD::SHL) {
3693     std::swap(LHS, RHS);
3694     std::swap(LHSShift, RHSShift);
3695     std::swap(LHSMask , RHSMask );
3696   }
3697
3698   unsigned OpSizeInBits = VT.getSizeInBits();
3699   SDValue LHSShiftArg = LHSShift.getOperand(0);
3700   SDValue LHSShiftAmt = LHSShift.getOperand(1);
3701   SDValue RHSShiftArg = RHSShift.getOperand(0);
3702   SDValue RHSShiftAmt = RHSShift.getOperand(1);
3703
3704   // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3705   // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
3706   if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3707       RHSShiftAmt.getOpcode() == ISD::Constant) {
3708     uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3709     uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
3710     if ((LShVal + RShVal) != OpSizeInBits)
3711       return nullptr;
3712
3713     SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3714                               LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3715
3716     // If there is an AND of either shifted operand, apply it to the result.
3717     if (LHSMask.getNode() || RHSMask.getNode()) {
3718       APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
3719
3720       if (LHSMask.getNode()) {
3721         APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3722         Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
3723       }
3724       if (RHSMask.getNode()) {
3725         APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3726         Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
3727       }
3728
3729       Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT));
3730     }
3731
3732     return Rot.getNode();
3733   }
3734
3735   // If there is a mask here, and we have a variable shift, we can't be sure
3736   // that we're masking out the right stuff.
3737   if (LHSMask.getNode() || RHSMask.getNode())
3738     return nullptr;
3739
3740   // If the shift amount is sign/zext/any-extended just peel it off.
3741   SDValue LExtOp0 = LHSShiftAmt;
3742   SDValue RExtOp0 = RHSShiftAmt;
3743   if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3744        LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3745        LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3746        LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3747       (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3748        RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3749        RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3750        RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
3751     LExtOp0 = LHSShiftAmt.getOperand(0);
3752     RExtOp0 = RHSShiftAmt.getOperand(0);
3753   }
3754
3755   SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
3756                                    LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
3757   if (TryL)
3758     return TryL;
3759
3760   SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
3761                                    RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
3762   if (TryR)
3763     return TryR;
3764
3765   return nullptr;
3766 }
3767
3768 SDValue DAGCombiner::visitXOR(SDNode *N) {
3769   SDValue N0 = N->getOperand(0);
3770   SDValue N1 = N->getOperand(1);
3771   SDValue LHS, RHS, CC;
3772   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3773   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3774   EVT VT = N0.getValueType();
3775
3776   // fold vector ops
3777   if (VT.isVector()) {
3778     SDValue FoldedVOp = SimplifyVBinOp(N);
3779     if (FoldedVOp.getNode()) return FoldedVOp;
3780
3781     // fold (xor x, 0) -> x, vector edition
3782     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3783       return N1;
3784     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3785       return N0;
3786   }
3787
3788   // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3789   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3790     return DAG.getConstant(0, VT);
3791   // fold (xor x, undef) -> undef
3792   if (N0.getOpcode() == ISD::UNDEF)
3793     return N0;
3794   if (N1.getOpcode() == ISD::UNDEF)
3795     return N1;
3796   // fold (xor c1, c2) -> c1^c2
3797   if (N0C && N1C)
3798     return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
3799   // canonicalize constant to RHS
3800   if (N0C && !N1C)
3801     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
3802   // fold (xor x, 0) -> x
3803   if (N1C && N1C->isNullValue())
3804     return N0;
3805   // reassociate xor
3806   SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1);
3807   if (RXOR.getNode())
3808     return RXOR;
3809
3810   // fold !(x cc y) -> (x !cc y)
3811   if (N1C && N1C->getAPIntValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) {
3812     bool isInt = LHS.getValueType().isInteger();
3813     ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3814                                                isInt);
3815
3816     if (!LegalOperations ||
3817         TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
3818       switch (N0.getOpcode()) {
3819       default:
3820         llvm_unreachable("Unhandled SetCC Equivalent!");
3821       case ISD::SETCC:
3822         return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
3823       case ISD::SELECT_CC:
3824         return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
3825                                N0.getOperand(3), NotCC);
3826       }
3827     }
3828   }
3829
3830   // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
3831   if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
3832       N0.getNode()->hasOneUse() &&
3833       isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
3834     SDValue V = N0.getOperand(0);
3835     V = DAG.getNode(ISD::XOR, SDLoc(N0), V.getValueType(), V,
3836                     DAG.getConstant(1, V.getValueType()));
3837     AddToWorklist(V.getNode());
3838     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
3839   }
3840
3841   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
3842   if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
3843       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3844     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3845     if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
3846       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3847       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3848       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3849       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
3850       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3851     }
3852   }
3853   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
3854   if (N1C && N1C->isAllOnesValue() &&
3855       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3856     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3857     if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
3858       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3859       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3860       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3861       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
3862       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3863     }
3864   }
3865   // fold (xor (and x, y), y) -> (and (not x), y)
3866   if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3867       N0->getOperand(1) == N1) {
3868     SDValue X = N0->getOperand(0);
3869     SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
3870     AddToWorklist(NotX.getNode());
3871     return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
3872   }
3873   // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
3874   if (N1C && N0.getOpcode() == ISD::XOR) {
3875     ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
3876     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3877     if (N00C)
3878       return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(1),
3879                          DAG.getConstant(N1C->getAPIntValue() ^
3880                                          N00C->getAPIntValue(), VT));
3881     if (N01C)
3882       return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(0),
3883                          DAG.getConstant(N1C->getAPIntValue() ^
3884                                          N01C->getAPIntValue(), VT));
3885   }
3886   // fold (xor x, x) -> 0
3887   if (N0 == N1)
3888     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
3889
3890   // Simplify: xor (op x...), (op y...)  -> (op (xor x, y))
3891   if (N0.getOpcode() == N1.getOpcode()) {
3892     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3893     if (Tmp.getNode()) return Tmp;
3894   }
3895
3896   // Simplify the expression using non-local knowledge.
3897   if (!VT.isVector() &&
3898       SimplifyDemandedBits(SDValue(N, 0)))
3899     return SDValue(N, 0);
3900
3901   return SDValue();
3902 }
3903
3904 /// visitShiftByConstant - Handle transforms common to the three shifts, when
3905 /// the shift amount is a constant.
3906 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
3907   // We can't and shouldn't fold opaque constants.
3908   if (Amt->isOpaque())
3909     return SDValue();
3910
3911   SDNode *LHS = N->getOperand(0).getNode();
3912   if (!LHS->hasOneUse()) return SDValue();
3913
3914   // We want to pull some binops through shifts, so that we have (and (shift))
3915   // instead of (shift (and)), likewise for add, or, xor, etc.  This sort of
3916   // thing happens with address calculations, so it's important to canonicalize
3917   // it.
3918   bool HighBitSet = false;  // Can we transform this if the high bit is set?
3919
3920   switch (LHS->getOpcode()) {
3921   default: return SDValue();
3922   case ISD::OR:
3923   case ISD::XOR:
3924     HighBitSet = false; // We can only transform sra if the high bit is clear.
3925     break;
3926   case ISD::AND:
3927     HighBitSet = true;  // We can only transform sra if the high bit is set.
3928     break;
3929   case ISD::ADD:
3930     if (N->getOpcode() != ISD::SHL)
3931       return SDValue(); // only shl(add) not sr[al](add).
3932     HighBitSet = false; // We can only transform sra if the high bit is clear.
3933     break;
3934   }
3935
3936   // We require the RHS of the binop to be a constant and not opaque as well.
3937   ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
3938   if (!BinOpCst || BinOpCst->isOpaque()) return SDValue();
3939
3940   // FIXME: disable this unless the input to the binop is a shift by a constant.
3941   // If it is not a shift, it pessimizes some common cases like:
3942   //
3943   //    void foo(int *X, int i) { X[i & 1235] = 1; }
3944   //    int bar(int *X, int i) { return X[i & 255]; }
3945   SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
3946   if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
3947        BinOpLHSVal->getOpcode() != ISD::SRA &&
3948        BinOpLHSVal->getOpcode() != ISD::SRL) ||
3949       !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
3950     return SDValue();
3951
3952   EVT VT = N->getValueType(0);
3953
3954   // If this is a signed shift right, and the high bit is modified by the
3955   // logical operation, do not perform the transformation. The highBitSet
3956   // boolean indicates the value of the high bit of the constant which would
3957   // cause it to be modified for this operation.
3958   if (N->getOpcode() == ISD::SRA) {
3959     bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
3960     if (BinOpRHSSignSet != HighBitSet)
3961       return SDValue();
3962   }
3963
3964   if (!TLI.isDesirableToCommuteWithShift(LHS))
3965     return SDValue();
3966
3967   // Fold the constants, shifting the binop RHS by the shift amount.
3968   SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
3969                                N->getValueType(0),
3970                                LHS->getOperand(1), N->getOperand(1));
3971   assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
3972
3973   // Create the new shift.
3974   SDValue NewShift = DAG.getNode(N->getOpcode(),
3975                                  SDLoc(LHS->getOperand(0)),
3976                                  VT, LHS->getOperand(0), N->getOperand(1));
3977
3978   // Create the new binop.
3979   return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
3980 }
3981
3982 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
3983   assert(N->getOpcode() == ISD::TRUNCATE);
3984   assert(N->getOperand(0).getOpcode() == ISD::AND);
3985
3986   // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
3987   if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
3988     SDValue N01 = N->getOperand(0).getOperand(1);
3989
3990     if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
3991       EVT TruncVT = N->getValueType(0);
3992       SDValue N00 = N->getOperand(0).getOperand(0);
3993       APInt TruncC = N01C->getAPIntValue();
3994       TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
3995
3996       return DAG.getNode(ISD::AND, SDLoc(N), TruncVT,
3997                          DAG.getNode(ISD::TRUNCATE, SDLoc(N), TruncVT, N00),
3998                          DAG.getConstant(TruncC, TruncVT));
3999     }
4000   }
4001
4002   return SDValue();
4003 }
4004
4005 SDValue DAGCombiner::visitRotate(SDNode *N) {
4006   // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
4007   if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
4008       N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
4009     SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode());
4010     if (NewOp1.getNode())
4011       return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
4012                          N->getOperand(0), NewOp1);
4013   }
4014   return SDValue();
4015 }
4016
4017 SDValue DAGCombiner::visitSHL(SDNode *N) {
4018   SDValue N0 = N->getOperand(0);
4019   SDValue N1 = N->getOperand(1);
4020   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4021   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4022   EVT VT = N0.getValueType();
4023   unsigned OpSizeInBits = VT.getScalarSizeInBits();
4024
4025   // fold vector ops
4026   if (VT.isVector()) {
4027     SDValue FoldedVOp = SimplifyVBinOp(N);
4028     if (FoldedVOp.getNode()) return FoldedVOp;
4029
4030     BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
4031     // If setcc produces all-one true value then:
4032     // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
4033     if (N1CV && N1CV->isConstant()) {
4034       if (N0.getOpcode() == ISD::AND) {
4035         SDValue N00 = N0->getOperand(0);
4036         SDValue N01 = N0->getOperand(1);
4037         BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
4038
4039         if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
4040             TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
4041                 TargetLowering::ZeroOrNegativeOneBooleanContent) {
4042           SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, VT, N01CV, N1CV);
4043           if (C.getNode())
4044             return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
4045         }
4046       } else {
4047         N1C = isConstOrConstSplat(N1);
4048       }
4049     }
4050   }
4051
4052   // fold (shl c1, c2) -> c1<<c2
4053   if (N0C && N1C)
4054     return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
4055   // fold (shl 0, x) -> 0
4056   if (N0C && N0C->isNullValue())
4057     return N0;
4058   // fold (shl x, c >= size(x)) -> undef
4059   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4060     return DAG.getUNDEF(VT);
4061   // fold (shl x, 0) -> x
4062   if (N1C && N1C->isNullValue())
4063     return N0;
4064   // fold (shl undef, x) -> 0
4065   if (N0.getOpcode() == ISD::UNDEF)
4066     return DAG.getConstant(0, VT);
4067   // if (shl x, c) is known to be zero, return 0
4068   if (DAG.MaskedValueIsZero(SDValue(N, 0),
4069                             APInt::getAllOnesValue(OpSizeInBits)))
4070     return DAG.getConstant(0, VT);
4071   // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
4072   if (N1.getOpcode() == ISD::TRUNCATE &&
4073       N1.getOperand(0).getOpcode() == ISD::AND) {
4074     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4075     if (NewOp1.getNode())
4076       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
4077   }
4078
4079   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4080     return SDValue(N, 0);
4081
4082   // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
4083   if (N1C && N0.getOpcode() == ISD::SHL) {
4084     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4085       uint64_t c1 = N0C1->getZExtValue();
4086       uint64_t c2 = N1C->getZExtValue();
4087       if (c1 + c2 >= OpSizeInBits)
4088         return DAG.getConstant(0, VT);
4089       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4090                          DAG.getConstant(c1 + c2, N1.getValueType()));
4091     }
4092   }
4093
4094   // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4095   // For this to be valid, the second form must not preserve any of the bits
4096   // that are shifted out by the inner shift in the first form.  This means
4097   // the outer shift size must be >= the number of bits added by the ext.
4098   // As a corollary, we don't care what kind of ext it is.
4099   if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4100               N0.getOpcode() == ISD::ANY_EXTEND ||
4101               N0.getOpcode() == ISD::SIGN_EXTEND) &&
4102       N0.getOperand(0).getOpcode() == ISD::SHL) {
4103     SDValue N0Op0 = N0.getOperand(0);
4104     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4105       uint64_t c1 = N0Op0C1->getZExtValue();
4106       uint64_t c2 = N1C->getZExtValue();
4107       EVT InnerShiftVT = N0Op0.getValueType();
4108       uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4109       if (c2 >= OpSizeInBits - InnerShiftSize) {
4110         if (c1 + c2 >= OpSizeInBits)
4111           return DAG.getConstant(0, VT);
4112         return DAG.getNode(ISD::SHL, SDLoc(N0), VT,
4113                            DAG.getNode(N0.getOpcode(), SDLoc(N0), VT,
4114                                        N0Op0->getOperand(0)),
4115                            DAG.getConstant(c1 + c2, N1.getValueType()));
4116       }
4117     }
4118   }
4119
4120   // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4121   // Only fold this if the inner zext has no other uses to avoid increasing
4122   // the total number of instructions.
4123   if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
4124       N0.getOperand(0).getOpcode() == ISD::SRL) {
4125     SDValue N0Op0 = N0.getOperand(0);
4126     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4127       uint64_t c1 = N0Op0C1->getZExtValue();
4128       if (c1 < VT.getScalarSizeInBits()) {
4129         uint64_t c2 = N1C->getZExtValue();
4130         if (c1 == c2) {
4131           SDValue NewOp0 = N0.getOperand(0);
4132           EVT CountVT = NewOp0.getOperand(1).getValueType();
4133           SDValue NewSHL = DAG.getNode(ISD::SHL, SDLoc(N), NewOp0.getValueType(),
4134                                        NewOp0, DAG.getConstant(c2, CountVT));
4135           AddToWorklist(NewSHL.getNode());
4136           return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4137         }
4138       }
4139     }
4140   }
4141
4142   // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4143   //                               (and (srl x, (sub c1, c2), MASK)
4144   // Only fold this if the inner shift has no other uses -- if it does, folding
4145   // this will increase the total number of instructions.
4146   if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4147     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4148       uint64_t c1 = N0C1->getZExtValue();
4149       if (c1 < OpSizeInBits) {
4150         uint64_t c2 = N1C->getZExtValue();
4151         APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4152         SDValue Shift;
4153         if (c2 > c1) {
4154           Mask = Mask.shl(c2 - c1);
4155           Shift = DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4156                               DAG.getConstant(c2 - c1, N1.getValueType()));
4157         } else {
4158           Mask = Mask.lshr(c1 - c2);
4159           Shift = DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4160                               DAG.getConstant(c1 - c2, N1.getValueType()));
4161         }
4162         return DAG.getNode(ISD::AND, SDLoc(N0), VT, Shift,
4163                            DAG.getConstant(Mask, VT));
4164       }
4165     }
4166   }
4167   // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
4168   if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
4169     unsigned BitSize = VT.getScalarSizeInBits();
4170     SDValue HiBitsMask =
4171       DAG.getConstant(APInt::getHighBitsSet(BitSize,
4172                                             BitSize - N1C->getZExtValue()), VT);
4173     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4174                        HiBitsMask);
4175   }
4176
4177   if (N1C) {
4178     SDValue NewSHL = visitShiftByConstant(N, N1C);
4179     if (NewSHL.getNode())
4180       return NewSHL;
4181   }
4182
4183   return SDValue();
4184 }
4185
4186 SDValue DAGCombiner::visitSRA(SDNode *N) {
4187   SDValue N0 = N->getOperand(0);
4188   SDValue N1 = N->getOperand(1);
4189   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4190   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4191   EVT VT = N0.getValueType();
4192   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4193
4194   // fold vector ops
4195   if (VT.isVector()) {
4196     SDValue FoldedVOp = SimplifyVBinOp(N);
4197     if (FoldedVOp.getNode()) return FoldedVOp;
4198
4199     N1C = isConstOrConstSplat(N1);
4200   }
4201
4202   // fold (sra c1, c2) -> (sra c1, c2)
4203   if (N0C && N1C)
4204     return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
4205   // fold (sra 0, x) -> 0
4206   if (N0C && N0C->isNullValue())
4207     return N0;
4208   // fold (sra -1, x) -> -1
4209   if (N0C && N0C->isAllOnesValue())
4210     return N0;
4211   // fold (sra x, (setge c, size(x))) -> undef
4212   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4213     return DAG.getUNDEF(VT);
4214   // fold (sra x, 0) -> x
4215   if (N1C && N1C->isNullValue())
4216     return N0;
4217   // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4218   // sext_inreg.
4219   if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
4220     unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
4221     EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4222     if (VT.isVector())
4223       ExtVT = EVT::getVectorVT(*DAG.getContext(),
4224                                ExtVT, VT.getVectorNumElements());
4225     if ((!LegalOperations ||
4226          TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
4227       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
4228                          N0.getOperand(0), DAG.getValueType(ExtVT));
4229   }
4230
4231   // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
4232   if (N1C && N0.getOpcode() == ISD::SRA) {
4233     if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
4234       unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
4235       if (Sum >= OpSizeInBits)
4236         Sum = OpSizeInBits - 1;
4237       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0.getOperand(0),
4238                          DAG.getConstant(Sum, N1.getValueType()));
4239     }
4240   }
4241
4242   // fold (sra (shl X, m), (sub result_size, n))
4243   // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
4244   // result_size - n != m.
4245   // If truncate is free for the target sext(shl) is likely to result in better
4246   // code.
4247   if (N0.getOpcode() == ISD::SHL && N1C) {
4248     // Get the two constanst of the shifts, CN0 = m, CN = n.
4249     const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4250     if (N01C) {
4251       LLVMContext &Ctx = *DAG.getContext();
4252       // Determine what the truncate's result bitsize and type would be.
4253       EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4254
4255       if (VT.isVector())
4256         TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4257
4258       // Determine the residual right-shift amount.
4259       signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
4260
4261       // If the shift is not a no-op (in which case this should be just a sign
4262       // extend already), the truncated to type is legal, sign_extend is legal
4263       // on that type, and the truncate to that type is both legal and free,
4264       // perform the transform.
4265       if ((ShiftAmt > 0) &&
4266           TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4267           TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
4268           TLI.isTruncateFree(VT, TruncVT)) {
4269
4270           SDValue Amt = DAG.getConstant(ShiftAmt,
4271               getShiftAmountTy(N0.getOperand(0).getValueType()));
4272           SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), VT,
4273                                       N0.getOperand(0), Amt);
4274           SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), TruncVT,
4275                                       Shift);
4276           return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N),
4277                              N->getValueType(0), Trunc);
4278       }
4279     }
4280   }
4281
4282   // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
4283   if (N1.getOpcode() == ISD::TRUNCATE &&
4284       N1.getOperand(0).getOpcode() == ISD::AND) {
4285     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4286     if (NewOp1.getNode())
4287       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
4288   }
4289
4290   // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
4291   //      if c1 is equal to the number of bits the trunc removes
4292   if (N0.getOpcode() == ISD::TRUNCATE &&
4293       (N0.getOperand(0).getOpcode() == ISD::SRL ||
4294        N0.getOperand(0).getOpcode() == ISD::SRA) &&
4295       N0.getOperand(0).hasOneUse() &&
4296       N0.getOperand(0).getOperand(1).hasOneUse() &&
4297       N1C) {
4298     SDValue N0Op0 = N0.getOperand(0);
4299     if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4300       unsigned LargeShiftVal = LargeShift->getZExtValue();
4301       EVT LargeVT = N0Op0.getValueType();
4302
4303       if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4304         SDValue Amt =
4305           DAG.getConstant(LargeShiftVal + N1C->getZExtValue(),
4306                           getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4307         SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), LargeVT,
4308                                   N0Op0.getOperand(0), Amt);
4309         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, SRA);
4310       }
4311     }
4312   }
4313
4314   // Simplify, based on bits shifted out of the LHS.
4315   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4316     return SDValue(N, 0);
4317
4318
4319   // If the sign bit is known to be zero, switch this to a SRL.
4320   if (DAG.SignBitIsZero(N0))
4321     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
4322
4323   if (N1C) {
4324     SDValue NewSRA = visitShiftByConstant(N, N1C);
4325     if (NewSRA.getNode())
4326       return NewSRA;
4327   }
4328
4329   return SDValue();
4330 }
4331
4332 SDValue DAGCombiner::visitSRL(SDNode *N) {
4333   SDValue N0 = N->getOperand(0);
4334   SDValue N1 = N->getOperand(1);
4335   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4336   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4337   EVT VT = N0.getValueType();
4338   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4339
4340   // fold vector ops
4341   if (VT.isVector()) {
4342     SDValue FoldedVOp = SimplifyVBinOp(N);
4343     if (FoldedVOp.getNode()) return FoldedVOp;
4344
4345     N1C = isConstOrConstSplat(N1);
4346   }
4347
4348   // fold (srl c1, c2) -> c1 >>u c2
4349   if (N0C && N1C)
4350     return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C);
4351   // fold (srl 0, x) -> 0
4352   if (N0C && N0C->isNullValue())
4353     return N0;
4354   // fold (srl x, c >= size(x)) -> undef
4355   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4356     return DAG.getUNDEF(VT);
4357   // fold (srl x, 0) -> x
4358   if (N1C && N1C->isNullValue())
4359     return N0;
4360   // if (srl x, c) is known to be zero, return 0
4361   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4362                                    APInt::getAllOnesValue(OpSizeInBits)))
4363     return DAG.getConstant(0, VT);
4364
4365   // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
4366   if (N1C && N0.getOpcode() == ISD::SRL) {
4367     if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
4368       uint64_t c1 = N01C->getZExtValue();
4369       uint64_t c2 = N1C->getZExtValue();
4370       if (c1 + c2 >= OpSizeInBits)
4371         return DAG.getConstant(0, VT);
4372       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4373                          DAG.getConstant(c1 + c2, N1.getValueType()));
4374     }
4375   }
4376
4377   // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4378   if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4379       N0.getOperand(0).getOpcode() == ISD::SRL &&
4380       isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4381     uint64_t c1 =
4382       cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4383     uint64_t c2 = N1C->getZExtValue();
4384     EVT InnerShiftVT = N0.getOperand(0).getValueType();
4385     EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4386     uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
4387     // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4388     if (c1 + OpSizeInBits == InnerShiftSize) {
4389       if (c1 + c2 >= InnerShiftSize)
4390         return DAG.getConstant(0, VT);
4391       return DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT,
4392                          DAG.getNode(ISD::SRL, SDLoc(N0), InnerShiftVT,
4393                                      N0.getOperand(0)->getOperand(0),
4394                                      DAG.getConstant(c1 + c2, ShiftCountVT)));
4395     }
4396   }
4397
4398   // fold (srl (shl x, c), c) -> (and x, cst2)
4399   if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4400     unsigned BitSize = N0.getScalarValueSizeInBits();
4401     if (BitSize <= 64) {
4402       uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4403       return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4404                          DAG.getConstant(~0ULL >> ShAmt, VT));
4405     }
4406   }
4407
4408   // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4409   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4410     // Shifting in all undef bits?
4411     EVT SmallVT = N0.getOperand(0).getValueType();
4412     unsigned BitSize = SmallVT.getScalarSizeInBits();
4413     if (N1C->getZExtValue() >= BitSize)
4414       return DAG.getUNDEF(VT);
4415
4416     if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4417       uint64_t ShiftAmt = N1C->getZExtValue();
4418       SDValue SmallShift = DAG.getNode(ISD::SRL, SDLoc(N0), SmallVT,
4419                                        N0.getOperand(0),
4420                           DAG.getConstant(ShiftAmt, getShiftAmountTy(SmallVT)));
4421       AddToWorklist(SmallShift.getNode());
4422       APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
4423       return DAG.getNode(ISD::AND, SDLoc(N), VT,
4424                          DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, SmallShift),
4425                          DAG.getConstant(Mask, VT));
4426     }
4427   }
4428
4429   // fold (srl (sra X, Y), 31) -> (srl X, 31).  This srl only looks at the sign
4430   // bit, which is unmodified by sra.
4431   if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
4432     if (N0.getOpcode() == ISD::SRA)
4433       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4434   }
4435
4436   // fold (srl (ctlz x), "5") -> x  iff x has one bit set (the low bit).
4437   if (N1C && N0.getOpcode() == ISD::CTLZ &&
4438       N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
4439     APInt KnownZero, KnownOne;
4440     DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne);
4441
4442     // If any of the input bits are KnownOne, then the input couldn't be all
4443     // zeros, thus the result of the srl will always be zero.
4444     if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
4445
4446     // If all of the bits input the to ctlz node are known to be zero, then
4447     // the result of the ctlz is "32" and the result of the shift is one.
4448     APInt UnknownBits = ~KnownZero;
4449     if (UnknownBits == 0) return DAG.getConstant(1, VT);
4450
4451     // Otherwise, check to see if there is exactly one bit input to the ctlz.
4452     if ((UnknownBits & (UnknownBits - 1)) == 0) {
4453       // Okay, we know that only that the single bit specified by UnknownBits
4454       // could be set on input to the CTLZ node. If this bit is set, the SRL
4455       // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4456       // to an SRL/XOR pair, which is likely to simplify more.
4457       unsigned ShAmt = UnknownBits.countTrailingZeros();
4458       SDValue Op = N0.getOperand(0);
4459
4460       if (ShAmt) {
4461         Op = DAG.getNode(ISD::SRL, SDLoc(N0), VT, Op,
4462                   DAG.getConstant(ShAmt, getShiftAmountTy(Op.getValueType())));
4463         AddToWorklist(Op.getNode());
4464       }
4465
4466       return DAG.getNode(ISD::XOR, SDLoc(N), VT,
4467                          Op, DAG.getConstant(1, VT));
4468     }
4469   }
4470
4471   // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4472   if (N1.getOpcode() == ISD::TRUNCATE &&
4473       N1.getOperand(0).getOpcode() == ISD::AND) {
4474     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4475     if (NewOp1.getNode())
4476       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
4477   }
4478
4479   // fold operands of srl based on knowledge that the low bits are not
4480   // demanded.
4481   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4482     return SDValue(N, 0);
4483
4484   if (N1C) {
4485     SDValue NewSRL = visitShiftByConstant(N, N1C);
4486     if (NewSRL.getNode())
4487       return NewSRL;
4488   }
4489
4490   // Attempt to convert a srl of a load into a narrower zero-extending load.
4491   SDValue NarrowLoad = ReduceLoadWidth(N);
4492   if (NarrowLoad.getNode())
4493     return NarrowLoad;
4494
4495   // Here is a common situation. We want to optimize:
4496   //
4497   //   %a = ...
4498   //   %b = and i32 %a, 2
4499   //   %c = srl i32 %b, 1
4500   //   brcond i32 %c ...
4501   //
4502   // into
4503   //
4504   //   %a = ...
4505   //   %b = and %a, 2
4506   //   %c = setcc eq %b, 0
4507   //   brcond %c ...
4508   //
4509   // However when after the source operand of SRL is optimized into AND, the SRL
4510   // itself may not be optimized further. Look for it and add the BRCOND into
4511   // the worklist.
4512   if (N->hasOneUse()) {
4513     SDNode *Use = *N->use_begin();
4514     if (Use->getOpcode() == ISD::BRCOND)
4515       AddToWorklist(Use);
4516     else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4517       // Also look pass the truncate.
4518       Use = *Use->use_begin();
4519       if (Use->getOpcode() == ISD::BRCOND)
4520         AddToWorklist(Use);
4521     }
4522   }
4523
4524   return SDValue();
4525 }
4526
4527 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4528   SDValue N0 = N->getOperand(0);
4529   EVT VT = N->getValueType(0);
4530
4531   // fold (ctlz c1) -> c2
4532   if (isa<ConstantSDNode>(N0))
4533     return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
4534   return SDValue();
4535 }
4536
4537 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4538   SDValue N0 = N->getOperand(0);
4539   EVT VT = N->getValueType(0);
4540
4541   // fold (ctlz_zero_undef c1) -> c2
4542   if (isa<ConstantSDNode>(N0))
4543     return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4544   return SDValue();
4545 }
4546
4547 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4548   SDValue N0 = N->getOperand(0);
4549   EVT VT = N->getValueType(0);
4550
4551   // fold (cttz c1) -> c2
4552   if (isa<ConstantSDNode>(N0))
4553     return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
4554   return SDValue();
4555 }
4556
4557 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4558   SDValue N0 = N->getOperand(0);
4559   EVT VT = N->getValueType(0);
4560
4561   // fold (cttz_zero_undef c1) -> c2
4562   if (isa<ConstantSDNode>(N0))
4563     return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4564   return SDValue();
4565 }
4566
4567 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4568   SDValue N0 = N->getOperand(0);
4569   EVT VT = N->getValueType(0);
4570
4571   // fold (ctpop c1) -> c2
4572   if (isa<ConstantSDNode>(N0))
4573     return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
4574   return SDValue();
4575 }
4576
4577 SDValue DAGCombiner::visitSELECT(SDNode *N) {
4578   SDValue N0 = N->getOperand(0);
4579   SDValue N1 = N->getOperand(1);
4580   SDValue N2 = N->getOperand(2);
4581   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4582   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4583   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
4584   EVT VT = N->getValueType(0);
4585   EVT VT0 = N0.getValueType();
4586
4587   // fold (select C, X, X) -> X
4588   if (N1 == N2)
4589     return N1;
4590   // fold (select true, X, Y) -> X
4591   if (N0C && !N0C->isNullValue())
4592     return N1;
4593   // fold (select false, X, Y) -> Y
4594   if (N0C && N0C->isNullValue())
4595     return N2;
4596   // fold (select C, 1, X) -> (or C, X)
4597   if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
4598     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4599   // fold (select C, 0, 1) -> (xor C, 1)
4600   // We can't do this reliably if integer based booleans have different contents
4601   // to floating point based booleans. This is because we can't tell whether we
4602   // have an integer-based boolean or a floating-point-based boolean unless we
4603   // can find the SETCC that produced it and inspect its operands. This is
4604   // fairly easy if C is the SETCC node, but it can potentially be
4605   // undiscoverable (or not reasonably discoverable). For example, it could be
4606   // in another basic block or it could require searching a complicated
4607   // expression.
4608   if (VT.isInteger() &&
4609       (VT0 == MVT::i1 || (VT0.isInteger() &&
4610                           TLI.getBooleanContents(false, false) ==
4611                               TLI.getBooleanContents(false, true) &&
4612                           TLI.getBooleanContents(false, false) ==
4613                               TargetLowering::ZeroOrOneBooleanContent)) &&
4614       N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
4615     SDValue XORNode;
4616     if (VT == VT0)
4617       return DAG.getNode(ISD::XOR, SDLoc(N), VT0,
4618                          N0, DAG.getConstant(1, VT0));
4619     XORNode = DAG.getNode(ISD::XOR, SDLoc(N0), VT0,
4620                           N0, DAG.getConstant(1, VT0));
4621     AddToWorklist(XORNode.getNode());
4622     if (VT.bitsGT(VT0))
4623       return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4624     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
4625   }
4626   // fold (select C, 0, X) -> (and (not C), X)
4627   if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
4628     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4629     AddToWorklist(NOTNode.getNode());
4630     return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
4631   }
4632   // fold (select C, X, 1) -> (or (not C), X)
4633   if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
4634     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4635     AddToWorklist(NOTNode.getNode());
4636     return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
4637   }
4638   // fold (select C, X, 0) -> (and C, X)
4639   if (VT == MVT::i1 && N2C && N2C->isNullValue())
4640     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4641   // fold (select X, X, Y) -> (or X, Y)
4642   // fold (select X, 1, Y) -> (or X, Y)
4643   if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
4644     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4645   // fold (select X, Y, X) -> (and X, Y)
4646   // fold (select X, Y, 0) -> (and X, Y)
4647   if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
4648     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4649
4650   // If we can fold this based on the true/false value, do so.
4651   if (SimplifySelectOps(N, N1, N2))
4652     return SDValue(N, 0);  // Don't revisit N.
4653
4654   // fold selects based on a setcc into other things, such as min/max/abs
4655   if (N0.getOpcode() == ISD::SETCC) {
4656     if ((!LegalOperations &&
4657          TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
4658         TLI.isOperationLegal(ISD::SELECT_CC, VT))
4659       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
4660                          N0.getOperand(0), N0.getOperand(1),
4661                          N1, N2, N0.getOperand(2));
4662     return SimplifySelect(SDLoc(N), N0, N1, N2);
4663   }
4664
4665   return SDValue();
4666 }
4667
4668 static
4669 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
4670   SDLoc DL(N);
4671   EVT LoVT, HiVT;
4672   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
4673
4674   // Split the inputs.
4675   SDValue Lo, Hi, LL, LH, RL, RH;
4676   std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
4677   std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
4678
4679   Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
4680   Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
4681
4682   return std::make_pair(Lo, Hi);
4683 }
4684
4685 // This function assumes all the vselect's arguments are CONCAT_VECTOR
4686 // nodes and that the condition is a BV of ConstantSDNodes (or undefs).
4687 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
4688   SDLoc dl(N);
4689   SDValue Cond = N->getOperand(0);
4690   SDValue LHS = N->getOperand(1);
4691   SDValue RHS = N->getOperand(2);
4692   EVT VT = N->getValueType(0);
4693   int NumElems = VT.getVectorNumElements();
4694   assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
4695          RHS.getOpcode() == ISD::CONCAT_VECTORS &&
4696          Cond.getOpcode() == ISD::BUILD_VECTOR);
4697
4698   // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about
4699   // binary ones here.
4700   if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2)
4701     return SDValue();
4702
4703   // We're sure we have an even number of elements due to the
4704   // concat_vectors we have as arguments to vselect.
4705   // Skip BV elements until we find one that's not an UNDEF
4706   // After we find an UNDEF element, keep looping until we get to half the
4707   // length of the BV and see if all the non-undef nodes are the same.
4708   ConstantSDNode *BottomHalf = nullptr;
4709   for (int i = 0; i < NumElems / 2; ++i) {
4710     if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
4711       continue;
4712
4713     if (BottomHalf == nullptr)
4714       BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
4715     else if (Cond->getOperand(i).getNode() != BottomHalf)
4716       return SDValue();
4717   }
4718
4719   // Do the same for the second half of the BuildVector
4720   ConstantSDNode *TopHalf = nullptr;
4721   for (int i = NumElems / 2; i < NumElems; ++i) {
4722     if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
4723       continue;
4724
4725     if (TopHalf == nullptr)
4726       TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
4727     else if (Cond->getOperand(i).getNode() != TopHalf)
4728       return SDValue();
4729   }
4730
4731   assert(TopHalf && BottomHalf &&
4732          "One half of the selector was all UNDEFs and the other was all the "
4733          "same value. This should have been addressed before this function.");
4734   return DAG.getNode(
4735       ISD::CONCAT_VECTORS, dl, VT,
4736       BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
4737       TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
4738 }
4739
4740 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
4741   SDValue N0 = N->getOperand(0);
4742   SDValue N1 = N->getOperand(1);
4743   SDValue N2 = N->getOperand(2);
4744   SDLoc DL(N);
4745
4746   // Canonicalize integer abs.
4747   // vselect (setg[te] X,  0),  X, -X ->
4748   // vselect (setgt    X, -1),  X, -X ->
4749   // vselect (setl[te] X,  0), -X,  X ->
4750   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
4751   if (N0.getOpcode() == ISD::SETCC) {
4752     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4753     ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4754     bool isAbs = false;
4755     bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
4756
4757     if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
4758          (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
4759         N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
4760       isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
4761     else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
4762              N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
4763       isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
4764
4765     if (isAbs) {
4766       EVT VT = LHS.getValueType();
4767       SDValue Shift = DAG.getNode(
4768           ISD::SRA, DL, VT, LHS,
4769           DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, VT));
4770       SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
4771       AddToWorklist(Shift.getNode());
4772       AddToWorklist(Add.getNode());
4773       return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
4774     }
4775   }
4776
4777   // If the VSELECT result requires splitting and the mask is provided by a
4778   // SETCC, then split both nodes and its operands before legalization. This
4779   // prevents the type legalizer from unrolling SETCC into scalar comparisons
4780   // and enables future optimizations (e.g. min/max pattern matching on X86).
4781   if (N0.getOpcode() == ISD::SETCC) {
4782     EVT VT = N->getValueType(0);
4783
4784     // Check if any splitting is required.
4785     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
4786         TargetLowering::TypeSplitVector)
4787       return SDValue();
4788
4789     SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
4790     std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
4791     std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
4792     std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
4793
4794     Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
4795     Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
4796
4797     // Add the new VSELECT nodes to the work list in case they need to be split
4798     // again.
4799     AddToWorklist(Lo.getNode());
4800     AddToWorklist(Hi.getNode());
4801
4802     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
4803   }
4804
4805   // Fold (vselect (build_vector all_ones), N1, N2) -> N1
4806   if (ISD::isBuildVectorAllOnes(N0.getNode()))
4807     return N1;
4808   // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
4809   if (ISD::isBuildVectorAllZeros(N0.getNode()))
4810     return N2;
4811
4812   // The ConvertSelectToConcatVector function is assuming both the above
4813   // checks for (vselect (build_vector all{ones,zeros) ...) have been made
4814   // and addressed.
4815   if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
4816       N2.getOpcode() == ISD::CONCAT_VECTORS &&
4817       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
4818     SDValue CV = ConvertSelectToConcatVector(N, DAG);
4819     if (CV.getNode())
4820       return CV;
4821   }
4822
4823   return SDValue();
4824 }
4825
4826 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
4827   SDValue N0 = N->getOperand(0);
4828   SDValue N1 = N->getOperand(1);
4829   SDValue N2 = N->getOperand(2);
4830   SDValue N3 = N->getOperand(3);
4831   SDValue N4 = N->getOperand(4);
4832   ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
4833
4834   // fold select_cc lhs, rhs, x, x, cc -> x
4835   if (N2 == N3)
4836     return N2;
4837
4838   // Determine if the condition we're dealing with is constant
4839   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
4840                               N0, N1, CC, SDLoc(N), false);
4841   if (SCC.getNode()) {
4842     AddToWorklist(SCC.getNode());
4843
4844     if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
4845       if (!SCCC->isNullValue())
4846         return N2;    // cond always true -> true val
4847       else
4848         return N3;    // cond always false -> false val
4849     }
4850
4851     // Fold to a simpler select_cc
4852     if (SCC.getOpcode() == ISD::SETCC)
4853       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
4854                          SCC.getOperand(0), SCC.getOperand(1), N2, N3,
4855                          SCC.getOperand(2));
4856   }
4857
4858   // If we can fold this based on the true/false value, do so.
4859   if (SimplifySelectOps(N, N2, N3))
4860     return SDValue(N, 0);  // Don't revisit N.
4861
4862   // fold select_cc into other things, such as min/max/abs
4863   return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
4864 }
4865
4866 SDValue DAGCombiner::visitSETCC(SDNode *N) {
4867   return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
4868                        cast<CondCodeSDNode>(N->getOperand(2))->get(),
4869                        SDLoc(N));
4870 }
4871
4872 // tryToFoldExtendOfConstant - Try to fold a sext/zext/aext
4873 // dag node into a ConstantSDNode or a build_vector of constants.
4874 // This function is called by the DAGCombiner when visiting sext/zext/aext
4875 // dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
4876 // Vector extends are not folded if operations are legal; this is to
4877 // avoid introducing illegal build_vector dag nodes.
4878 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
4879                                          SelectionDAG &DAG, bool LegalTypes,
4880                                          bool LegalOperations) {
4881   unsigned Opcode = N->getOpcode();
4882   SDValue N0 = N->getOperand(0);
4883   EVT VT = N->getValueType(0);
4884
4885   assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
4886          Opcode == ISD::ANY_EXTEND) && "Expected EXTEND dag node in input!");
4887
4888   // fold (sext c1) -> c1
4889   // fold (zext c1) -> c1
4890   // fold (aext c1) -> c1
4891   if (isa<ConstantSDNode>(N0))
4892     return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
4893
4894   // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
4895   // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
4896   // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
4897   EVT SVT = VT.getScalarType();
4898   if (!(VT.isVector() &&
4899       (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
4900       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
4901     return nullptr;
4902
4903   // We can fold this node into a build_vector.
4904   unsigned VTBits = SVT.getSizeInBits();
4905   unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
4906   unsigned ShAmt = VTBits - EVTBits;
4907   SmallVector<SDValue, 8> Elts;
4908   unsigned NumElts = N0->getNumOperands();
4909   SDLoc DL(N);
4910
4911   for (unsigned i=0; i != NumElts; ++i) {
4912     SDValue Op = N0->getOperand(i);
4913     if (Op->getOpcode() == ISD::UNDEF) {
4914       Elts.push_back(DAG.getUNDEF(SVT));
4915       continue;
4916     }
4917
4918     ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
4919     const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
4920     if (Opcode == ISD::SIGN_EXTEND)
4921       Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
4922                                      SVT));
4923     else
4924       Elts.push_back(DAG.getConstant(C.shl(ShAmt).lshr(ShAmt).getZExtValue(),
4925                                      SVT));
4926   }
4927
4928   return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts).getNode();
4929 }
4930
4931 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
4932 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
4933 // transformation. Returns true if extension are possible and the above
4934 // mentioned transformation is profitable.
4935 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
4936                                     unsigned ExtOpc,
4937                                     SmallVectorImpl<SDNode *> &ExtendNodes,
4938                                     const TargetLowering &TLI) {
4939   bool HasCopyToRegUses = false;
4940   bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
4941   for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
4942                             UE = N0.getNode()->use_end();
4943        UI != UE; ++UI) {
4944     SDNode *User = *UI;
4945     if (User == N)
4946       continue;
4947     if (UI.getUse().getResNo() != N0.getResNo())
4948       continue;
4949     // FIXME: Only extend SETCC N, N and SETCC N, c for now.
4950     if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
4951       ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
4952       if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
4953         // Sign bits will be lost after a zext.
4954         return false;
4955       bool Add = false;
4956       for (unsigned i = 0; i != 2; ++i) {
4957         SDValue UseOp = User->getOperand(i);
4958         if (UseOp == N0)
4959           continue;
4960         if (!isa<ConstantSDNode>(UseOp))
4961           return false;
4962         Add = true;
4963       }
4964       if (Add)
4965         ExtendNodes.push_back(User);
4966       continue;
4967     }
4968     // If truncates aren't free and there are users we can't
4969     // extend, it isn't worthwhile.
4970     if (!isTruncFree)
4971       return false;
4972     // Remember if this value is live-out.
4973     if (User->getOpcode() == ISD::CopyToReg)
4974       HasCopyToRegUses = true;
4975   }
4976
4977   if (HasCopyToRegUses) {
4978     bool BothLiveOut = false;
4979     for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
4980          UI != UE; ++UI) {
4981       SDUse &Use = UI.getUse();
4982       if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
4983         BothLiveOut = true;
4984         break;
4985       }
4986     }
4987     if (BothLiveOut)
4988       // Both unextended and extended values are live out. There had better be
4989       // a good reason for the transformation.
4990       return ExtendNodes.size();
4991   }
4992   return true;
4993 }
4994
4995 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
4996                                   SDValue Trunc, SDValue ExtLoad, SDLoc DL,
4997                                   ISD::NodeType ExtType) {
4998   // Extend SetCC uses if necessary.
4999   for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
5000     SDNode *SetCC = SetCCs[i];
5001     SmallVector<SDValue, 4> Ops;
5002
5003     for (unsigned j = 0; j != 2; ++j) {
5004       SDValue SOp = SetCC->getOperand(j);
5005       if (SOp == Trunc)
5006         Ops.push_back(ExtLoad);
5007       else
5008         Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
5009     }
5010
5011     Ops.push_back(SetCC->getOperand(2));
5012     CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
5013   }
5014 }
5015
5016 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
5017   SDValue N0 = N->getOperand(0);
5018   EVT VT = N->getValueType(0);
5019
5020   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5021                                               LegalOperations))
5022     return SDValue(Res, 0);
5023
5024   // fold (sext (sext x)) -> (sext x)
5025   // fold (sext (aext x)) -> (sext x)
5026   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5027     return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
5028                        N0.getOperand(0));
5029
5030   if (N0.getOpcode() == ISD::TRUNCATE) {
5031     // fold (sext (truncate (load x))) -> (sext (smaller load x))
5032     // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
5033     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5034     if (NarrowLoad.getNode()) {
5035       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5036       if (NarrowLoad.getNode() != N0.getNode()) {
5037         CombineTo(N0.getNode(), NarrowLoad);
5038         // CombineTo deleted the truncate, if needed, but not what's under it.
5039         AddToWorklist(oye);
5040       }
5041       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5042     }
5043
5044     // See if the value being truncated is already sign extended.  If so, just
5045     // eliminate the trunc/sext pair.
5046     SDValue Op = N0.getOperand(0);
5047     unsigned OpBits   = Op.getValueType().getScalarType().getSizeInBits();
5048     unsigned MidBits  = N0.getValueType().getScalarType().getSizeInBits();
5049     unsigned DestBits = VT.getScalarType().getSizeInBits();
5050     unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
5051
5052     if (OpBits == DestBits) {
5053       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
5054       // bits, it is already ready.
5055       if (NumSignBits > DestBits-MidBits)
5056         return Op;
5057     } else if (OpBits < DestBits) {
5058       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
5059       // bits, just sext from i32.
5060       if (NumSignBits > OpBits-MidBits)
5061         return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
5062     } else {
5063       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
5064       // bits, just truncate to i32.
5065       if (NumSignBits > OpBits-MidBits)
5066         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5067     }
5068
5069     // fold (sext (truncate x)) -> (sextinreg x).
5070     if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
5071                                                  N0.getValueType())) {
5072       if (OpBits < DestBits)
5073         Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
5074       else if (OpBits > DestBits)
5075         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
5076       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
5077                          DAG.getValueType(N0.getValueType()));
5078     }
5079   }
5080
5081   // fold (sext (load x)) -> (sext (truncate (sextload x)))
5082   // None of the supported targets knows how to perform load and sign extend
5083   // on vectors in one instruction.  We only perform this transformation on
5084   // scalars.
5085   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5086       ISD::isUNINDEXEDLoad(N0.getNode()) &&
5087       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5088        TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()))) {
5089     bool DoXform = true;
5090     SmallVector<SDNode*, 4> SetCCs;
5091     if (!N0.hasOneUse())
5092       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
5093     if (DoXform) {
5094       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5095       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5096                                        LN0->getChain(),
5097                                        LN0->getBasePtr(), N0.getValueType(),
5098                                        LN0->getMemOperand());
5099       CombineTo(N, ExtLoad);
5100       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5101                                   N0.getValueType(), ExtLoad);
5102       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5103       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5104                       ISD::SIGN_EXTEND);
5105       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5106     }
5107   }
5108
5109   // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
5110   // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
5111   if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5112       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5113     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5114     EVT MemVT = LN0->getMemoryVT();
5115     if ((!LegalOperations && !LN0->isVolatile()) ||
5116         TLI.isLoadExtLegal(ISD::SEXTLOAD, MemVT)) {
5117       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5118                                        LN0->getChain(),
5119                                        LN0->getBasePtr(), MemVT,
5120                                        LN0->getMemOperand());
5121       CombineTo(N, ExtLoad);
5122       CombineTo(N0.getNode(),
5123                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5124                             N0.getValueType(), ExtLoad),
5125                 ExtLoad.getValue(1));
5126       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5127     }
5128   }
5129
5130   // fold (sext (and/or/xor (load x), cst)) ->
5131   //      (and/or/xor (sextload x), (sext cst))
5132   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5133        N0.getOpcode() == ISD::XOR) &&
5134       isa<LoadSDNode>(N0.getOperand(0)) &&
5135       N0.getOperand(1).getOpcode() == ISD::Constant &&
5136       TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()) &&
5137       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5138     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5139     if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
5140       bool DoXform = true;
5141       SmallVector<SDNode*, 4> SetCCs;
5142       if (!N0.hasOneUse())
5143         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
5144                                           SetCCs, TLI);
5145       if (DoXform) {
5146         SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
5147                                          LN0->getChain(), LN0->getBasePtr(),
5148                                          LN0->getMemoryVT(),
5149                                          LN0->getMemOperand());
5150         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5151         Mask = Mask.sext(VT.getSizeInBits());
5152         SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5153                                   ExtLoad, DAG.getConstant(Mask, VT));
5154         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5155                                     SDLoc(N0.getOperand(0)),
5156                                     N0.getOperand(0).getValueType(), ExtLoad);
5157         CombineTo(N, And);
5158         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5159         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5160                         ISD::SIGN_EXTEND);
5161         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5162       }
5163     }
5164   }
5165
5166   if (N0.getOpcode() == ISD::SETCC) {
5167     EVT N0VT = N0.getOperand(0).getValueType();
5168     // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
5169     // Only do this before legalize for now.
5170     if (VT.isVector() && !LegalOperations &&
5171         TLI.getBooleanContents(N0VT) ==
5172             TargetLowering::ZeroOrNegativeOneBooleanContent) {
5173       // On some architectures (such as SSE/NEON/etc) the SETCC result type is
5174       // of the same size as the compared operands. Only optimize sext(setcc())
5175       // if this is the case.
5176       EVT SVT = getSetCCResultType(N0VT);
5177
5178       // We know that the # elements of the results is the same as the
5179       // # elements of the compare (and the # elements of the compare result
5180       // for that matter).  Check to see that they are the same size.  If so,
5181       // we know that the element size of the sext'd result matches the
5182       // element size of the compare operands.
5183       if (VT.getSizeInBits() == SVT.getSizeInBits())
5184         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5185                              N0.getOperand(1),
5186                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
5187
5188       // If the desired elements are smaller or larger than the source
5189       // elements we can use a matching integer vector type and then
5190       // truncate/sign extend
5191       EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5192       if (SVT == MatchingVectorType) {
5193         SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
5194                                N0.getOperand(0), N0.getOperand(1),
5195                                cast<CondCodeSDNode>(N0.getOperand(2))->get());
5196         return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
5197       }
5198     }
5199
5200     // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
5201     unsigned ElementWidth = VT.getScalarType().getSizeInBits();
5202     SDValue NegOne =
5203       DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT);
5204     SDValue SCC =
5205       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5206                        NegOne, DAG.getConstant(0, VT),
5207                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5208     if (SCC.getNode()) return SCC;
5209
5210     if (!VT.isVector()) {
5211       EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
5212       if (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, SetCCVT)) {
5213         SDLoc DL(N);
5214         ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5215         SDValue SetCC = DAG.getSetCC(DL,
5216                                      SetCCVT,
5217                                      N0.getOperand(0), N0.getOperand(1), CC);
5218         EVT SelectVT = getSetCCResultType(VT);
5219         return DAG.getSelect(DL, VT,
5220                              DAG.getSExtOrTrunc(SetCC, DL, SelectVT),
5221                              NegOne, DAG.getConstant(0, VT));
5222
5223       }
5224     }
5225   }
5226
5227   // fold (sext x) -> (zext x) if the sign bit is known zero.
5228   if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
5229       DAG.SignBitIsZero(N0))
5230     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
5231
5232   return SDValue();
5233 }
5234
5235 // isTruncateOf - If N is a truncate of some other value, return true, record
5236 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
5237 // This function computes KnownZero to avoid a duplicated call to
5238 // computeKnownBits in the caller.
5239 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
5240                          APInt &KnownZero) {
5241   APInt KnownOne;
5242   if (N->getOpcode() == ISD::TRUNCATE) {
5243     Op = N->getOperand(0);
5244     DAG.computeKnownBits(Op, KnownZero, KnownOne);
5245     return true;
5246   }
5247
5248   if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
5249       cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
5250     return false;
5251
5252   SDValue Op0 = N->getOperand(0);
5253   SDValue Op1 = N->getOperand(1);
5254   assert(Op0.getValueType() == Op1.getValueType());
5255
5256   ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0);
5257   ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
5258   if (COp0 && COp0->isNullValue())
5259     Op = Op1;
5260   else if (COp1 && COp1->isNullValue())
5261     Op = Op0;
5262   else
5263     return false;
5264
5265   DAG.computeKnownBits(Op, KnownZero, KnownOne);
5266
5267   if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
5268     return false;
5269
5270   return true;
5271 }
5272
5273 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
5274   SDValue N0 = N->getOperand(0);
5275   EVT VT = N->getValueType(0);
5276
5277   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5278                                               LegalOperations))
5279     return SDValue(Res, 0);
5280
5281   // fold (zext (zext x)) -> (zext x)
5282   // fold (zext (aext x)) -> (zext x)
5283   if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5284     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
5285                        N0.getOperand(0));
5286
5287   // fold (zext (truncate x)) -> (zext x) or
5288   //      (zext (truncate x)) -> (truncate x)
5289   // This is valid when the truncated bits of x are already zero.
5290   // FIXME: We should extend this to work for vectors too.
5291   SDValue Op;
5292   APInt KnownZero;
5293   if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
5294     APInt TruncatedBits =
5295       (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
5296       APInt(Op.getValueSizeInBits(), 0) :
5297       APInt::getBitsSet(Op.getValueSizeInBits(),
5298                         N0.getValueSizeInBits(),
5299                         std::min(Op.getValueSizeInBits(),
5300                                  VT.getSizeInBits()));
5301     if (TruncatedBits == (KnownZero & TruncatedBits)) {
5302       if (VT.bitsGT(Op.getValueType()))
5303         return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
5304       if (VT.bitsLT(Op.getValueType()))
5305         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5306
5307       return Op;
5308     }
5309   }
5310
5311   // fold (zext (truncate (load x))) -> (zext (smaller load x))
5312   // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
5313   if (N0.getOpcode() == ISD::TRUNCATE) {
5314     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5315     if (NarrowLoad.getNode()) {
5316       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5317       if (NarrowLoad.getNode() != N0.getNode()) {
5318         CombineTo(N0.getNode(), NarrowLoad);
5319         // CombineTo deleted the truncate, if needed, but not what's under it.
5320         AddToWorklist(oye);
5321       }
5322       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5323     }
5324   }
5325
5326   // fold (zext (truncate x)) -> (and x, mask)
5327   if (N0.getOpcode() == ISD::TRUNCATE &&
5328       (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
5329
5330     // fold (zext (truncate (load x))) -> (zext (smaller load x))
5331     // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
5332     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5333     if (NarrowLoad.getNode()) {
5334       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5335       if (NarrowLoad.getNode() != N0.getNode()) {
5336         CombineTo(N0.getNode(), NarrowLoad);
5337         // CombineTo deleted the truncate, if needed, but not what's under it.
5338         AddToWorklist(oye);
5339       }
5340       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5341     }
5342
5343     SDValue Op = N0.getOperand(0);
5344     if (Op.getValueType().bitsLT(VT)) {
5345       Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
5346       AddToWorklist(Op.getNode());
5347     } else if (Op.getValueType().bitsGT(VT)) {
5348       Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5349       AddToWorklist(Op.getNode());
5350     }
5351     return DAG.getZeroExtendInReg(Op, SDLoc(N),
5352                                   N0.getValueType().getScalarType());
5353   }
5354
5355   // Fold (zext (and (trunc x), cst)) -> (and x, cst),
5356   // if either of the casts is not free.
5357   if (N0.getOpcode() == ISD::AND &&
5358       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5359       N0.getOperand(1).getOpcode() == ISD::Constant &&
5360       (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5361                            N0.getValueType()) ||
5362        !TLI.isZExtFree(N0.getValueType(), VT))) {
5363     SDValue X = N0.getOperand(0).getOperand(0);
5364     if (X.getValueType().bitsLT(VT)) {
5365       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
5366     } else if (X.getValueType().bitsGT(VT)) {
5367       X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
5368     }
5369     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5370     Mask = Mask.zext(VT.getSizeInBits());
5371     return DAG.getNode(ISD::AND, SDLoc(N), VT,
5372                        X, DAG.getConstant(Mask, VT));
5373   }
5374
5375   // fold (zext (load x)) -> (zext (truncate (zextload x)))
5376   // None of the supported targets knows how to perform load and vector_zext
5377   // on vectors in one instruction.  We only perform this transformation on
5378   // scalars.
5379   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5380       ISD::isUNINDEXEDLoad(N0.getNode()) &&
5381       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5382        TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()))) {
5383     bool DoXform = true;
5384     SmallVector<SDNode*, 4> SetCCs;
5385     if (!N0.hasOneUse())
5386       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
5387     if (DoXform) {
5388       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5389       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5390                                        LN0->getChain(),
5391                                        LN0->getBasePtr(), N0.getValueType(),
5392                                        LN0->getMemOperand());
5393       CombineTo(N, ExtLoad);
5394       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5395                                   N0.getValueType(), ExtLoad);
5396       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5397
5398       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5399                       ISD::ZERO_EXTEND);
5400       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5401     }
5402   }
5403
5404   // fold (zext (and/or/xor (load x), cst)) ->
5405   //      (and/or/xor (zextload x), (zext cst))
5406   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5407        N0.getOpcode() == ISD::XOR) &&
5408       isa<LoadSDNode>(N0.getOperand(0)) &&
5409       N0.getOperand(1).getOpcode() == ISD::Constant &&
5410       TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()) &&
5411       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5412     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5413     if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
5414       bool DoXform = true;
5415       SmallVector<SDNode*, 4> SetCCs;
5416       if (!N0.hasOneUse())
5417         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
5418                                           SetCCs, TLI);
5419       if (DoXform) {
5420         SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
5421                                          LN0->getChain(), LN0->getBasePtr(),
5422                                          LN0->getMemoryVT(),
5423                                          LN0->getMemOperand());
5424         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5425         Mask = Mask.zext(VT.getSizeInBits());
5426         SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5427                                   ExtLoad, DAG.getConstant(Mask, VT));
5428         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5429                                     SDLoc(N0.getOperand(0)),
5430                                     N0.getOperand(0).getValueType(), ExtLoad);
5431         CombineTo(N, And);
5432         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5433         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5434                         ISD::ZERO_EXTEND);
5435         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5436       }
5437     }
5438   }
5439
5440   // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
5441   // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
5442   if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5443       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5444     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5445     EVT MemVT = LN0->getMemoryVT();
5446     if ((!LegalOperations && !LN0->isVolatile()) ||
5447         TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT)) {
5448       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5449                                        LN0->getChain(),
5450                                        LN0->getBasePtr(), MemVT,
5451                                        LN0->getMemOperand());
5452       CombineTo(N, ExtLoad);
5453       CombineTo(N0.getNode(),
5454                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
5455                             ExtLoad),
5456                 ExtLoad.getValue(1));
5457       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5458     }
5459   }
5460
5461   if (N0.getOpcode() == ISD::SETCC) {
5462     if (!LegalOperations && VT.isVector() &&
5463         N0.getValueType().getVectorElementType() == MVT::i1) {
5464       EVT N0VT = N0.getOperand(0).getValueType();
5465       if (getSetCCResultType(N0VT) == N0.getValueType())
5466         return SDValue();
5467
5468       // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
5469       // Only do this before legalize for now.
5470       EVT EltVT = VT.getVectorElementType();
5471       SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
5472                                     DAG.getConstant(1, EltVT));
5473       if (VT.getSizeInBits() == N0VT.getSizeInBits())
5474         // We know that the # elements of the results is the same as the
5475         // # elements of the compare (and the # elements of the compare result
5476         // for that matter).  Check to see that they are the same size.  If so,
5477         // we know that the element size of the sext'd result matches the
5478         // element size of the compare operands.
5479         return DAG.getNode(ISD::AND, SDLoc(N), VT,
5480                            DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5481                                          N0.getOperand(1),
5482                                  cast<CondCodeSDNode>(N0.getOperand(2))->get()),
5483                            DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
5484                                        OneOps));
5485
5486       // If the desired elements are smaller or larger than the source
5487       // elements we can use a matching integer vector type and then
5488       // truncate/sign extend
5489       EVT MatchingElementType =
5490         EVT::getIntegerVT(*DAG.getContext(),
5491                           N0VT.getScalarType().getSizeInBits());
5492       EVT MatchingVectorType =
5493         EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
5494                          N0VT.getVectorNumElements());
5495       SDValue VsetCC =
5496         DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5497                       N0.getOperand(1),
5498                       cast<CondCodeSDNode>(N0.getOperand(2))->get());
5499       return DAG.getNode(ISD::AND, SDLoc(N), VT,
5500                          DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT),
5501                          DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, OneOps));
5502     }
5503
5504     // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5505     SDValue SCC =
5506       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5507                        DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5508                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5509     if (SCC.getNode()) return SCC;
5510   }
5511
5512   // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
5513   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
5514       isa<ConstantSDNode>(N0.getOperand(1)) &&
5515       N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
5516       N0.hasOneUse()) {
5517     SDValue ShAmt = N0.getOperand(1);
5518     unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
5519     if (N0.getOpcode() == ISD::SHL) {
5520       SDValue InnerZExt = N0.getOperand(0);
5521       // If the original shl may be shifting out bits, do not perform this
5522       // transformation.
5523       unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
5524         InnerZExt.getOperand(0).getValueType().getSizeInBits();
5525       if (ShAmtVal > KnownZeroBits)
5526         return SDValue();
5527     }
5528
5529     SDLoc DL(N);
5530
5531     // Ensure that the shift amount is wide enough for the shifted value.
5532     if (VT.getSizeInBits() >= 256)
5533       ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
5534
5535     return DAG.getNode(N0.getOpcode(), DL, VT,
5536                        DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
5537                        ShAmt);
5538   }
5539
5540   return SDValue();
5541 }
5542
5543 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
5544   SDValue N0 = N->getOperand(0);
5545   EVT VT = N->getValueType(0);
5546
5547   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5548                                               LegalOperations))
5549     return SDValue(Res, 0);
5550
5551   // fold (aext (aext x)) -> (aext x)
5552   // fold (aext (zext x)) -> (zext x)
5553   // fold (aext (sext x)) -> (sext x)
5554   if (N0.getOpcode() == ISD::ANY_EXTEND  ||
5555       N0.getOpcode() == ISD::ZERO_EXTEND ||
5556       N0.getOpcode() == ISD::SIGN_EXTEND)
5557     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
5558
5559   // fold (aext (truncate (load x))) -> (aext (smaller load x))
5560   // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
5561   if (N0.getOpcode() == ISD::TRUNCATE) {
5562     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5563     if (NarrowLoad.getNode()) {
5564       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5565       if (NarrowLoad.getNode() != N0.getNode()) {
5566         CombineTo(N0.getNode(), NarrowLoad);
5567         // CombineTo deleted the truncate, if needed, but not what's under it.
5568         AddToWorklist(oye);
5569       }
5570       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5571     }
5572   }
5573
5574   // fold (aext (truncate x))
5575   if (N0.getOpcode() == ISD::TRUNCATE) {
5576     SDValue TruncOp = N0.getOperand(0);
5577     if (TruncOp.getValueType() == VT)
5578       return TruncOp; // x iff x size == zext size.
5579     if (TruncOp.getValueType().bitsGT(VT))
5580       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
5581     return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
5582   }
5583
5584   // Fold (aext (and (trunc x), cst)) -> (and x, cst)
5585   // if the trunc is not free.
5586   if (N0.getOpcode() == ISD::AND &&
5587       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5588       N0.getOperand(1).getOpcode() == ISD::Constant &&
5589       !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5590                           N0.getValueType())) {
5591     SDValue X = N0.getOperand(0).getOperand(0);
5592     if (X.getValueType().bitsLT(VT)) {
5593       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
5594     } else if (X.getValueType().bitsGT(VT)) {
5595       X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
5596     }
5597     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5598     Mask = Mask.zext(VT.getSizeInBits());
5599     return DAG.getNode(ISD::AND, SDLoc(N), VT,
5600                        X, DAG.getConstant(Mask, VT));
5601   }
5602
5603   // fold (aext (load x)) -> (aext (truncate (extload x)))
5604   // None of the supported targets knows how to perform load and any_ext
5605   // on vectors in one instruction.  We only perform this transformation on
5606   // scalars.
5607   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5608       ISD::isUNINDEXEDLoad(N0.getNode()) &&
5609       TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType())) {
5610     bool DoXform = true;
5611     SmallVector<SDNode*, 4> SetCCs;
5612     if (!N0.hasOneUse())
5613       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
5614     if (DoXform) {
5615       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5616       SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
5617                                        LN0->getChain(),
5618                                        LN0->getBasePtr(), N0.getValueType(),
5619                                        LN0->getMemOperand());
5620       CombineTo(N, ExtLoad);
5621       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5622                                   N0.getValueType(), ExtLoad);
5623       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5624       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5625                       ISD::ANY_EXTEND);
5626       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5627     }
5628   }
5629
5630   // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
5631   // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
5632   // fold (aext ( extload x)) -> (aext (truncate (extload  x)))
5633   if (N0.getOpcode() == ISD::LOAD &&
5634       !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5635       N0.hasOneUse()) {
5636     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5637     ISD::LoadExtType ExtType = LN0->getExtensionType();
5638     EVT MemVT = LN0->getMemoryVT();
5639     if (!LegalOperations || TLI.isLoadExtLegal(ExtType, MemVT)) {
5640       SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
5641                                        VT, LN0->getChain(), LN0->getBasePtr(),
5642                                        MemVT, LN0->getMemOperand());
5643       CombineTo(N, ExtLoad);
5644       CombineTo(N0.getNode(),
5645                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5646                             N0.getValueType(), ExtLoad),
5647                 ExtLoad.getValue(1));
5648       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5649     }
5650   }
5651
5652   if (N0.getOpcode() == ISD::SETCC) {
5653     // For vectors:
5654     // aext(setcc) -> vsetcc
5655     // aext(setcc) -> truncate(vsetcc)
5656     // aext(setcc) -> aext(vsetcc)
5657     // Only do this before legalize for now.
5658     if (VT.isVector() && !LegalOperations) {
5659       EVT N0VT = N0.getOperand(0).getValueType();
5660         // We know that the # elements of the results is the same as the
5661         // # elements of the compare (and the # elements of the compare result
5662         // for that matter).  Check to see that they are the same size.  If so,
5663         // we know that the element size of the sext'd result matches the
5664         // element size of the compare operands.
5665       if (VT.getSizeInBits() == N0VT.getSizeInBits())
5666         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5667                              N0.getOperand(1),
5668                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
5669       // If the desired elements are smaller or larger than the source
5670       // elements we can use a matching integer vector type and then
5671       // truncate/any extend
5672       else {
5673         EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5674         SDValue VsetCC =
5675           DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5676                         N0.getOperand(1),
5677                         cast<CondCodeSDNode>(N0.getOperand(2))->get());
5678         return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
5679       }
5680     }
5681
5682     // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5683     SDValue SCC =
5684       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5685                        DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5686                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5687     if (SCC.getNode())
5688       return SCC;
5689   }
5690
5691   return SDValue();
5692 }
5693
5694 /// GetDemandedBits - See if the specified operand can be simplified with the
5695 /// knowledge that only the bits specified by Mask are used.  If so, return the
5696 /// simpler operand, otherwise return a null SDValue.
5697 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
5698   switch (V.getOpcode()) {
5699   default: break;
5700   case ISD::Constant: {
5701     const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
5702     assert(CV && "Const value should be ConstSDNode.");
5703     const APInt &CVal = CV->getAPIntValue();
5704     APInt NewVal = CVal & Mask;
5705     if (NewVal != CVal)
5706       return DAG.getConstant(NewVal, V.getValueType());
5707     break;
5708   }
5709   case ISD::OR:
5710   case ISD::XOR:
5711     // If the LHS or RHS don't contribute bits to the or, drop them.
5712     if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
5713       return V.getOperand(1);
5714     if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
5715       return V.getOperand(0);
5716     break;
5717   case ISD::SRL:
5718     // Only look at single-use SRLs.
5719     if (!V.getNode()->hasOneUse())
5720       break;
5721     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
5722       // See if we can recursively simplify the LHS.
5723       unsigned Amt = RHSC->getZExtValue();
5724
5725       // Watch out for shift count overflow though.
5726       if (Amt >= Mask.getBitWidth()) break;
5727       APInt NewMask = Mask << Amt;
5728       SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
5729       if (SimplifyLHS.getNode())
5730         return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
5731                            SimplifyLHS, V.getOperand(1));
5732     }
5733   }
5734   return SDValue();
5735 }
5736
5737 /// ReduceLoadWidth - If the result of a wider load is shifted to right of N
5738 /// bits and then truncated to a narrower type and where N is a multiple
5739 /// of number of bits of the narrower type, transform it to a narrower load
5740 /// from address + N / num of bits of new type. If the result is to be
5741 /// extended, also fold the extension to form a extending load.
5742 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
5743   unsigned Opc = N->getOpcode();
5744
5745   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
5746   SDValue N0 = N->getOperand(0);
5747   EVT VT = N->getValueType(0);
5748   EVT ExtVT = VT;
5749
5750   // This transformation isn't valid for vector loads.
5751   if (VT.isVector())
5752     return SDValue();
5753
5754   // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
5755   // extended to VT.
5756   if (Opc == ISD::SIGN_EXTEND_INREG) {
5757     ExtType = ISD::SEXTLOAD;
5758     ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
5759   } else if (Opc == ISD::SRL) {
5760     // Another special-case: SRL is basically zero-extending a narrower value.
5761     ExtType = ISD::ZEXTLOAD;
5762     N0 = SDValue(N, 0);
5763     ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
5764     if (!N01) return SDValue();
5765     ExtVT = EVT::getIntegerVT(*DAG.getContext(),
5766                               VT.getSizeInBits() - N01->getZExtValue());
5767   }
5768   if (LegalOperations && !TLI.isLoadExtLegal(ExtType, ExtVT))
5769     return SDValue();
5770
5771   unsigned EVTBits = ExtVT.getSizeInBits();
5772
5773   // Do not generate loads of non-round integer types since these can
5774   // be expensive (and would be wrong if the type is not byte sized).
5775   if (!ExtVT.isRound())
5776     return SDValue();
5777
5778   unsigned ShAmt = 0;
5779   if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
5780     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5781       ShAmt = N01->getZExtValue();
5782       // Is the shift amount a multiple of size of VT?
5783       if ((ShAmt & (EVTBits-1)) == 0) {
5784         N0 = N0.getOperand(0);
5785         // Is the load width a multiple of size of VT?
5786         if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
5787           return SDValue();
5788       }
5789
5790       // At this point, we must have a load or else we can't do the transform.
5791       if (!isa<LoadSDNode>(N0)) return SDValue();
5792
5793       // Because a SRL must be assumed to *need* to zero-extend the high bits
5794       // (as opposed to anyext the high bits), we can't combine the zextload
5795       // lowering of SRL and an sextload.
5796       if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
5797         return SDValue();
5798
5799       // If the shift amount is larger than the input type then we're not
5800       // accessing any of the loaded bytes.  If the load was a zextload/extload
5801       // then the result of the shift+trunc is zero/undef (handled elsewhere).
5802       if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
5803         return SDValue();
5804     }
5805   }
5806
5807   // If the load is shifted left (and the result isn't shifted back right),
5808   // we can fold the truncate through the shift.
5809   unsigned ShLeftAmt = 0;
5810   if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
5811       ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
5812     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5813       ShLeftAmt = N01->getZExtValue();
5814       N0 = N0.getOperand(0);
5815     }
5816   }
5817
5818   // If we haven't found a load, we can't narrow it.  Don't transform one with
5819   // multiple uses, this would require adding a new load.
5820   if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
5821     return SDValue();
5822
5823   // Don't change the width of a volatile load.
5824   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5825   if (LN0->isVolatile())
5826     return SDValue();
5827
5828   // Verify that we are actually reducing a load width here.
5829   if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
5830     return SDValue();
5831
5832   // For the transform to be legal, the load must produce only two values
5833   // (the value loaded and the chain).  Don't transform a pre-increment
5834   // load, for example, which produces an extra value.  Otherwise the
5835   // transformation is not equivalent, and the downstream logic to replace
5836   // uses gets things wrong.
5837   if (LN0->getNumValues() > 2)
5838     return SDValue();
5839
5840   // If the load that we're shrinking is an extload and we're not just
5841   // discarding the extension we can't simply shrink the load. Bail.
5842   // TODO: It would be possible to merge the extensions in some cases.
5843   if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
5844       LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
5845     return SDValue();
5846
5847   EVT PtrType = N0.getOperand(1).getValueType();
5848
5849   if (PtrType == MVT::Untyped || PtrType.isExtended())
5850     // It's not possible to generate a constant of extended or untyped type.
5851     return SDValue();
5852
5853   // For big endian targets, we need to adjust the offset to the pointer to
5854   // load the correct bytes.
5855   if (TLI.isBigEndian()) {
5856     unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
5857     unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
5858     ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
5859   }
5860
5861   uint64_t PtrOff = ShAmt / 8;
5862   unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
5863   SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0),
5864                                PtrType, LN0->getBasePtr(),
5865                                DAG.getConstant(PtrOff, PtrType));
5866   AddToWorklist(NewPtr.getNode());
5867
5868   SDValue Load;
5869   if (ExtType == ISD::NON_EXTLOAD)
5870     Load =  DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
5871                         LN0->getPointerInfo().getWithOffset(PtrOff),
5872                         LN0->isVolatile(), LN0->isNonTemporal(),
5873                         LN0->isInvariant(), NewAlign, LN0->getAAInfo());
5874   else
5875     Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
5876                           LN0->getPointerInfo().getWithOffset(PtrOff),
5877                           ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
5878                           LN0->isInvariant(), NewAlign, LN0->getAAInfo());
5879
5880   // Replace the old load's chain with the new load's chain.
5881   WorklistRemover DeadNodes(*this);
5882   DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
5883
5884   // Shift the result left, if we've swallowed a left shift.
5885   SDValue Result = Load;
5886   if (ShLeftAmt != 0) {
5887     EVT ShImmTy = getShiftAmountTy(Result.getValueType());
5888     if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
5889       ShImmTy = VT;
5890     // If the shift amount is as large as the result size (but, presumably,
5891     // no larger than the source) then the useful bits of the result are
5892     // zero; we can't simply return the shortened shift, because the result
5893     // of that operation is undefined.
5894     if (ShLeftAmt >= VT.getSizeInBits())
5895       Result = DAG.getConstant(0, VT);
5896     else
5897       Result = DAG.getNode(ISD::SHL, SDLoc(N0), VT,
5898                           Result, DAG.getConstant(ShLeftAmt, ShImmTy));
5899   }
5900
5901   // Return the new loaded value.
5902   return Result;
5903 }
5904
5905 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
5906   SDValue N0 = N->getOperand(0);
5907   SDValue N1 = N->getOperand(1);
5908   EVT VT = N->getValueType(0);
5909   EVT EVT = cast<VTSDNode>(N1)->getVT();
5910   unsigned VTBits = VT.getScalarType().getSizeInBits();
5911   unsigned EVTBits = EVT.getScalarType().getSizeInBits();
5912
5913   // fold (sext_in_reg c1) -> c1
5914   if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
5915     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
5916
5917   // If the input is already sign extended, just drop the extension.
5918   if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
5919     return N0;
5920
5921   // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
5922   if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
5923       EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
5924     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5925                        N0.getOperand(0), N1);
5926
5927   // fold (sext_in_reg (sext x)) -> (sext x)
5928   // fold (sext_in_reg (aext x)) -> (sext x)
5929   // if x is small enough.
5930   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
5931     SDValue N00 = N0.getOperand(0);
5932     if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
5933         (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
5934       return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
5935   }
5936
5937   // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
5938   if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
5939     return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
5940
5941   // fold operands of sext_in_reg based on knowledge that the top bits are not
5942   // demanded.
5943   if (SimplifyDemandedBits(SDValue(N, 0)))
5944     return SDValue(N, 0);
5945
5946   // fold (sext_in_reg (load x)) -> (smaller sextload x)
5947   // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
5948   SDValue NarrowLoad = ReduceLoadWidth(N);
5949   if (NarrowLoad.getNode())
5950     return NarrowLoad;
5951
5952   // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
5953   // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
5954   // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
5955   if (N0.getOpcode() == ISD::SRL) {
5956     if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
5957       if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
5958         // We can turn this into an SRA iff the input to the SRL is already sign
5959         // extended enough.
5960         unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
5961         if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
5962           return DAG.getNode(ISD::SRA, SDLoc(N), VT,
5963                              N0.getOperand(0), N0.getOperand(1));
5964       }
5965   }
5966
5967   // fold (sext_inreg (extload x)) -> (sextload x)
5968   if (ISD::isEXTLoad(N0.getNode()) &&
5969       ISD::isUNINDEXEDLoad(N0.getNode()) &&
5970       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5971       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5972        TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5973     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5974     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5975                                      LN0->getChain(),
5976                                      LN0->getBasePtr(), EVT,
5977                                      LN0->getMemOperand());
5978     CombineTo(N, ExtLoad);
5979     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5980     AddToWorklist(ExtLoad.getNode());
5981     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5982   }
5983   // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
5984   if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5985       N0.hasOneUse() &&
5986       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5987       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5988        TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5989     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5990     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5991                                      LN0->getChain(),
5992                                      LN0->getBasePtr(), EVT,
5993                                      LN0->getMemOperand());
5994     CombineTo(N, ExtLoad);
5995     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5996     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5997   }
5998
5999   // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
6000   if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
6001     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
6002                                        N0.getOperand(1), false);
6003     if (BSwap.getNode())
6004       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6005                          BSwap, N1);
6006   }
6007
6008   // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs
6009   // into a build_vector.
6010   if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
6011     SmallVector<SDValue, 8> Elts;
6012     unsigned NumElts = N0->getNumOperands();
6013     unsigned ShAmt = VTBits - EVTBits;
6014
6015     for (unsigned i = 0; i != NumElts; ++i) {
6016       SDValue Op = N0->getOperand(i);
6017       if (Op->getOpcode() == ISD::UNDEF) {
6018         Elts.push_back(Op);
6019         continue;
6020       }
6021
6022       ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
6023       const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
6024       Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
6025                                      Op.getValueType()));
6026     }
6027
6028     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Elts);
6029   }
6030
6031   return SDValue();
6032 }
6033
6034 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
6035   SDValue N0 = N->getOperand(0);
6036   EVT VT = N->getValueType(0);
6037   bool isLE = TLI.isLittleEndian();
6038
6039   // noop truncate
6040   if (N0.getValueType() == N->getValueType(0))
6041     return N0;
6042   // fold (truncate c1) -> c1
6043   if (isa<ConstantSDNode>(N0))
6044     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
6045   // fold (truncate (truncate x)) -> (truncate x)
6046   if (N0.getOpcode() == ISD::TRUNCATE)
6047     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6048   // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
6049   if (N0.getOpcode() == ISD::ZERO_EXTEND ||
6050       N0.getOpcode() == ISD::SIGN_EXTEND ||
6051       N0.getOpcode() == ISD::ANY_EXTEND) {
6052     if (N0.getOperand(0).getValueType().bitsLT(VT))
6053       // if the source is smaller than the dest, we still need an extend
6054       return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
6055                          N0.getOperand(0));
6056     if (N0.getOperand(0).getValueType().bitsGT(VT))
6057       // if the source is larger than the dest, than we just need the truncate
6058       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6059     // if the source and dest are the same type, we can drop both the extend
6060     // and the truncate.
6061     return N0.getOperand(0);
6062   }
6063
6064   // Fold extract-and-trunc into a narrow extract. For example:
6065   //   i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
6066   //   i32 y = TRUNCATE(i64 x)
6067   //        -- becomes --
6068   //   v16i8 b = BITCAST (v2i64 val)
6069   //   i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
6070   //
6071   // Note: We only run this optimization after type legalization (which often
6072   // creates this pattern) and before operation legalization after which
6073   // we need to be more careful about the vector instructions that we generate.
6074   if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6075       LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
6076
6077     EVT VecTy = N0.getOperand(0).getValueType();
6078     EVT ExTy = N0.getValueType();
6079     EVT TrTy = N->getValueType(0);
6080
6081     unsigned NumElem = VecTy.getVectorNumElements();
6082     unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
6083
6084     EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
6085     assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
6086
6087     SDValue EltNo = N0->getOperand(1);
6088     if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
6089       int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
6090       EVT IndexTy = TLI.getVectorIdxTy();
6091       int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
6092
6093       SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
6094                               NVT, N0.getOperand(0));
6095
6096       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
6097                          SDLoc(N), TrTy, V,
6098                          DAG.getConstant(Index, IndexTy));
6099     }
6100   }
6101
6102   // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
6103   if (N0.getOpcode() == ISD::SELECT) {
6104     EVT SrcVT = N0.getValueType();
6105     if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
6106         TLI.isTruncateFree(SrcVT, VT)) {
6107       SDLoc SL(N0);
6108       SDValue Cond = N0.getOperand(0);
6109       SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
6110       SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
6111       return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
6112     }
6113   }
6114
6115   // Fold a series of buildvector, bitcast, and truncate if possible.
6116   // For example fold
6117   //   (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
6118   //   (2xi32 (buildvector x, y)).
6119   if (Level == AfterLegalizeVectorOps && VT.isVector() &&
6120       N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
6121       N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
6122       N0.getOperand(0).hasOneUse()) {
6123
6124     SDValue BuildVect = N0.getOperand(0);
6125     EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
6126     EVT TruncVecEltTy = VT.getVectorElementType();
6127
6128     // Check that the element types match.
6129     if (BuildVectEltTy == TruncVecEltTy) {
6130       // Now we only need to compute the offset of the truncated elements.
6131       unsigned BuildVecNumElts =  BuildVect.getNumOperands();
6132       unsigned TruncVecNumElts = VT.getVectorNumElements();
6133       unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
6134
6135       assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
6136              "Invalid number of elements");
6137
6138       SmallVector<SDValue, 8> Opnds;
6139       for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
6140         Opnds.push_back(BuildVect.getOperand(i));
6141
6142       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
6143     }
6144   }
6145
6146   // See if we can simplify the input to this truncate through knowledge that
6147   // only the low bits are being used.
6148   // For example "trunc (or (shl x, 8), y)" // -> trunc y
6149   // Currently we only perform this optimization on scalars because vectors
6150   // may have different active low bits.
6151   if (!VT.isVector()) {
6152     SDValue Shorter =
6153       GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
6154                                                VT.getSizeInBits()));
6155     if (Shorter.getNode())
6156       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
6157   }
6158   // fold (truncate (load x)) -> (smaller load x)
6159   // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
6160   if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
6161     SDValue Reduced = ReduceLoadWidth(N);
6162     if (Reduced.getNode())
6163       return Reduced;
6164     // Handle the case where the load remains an extending load even
6165     // after truncation.
6166     if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
6167       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6168       if (!LN0->isVolatile() &&
6169           LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
6170         SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
6171                                          VT, LN0->getChain(), LN0->getBasePtr(),
6172                                          LN0->getMemoryVT(),
6173                                          LN0->getMemOperand());
6174         DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
6175         return NewLoad;
6176       }
6177     }
6178   }
6179   // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
6180   // where ... are all 'undef'.
6181   if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
6182     SmallVector<EVT, 8> VTs;
6183     SDValue V;
6184     unsigned Idx = 0;
6185     unsigned NumDefs = 0;
6186
6187     for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
6188       SDValue X = N0.getOperand(i);
6189       if (X.getOpcode() != ISD::UNDEF) {
6190         V = X;
6191         Idx = i;
6192         NumDefs++;
6193       }
6194       // Stop if more than one members are non-undef.
6195       if (NumDefs > 1)
6196         break;
6197       VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
6198                                      VT.getVectorElementType(),
6199                                      X.getValueType().getVectorNumElements()));
6200     }
6201
6202     if (NumDefs == 0)
6203       return DAG.getUNDEF(VT);
6204
6205     if (NumDefs == 1) {
6206       assert(V.getNode() && "The single defined operand is empty!");
6207       SmallVector<SDValue, 8> Opnds;
6208       for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
6209         if (i != Idx) {
6210           Opnds.push_back(DAG.getUNDEF(VTs[i]));
6211           continue;
6212         }
6213         SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
6214         AddToWorklist(NV.getNode());
6215         Opnds.push_back(NV);
6216       }
6217       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
6218     }
6219   }
6220
6221   // Simplify the operands using demanded-bits information.
6222   if (!VT.isVector() &&
6223       SimplifyDemandedBits(SDValue(N, 0)))
6224     return SDValue(N, 0);
6225
6226   return SDValue();
6227 }
6228
6229 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
6230   SDValue Elt = N->getOperand(i);
6231   if (Elt.getOpcode() != ISD::MERGE_VALUES)
6232     return Elt.getNode();
6233   return Elt.getOperand(Elt.getResNo()).getNode();
6234 }
6235
6236 /// CombineConsecutiveLoads - build_pair (load, load) -> load
6237 /// if load locations are consecutive.
6238 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
6239   assert(N->getOpcode() == ISD::BUILD_PAIR);
6240
6241   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
6242   LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
6243   if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
6244       LD1->getAddressSpace() != LD2->getAddressSpace())
6245     return SDValue();
6246   EVT LD1VT = LD1->getValueType(0);
6247
6248   if (ISD::isNON_EXTLoad(LD2) &&
6249       LD2->hasOneUse() &&
6250       // If both are volatile this would reduce the number of volatile loads.
6251       // If one is volatile it might be ok, but play conservative and bail out.
6252       !LD1->isVolatile() &&
6253       !LD2->isVolatile() &&
6254       DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
6255     unsigned Align = LD1->getAlignment();
6256     unsigned NewAlign = TLI.getDataLayout()->
6257       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6258
6259     if (NewAlign <= Align &&
6260         (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
6261       return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
6262                          LD1->getBasePtr(), LD1->getPointerInfo(),
6263                          false, false, false, Align);
6264   }
6265
6266   return SDValue();
6267 }
6268
6269 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
6270   SDValue N0 = N->getOperand(0);
6271   EVT VT = N->getValueType(0);
6272
6273   // If the input is a BUILD_VECTOR with all constant elements, fold this now.
6274   // Only do this before legalize, since afterward the target may be depending
6275   // on the bitconvert.
6276   // First check to see if this is all constant.
6277   if (!LegalTypes &&
6278       N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
6279       VT.isVector()) {
6280     bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
6281
6282     EVT DestEltVT = N->getValueType(0).getVectorElementType();
6283     assert(!DestEltVT.isVector() &&
6284            "Element type of vector ValueType must not be vector!");
6285     if (isSimple)
6286       return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
6287   }
6288
6289   // If the input is a constant, let getNode fold it.
6290   if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
6291     SDValue Res = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
6292     if (Res.getNode() != N) {
6293       if (!LegalOperations ||
6294           TLI.isOperationLegal(Res.getNode()->getOpcode(), VT))
6295         return Res;
6296
6297       // Folding it resulted in an illegal node, and it's too late to
6298       // do that. Clean up the old node and forego the transformation.
6299       // Ideally this won't happen very often, because instcombine
6300       // and the earlier dagcombine runs (where illegal nodes are
6301       // permitted) should have folded most of them already.
6302       deleteAndRecombine(Res.getNode());
6303     }
6304   }
6305
6306   // (conv (conv x, t1), t2) -> (conv x, t2)
6307   if (N0.getOpcode() == ISD::BITCAST)
6308     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
6309                        N0.getOperand(0));
6310
6311   // fold (conv (load x)) -> (load (conv*)x)
6312   // If the resultant load doesn't need a higher alignment than the original!
6313   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
6314       // Do not change the width of a volatile load.
6315       !cast<LoadSDNode>(N0)->isVolatile() &&
6316       // Do not remove the cast if the types differ in endian layout.
6317       TLI.hasBigEndianPartOrdering(N0.getValueType()) ==
6318       TLI.hasBigEndianPartOrdering(VT) &&
6319       (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
6320       TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
6321     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6322     unsigned Align = TLI.getDataLayout()->
6323       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6324     unsigned OrigAlign = LN0->getAlignment();
6325
6326     if (Align <= OrigAlign) {
6327       SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
6328                                  LN0->getBasePtr(), LN0->getPointerInfo(),
6329                                  LN0->isVolatile(), LN0->isNonTemporal(),
6330                                  LN0->isInvariant(), OrigAlign,
6331                                  LN0->getAAInfo());
6332       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
6333       return Load;
6334     }
6335   }
6336
6337   // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
6338   // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
6339   // This often reduces constant pool loads.
6340   if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
6341        (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
6342       N0.getNode()->hasOneUse() && VT.isInteger() &&
6343       !VT.isVector() && !N0.getValueType().isVector()) {
6344     SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
6345                                   N0.getOperand(0));
6346     AddToWorklist(NewConv.getNode());
6347
6348     APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6349     if (N0.getOpcode() == ISD::FNEG)
6350       return DAG.getNode(ISD::XOR, SDLoc(N), VT,
6351                          NewConv, DAG.getConstant(SignBit, VT));
6352     assert(N0.getOpcode() == ISD::FABS);
6353     return DAG.getNode(ISD::AND, SDLoc(N), VT,
6354                        NewConv, DAG.getConstant(~SignBit, VT));
6355   }
6356
6357   // fold (bitconvert (fcopysign cst, x)) ->
6358   //         (or (and (bitconvert x), sign), (and cst, (not sign)))
6359   // Note that we don't handle (copysign x, cst) because this can always be
6360   // folded to an fneg or fabs.
6361   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
6362       isa<ConstantFPSDNode>(N0.getOperand(0)) &&
6363       VT.isInteger() && !VT.isVector()) {
6364     unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
6365     EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
6366     if (isTypeLegal(IntXVT)) {
6367       SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6368                               IntXVT, N0.getOperand(1));
6369       AddToWorklist(X.getNode());
6370
6371       // If X has a different width than the result/lhs, sext it or truncate it.
6372       unsigned VTWidth = VT.getSizeInBits();
6373       if (OrigXWidth < VTWidth) {
6374         X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
6375         AddToWorklist(X.getNode());
6376       } else if (OrigXWidth > VTWidth) {
6377         // To get the sign bit in the right place, we have to shift it right
6378         // before truncating.
6379         X = DAG.getNode(ISD::SRL, SDLoc(X),
6380                         X.getValueType(), X,
6381                         DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
6382         AddToWorklist(X.getNode());
6383         X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
6384         AddToWorklist(X.getNode());
6385       }
6386
6387       APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6388       X = DAG.getNode(ISD::AND, SDLoc(X), VT,
6389                       X, DAG.getConstant(SignBit, VT));
6390       AddToWorklist(X.getNode());
6391
6392       SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6393                                 VT, N0.getOperand(0));
6394       Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
6395                         Cst, DAG.getConstant(~SignBit, VT));
6396       AddToWorklist(Cst.getNode());
6397
6398       return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
6399     }
6400   }
6401
6402   // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
6403   if (N0.getOpcode() == ISD::BUILD_PAIR) {
6404     SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
6405     if (CombineLD.getNode())
6406       return CombineLD;
6407   }
6408
6409   return SDValue();
6410 }
6411
6412 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
6413   EVT VT = N->getValueType(0);
6414   return CombineConsecutiveLoads(N, VT);
6415 }
6416
6417 /// ConstantFoldBITCASTofBUILD_VECTOR - We know that BV is a build_vector
6418 /// node with Constant, ConstantFP or Undef operands.  DstEltVT indicates the
6419 /// destination element value type.
6420 SDValue DAGCombiner::
6421 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
6422   EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
6423
6424   // If this is already the right type, we're done.
6425   if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
6426
6427   unsigned SrcBitSize = SrcEltVT.getSizeInBits();
6428   unsigned DstBitSize = DstEltVT.getSizeInBits();
6429
6430   // If this is a conversion of N elements of one type to N elements of another
6431   // type, convert each element.  This handles FP<->INT cases.
6432   if (SrcBitSize == DstBitSize) {
6433     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6434                               BV->getValueType(0).getVectorNumElements());
6435
6436     // Due to the FP element handling below calling this routine recursively,
6437     // we can end up with a scalar-to-vector node here.
6438     if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
6439       return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6440                          DAG.getNode(ISD::BITCAST, SDLoc(BV),
6441                                      DstEltVT, BV->getOperand(0)));
6442
6443     SmallVector<SDValue, 8> Ops;
6444     for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6445       SDValue Op = BV->getOperand(i);
6446       // If the vector element type is not legal, the BUILD_VECTOR operands
6447       // are promoted and implicitly truncated.  Make that explicit here.
6448       if (Op.getValueType() != SrcEltVT)
6449         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
6450       Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
6451                                 DstEltVT, Op));
6452       AddToWorklist(Ops.back().getNode());
6453     }
6454     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6455   }
6456
6457   // Otherwise, we're growing or shrinking the elements.  To avoid having to
6458   // handle annoying details of growing/shrinking FP values, we convert them to
6459   // int first.
6460   if (SrcEltVT.isFloatingPoint()) {
6461     // Convert the input float vector to a int vector where the elements are the
6462     // same sizes.
6463     assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!");
6464     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
6465     BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
6466     SrcEltVT = IntVT;
6467   }
6468
6469   // Now we know the input is an integer vector.  If the output is a FP type,
6470   // convert to integer first, then to FP of the right size.
6471   if (DstEltVT.isFloatingPoint()) {
6472     assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!");
6473     EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
6474     SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
6475
6476     // Next, convert to FP elements of the same size.
6477     return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
6478   }
6479
6480   // Okay, we know the src/dst types are both integers of differing types.
6481   // Handling growing first.
6482   assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
6483   if (SrcBitSize < DstBitSize) {
6484     unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
6485
6486     SmallVector<SDValue, 8> Ops;
6487     for (unsigned i = 0, e = BV->getNumOperands(); i != e;
6488          i += NumInputsPerOutput) {
6489       bool isLE = TLI.isLittleEndian();
6490       APInt NewBits = APInt(DstBitSize, 0);
6491       bool EltIsUndef = true;
6492       for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
6493         // Shift the previously computed bits over.
6494         NewBits <<= SrcBitSize;
6495         SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
6496         if (Op.getOpcode() == ISD::UNDEF) continue;
6497         EltIsUndef = false;
6498
6499         NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
6500                    zextOrTrunc(SrcBitSize).zext(DstBitSize);
6501       }
6502
6503       if (EltIsUndef)
6504         Ops.push_back(DAG.getUNDEF(DstEltVT));
6505       else
6506         Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
6507     }
6508
6509     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
6510     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6511   }
6512
6513   // Finally, this must be the case where we are shrinking elements: each input
6514   // turns into multiple outputs.
6515   bool isS2V = ISD::isScalarToVector(BV);
6516   unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
6517   EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6518                             NumOutputsPerInput*BV->getNumOperands());
6519   SmallVector<SDValue, 8> Ops;
6520
6521   for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6522     if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
6523       for (unsigned j = 0; j != NumOutputsPerInput; ++j)
6524         Ops.push_back(DAG.getUNDEF(DstEltVT));
6525       continue;
6526     }
6527
6528     APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
6529                   getAPIntValue().zextOrTrunc(SrcBitSize);
6530
6531     for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
6532       APInt ThisVal = OpVal.trunc(DstBitSize);
6533       Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
6534       if (isS2V && i == 0 && j == 0 && ThisVal.zext(SrcBitSize) == OpVal)
6535         // Simply turn this into a SCALAR_TO_VECTOR of the new type.
6536         return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6537                            Ops[0]);
6538       OpVal = OpVal.lshr(DstBitSize);
6539     }
6540
6541     // For big endian targets, swap the order of the pieces of each element.
6542     if (TLI.isBigEndian())
6543       std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
6544   }
6545
6546   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6547 }
6548
6549 SDValue DAGCombiner::visitFADD(SDNode *N) {
6550   SDValue N0 = N->getOperand(0);
6551   SDValue N1 = N->getOperand(1);
6552   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6553   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6554   EVT VT = N->getValueType(0);
6555
6556   // fold vector ops
6557   if (VT.isVector()) {
6558     SDValue FoldedVOp = SimplifyVBinOp(N);
6559     if (FoldedVOp.getNode()) return FoldedVOp;
6560   }
6561
6562   // fold (fadd c1, c2) -> c1 + c2
6563   if (N0CFP && N1CFP)
6564     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N1);
6565   // canonicalize constant to RHS
6566   if (N0CFP && !N1CFP)
6567     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N0);
6568   // fold (fadd A, 0) -> A
6569   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6570       N1CFP->getValueAPF().isZero())
6571     return N0;
6572   // fold (fadd A, (fneg B)) -> (fsub A, B)
6573   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6574     isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
6575     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0,
6576                        GetNegatedExpression(N1, DAG, LegalOperations));
6577   // fold (fadd (fneg A), B) -> (fsub B, A)
6578   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6579     isNegatibleForFree(N0, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
6580     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N1,
6581                        GetNegatedExpression(N0, DAG, LegalOperations));
6582
6583   // If allowed, fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
6584   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6585       N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
6586       isa<ConstantFPSDNode>(N0.getOperand(1)))
6587     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0.getOperand(0),
6588                        DAG.getNode(ISD::FADD, SDLoc(N), VT,
6589                                    N0.getOperand(1), N1));
6590
6591   // No FP constant should be created after legalization as Instruction
6592   // Selection pass has hard time in dealing with FP constant.
6593   //
6594   // We don't need test this condition for transformation like following, as
6595   // the DAG being transformed implies it is legal to take FP constant as
6596   // operand.
6597   //
6598   //  (fadd (fmul c, x), x) -> (fmul c+1, x)
6599   //
6600   bool AllowNewFpConst = (Level < AfterLegalizeDAG);
6601
6602   // If allow, fold (fadd (fneg x), x) -> 0.0
6603   if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
6604       N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
6605     return DAG.getConstantFP(0.0, VT);
6606
6607     // If allow, fold (fadd x, (fneg x)) -> 0.0
6608   if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
6609       N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
6610     return DAG.getConstantFP(0.0, VT);
6611
6612   // In unsafe math mode, we can fold chains of FADD's of the same value
6613   // into multiplications.  This transform is not safe in general because
6614   // we are reducing the number of rounding steps.
6615   if (DAG.getTarget().Options.UnsafeFPMath &&
6616       TLI.isOperationLegalOrCustom(ISD::FMUL, VT) &&
6617       !N0CFP && !N1CFP) {
6618     if (N0.getOpcode() == ISD::FMUL) {
6619       ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6620       ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
6621
6622       // (fadd (fmul c, x), x) -> (fmul x, c+1)
6623       if (CFP00 && !CFP01 && N0.getOperand(1) == N1) {
6624         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6625                                      SDValue(CFP00, 0),
6626                                      DAG.getConstantFP(1.0, VT));
6627         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6628                            N1, NewCFP);
6629       }
6630
6631       // (fadd (fmul x, c), x) -> (fmul x, c+1)
6632       if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
6633         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6634                                      SDValue(CFP01, 0),
6635                                      DAG.getConstantFP(1.0, VT));
6636         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6637                            N1, NewCFP);
6638       }
6639
6640       // (fadd (fmul c, x), (fadd x, x)) -> (fmul x, c+2)
6641       if (CFP00 && !CFP01 && N1.getOpcode() == ISD::FADD &&
6642           N1.getOperand(0) == N1.getOperand(1) &&
6643           N0.getOperand(1) == N1.getOperand(0)) {
6644         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6645                                      SDValue(CFP00, 0),
6646                                      DAG.getConstantFP(2.0, VT));
6647         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6648                            N0.getOperand(1), NewCFP);
6649       }
6650
6651       // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
6652       if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
6653           N1.getOperand(0) == N1.getOperand(1) &&
6654           N0.getOperand(0) == N1.getOperand(0)) {
6655         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6656                                      SDValue(CFP01, 0),
6657                                      DAG.getConstantFP(2.0, VT));
6658         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6659                            N0.getOperand(0), NewCFP);
6660       }
6661     }
6662
6663     if (N1.getOpcode() == ISD::FMUL) {
6664       ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6665       ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
6666
6667       // (fadd x, (fmul c, x)) -> (fmul x, c+1)
6668       if (CFP10 && !CFP11 && N1.getOperand(1) == N0) {
6669         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6670                                      SDValue(CFP10, 0),
6671                                      DAG.getConstantFP(1.0, VT));
6672         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6673                            N0, NewCFP);
6674       }
6675
6676       // (fadd x, (fmul x, c)) -> (fmul x, c+1)
6677       if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
6678         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6679                                      SDValue(CFP11, 0),
6680                                      DAG.getConstantFP(1.0, VT));
6681         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6682                            N0, NewCFP);
6683       }
6684
6685
6686       // (fadd (fadd x, x), (fmul c, x)) -> (fmul x, c+2)
6687       if (CFP10 && !CFP11 && N0.getOpcode() == ISD::FADD &&
6688           N0.getOperand(0) == N0.getOperand(1) &&
6689           N1.getOperand(1) == N0.getOperand(0)) {
6690         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6691                                      SDValue(CFP10, 0),
6692                                      DAG.getConstantFP(2.0, VT));
6693         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6694                            N1.getOperand(1), NewCFP);
6695       }
6696
6697       // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
6698       if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
6699           N0.getOperand(0) == N0.getOperand(1) &&
6700           N1.getOperand(0) == N0.getOperand(0)) {
6701         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6702                                      SDValue(CFP11, 0),
6703                                      DAG.getConstantFP(2.0, VT));
6704         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6705                            N1.getOperand(0), NewCFP);
6706       }
6707     }
6708
6709     if (N0.getOpcode() == ISD::FADD && AllowNewFpConst) {
6710       ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6711       // (fadd (fadd x, x), x) -> (fmul x, 3.0)
6712       if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
6713           (N0.getOperand(0) == N1))
6714         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6715                            N1, DAG.getConstantFP(3.0, VT));
6716     }
6717
6718     if (N1.getOpcode() == ISD::FADD && AllowNewFpConst) {
6719       ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6720       // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
6721       if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
6722           N1.getOperand(0) == N0)
6723         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6724                            N0, DAG.getConstantFP(3.0, VT));
6725     }
6726
6727     // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
6728     if (AllowNewFpConst &&
6729         N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
6730         N0.getOperand(0) == N0.getOperand(1) &&
6731         N1.getOperand(0) == N1.getOperand(1) &&
6732         N0.getOperand(0) == N1.getOperand(0))
6733       return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6734                          N0.getOperand(0),
6735                          DAG.getConstantFP(4.0, VT));
6736   }
6737
6738   // FADD -> FMA combines:
6739   if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
6740        DAG.getTarget().Options.UnsafeFPMath) &&
6741       DAG.getTarget()
6742           .getSubtargetImpl()
6743           ->getTargetLowering()
6744           ->isFMAFasterThanFMulAndFAdd(VT) &&
6745       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6746
6747     // fold (fadd (fmul x, y), z) -> (fma x, y, z)
6748     if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
6749       return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6750                          N0.getOperand(0), N0.getOperand(1), N1);
6751
6752     // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
6753     // Note: Commutes FADD operands.
6754     if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
6755       return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6756                          N1.getOperand(0), N1.getOperand(1), N0);
6757   }
6758
6759   return SDValue();
6760 }
6761
6762 SDValue DAGCombiner::visitFSUB(SDNode *N) {
6763   SDValue N0 = N->getOperand(0);
6764   SDValue N1 = N->getOperand(1);
6765   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6766   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6767   EVT VT = N->getValueType(0);
6768   SDLoc dl(N);
6769
6770   // fold vector ops
6771   if (VT.isVector()) {
6772     SDValue FoldedVOp = SimplifyVBinOp(N);
6773     if (FoldedVOp.getNode()) return FoldedVOp;
6774   }
6775
6776   // fold (fsub c1, c2) -> c1-c2
6777   if (N0CFP && N1CFP)
6778     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0, N1);
6779   // fold (fsub A, 0) -> A
6780   if (DAG.getTarget().Options.UnsafeFPMath &&
6781       N1CFP && N1CFP->getValueAPF().isZero())
6782     return N0;
6783   // fold (fsub 0, B) -> -B
6784   if (DAG.getTarget().Options.UnsafeFPMath &&
6785       N0CFP && N0CFP->getValueAPF().isZero()) {
6786     if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
6787       return GetNegatedExpression(N1, DAG, LegalOperations);
6788     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6789       return DAG.getNode(ISD::FNEG, dl, VT, N1);
6790   }
6791   // fold (fsub A, (fneg B)) -> (fadd A, B)
6792   if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
6793     return DAG.getNode(ISD::FADD, dl, VT, N0,
6794                        GetNegatedExpression(N1, DAG, LegalOperations));
6795
6796   // If 'unsafe math' is enabled, fold
6797   //    (fsub x, x) -> 0.0 &
6798   //    (fsub x, (fadd x, y)) -> (fneg y) &
6799   //    (fsub x, (fadd y, x)) -> (fneg y)
6800   if (DAG.getTarget().Options.UnsafeFPMath) {
6801     if (N0 == N1)
6802       return DAG.getConstantFP(0.0f, VT);
6803
6804     if (N1.getOpcode() == ISD::FADD) {
6805       SDValue N10 = N1->getOperand(0);
6806       SDValue N11 = N1->getOperand(1);
6807
6808       if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI,
6809                                           &DAG.getTarget().Options))
6810         return GetNegatedExpression(N11, DAG, LegalOperations);
6811
6812       if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI,
6813                                           &DAG.getTarget().Options))
6814         return GetNegatedExpression(N10, DAG, LegalOperations);
6815     }
6816   }
6817
6818   // FSUB -> FMA combines:
6819   if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
6820        DAG.getTarget().Options.UnsafeFPMath) &&
6821       DAG.getTarget()
6822           .getSubtargetImpl()
6823           ->getTargetLowering()
6824           ->isFMAFasterThanFMulAndFAdd(VT) &&
6825       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6826
6827     // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
6828     if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
6829       return DAG.getNode(ISD::FMA, dl, VT,
6830                          N0.getOperand(0), N0.getOperand(1),
6831                          DAG.getNode(ISD::FNEG, dl, VT, N1));
6832
6833     // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
6834     // Note: Commutes FSUB operands.
6835     if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
6836       return DAG.getNode(ISD::FMA, dl, VT,
6837                          DAG.getNode(ISD::FNEG, dl, VT,
6838                          N1.getOperand(0)),
6839                          N1.getOperand(1), N0);
6840
6841     // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
6842     if (N0.getOpcode() == ISD::FNEG &&
6843         N0.getOperand(0).getOpcode() == ISD::FMUL &&
6844         N0->hasOneUse() && N0.getOperand(0).hasOneUse()) {
6845       SDValue N00 = N0.getOperand(0).getOperand(0);
6846       SDValue N01 = N0.getOperand(0).getOperand(1);
6847       return DAG.getNode(ISD::FMA, dl, VT,
6848                          DAG.getNode(ISD::FNEG, dl, VT, N00), N01,
6849                          DAG.getNode(ISD::FNEG, dl, VT, N1));
6850     }
6851   }
6852
6853   return SDValue();
6854 }
6855
6856 SDValue DAGCombiner::visitFMUL(SDNode *N) {
6857   SDValue N0 = N->getOperand(0);
6858   SDValue N1 = N->getOperand(1);
6859   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
6860   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
6861   EVT VT = N->getValueType(0);
6862   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6863
6864   // fold vector ops
6865   if (VT.isVector()) {
6866     SDValue FoldedVOp = SimplifyVBinOp(N);
6867     if (FoldedVOp.getNode()) return FoldedVOp;
6868   }
6869
6870   // fold (fmul c1, c2) -> c1*c2
6871   if (N0CFP && N1CFP)
6872     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, N1);
6873   // canonicalize constant to RHS
6874   if (N0CFP && !N1CFP)
6875     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, N0);
6876   // fold (fmul A, 0) -> 0
6877   if (DAG.getTarget().Options.UnsafeFPMath &&
6878       N1CFP && N1CFP->getValueAPF().isZero())
6879     return N1;
6880   // fold (fmul A, 1.0) -> A
6881   if (N1CFP && N1CFP->isExactlyValue(1.0))
6882     return N0;
6883
6884   // fold (fmul X, 2.0) -> (fadd X, X)
6885   if (N1CFP && N1CFP->isExactlyValue(+2.0))
6886     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N0);
6887   // fold (fmul X, -1.0) -> (fneg X)
6888   if (N1CFP && N1CFP->isExactlyValue(-1.0))
6889     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6890       return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
6891
6892   // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
6893   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
6894                                        &DAG.getTarget().Options)) {
6895     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
6896                                          &DAG.getTarget().Options)) {
6897       // Both can be negated for free, check to see if at least one is cheaper
6898       // negated.
6899       if (LHSNeg == 2 || RHSNeg == 2)
6900         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6901                            GetNegatedExpression(N0, DAG, LegalOperations),
6902                            GetNegatedExpression(N1, DAG, LegalOperations));
6903     }
6904   }
6905
6906   // If allowed, fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
6907   if (DAG.getTarget().Options.UnsafeFPMath &&
6908       N1CFP && N0.getOpcode() == ISD::FMUL &&
6909       N0.getNode()->hasOneUse() && isConstOrConstSplatFP(N0.getOperand(1))) {
6910     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
6911                        DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6912                                    N0.getOperand(1), N1));
6913   }
6914
6915   return SDValue();
6916 }
6917
6918 SDValue DAGCombiner::visitFMA(SDNode *N) {
6919   SDValue N0 = N->getOperand(0);
6920   SDValue N1 = N->getOperand(1);
6921   SDValue N2 = N->getOperand(2);
6922   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6923   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6924   EVT VT = N->getValueType(0);
6925   SDLoc dl(N);
6926
6927
6928   // Constant fold FMA.
6929   if (isa<ConstantFPSDNode>(N0) &&
6930       isa<ConstantFPSDNode>(N1) &&
6931       isa<ConstantFPSDNode>(N2)) {
6932     return DAG.getNode(ISD::FMA, dl, VT, N0, N1, N2);
6933   }
6934
6935   if (DAG.getTarget().Options.UnsafeFPMath) {
6936     if (N0CFP && N0CFP->isZero())
6937       return N2;
6938     if (N1CFP && N1CFP->isZero())
6939       return N2;
6940   }
6941   if (N0CFP && N0CFP->isExactlyValue(1.0))
6942     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
6943   if (N1CFP && N1CFP->isExactlyValue(1.0))
6944     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
6945
6946   // Canonicalize (fma c, x, y) -> (fma x, c, y)
6947   if (N0CFP && !N1CFP)
6948     return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
6949
6950   // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
6951   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6952       N2.getOpcode() == ISD::FMUL &&
6953       N0 == N2.getOperand(0) &&
6954       N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
6955     return DAG.getNode(ISD::FMUL, dl, VT, N0,
6956                        DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
6957   }
6958
6959
6960   // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
6961   if (DAG.getTarget().Options.UnsafeFPMath &&
6962       N0.getOpcode() == ISD::FMUL && N1CFP &&
6963       N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
6964     return DAG.getNode(ISD::FMA, dl, VT,
6965                        N0.getOperand(0),
6966                        DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
6967                        N2);
6968   }
6969
6970   // (fma x, 1, y) -> (fadd x, y)
6971   // (fma x, -1, y) -> (fadd (fneg x), y)
6972   if (N1CFP) {
6973     if (N1CFP->isExactlyValue(1.0))
6974       return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
6975
6976     if (N1CFP->isExactlyValue(-1.0) &&
6977         (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
6978       SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
6979       AddToWorklist(RHSNeg.getNode());
6980       return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
6981     }
6982   }
6983
6984   // (fma x, c, x) -> (fmul x, (c+1))
6985   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP && N0 == N2)
6986     return DAG.getNode(ISD::FMUL, dl, VT, N0,
6987                        DAG.getNode(ISD::FADD, dl, VT,
6988                                    N1, DAG.getConstantFP(1.0, VT)));
6989
6990   // (fma x, c, (fneg x)) -> (fmul x, (c-1))
6991   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6992       N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
6993     return DAG.getNode(ISD::FMUL, dl, VT, N0,
6994                        DAG.getNode(ISD::FADD, dl, VT,
6995                                    N1, DAG.getConstantFP(-1.0, VT)));
6996
6997
6998   return SDValue();
6999 }
7000
7001 SDValue DAGCombiner::visitFDIV(SDNode *N) {
7002   SDValue N0 = N->getOperand(0);
7003   SDValue N1 = N->getOperand(1);
7004   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7005   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7006   EVT VT = N->getValueType(0);
7007   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7008
7009   // fold vector ops
7010   if (VT.isVector()) {
7011     SDValue FoldedVOp = SimplifyVBinOp(N);
7012     if (FoldedVOp.getNode()) return FoldedVOp;
7013   }
7014
7015   // fold (fdiv c1, c2) -> c1/c2
7016   if (N0CFP && N1CFP)
7017     return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
7018
7019   // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
7020   if (N1CFP && DAG.getTarget().Options.UnsafeFPMath) {
7021     // Compute the reciprocal 1.0 / c2.
7022     APFloat N1APF = N1CFP->getValueAPF();
7023     APFloat Recip(N1APF.getSemantics(), 1); // 1.0
7024     APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
7025     // Only do the transform if the reciprocal is a legal fp immediate that
7026     // isn't too nasty (eg NaN, denormal, ...).
7027     if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
7028         (!LegalOperations ||
7029          // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
7030          // backend)... we should handle this gracefully after Legalize.
7031          // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
7032          TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
7033          TLI.isFPImmLegal(Recip, VT)))
7034       return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0,
7035                          DAG.getConstantFP(Recip, VT));
7036   }
7037
7038   // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
7039   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
7040                                        &DAG.getTarget().Options)) {
7041     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
7042                                          &DAG.getTarget().Options)) {
7043       // Both can be negated for free, check to see if at least one is cheaper
7044       // negated.
7045       if (LHSNeg == 2 || RHSNeg == 2)
7046         return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
7047                            GetNegatedExpression(N0, DAG, LegalOperations),
7048                            GetNegatedExpression(N1, DAG, LegalOperations));
7049     }
7050   }
7051
7052   return SDValue();
7053 }
7054
7055 SDValue DAGCombiner::visitFREM(SDNode *N) {
7056   SDValue N0 = N->getOperand(0);
7057   SDValue N1 = N->getOperand(1);
7058   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7059   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7060   EVT VT = N->getValueType(0);
7061
7062   // fold (frem c1, c2) -> fmod(c1,c2)
7063   if (N0CFP && N1CFP)
7064     return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
7065
7066   return SDValue();
7067 }
7068
7069 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
7070   SDValue N0 = N->getOperand(0);
7071   SDValue N1 = N->getOperand(1);
7072   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7073   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7074   EVT VT = N->getValueType(0);
7075
7076   if (N0CFP && N1CFP)  // Constant fold
7077     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
7078
7079   if (N1CFP) {
7080     const APFloat& V = N1CFP->getValueAPF();
7081     // copysign(x, c1) -> fabs(x)       iff ispos(c1)
7082     // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
7083     if (!V.isNegative()) {
7084       if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
7085         return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7086     } else {
7087       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
7088         return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
7089                            DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
7090     }
7091   }
7092
7093   // copysign(fabs(x), y) -> copysign(x, y)
7094   // copysign(fneg(x), y) -> copysign(x, y)
7095   // copysign(copysign(x,z), y) -> copysign(x, y)
7096   if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
7097       N0.getOpcode() == ISD::FCOPYSIGN)
7098     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7099                        N0.getOperand(0), N1);
7100
7101   // copysign(x, abs(y)) -> abs(x)
7102   if (N1.getOpcode() == ISD::FABS)
7103     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7104
7105   // copysign(x, copysign(y,z)) -> copysign(x, z)
7106   if (N1.getOpcode() == ISD::FCOPYSIGN)
7107     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7108                        N0, N1.getOperand(1));
7109
7110   // copysign(x, fp_extend(y)) -> copysign(x, y)
7111   // copysign(x, fp_round(y)) -> copysign(x, y)
7112   if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
7113     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7114                        N0, N1.getOperand(0));
7115
7116   return SDValue();
7117 }
7118
7119 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
7120   SDValue N0 = N->getOperand(0);
7121   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
7122   EVT VT = N->getValueType(0);
7123   EVT OpVT = N0.getValueType();
7124
7125   // fold (sint_to_fp c1) -> c1fp
7126   if (N0C &&
7127       // ...but only if the target supports immediate floating-point values
7128       (!LegalOperations ||
7129        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
7130     return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
7131
7132   // If the input is a legal type, and SINT_TO_FP is not legal on this target,
7133   // but UINT_TO_FP is legal on this target, try to convert.
7134   if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
7135       TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
7136     // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
7137     if (DAG.SignBitIsZero(N0))
7138       return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
7139   }
7140
7141   // The next optimizations are desirable only if SELECT_CC can be lowered.
7142   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
7143     // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
7144     if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
7145         !VT.isVector() &&
7146         (!LegalOperations ||
7147          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7148       SDValue Ops[] =
7149         { N0.getOperand(0), N0.getOperand(1),
7150           DAG.getConstantFP(-1.0, VT) , DAG.getConstantFP(0.0, VT),
7151           N0.getOperand(2) };
7152       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7153     }
7154
7155     // fold (sint_to_fp (zext (setcc x, y, cc))) ->
7156     //      (select_cc x, y, 1.0, 0.0,, cc)
7157     if (N0.getOpcode() == ISD::ZERO_EXTEND &&
7158         N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
7159         (!LegalOperations ||
7160          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7161       SDValue Ops[] =
7162         { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
7163           DAG.getConstantFP(1.0, VT) , DAG.getConstantFP(0.0, VT),
7164           N0.getOperand(0).getOperand(2) };
7165       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7166     }
7167   }
7168
7169   return SDValue();
7170 }
7171
7172 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
7173   SDValue N0 = N->getOperand(0);
7174   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
7175   EVT VT = N->getValueType(0);
7176   EVT OpVT = N0.getValueType();
7177
7178   // fold (uint_to_fp c1) -> c1fp
7179   if (N0C &&
7180       // ...but only if the target supports immediate floating-point values
7181       (!LegalOperations ||
7182        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
7183     return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
7184
7185   // If the input is a legal type, and UINT_TO_FP is not legal on this target,
7186   // but SINT_TO_FP is legal on this target, try to convert.
7187   if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
7188       TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
7189     // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
7190     if (DAG.SignBitIsZero(N0))
7191       return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
7192   }
7193
7194   // The next optimizations are desirable only if SELECT_CC can be lowered.
7195   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
7196     // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
7197
7198     if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
7199         (!LegalOperations ||
7200          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7201       SDValue Ops[] =
7202         { N0.getOperand(0), N0.getOperand(1),
7203           DAG.getConstantFP(1.0, VT),  DAG.getConstantFP(0.0, VT),
7204           N0.getOperand(2) };
7205       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7206     }
7207   }
7208
7209   return SDValue();
7210 }
7211
7212 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
7213   SDValue N0 = N->getOperand(0);
7214   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7215   EVT VT = N->getValueType(0);
7216
7217   // fold (fp_to_sint c1fp) -> c1
7218   if (N0CFP)
7219     return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
7220
7221   return SDValue();
7222 }
7223
7224 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
7225   SDValue N0 = N->getOperand(0);
7226   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7227   EVT VT = N->getValueType(0);
7228
7229   // fold (fp_to_uint c1fp) -> c1
7230   if (N0CFP)
7231     return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
7232
7233   return SDValue();
7234 }
7235
7236 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
7237   SDValue N0 = N->getOperand(0);
7238   SDValue N1 = N->getOperand(1);
7239   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7240   EVT VT = N->getValueType(0);
7241
7242   // fold (fp_round c1fp) -> c1fp
7243   if (N0CFP)
7244     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
7245
7246   // fold (fp_round (fp_extend x)) -> x
7247   if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
7248     return N0.getOperand(0);
7249
7250   // fold (fp_round (fp_round x)) -> (fp_round x)
7251   if (N0.getOpcode() == ISD::FP_ROUND) {
7252     // This is a value preserving truncation if both round's are.
7253     bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
7254                    N0.getNode()->getConstantOperandVal(1) == 1;
7255     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0.getOperand(0),
7256                        DAG.getIntPtrConstant(IsTrunc));
7257   }
7258
7259   // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
7260   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
7261     SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
7262                               N0.getOperand(0), N1);
7263     AddToWorklist(Tmp.getNode());
7264     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7265                        Tmp, N0.getOperand(1));
7266   }
7267
7268   return SDValue();
7269 }
7270
7271 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
7272   SDValue N0 = N->getOperand(0);
7273   EVT VT = N->getValueType(0);
7274   EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
7275   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7276
7277   // fold (fp_round_inreg c1fp) -> c1fp
7278   if (N0CFP && isTypeLegal(EVT)) {
7279     SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
7280     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, Round);
7281   }
7282
7283   return SDValue();
7284 }
7285
7286 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
7287   SDValue N0 = N->getOperand(0);
7288   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7289   EVT VT = N->getValueType(0);
7290
7291   // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
7292   if (N->hasOneUse() &&
7293       N->use_begin()->getOpcode() == ISD::FP_ROUND)
7294     return SDValue();
7295
7296   // fold (fp_extend c1fp) -> c1fp
7297   if (N0CFP)
7298     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
7299
7300   // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
7301   // value of X.
7302   if (N0.getOpcode() == ISD::FP_ROUND
7303       && N0.getNode()->getConstantOperandVal(1) == 1) {
7304     SDValue In = N0.getOperand(0);
7305     if (In.getValueType() == VT) return In;
7306     if (VT.bitsLT(In.getValueType()))
7307       return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
7308                          In, N0.getOperand(1));
7309     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
7310   }
7311
7312   // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
7313   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7314        TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType())) {
7315     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7316     SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
7317                                      LN0->getChain(),
7318                                      LN0->getBasePtr(), N0.getValueType(),
7319                                      LN0->getMemOperand());
7320     CombineTo(N, ExtLoad);
7321     CombineTo(N0.getNode(),
7322               DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
7323                           N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
7324               ExtLoad.getValue(1));
7325     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7326   }
7327
7328   return SDValue();
7329 }
7330
7331 SDValue DAGCombiner::visitFNEG(SDNode *N) {
7332   SDValue N0 = N->getOperand(0);
7333   EVT VT = N->getValueType(0);
7334
7335   // Constant fold FNEG.
7336   if (isa<ConstantFPSDNode>(N0))
7337     return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N->getOperand(0));
7338
7339   if (VT.isVector()) {
7340     SDValue FoldedVOp = SimplifyVUnaryOp(N);
7341     if (FoldedVOp.getNode()) return FoldedVOp;
7342   }
7343
7344   if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
7345                          &DAG.getTarget().Options))
7346     return GetNegatedExpression(N0, DAG, LegalOperations);
7347
7348   // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading
7349   // constant pool values.
7350   if (!TLI.isFNegFree(VT) && N0.getOpcode() == ISD::BITCAST &&
7351       N0.getNode()->hasOneUse()) {
7352     SDValue Int = N0.getOperand(0);
7353     EVT IntVT = Int.getValueType();
7354     if (IntVT.isInteger() && !IntVT.isVector()) {
7355       APInt SignMask;
7356       if (N0.getValueType().isVector()) {
7357         // For a vector, get a mask such as 0x80... per scalar element
7358         // and splat it.
7359         SignMask = APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
7360         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
7361       } else {
7362         // For a scalar, just generate 0x80...
7363         SignMask = APInt::getSignBit(IntVT.getSizeInBits());
7364       }
7365       Int = DAG.getNode(ISD::XOR, SDLoc(N0), IntVT, Int,
7366                         DAG.getConstant(SignMask, IntVT));
7367       AddToWorklist(Int.getNode());
7368       return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Int);
7369     }
7370   }
7371
7372   // (fneg (fmul c, x)) -> (fmul -c, x)
7373   if (N0.getOpcode() == ISD::FMUL) {
7374     ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
7375     if (CFP1) {
7376       APFloat CVal = CFP1->getValueAPF();
7377       CVal.changeSign();
7378       if (Level >= AfterLegalizeDAG &&
7379           (TLI.isFPImmLegal(CVal, N->getValueType(0)) ||
7380            TLI.isOperationLegal(ISD::ConstantFP, N->getValueType(0))))
7381         return DAG.getNode(
7382             ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
7383             DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0.getOperand(1)));
7384     }
7385   }
7386
7387   return SDValue();
7388 }
7389
7390 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
7391   SDValue N0 = N->getOperand(0);
7392   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7393   EVT VT = N->getValueType(0);
7394
7395   // fold (fceil c1) -> fceil(c1)
7396   if (N0CFP)
7397     return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
7398
7399   return SDValue();
7400 }
7401
7402 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
7403   SDValue N0 = N->getOperand(0);
7404   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7405   EVT VT = N->getValueType(0);
7406
7407   // fold (ftrunc c1) -> ftrunc(c1)
7408   if (N0CFP)
7409     return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
7410
7411   return SDValue();
7412 }
7413
7414 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
7415   SDValue N0 = N->getOperand(0);
7416   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7417   EVT VT = N->getValueType(0);
7418
7419   // fold (ffloor c1) -> ffloor(c1)
7420   if (N0CFP)
7421     return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
7422
7423   return SDValue();
7424 }
7425
7426 SDValue DAGCombiner::visitFABS(SDNode *N) {
7427   SDValue N0 = N->getOperand(0);
7428   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7429   EVT VT = N->getValueType(0);
7430
7431   if (VT.isVector()) {
7432     SDValue FoldedVOp = SimplifyVUnaryOp(N);
7433     if (FoldedVOp.getNode()) return FoldedVOp;
7434   }
7435
7436   // fold (fabs c1) -> fabs(c1)
7437   if (N0CFP)
7438     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7439   // fold (fabs (fabs x)) -> (fabs x)
7440   if (N0.getOpcode() == ISD::FABS)
7441     return N->getOperand(0);
7442   // fold (fabs (fneg x)) -> (fabs x)
7443   // fold (fabs (fcopysign x, y)) -> (fabs x)
7444   if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
7445     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
7446
7447   // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading
7448   // constant pool values.
7449   if (!TLI.isFAbsFree(VT) &&
7450       N0.getOpcode() == ISD::BITCAST &&
7451       N0.getNode()->hasOneUse()) {
7452     SDValue Int = N0.getOperand(0);
7453     EVT IntVT = Int.getValueType();
7454     if (IntVT.isInteger() && !IntVT.isVector()) {
7455       APInt SignMask;
7456       if (N0.getValueType().isVector()) {
7457         // For a vector, get a mask such as 0x7f... per scalar element
7458         // and splat it.
7459         SignMask = ~APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
7460         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
7461       } else {
7462         // For a scalar, just generate 0x7f...
7463         SignMask = ~APInt::getSignBit(IntVT.getSizeInBits());
7464       }
7465       Int = DAG.getNode(ISD::AND, SDLoc(N0), IntVT, Int,
7466                         DAG.getConstant(SignMask, IntVT));
7467       AddToWorklist(Int.getNode());
7468       return DAG.getNode(ISD::BITCAST, SDLoc(N), N->getValueType(0), Int);
7469     }
7470   }
7471
7472   return SDValue();
7473 }
7474
7475 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
7476   SDValue Chain = N->getOperand(0);
7477   SDValue N1 = N->getOperand(1);
7478   SDValue N2 = N->getOperand(2);
7479
7480   // If N is a constant we could fold this into a fallthrough or unconditional
7481   // branch. However that doesn't happen very often in normal code, because
7482   // Instcombine/SimplifyCFG should have handled the available opportunities.
7483   // If we did this folding here, it would be necessary to update the
7484   // MachineBasicBlock CFG, which is awkward.
7485
7486   // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
7487   // on the target.
7488   if (N1.getOpcode() == ISD::SETCC &&
7489       TLI.isOperationLegalOrCustom(ISD::BR_CC,
7490                                    N1.getOperand(0).getValueType())) {
7491     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7492                        Chain, N1.getOperand(2),
7493                        N1.getOperand(0), N1.getOperand(1), N2);
7494   }
7495
7496   if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
7497       ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
7498        (N1.getOperand(0).hasOneUse() &&
7499         N1.getOperand(0).getOpcode() == ISD::SRL))) {
7500     SDNode *Trunc = nullptr;
7501     if (N1.getOpcode() == ISD::TRUNCATE) {
7502       // Look pass the truncate.
7503       Trunc = N1.getNode();
7504       N1 = N1.getOperand(0);
7505     }
7506
7507     // Match this pattern so that we can generate simpler code:
7508     //
7509     //   %a = ...
7510     //   %b = and i32 %a, 2
7511     //   %c = srl i32 %b, 1
7512     //   brcond i32 %c ...
7513     //
7514     // into
7515     //
7516     //   %a = ...
7517     //   %b = and i32 %a, 2
7518     //   %c = setcc eq %b, 0
7519     //   brcond %c ...
7520     //
7521     // This applies only when the AND constant value has one bit set and the
7522     // SRL constant is equal to the log2 of the AND constant. The back-end is
7523     // smart enough to convert the result into a TEST/JMP sequence.
7524     SDValue Op0 = N1.getOperand(0);
7525     SDValue Op1 = N1.getOperand(1);
7526
7527     if (Op0.getOpcode() == ISD::AND &&
7528         Op1.getOpcode() == ISD::Constant) {
7529       SDValue AndOp1 = Op0.getOperand(1);
7530
7531       if (AndOp1.getOpcode() == ISD::Constant) {
7532         const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
7533
7534         if (AndConst.isPowerOf2() &&
7535             cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
7536           SDValue SetCC =
7537             DAG.getSetCC(SDLoc(N),
7538                          getSetCCResultType(Op0.getValueType()),
7539                          Op0, DAG.getConstant(0, Op0.getValueType()),
7540                          ISD::SETNE);
7541
7542           SDValue NewBRCond = DAG.getNode(ISD::BRCOND, SDLoc(N),
7543                                           MVT::Other, Chain, SetCC, N2);
7544           // Don't add the new BRCond into the worklist or else SimplifySelectCC
7545           // will convert it back to (X & C1) >> C2.
7546           CombineTo(N, NewBRCond, false);
7547           // Truncate is dead.
7548           if (Trunc)
7549             deleteAndRecombine(Trunc);
7550           // Replace the uses of SRL with SETCC
7551           WorklistRemover DeadNodes(*this);
7552           DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
7553           deleteAndRecombine(N1.getNode());
7554           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7555         }
7556       }
7557     }
7558
7559     if (Trunc)
7560       // Restore N1 if the above transformation doesn't match.
7561       N1 = N->getOperand(1);
7562   }
7563
7564   // Transform br(xor(x, y)) -> br(x != y)
7565   // Transform br(xor(xor(x,y), 1)) -> br (x == y)
7566   if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
7567     SDNode *TheXor = N1.getNode();
7568     SDValue Op0 = TheXor->getOperand(0);
7569     SDValue Op1 = TheXor->getOperand(1);
7570     if (Op0.getOpcode() == Op1.getOpcode()) {
7571       // Avoid missing important xor optimizations.
7572       SDValue Tmp = visitXOR(TheXor);
7573       if (Tmp.getNode()) {
7574         if (Tmp.getNode() != TheXor) {
7575           DEBUG(dbgs() << "\nReplacing.8 ";
7576                 TheXor->dump(&DAG);
7577                 dbgs() << "\nWith: ";
7578                 Tmp.getNode()->dump(&DAG);
7579                 dbgs() << '\n');
7580           WorklistRemover DeadNodes(*this);
7581           DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
7582           deleteAndRecombine(TheXor);
7583           return DAG.getNode(ISD::BRCOND, SDLoc(N),
7584                              MVT::Other, Chain, Tmp, N2);
7585         }
7586
7587         // visitXOR has changed XOR's operands or replaced the XOR completely,
7588         // bail out.
7589         return SDValue(N, 0);
7590       }
7591     }
7592
7593     if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
7594       bool Equal = false;
7595       if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
7596         if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
7597             Op0.getOpcode() == ISD::XOR) {
7598           TheXor = Op0.getNode();
7599           Equal = true;
7600         }
7601
7602       EVT SetCCVT = N1.getValueType();
7603       if (LegalTypes)
7604         SetCCVT = getSetCCResultType(SetCCVT);
7605       SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
7606                                    SetCCVT,
7607                                    Op0, Op1,
7608                                    Equal ? ISD::SETEQ : ISD::SETNE);
7609       // Replace the uses of XOR with SETCC
7610       WorklistRemover DeadNodes(*this);
7611       DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
7612       deleteAndRecombine(N1.getNode());
7613       return DAG.getNode(ISD::BRCOND, SDLoc(N),
7614                          MVT::Other, Chain, SetCC, N2);
7615     }
7616   }
7617
7618   return SDValue();
7619 }
7620
7621 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
7622 //
7623 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
7624   CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
7625   SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
7626
7627   // If N is a constant we could fold this into a fallthrough or unconditional
7628   // branch. However that doesn't happen very often in normal code, because
7629   // Instcombine/SimplifyCFG should have handled the available opportunities.
7630   // If we did this folding here, it would be necessary to update the
7631   // MachineBasicBlock CFG, which is awkward.
7632
7633   // Use SimplifySetCC to simplify SETCC's.
7634   SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
7635                                CondLHS, CondRHS, CC->get(), SDLoc(N),
7636                                false);
7637   if (Simp.getNode()) AddToWorklist(Simp.getNode());
7638
7639   // fold to a simpler setcc
7640   if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
7641     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7642                        N->getOperand(0), Simp.getOperand(2),
7643                        Simp.getOperand(0), Simp.getOperand(1),
7644                        N->getOperand(4));
7645
7646   return SDValue();
7647 }
7648
7649 /// canFoldInAddressingMode - Return true if 'Use' is a load or a store that
7650 /// uses N as its base pointer and that N may be folded in the load / store
7651 /// addressing mode.
7652 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
7653                                     SelectionDAG &DAG,
7654                                     const TargetLowering &TLI) {
7655   EVT VT;
7656   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(Use)) {
7657     if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
7658       return false;
7659     VT = Use->getValueType(0);
7660   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(Use)) {
7661     if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
7662       return false;
7663     VT = ST->getValue().getValueType();
7664   } else
7665     return false;
7666
7667   TargetLowering::AddrMode AM;
7668   if (N->getOpcode() == ISD::ADD) {
7669     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7670     if (Offset)
7671       // [reg +/- imm]
7672       AM.BaseOffs = Offset->getSExtValue();
7673     else
7674       // [reg +/- reg]
7675       AM.Scale = 1;
7676   } else if (N->getOpcode() == ISD::SUB) {
7677     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7678     if (Offset)
7679       // [reg +/- imm]
7680       AM.BaseOffs = -Offset->getSExtValue();
7681     else
7682       // [reg +/- reg]
7683       AM.Scale = 1;
7684   } else
7685     return false;
7686
7687   return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
7688 }
7689
7690 /// CombineToPreIndexedLoadStore - Try turning a load / store into a
7691 /// pre-indexed load / store when the base pointer is an add or subtract
7692 /// and it has other uses besides the load / store. After the
7693 /// transformation, the new indexed load / store has effectively folded
7694 /// the add / subtract in and all of its other uses are redirected to the
7695 /// new load / store.
7696 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
7697   if (Level < AfterLegalizeDAG)
7698     return false;
7699
7700   bool isLoad = true;
7701   SDValue Ptr;
7702   EVT VT;
7703   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
7704     if (LD->isIndexed())
7705       return false;
7706     VT = LD->getMemoryVT();
7707     if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
7708         !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
7709       return false;
7710     Ptr = LD->getBasePtr();
7711   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
7712     if (ST->isIndexed())
7713       return false;
7714     VT = ST->getMemoryVT();
7715     if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
7716         !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
7717       return false;
7718     Ptr = ST->getBasePtr();
7719     isLoad = false;
7720   } else {
7721     return false;
7722   }
7723
7724   // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
7725   // out.  There is no reason to make this a preinc/predec.
7726   if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
7727       Ptr.getNode()->hasOneUse())
7728     return false;
7729
7730   // Ask the target to do addressing mode selection.
7731   SDValue BasePtr;
7732   SDValue Offset;
7733   ISD::MemIndexedMode AM = ISD::UNINDEXED;
7734   if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
7735     return false;
7736
7737   // Backends without true r+i pre-indexed forms may need to pass a
7738   // constant base with a variable offset so that constant coercion
7739   // will work with the patterns in canonical form.
7740   bool Swapped = false;
7741   if (isa<ConstantSDNode>(BasePtr)) {
7742     std::swap(BasePtr, Offset);
7743     Swapped = true;
7744   }
7745
7746   // Don't create a indexed load / store with zero offset.
7747   if (isa<ConstantSDNode>(Offset) &&
7748       cast<ConstantSDNode>(Offset)->isNullValue())
7749     return false;
7750
7751   // Try turning it into a pre-indexed load / store except when:
7752   // 1) The new base ptr is a frame index.
7753   // 2) If N is a store and the new base ptr is either the same as or is a
7754   //    predecessor of the value being stored.
7755   // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
7756   //    that would create a cycle.
7757   // 4) All uses are load / store ops that use it as old base ptr.
7758
7759   // Check #1.  Preinc'ing a frame index would require copying the stack pointer
7760   // (plus the implicit offset) to a register to preinc anyway.
7761   if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7762     return false;
7763
7764   // Check #2.
7765   if (!isLoad) {
7766     SDValue Val = cast<StoreSDNode>(N)->getValue();
7767     if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
7768       return false;
7769   }
7770
7771   // If the offset is a constant, there may be other adds of constants that
7772   // can be folded with this one. We should do this to avoid having to keep
7773   // a copy of the original base pointer.
7774   SmallVector<SDNode *, 16> OtherUses;
7775   if (isa<ConstantSDNode>(Offset))
7776     for (SDNode *Use : BasePtr.getNode()->uses()) {
7777       if (Use == Ptr.getNode())
7778         continue;
7779
7780       if (Use->isPredecessorOf(N))
7781         continue;
7782
7783       if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) {
7784         OtherUses.clear();
7785         break;
7786       }
7787
7788       SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1);
7789       if (Op1.getNode() == BasePtr.getNode())
7790         std::swap(Op0, Op1);
7791       assert(Op0.getNode() == BasePtr.getNode() &&
7792              "Use of ADD/SUB but not an operand");
7793
7794       if (!isa<ConstantSDNode>(Op1)) {
7795         OtherUses.clear();
7796         break;
7797       }
7798
7799       // FIXME: In some cases, we can be smarter about this.
7800       if (Op1.getValueType() != Offset.getValueType()) {
7801         OtherUses.clear();
7802         break;
7803       }
7804
7805       OtherUses.push_back(Use);
7806     }
7807
7808   if (Swapped)
7809     std::swap(BasePtr, Offset);
7810
7811   // Now check for #3 and #4.
7812   bool RealUse = false;
7813
7814   // Caches for hasPredecessorHelper
7815   SmallPtrSet<const SDNode *, 32> Visited;
7816   SmallVector<const SDNode *, 16> Worklist;
7817
7818   for (SDNode *Use : Ptr.getNode()->uses()) {
7819     if (Use == N)
7820       continue;
7821     if (N->hasPredecessorHelper(Use, Visited, Worklist))
7822       return false;
7823
7824     // If Ptr may be folded in addressing mode of other use, then it's
7825     // not profitable to do this transformation.
7826     if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
7827       RealUse = true;
7828   }
7829
7830   if (!RealUse)
7831     return false;
7832
7833   SDValue Result;
7834   if (isLoad)
7835     Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
7836                                 BasePtr, Offset, AM);
7837   else
7838     Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
7839                                  BasePtr, Offset, AM);
7840   ++PreIndexedNodes;
7841   ++NodesCombined;
7842   DEBUG(dbgs() << "\nReplacing.4 ";
7843         N->dump(&DAG);
7844         dbgs() << "\nWith: ";
7845         Result.getNode()->dump(&DAG);
7846         dbgs() << '\n');
7847   WorklistRemover DeadNodes(*this);
7848   if (isLoad) {
7849     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7850     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
7851   } else {
7852     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
7853   }
7854
7855   // Finally, since the node is now dead, remove it from the graph.
7856   deleteAndRecombine(N);
7857
7858   if (Swapped)
7859     std::swap(BasePtr, Offset);
7860
7861   // Replace other uses of BasePtr that can be updated to use Ptr
7862   for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
7863     unsigned OffsetIdx = 1;
7864     if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
7865       OffsetIdx = 0;
7866     assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
7867            BasePtr.getNode() && "Expected BasePtr operand");
7868
7869     // We need to replace ptr0 in the following expression:
7870     //   x0 * offset0 + y0 * ptr0 = t0
7871     // knowing that
7872     //   x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
7873     //
7874     // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
7875     // indexed load/store and the expresion that needs to be re-written.
7876     //
7877     // Therefore, we have:
7878     //   t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
7879
7880     ConstantSDNode *CN =
7881       cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
7882     int X0, X1, Y0, Y1;
7883     APInt Offset0 = CN->getAPIntValue();
7884     APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
7885
7886     X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
7887     Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
7888     X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
7889     Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
7890
7891     unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
7892
7893     APInt CNV = Offset0;
7894     if (X0 < 0) CNV = -CNV;
7895     if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
7896     else CNV = CNV - Offset1;
7897
7898     // We can now generate the new expression.
7899     SDValue NewOp1 = DAG.getConstant(CNV, CN->getValueType(0));
7900     SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
7901
7902     SDValue NewUse = DAG.getNode(Opcode,
7903                                  SDLoc(OtherUses[i]),
7904                                  OtherUses[i]->getValueType(0), NewOp1, NewOp2);
7905     DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
7906     deleteAndRecombine(OtherUses[i]);
7907   }
7908
7909   // Replace the uses of Ptr with uses of the updated base value.
7910   DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
7911   deleteAndRecombine(Ptr.getNode());
7912
7913   return true;
7914 }
7915
7916 /// CombineToPostIndexedLoadStore - Try to combine a load / store with a
7917 /// add / sub of the base pointer node into a post-indexed load / store.
7918 /// The transformation folded the add / subtract into the new indexed
7919 /// load / store effectively and all of its uses are redirected to the
7920 /// new load / store.
7921 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
7922   if (Level < AfterLegalizeDAG)
7923     return false;
7924
7925   bool isLoad = true;
7926   SDValue Ptr;
7927   EVT VT;
7928   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
7929     if (LD->isIndexed())
7930       return false;
7931     VT = LD->getMemoryVT();
7932     if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
7933         !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
7934       return false;
7935     Ptr = LD->getBasePtr();
7936   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
7937     if (ST->isIndexed())
7938       return false;
7939     VT = ST->getMemoryVT();
7940     if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
7941         !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
7942       return false;
7943     Ptr = ST->getBasePtr();
7944     isLoad = false;
7945   } else {
7946     return false;
7947   }
7948
7949   if (Ptr.getNode()->hasOneUse())
7950     return false;
7951
7952   for (SDNode *Op : Ptr.getNode()->uses()) {
7953     if (Op == N ||
7954         (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
7955       continue;
7956
7957     SDValue BasePtr;
7958     SDValue Offset;
7959     ISD::MemIndexedMode AM = ISD::UNINDEXED;
7960     if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
7961       // Don't create a indexed load / store with zero offset.
7962       if (isa<ConstantSDNode>(Offset) &&
7963           cast<ConstantSDNode>(Offset)->isNullValue())
7964         continue;
7965
7966       // Try turning it into a post-indexed load / store except when
7967       // 1) All uses are load / store ops that use it as base ptr (and
7968       //    it may be folded as addressing mmode).
7969       // 2) Op must be independent of N, i.e. Op is neither a predecessor
7970       //    nor a successor of N. Otherwise, if Op is folded that would
7971       //    create a cycle.
7972
7973       if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7974         continue;
7975
7976       // Check for #1.
7977       bool TryNext = false;
7978       for (SDNode *Use : BasePtr.getNode()->uses()) {
7979         if (Use == Ptr.getNode())
7980           continue;
7981
7982         // If all the uses are load / store addresses, then don't do the
7983         // transformation.
7984         if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
7985           bool RealUse = false;
7986           for (SDNode *UseUse : Use->uses()) {
7987             if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
7988               RealUse = true;
7989           }
7990
7991           if (!RealUse) {
7992             TryNext = true;
7993             break;
7994           }
7995         }
7996       }
7997
7998       if (TryNext)
7999         continue;
8000
8001       // Check for #2
8002       if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
8003         SDValue Result = isLoad
8004           ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
8005                                BasePtr, Offset, AM)
8006           : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
8007                                 BasePtr, Offset, AM);
8008         ++PostIndexedNodes;
8009         ++NodesCombined;
8010         DEBUG(dbgs() << "\nReplacing.5 ";
8011               N->dump(&DAG);
8012               dbgs() << "\nWith: ";
8013               Result.getNode()->dump(&DAG);
8014               dbgs() << '\n');
8015         WorklistRemover DeadNodes(*this);
8016         if (isLoad) {
8017           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
8018           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
8019         } else {
8020           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
8021         }
8022
8023         // Finally, since the node is now dead, remove it from the graph.
8024         deleteAndRecombine(N);
8025
8026         // Replace the uses of Use with uses of the updated base value.
8027         DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
8028                                       Result.getValue(isLoad ? 1 : 0));
8029         deleteAndRecombine(Op);
8030         return true;
8031       }
8032     }
8033   }
8034
8035   return false;
8036 }
8037
8038 SDValue DAGCombiner::visitLOAD(SDNode *N) {
8039   LoadSDNode *LD  = cast<LoadSDNode>(N);
8040   SDValue Chain = LD->getChain();
8041   SDValue Ptr   = LD->getBasePtr();
8042
8043   // If load is not volatile and there are no uses of the loaded value (and
8044   // the updated indexed value in case of indexed loads), change uses of the
8045   // chain value into uses of the chain input (i.e. delete the dead load).
8046   if (!LD->isVolatile()) {
8047     if (N->getValueType(1) == MVT::Other) {
8048       // Unindexed loads.
8049       if (!N->hasAnyUseOfValue(0)) {
8050         // It's not safe to use the two value CombineTo variant here. e.g.
8051         // v1, chain2 = load chain1, loc
8052         // v2, chain3 = load chain2, loc
8053         // v3         = add v2, c
8054         // Now we replace use of chain2 with chain1.  This makes the second load
8055         // isomorphic to the one we are deleting, and thus makes this load live.
8056         DEBUG(dbgs() << "\nReplacing.6 ";
8057               N->dump(&DAG);
8058               dbgs() << "\nWith chain: ";
8059               Chain.getNode()->dump(&DAG);
8060               dbgs() << "\n");
8061         WorklistRemover DeadNodes(*this);
8062         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
8063
8064         if (N->use_empty())
8065           deleteAndRecombine(N);
8066
8067         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
8068       }
8069     } else {
8070       // Indexed loads.
8071       assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
8072       if (!N->hasAnyUseOfValue(0) && !N->hasAnyUseOfValue(1)) {
8073         SDValue Undef = DAG.getUNDEF(N->getValueType(0));
8074         DEBUG(dbgs() << "\nReplacing.7 ";
8075               N->dump(&DAG);
8076               dbgs() << "\nWith: ";
8077               Undef.getNode()->dump(&DAG);
8078               dbgs() << " and 2 other values\n");
8079         WorklistRemover DeadNodes(*this);
8080         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
8081         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1),
8082                                       DAG.getUNDEF(N->getValueType(1)));
8083         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
8084         deleteAndRecombine(N);
8085         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
8086       }
8087     }
8088   }
8089
8090   // If this load is directly stored, replace the load value with the stored
8091   // value.
8092   // TODO: Handle store large -> read small portion.
8093   // TODO: Handle TRUNCSTORE/LOADEXT
8094   if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
8095     if (ISD::isNON_TRUNCStore(Chain.getNode())) {
8096       StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
8097       if (PrevST->getBasePtr() == Ptr &&
8098           PrevST->getValue().getValueType() == N->getValueType(0))
8099       return CombineTo(N, Chain.getOperand(1), Chain);
8100     }
8101   }
8102
8103   // Try to infer better alignment information than the load already has.
8104   if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
8105     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
8106       if (Align > LD->getMemOperand()->getBaseAlignment()) {
8107         SDValue NewLoad =
8108                DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
8109                               LD->getValueType(0),
8110                               Chain, Ptr, LD->getPointerInfo(),
8111                               LD->getMemoryVT(),
8112                               LD->isVolatile(), LD->isNonTemporal(),
8113                               LD->isInvariant(), Align, LD->getAAInfo());
8114         return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
8115       }
8116     }
8117   }
8118
8119   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
8120     TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
8121 #ifndef NDEBUG
8122   if (CombinerAAOnlyFunc.getNumOccurrences() &&
8123       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
8124     UseAA = false;
8125 #endif
8126   if (UseAA && LD->isUnindexed()) {
8127     // Walk up chain skipping non-aliasing memory nodes.
8128     SDValue BetterChain = FindBetterChain(N, Chain);
8129
8130     // If there is a better chain.
8131     if (Chain != BetterChain) {
8132       SDValue ReplLoad;
8133
8134       // Replace the chain to void dependency.
8135       if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
8136         ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
8137                                BetterChain, Ptr, LD->getMemOperand());
8138       } else {
8139         ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
8140                                   LD->getValueType(0),
8141                                   BetterChain, Ptr, LD->getMemoryVT(),
8142                                   LD->getMemOperand());
8143       }
8144
8145       // Create token factor to keep old chain connected.
8146       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
8147                                   MVT::Other, Chain, ReplLoad.getValue(1));
8148
8149       // Make sure the new and old chains are cleaned up.
8150       AddToWorklist(Token.getNode());
8151
8152       // Replace uses with load result and token factor. Don't add users
8153       // to work list.
8154       return CombineTo(N, ReplLoad.getValue(0), Token, false);
8155     }
8156   }
8157
8158   // Try transforming N to an indexed load.
8159   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
8160     return SDValue(N, 0);
8161
8162   // Try to slice up N to more direct loads if the slices are mapped to
8163   // different register banks or pairing can take place.
8164   if (SliceUpLoad(N))
8165     return SDValue(N, 0);
8166
8167   return SDValue();
8168 }
8169
8170 namespace {
8171 /// \brief Helper structure used to slice a load in smaller loads.
8172 /// Basically a slice is obtained from the following sequence:
8173 /// Origin = load Ty1, Base
8174 /// Shift = srl Ty1 Origin, CstTy Amount
8175 /// Inst = trunc Shift to Ty2
8176 ///
8177 /// Then, it will be rewriten into:
8178 /// Slice = load SliceTy, Base + SliceOffset
8179 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
8180 ///
8181 /// SliceTy is deduced from the number of bits that are actually used to
8182 /// build Inst.
8183 struct LoadedSlice {
8184   /// \brief Helper structure used to compute the cost of a slice.
8185   struct Cost {
8186     /// Are we optimizing for code size.
8187     bool ForCodeSize;
8188     /// Various cost.
8189     unsigned Loads;
8190     unsigned Truncates;
8191     unsigned CrossRegisterBanksCopies;
8192     unsigned ZExts;
8193     unsigned Shift;
8194
8195     Cost(bool ForCodeSize = false)
8196         : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
8197           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
8198
8199     /// \brief Get the cost of one isolated slice.
8200     Cost(const LoadedSlice &LS, bool ForCodeSize = false)
8201         : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
8202           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
8203       EVT TruncType = LS.Inst->getValueType(0);
8204       EVT LoadedType = LS.getLoadedType();
8205       if (TruncType != LoadedType &&
8206           !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
8207         ZExts = 1;
8208     }
8209
8210     /// \brief Account for slicing gain in the current cost.
8211     /// Slicing provide a few gains like removing a shift or a
8212     /// truncate. This method allows to grow the cost of the original
8213     /// load with the gain from this slice.
8214     void addSliceGain(const LoadedSlice &LS) {
8215       // Each slice saves a truncate.
8216       const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
8217       if (!TLI.isTruncateFree(LS.Inst->getValueType(0),
8218                               LS.Inst->getOperand(0).getValueType()))
8219         ++Truncates;
8220       // If there is a shift amount, this slice gets rid of it.
8221       if (LS.Shift)
8222         ++Shift;
8223       // If this slice can merge a cross register bank copy, account for it.
8224       if (LS.canMergeExpensiveCrossRegisterBankCopy())
8225         ++CrossRegisterBanksCopies;
8226     }
8227
8228     Cost &operator+=(const Cost &RHS) {
8229       Loads += RHS.Loads;
8230       Truncates += RHS.Truncates;
8231       CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
8232       ZExts += RHS.ZExts;
8233       Shift += RHS.Shift;
8234       return *this;
8235     }
8236
8237     bool operator==(const Cost &RHS) const {
8238       return Loads == RHS.Loads && Truncates == RHS.Truncates &&
8239              CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
8240              ZExts == RHS.ZExts && Shift == RHS.Shift;
8241     }
8242
8243     bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
8244
8245     bool operator<(const Cost &RHS) const {
8246       // Assume cross register banks copies are as expensive as loads.
8247       // FIXME: Do we want some more target hooks?
8248       unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
8249       unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
8250       // Unless we are optimizing for code size, consider the
8251       // expensive operation first.
8252       if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
8253         return ExpensiveOpsLHS < ExpensiveOpsRHS;
8254       return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
8255              (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
8256     }
8257
8258     bool operator>(const Cost &RHS) const { return RHS < *this; }
8259
8260     bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
8261
8262     bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
8263   };
8264   // The last instruction that represent the slice. This should be a
8265   // truncate instruction.
8266   SDNode *Inst;
8267   // The original load instruction.
8268   LoadSDNode *Origin;
8269   // The right shift amount in bits from the original load.
8270   unsigned Shift;
8271   // The DAG from which Origin came from.
8272   // This is used to get some contextual information about legal types, etc.
8273   SelectionDAG *DAG;
8274
8275   LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
8276               unsigned Shift = 0, SelectionDAG *DAG = nullptr)
8277       : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
8278
8279   LoadedSlice(const LoadedSlice &LS)
8280       : Inst(LS.Inst), Origin(LS.Origin), Shift(LS.Shift), DAG(LS.DAG) {}
8281
8282   /// \brief Get the bits used in a chunk of bits \p BitWidth large.
8283   /// \return Result is \p BitWidth and has used bits set to 1 and
8284   ///         not used bits set to 0.
8285   APInt getUsedBits() const {
8286     // Reproduce the trunc(lshr) sequence:
8287     // - Start from the truncated value.
8288     // - Zero extend to the desired bit width.
8289     // - Shift left.
8290     assert(Origin && "No original load to compare against.");
8291     unsigned BitWidth = Origin->getValueSizeInBits(0);
8292     assert(Inst && "This slice is not bound to an instruction");
8293     assert(Inst->getValueSizeInBits(0) <= BitWidth &&
8294            "Extracted slice is bigger than the whole type!");
8295     APInt UsedBits(Inst->getValueSizeInBits(0), 0);
8296     UsedBits.setAllBits();
8297     UsedBits = UsedBits.zext(BitWidth);
8298     UsedBits <<= Shift;
8299     return UsedBits;
8300   }
8301
8302   /// \brief Get the size of the slice to be loaded in bytes.
8303   unsigned getLoadedSize() const {
8304     unsigned SliceSize = getUsedBits().countPopulation();
8305     assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
8306     return SliceSize / 8;
8307   }
8308
8309   /// \brief Get the type that will be loaded for this slice.
8310   /// Note: This may not be the final type for the slice.
8311   EVT getLoadedType() const {
8312     assert(DAG && "Missing context");
8313     LLVMContext &Ctxt = *DAG->getContext();
8314     return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
8315   }
8316
8317   /// \brief Get the alignment of the load used for this slice.
8318   unsigned getAlignment() const {
8319     unsigned Alignment = Origin->getAlignment();
8320     unsigned Offset = getOffsetFromBase();
8321     if (Offset != 0)
8322       Alignment = MinAlign(Alignment, Alignment + Offset);
8323     return Alignment;
8324   }
8325
8326   /// \brief Check if this slice can be rewritten with legal operations.
8327   bool isLegal() const {
8328     // An invalid slice is not legal.
8329     if (!Origin || !Inst || !DAG)
8330       return false;
8331
8332     // Offsets are for indexed load only, we do not handle that.
8333     if (Origin->getOffset().getOpcode() != ISD::UNDEF)
8334       return false;
8335
8336     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8337
8338     // Check that the type is legal.
8339     EVT SliceType = getLoadedType();
8340     if (!TLI.isTypeLegal(SliceType))
8341       return false;
8342
8343     // Check that the load is legal for this type.
8344     if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
8345       return false;
8346
8347     // Check that the offset can be computed.
8348     // 1. Check its type.
8349     EVT PtrType = Origin->getBasePtr().getValueType();
8350     if (PtrType == MVT::Untyped || PtrType.isExtended())
8351       return false;
8352
8353     // 2. Check that it fits in the immediate.
8354     if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
8355       return false;
8356
8357     // 3. Check that the computation is legal.
8358     if (!TLI.isOperationLegal(ISD::ADD, PtrType))
8359       return false;
8360
8361     // Check that the zext is legal if it needs one.
8362     EVT TruncateType = Inst->getValueType(0);
8363     if (TruncateType != SliceType &&
8364         !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
8365       return false;
8366
8367     return true;
8368   }
8369
8370   /// \brief Get the offset in bytes of this slice in the original chunk of
8371   /// bits.
8372   /// \pre DAG != nullptr.
8373   uint64_t getOffsetFromBase() const {
8374     assert(DAG && "Missing context.");
8375     bool IsBigEndian =
8376         DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian();
8377     assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
8378     uint64_t Offset = Shift / 8;
8379     unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
8380     assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
8381            "The size of the original loaded type is not a multiple of a"
8382            " byte.");
8383     // If Offset is bigger than TySizeInBytes, it means we are loading all
8384     // zeros. This should have been optimized before in the process.
8385     assert(TySizeInBytes > Offset &&
8386            "Invalid shift amount for given loaded size");
8387     if (IsBigEndian)
8388       Offset = TySizeInBytes - Offset - getLoadedSize();
8389     return Offset;
8390   }
8391
8392   /// \brief Generate the sequence of instructions to load the slice
8393   /// represented by this object and redirect the uses of this slice to
8394   /// this new sequence of instructions.
8395   /// \pre this->Inst && this->Origin are valid Instructions and this
8396   /// object passed the legal check: LoadedSlice::isLegal returned true.
8397   /// \return The last instruction of the sequence used to load the slice.
8398   SDValue loadSlice() const {
8399     assert(Inst && Origin && "Unable to replace a non-existing slice.");
8400     const SDValue &OldBaseAddr = Origin->getBasePtr();
8401     SDValue BaseAddr = OldBaseAddr;
8402     // Get the offset in that chunk of bytes w.r.t. the endianess.
8403     int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
8404     assert(Offset >= 0 && "Offset too big to fit in int64_t!");
8405     if (Offset) {
8406       // BaseAddr = BaseAddr + Offset.
8407       EVT ArithType = BaseAddr.getValueType();
8408       BaseAddr = DAG->getNode(ISD::ADD, SDLoc(Origin), ArithType, BaseAddr,
8409                               DAG->getConstant(Offset, ArithType));
8410     }
8411
8412     // Create the type of the loaded slice according to its size.
8413     EVT SliceType = getLoadedType();
8414
8415     // Create the load for the slice.
8416     SDValue LastInst = DAG->getLoad(
8417         SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
8418         Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
8419         Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
8420     // If the final type is not the same as the loaded type, this means that
8421     // we have to pad with zero. Create a zero extend for that.
8422     EVT FinalType = Inst->getValueType(0);
8423     if (SliceType != FinalType)
8424       LastInst =
8425           DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
8426     return LastInst;
8427   }
8428
8429   /// \brief Check if this slice can be merged with an expensive cross register
8430   /// bank copy. E.g.,
8431   /// i = load i32
8432   /// f = bitcast i32 i to float
8433   bool canMergeExpensiveCrossRegisterBankCopy() const {
8434     if (!Inst || !Inst->hasOneUse())
8435       return false;
8436     SDNode *Use = *Inst->use_begin();
8437     if (Use->getOpcode() != ISD::BITCAST)
8438       return false;
8439     assert(DAG && "Missing context");
8440     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8441     EVT ResVT = Use->getValueType(0);
8442     const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
8443     const TargetRegisterClass *ArgRC =
8444         TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
8445     if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
8446       return false;
8447
8448     // At this point, we know that we perform a cross-register-bank copy.
8449     // Check if it is expensive.
8450     const TargetRegisterInfo *TRI =
8451         TLI.getTargetMachine().getSubtargetImpl()->getRegisterInfo();
8452     // Assume bitcasts are cheap, unless both register classes do not
8453     // explicitly share a common sub class.
8454     if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
8455       return false;
8456
8457     // Check if it will be merged with the load.
8458     // 1. Check the alignment constraint.
8459     unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment(
8460         ResVT.getTypeForEVT(*DAG->getContext()));
8461
8462     if (RequiredAlignment > getAlignment())
8463       return false;
8464
8465     // 2. Check that the load is a legal operation for that type.
8466     if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
8467       return false;
8468
8469     // 3. Check that we do not have a zext in the way.
8470     if (Inst->getValueType(0) != getLoadedType())
8471       return false;
8472
8473     return true;
8474   }
8475 };
8476 }
8477
8478 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
8479 /// \p UsedBits looks like 0..0 1..1 0..0.
8480 static bool areUsedBitsDense(const APInt &UsedBits) {
8481   // If all the bits are one, this is dense!
8482   if (UsedBits.isAllOnesValue())
8483     return true;
8484
8485   // Get rid of the unused bits on the right.
8486   APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
8487   // Get rid of the unused bits on the left.
8488   if (NarrowedUsedBits.countLeadingZeros())
8489     NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
8490   // Check that the chunk of bits is completely used.
8491   return NarrowedUsedBits.isAllOnesValue();
8492 }
8493
8494 /// \brief Check whether or not \p First and \p Second are next to each other
8495 /// in memory. This means that there is no hole between the bits loaded
8496 /// by \p First and the bits loaded by \p Second.
8497 static bool areSlicesNextToEachOther(const LoadedSlice &First,
8498                                      const LoadedSlice &Second) {
8499   assert(First.Origin == Second.Origin && First.Origin &&
8500          "Unable to match different memory origins.");
8501   APInt UsedBits = First.getUsedBits();
8502   assert((UsedBits & Second.getUsedBits()) == 0 &&
8503          "Slices are not supposed to overlap.");
8504   UsedBits |= Second.getUsedBits();
8505   return areUsedBitsDense(UsedBits);
8506 }
8507
8508 /// \brief Adjust the \p GlobalLSCost according to the target
8509 /// paring capabilities and the layout of the slices.
8510 /// \pre \p GlobalLSCost should account for at least as many loads as
8511 /// there is in the slices in \p LoadedSlices.
8512 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8513                                  LoadedSlice::Cost &GlobalLSCost) {
8514   unsigned NumberOfSlices = LoadedSlices.size();
8515   // If there is less than 2 elements, no pairing is possible.
8516   if (NumberOfSlices < 2)
8517     return;
8518
8519   // Sort the slices so that elements that are likely to be next to each
8520   // other in memory are next to each other in the list.
8521   std::sort(LoadedSlices.begin(), LoadedSlices.end(),
8522             [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
8523     assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
8524     return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
8525   });
8526   const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
8527   // First (resp. Second) is the first (resp. Second) potentially candidate
8528   // to be placed in a paired load.
8529   const LoadedSlice *First = nullptr;
8530   const LoadedSlice *Second = nullptr;
8531   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
8532                 // Set the beginning of the pair.
8533                                                            First = Second) {
8534
8535     Second = &LoadedSlices[CurrSlice];
8536
8537     // If First is NULL, it means we start a new pair.
8538     // Get to the next slice.
8539     if (!First)
8540       continue;
8541
8542     EVT LoadedType = First->getLoadedType();
8543
8544     // If the types of the slices are different, we cannot pair them.
8545     if (LoadedType != Second->getLoadedType())
8546       continue;
8547
8548     // Check if the target supplies paired loads for this type.
8549     unsigned RequiredAlignment = 0;
8550     if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
8551       // move to the next pair, this type is hopeless.
8552       Second = nullptr;
8553       continue;
8554     }
8555     // Check if we meet the alignment requirement.
8556     if (RequiredAlignment > First->getAlignment())
8557       continue;
8558
8559     // Check that both loads are next to each other in memory.
8560     if (!areSlicesNextToEachOther(*First, *Second))
8561       continue;
8562
8563     assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
8564     --GlobalLSCost.Loads;
8565     // Move to the next pair.
8566     Second = nullptr;
8567   }
8568 }
8569
8570 /// \brief Check the profitability of all involved LoadedSlice.
8571 /// Currently, it is considered profitable if there is exactly two
8572 /// involved slices (1) which are (2) next to each other in memory, and
8573 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
8574 ///
8575 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
8576 /// the elements themselves.
8577 ///
8578 /// FIXME: When the cost model will be mature enough, we can relax
8579 /// constraints (1) and (2).
8580 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8581                                 const APInt &UsedBits, bool ForCodeSize) {
8582   unsigned NumberOfSlices = LoadedSlices.size();
8583   if (StressLoadSlicing)
8584     return NumberOfSlices > 1;
8585
8586   // Check (1).
8587   if (NumberOfSlices != 2)
8588     return false;
8589
8590   // Check (2).
8591   if (!areUsedBitsDense(UsedBits))
8592     return false;
8593
8594   // Check (3).
8595   LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
8596   // The original code has one big load.
8597   OrigCost.Loads = 1;
8598   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
8599     const LoadedSlice &LS = LoadedSlices[CurrSlice];
8600     // Accumulate the cost of all the slices.
8601     LoadedSlice::Cost SliceCost(LS, ForCodeSize);
8602     GlobalSlicingCost += SliceCost;
8603
8604     // Account as cost in the original configuration the gain obtained
8605     // with the current slices.
8606     OrigCost.addSliceGain(LS);
8607   }
8608
8609   // If the target supports paired load, adjust the cost accordingly.
8610   adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
8611   return OrigCost > GlobalSlicingCost;
8612 }
8613
8614 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
8615 /// operations, split it in the various pieces being extracted.
8616 ///
8617 /// This sort of thing is introduced by SROA.
8618 /// This slicing takes care not to insert overlapping loads.
8619 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
8620 bool DAGCombiner::SliceUpLoad(SDNode *N) {
8621   if (Level < AfterLegalizeDAG)
8622     return false;
8623
8624   LoadSDNode *LD = cast<LoadSDNode>(N);
8625   if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
8626       !LD->getValueType(0).isInteger())
8627     return false;
8628
8629   // Keep track of already used bits to detect overlapping values.
8630   // In that case, we will just abort the transformation.
8631   APInt UsedBits(LD->getValueSizeInBits(0), 0);
8632
8633   SmallVector<LoadedSlice, 4> LoadedSlices;
8634
8635   // Check if this load is used as several smaller chunks of bits.
8636   // Basically, look for uses in trunc or trunc(lshr) and record a new chain
8637   // of computation for each trunc.
8638   for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
8639        UI != UIEnd; ++UI) {
8640     // Skip the uses of the chain.
8641     if (UI.getUse().getResNo() != 0)
8642       continue;
8643
8644     SDNode *User = *UI;
8645     unsigned Shift = 0;
8646
8647     // Check if this is a trunc(lshr).
8648     if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
8649         isa<ConstantSDNode>(User->getOperand(1))) {
8650       Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
8651       User = *User->use_begin();
8652     }
8653
8654     // At this point, User is a Truncate, iff we encountered, trunc or
8655     // trunc(lshr).
8656     if (User->getOpcode() != ISD::TRUNCATE)
8657       return false;
8658
8659     // The width of the type must be a power of 2 and greater than 8-bits.
8660     // Otherwise the load cannot be represented in LLVM IR.
8661     // Moreover, if we shifted with a non-8-bits multiple, the slice
8662     // will be across several bytes. We do not support that.
8663     unsigned Width = User->getValueSizeInBits(0);
8664     if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
8665       return 0;
8666
8667     // Build the slice for this chain of computations.
8668     LoadedSlice LS(User, LD, Shift, &DAG);
8669     APInt CurrentUsedBits = LS.getUsedBits();
8670
8671     // Check if this slice overlaps with another.
8672     if ((CurrentUsedBits & UsedBits) != 0)
8673       return false;
8674     // Update the bits used globally.
8675     UsedBits |= CurrentUsedBits;
8676
8677     // Check if the new slice would be legal.
8678     if (!LS.isLegal())
8679       return false;
8680
8681     // Record the slice.
8682     LoadedSlices.push_back(LS);
8683   }
8684
8685   // Abort slicing if it does not seem to be profitable.
8686   if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
8687     return false;
8688
8689   ++SlicedLoads;
8690
8691   // Rewrite each chain to use an independent load.
8692   // By construction, each chain can be represented by a unique load.
8693
8694   // Prepare the argument for the new token factor for all the slices.
8695   SmallVector<SDValue, 8> ArgChains;
8696   for (SmallVectorImpl<LoadedSlice>::const_iterator
8697            LSIt = LoadedSlices.begin(),
8698            LSItEnd = LoadedSlices.end();
8699        LSIt != LSItEnd; ++LSIt) {
8700     SDValue SliceInst = LSIt->loadSlice();
8701     CombineTo(LSIt->Inst, SliceInst, true);
8702     if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
8703       SliceInst = SliceInst.getOperand(0);
8704     assert(SliceInst->getOpcode() == ISD::LOAD &&
8705            "It takes more than a zext to get to the loaded slice!!");
8706     ArgChains.push_back(SliceInst.getValue(1));
8707   }
8708
8709   SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
8710                               ArgChains);
8711   DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
8712   return true;
8713 }
8714
8715 /// CheckForMaskedLoad - Check to see if V is (and load (ptr), imm), where the
8716 /// load is having specific bytes cleared out.  If so, return the byte size
8717 /// being masked out and the shift amount.
8718 static std::pair<unsigned, unsigned>
8719 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
8720   std::pair<unsigned, unsigned> Result(0, 0);
8721
8722   // Check for the structure we're looking for.
8723   if (V->getOpcode() != ISD::AND ||
8724       !isa<ConstantSDNode>(V->getOperand(1)) ||
8725       !ISD::isNormalLoad(V->getOperand(0).getNode()))
8726     return Result;
8727
8728   // Check the chain and pointer.
8729   LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
8730   if (LD->getBasePtr() != Ptr) return Result;  // Not from same pointer.
8731
8732   // The store should be chained directly to the load or be an operand of a
8733   // tokenfactor.
8734   if (LD == Chain.getNode())
8735     ; // ok.
8736   else if (Chain->getOpcode() != ISD::TokenFactor)
8737     return Result; // Fail.
8738   else {
8739     bool isOk = false;
8740     for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
8741       if (Chain->getOperand(i).getNode() == LD) {
8742         isOk = true;
8743         break;
8744       }
8745     if (!isOk) return Result;
8746   }
8747
8748   // This only handles simple types.
8749   if (V.getValueType() != MVT::i16 &&
8750       V.getValueType() != MVT::i32 &&
8751       V.getValueType() != MVT::i64)
8752     return Result;
8753
8754   // Check the constant mask.  Invert it so that the bits being masked out are
8755   // 0 and the bits being kept are 1.  Use getSExtValue so that leading bits
8756   // follow the sign bit for uniformity.
8757   uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
8758   unsigned NotMaskLZ = countLeadingZeros(NotMask);
8759   if (NotMaskLZ & 7) return Result;  // Must be multiple of a byte.
8760   unsigned NotMaskTZ = countTrailingZeros(NotMask);
8761   if (NotMaskTZ & 7) return Result;  // Must be multiple of a byte.
8762   if (NotMaskLZ == 64) return Result;  // All zero mask.
8763
8764   // See if we have a continuous run of bits.  If so, we have 0*1+0*
8765   if (CountTrailingOnes_64(NotMask >> NotMaskTZ)+NotMaskTZ+NotMaskLZ != 64)
8766     return Result;
8767
8768   // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
8769   if (V.getValueType() != MVT::i64 && NotMaskLZ)
8770     NotMaskLZ -= 64-V.getValueSizeInBits();
8771
8772   unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
8773   switch (MaskedBytes) {
8774   case 1:
8775   case 2:
8776   case 4: break;
8777   default: return Result; // All one mask, or 5-byte mask.
8778   }
8779
8780   // Verify that the first bit starts at a multiple of mask so that the access
8781   // is aligned the same as the access width.
8782   if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
8783
8784   Result.first = MaskedBytes;
8785   Result.second = NotMaskTZ/8;
8786   return Result;
8787 }
8788
8789
8790 /// ShrinkLoadReplaceStoreWithStore - Check to see if IVal is something that
8791 /// provides a value as specified by MaskInfo.  If so, replace the specified
8792 /// store with a narrower store of truncated IVal.
8793 static SDNode *
8794 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
8795                                 SDValue IVal, StoreSDNode *St,
8796                                 DAGCombiner *DC) {
8797   unsigned NumBytes = MaskInfo.first;
8798   unsigned ByteShift = MaskInfo.second;
8799   SelectionDAG &DAG = DC->getDAG();
8800
8801   // Check to see if IVal is all zeros in the part being masked in by the 'or'
8802   // that uses this.  If not, this is not a replacement.
8803   APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
8804                                   ByteShift*8, (ByteShift+NumBytes)*8);
8805   if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
8806
8807   // Check that it is legal on the target to do this.  It is legal if the new
8808   // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
8809   // legalization.
8810   MVT VT = MVT::getIntegerVT(NumBytes*8);
8811   if (!DC->isTypeLegal(VT))
8812     return nullptr;
8813
8814   // Okay, we can do this!  Replace the 'St' store with a store of IVal that is
8815   // shifted by ByteShift and truncated down to NumBytes.
8816   if (ByteShift)
8817     IVal = DAG.getNode(ISD::SRL, SDLoc(IVal), IVal.getValueType(), IVal,
8818                        DAG.getConstant(ByteShift*8,
8819                                     DC->getShiftAmountTy(IVal.getValueType())));
8820
8821   // Figure out the offset for the store and the alignment of the access.
8822   unsigned StOffset;
8823   unsigned NewAlign = St->getAlignment();
8824
8825   if (DAG.getTargetLoweringInfo().isLittleEndian())
8826     StOffset = ByteShift;
8827   else
8828     StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
8829
8830   SDValue Ptr = St->getBasePtr();
8831   if (StOffset) {
8832     Ptr = DAG.getNode(ISD::ADD, SDLoc(IVal), Ptr.getValueType(),
8833                       Ptr, DAG.getConstant(StOffset, Ptr.getValueType()));
8834     NewAlign = MinAlign(NewAlign, StOffset);
8835   }
8836
8837   // Truncate down to the new size.
8838   IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
8839
8840   ++OpsNarrowed;
8841   return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
8842                       St->getPointerInfo().getWithOffset(StOffset),
8843                       false, false, NewAlign).getNode();
8844 }
8845
8846
8847 /// ReduceLoadOpStoreWidth - Look for sequence of load / op / store where op is
8848 /// one of 'or', 'xor', and 'and' of immediates. If 'op' is only touching some
8849 /// of the loaded bits, try narrowing the load and store if it would end up
8850 /// being a win for performance or code size.
8851 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
8852   StoreSDNode *ST  = cast<StoreSDNode>(N);
8853   if (ST->isVolatile())
8854     return SDValue();
8855
8856   SDValue Chain = ST->getChain();
8857   SDValue Value = ST->getValue();
8858   SDValue Ptr   = ST->getBasePtr();
8859   EVT VT = Value.getValueType();
8860
8861   if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
8862     return SDValue();
8863
8864   unsigned Opc = Value.getOpcode();
8865
8866   // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
8867   // is a byte mask indicating a consecutive number of bytes, check to see if
8868   // Y is known to provide just those bytes.  If so, we try to replace the
8869   // load + replace + store sequence with a single (narrower) store, which makes
8870   // the load dead.
8871   if (Opc == ISD::OR) {
8872     std::pair<unsigned, unsigned> MaskedLoad;
8873     MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
8874     if (MaskedLoad.first)
8875       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8876                                                   Value.getOperand(1), ST,this))
8877         return SDValue(NewST, 0);
8878
8879     // Or is commutative, so try swapping X and Y.
8880     MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
8881     if (MaskedLoad.first)
8882       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8883                                                   Value.getOperand(0), ST,this))
8884         return SDValue(NewST, 0);
8885   }
8886
8887   if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
8888       Value.getOperand(1).getOpcode() != ISD::Constant)
8889     return SDValue();
8890
8891   SDValue N0 = Value.getOperand(0);
8892   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8893       Chain == SDValue(N0.getNode(), 1)) {
8894     LoadSDNode *LD = cast<LoadSDNode>(N0);
8895     if (LD->getBasePtr() != Ptr ||
8896         LD->getPointerInfo().getAddrSpace() !=
8897         ST->getPointerInfo().getAddrSpace())
8898       return SDValue();
8899
8900     // Find the type to narrow it the load / op / store to.
8901     SDValue N1 = Value.getOperand(1);
8902     unsigned BitWidth = N1.getValueSizeInBits();
8903     APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
8904     if (Opc == ISD::AND)
8905       Imm ^= APInt::getAllOnesValue(BitWidth);
8906     if (Imm == 0 || Imm.isAllOnesValue())
8907       return SDValue();
8908     unsigned ShAmt = Imm.countTrailingZeros();
8909     unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
8910     unsigned NewBW = NextPowerOf2(MSB - ShAmt);
8911     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
8912     while (NewBW < BitWidth &&
8913            !(TLI.isOperationLegalOrCustom(Opc, NewVT) &&
8914              TLI.isNarrowingProfitable(VT, NewVT))) {
8915       NewBW = NextPowerOf2(NewBW);
8916       NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
8917     }
8918     if (NewBW >= BitWidth)
8919       return SDValue();
8920
8921     // If the lsb changed does not start at the type bitwidth boundary,
8922     // start at the previous one.
8923     if (ShAmt % NewBW)
8924       ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
8925     APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
8926                                    std::min(BitWidth, ShAmt + NewBW));
8927     if ((Imm & Mask) == Imm) {
8928       APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
8929       if (Opc == ISD::AND)
8930         NewImm ^= APInt::getAllOnesValue(NewBW);
8931       uint64_t PtrOff = ShAmt / 8;
8932       // For big endian targets, we need to adjust the offset to the pointer to
8933       // load the correct bytes.
8934       if (TLI.isBigEndian())
8935         PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
8936
8937       unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
8938       Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
8939       if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
8940         return SDValue();
8941
8942       SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
8943                                    Ptr.getValueType(), Ptr,
8944                                    DAG.getConstant(PtrOff, Ptr.getValueType()));
8945       SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
8946                                   LD->getChain(), NewPtr,
8947                                   LD->getPointerInfo().getWithOffset(PtrOff),
8948                                   LD->isVolatile(), LD->isNonTemporal(),
8949                                   LD->isInvariant(), NewAlign,
8950                                   LD->getAAInfo());
8951       SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
8952                                    DAG.getConstant(NewImm, NewVT));
8953       SDValue NewST = DAG.getStore(Chain, SDLoc(N),
8954                                    NewVal, NewPtr,
8955                                    ST->getPointerInfo().getWithOffset(PtrOff),
8956                                    false, false, NewAlign);
8957
8958       AddToWorklist(NewPtr.getNode());
8959       AddToWorklist(NewLD.getNode());
8960       AddToWorklist(NewVal.getNode());
8961       WorklistRemover DeadNodes(*this);
8962       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
8963       ++OpsNarrowed;
8964       return NewST;
8965     }
8966   }
8967
8968   return SDValue();
8969 }
8970
8971 /// TransformFPLoadStorePair - For a given floating point load / store pair,
8972 /// if the load value isn't used by any other operations, then consider
8973 /// transforming the pair to integer load / store operations if the target
8974 /// deems the transformation profitable.
8975 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
8976   StoreSDNode *ST  = cast<StoreSDNode>(N);
8977   SDValue Chain = ST->getChain();
8978   SDValue Value = ST->getValue();
8979   if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
8980       Value.hasOneUse() &&
8981       Chain == SDValue(Value.getNode(), 1)) {
8982     LoadSDNode *LD = cast<LoadSDNode>(Value);
8983     EVT VT = LD->getMemoryVT();
8984     if (!VT.isFloatingPoint() ||
8985         VT != ST->getMemoryVT() ||
8986         LD->isNonTemporal() ||
8987         ST->isNonTemporal() ||
8988         LD->getPointerInfo().getAddrSpace() != 0 ||
8989         ST->getPointerInfo().getAddrSpace() != 0)
8990       return SDValue();
8991
8992     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
8993     if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
8994         !TLI.isOperationLegal(ISD::STORE, IntVT) ||
8995         !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
8996         !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
8997       return SDValue();
8998
8999     unsigned LDAlign = LD->getAlignment();
9000     unsigned STAlign = ST->getAlignment();
9001     Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
9002     unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
9003     if (LDAlign < ABIAlign || STAlign < ABIAlign)
9004       return SDValue();
9005
9006     SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
9007                                 LD->getChain(), LD->getBasePtr(),
9008                                 LD->getPointerInfo(),
9009                                 false, false, false, LDAlign);
9010
9011     SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
9012                                  NewLD, ST->getBasePtr(),
9013                                  ST->getPointerInfo(),
9014                                  false, false, STAlign);
9015
9016     AddToWorklist(NewLD.getNode());
9017     AddToWorklist(NewST.getNode());
9018     WorklistRemover DeadNodes(*this);
9019     DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
9020     ++LdStFP2Int;
9021     return NewST;
9022   }
9023
9024   return SDValue();
9025 }
9026
9027 /// Helper struct to parse and store a memory address as base + index + offset.
9028 /// We ignore sign extensions when it is safe to do so.
9029 /// The following two expressions are not equivalent. To differentiate we need
9030 /// to store whether there was a sign extension involved in the index
9031 /// computation.
9032 ///  (load (i64 add (i64 copyfromreg %c)
9033 ///                 (i64 signextend (add (i8 load %index)
9034 ///                                      (i8 1))))
9035 /// vs
9036 ///
9037 /// (load (i64 add (i64 copyfromreg %c)
9038 ///                (i64 signextend (i32 add (i32 signextend (i8 load %index))
9039 ///                                         (i32 1)))))
9040 struct BaseIndexOffset {
9041   SDValue Base;
9042   SDValue Index;
9043   int64_t Offset;
9044   bool IsIndexSignExt;
9045
9046   BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
9047
9048   BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
9049                   bool IsIndexSignExt) :
9050     Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
9051
9052   bool equalBaseIndex(const BaseIndexOffset &Other) {
9053     return Other.Base == Base && Other.Index == Index &&
9054       Other.IsIndexSignExt == IsIndexSignExt;
9055   }
9056
9057   /// Parses tree in Ptr for base, index, offset addresses.
9058   static BaseIndexOffset match(SDValue Ptr) {
9059     bool IsIndexSignExt = false;
9060
9061     // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
9062     // instruction, then it could be just the BASE or everything else we don't
9063     // know how to handle. Just use Ptr as BASE and give up.
9064     if (Ptr->getOpcode() != ISD::ADD)
9065       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9066
9067     // We know that we have at least an ADD instruction. Try to pattern match
9068     // the simple case of BASE + OFFSET.
9069     if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
9070       int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
9071       return  BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
9072                               IsIndexSignExt);
9073     }
9074
9075     // Inside a loop the current BASE pointer is calculated using an ADD and a
9076     // MUL instruction. In this case Ptr is the actual BASE pointer.
9077     // (i64 add (i64 %array_ptr)
9078     //          (i64 mul (i64 %induction_var)
9079     //                   (i64 %element_size)))
9080     if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
9081       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9082
9083     // Look at Base + Index + Offset cases.
9084     SDValue Base = Ptr->getOperand(0);
9085     SDValue IndexOffset = Ptr->getOperand(1);
9086
9087     // Skip signextends.
9088     if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
9089       IndexOffset = IndexOffset->getOperand(0);
9090       IsIndexSignExt = true;
9091     }
9092
9093     // Either the case of Base + Index (no offset) or something else.
9094     if (IndexOffset->getOpcode() != ISD::ADD)
9095       return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
9096
9097     // Now we have the case of Base + Index + offset.
9098     SDValue Index = IndexOffset->getOperand(0);
9099     SDValue Offset = IndexOffset->getOperand(1);
9100
9101     if (!isa<ConstantSDNode>(Offset))
9102       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9103
9104     // Ignore signextends.
9105     if (Index->getOpcode() == ISD::SIGN_EXTEND) {
9106       Index = Index->getOperand(0);
9107       IsIndexSignExt = true;
9108     } else IsIndexSignExt = false;
9109
9110     int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
9111     return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
9112   }
9113 };
9114
9115 /// Holds a pointer to an LSBaseSDNode as well as information on where it
9116 /// is located in a sequence of memory operations connected by a chain.
9117 struct MemOpLink {
9118   MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
9119     MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
9120   // Ptr to the mem node.
9121   LSBaseSDNode *MemNode;
9122   // Offset from the base ptr.
9123   int64_t OffsetFromBase;
9124   // What is the sequence number of this mem node.
9125   // Lowest mem operand in the DAG starts at zero.
9126   unsigned SequenceNum;
9127 };
9128
9129 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
9130   EVT MemVT = St->getMemoryVT();
9131   int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
9132   bool NoVectors = DAG.getMachineFunction().getFunction()->getAttributes().
9133     hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
9134
9135   // Don't merge vectors into wider inputs.
9136   if (MemVT.isVector() || !MemVT.isSimple())
9137     return false;
9138
9139   // Perform an early exit check. Do not bother looking at stored values that
9140   // are not constants or loads.
9141   SDValue StoredVal = St->getValue();
9142   bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
9143   if (!isa<ConstantSDNode>(StoredVal) && !isa<ConstantFPSDNode>(StoredVal) &&
9144       !IsLoadSrc)
9145     return false;
9146
9147   // Only look at ends of store sequences.
9148   SDValue Chain = SDValue(St, 0);
9149   if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
9150     return false;
9151
9152   // This holds the base pointer, index, and the offset in bytes from the base
9153   // pointer.
9154   BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
9155
9156   // We must have a base and an offset.
9157   if (!BasePtr.Base.getNode())
9158     return false;
9159
9160   // Do not handle stores to undef base pointers.
9161   if (BasePtr.Base.getOpcode() == ISD::UNDEF)
9162     return false;
9163
9164   // Save the LoadSDNodes that we find in the chain.
9165   // We need to make sure that these nodes do not interfere with
9166   // any of the store nodes.
9167   SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
9168
9169   // Save the StoreSDNodes that we find in the chain.
9170   SmallVector<MemOpLink, 8> StoreNodes;
9171
9172   // Walk up the chain and look for nodes with offsets from the same
9173   // base pointer. Stop when reaching an instruction with a different kind
9174   // or instruction which has a different base pointer.
9175   unsigned Seq = 0;
9176   StoreSDNode *Index = St;
9177   while (Index) {
9178     // If the chain has more than one use, then we can't reorder the mem ops.
9179     if (Index != St && !SDValue(Index, 0)->hasOneUse())
9180       break;
9181
9182     // Find the base pointer and offset for this memory node.
9183     BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
9184
9185     // Check that the base pointer is the same as the original one.
9186     if (!Ptr.equalBaseIndex(BasePtr))
9187       break;
9188
9189     // Check that the alignment is the same.
9190     if (Index->getAlignment() != St->getAlignment())
9191       break;
9192
9193     // The memory operands must not be volatile.
9194     if (Index->isVolatile() || Index->isIndexed())
9195       break;
9196
9197     // No truncation.
9198     if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
9199       if (St->isTruncatingStore())
9200         break;
9201
9202     // The stored memory type must be the same.
9203     if (Index->getMemoryVT() != MemVT)
9204       break;
9205
9206     // We do not allow unaligned stores because we want to prevent overriding
9207     // stores.
9208     if (Index->getAlignment()*8 != MemVT.getSizeInBits())
9209       break;
9210
9211     // We found a potential memory operand to merge.
9212     StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
9213
9214     // Find the next memory operand in the chain. If the next operand in the
9215     // chain is a store then move up and continue the scan with the next
9216     // memory operand. If the next operand is a load save it and use alias
9217     // information to check if it interferes with anything.
9218     SDNode *NextInChain = Index->getChain().getNode();
9219     while (1) {
9220       if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
9221         // We found a store node. Use it for the next iteration.
9222         Index = STn;
9223         break;
9224       } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
9225         if (Ldn->isVolatile()) {
9226           Index = nullptr;
9227           break;
9228         }
9229
9230         // Save the load node for later. Continue the scan.
9231         AliasLoadNodes.push_back(Ldn);
9232         NextInChain = Ldn->getChain().getNode();
9233         continue;
9234       } else {
9235         Index = nullptr;
9236         break;
9237       }
9238     }
9239   }
9240
9241   // Check if there is anything to merge.
9242   if (StoreNodes.size() < 2)
9243     return false;
9244
9245   // Sort the memory operands according to their distance from the base pointer.
9246   std::sort(StoreNodes.begin(), StoreNodes.end(),
9247             [](MemOpLink LHS, MemOpLink RHS) {
9248     return LHS.OffsetFromBase < RHS.OffsetFromBase ||
9249            (LHS.OffsetFromBase == RHS.OffsetFromBase &&
9250             LHS.SequenceNum > RHS.SequenceNum);
9251   });
9252
9253   // Scan the memory operations on the chain and find the first non-consecutive
9254   // store memory address.
9255   unsigned LastConsecutiveStore = 0;
9256   int64_t StartAddress = StoreNodes[0].OffsetFromBase;
9257   for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
9258
9259     // Check that the addresses are consecutive starting from the second
9260     // element in the list of stores.
9261     if (i > 0) {
9262       int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
9263       if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9264         break;
9265     }
9266
9267     bool Alias = false;
9268     // Check if this store interferes with any of the loads that we found.
9269     for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
9270       if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
9271         Alias = true;
9272         break;
9273       }
9274     // We found a load that alias with this store. Stop the sequence.
9275     if (Alias)
9276       break;
9277
9278     // Mark this node as useful.
9279     LastConsecutiveStore = i;
9280   }
9281
9282   // The node with the lowest store address.
9283   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
9284
9285   // Store the constants into memory as one consecutive store.
9286   if (!IsLoadSrc) {
9287     unsigned LastLegalType = 0;
9288     unsigned LastLegalVectorType = 0;
9289     bool NonZero = false;
9290     for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9291       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
9292       SDValue StoredVal = St->getValue();
9293
9294       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
9295         NonZero |= !C->isNullValue();
9296       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
9297         NonZero |= !C->getConstantFPValue()->isNullValue();
9298       } else {
9299         // Non-constant.
9300         break;
9301       }
9302
9303       // Find a legal type for the constant store.
9304       unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9305       EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9306       if (TLI.isTypeLegal(StoreTy))
9307         LastLegalType = i+1;
9308       // Or check whether a truncstore is legal.
9309       else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9310                TargetLowering::TypePromoteInteger) {
9311         EVT LegalizedStoredValueTy =
9312           TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
9313         if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy))
9314           LastLegalType = i+1;
9315       }
9316
9317       // Find a legal type for the vector store.
9318       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9319       if (TLI.isTypeLegal(Ty))
9320         LastLegalVectorType = i + 1;
9321     }
9322
9323     // We only use vectors if the constant is known to be zero and the
9324     // function is not marked with the noimplicitfloat attribute.
9325     if (NonZero || NoVectors)
9326       LastLegalVectorType = 0;
9327
9328     // Check if we found a legal integer type to store.
9329     if (LastLegalType == 0 && LastLegalVectorType == 0)
9330       return false;
9331
9332     bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
9333     unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
9334
9335     // Make sure we have something to merge.
9336     if (NumElem < 2)
9337       return false;
9338
9339     unsigned EarliestNodeUsed = 0;
9340     for (unsigned i=0; i < NumElem; ++i) {
9341       // Find a chain for the new wide-store operand. Notice that some
9342       // of the store nodes that we found may not be selected for inclusion
9343       // in the wide store. The chain we use needs to be the chain of the
9344       // earliest store node which is *used* and replaced by the wide store.
9345       if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9346         EarliestNodeUsed = i;
9347     }
9348
9349     // The earliest Node in the DAG.
9350     LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9351     SDLoc DL(StoreNodes[0].MemNode);
9352
9353     SDValue StoredVal;
9354     if (UseVector) {
9355       // Find a legal type for the vector store.
9356       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9357       assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
9358       StoredVal = DAG.getConstant(0, Ty);
9359     } else {
9360       unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9361       APInt StoreInt(StoreBW, 0);
9362
9363       // Construct a single integer constant which is made of the smaller
9364       // constant inputs.
9365       bool IsLE = TLI.isLittleEndian();
9366       for (unsigned i = 0; i < NumElem ; ++i) {
9367         unsigned Idx = IsLE ?(NumElem - 1 - i) : i;
9368         StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
9369         SDValue Val = St->getValue();
9370         StoreInt<<=ElementSizeBytes*8;
9371         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
9372           StoreInt|=C->getAPIntValue().zext(StoreBW);
9373         } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
9374           StoreInt|= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
9375         } else {
9376           assert(false && "Invalid constant element type");
9377         }
9378       }
9379
9380       // Create the new Load and Store operations.
9381       EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9382       StoredVal = DAG.getConstant(StoreInt, StoreTy);
9383     }
9384
9385     SDValue NewStore = DAG.getStore(EarliestOp->getChain(), DL, StoredVal,
9386                                     FirstInChain->getBasePtr(),
9387                                     FirstInChain->getPointerInfo(),
9388                                     false, false,
9389                                     FirstInChain->getAlignment());
9390
9391     // Replace the first store with the new store
9392     CombineTo(EarliestOp, NewStore);
9393     // Erase all other stores.
9394     for (unsigned i = 0; i < NumElem ; ++i) {
9395       if (StoreNodes[i].MemNode == EarliestOp)
9396         continue;
9397       StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9398       // ReplaceAllUsesWith will replace all uses that existed when it was
9399       // called, but graph optimizations may cause new ones to appear. For
9400       // example, the case in pr14333 looks like
9401       //
9402       //  St's chain -> St -> another store -> X
9403       //
9404       // And the only difference from St to the other store is the chain.
9405       // When we change it's chain to be St's chain they become identical,
9406       // get CSEed and the net result is that X is now a use of St.
9407       // Since we know that St is redundant, just iterate.
9408       while (!St->use_empty())
9409         DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
9410       deleteAndRecombine(St);
9411     }
9412
9413     return true;
9414   }
9415
9416   // Below we handle the case of multiple consecutive stores that
9417   // come from multiple consecutive loads. We merge them into a single
9418   // wide load and a single wide store.
9419
9420   // Look for load nodes which are used by the stored values.
9421   SmallVector<MemOpLink, 8> LoadNodes;
9422
9423   // Find acceptable loads. Loads need to have the same chain (token factor),
9424   // must not be zext, volatile, indexed, and they must be consecutive.
9425   BaseIndexOffset LdBasePtr;
9426   for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9427     StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
9428     LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
9429     if (!Ld) break;
9430
9431     // Loads must only have one use.
9432     if (!Ld->hasNUsesOfValue(1, 0))
9433       break;
9434
9435     // Check that the alignment is the same as the stores.
9436     if (Ld->getAlignment() != St->getAlignment())
9437       break;
9438
9439     // The memory operands must not be volatile.
9440     if (Ld->isVolatile() || Ld->isIndexed())
9441       break;
9442
9443     // We do not accept ext loads.
9444     if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
9445       break;
9446
9447     // The stored memory type must be the same.
9448     if (Ld->getMemoryVT() != MemVT)
9449       break;
9450
9451     BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
9452     // If this is not the first ptr that we check.
9453     if (LdBasePtr.Base.getNode()) {
9454       // The base ptr must be the same.
9455       if (!LdPtr.equalBaseIndex(LdBasePtr))
9456         break;
9457     } else {
9458       // Check that all other base pointers are the same as this one.
9459       LdBasePtr = LdPtr;
9460     }
9461
9462     // We found a potential memory operand to merge.
9463     LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
9464   }
9465
9466   if (LoadNodes.size() < 2)
9467     return false;
9468
9469   // If we have load/store pair instructions and we only have two values,
9470   // don't bother.
9471   unsigned RequiredAlignment;
9472   if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) &&
9473       St->getAlignment() >= RequiredAlignment)
9474     return false;
9475
9476   // Scan the memory operations on the chain and find the first non-consecutive
9477   // load memory address. These variables hold the index in the store node
9478   // array.
9479   unsigned LastConsecutiveLoad = 0;
9480   // This variable refers to the size and not index in the array.
9481   unsigned LastLegalVectorType = 0;
9482   unsigned LastLegalIntegerType = 0;
9483   StartAddress = LoadNodes[0].OffsetFromBase;
9484   SDValue FirstChain = LoadNodes[0].MemNode->getChain();
9485   for (unsigned i = 1; i < LoadNodes.size(); ++i) {
9486     // All loads much share the same chain.
9487     if (LoadNodes[i].MemNode->getChain() != FirstChain)
9488       break;
9489
9490     int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
9491     if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9492       break;
9493     LastConsecutiveLoad = i;
9494
9495     // Find a legal type for the vector store.
9496     EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9497     if (TLI.isTypeLegal(StoreTy))
9498       LastLegalVectorType = i + 1;
9499
9500     // Find a legal type for the integer store.
9501     unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9502     StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9503     if (TLI.isTypeLegal(StoreTy))
9504       LastLegalIntegerType = i + 1;
9505     // Or check whether a truncstore and extload is legal.
9506     else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9507              TargetLowering::TypePromoteInteger) {
9508       EVT LegalizedStoredValueTy =
9509         TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
9510       if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
9511           TLI.isLoadExtLegal(ISD::ZEXTLOAD, StoreTy) &&
9512           TLI.isLoadExtLegal(ISD::SEXTLOAD, StoreTy) &&
9513           TLI.isLoadExtLegal(ISD::EXTLOAD, StoreTy))
9514         LastLegalIntegerType = i+1;
9515     }
9516   }
9517
9518   // Only use vector types if the vector type is larger than the integer type.
9519   // If they are the same, use integers.
9520   bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
9521   unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
9522
9523   // We add +1 here because the LastXXX variables refer to location while
9524   // the NumElem refers to array/index size.
9525   unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
9526   NumElem = std::min(LastLegalType, NumElem);
9527
9528   if (NumElem < 2)
9529     return false;
9530
9531   // The earliest Node in the DAG.
9532   unsigned EarliestNodeUsed = 0;
9533   LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9534   for (unsigned i=1; i<NumElem; ++i) {
9535     // Find a chain for the new wide-store operand. Notice that some
9536     // of the store nodes that we found may not be selected for inclusion
9537     // in the wide store. The chain we use needs to be the chain of the
9538     // earliest store node which is *used* and replaced by the wide store.
9539     if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9540       EarliestNodeUsed = i;
9541   }
9542
9543   // Find if it is better to use vectors or integers to load and store
9544   // to memory.
9545   EVT JointMemOpVT;
9546   if (UseVectorTy) {
9547     JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9548   } else {
9549     unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9550     JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9551   }
9552
9553   SDLoc LoadDL(LoadNodes[0].MemNode);
9554   SDLoc StoreDL(StoreNodes[0].MemNode);
9555
9556   LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
9557   SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL,
9558                                 FirstLoad->getChain(),
9559                                 FirstLoad->getBasePtr(),
9560                                 FirstLoad->getPointerInfo(),
9561                                 false, false, false,
9562                                 FirstLoad->getAlignment());
9563
9564   SDValue NewStore = DAG.getStore(EarliestOp->getChain(), StoreDL, NewLoad,
9565                                   FirstInChain->getBasePtr(),
9566                                   FirstInChain->getPointerInfo(), false, false,
9567                                   FirstInChain->getAlignment());
9568
9569   // Replace one of the loads with the new load.
9570   LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
9571   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
9572                                 SDValue(NewLoad.getNode(), 1));
9573
9574   // Remove the rest of the load chains.
9575   for (unsigned i = 1; i < NumElem ; ++i) {
9576     // Replace all chain users of the old load nodes with the chain of the new
9577     // load node.
9578     LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
9579     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
9580   }
9581
9582   // Replace the first store with the new store.
9583   CombineTo(EarliestOp, NewStore);
9584   // Erase all other stores.
9585   for (unsigned i = 0; i < NumElem ; ++i) {
9586     // Remove all Store nodes.
9587     if (StoreNodes[i].MemNode == EarliestOp)
9588       continue;
9589     StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9590     DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
9591     deleteAndRecombine(St);
9592   }
9593
9594   return true;
9595 }
9596
9597 SDValue DAGCombiner::visitSTORE(SDNode *N) {
9598   StoreSDNode *ST  = cast<StoreSDNode>(N);
9599   SDValue Chain = ST->getChain();
9600   SDValue Value = ST->getValue();
9601   SDValue Ptr   = ST->getBasePtr();
9602
9603   // If this is a store of a bit convert, store the input value if the
9604   // resultant store does not need a higher alignment than the original.
9605   if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
9606       ST->isUnindexed()) {
9607     unsigned OrigAlign = ST->getAlignment();
9608     EVT SVT = Value.getOperand(0).getValueType();
9609     unsigned Align = TLI.getDataLayout()->
9610       getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
9611     if (Align <= OrigAlign &&
9612         ((!LegalOperations && !ST->isVolatile()) ||
9613          TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
9614       return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
9615                           Ptr, ST->getPointerInfo(), ST->isVolatile(),
9616                           ST->isNonTemporal(), OrigAlign,
9617                           ST->getAAInfo());
9618   }
9619
9620   // Turn 'store undef, Ptr' -> nothing.
9621   if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
9622     return Chain;
9623
9624   // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
9625   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
9626     // NOTE: If the original store is volatile, this transform must not increase
9627     // the number of stores.  For example, on x86-32 an f64 can be stored in one
9628     // processor operation but an i64 (which is not legal) requires two.  So the
9629     // transform should not be done in this case.
9630     if (Value.getOpcode() != ISD::TargetConstantFP) {
9631       SDValue Tmp;
9632       switch (CFP->getSimpleValueType(0).SimpleTy) {
9633       default: llvm_unreachable("Unknown FP type");
9634       case MVT::f16:    // We don't do this for these yet.
9635       case MVT::f80:
9636       case MVT::f128:
9637       case MVT::ppcf128:
9638         break;
9639       case MVT::f32:
9640         if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
9641             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
9642           Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
9643                               bitcastToAPInt().getZExtValue(), MVT::i32);
9644           return DAG.getStore(Chain, SDLoc(N), Tmp,
9645                               Ptr, ST->getMemOperand());
9646         }
9647         break;
9648       case MVT::f64:
9649         if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
9650              !ST->isVolatile()) ||
9651             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
9652           Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
9653                                 getZExtValue(), MVT::i64);
9654           return DAG.getStore(Chain, SDLoc(N), Tmp,
9655                               Ptr, ST->getMemOperand());
9656         }
9657
9658         if (!ST->isVolatile() &&
9659             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
9660           // Many FP stores are not made apparent until after legalize, e.g. for
9661           // argument passing.  Since this is so common, custom legalize the
9662           // 64-bit integer store into two 32-bit stores.
9663           uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
9664           SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
9665           SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
9666           if (TLI.isBigEndian()) std::swap(Lo, Hi);
9667
9668           unsigned Alignment = ST->getAlignment();
9669           bool isVolatile = ST->isVolatile();
9670           bool isNonTemporal = ST->isNonTemporal();
9671           AAMDNodes AAInfo = ST->getAAInfo();
9672
9673           SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
9674                                      Ptr, ST->getPointerInfo(),
9675                                      isVolatile, isNonTemporal,
9676                                      ST->getAlignment(), AAInfo);
9677           Ptr = DAG.getNode(ISD::ADD, SDLoc(N), Ptr.getValueType(), Ptr,
9678                             DAG.getConstant(4, Ptr.getValueType()));
9679           Alignment = MinAlign(Alignment, 4U);
9680           SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
9681                                      Ptr, ST->getPointerInfo().getWithOffset(4),
9682                                      isVolatile, isNonTemporal,
9683                                      Alignment, AAInfo);
9684           return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
9685                              St0, St1);
9686         }
9687
9688         break;
9689       }
9690     }
9691   }
9692
9693   // Try to infer better alignment information than the store already has.
9694   if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
9695     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
9696       if (Align > ST->getAlignment())
9697         return DAG.getTruncStore(Chain, SDLoc(N), Value,
9698                                  Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
9699                                  ST->isVolatile(), ST->isNonTemporal(), Align,
9700                                  ST->getAAInfo());
9701     }
9702   }
9703
9704   // Try transforming a pair floating point load / store ops to integer
9705   // load / store ops.
9706   SDValue NewST = TransformFPLoadStorePair(N);
9707   if (NewST.getNode())
9708     return NewST;
9709
9710   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
9711     TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
9712 #ifndef NDEBUG
9713   if (CombinerAAOnlyFunc.getNumOccurrences() &&
9714       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
9715     UseAA = false;
9716 #endif
9717   if (UseAA && ST->isUnindexed()) {
9718     // Walk up chain skipping non-aliasing memory nodes.
9719     SDValue BetterChain = FindBetterChain(N, Chain);
9720
9721     // If there is a better chain.
9722     if (Chain != BetterChain) {
9723       SDValue ReplStore;
9724
9725       // Replace the chain to avoid dependency.
9726       if (ST->isTruncatingStore()) {
9727         ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
9728                                       ST->getMemoryVT(), ST->getMemOperand());
9729       } else {
9730         ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
9731                                  ST->getMemOperand());
9732       }
9733
9734       // Create token to keep both nodes around.
9735       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
9736                                   MVT::Other, Chain, ReplStore);
9737
9738       // Make sure the new and old chains are cleaned up.
9739       AddToWorklist(Token.getNode());
9740
9741       // Don't add users to work list.
9742       return CombineTo(N, Token, false);
9743     }
9744   }
9745
9746   // Try transforming N to an indexed store.
9747   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
9748     return SDValue(N, 0);
9749
9750   // FIXME: is there such a thing as a truncating indexed store?
9751   if (ST->isTruncatingStore() && ST->isUnindexed() &&
9752       Value.getValueType().isInteger()) {
9753     // See if we can simplify the input to this truncstore with knowledge that
9754     // only the low bits are being used.  For example:
9755     // "truncstore (or (shl x, 8), y), i8"  -> "truncstore y, i8"
9756     SDValue Shorter =
9757       GetDemandedBits(Value,
9758                       APInt::getLowBitsSet(
9759                         Value.getValueType().getScalarType().getSizeInBits(),
9760                         ST->getMemoryVT().getScalarType().getSizeInBits()));
9761     AddToWorklist(Value.getNode());
9762     if (Shorter.getNode())
9763       return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
9764                                Ptr, ST->getMemoryVT(), ST->getMemOperand());
9765
9766     // Otherwise, see if we can simplify the operation with
9767     // SimplifyDemandedBits, which only works if the value has a single use.
9768     if (SimplifyDemandedBits(Value,
9769                         APInt::getLowBitsSet(
9770                           Value.getValueType().getScalarType().getSizeInBits(),
9771                           ST->getMemoryVT().getScalarType().getSizeInBits())))
9772       return SDValue(N, 0);
9773   }
9774
9775   // If this is a load followed by a store to the same location, then the store
9776   // is dead/noop.
9777   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
9778     if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
9779         ST->isUnindexed() && !ST->isVolatile() &&
9780         // There can't be any side effects between the load and store, such as
9781         // a call or store.
9782         Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
9783       // The store is dead, remove it.
9784       return Chain;
9785     }
9786   }
9787
9788   // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
9789   // truncating store.  We can do this even if this is already a truncstore.
9790   if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
9791       && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
9792       TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
9793                             ST->getMemoryVT())) {
9794     return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
9795                              Ptr, ST->getMemoryVT(), ST->getMemOperand());
9796   }
9797
9798   // Only perform this optimization before the types are legal, because we
9799   // don't want to perform this optimization on every DAGCombine invocation.
9800   if (!LegalTypes) {
9801     bool EverChanged = false;
9802
9803     do {
9804       // There can be multiple store sequences on the same chain.
9805       // Keep trying to merge store sequences until we are unable to do so
9806       // or until we merge the last store on the chain.
9807       bool Changed = MergeConsecutiveStores(ST);
9808       EverChanged |= Changed;
9809       if (!Changed) break;
9810     } while (ST->getOpcode() != ISD::DELETED_NODE);
9811
9812     if (EverChanged)
9813       return SDValue(N, 0);
9814   }
9815
9816   return ReduceLoadOpStoreWidth(N);
9817 }
9818
9819 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
9820   SDValue InVec = N->getOperand(0);
9821   SDValue InVal = N->getOperand(1);
9822   SDValue EltNo = N->getOperand(2);
9823   SDLoc dl(N);
9824
9825   // If the inserted element is an UNDEF, just use the input vector.
9826   if (InVal.getOpcode() == ISD::UNDEF)
9827     return InVec;
9828
9829   EVT VT = InVec.getValueType();
9830
9831   // If we can't generate a legal BUILD_VECTOR, exit
9832   if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
9833     return SDValue();
9834
9835   // Check that we know which element is being inserted
9836   if (!isa<ConstantSDNode>(EltNo))
9837     return SDValue();
9838   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9839
9840   // Canonicalize insert_vector_elt dag nodes.
9841   // Example:
9842   // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
9843   // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
9844   //
9845   // Do this only if the child insert_vector node has one use; also
9846   // do this only if indices are both constants and Idx1 < Idx0.
9847   if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
9848       && isa<ConstantSDNode>(InVec.getOperand(2))) {
9849     unsigned OtherElt =
9850       cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue();
9851     if (Elt < OtherElt) {
9852       // Swap nodes.
9853       SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT,
9854                                   InVec.getOperand(0), InVal, EltNo);
9855       AddToWorklist(NewOp.getNode());
9856       return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
9857                          VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
9858     }
9859   }
9860
9861   // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
9862   // be converted to a BUILD_VECTOR).  Fill in the Ops vector with the
9863   // vector elements.
9864   SmallVector<SDValue, 8> Ops;
9865   // Do not combine these two vectors if the output vector will not replace
9866   // the input vector.
9867   if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
9868     Ops.append(InVec.getNode()->op_begin(),
9869                InVec.getNode()->op_end());
9870   } else if (InVec.getOpcode() == ISD::UNDEF) {
9871     unsigned NElts = VT.getVectorNumElements();
9872     Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
9873   } else {
9874     return SDValue();
9875   }
9876
9877   // Insert the element
9878   if (Elt < Ops.size()) {
9879     // All the operands of BUILD_VECTOR must have the same type;
9880     // we enforce that here.
9881     EVT OpVT = Ops[0].getValueType();
9882     if (InVal.getValueType() != OpVT)
9883       InVal = OpVT.bitsGT(InVal.getValueType()) ?
9884                 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
9885                 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
9886     Ops[Elt] = InVal;
9887   }
9888
9889   // Return the new vector
9890   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
9891 }
9892
9893 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
9894     SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) {
9895   EVT ResultVT = EVE->getValueType(0);
9896   EVT VecEltVT = InVecVT.getVectorElementType();
9897   unsigned Align = OriginalLoad->getAlignment();
9898   unsigned NewAlign = TLI.getDataLayout()->getABITypeAlignment(
9899       VecEltVT.getTypeForEVT(*DAG.getContext()));
9900
9901   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
9902     return SDValue();
9903
9904   Align = NewAlign;
9905
9906   SDValue NewPtr = OriginalLoad->getBasePtr();
9907   SDValue Offset;
9908   EVT PtrType = NewPtr.getValueType();
9909   MachinePointerInfo MPI;
9910   if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
9911     int Elt = ConstEltNo->getZExtValue();
9912     unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
9913     if (TLI.isBigEndian())
9914       PtrOff = InVecVT.getSizeInBits() / 8 - PtrOff;
9915     Offset = DAG.getConstant(PtrOff, PtrType);
9916     MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
9917   } else {
9918     Offset = DAG.getNode(
9919         ISD::MUL, SDLoc(EVE), EltNo.getValueType(), EltNo,
9920         DAG.getConstant(VecEltVT.getStoreSize(), EltNo.getValueType()));
9921     if (TLI.isBigEndian())
9922       Offset = DAG.getNode(
9923           ISD::SUB, SDLoc(EVE), EltNo.getValueType(),
9924           DAG.getConstant(InVecVT.getStoreSize(), EltNo.getValueType()), Offset);
9925     MPI = OriginalLoad->getPointerInfo();
9926   }
9927   NewPtr = DAG.getNode(ISD::ADD, SDLoc(EVE), PtrType, NewPtr, Offset);
9928
9929   // The replacement we need to do here is a little tricky: we need to
9930   // replace an extractelement of a load with a load.
9931   // Use ReplaceAllUsesOfValuesWith to do the replacement.
9932   // Note that this replacement assumes that the extractvalue is the only
9933   // use of the load; that's okay because we don't want to perform this
9934   // transformation in other cases anyway.
9935   SDValue Load;
9936   SDValue Chain;
9937   if (ResultVT.bitsGT(VecEltVT)) {
9938     // If the result type of vextract is wider than the load, then issue an
9939     // extending load instead.
9940     ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, VecEltVT)
9941                                    ? ISD::ZEXTLOAD
9942                                    : ISD::EXTLOAD;
9943     Load = DAG.getExtLoad(
9944         ExtType, SDLoc(EVE), ResultVT, OriginalLoad->getChain(), NewPtr, MPI,
9945         VecEltVT, OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
9946         OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
9947     Chain = Load.getValue(1);
9948   } else {
9949     Load = DAG.getLoad(
9950         VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, MPI,
9951         OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
9952         OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
9953     Chain = Load.getValue(1);
9954     if (ResultVT.bitsLT(VecEltVT))
9955       Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
9956     else
9957       Load = DAG.getNode(ISD::BITCAST, SDLoc(EVE), ResultVT, Load);
9958   }
9959   WorklistRemover DeadNodes(*this);
9960   SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
9961   SDValue To[] = { Load, Chain };
9962   DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
9963   // Since we're explicitly calling ReplaceAllUses, add the new node to the
9964   // worklist explicitly as well.
9965   AddToWorklist(Load.getNode());
9966   AddUsersToWorklist(Load.getNode()); // Add users too
9967   // Make sure to revisit this node to clean it up; it will usually be dead.
9968   AddToWorklist(EVE);
9969   ++OpsNarrowed;
9970   return SDValue(EVE, 0);
9971 }
9972
9973 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
9974   // (vextract (scalar_to_vector val, 0) -> val
9975   SDValue InVec = N->getOperand(0);
9976   EVT VT = InVec.getValueType();
9977   EVT NVT = N->getValueType(0);
9978
9979   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
9980     // Check if the result type doesn't match the inserted element type. A
9981     // SCALAR_TO_VECTOR may truncate the inserted element and the
9982     // EXTRACT_VECTOR_ELT may widen the extracted vector.
9983     SDValue InOp = InVec.getOperand(0);
9984     if (InOp.getValueType() != NVT) {
9985       assert(InOp.getValueType().isInteger() && NVT.isInteger());
9986       return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
9987     }
9988     return InOp;
9989   }
9990
9991   SDValue EltNo = N->getOperand(1);
9992   bool ConstEltNo = isa<ConstantSDNode>(EltNo);
9993
9994   // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
9995   // We only perform this optimization before the op legalization phase because
9996   // we may introduce new vector instructions which are not backed by TD
9997   // patterns. For example on AVX, extracting elements from a wide vector
9998   // without using extract_subvector. However, if we can find an underlying
9999   // scalar value, then we can always use that.
10000   if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
10001       && ConstEltNo) {
10002     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
10003     int NumElem = VT.getVectorNumElements();
10004     ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
10005     // Find the new index to extract from.
10006     int OrigElt = SVOp->getMaskElt(Elt);
10007
10008     // Extracting an undef index is undef.
10009     if (OrigElt == -1)
10010       return DAG.getUNDEF(NVT);
10011
10012     // Select the right vector half to extract from.
10013     SDValue SVInVec;
10014     if (OrigElt < NumElem) {
10015       SVInVec = InVec->getOperand(0);
10016     } else {
10017       SVInVec = InVec->getOperand(1);
10018       OrigElt -= NumElem;
10019     }
10020
10021     if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
10022       SDValue InOp = SVInVec.getOperand(OrigElt);
10023       if (InOp.getValueType() != NVT) {
10024         assert(InOp.getValueType().isInteger() && NVT.isInteger());
10025         InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
10026       }
10027
10028       return InOp;
10029     }
10030
10031     // FIXME: We should handle recursing on other vector shuffles and
10032     // scalar_to_vector here as well.
10033
10034     if (!LegalOperations) {
10035       EVT IndexTy = TLI.getVectorIdxTy();
10036       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT,
10037                          SVInVec, DAG.getConstant(OrigElt, IndexTy));
10038     }
10039   }
10040
10041   bool BCNumEltsChanged = false;
10042   EVT ExtVT = VT.getVectorElementType();
10043   EVT LVT = ExtVT;
10044
10045   // If the result of load has to be truncated, then it's not necessarily
10046   // profitable.
10047   if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
10048     return SDValue();
10049
10050   if (InVec.getOpcode() == ISD::BITCAST) {
10051     // Don't duplicate a load with other uses.
10052     if (!InVec.hasOneUse())
10053       return SDValue();
10054
10055     EVT BCVT = InVec.getOperand(0).getValueType();
10056     if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
10057       return SDValue();
10058     if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
10059       BCNumEltsChanged = true;
10060     InVec = InVec.getOperand(0);
10061     ExtVT = BCVT.getVectorElementType();
10062   }
10063
10064   // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size)
10065   if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() &&
10066       ISD::isNormalLoad(InVec.getNode()) &&
10067       !N->getOperand(1)->hasPredecessor(InVec.getNode())) {
10068     SDValue Index = N->getOperand(1);
10069     if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec))
10070       return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index,
10071                                                            OrigLoad);
10072   }
10073
10074   // Perform only after legalization to ensure build_vector / vector_shuffle
10075   // optimizations have already been done.
10076   if (!LegalOperations) return SDValue();
10077
10078   // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
10079   // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
10080   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
10081
10082   if (ConstEltNo) {
10083     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
10084
10085     LoadSDNode *LN0 = nullptr;
10086     const ShuffleVectorSDNode *SVN = nullptr;
10087     if (ISD::isNormalLoad(InVec.getNode())) {
10088       LN0 = cast<LoadSDNode>(InVec);
10089     } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
10090                InVec.getOperand(0).getValueType() == ExtVT &&
10091                ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
10092       // Don't duplicate a load with other uses.
10093       if (!InVec.hasOneUse())
10094         return SDValue();
10095
10096       LN0 = cast<LoadSDNode>(InVec.getOperand(0));
10097     } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
10098       // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
10099       // =>
10100       // (load $addr+1*size)
10101
10102       // Don't duplicate a load with other uses.
10103       if (!InVec.hasOneUse())
10104         return SDValue();
10105
10106       // If the bit convert changed the number of elements, it is unsafe
10107       // to examine the mask.
10108       if (BCNumEltsChanged)
10109         return SDValue();
10110
10111       // Select the input vector, guarding against out of range extract vector.
10112       unsigned NumElems = VT.getVectorNumElements();
10113       int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
10114       InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
10115
10116       if (InVec.getOpcode() == ISD::BITCAST) {
10117         // Don't duplicate a load with other uses.
10118         if (!InVec.hasOneUse())
10119           return SDValue();
10120
10121         InVec = InVec.getOperand(0);
10122       }
10123       if (ISD::isNormalLoad(InVec.getNode())) {
10124         LN0 = cast<LoadSDNode>(InVec);
10125         Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
10126         EltNo = DAG.getConstant(Elt, EltNo.getValueType());
10127       }
10128     }
10129
10130     // Make sure we found a non-volatile load and the extractelement is
10131     // the only use.
10132     if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
10133       return SDValue();
10134
10135     // If Idx was -1 above, Elt is going to be -1, so just return undef.
10136     if (Elt == -1)
10137       return DAG.getUNDEF(LVT);
10138
10139     return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0);
10140   }
10141
10142   return SDValue();
10143 }
10144
10145 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
10146 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
10147   // We perform this optimization post type-legalization because
10148   // the type-legalizer often scalarizes integer-promoted vectors.
10149   // Performing this optimization before may create bit-casts which
10150   // will be type-legalized to complex code sequences.
10151   // We perform this optimization only before the operation legalizer because we
10152   // may introduce illegal operations.
10153   if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
10154     return SDValue();
10155
10156   unsigned NumInScalars = N->getNumOperands();
10157   SDLoc dl(N);
10158   EVT VT = N->getValueType(0);
10159
10160   // Check to see if this is a BUILD_VECTOR of a bunch of values
10161   // which come from any_extend or zero_extend nodes. If so, we can create
10162   // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
10163   // optimizations. We do not handle sign-extend because we can't fill the sign
10164   // using shuffles.
10165   EVT SourceType = MVT::Other;
10166   bool AllAnyExt = true;
10167
10168   for (unsigned i = 0; i != NumInScalars; ++i) {
10169     SDValue In = N->getOperand(i);
10170     // Ignore undef inputs.
10171     if (In.getOpcode() == ISD::UNDEF) continue;
10172
10173     bool AnyExt  = In.getOpcode() == ISD::ANY_EXTEND;
10174     bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
10175
10176     // Abort if the element is not an extension.
10177     if (!ZeroExt && !AnyExt) {
10178       SourceType = MVT::Other;
10179       break;
10180     }
10181
10182     // The input is a ZeroExt or AnyExt. Check the original type.
10183     EVT InTy = In.getOperand(0).getValueType();
10184
10185     // Check that all of the widened source types are the same.
10186     if (SourceType == MVT::Other)
10187       // First time.
10188       SourceType = InTy;
10189     else if (InTy != SourceType) {
10190       // Multiple income types. Abort.
10191       SourceType = MVT::Other;
10192       break;
10193     }
10194
10195     // Check if all of the extends are ANY_EXTENDs.
10196     AllAnyExt &= AnyExt;
10197   }
10198
10199   // In order to have valid types, all of the inputs must be extended from the
10200   // same source type and all of the inputs must be any or zero extend.
10201   // Scalar sizes must be a power of two.
10202   EVT OutScalarTy = VT.getScalarType();
10203   bool ValidTypes = SourceType != MVT::Other &&
10204                  isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
10205                  isPowerOf2_32(SourceType.getSizeInBits());
10206
10207   // Create a new simpler BUILD_VECTOR sequence which other optimizations can
10208   // turn into a single shuffle instruction.
10209   if (!ValidTypes)
10210     return SDValue();
10211
10212   bool isLE = TLI.isLittleEndian();
10213   unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
10214   assert(ElemRatio > 1 && "Invalid element size ratio");
10215   SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
10216                                DAG.getConstant(0, SourceType);
10217
10218   unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
10219   SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
10220
10221   // Populate the new build_vector
10222   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
10223     SDValue Cast = N->getOperand(i);
10224     assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
10225             Cast.getOpcode() == ISD::ZERO_EXTEND ||
10226             Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
10227     SDValue In;
10228     if (Cast.getOpcode() == ISD::UNDEF)
10229       In = DAG.getUNDEF(SourceType);
10230     else
10231       In = Cast->getOperand(0);
10232     unsigned Index = isLE ? (i * ElemRatio) :
10233                             (i * ElemRatio + (ElemRatio - 1));
10234
10235     assert(Index < Ops.size() && "Invalid index");
10236     Ops[Index] = In;
10237   }
10238
10239   // The type of the new BUILD_VECTOR node.
10240   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
10241   assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
10242          "Invalid vector size");
10243   // Check if the new vector type is legal.
10244   if (!isTypeLegal(VecVT)) return SDValue();
10245
10246   // Make the new BUILD_VECTOR.
10247   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
10248
10249   // The new BUILD_VECTOR node has the potential to be further optimized.
10250   AddToWorklist(BV.getNode());
10251   // Bitcast to the desired type.
10252   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
10253 }
10254
10255 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
10256   EVT VT = N->getValueType(0);
10257
10258   unsigned NumInScalars = N->getNumOperands();
10259   SDLoc dl(N);
10260
10261   EVT SrcVT = MVT::Other;
10262   unsigned Opcode = ISD::DELETED_NODE;
10263   unsigned NumDefs = 0;
10264
10265   for (unsigned i = 0; i != NumInScalars; ++i) {
10266     SDValue In = N->getOperand(i);
10267     unsigned Opc = In.getOpcode();
10268
10269     if (Opc == ISD::UNDEF)
10270       continue;
10271
10272     // If all scalar values are floats and converted from integers.
10273     if (Opcode == ISD::DELETED_NODE &&
10274         (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
10275       Opcode = Opc;
10276     }
10277
10278     if (Opc != Opcode)
10279       return SDValue();
10280
10281     EVT InVT = In.getOperand(0).getValueType();
10282
10283     // If all scalar values are typed differently, bail out. It's chosen to
10284     // simplify BUILD_VECTOR of integer types.
10285     if (SrcVT == MVT::Other)
10286       SrcVT = InVT;
10287     if (SrcVT != InVT)
10288       return SDValue();
10289     NumDefs++;
10290   }
10291
10292   // If the vector has just one element defined, it's not worth to fold it into
10293   // a vectorized one.
10294   if (NumDefs < 2)
10295     return SDValue();
10296
10297   assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
10298          && "Should only handle conversion from integer to float.");
10299   assert(SrcVT != MVT::Other && "Cannot determine source type!");
10300
10301   EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
10302
10303   if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
10304     return SDValue();
10305
10306   SmallVector<SDValue, 8> Opnds;
10307   for (unsigned i = 0; i != NumInScalars; ++i) {
10308     SDValue In = N->getOperand(i);
10309
10310     if (In.getOpcode() == ISD::UNDEF)
10311       Opnds.push_back(DAG.getUNDEF(SrcVT));
10312     else
10313       Opnds.push_back(In.getOperand(0));
10314   }
10315   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds);
10316   AddToWorklist(BV.getNode());
10317
10318   return DAG.getNode(Opcode, dl, VT, BV);
10319 }
10320
10321 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
10322   unsigned NumInScalars = N->getNumOperands();
10323   SDLoc dl(N);
10324   EVT VT = N->getValueType(0);
10325
10326   // A vector built entirely of undefs is undef.
10327   if (ISD::allOperandsUndef(N))
10328     return DAG.getUNDEF(VT);
10329
10330   SDValue V = reduceBuildVecExtToExtBuildVec(N);
10331   if (V.getNode())
10332     return V;
10333
10334   V = reduceBuildVecConvertToConvertBuildVec(N);
10335   if (V.getNode())
10336     return V;
10337
10338   // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
10339   // operations.  If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
10340   // at most two distinct vectors, turn this into a shuffle node.
10341
10342   // May only combine to shuffle after legalize if shuffle is legal.
10343   if (LegalOperations &&
10344       !TLI.isOperationLegalOrCustom(ISD::VECTOR_SHUFFLE, VT))
10345     return SDValue();
10346
10347   SDValue VecIn1, VecIn2;
10348   for (unsigned i = 0; i != NumInScalars; ++i) {
10349     // Ignore undef inputs.
10350     if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
10351
10352     // If this input is something other than a EXTRACT_VECTOR_ELT with a
10353     // constant index, bail out.
10354     if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10355         !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) {
10356       VecIn1 = VecIn2 = SDValue(nullptr, 0);
10357       break;
10358     }
10359
10360     // We allow up to two distinct input vectors.
10361     SDValue ExtractedFromVec = N->getOperand(i).getOperand(0);
10362     if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
10363       continue;
10364
10365     if (!VecIn1.getNode()) {
10366       VecIn1 = ExtractedFromVec;
10367     } else if (!VecIn2.getNode()) {
10368       VecIn2 = ExtractedFromVec;
10369     } else {
10370       // Too many inputs.
10371       VecIn1 = VecIn2 = SDValue(nullptr, 0);
10372       break;
10373     }
10374   }
10375
10376   // If everything is good, we can make a shuffle operation.
10377   if (VecIn1.getNode()) {
10378     SmallVector<int, 8> Mask;
10379     for (unsigned i = 0; i != NumInScalars; ++i) {
10380       if (N->getOperand(i).getOpcode() == ISD::UNDEF) {
10381         Mask.push_back(-1);
10382         continue;
10383       }
10384
10385       // If extracting from the first vector, just use the index directly.
10386       SDValue Extract = N->getOperand(i);
10387       SDValue ExtVal = Extract.getOperand(1);
10388       if (Extract.getOperand(0) == VecIn1) {
10389         unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
10390         if (ExtIndex > VT.getVectorNumElements())
10391           return SDValue();
10392
10393         Mask.push_back(ExtIndex);
10394         continue;
10395       }
10396
10397       // Otherwise, use InIdx + VecSize
10398       unsigned Idx = cast<ConstantSDNode>(ExtVal)->getZExtValue();
10399       Mask.push_back(Idx+NumInScalars);
10400     }
10401
10402     // We can't generate a shuffle node with mismatched input and output types.
10403     // Attempt to transform a single input vector to the correct type.
10404     if ((VT != VecIn1.getValueType())) {
10405       // We don't support shuffeling between TWO values of different types.
10406       if (VecIn2.getNode())
10407         return SDValue();
10408
10409       // We only support widening of vectors which are half the size of the
10410       // output registers. For example XMM->YMM widening on X86 with AVX.
10411       if (VecIn1.getValueType().getSizeInBits()*2 != VT.getSizeInBits())
10412         return SDValue();
10413
10414       // If the input vector type has a different base type to the output
10415       // vector type, bail out.
10416       if (VecIn1.getValueType().getVectorElementType() !=
10417           VT.getVectorElementType())
10418         return SDValue();
10419
10420       // Widen the input vector by adding undef values.
10421       VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10422                            VecIn1, DAG.getUNDEF(VecIn1.getValueType()));
10423     }
10424
10425     // If VecIn2 is unused then change it to undef.
10426     VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
10427
10428     // Check that we were able to transform all incoming values to the same
10429     // type.
10430     if (VecIn2.getValueType() != VecIn1.getValueType() ||
10431         VecIn1.getValueType() != VT)
10432           return SDValue();
10433
10434     // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
10435     if (!isTypeLegal(VT))
10436       return SDValue();
10437
10438     // Return the new VECTOR_SHUFFLE node.
10439     SDValue Ops[2];
10440     Ops[0] = VecIn1;
10441     Ops[1] = VecIn2;
10442     return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
10443   }
10444
10445   return SDValue();
10446 }
10447
10448 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
10449   // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
10450   // EXTRACT_SUBVECTOR operations.  If so, and if the EXTRACT_SUBVECTOR vector
10451   // inputs come from at most two distinct vectors, turn this into a shuffle
10452   // node.
10453
10454   // If we only have one input vector, we don't need to do any concatenation.
10455   if (N->getNumOperands() == 1)
10456     return N->getOperand(0);
10457
10458   // Check if all of the operands are undefs.
10459   EVT VT = N->getValueType(0);
10460   if (ISD::allOperandsUndef(N))
10461     return DAG.getUNDEF(VT);
10462
10463   // Optimize concat_vectors where one of the vectors is undef.
10464   if (N->getNumOperands() == 2 &&
10465       N->getOperand(1)->getOpcode() == ISD::UNDEF) {
10466     SDValue In = N->getOperand(0);
10467     assert(In.getValueType().isVector() && "Must concat vectors");
10468
10469     // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
10470     if (In->getOpcode() == ISD::BITCAST &&
10471         !In->getOperand(0)->getValueType(0).isVector()) {
10472       SDValue Scalar = In->getOperand(0);
10473       EVT SclTy = Scalar->getValueType(0);
10474
10475       if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
10476         return SDValue();
10477
10478       EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
10479                                  VT.getSizeInBits() / SclTy.getSizeInBits());
10480       if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
10481         return SDValue();
10482
10483       SDLoc dl = SDLoc(N);
10484       SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
10485       return DAG.getNode(ISD::BITCAST, dl, VT, Res);
10486     }
10487   }
10488
10489   // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
10490   // -> (BUILD_VECTOR A, B, ..., C, D, ...)
10491   if (N->getNumOperands() == 2 &&
10492       N->getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
10493       N->getOperand(1).getOpcode() == ISD::BUILD_VECTOR) {
10494     EVT VT = N->getValueType(0);
10495     SDValue N0 = N->getOperand(0);
10496     SDValue N1 = N->getOperand(1);
10497     SmallVector<SDValue, 8> Opnds;
10498     unsigned BuildVecNumElts =  N0.getNumOperands();
10499
10500     EVT SclTy0 = N0.getOperand(0)->getValueType(0);
10501     EVT SclTy1 = N1.getOperand(0)->getValueType(0);
10502     if (SclTy0.isFloatingPoint()) {
10503       for (unsigned i = 0; i != BuildVecNumElts; ++i)
10504         Opnds.push_back(N0.getOperand(i));
10505       for (unsigned i = 0; i != BuildVecNumElts; ++i)
10506         Opnds.push_back(N1.getOperand(i));
10507     } else {
10508       // If BUILD_VECTOR are from built from integer, they may have different
10509       // operand types. Get the smaller type and truncate all operands to it.
10510       EVT MinTy = SclTy0.bitsLE(SclTy1) ? SclTy0 : SclTy1;
10511       for (unsigned i = 0; i != BuildVecNumElts; ++i)
10512         Opnds.push_back(DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinTy,
10513                         N0.getOperand(i)));
10514       for (unsigned i = 0; i != BuildVecNumElts; ++i)
10515         Opnds.push_back(DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinTy,
10516                         N1.getOperand(i)));
10517     }
10518
10519     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
10520   }
10521
10522   // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
10523   // nodes often generate nop CONCAT_VECTOR nodes.
10524   // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
10525   // place the incoming vectors at the exact same location.
10526   SDValue SingleSource = SDValue();
10527   unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
10528
10529   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
10530     SDValue Op = N->getOperand(i);
10531
10532     if (Op.getOpcode() == ISD::UNDEF)
10533       continue;
10534
10535     // Check if this is the identity extract:
10536     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
10537       return SDValue();
10538
10539     // Find the single incoming vector for the extract_subvector.
10540     if (SingleSource.getNode()) {
10541       if (Op.getOperand(0) != SingleSource)
10542         return SDValue();
10543     } else {
10544       SingleSource = Op.getOperand(0);
10545
10546       // Check the source type is the same as the type of the result.
10547       // If not, this concat may extend the vector, so we can not
10548       // optimize it away.
10549       if (SingleSource.getValueType() != N->getValueType(0))
10550         return SDValue();
10551     }
10552
10553     unsigned IdentityIndex = i * PartNumElem;
10554     ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
10555     // The extract index must be constant.
10556     if (!CS)
10557       return SDValue();
10558
10559     // Check that we are reading from the identity index.
10560     if (CS->getZExtValue() != IdentityIndex)
10561       return SDValue();
10562   }
10563
10564   if (SingleSource.getNode())
10565     return SingleSource;
10566
10567   return SDValue();
10568 }
10569
10570 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
10571   EVT NVT = N->getValueType(0);
10572   SDValue V = N->getOperand(0);
10573
10574   if (V->getOpcode() == ISD::CONCAT_VECTORS) {
10575     // Combine:
10576     //    (extract_subvec (concat V1, V2, ...), i)
10577     // Into:
10578     //    Vi if possible
10579     // Only operand 0 is checked as 'concat' assumes all inputs of the same
10580     // type.
10581     if (V->getOperand(0).getValueType() != NVT)
10582       return SDValue();
10583     unsigned Idx = dyn_cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
10584     unsigned NumElems = NVT.getVectorNumElements();
10585     assert((Idx % NumElems) == 0 &&
10586            "IDX in concat is not a multiple of the result vector length.");
10587     return V->getOperand(Idx / NumElems);
10588   }
10589
10590   // Skip bitcasting
10591   if (V->getOpcode() == ISD::BITCAST)
10592     V = V.getOperand(0);
10593
10594   if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
10595     SDLoc dl(N);
10596     // Handle only simple case where vector being inserted and vector
10597     // being extracted are of same type, and are half size of larger vectors.
10598     EVT BigVT = V->getOperand(0).getValueType();
10599     EVT SmallVT = V->getOperand(1).getValueType();
10600     if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
10601       return SDValue();
10602
10603     // Only handle cases where both indexes are constants with the same type.
10604     ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
10605     ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
10606
10607     if (InsIdx && ExtIdx &&
10608         InsIdx->getValueType(0).getSizeInBits() <= 64 &&
10609         ExtIdx->getValueType(0).getSizeInBits() <= 64) {
10610       // Combine:
10611       //    (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
10612       // Into:
10613       //    indices are equal or bit offsets are equal => V1
10614       //    otherwise => (extract_subvec V1, ExtIdx)
10615       if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
10616           ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
10617         return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
10618       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
10619                          DAG.getNode(ISD::BITCAST, dl,
10620                                      N->getOperand(0).getValueType(),
10621                                      V->getOperand(0)), N->getOperand(1));
10622     }
10623   }
10624
10625   return SDValue();
10626 }
10627
10628 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat.
10629 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
10630   EVT VT = N->getValueType(0);
10631   unsigned NumElts = VT.getVectorNumElements();
10632
10633   SDValue N0 = N->getOperand(0);
10634   SDValue N1 = N->getOperand(1);
10635   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10636
10637   SmallVector<SDValue, 4> Ops;
10638   EVT ConcatVT = N0.getOperand(0).getValueType();
10639   unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
10640   unsigned NumConcats = NumElts / NumElemsPerConcat;
10641
10642   // Look at every vector that's inserted. We're looking for exact
10643   // subvector-sized copies from a concatenated vector
10644   for (unsigned I = 0; I != NumConcats; ++I) {
10645     // Make sure we're dealing with a copy.
10646     unsigned Begin = I * NumElemsPerConcat;
10647     bool AllUndef = true, NoUndef = true;
10648     for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
10649       if (SVN->getMaskElt(J) >= 0)
10650         AllUndef = false;
10651       else
10652         NoUndef = false;
10653     }
10654
10655     if (NoUndef) {
10656       if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
10657         return SDValue();
10658
10659       for (unsigned J = 1; J != NumElemsPerConcat; ++J)
10660         if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
10661           return SDValue();
10662
10663       unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
10664       if (FirstElt < N0.getNumOperands())
10665         Ops.push_back(N0.getOperand(FirstElt));
10666       else
10667         Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
10668
10669     } else if (AllUndef) {
10670       Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
10671     } else { // Mixed with general masks and undefs, can't do optimization.
10672       return SDValue();
10673     }
10674   }
10675
10676   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
10677 }
10678
10679 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
10680   EVT VT = N->getValueType(0);
10681   unsigned NumElts = VT.getVectorNumElements();
10682
10683   SDValue N0 = N->getOperand(0);
10684   SDValue N1 = N->getOperand(1);
10685
10686   assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
10687
10688   // Canonicalize shuffle undef, undef -> undef
10689   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
10690     return DAG.getUNDEF(VT);
10691
10692   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10693
10694   // Canonicalize shuffle v, v -> v, undef
10695   if (N0 == N1) {
10696     SmallVector<int, 8> NewMask;
10697     for (unsigned i = 0; i != NumElts; ++i) {
10698       int Idx = SVN->getMaskElt(i);
10699       if (Idx >= (int)NumElts) Idx -= NumElts;
10700       NewMask.push_back(Idx);
10701     }
10702     return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
10703                                 &NewMask[0]);
10704   }
10705
10706   // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
10707   if (N0.getOpcode() == ISD::UNDEF) {
10708     SmallVector<int, 8> NewMask;
10709     for (unsigned i = 0; i != NumElts; ++i) {
10710       int Idx = SVN->getMaskElt(i);
10711       if (Idx >= 0) {
10712         if (Idx >= (int)NumElts)
10713           Idx -= NumElts;
10714         else
10715           Idx = -1; // remove reference to lhs
10716       }
10717       NewMask.push_back(Idx);
10718     }
10719     return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
10720                                 &NewMask[0]);
10721   }
10722
10723   // Remove references to rhs if it is undef
10724   if (N1.getOpcode() == ISD::UNDEF) {
10725     bool Changed = false;
10726     SmallVector<int, 8> NewMask;
10727     for (unsigned i = 0; i != NumElts; ++i) {
10728       int Idx = SVN->getMaskElt(i);
10729       if (Idx >= (int)NumElts) {
10730         Idx = -1;
10731         Changed = true;
10732       }
10733       NewMask.push_back(Idx);
10734     }
10735     if (Changed)
10736       return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
10737   }
10738
10739   // If it is a splat, check if the argument vector is another splat or a
10740   // build_vector with all scalar elements the same.
10741   if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
10742     SDNode *V = N0.getNode();
10743
10744     // If this is a bit convert that changes the element type of the vector but
10745     // not the number of vector elements, look through it.  Be careful not to
10746     // look though conversions that change things like v4f32 to v2f64.
10747     if (V->getOpcode() == ISD::BITCAST) {
10748       SDValue ConvInput = V->getOperand(0);
10749       if (ConvInput.getValueType().isVector() &&
10750           ConvInput.getValueType().getVectorNumElements() == NumElts)
10751         V = ConvInput.getNode();
10752     }
10753
10754     if (V->getOpcode() == ISD::BUILD_VECTOR) {
10755       assert(V->getNumOperands() == NumElts &&
10756              "BUILD_VECTOR has wrong number of operands");
10757       SDValue Base;
10758       bool AllSame = true;
10759       for (unsigned i = 0; i != NumElts; ++i) {
10760         if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
10761           Base = V->getOperand(i);
10762           break;
10763         }
10764       }
10765       // Splat of <u, u, u, u>, return <u, u, u, u>
10766       if (!Base.getNode())
10767         return N0;
10768       for (unsigned i = 0; i != NumElts; ++i) {
10769         if (V->getOperand(i) != Base) {
10770           AllSame = false;
10771           break;
10772         }
10773       }
10774       // Splat of <x, x, x, x>, return <x, x, x, x>
10775       if (AllSame)
10776         return N0;
10777     }
10778   }
10779
10780   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
10781       Level < AfterLegalizeVectorOps &&
10782       (N1.getOpcode() == ISD::UNDEF ||
10783       (N1.getOpcode() == ISD::CONCAT_VECTORS &&
10784        N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
10785     SDValue V = partitionShuffleOfConcats(N, DAG);
10786
10787     if (V.getNode())
10788       return V;
10789   }
10790
10791   // If this shuffle node is simply a swizzle of another shuffle node,
10792   // then try to simplify it.
10793   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
10794       N1.getOpcode() == ISD::UNDEF) {
10795
10796     ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
10797
10798     // The incoming shuffle must be of the same type as the result of the
10799     // current shuffle.
10800     assert(OtherSV->getOperand(0).getValueType() == VT &&
10801            "Shuffle types don't match");
10802
10803     SmallVector<int, 4> Mask;
10804     // Compute the combined shuffle mask.
10805     for (unsigned i = 0; i != NumElts; ++i) {
10806       int Idx = SVN->getMaskElt(i);
10807       assert(Idx < (int)NumElts && "Index references undef operand");
10808       // Next, this index comes from the first value, which is the incoming
10809       // shuffle. Adopt the incoming index.
10810       if (Idx >= 0)
10811         Idx = OtherSV->getMaskElt(Idx);
10812       Mask.push_back(Idx);
10813     }
10814
10815     // Check if all indices in Mask are Undef. In case, propagate Undef.
10816     bool isUndefMask = true;
10817     for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
10818       isUndefMask &= Mask[i] < 0;
10819
10820     if (isUndefMask)
10821       return DAG.getUNDEF(VT);
10822     
10823     bool CommuteOperands = false;
10824     if (N0.getOperand(1).getOpcode() != ISD::UNDEF) {
10825       // To be valid, the combine shuffle mask should only reference elements
10826       // from one of the two vectors in input to the inner shufflevector.
10827       bool IsValidMask = true;
10828       for (unsigned i = 0; i != NumElts && IsValidMask; ++i)
10829         // See if the combined mask only reference undefs or elements coming
10830         // from the first shufflevector operand.
10831         IsValidMask = Mask[i] < 0 || (unsigned)Mask[i] < NumElts;
10832
10833       if (!IsValidMask) {
10834         IsValidMask = true;
10835         for (unsigned i = 0; i != NumElts && IsValidMask; ++i)
10836           // Check that all the elements come from the second shuffle operand.
10837           IsValidMask = Mask[i] < 0 || (unsigned)Mask[i] >= NumElts;
10838         CommuteOperands = IsValidMask;
10839       }
10840
10841       // Early exit if the combined shuffle mask is not valid.
10842       if (!IsValidMask)
10843         return SDValue();
10844     }
10845
10846     // See if this pair of shuffles can be safely folded according to either
10847     // of the following rules:
10848     //   shuffle(shuffle(x, y), undef) -> x
10849     //   shuffle(shuffle(x, undef), undef) -> x
10850     //   shuffle(shuffle(x, y), undef) -> y
10851     bool IsIdentityMask = true;
10852     unsigned BaseMaskIndex = CommuteOperands ? NumElts : 0;
10853     for (unsigned i = 0; i != NumElts && IsIdentityMask; ++i) {
10854       // Skip Undefs.
10855       if (Mask[i] < 0)
10856         continue;
10857
10858       // The combined shuffle must map each index to itself.
10859       IsIdentityMask = (unsigned)Mask[i] == i + BaseMaskIndex;
10860     }
10861     
10862     if (IsIdentityMask) {
10863       if (CommuteOperands)
10864         // optimize shuffle(shuffle(x, y), undef) -> y.
10865         return OtherSV->getOperand(1);
10866       
10867       // optimize shuffle(shuffle(x, undef), undef) -> x
10868       // optimize shuffle(shuffle(x, y), undef) -> x
10869       return OtherSV->getOperand(0);
10870     }
10871
10872     // It may still be beneficial to combine the two shuffles if the
10873     // resulting shuffle is legal.
10874     if (TLI.isTypeLegal(VT)) {
10875       if (!CommuteOperands) {
10876         if (TLI.isShuffleMaskLegal(Mask, VT))
10877           // shuffle(shuffle(x, undef, M1), undef, M2) -> shuffle(x, undef, M3).
10878           // shuffle(shuffle(x, y, M1), undef, M2) -> shuffle(x, undef, M3)
10879           return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0), N1,
10880                                       &Mask[0]);
10881       } else {
10882         // Compute the commuted shuffle mask.
10883         for (unsigned i = 0; i != NumElts; ++i) {
10884           int idx = Mask[i];
10885           if (idx < 0)
10886             continue;
10887           else if (idx < (int)NumElts)
10888             Mask[i] = idx + NumElts;
10889           else
10890             Mask[i] = idx - NumElts;
10891         }
10892
10893         if (TLI.isShuffleMaskLegal(Mask, VT))
10894           //   shuffle(shuffle(x, y, M1), undef, M2) -> shuffle(y, undef, M3)
10895           return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(1), N1,
10896                                       &Mask[0]);
10897       }
10898     }
10899   }
10900
10901   // Canonicalize shuffles according to rules:
10902   //  shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
10903   //  shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
10904   //  shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
10905   if (N1.getOpcode() == ISD::VECTOR_SHUFFLE && N0.getOpcode() != ISD::UNDEF &&
10906       N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
10907       TLI.isTypeLegal(VT)) {
10908     // The incoming shuffle must be of the same type as the result of the
10909     // current shuffle.
10910     assert(N1->getOperand(0).getValueType() == VT &&
10911            "Shuffle types don't match");
10912
10913     SDValue SV0 = N1->getOperand(0);
10914     SDValue SV1 = N1->getOperand(1);
10915     bool HasSameOp0 = N0 == SV0;
10916     bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
10917     if (HasSameOp0 || IsSV1Undef || N0 == SV1)
10918       // Commute the operands of this shuffle so that next rule
10919       // will trigger.
10920       return DAG.getCommutedVectorShuffle(*SVN);
10921   }
10922
10923   // Try to fold according to rules:
10924   //   shuffle(shuffle(A, B, M0), B, M1) -> shuffle(A, B, M2)
10925   //   shuffle(shuffle(A, B, M0), A, M1) -> shuffle(A, B, M2)
10926   //   shuffle(shuffle(A, Undef, M0), B, M1) -> shuffle(A, B, M2)
10927   //   shuffle(shuffle(A, Undef, M0), A, M1) -> shuffle(A, Undef, M2)
10928   // Don't try to fold shuffles with illegal type.
10929   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
10930       N1.getOpcode() != ISD::UNDEF && TLI.isTypeLegal(VT)) {
10931     ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
10932
10933     // The incoming shuffle must be of the same type as the result of the
10934     // current shuffle.
10935     assert(OtherSV->getOperand(0).getValueType() == VT &&
10936            "Shuffle types don't match");
10937
10938     SDValue SV0 = OtherSV->getOperand(0);
10939     SDValue SV1 = OtherSV->getOperand(1);
10940     bool HasSameOp0 = N1 == SV0;
10941     bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
10942     if (!HasSameOp0 && !IsSV1Undef && N1 != SV1)
10943       // Early exit.
10944       return SDValue();
10945
10946     SmallVector<int, 4> Mask;
10947     // Compute the combined shuffle mask for a shuffle with SV0 as the first
10948     // operand, and SV1 as the second operand.
10949     for (unsigned i = 0; i != NumElts; ++i) {
10950       int Idx = SVN->getMaskElt(i);
10951       if (Idx < 0) {
10952         // Propagate Undef.
10953         Mask.push_back(Idx);
10954         continue;
10955       }
10956
10957       if (Idx < (int)NumElts) {
10958         Idx = OtherSV->getMaskElt(Idx);
10959         if (IsSV1Undef && Idx >= (int) NumElts)
10960           Idx = -1;  // Propagate Undef.
10961       } else
10962         Idx = HasSameOp0 ? Idx - NumElts : Idx;
10963
10964       Mask.push_back(Idx);
10965     }
10966
10967     // Check if all indices in Mask are Undef. In case, propagate Undef.
10968     bool isUndefMask = true;
10969     for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
10970       isUndefMask &= Mask[i] < 0;
10971
10972     if (isUndefMask)
10973       return DAG.getUNDEF(VT);
10974
10975     // Avoid introducing shuffles with illegal mask.
10976     if (TLI.isShuffleMaskLegal(Mask, VT)) {
10977       if (IsSV1Undef)
10978         //   shuffle(shuffle(A, Undef, M0), B, M1) -> shuffle(A, B, M2)
10979         //   shuffle(shuffle(A, Undef, M0), A, M1) -> shuffle(A, Undef, M2)
10980         return DAG.getVectorShuffle(VT, SDLoc(N), SV0, N1, &Mask[0]);
10981       return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, &Mask[0]);
10982     }
10983   }
10984
10985   return SDValue();
10986 }
10987
10988 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
10989   SDValue N0 = N->getOperand(0);
10990   SDValue N2 = N->getOperand(2);
10991
10992   // If the input vector is a concatenation, and the insert replaces
10993   // one of the halves, we can optimize into a single concat_vectors.
10994   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
10995       N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
10996     APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
10997     EVT VT = N->getValueType(0);
10998
10999     // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
11000     // (concat_vectors Z, Y)
11001     if (InsIdx == 0)
11002       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
11003                          N->getOperand(1), N0.getOperand(1));
11004
11005     // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
11006     // (concat_vectors X, Z)
11007     if (InsIdx == VT.getVectorNumElements()/2)
11008       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
11009                          N0.getOperand(0), N->getOperand(1));
11010   }
11011
11012   return SDValue();
11013 }
11014
11015 /// XformToShuffleWithZero - Returns a vector_shuffle if it able to transform
11016 /// an AND to a vector_shuffle with the destination vector and a zero vector.
11017 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
11018 ///      vector_shuffle V, Zero, <0, 4, 2, 4>
11019 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
11020   EVT VT = N->getValueType(0);
11021   SDLoc dl(N);
11022   SDValue LHS = N->getOperand(0);
11023   SDValue RHS = N->getOperand(1);
11024   if (N->getOpcode() == ISD::AND) {
11025     if (RHS.getOpcode() == ISD::BITCAST)
11026       RHS = RHS.getOperand(0);
11027     if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
11028       SmallVector<int, 8> Indices;
11029       unsigned NumElts = RHS.getNumOperands();
11030       for (unsigned i = 0; i != NumElts; ++i) {
11031         SDValue Elt = RHS.getOperand(i);
11032         if (!isa<ConstantSDNode>(Elt))
11033           return SDValue();
11034
11035         if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
11036           Indices.push_back(i);
11037         else if (cast<ConstantSDNode>(Elt)->isNullValue())
11038           Indices.push_back(NumElts);
11039         else
11040           return SDValue();
11041       }
11042
11043       // Let's see if the target supports this vector_shuffle.
11044       EVT RVT = RHS.getValueType();
11045       if (!TLI.isVectorClearMaskLegal(Indices, RVT))
11046         return SDValue();
11047
11048       // Return the new VECTOR_SHUFFLE node.
11049       EVT EltVT = RVT.getVectorElementType();
11050       SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
11051                                      DAG.getConstant(0, EltVT));
11052       SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), RVT, ZeroOps);
11053       LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
11054       SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
11055       return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
11056     }
11057   }
11058
11059   return SDValue();
11060 }
11061
11062 /// SimplifyVBinOp - Visit a binary vector operation, like ADD.
11063 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
11064   assert(N->getValueType(0).isVector() &&
11065          "SimplifyVBinOp only works on vectors!");
11066
11067   SDValue LHS = N->getOperand(0);
11068   SDValue RHS = N->getOperand(1);
11069   SDValue Shuffle = XformToShuffleWithZero(N);
11070   if (Shuffle.getNode()) return Shuffle;
11071
11072   // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
11073   // this operation.
11074   if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
11075       RHS.getOpcode() == ISD::BUILD_VECTOR) {
11076     // Check if both vectors are constants. If not bail out.
11077     if (!(cast<BuildVectorSDNode>(LHS)->isConstant() &&
11078           cast<BuildVectorSDNode>(RHS)->isConstant()))
11079       return SDValue();
11080
11081     SmallVector<SDValue, 8> Ops;
11082     for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
11083       SDValue LHSOp = LHS.getOperand(i);
11084       SDValue RHSOp = RHS.getOperand(i);
11085
11086       // Can't fold divide by zero.
11087       if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
11088           N->getOpcode() == ISD::FDIV) {
11089         if ((RHSOp.getOpcode() == ISD::Constant &&
11090              cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
11091             (RHSOp.getOpcode() == ISD::ConstantFP &&
11092              cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
11093           break;
11094       }
11095
11096       EVT VT = LHSOp.getValueType();
11097       EVT RVT = RHSOp.getValueType();
11098       if (RVT != VT) {
11099         // Integer BUILD_VECTOR operands may have types larger than the element
11100         // size (e.g., when the element type is not legal).  Prior to type
11101         // legalization, the types may not match between the two BUILD_VECTORS.
11102         // Truncate one of the operands to make them match.
11103         if (RVT.getSizeInBits() > VT.getSizeInBits()) {
11104           RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
11105         } else {
11106           LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
11107           VT = RVT;
11108         }
11109       }
11110       SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
11111                                    LHSOp, RHSOp);
11112       if (FoldOp.getOpcode() != ISD::UNDEF &&
11113           FoldOp.getOpcode() != ISD::Constant &&
11114           FoldOp.getOpcode() != ISD::ConstantFP)
11115         break;
11116       Ops.push_back(FoldOp);
11117       AddToWorklist(FoldOp.getNode());
11118     }
11119
11120     if (Ops.size() == LHS.getNumOperands())
11121       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), LHS.getValueType(), Ops);
11122   }
11123
11124   // Type legalization might introduce new shuffles in the DAG.
11125   // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
11126   //   -> (shuffle (VBinOp (A, B)), Undef, Mask).
11127   if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
11128       isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
11129       LHS.getOperand(1).getOpcode() == ISD::UNDEF &&
11130       RHS.getOperand(1).getOpcode() == ISD::UNDEF) {
11131     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
11132     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
11133
11134     if (SVN0->getMask().equals(SVN1->getMask())) {
11135       EVT VT = N->getValueType(0);
11136       SDValue UndefVector = LHS.getOperand(1);
11137       SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
11138                                      LHS.getOperand(0), RHS.getOperand(0));
11139       AddUsersToWorklist(N);
11140       return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
11141                                   &SVN0->getMask()[0]);
11142     }
11143   }
11144
11145   return SDValue();
11146 }
11147
11148 /// SimplifyVUnaryOp - Visit a binary vector operation, like FABS/FNEG.
11149 SDValue DAGCombiner::SimplifyVUnaryOp(SDNode *N) {
11150   assert(N->getValueType(0).isVector() &&
11151          "SimplifyVUnaryOp only works on vectors!");
11152
11153   SDValue N0 = N->getOperand(0);
11154
11155   if (N0.getOpcode() != ISD::BUILD_VECTOR)
11156     return SDValue();
11157
11158   // Operand is a BUILD_VECTOR node, see if we can constant fold it.
11159   SmallVector<SDValue, 8> Ops;
11160   for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
11161     SDValue Op = N0.getOperand(i);
11162     if (Op.getOpcode() != ISD::UNDEF &&
11163         Op.getOpcode() != ISD::ConstantFP)
11164       break;
11165     EVT EltVT = Op.getValueType();
11166     SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(N0), EltVT, Op);
11167     if (FoldOp.getOpcode() != ISD::UNDEF &&
11168         FoldOp.getOpcode() != ISD::ConstantFP)
11169       break;
11170     Ops.push_back(FoldOp);
11171     AddToWorklist(FoldOp.getNode());
11172   }
11173
11174   if (Ops.size() != N0.getNumOperands())
11175     return SDValue();
11176
11177   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), N0.getValueType(), Ops);
11178 }
11179
11180 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
11181                                     SDValue N1, SDValue N2){
11182   assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
11183
11184   SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
11185                                  cast<CondCodeSDNode>(N0.getOperand(2))->get());
11186
11187   // If we got a simplified select_cc node back from SimplifySelectCC, then
11188   // break it down into a new SETCC node, and a new SELECT node, and then return
11189   // the SELECT node, since we were called with a SELECT node.
11190   if (SCC.getNode()) {
11191     // Check to see if we got a select_cc back (to turn into setcc/select).
11192     // Otherwise, just return whatever node we got back, like fabs.
11193     if (SCC.getOpcode() == ISD::SELECT_CC) {
11194       SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
11195                                   N0.getValueType(),
11196                                   SCC.getOperand(0), SCC.getOperand(1),
11197                                   SCC.getOperand(4));
11198       AddToWorklist(SETCC.getNode());
11199       return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC,
11200                            SCC.getOperand(2), SCC.getOperand(3));
11201     }
11202
11203     return SCC;
11204   }
11205   return SDValue();
11206 }
11207
11208 /// SimplifySelectOps - Given a SELECT or a SELECT_CC node, where LHS and RHS
11209 /// are the two values being selected between, see if we can simplify the
11210 /// select.  Callers of this should assume that TheSelect is deleted if this
11211 /// returns true.  As such, they should return the appropriate thing (e.g. the
11212 /// node) back to the top-level of the DAG combiner loop to avoid it being
11213 /// looked at.
11214 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
11215                                     SDValue RHS) {
11216
11217   // Cannot simplify select with vector condition
11218   if (TheSelect->getOperand(0).getValueType().isVector()) return false;
11219
11220   // If this is a select from two identical things, try to pull the operation
11221   // through the select.
11222   if (LHS.getOpcode() != RHS.getOpcode() ||
11223       !LHS.hasOneUse() || !RHS.hasOneUse())
11224     return false;
11225
11226   // If this is a load and the token chain is identical, replace the select
11227   // of two loads with a load through a select of the address to load from.
11228   // This triggers in things like "select bool X, 10.0, 123.0" after the FP
11229   // constants have been dropped into the constant pool.
11230   if (LHS.getOpcode() == ISD::LOAD) {
11231     LoadSDNode *LLD = cast<LoadSDNode>(LHS);
11232     LoadSDNode *RLD = cast<LoadSDNode>(RHS);
11233
11234     // Token chains must be identical.
11235     if (LHS.getOperand(0) != RHS.getOperand(0) ||
11236         // Do not let this transformation reduce the number of volatile loads.
11237         LLD->isVolatile() || RLD->isVolatile() ||
11238         // If this is an EXTLOAD, the VT's must match.
11239         LLD->getMemoryVT() != RLD->getMemoryVT() ||
11240         // If this is an EXTLOAD, the kind of extension must match.
11241         (LLD->getExtensionType() != RLD->getExtensionType() &&
11242          // The only exception is if one of the extensions is anyext.
11243          LLD->getExtensionType() != ISD::EXTLOAD &&
11244          RLD->getExtensionType() != ISD::EXTLOAD) ||
11245         // FIXME: this discards src value information.  This is
11246         // over-conservative. It would be beneficial to be able to remember
11247         // both potential memory locations.  Since we are discarding
11248         // src value info, don't do the transformation if the memory
11249         // locations are not in the default address space.
11250         LLD->getPointerInfo().getAddrSpace() != 0 ||
11251         RLD->getPointerInfo().getAddrSpace() != 0 ||
11252         !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
11253                                       LLD->getBasePtr().getValueType()))
11254       return false;
11255
11256     // Check that the select condition doesn't reach either load.  If so,
11257     // folding this will induce a cycle into the DAG.  If not, this is safe to
11258     // xform, so create a select of the addresses.
11259     SDValue Addr;
11260     if (TheSelect->getOpcode() == ISD::SELECT) {
11261       SDNode *CondNode = TheSelect->getOperand(0).getNode();
11262       if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
11263           (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
11264         return false;
11265       // The loads must not depend on one another.
11266       if (LLD->isPredecessorOf(RLD) ||
11267           RLD->isPredecessorOf(LLD))
11268         return false;
11269       Addr = DAG.getSelect(SDLoc(TheSelect),
11270                            LLD->getBasePtr().getValueType(),
11271                            TheSelect->getOperand(0), LLD->getBasePtr(),
11272                            RLD->getBasePtr());
11273     } else {  // Otherwise SELECT_CC
11274       SDNode *CondLHS = TheSelect->getOperand(0).getNode();
11275       SDNode *CondRHS = TheSelect->getOperand(1).getNode();
11276
11277       if ((LLD->hasAnyUseOfValue(1) &&
11278            (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
11279           (RLD->hasAnyUseOfValue(1) &&
11280            (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
11281         return false;
11282
11283       Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
11284                          LLD->getBasePtr().getValueType(),
11285                          TheSelect->getOperand(0),
11286                          TheSelect->getOperand(1),
11287                          LLD->getBasePtr(), RLD->getBasePtr(),
11288                          TheSelect->getOperand(4));
11289     }
11290
11291     SDValue Load;
11292     // It is safe to replace the two loads if they have different alignments,
11293     // but the new load must be the minimum (most restrictive) alignment of the
11294     // inputs.
11295     bool isInvariant = LLD->getAlignment() & RLD->getAlignment();
11296     unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment());
11297     if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
11298       Load = DAG.getLoad(TheSelect->getValueType(0),
11299                          SDLoc(TheSelect),
11300                          // FIXME: Discards pointer and AA info.
11301                          LLD->getChain(), Addr, MachinePointerInfo(),
11302                          LLD->isVolatile(), LLD->isNonTemporal(),
11303                          isInvariant, Alignment);
11304     } else {
11305       Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
11306                             RLD->getExtensionType() : LLD->getExtensionType(),
11307                             SDLoc(TheSelect),
11308                             TheSelect->getValueType(0),
11309                             // FIXME: Discards pointer and AA info.
11310                             LLD->getChain(), Addr, MachinePointerInfo(),
11311                             LLD->getMemoryVT(), LLD->isVolatile(),
11312                             LLD->isNonTemporal(), isInvariant, Alignment);
11313     }
11314
11315     // Users of the select now use the result of the load.
11316     CombineTo(TheSelect, Load);
11317
11318     // Users of the old loads now use the new load's chain.  We know the
11319     // old-load value is dead now.
11320     CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
11321     CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
11322     return true;
11323   }
11324
11325   return false;
11326 }
11327
11328 /// SimplifySelectCC - Simplify an expression of the form (N0 cond N1) ? N2 : N3
11329 /// where 'cond' is the comparison specified by CC.
11330 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
11331                                       SDValue N2, SDValue N3,
11332                                       ISD::CondCode CC, bool NotExtCompare) {
11333   // (x ? y : y) -> y.
11334   if (N2 == N3) return N2;
11335
11336   EVT VT = N2.getValueType();
11337   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
11338   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
11339   ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
11340
11341   // Determine if the condition we're dealing with is constant
11342   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
11343                               N0, N1, CC, DL, false);
11344   if (SCC.getNode()) AddToWorklist(SCC.getNode());
11345   ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
11346
11347   // fold select_cc true, x, y -> x
11348   if (SCCC && !SCCC->isNullValue())
11349     return N2;
11350   // fold select_cc false, x, y -> y
11351   if (SCCC && SCCC->isNullValue())
11352     return N3;
11353
11354   // Check to see if we can simplify the select into an fabs node
11355   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
11356     // Allow either -0.0 or 0.0
11357     if (CFP->getValueAPF().isZero()) {
11358       // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
11359       if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
11360           N0 == N2 && N3.getOpcode() == ISD::FNEG &&
11361           N2 == N3.getOperand(0))
11362         return DAG.getNode(ISD::FABS, DL, VT, N0);
11363
11364       // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
11365       if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
11366           N0 == N3 && N2.getOpcode() == ISD::FNEG &&
11367           N2.getOperand(0) == N3)
11368         return DAG.getNode(ISD::FABS, DL, VT, N3);
11369     }
11370   }
11371
11372   // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
11373   // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
11374   // in it.  This is a win when the constant is not otherwise available because
11375   // it replaces two constant pool loads with one.  We only do this if the FP
11376   // type is known to be legal, because if it isn't, then we are before legalize
11377   // types an we want the other legalization to happen first (e.g. to avoid
11378   // messing with soft float) and if the ConstantFP is not legal, because if
11379   // it is legal, we may not need to store the FP constant in a constant pool.
11380   if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
11381     if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
11382       if (TLI.isTypeLegal(N2.getValueType()) &&
11383           (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
11384                TargetLowering::Legal &&
11385            !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
11386            !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
11387           // If both constants have multiple uses, then we won't need to do an
11388           // extra load, they are likely around in registers for other users.
11389           (TV->hasOneUse() || FV->hasOneUse())) {
11390         Constant *Elts[] = {
11391           const_cast<ConstantFP*>(FV->getConstantFPValue()),
11392           const_cast<ConstantFP*>(TV->getConstantFPValue())
11393         };
11394         Type *FPTy = Elts[0]->getType();
11395         const DataLayout &TD = *TLI.getDataLayout();
11396
11397         // Create a ConstantArray of the two constants.
11398         Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
11399         SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
11400                                             TD.getPrefTypeAlignment(FPTy));
11401         unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
11402
11403         // Get the offsets to the 0 and 1 element of the array so that we can
11404         // select between them.
11405         SDValue Zero = DAG.getIntPtrConstant(0);
11406         unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
11407         SDValue One = DAG.getIntPtrConstant(EltSize);
11408
11409         SDValue Cond = DAG.getSetCC(DL,
11410                                     getSetCCResultType(N0.getValueType()),
11411                                     N0, N1, CC);
11412         AddToWorklist(Cond.getNode());
11413         SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
11414                                           Cond, One, Zero);
11415         AddToWorklist(CstOffset.getNode());
11416         CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
11417                             CstOffset);
11418         AddToWorklist(CPIdx.getNode());
11419         return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
11420                            MachinePointerInfo::getConstantPool(), false,
11421                            false, false, Alignment);
11422
11423       }
11424     }
11425
11426   // Check to see if we can perform the "gzip trick", transforming
11427   // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
11428   if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
11429       (N1C->isNullValue() ||                         // (a < 0) ? b : 0
11430        (N1C->getAPIntValue() == 1 && N0 == N2))) {   // (a < 1) ? a : 0
11431     EVT XType = N0.getValueType();
11432     EVT AType = N2.getValueType();
11433     if (XType.bitsGE(AType)) {
11434       // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
11435       // single-bit constant.
11436       if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
11437         unsigned ShCtV = N2C->getAPIntValue().logBase2();
11438         ShCtV = XType.getSizeInBits()-ShCtV-1;
11439         SDValue ShCt = DAG.getConstant(ShCtV,
11440                                        getShiftAmountTy(N0.getValueType()));
11441         SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
11442                                     XType, N0, ShCt);
11443         AddToWorklist(Shift.getNode());
11444
11445         if (XType.bitsGT(AType)) {
11446           Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
11447           AddToWorklist(Shift.getNode());
11448         }
11449
11450         return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
11451       }
11452
11453       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
11454                                   XType, N0,
11455                                   DAG.getConstant(XType.getSizeInBits()-1,
11456                                          getShiftAmountTy(N0.getValueType())));
11457       AddToWorklist(Shift.getNode());
11458
11459       if (XType.bitsGT(AType)) {
11460         Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
11461         AddToWorklist(Shift.getNode());
11462       }
11463
11464       return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
11465     }
11466   }
11467
11468   // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
11469   // where y is has a single bit set.
11470   // A plaintext description would be, we can turn the SELECT_CC into an AND
11471   // when the condition can be materialized as an all-ones register.  Any
11472   // single bit-test can be materialized as an all-ones register with
11473   // shift-left and shift-right-arith.
11474   if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
11475       N0->getValueType(0) == VT &&
11476       N1C && N1C->isNullValue() &&
11477       N2C && N2C->isNullValue()) {
11478     SDValue AndLHS = N0->getOperand(0);
11479     ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
11480     if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
11481       // Shift the tested bit over the sign bit.
11482       APInt AndMask = ConstAndRHS->getAPIntValue();
11483       SDValue ShlAmt =
11484         DAG.getConstant(AndMask.countLeadingZeros(),
11485                         getShiftAmountTy(AndLHS.getValueType()));
11486       SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
11487
11488       // Now arithmetic right shift it all the way over, so the result is either
11489       // all-ones, or zero.
11490       SDValue ShrAmt =
11491         DAG.getConstant(AndMask.getBitWidth()-1,
11492                         getShiftAmountTy(Shl.getValueType()));
11493       SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
11494
11495       return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
11496     }
11497   }
11498
11499   // fold select C, 16, 0 -> shl C, 4
11500   if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
11501       TLI.getBooleanContents(N0.getValueType()) ==
11502           TargetLowering::ZeroOrOneBooleanContent) {
11503
11504     // If the caller doesn't want us to simplify this into a zext of a compare,
11505     // don't do it.
11506     if (NotExtCompare && N2C->getAPIntValue() == 1)
11507       return SDValue();
11508
11509     // Get a SetCC of the condition
11510     // NOTE: Don't create a SETCC if it's not legal on this target.
11511     if (!LegalOperations ||
11512         TLI.isOperationLegal(ISD::SETCC,
11513           LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
11514       SDValue Temp, SCC;
11515       // cast from setcc result type to select result type
11516       if (LegalTypes) {
11517         SCC  = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
11518                             N0, N1, CC);
11519         if (N2.getValueType().bitsLT(SCC.getValueType()))
11520           Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
11521                                         N2.getValueType());
11522         else
11523           Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
11524                              N2.getValueType(), SCC);
11525       } else {
11526         SCC  = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
11527         Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
11528                            N2.getValueType(), SCC);
11529       }
11530
11531       AddToWorklist(SCC.getNode());
11532       AddToWorklist(Temp.getNode());
11533
11534       if (N2C->getAPIntValue() == 1)
11535         return Temp;
11536
11537       // shl setcc result by log2 n2c
11538       return DAG.getNode(
11539           ISD::SHL, DL, N2.getValueType(), Temp,
11540           DAG.getConstant(N2C->getAPIntValue().logBase2(),
11541                           getShiftAmountTy(Temp.getValueType())));
11542     }
11543   }
11544
11545   // Check to see if this is the equivalent of setcc
11546   // FIXME: Turn all of these into setcc if setcc if setcc is legal
11547   // otherwise, go ahead with the folds.
11548   if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
11549     EVT XType = N0.getValueType();
11550     if (!LegalOperations ||
11551         TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
11552       SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
11553       if (Res.getValueType() != VT)
11554         Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
11555       return Res;
11556     }
11557
11558     // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
11559     if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
11560         (!LegalOperations ||
11561          TLI.isOperationLegal(ISD::CTLZ, XType))) {
11562       SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
11563       return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
11564                          DAG.getConstant(Log2_32(XType.getSizeInBits()),
11565                                        getShiftAmountTy(Ctlz.getValueType())));
11566     }
11567     // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
11568     if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
11569       SDValue NegN0 = DAG.getNode(ISD::SUB, SDLoc(N0),
11570                                   XType, DAG.getConstant(0, XType), N0);
11571       SDValue NotN0 = DAG.getNOT(SDLoc(N0), N0, XType);
11572       return DAG.getNode(ISD::SRL, DL, XType,
11573                          DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
11574                          DAG.getConstant(XType.getSizeInBits()-1,
11575                                          getShiftAmountTy(XType)));
11576     }
11577     // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
11578     if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
11579       SDValue Sign = DAG.getNode(ISD::SRL, SDLoc(N0), XType, N0,
11580                                  DAG.getConstant(XType.getSizeInBits()-1,
11581                                          getShiftAmountTy(N0.getValueType())));
11582       return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
11583     }
11584   }
11585
11586   // Check to see if this is an integer abs.
11587   // select_cc setg[te] X,  0,  X, -X ->
11588   // select_cc setgt    X, -1,  X, -X ->
11589   // select_cc setl[te] X,  0, -X,  X ->
11590   // select_cc setlt    X,  1, -X,  X ->
11591   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
11592   if (N1C) {
11593     ConstantSDNode *SubC = nullptr;
11594     if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
11595          (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
11596         N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
11597       SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
11598     else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
11599               (N1C->isOne() && CC == ISD::SETLT)) &&
11600              N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
11601       SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
11602
11603     EVT XType = N0.getValueType();
11604     if (SubC && SubC->isNullValue() && XType.isInteger()) {
11605       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), XType,
11606                                   N0,
11607                                   DAG.getConstant(XType.getSizeInBits()-1,
11608                                          getShiftAmountTy(N0.getValueType())));
11609       SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0),
11610                                 XType, N0, Shift);
11611       AddToWorklist(Shift.getNode());
11612       AddToWorklist(Add.getNode());
11613       return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
11614     }
11615   }
11616
11617   return SDValue();
11618 }
11619
11620 /// SimplifySetCC - This is a stub for TargetLowering::SimplifySetCC.
11621 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
11622                                    SDValue N1, ISD::CondCode Cond,
11623                                    SDLoc DL, bool foldBooleans) {
11624   TargetLowering::DAGCombinerInfo
11625     DagCombineInfo(DAG, Level, false, this);
11626   return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
11627 }
11628
11629 /// BuildSDIV - Given an ISD::SDIV node expressing a divide by constant, return
11630 /// a DAG expression to select that will generate the same value by multiplying
11631 /// by a magic number.  See:
11632 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
11633 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
11634   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
11635   if (!C)
11636     return SDValue();
11637
11638   // Avoid division by zero.
11639   if (!C->getAPIntValue())
11640     return SDValue();
11641
11642   std::vector<SDNode*> Built;
11643   SDValue S =
11644       TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
11645
11646   for (SDNode *N : Built)
11647     AddToWorklist(N);
11648   return S;
11649 }
11650
11651 /// BuildSDIVPow2 - Given an ISD::SDIV node expressing a divide by constant
11652 /// power of 2, return a DAG expression to select that will generate the same
11653 /// value by right shifting.
11654 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
11655   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
11656   if (!C)
11657     return SDValue();
11658
11659   // Avoid division by zero.
11660   if (!C->getAPIntValue())
11661     return SDValue();
11662
11663   std::vector<SDNode *> Built;
11664   SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
11665
11666   for (SDNode *N : Built)
11667     AddToWorklist(N);
11668   return S;
11669 }
11670
11671 /// BuildUDIV - Given an ISD::UDIV node expressing a divide by constant,
11672 /// return a DAG expression to select that will generate the same value by
11673 /// multiplying by a magic number.  See:
11674 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
11675 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
11676   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
11677   if (!C)
11678     return SDValue();
11679
11680   // Avoid division by zero.
11681   if (!C->getAPIntValue())
11682     return SDValue();
11683
11684   std::vector<SDNode*> Built;
11685   SDValue S =
11686       TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
11687
11688   for (SDNode *N : Built)
11689     AddToWorklist(N);
11690   return S;
11691 }
11692
11693 /// FindBaseOffset - Return true if base is a frame index, which is known not
11694 // to alias with anything but itself.  Provides base object and offset as
11695 // results.
11696 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
11697                            const GlobalValue *&GV, const void *&CV) {
11698   // Assume it is a primitive operation.
11699   Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
11700
11701   // If it's an adding a simple constant then integrate the offset.
11702   if (Base.getOpcode() == ISD::ADD) {
11703     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
11704       Base = Base.getOperand(0);
11705       Offset += C->getZExtValue();
11706     }
11707   }
11708
11709   // Return the underlying GlobalValue, and update the Offset.  Return false
11710   // for GlobalAddressSDNode since the same GlobalAddress may be represented
11711   // by multiple nodes with different offsets.
11712   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
11713     GV = G->getGlobal();
11714     Offset += G->getOffset();
11715     return false;
11716   }
11717
11718   // Return the underlying Constant value, and update the Offset.  Return false
11719   // for ConstantSDNodes since the same constant pool entry may be represented
11720   // by multiple nodes with different offsets.
11721   if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
11722     CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
11723                                          : (const void *)C->getConstVal();
11724     Offset += C->getOffset();
11725     return false;
11726   }
11727   // If it's any of the following then it can't alias with anything but itself.
11728   return isa<FrameIndexSDNode>(Base);
11729 }
11730
11731 /// isAlias - Return true if there is any possibility that the two addresses
11732 /// overlap.
11733 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
11734   // If they are the same then they must be aliases.
11735   if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
11736
11737   // If they are both volatile then they cannot be reordered.
11738   if (Op0->isVolatile() && Op1->isVolatile()) return true;
11739
11740   // Gather base node and offset information.
11741   SDValue Base1, Base2;
11742   int64_t Offset1, Offset2;
11743   const GlobalValue *GV1, *GV2;
11744   const void *CV1, *CV2;
11745   bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
11746                                       Base1, Offset1, GV1, CV1);
11747   bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
11748                                       Base2, Offset2, GV2, CV2);
11749
11750   // If they have a same base address then check to see if they overlap.
11751   if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
11752     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
11753              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
11754
11755   // It is possible for different frame indices to alias each other, mostly
11756   // when tail call optimization reuses return address slots for arguments.
11757   // To catch this case, look up the actual index of frame indices to compute
11758   // the real alias relationship.
11759   if (isFrameIndex1 && isFrameIndex2) {
11760     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11761     Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
11762     Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
11763     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
11764              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
11765   }
11766
11767   // Otherwise, if we know what the bases are, and they aren't identical, then
11768   // we know they cannot alias.
11769   if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
11770     return false;
11771
11772   // If we know required SrcValue1 and SrcValue2 have relatively large alignment
11773   // compared to the size and offset of the access, we may be able to prove they
11774   // do not alias.  This check is conservative for now to catch cases created by
11775   // splitting vector types.
11776   if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
11777       (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
11778       (Op0->getMemoryVT().getSizeInBits() >> 3 ==
11779        Op1->getMemoryVT().getSizeInBits() >> 3) &&
11780       (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) {
11781     int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
11782     int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
11783
11784     // There is no overlap between these relatively aligned accesses of similar
11785     // size, return no alias.
11786     if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
11787         (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
11788       return false;
11789   }
11790
11791   bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0 ? CombinerGlobalAA :
11792     TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
11793 #ifndef NDEBUG
11794   if (CombinerAAOnlyFunc.getNumOccurrences() &&
11795       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
11796     UseAA = false;
11797 #endif
11798   if (UseAA &&
11799       Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
11800     // Use alias analysis information.
11801     int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
11802                                  Op1->getSrcValueOffset());
11803     int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
11804         Op0->getSrcValueOffset() - MinOffset;
11805     int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
11806         Op1->getSrcValueOffset() - MinOffset;
11807     AliasAnalysis::AliasResult AAResult =
11808         AA.alias(AliasAnalysis::Location(Op0->getMemOperand()->getValue(),
11809                                          Overlap1,
11810                                          UseTBAA ? Op0->getAAInfo() : AAMDNodes()),
11811                  AliasAnalysis::Location(Op1->getMemOperand()->getValue(),
11812                                          Overlap2,
11813                                          UseTBAA ? Op1->getAAInfo() : AAMDNodes()));
11814     if (AAResult == AliasAnalysis::NoAlias)
11815       return false;
11816   }
11817
11818   // Otherwise we have to assume they alias.
11819   return true;
11820 }
11821
11822 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
11823 /// looking for aliasing nodes and adding them to the Aliases vector.
11824 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
11825                                    SmallVectorImpl<SDValue> &Aliases) {
11826   SmallVector<SDValue, 8> Chains;     // List of chains to visit.
11827   SmallPtrSet<SDNode *, 16> Visited;  // Visited node set.
11828
11829   // Get alias information for node.
11830   bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
11831
11832   // Starting off.
11833   Chains.push_back(OriginalChain);
11834   unsigned Depth = 0;
11835
11836   // Look at each chain and determine if it is an alias.  If so, add it to the
11837   // aliases list.  If not, then continue up the chain looking for the next
11838   // candidate.
11839   while (!Chains.empty()) {
11840     SDValue Chain = Chains.back();
11841     Chains.pop_back();
11842
11843     // For TokenFactor nodes, look at each operand and only continue up the
11844     // chain until we find two aliases.  If we've seen two aliases, assume we'll
11845     // find more and revert to original chain since the xform is unlikely to be
11846     // profitable.
11847     //
11848     // FIXME: The depth check could be made to return the last non-aliasing
11849     // chain we found before we hit a tokenfactor rather than the original
11850     // chain.
11851     if (Depth > 6 || Aliases.size() == 2) {
11852       Aliases.clear();
11853       Aliases.push_back(OriginalChain);
11854       return;
11855     }
11856
11857     // Don't bother if we've been before.
11858     if (!Visited.insert(Chain.getNode()))
11859       continue;
11860
11861     switch (Chain.getOpcode()) {
11862     case ISD::EntryToken:
11863       // Entry token is ideal chain operand, but handled in FindBetterChain.
11864       break;
11865
11866     case ISD::LOAD:
11867     case ISD::STORE: {
11868       // Get alias information for Chain.
11869       bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
11870           !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
11871
11872       // If chain is alias then stop here.
11873       if (!(IsLoad && IsOpLoad) &&
11874           isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
11875         Aliases.push_back(Chain);
11876       } else {
11877         // Look further up the chain.
11878         Chains.push_back(Chain.getOperand(0));
11879         ++Depth;
11880       }
11881       break;
11882     }
11883
11884     case ISD::TokenFactor:
11885       // We have to check each of the operands of the token factor for "small"
11886       // token factors, so we queue them up.  Adding the operands to the queue
11887       // (stack) in reverse order maintains the original order and increases the
11888       // likelihood that getNode will find a matching token factor (CSE.)
11889       if (Chain.getNumOperands() > 16) {
11890         Aliases.push_back(Chain);
11891         break;
11892       }
11893       for (unsigned n = Chain.getNumOperands(); n;)
11894         Chains.push_back(Chain.getOperand(--n));
11895       ++Depth;
11896       break;
11897
11898     default:
11899       // For all other instructions we will just have to take what we can get.
11900       Aliases.push_back(Chain);
11901       break;
11902     }
11903   }
11904
11905   // We need to be careful here to also search for aliases through the
11906   // value operand of a store, etc. Consider the following situation:
11907   //   Token1 = ...
11908   //   L1 = load Token1, %52
11909   //   S1 = store Token1, L1, %51
11910   //   L2 = load Token1, %52+8
11911   //   S2 = store Token1, L2, %51+8
11912   //   Token2 = Token(S1, S2)
11913   //   L3 = load Token2, %53
11914   //   S3 = store Token2, L3, %52
11915   //   L4 = load Token2, %53+8
11916   //   S4 = store Token2, L4, %52+8
11917   // If we search for aliases of S3 (which loads address %52), and we look
11918   // only through the chain, then we'll miss the trivial dependence on L1
11919   // (which also loads from %52). We then might change all loads and
11920   // stores to use Token1 as their chain operand, which could result in
11921   // copying %53 into %52 before copying %52 into %51 (which should
11922   // happen first).
11923   //
11924   // The problem is, however, that searching for such data dependencies
11925   // can become expensive, and the cost is not directly related to the
11926   // chain depth. Instead, we'll rule out such configurations here by
11927   // insisting that we've visited all chain users (except for users
11928   // of the original chain, which is not necessary). When doing this,
11929   // we need to look through nodes we don't care about (otherwise, things
11930   // like register copies will interfere with trivial cases).
11931
11932   SmallVector<const SDNode *, 16> Worklist;
11933   for (SmallPtrSet<SDNode *, 16>::iterator I = Visited.begin(),
11934        IE = Visited.end(); I != IE; ++I)
11935     if (*I != OriginalChain.getNode())
11936       Worklist.push_back(*I);
11937
11938   while (!Worklist.empty()) {
11939     const SDNode *M = Worklist.pop_back_val();
11940
11941     // We have already visited M, and want to make sure we've visited any uses
11942     // of M that we care about. For uses that we've not visisted, and don't
11943     // care about, queue them to the worklist.
11944
11945     for (SDNode::use_iterator UI = M->use_begin(),
11946          UIE = M->use_end(); UI != UIE; ++UI)
11947       if (UI.getUse().getValueType() == MVT::Other && Visited.insert(*UI)) {
11948         if (isa<MemIntrinsicSDNode>(*UI) || isa<MemSDNode>(*UI)) {
11949           // We've not visited this use, and we care about it (it could have an
11950           // ordering dependency with the original node).
11951           Aliases.clear();
11952           Aliases.push_back(OriginalChain);
11953           return;
11954         }
11955
11956         // We've not visited this use, but we don't care about it. Mark it as
11957         // visited and enqueue it to the worklist.
11958         Worklist.push_back(*UI);
11959       }
11960   }
11961 }
11962
11963 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes, looking
11964 /// for a better chain (aliasing node.)
11965 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
11966   SmallVector<SDValue, 8> Aliases;  // Ops for replacing token factor.
11967
11968   // Accumulate all the aliases to this node.
11969   GatherAllAliases(N, OldChain, Aliases);
11970
11971   // If no operands then chain to entry token.
11972   if (Aliases.size() == 0)
11973     return DAG.getEntryNode();
11974
11975   // If a single operand then chain to it.  We don't need to revisit it.
11976   if (Aliases.size() == 1)
11977     return Aliases[0];
11978
11979   // Construct a custom tailored token factor.
11980   return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
11981 }
11982
11983 // SelectionDAG::Combine - This is the entry point for the file.
11984 //
11985 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
11986                            CodeGenOpt::Level OptLevel) {
11987   /// run - This is the main entry point to this class.
11988   ///
11989   DAGCombiner(*this, AA, OptLevel).Run(Level);
11990 }