Fix fmul combines with constant splat vectors
[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.isPow2DivCheap())
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   MVT VT = N->getSimpleValueType(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   // We're sure we have an even number of elements due to the
4699   // concat_vectors we have as arguments to vselect.
4700   // Skip BV elements until we find one that's not an UNDEF
4701   // After we find an UNDEF element, keep looping until we get to half the
4702   // length of the BV and see if all the non-undef nodes are the same.
4703   ConstantSDNode *BottomHalf = nullptr;
4704   for (int i = 0; i < NumElems / 2; ++i) {
4705     if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
4706       continue;
4707
4708     if (BottomHalf == nullptr)
4709       BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
4710     else if (Cond->getOperand(i).getNode() != BottomHalf)
4711       return SDValue();
4712   }
4713
4714   // Do the same for the second half of the BuildVector
4715   ConstantSDNode *TopHalf = nullptr;
4716   for (int i = NumElems / 2; i < NumElems; ++i) {
4717     if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
4718       continue;
4719
4720     if (TopHalf == nullptr)
4721       TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
4722     else if (Cond->getOperand(i).getNode() != TopHalf)
4723       return SDValue();
4724   }
4725
4726   assert(TopHalf && BottomHalf &&
4727          "One half of the selector was all UNDEFs and the other was all the "
4728          "same value. This should have been addressed before this function.");
4729   return DAG.getNode(
4730       ISD::CONCAT_VECTORS, dl, VT,
4731       BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
4732       TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
4733 }
4734
4735 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
4736   SDValue N0 = N->getOperand(0);
4737   SDValue N1 = N->getOperand(1);
4738   SDValue N2 = N->getOperand(2);
4739   SDLoc DL(N);
4740
4741   // Canonicalize integer abs.
4742   // vselect (setg[te] X,  0),  X, -X ->
4743   // vselect (setgt    X, -1),  X, -X ->
4744   // vselect (setl[te] X,  0), -X,  X ->
4745   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
4746   if (N0.getOpcode() == ISD::SETCC) {
4747     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4748     ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4749     bool isAbs = false;
4750     bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
4751
4752     if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
4753          (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
4754         N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
4755       isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
4756     else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
4757              N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
4758       isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
4759
4760     if (isAbs) {
4761       EVT VT = LHS.getValueType();
4762       SDValue Shift = DAG.getNode(
4763           ISD::SRA, DL, VT, LHS,
4764           DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, VT));
4765       SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
4766       AddToWorklist(Shift.getNode());
4767       AddToWorklist(Add.getNode());
4768       return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
4769     }
4770   }
4771
4772   // If the VSELECT result requires splitting and the mask is provided by a
4773   // SETCC, then split both nodes and its operands before legalization. This
4774   // prevents the type legalizer from unrolling SETCC into scalar comparisons
4775   // and enables future optimizations (e.g. min/max pattern matching on X86).
4776   if (N0.getOpcode() == ISD::SETCC) {
4777     EVT VT = N->getValueType(0);
4778
4779     // Check if any splitting is required.
4780     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
4781         TargetLowering::TypeSplitVector)
4782       return SDValue();
4783
4784     SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
4785     std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
4786     std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
4787     std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
4788
4789     Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
4790     Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
4791
4792     // Add the new VSELECT nodes to the work list in case they need to be split
4793     // again.
4794     AddToWorklist(Lo.getNode());
4795     AddToWorklist(Hi.getNode());
4796
4797     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
4798   }
4799
4800   // Fold (vselect (build_vector all_ones), N1, N2) -> N1
4801   if (ISD::isBuildVectorAllOnes(N0.getNode()))
4802     return N1;
4803   // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
4804   if (ISD::isBuildVectorAllZeros(N0.getNode()))
4805     return N2;
4806
4807   // The ConvertSelectToConcatVector function is assuming both the above
4808   // checks for (vselect (build_vector all{ones,zeros) ...) have been made
4809   // and addressed.
4810   if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
4811       N2.getOpcode() == ISD::CONCAT_VECTORS &&
4812       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
4813     SDValue CV = ConvertSelectToConcatVector(N, DAG);
4814     if (CV.getNode())
4815       return CV;
4816   }
4817
4818   return SDValue();
4819 }
4820
4821 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
4822   SDValue N0 = N->getOperand(0);
4823   SDValue N1 = N->getOperand(1);
4824   SDValue N2 = N->getOperand(2);
4825   SDValue N3 = N->getOperand(3);
4826   SDValue N4 = N->getOperand(4);
4827   ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
4828
4829   // fold select_cc lhs, rhs, x, x, cc -> x
4830   if (N2 == N3)
4831     return N2;
4832
4833   // Determine if the condition we're dealing with is constant
4834   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
4835                               N0, N1, CC, SDLoc(N), false);
4836   if (SCC.getNode()) {
4837     AddToWorklist(SCC.getNode());
4838
4839     if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
4840       if (!SCCC->isNullValue())
4841         return N2;    // cond always true -> true val
4842       else
4843         return N3;    // cond always false -> false val
4844     }
4845
4846     // Fold to a simpler select_cc
4847     if (SCC.getOpcode() == ISD::SETCC)
4848       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
4849                          SCC.getOperand(0), SCC.getOperand(1), N2, N3,
4850                          SCC.getOperand(2));
4851   }
4852
4853   // If we can fold this based on the true/false value, do so.
4854   if (SimplifySelectOps(N, N2, N3))
4855     return SDValue(N, 0);  // Don't revisit N.
4856
4857   // fold select_cc into other things, such as min/max/abs
4858   return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
4859 }
4860
4861 SDValue DAGCombiner::visitSETCC(SDNode *N) {
4862   return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
4863                        cast<CondCodeSDNode>(N->getOperand(2))->get(),
4864                        SDLoc(N));
4865 }
4866
4867 // tryToFoldExtendOfConstant - Try to fold a sext/zext/aext
4868 // dag node into a ConstantSDNode or a build_vector of constants.
4869 // This function is called by the DAGCombiner when visiting sext/zext/aext
4870 // dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
4871 // Vector extends are not folded if operations are legal; this is to
4872 // avoid introducing illegal build_vector dag nodes.
4873 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
4874                                          SelectionDAG &DAG, bool LegalTypes,
4875                                          bool LegalOperations) {
4876   unsigned Opcode = N->getOpcode();
4877   SDValue N0 = N->getOperand(0);
4878   EVT VT = N->getValueType(0);
4879
4880   assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
4881          Opcode == ISD::ANY_EXTEND) && "Expected EXTEND dag node in input!");
4882
4883   // fold (sext c1) -> c1
4884   // fold (zext c1) -> c1
4885   // fold (aext c1) -> c1
4886   if (isa<ConstantSDNode>(N0))
4887     return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
4888
4889   // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
4890   // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
4891   // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
4892   EVT SVT = VT.getScalarType();
4893   if (!(VT.isVector() &&
4894       (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
4895       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
4896     return nullptr;
4897
4898   // We can fold this node into a build_vector.
4899   unsigned VTBits = SVT.getSizeInBits();
4900   unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
4901   unsigned ShAmt = VTBits - EVTBits;
4902   SmallVector<SDValue, 8> Elts;
4903   unsigned NumElts = N0->getNumOperands();
4904   SDLoc DL(N);
4905
4906   for (unsigned i=0; i != NumElts; ++i) {
4907     SDValue Op = N0->getOperand(i);
4908     if (Op->getOpcode() == ISD::UNDEF) {
4909       Elts.push_back(DAG.getUNDEF(SVT));
4910       continue;
4911     }
4912
4913     ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
4914     const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
4915     if (Opcode == ISD::SIGN_EXTEND)
4916       Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
4917                                      SVT));
4918     else
4919       Elts.push_back(DAG.getConstant(C.shl(ShAmt).lshr(ShAmt).getZExtValue(),
4920                                      SVT));
4921   }
4922
4923   return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts).getNode();
4924 }
4925
4926 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
4927 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
4928 // transformation. Returns true if extension are possible and the above
4929 // mentioned transformation is profitable.
4930 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
4931                                     unsigned ExtOpc,
4932                                     SmallVectorImpl<SDNode *> &ExtendNodes,
4933                                     const TargetLowering &TLI) {
4934   bool HasCopyToRegUses = false;
4935   bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
4936   for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
4937                             UE = N0.getNode()->use_end();
4938        UI != UE; ++UI) {
4939     SDNode *User = *UI;
4940     if (User == N)
4941       continue;
4942     if (UI.getUse().getResNo() != N0.getResNo())
4943       continue;
4944     // FIXME: Only extend SETCC N, N and SETCC N, c for now.
4945     if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
4946       ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
4947       if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
4948         // Sign bits will be lost after a zext.
4949         return false;
4950       bool Add = false;
4951       for (unsigned i = 0; i != 2; ++i) {
4952         SDValue UseOp = User->getOperand(i);
4953         if (UseOp == N0)
4954           continue;
4955         if (!isa<ConstantSDNode>(UseOp))
4956           return false;
4957         Add = true;
4958       }
4959       if (Add)
4960         ExtendNodes.push_back(User);
4961       continue;
4962     }
4963     // If truncates aren't free and there are users we can't
4964     // extend, it isn't worthwhile.
4965     if (!isTruncFree)
4966       return false;
4967     // Remember if this value is live-out.
4968     if (User->getOpcode() == ISD::CopyToReg)
4969       HasCopyToRegUses = true;
4970   }
4971
4972   if (HasCopyToRegUses) {
4973     bool BothLiveOut = false;
4974     for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
4975          UI != UE; ++UI) {
4976       SDUse &Use = UI.getUse();
4977       if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
4978         BothLiveOut = true;
4979         break;
4980       }
4981     }
4982     if (BothLiveOut)
4983       // Both unextended and extended values are live out. There had better be
4984       // a good reason for the transformation.
4985       return ExtendNodes.size();
4986   }
4987   return true;
4988 }
4989
4990 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
4991                                   SDValue Trunc, SDValue ExtLoad, SDLoc DL,
4992                                   ISD::NodeType ExtType) {
4993   // Extend SetCC uses if necessary.
4994   for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
4995     SDNode *SetCC = SetCCs[i];
4996     SmallVector<SDValue, 4> Ops;
4997
4998     for (unsigned j = 0; j != 2; ++j) {
4999       SDValue SOp = SetCC->getOperand(j);
5000       if (SOp == Trunc)
5001         Ops.push_back(ExtLoad);
5002       else
5003         Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
5004     }
5005
5006     Ops.push_back(SetCC->getOperand(2));
5007     CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
5008   }
5009 }
5010
5011 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
5012   SDValue N0 = N->getOperand(0);
5013   EVT VT = N->getValueType(0);
5014
5015   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5016                                               LegalOperations))
5017     return SDValue(Res, 0);
5018
5019   // fold (sext (sext x)) -> (sext x)
5020   // fold (sext (aext x)) -> (sext x)
5021   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5022     return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
5023                        N0.getOperand(0));
5024
5025   if (N0.getOpcode() == ISD::TRUNCATE) {
5026     // fold (sext (truncate (load x))) -> (sext (smaller load x))
5027     // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
5028     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5029     if (NarrowLoad.getNode()) {
5030       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5031       if (NarrowLoad.getNode() != N0.getNode()) {
5032         CombineTo(N0.getNode(), NarrowLoad);
5033         // CombineTo deleted the truncate, if needed, but not what's under it.
5034         AddToWorklist(oye);
5035       }
5036       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5037     }
5038
5039     // See if the value being truncated is already sign extended.  If so, just
5040     // eliminate the trunc/sext pair.
5041     SDValue Op = N0.getOperand(0);
5042     unsigned OpBits   = Op.getValueType().getScalarType().getSizeInBits();
5043     unsigned MidBits  = N0.getValueType().getScalarType().getSizeInBits();
5044     unsigned DestBits = VT.getScalarType().getSizeInBits();
5045     unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
5046
5047     if (OpBits == DestBits) {
5048       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
5049       // bits, it is already ready.
5050       if (NumSignBits > DestBits-MidBits)
5051         return Op;
5052     } else if (OpBits < DestBits) {
5053       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
5054       // bits, just sext from i32.
5055       if (NumSignBits > OpBits-MidBits)
5056         return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
5057     } else {
5058       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
5059       // bits, just truncate to i32.
5060       if (NumSignBits > OpBits-MidBits)
5061         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5062     }
5063
5064     // fold (sext (truncate x)) -> (sextinreg x).
5065     if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
5066                                                  N0.getValueType())) {
5067       if (OpBits < DestBits)
5068         Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
5069       else if (OpBits > DestBits)
5070         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
5071       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
5072                          DAG.getValueType(N0.getValueType()));
5073     }
5074   }
5075
5076   // fold (sext (load x)) -> (sext (truncate (sextload x)))
5077   // None of the supported targets knows how to perform load and sign extend
5078   // on vectors in one instruction.  We only perform this transformation on
5079   // scalars.
5080   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5081       ISD::isUNINDEXEDLoad(N0.getNode()) &&
5082       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5083        TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()))) {
5084     bool DoXform = true;
5085     SmallVector<SDNode*, 4> SetCCs;
5086     if (!N0.hasOneUse())
5087       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
5088     if (DoXform) {
5089       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5090       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5091                                        LN0->getChain(),
5092                                        LN0->getBasePtr(), N0.getValueType(),
5093                                        LN0->getMemOperand());
5094       CombineTo(N, ExtLoad);
5095       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5096                                   N0.getValueType(), ExtLoad);
5097       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5098       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5099                       ISD::SIGN_EXTEND);
5100       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5101     }
5102   }
5103
5104   // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
5105   // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
5106   if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5107       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5108     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5109     EVT MemVT = LN0->getMemoryVT();
5110     if ((!LegalOperations && !LN0->isVolatile()) ||
5111         TLI.isLoadExtLegal(ISD::SEXTLOAD, MemVT)) {
5112       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5113                                        LN0->getChain(),
5114                                        LN0->getBasePtr(), MemVT,
5115                                        LN0->getMemOperand());
5116       CombineTo(N, ExtLoad);
5117       CombineTo(N0.getNode(),
5118                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5119                             N0.getValueType(), ExtLoad),
5120                 ExtLoad.getValue(1));
5121       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5122     }
5123   }
5124
5125   // fold (sext (and/or/xor (load x), cst)) ->
5126   //      (and/or/xor (sextload x), (sext cst))
5127   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5128        N0.getOpcode() == ISD::XOR) &&
5129       isa<LoadSDNode>(N0.getOperand(0)) &&
5130       N0.getOperand(1).getOpcode() == ISD::Constant &&
5131       TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()) &&
5132       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5133     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5134     if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
5135       bool DoXform = true;
5136       SmallVector<SDNode*, 4> SetCCs;
5137       if (!N0.hasOneUse())
5138         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
5139                                           SetCCs, TLI);
5140       if (DoXform) {
5141         SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
5142                                          LN0->getChain(), LN0->getBasePtr(),
5143                                          LN0->getMemoryVT(),
5144                                          LN0->getMemOperand());
5145         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5146         Mask = Mask.sext(VT.getSizeInBits());
5147         SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5148                                   ExtLoad, DAG.getConstant(Mask, VT));
5149         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5150                                     SDLoc(N0.getOperand(0)),
5151                                     N0.getOperand(0).getValueType(), ExtLoad);
5152         CombineTo(N, And);
5153         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5154         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5155                         ISD::SIGN_EXTEND);
5156         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5157       }
5158     }
5159   }
5160
5161   if (N0.getOpcode() == ISD::SETCC) {
5162     EVT N0VT = N0.getOperand(0).getValueType();
5163     // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
5164     // Only do this before legalize for now.
5165     if (VT.isVector() && !LegalOperations &&
5166         TLI.getBooleanContents(N0VT) ==
5167             TargetLowering::ZeroOrNegativeOneBooleanContent) {
5168       // On some architectures (such as SSE/NEON/etc) the SETCC result type is
5169       // of the same size as the compared operands. Only optimize sext(setcc())
5170       // if this is the case.
5171       EVT SVT = getSetCCResultType(N0VT);
5172
5173       // We know that the # elements of the results is the same as the
5174       // # elements of the compare (and the # elements of the compare result
5175       // for that matter).  Check to see that they are the same size.  If so,
5176       // we know that the element size of the sext'd result matches the
5177       // element size of the compare operands.
5178       if (VT.getSizeInBits() == SVT.getSizeInBits())
5179         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5180                              N0.getOperand(1),
5181                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
5182
5183       // If the desired elements are smaller or larger than the source
5184       // elements we can use a matching integer vector type and then
5185       // truncate/sign extend
5186       EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5187       if (SVT == MatchingVectorType) {
5188         SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
5189                                N0.getOperand(0), N0.getOperand(1),
5190                                cast<CondCodeSDNode>(N0.getOperand(2))->get());
5191         return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
5192       }
5193     }
5194
5195     // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
5196     unsigned ElementWidth = VT.getScalarType().getSizeInBits();
5197     SDValue NegOne =
5198       DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT);
5199     SDValue SCC =
5200       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5201                        NegOne, DAG.getConstant(0, VT),
5202                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5203     if (SCC.getNode()) return SCC;
5204
5205     if (!VT.isVector()) {
5206       EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
5207       if (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, SetCCVT)) {
5208         SDLoc DL(N);
5209         ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5210         SDValue SetCC = DAG.getSetCC(DL,
5211                                      SetCCVT,
5212                                      N0.getOperand(0), N0.getOperand(1), CC);
5213         EVT SelectVT = getSetCCResultType(VT);
5214         return DAG.getSelect(DL, VT,
5215                              DAG.getSExtOrTrunc(SetCC, DL, SelectVT),
5216                              NegOne, DAG.getConstant(0, VT));
5217
5218       }
5219     }
5220   }
5221
5222   // fold (sext x) -> (zext x) if the sign bit is known zero.
5223   if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
5224       DAG.SignBitIsZero(N0))
5225     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
5226
5227   return SDValue();
5228 }
5229
5230 // isTruncateOf - If N is a truncate of some other value, return true, record
5231 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
5232 // This function computes KnownZero to avoid a duplicated call to
5233 // computeKnownBits in the caller.
5234 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
5235                          APInt &KnownZero) {
5236   APInt KnownOne;
5237   if (N->getOpcode() == ISD::TRUNCATE) {
5238     Op = N->getOperand(0);
5239     DAG.computeKnownBits(Op, KnownZero, KnownOne);
5240     return true;
5241   }
5242
5243   if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
5244       cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
5245     return false;
5246
5247   SDValue Op0 = N->getOperand(0);
5248   SDValue Op1 = N->getOperand(1);
5249   assert(Op0.getValueType() == Op1.getValueType());
5250
5251   ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0);
5252   ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
5253   if (COp0 && COp0->isNullValue())
5254     Op = Op1;
5255   else if (COp1 && COp1->isNullValue())
5256     Op = Op0;
5257   else
5258     return false;
5259
5260   DAG.computeKnownBits(Op, KnownZero, KnownOne);
5261
5262   if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
5263     return false;
5264
5265   return true;
5266 }
5267
5268 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
5269   SDValue N0 = N->getOperand(0);
5270   EVT VT = N->getValueType(0);
5271
5272   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5273                                               LegalOperations))
5274     return SDValue(Res, 0);
5275
5276   // fold (zext (zext x)) -> (zext x)
5277   // fold (zext (aext x)) -> (zext x)
5278   if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5279     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
5280                        N0.getOperand(0));
5281
5282   // fold (zext (truncate x)) -> (zext x) or
5283   //      (zext (truncate x)) -> (truncate x)
5284   // This is valid when the truncated bits of x are already zero.
5285   // FIXME: We should extend this to work for vectors too.
5286   SDValue Op;
5287   APInt KnownZero;
5288   if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
5289     APInt TruncatedBits =
5290       (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
5291       APInt(Op.getValueSizeInBits(), 0) :
5292       APInt::getBitsSet(Op.getValueSizeInBits(),
5293                         N0.getValueSizeInBits(),
5294                         std::min(Op.getValueSizeInBits(),
5295                                  VT.getSizeInBits()));
5296     if (TruncatedBits == (KnownZero & TruncatedBits)) {
5297       if (VT.bitsGT(Op.getValueType()))
5298         return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
5299       if (VT.bitsLT(Op.getValueType()))
5300         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5301
5302       return Op;
5303     }
5304   }
5305
5306   // fold (zext (truncate (load x))) -> (zext (smaller load x))
5307   // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
5308   if (N0.getOpcode() == ISD::TRUNCATE) {
5309     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5310     if (NarrowLoad.getNode()) {
5311       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5312       if (NarrowLoad.getNode() != N0.getNode()) {
5313         CombineTo(N0.getNode(), NarrowLoad);
5314         // CombineTo deleted the truncate, if needed, but not what's under it.
5315         AddToWorklist(oye);
5316       }
5317       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5318     }
5319   }
5320
5321   // fold (zext (truncate x)) -> (and x, mask)
5322   if (N0.getOpcode() == ISD::TRUNCATE &&
5323       (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
5324
5325     // fold (zext (truncate (load x))) -> (zext (smaller load x))
5326     // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
5327     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5328     if (NarrowLoad.getNode()) {
5329       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5330       if (NarrowLoad.getNode() != N0.getNode()) {
5331         CombineTo(N0.getNode(), NarrowLoad);
5332         // CombineTo deleted the truncate, if needed, but not what's under it.
5333         AddToWorklist(oye);
5334       }
5335       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5336     }
5337
5338     SDValue Op = N0.getOperand(0);
5339     if (Op.getValueType().bitsLT(VT)) {
5340       Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
5341       AddToWorklist(Op.getNode());
5342     } else if (Op.getValueType().bitsGT(VT)) {
5343       Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5344       AddToWorklist(Op.getNode());
5345     }
5346     return DAG.getZeroExtendInReg(Op, SDLoc(N),
5347                                   N0.getValueType().getScalarType());
5348   }
5349
5350   // Fold (zext (and (trunc x), cst)) -> (and x, cst),
5351   // if either of the casts is not free.
5352   if (N0.getOpcode() == ISD::AND &&
5353       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5354       N0.getOperand(1).getOpcode() == ISD::Constant &&
5355       (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5356                            N0.getValueType()) ||
5357        !TLI.isZExtFree(N0.getValueType(), VT))) {
5358     SDValue X = N0.getOperand(0).getOperand(0);
5359     if (X.getValueType().bitsLT(VT)) {
5360       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
5361     } else if (X.getValueType().bitsGT(VT)) {
5362       X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
5363     }
5364     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5365     Mask = Mask.zext(VT.getSizeInBits());
5366     return DAG.getNode(ISD::AND, SDLoc(N), VT,
5367                        X, DAG.getConstant(Mask, VT));
5368   }
5369
5370   // fold (zext (load x)) -> (zext (truncate (zextload x)))
5371   // None of the supported targets knows how to perform load and vector_zext
5372   // on vectors in one instruction.  We only perform this transformation on
5373   // scalars.
5374   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5375       ISD::isUNINDEXEDLoad(N0.getNode()) &&
5376       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5377        TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()))) {
5378     bool DoXform = true;
5379     SmallVector<SDNode*, 4> SetCCs;
5380     if (!N0.hasOneUse())
5381       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
5382     if (DoXform) {
5383       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5384       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5385                                        LN0->getChain(),
5386                                        LN0->getBasePtr(), N0.getValueType(),
5387                                        LN0->getMemOperand());
5388       CombineTo(N, ExtLoad);
5389       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5390                                   N0.getValueType(), ExtLoad);
5391       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5392
5393       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5394                       ISD::ZERO_EXTEND);
5395       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5396     }
5397   }
5398
5399   // fold (zext (and/or/xor (load x), cst)) ->
5400   //      (and/or/xor (zextload x), (zext cst))
5401   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5402        N0.getOpcode() == ISD::XOR) &&
5403       isa<LoadSDNode>(N0.getOperand(0)) &&
5404       N0.getOperand(1).getOpcode() == ISD::Constant &&
5405       TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()) &&
5406       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5407     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5408     if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
5409       bool DoXform = true;
5410       SmallVector<SDNode*, 4> SetCCs;
5411       if (!N0.hasOneUse())
5412         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
5413                                           SetCCs, TLI);
5414       if (DoXform) {
5415         SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
5416                                          LN0->getChain(), LN0->getBasePtr(),
5417                                          LN0->getMemoryVT(),
5418                                          LN0->getMemOperand());
5419         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5420         Mask = Mask.zext(VT.getSizeInBits());
5421         SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5422                                   ExtLoad, DAG.getConstant(Mask, VT));
5423         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5424                                     SDLoc(N0.getOperand(0)),
5425                                     N0.getOperand(0).getValueType(), ExtLoad);
5426         CombineTo(N, And);
5427         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5428         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5429                         ISD::ZERO_EXTEND);
5430         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5431       }
5432     }
5433   }
5434
5435   // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
5436   // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
5437   if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5438       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5439     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5440     EVT MemVT = LN0->getMemoryVT();
5441     if ((!LegalOperations && !LN0->isVolatile()) ||
5442         TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT)) {
5443       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5444                                        LN0->getChain(),
5445                                        LN0->getBasePtr(), MemVT,
5446                                        LN0->getMemOperand());
5447       CombineTo(N, ExtLoad);
5448       CombineTo(N0.getNode(),
5449                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
5450                             ExtLoad),
5451                 ExtLoad.getValue(1));
5452       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5453     }
5454   }
5455
5456   if (N0.getOpcode() == ISD::SETCC) {
5457     if (!LegalOperations && VT.isVector() &&
5458         N0.getValueType().getVectorElementType() == MVT::i1) {
5459       EVT N0VT = N0.getOperand(0).getValueType();
5460       if (getSetCCResultType(N0VT) == N0.getValueType())
5461         return SDValue();
5462
5463       // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
5464       // Only do this before legalize for now.
5465       EVT EltVT = VT.getVectorElementType();
5466       SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
5467                                     DAG.getConstant(1, EltVT));
5468       if (VT.getSizeInBits() == N0VT.getSizeInBits())
5469         // We know that the # elements of the results is the same as the
5470         // # elements of the compare (and the # elements of the compare result
5471         // for that matter).  Check to see that they are the same size.  If so,
5472         // we know that the element size of the sext'd result matches the
5473         // element size of the compare operands.
5474         return DAG.getNode(ISD::AND, SDLoc(N), VT,
5475                            DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5476                                          N0.getOperand(1),
5477                                  cast<CondCodeSDNode>(N0.getOperand(2))->get()),
5478                            DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
5479                                        OneOps));
5480
5481       // If the desired elements are smaller or larger than the source
5482       // elements we can use a matching integer vector type and then
5483       // truncate/sign extend
5484       EVT MatchingElementType =
5485         EVT::getIntegerVT(*DAG.getContext(),
5486                           N0VT.getScalarType().getSizeInBits());
5487       EVT MatchingVectorType =
5488         EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
5489                          N0VT.getVectorNumElements());
5490       SDValue VsetCC =
5491         DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5492                       N0.getOperand(1),
5493                       cast<CondCodeSDNode>(N0.getOperand(2))->get());
5494       return DAG.getNode(ISD::AND, SDLoc(N), VT,
5495                          DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT),
5496                          DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, OneOps));
5497     }
5498
5499     // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5500     SDValue SCC =
5501       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5502                        DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5503                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5504     if (SCC.getNode()) return SCC;
5505   }
5506
5507   // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
5508   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
5509       isa<ConstantSDNode>(N0.getOperand(1)) &&
5510       N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
5511       N0.hasOneUse()) {
5512     SDValue ShAmt = N0.getOperand(1);
5513     unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
5514     if (N0.getOpcode() == ISD::SHL) {
5515       SDValue InnerZExt = N0.getOperand(0);
5516       // If the original shl may be shifting out bits, do not perform this
5517       // transformation.
5518       unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
5519         InnerZExt.getOperand(0).getValueType().getSizeInBits();
5520       if (ShAmtVal > KnownZeroBits)
5521         return SDValue();
5522     }
5523
5524     SDLoc DL(N);
5525
5526     // Ensure that the shift amount is wide enough for the shifted value.
5527     if (VT.getSizeInBits() >= 256)
5528       ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
5529
5530     return DAG.getNode(N0.getOpcode(), DL, VT,
5531                        DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
5532                        ShAmt);
5533   }
5534
5535   return SDValue();
5536 }
5537
5538 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
5539   SDValue N0 = N->getOperand(0);
5540   EVT VT = N->getValueType(0);
5541
5542   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5543                                               LegalOperations))
5544     return SDValue(Res, 0);
5545
5546   // fold (aext (aext x)) -> (aext x)
5547   // fold (aext (zext x)) -> (zext x)
5548   // fold (aext (sext x)) -> (sext x)
5549   if (N0.getOpcode() == ISD::ANY_EXTEND  ||
5550       N0.getOpcode() == ISD::ZERO_EXTEND ||
5551       N0.getOpcode() == ISD::SIGN_EXTEND)
5552     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
5553
5554   // fold (aext (truncate (load x))) -> (aext (smaller load x))
5555   // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
5556   if (N0.getOpcode() == ISD::TRUNCATE) {
5557     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5558     if (NarrowLoad.getNode()) {
5559       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5560       if (NarrowLoad.getNode() != N0.getNode()) {
5561         CombineTo(N0.getNode(), NarrowLoad);
5562         // CombineTo deleted the truncate, if needed, but not what's under it.
5563         AddToWorklist(oye);
5564       }
5565       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5566     }
5567   }
5568
5569   // fold (aext (truncate x))
5570   if (N0.getOpcode() == ISD::TRUNCATE) {
5571     SDValue TruncOp = N0.getOperand(0);
5572     if (TruncOp.getValueType() == VT)
5573       return TruncOp; // x iff x size == zext size.
5574     if (TruncOp.getValueType().bitsGT(VT))
5575       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
5576     return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
5577   }
5578
5579   // Fold (aext (and (trunc x), cst)) -> (and x, cst)
5580   // if the trunc is not free.
5581   if (N0.getOpcode() == ISD::AND &&
5582       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5583       N0.getOperand(1).getOpcode() == ISD::Constant &&
5584       !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5585                           N0.getValueType())) {
5586     SDValue X = N0.getOperand(0).getOperand(0);
5587     if (X.getValueType().bitsLT(VT)) {
5588       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
5589     } else if (X.getValueType().bitsGT(VT)) {
5590       X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
5591     }
5592     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5593     Mask = Mask.zext(VT.getSizeInBits());
5594     return DAG.getNode(ISD::AND, SDLoc(N), VT,
5595                        X, DAG.getConstant(Mask, VT));
5596   }
5597
5598   // fold (aext (load x)) -> (aext (truncate (extload x)))
5599   // None of the supported targets knows how to perform load and any_ext
5600   // on vectors in one instruction.  We only perform this transformation on
5601   // scalars.
5602   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5603       ISD::isUNINDEXEDLoad(N0.getNode()) &&
5604       TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType())) {
5605     bool DoXform = true;
5606     SmallVector<SDNode*, 4> SetCCs;
5607     if (!N0.hasOneUse())
5608       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
5609     if (DoXform) {
5610       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5611       SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
5612                                        LN0->getChain(),
5613                                        LN0->getBasePtr(), N0.getValueType(),
5614                                        LN0->getMemOperand());
5615       CombineTo(N, ExtLoad);
5616       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5617                                   N0.getValueType(), ExtLoad);
5618       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5619       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5620                       ISD::ANY_EXTEND);
5621       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5622     }
5623   }
5624
5625   // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
5626   // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
5627   // fold (aext ( extload x)) -> (aext (truncate (extload  x)))
5628   if (N0.getOpcode() == ISD::LOAD &&
5629       !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5630       N0.hasOneUse()) {
5631     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5632     ISD::LoadExtType ExtType = LN0->getExtensionType();
5633     EVT MemVT = LN0->getMemoryVT();
5634     if (!LegalOperations || TLI.isLoadExtLegal(ExtType, MemVT)) {
5635       SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
5636                                        VT, LN0->getChain(), LN0->getBasePtr(),
5637                                        MemVT, LN0->getMemOperand());
5638       CombineTo(N, ExtLoad);
5639       CombineTo(N0.getNode(),
5640                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5641                             N0.getValueType(), ExtLoad),
5642                 ExtLoad.getValue(1));
5643       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5644     }
5645   }
5646
5647   if (N0.getOpcode() == ISD::SETCC) {
5648     // For vectors:
5649     // aext(setcc) -> vsetcc
5650     // aext(setcc) -> truncate(vsetcc)
5651     // aext(setcc) -> aext(vsetcc)
5652     // Only do this before legalize for now.
5653     if (VT.isVector() && !LegalOperations) {
5654       EVT N0VT = N0.getOperand(0).getValueType();
5655         // We know that the # elements of the results is the same as the
5656         // # elements of the compare (and the # elements of the compare result
5657         // for that matter).  Check to see that they are the same size.  If so,
5658         // we know that the element size of the sext'd result matches the
5659         // element size of the compare operands.
5660       if (VT.getSizeInBits() == N0VT.getSizeInBits())
5661         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5662                              N0.getOperand(1),
5663                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
5664       // If the desired elements are smaller or larger than the source
5665       // elements we can use a matching integer vector type and then
5666       // truncate/any extend
5667       else {
5668         EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5669         SDValue VsetCC =
5670           DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5671                         N0.getOperand(1),
5672                         cast<CondCodeSDNode>(N0.getOperand(2))->get());
5673         return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
5674       }
5675     }
5676
5677     // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5678     SDValue SCC =
5679       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5680                        DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5681                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5682     if (SCC.getNode())
5683       return SCC;
5684   }
5685
5686   return SDValue();
5687 }
5688
5689 /// GetDemandedBits - See if the specified operand can be simplified with the
5690 /// knowledge that only the bits specified by Mask are used.  If so, return the
5691 /// simpler operand, otherwise return a null SDValue.
5692 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
5693   switch (V.getOpcode()) {
5694   default: break;
5695   case ISD::Constant: {
5696     const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
5697     assert(CV && "Const value should be ConstSDNode.");
5698     const APInt &CVal = CV->getAPIntValue();
5699     APInt NewVal = CVal & Mask;
5700     if (NewVal != CVal)
5701       return DAG.getConstant(NewVal, V.getValueType());
5702     break;
5703   }
5704   case ISD::OR:
5705   case ISD::XOR:
5706     // If the LHS or RHS don't contribute bits to the or, drop them.
5707     if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
5708       return V.getOperand(1);
5709     if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
5710       return V.getOperand(0);
5711     break;
5712   case ISD::SRL:
5713     // Only look at single-use SRLs.
5714     if (!V.getNode()->hasOneUse())
5715       break;
5716     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
5717       // See if we can recursively simplify the LHS.
5718       unsigned Amt = RHSC->getZExtValue();
5719
5720       // Watch out for shift count overflow though.
5721       if (Amt >= Mask.getBitWidth()) break;
5722       APInt NewMask = Mask << Amt;
5723       SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
5724       if (SimplifyLHS.getNode())
5725         return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
5726                            SimplifyLHS, V.getOperand(1));
5727     }
5728   }
5729   return SDValue();
5730 }
5731
5732 /// ReduceLoadWidth - If the result of a wider load is shifted to right of N
5733 /// bits and then truncated to a narrower type and where N is a multiple
5734 /// of number of bits of the narrower type, transform it to a narrower load
5735 /// from address + N / num of bits of new type. If the result is to be
5736 /// extended, also fold the extension to form a extending load.
5737 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
5738   unsigned Opc = N->getOpcode();
5739
5740   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
5741   SDValue N0 = N->getOperand(0);
5742   EVT VT = N->getValueType(0);
5743   EVT ExtVT = VT;
5744
5745   // This transformation isn't valid for vector loads.
5746   if (VT.isVector())
5747     return SDValue();
5748
5749   // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
5750   // extended to VT.
5751   if (Opc == ISD::SIGN_EXTEND_INREG) {
5752     ExtType = ISD::SEXTLOAD;
5753     ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
5754   } else if (Opc == ISD::SRL) {
5755     // Another special-case: SRL is basically zero-extending a narrower value.
5756     ExtType = ISD::ZEXTLOAD;
5757     N0 = SDValue(N, 0);
5758     ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
5759     if (!N01) return SDValue();
5760     ExtVT = EVT::getIntegerVT(*DAG.getContext(),
5761                               VT.getSizeInBits() - N01->getZExtValue());
5762   }
5763   if (LegalOperations && !TLI.isLoadExtLegal(ExtType, ExtVT))
5764     return SDValue();
5765
5766   unsigned EVTBits = ExtVT.getSizeInBits();
5767
5768   // Do not generate loads of non-round integer types since these can
5769   // be expensive (and would be wrong if the type is not byte sized).
5770   if (!ExtVT.isRound())
5771     return SDValue();
5772
5773   unsigned ShAmt = 0;
5774   if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
5775     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5776       ShAmt = N01->getZExtValue();
5777       // Is the shift amount a multiple of size of VT?
5778       if ((ShAmt & (EVTBits-1)) == 0) {
5779         N0 = N0.getOperand(0);
5780         // Is the load width a multiple of size of VT?
5781         if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
5782           return SDValue();
5783       }
5784
5785       // At this point, we must have a load or else we can't do the transform.
5786       if (!isa<LoadSDNode>(N0)) return SDValue();
5787
5788       // Because a SRL must be assumed to *need* to zero-extend the high bits
5789       // (as opposed to anyext the high bits), we can't combine the zextload
5790       // lowering of SRL and an sextload.
5791       if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
5792         return SDValue();
5793
5794       // If the shift amount is larger than the input type then we're not
5795       // accessing any of the loaded bytes.  If the load was a zextload/extload
5796       // then the result of the shift+trunc is zero/undef (handled elsewhere).
5797       if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
5798         return SDValue();
5799     }
5800   }
5801
5802   // If the load is shifted left (and the result isn't shifted back right),
5803   // we can fold the truncate through the shift.
5804   unsigned ShLeftAmt = 0;
5805   if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
5806       ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
5807     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5808       ShLeftAmt = N01->getZExtValue();
5809       N0 = N0.getOperand(0);
5810     }
5811   }
5812
5813   // If we haven't found a load, we can't narrow it.  Don't transform one with
5814   // multiple uses, this would require adding a new load.
5815   if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
5816     return SDValue();
5817
5818   // Don't change the width of a volatile load.
5819   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5820   if (LN0->isVolatile())
5821     return SDValue();
5822
5823   // Verify that we are actually reducing a load width here.
5824   if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
5825     return SDValue();
5826
5827   // For the transform to be legal, the load must produce only two values
5828   // (the value loaded and the chain).  Don't transform a pre-increment
5829   // load, for example, which produces an extra value.  Otherwise the
5830   // transformation is not equivalent, and the downstream logic to replace
5831   // uses gets things wrong.
5832   if (LN0->getNumValues() > 2)
5833     return SDValue();
5834
5835   // If the load that we're shrinking is an extload and we're not just
5836   // discarding the extension we can't simply shrink the load. Bail.
5837   // TODO: It would be possible to merge the extensions in some cases.
5838   if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
5839       LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
5840     return SDValue();
5841
5842   EVT PtrType = N0.getOperand(1).getValueType();
5843
5844   if (PtrType == MVT::Untyped || PtrType.isExtended())
5845     // It's not possible to generate a constant of extended or untyped type.
5846     return SDValue();
5847
5848   // For big endian targets, we need to adjust the offset to the pointer to
5849   // load the correct bytes.
5850   if (TLI.isBigEndian()) {
5851     unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
5852     unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
5853     ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
5854   }
5855
5856   uint64_t PtrOff = ShAmt / 8;
5857   unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
5858   SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0),
5859                                PtrType, LN0->getBasePtr(),
5860                                DAG.getConstant(PtrOff, PtrType));
5861   AddToWorklist(NewPtr.getNode());
5862
5863   SDValue Load;
5864   if (ExtType == ISD::NON_EXTLOAD)
5865     Load =  DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
5866                         LN0->getPointerInfo().getWithOffset(PtrOff),
5867                         LN0->isVolatile(), LN0->isNonTemporal(),
5868                         LN0->isInvariant(), NewAlign, LN0->getAAInfo());
5869   else
5870     Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
5871                           LN0->getPointerInfo().getWithOffset(PtrOff),
5872                           ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
5873                           LN0->isInvariant(), NewAlign, LN0->getAAInfo());
5874
5875   // Replace the old load's chain with the new load's chain.
5876   WorklistRemover DeadNodes(*this);
5877   DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
5878
5879   // Shift the result left, if we've swallowed a left shift.
5880   SDValue Result = Load;
5881   if (ShLeftAmt != 0) {
5882     EVT ShImmTy = getShiftAmountTy(Result.getValueType());
5883     if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
5884       ShImmTy = VT;
5885     // If the shift amount is as large as the result size (but, presumably,
5886     // no larger than the source) then the useful bits of the result are
5887     // zero; we can't simply return the shortened shift, because the result
5888     // of that operation is undefined.
5889     if (ShLeftAmt >= VT.getSizeInBits())
5890       Result = DAG.getConstant(0, VT);
5891     else
5892       Result = DAG.getNode(ISD::SHL, SDLoc(N0), VT,
5893                           Result, DAG.getConstant(ShLeftAmt, ShImmTy));
5894   }
5895
5896   // Return the new loaded value.
5897   return Result;
5898 }
5899
5900 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
5901   SDValue N0 = N->getOperand(0);
5902   SDValue N1 = N->getOperand(1);
5903   EVT VT = N->getValueType(0);
5904   EVT EVT = cast<VTSDNode>(N1)->getVT();
5905   unsigned VTBits = VT.getScalarType().getSizeInBits();
5906   unsigned EVTBits = EVT.getScalarType().getSizeInBits();
5907
5908   // fold (sext_in_reg c1) -> c1
5909   if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
5910     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
5911
5912   // If the input is already sign extended, just drop the extension.
5913   if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
5914     return N0;
5915
5916   // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
5917   if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
5918       EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
5919     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5920                        N0.getOperand(0), N1);
5921
5922   // fold (sext_in_reg (sext x)) -> (sext x)
5923   // fold (sext_in_reg (aext x)) -> (sext x)
5924   // if x is small enough.
5925   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
5926     SDValue N00 = N0.getOperand(0);
5927     if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
5928         (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
5929       return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
5930   }
5931
5932   // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
5933   if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
5934     return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
5935
5936   // fold operands of sext_in_reg based on knowledge that the top bits are not
5937   // demanded.
5938   if (SimplifyDemandedBits(SDValue(N, 0)))
5939     return SDValue(N, 0);
5940
5941   // fold (sext_in_reg (load x)) -> (smaller sextload x)
5942   // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
5943   SDValue NarrowLoad = ReduceLoadWidth(N);
5944   if (NarrowLoad.getNode())
5945     return NarrowLoad;
5946
5947   // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
5948   // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
5949   // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
5950   if (N0.getOpcode() == ISD::SRL) {
5951     if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
5952       if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
5953         // We can turn this into an SRA iff the input to the SRL is already sign
5954         // extended enough.
5955         unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
5956         if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
5957           return DAG.getNode(ISD::SRA, SDLoc(N), VT,
5958                              N0.getOperand(0), N0.getOperand(1));
5959       }
5960   }
5961
5962   // fold (sext_inreg (extload x)) -> (sextload x)
5963   if (ISD::isEXTLoad(N0.getNode()) &&
5964       ISD::isUNINDEXEDLoad(N0.getNode()) &&
5965       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5966       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5967        TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5968     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5969     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5970                                      LN0->getChain(),
5971                                      LN0->getBasePtr(), EVT,
5972                                      LN0->getMemOperand());
5973     CombineTo(N, ExtLoad);
5974     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5975     AddToWorklist(ExtLoad.getNode());
5976     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5977   }
5978   // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
5979   if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5980       N0.hasOneUse() &&
5981       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5982       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5983        TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5984     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5985     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5986                                      LN0->getChain(),
5987                                      LN0->getBasePtr(), EVT,
5988                                      LN0->getMemOperand());
5989     CombineTo(N, ExtLoad);
5990     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5991     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5992   }
5993
5994   // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
5995   if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
5996     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
5997                                        N0.getOperand(1), false);
5998     if (BSwap.getNode())
5999       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6000                          BSwap, N1);
6001   }
6002
6003   // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs
6004   // into a build_vector.
6005   if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
6006     SmallVector<SDValue, 8> Elts;
6007     unsigned NumElts = N0->getNumOperands();
6008     unsigned ShAmt = VTBits - EVTBits;
6009
6010     for (unsigned i = 0; i != NumElts; ++i) {
6011       SDValue Op = N0->getOperand(i);
6012       if (Op->getOpcode() == ISD::UNDEF) {
6013         Elts.push_back(Op);
6014         continue;
6015       }
6016
6017       ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
6018       const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
6019       Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
6020                                      Op.getValueType()));
6021     }
6022
6023     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Elts);
6024   }
6025
6026   return SDValue();
6027 }
6028
6029 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
6030   SDValue N0 = N->getOperand(0);
6031   EVT VT = N->getValueType(0);
6032   bool isLE = TLI.isLittleEndian();
6033
6034   // noop truncate
6035   if (N0.getValueType() == N->getValueType(0))
6036     return N0;
6037   // fold (truncate c1) -> c1
6038   if (isa<ConstantSDNode>(N0))
6039     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
6040   // fold (truncate (truncate x)) -> (truncate x)
6041   if (N0.getOpcode() == ISD::TRUNCATE)
6042     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6043   // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
6044   if (N0.getOpcode() == ISD::ZERO_EXTEND ||
6045       N0.getOpcode() == ISD::SIGN_EXTEND ||
6046       N0.getOpcode() == ISD::ANY_EXTEND) {
6047     if (N0.getOperand(0).getValueType().bitsLT(VT))
6048       // if the source is smaller than the dest, we still need an extend
6049       return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
6050                          N0.getOperand(0));
6051     if (N0.getOperand(0).getValueType().bitsGT(VT))
6052       // if the source is larger than the dest, than we just need the truncate
6053       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6054     // if the source and dest are the same type, we can drop both the extend
6055     // and the truncate.
6056     return N0.getOperand(0);
6057   }
6058
6059   // Fold extract-and-trunc into a narrow extract. For example:
6060   //   i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
6061   //   i32 y = TRUNCATE(i64 x)
6062   //        -- becomes --
6063   //   v16i8 b = BITCAST (v2i64 val)
6064   //   i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
6065   //
6066   // Note: We only run this optimization after type legalization (which often
6067   // creates this pattern) and before operation legalization after which
6068   // we need to be more careful about the vector instructions that we generate.
6069   if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6070       LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
6071
6072     EVT VecTy = N0.getOperand(0).getValueType();
6073     EVT ExTy = N0.getValueType();
6074     EVT TrTy = N->getValueType(0);
6075
6076     unsigned NumElem = VecTy.getVectorNumElements();
6077     unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
6078
6079     EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
6080     assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
6081
6082     SDValue EltNo = N0->getOperand(1);
6083     if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
6084       int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
6085       EVT IndexTy = TLI.getVectorIdxTy();
6086       int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
6087
6088       SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
6089                               NVT, N0.getOperand(0));
6090
6091       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
6092                          SDLoc(N), TrTy, V,
6093                          DAG.getConstant(Index, IndexTy));
6094     }
6095   }
6096
6097   // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
6098   if (N0.getOpcode() == ISD::SELECT) {
6099     EVT SrcVT = N0.getValueType();
6100     if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
6101         TLI.isTruncateFree(SrcVT, VT)) {
6102       SDLoc SL(N0);
6103       SDValue Cond = N0.getOperand(0);
6104       SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
6105       SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
6106       return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
6107     }
6108   }
6109
6110   // Fold a series of buildvector, bitcast, and truncate if possible.
6111   // For example fold
6112   //   (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
6113   //   (2xi32 (buildvector x, y)).
6114   if (Level == AfterLegalizeVectorOps && VT.isVector() &&
6115       N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
6116       N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
6117       N0.getOperand(0).hasOneUse()) {
6118
6119     SDValue BuildVect = N0.getOperand(0);
6120     EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
6121     EVT TruncVecEltTy = VT.getVectorElementType();
6122
6123     // Check that the element types match.
6124     if (BuildVectEltTy == TruncVecEltTy) {
6125       // Now we only need to compute the offset of the truncated elements.
6126       unsigned BuildVecNumElts =  BuildVect.getNumOperands();
6127       unsigned TruncVecNumElts = VT.getVectorNumElements();
6128       unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
6129
6130       assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
6131              "Invalid number of elements");
6132
6133       SmallVector<SDValue, 8> Opnds;
6134       for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
6135         Opnds.push_back(BuildVect.getOperand(i));
6136
6137       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
6138     }
6139   }
6140
6141   // See if we can simplify the input to this truncate through knowledge that
6142   // only the low bits are being used.
6143   // For example "trunc (or (shl x, 8), y)" // -> trunc y
6144   // Currently we only perform this optimization on scalars because vectors
6145   // may have different active low bits.
6146   if (!VT.isVector()) {
6147     SDValue Shorter =
6148       GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
6149                                                VT.getSizeInBits()));
6150     if (Shorter.getNode())
6151       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
6152   }
6153   // fold (truncate (load x)) -> (smaller load x)
6154   // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
6155   if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
6156     SDValue Reduced = ReduceLoadWidth(N);
6157     if (Reduced.getNode())
6158       return Reduced;
6159     // Handle the case where the load remains an extending load even
6160     // after truncation.
6161     if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
6162       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6163       if (!LN0->isVolatile() &&
6164           LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
6165         SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
6166                                          VT, LN0->getChain(), LN0->getBasePtr(),
6167                                          LN0->getMemoryVT(),
6168                                          LN0->getMemOperand());
6169         DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
6170         return NewLoad;
6171       }
6172     }
6173   }
6174   // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
6175   // where ... are all 'undef'.
6176   if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
6177     SmallVector<EVT, 8> VTs;
6178     SDValue V;
6179     unsigned Idx = 0;
6180     unsigned NumDefs = 0;
6181
6182     for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
6183       SDValue X = N0.getOperand(i);
6184       if (X.getOpcode() != ISD::UNDEF) {
6185         V = X;
6186         Idx = i;
6187         NumDefs++;
6188       }
6189       // Stop if more than one members are non-undef.
6190       if (NumDefs > 1)
6191         break;
6192       VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
6193                                      VT.getVectorElementType(),
6194                                      X.getValueType().getVectorNumElements()));
6195     }
6196
6197     if (NumDefs == 0)
6198       return DAG.getUNDEF(VT);
6199
6200     if (NumDefs == 1) {
6201       assert(V.getNode() && "The single defined operand is empty!");
6202       SmallVector<SDValue, 8> Opnds;
6203       for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
6204         if (i != Idx) {
6205           Opnds.push_back(DAG.getUNDEF(VTs[i]));
6206           continue;
6207         }
6208         SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
6209         AddToWorklist(NV.getNode());
6210         Opnds.push_back(NV);
6211       }
6212       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
6213     }
6214   }
6215
6216   // Simplify the operands using demanded-bits information.
6217   if (!VT.isVector() &&
6218       SimplifyDemandedBits(SDValue(N, 0)))
6219     return SDValue(N, 0);
6220
6221   return SDValue();
6222 }
6223
6224 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
6225   SDValue Elt = N->getOperand(i);
6226   if (Elt.getOpcode() != ISD::MERGE_VALUES)
6227     return Elt.getNode();
6228   return Elt.getOperand(Elt.getResNo()).getNode();
6229 }
6230
6231 /// CombineConsecutiveLoads - build_pair (load, load) -> load
6232 /// if load locations are consecutive.
6233 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
6234   assert(N->getOpcode() == ISD::BUILD_PAIR);
6235
6236   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
6237   LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
6238   if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
6239       LD1->getAddressSpace() != LD2->getAddressSpace())
6240     return SDValue();
6241   EVT LD1VT = LD1->getValueType(0);
6242
6243   if (ISD::isNON_EXTLoad(LD2) &&
6244       LD2->hasOneUse() &&
6245       // If both are volatile this would reduce the number of volatile loads.
6246       // If one is volatile it might be ok, but play conservative and bail out.
6247       !LD1->isVolatile() &&
6248       !LD2->isVolatile() &&
6249       DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
6250     unsigned Align = LD1->getAlignment();
6251     unsigned NewAlign = TLI.getDataLayout()->
6252       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6253
6254     if (NewAlign <= Align &&
6255         (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
6256       return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
6257                          LD1->getBasePtr(), LD1->getPointerInfo(),
6258                          false, false, false, Align);
6259   }
6260
6261   return SDValue();
6262 }
6263
6264 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
6265   SDValue N0 = N->getOperand(0);
6266   EVT VT = N->getValueType(0);
6267
6268   // If the input is a BUILD_VECTOR with all constant elements, fold this now.
6269   // Only do this before legalize, since afterward the target may be depending
6270   // on the bitconvert.
6271   // First check to see if this is all constant.
6272   if (!LegalTypes &&
6273       N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
6274       VT.isVector()) {
6275     bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
6276
6277     EVT DestEltVT = N->getValueType(0).getVectorElementType();
6278     assert(!DestEltVT.isVector() &&
6279            "Element type of vector ValueType must not be vector!");
6280     if (isSimple)
6281       return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
6282   }
6283
6284   // If the input is a constant, let getNode fold it.
6285   if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
6286     SDValue Res = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
6287     if (Res.getNode() != N) {
6288       if (!LegalOperations ||
6289           TLI.isOperationLegal(Res.getNode()->getOpcode(), VT))
6290         return Res;
6291
6292       // Folding it resulted in an illegal node, and it's too late to
6293       // do that. Clean up the old node and forego the transformation.
6294       // Ideally this won't happen very often, because instcombine
6295       // and the earlier dagcombine runs (where illegal nodes are
6296       // permitted) should have folded most of them already.
6297       deleteAndRecombine(Res.getNode());
6298     }
6299   }
6300
6301   // (conv (conv x, t1), t2) -> (conv x, t2)
6302   if (N0.getOpcode() == ISD::BITCAST)
6303     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
6304                        N0.getOperand(0));
6305
6306   // fold (conv (load x)) -> (load (conv*)x)
6307   // If the resultant load doesn't need a higher alignment than the original!
6308   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
6309       // Do not change the width of a volatile load.
6310       !cast<LoadSDNode>(N0)->isVolatile() &&
6311       // Do not remove the cast if the types differ in endian layout.
6312       TLI.hasBigEndianPartOrdering(N0.getValueType()) ==
6313       TLI.hasBigEndianPartOrdering(VT) &&
6314       (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
6315       TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
6316     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6317     unsigned Align = TLI.getDataLayout()->
6318       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6319     unsigned OrigAlign = LN0->getAlignment();
6320
6321     if (Align <= OrigAlign) {
6322       SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
6323                                  LN0->getBasePtr(), LN0->getPointerInfo(),
6324                                  LN0->isVolatile(), LN0->isNonTemporal(),
6325                                  LN0->isInvariant(), OrigAlign,
6326                                  LN0->getAAInfo());
6327       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
6328       return Load;
6329     }
6330   }
6331
6332   // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
6333   // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
6334   // This often reduces constant pool loads.
6335   if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
6336        (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
6337       N0.getNode()->hasOneUse() && VT.isInteger() &&
6338       !VT.isVector() && !N0.getValueType().isVector()) {
6339     SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
6340                                   N0.getOperand(0));
6341     AddToWorklist(NewConv.getNode());
6342
6343     APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6344     if (N0.getOpcode() == ISD::FNEG)
6345       return DAG.getNode(ISD::XOR, SDLoc(N), VT,
6346                          NewConv, DAG.getConstant(SignBit, VT));
6347     assert(N0.getOpcode() == ISD::FABS);
6348     return DAG.getNode(ISD::AND, SDLoc(N), VT,
6349                        NewConv, DAG.getConstant(~SignBit, VT));
6350   }
6351
6352   // fold (bitconvert (fcopysign cst, x)) ->
6353   //         (or (and (bitconvert x), sign), (and cst, (not sign)))
6354   // Note that we don't handle (copysign x, cst) because this can always be
6355   // folded to an fneg or fabs.
6356   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
6357       isa<ConstantFPSDNode>(N0.getOperand(0)) &&
6358       VT.isInteger() && !VT.isVector()) {
6359     unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
6360     EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
6361     if (isTypeLegal(IntXVT)) {
6362       SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6363                               IntXVT, N0.getOperand(1));
6364       AddToWorklist(X.getNode());
6365
6366       // If X has a different width than the result/lhs, sext it or truncate it.
6367       unsigned VTWidth = VT.getSizeInBits();
6368       if (OrigXWidth < VTWidth) {
6369         X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
6370         AddToWorklist(X.getNode());
6371       } else if (OrigXWidth > VTWidth) {
6372         // To get the sign bit in the right place, we have to shift it right
6373         // before truncating.
6374         X = DAG.getNode(ISD::SRL, SDLoc(X),
6375                         X.getValueType(), X,
6376                         DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
6377         AddToWorklist(X.getNode());
6378         X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
6379         AddToWorklist(X.getNode());
6380       }
6381
6382       APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6383       X = DAG.getNode(ISD::AND, SDLoc(X), VT,
6384                       X, DAG.getConstant(SignBit, VT));
6385       AddToWorklist(X.getNode());
6386
6387       SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6388                                 VT, N0.getOperand(0));
6389       Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
6390                         Cst, DAG.getConstant(~SignBit, VT));
6391       AddToWorklist(Cst.getNode());
6392
6393       return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
6394     }
6395   }
6396
6397   // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
6398   if (N0.getOpcode() == ISD::BUILD_PAIR) {
6399     SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
6400     if (CombineLD.getNode())
6401       return CombineLD;
6402   }
6403
6404   return SDValue();
6405 }
6406
6407 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
6408   EVT VT = N->getValueType(0);
6409   return CombineConsecutiveLoads(N, VT);
6410 }
6411
6412 /// ConstantFoldBITCASTofBUILD_VECTOR - We know that BV is a build_vector
6413 /// node with Constant, ConstantFP or Undef operands.  DstEltVT indicates the
6414 /// destination element value type.
6415 SDValue DAGCombiner::
6416 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
6417   EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
6418
6419   // If this is already the right type, we're done.
6420   if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
6421
6422   unsigned SrcBitSize = SrcEltVT.getSizeInBits();
6423   unsigned DstBitSize = DstEltVT.getSizeInBits();
6424
6425   // If this is a conversion of N elements of one type to N elements of another
6426   // type, convert each element.  This handles FP<->INT cases.
6427   if (SrcBitSize == DstBitSize) {
6428     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6429                               BV->getValueType(0).getVectorNumElements());
6430
6431     // Due to the FP element handling below calling this routine recursively,
6432     // we can end up with a scalar-to-vector node here.
6433     if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
6434       return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6435                          DAG.getNode(ISD::BITCAST, SDLoc(BV),
6436                                      DstEltVT, BV->getOperand(0)));
6437
6438     SmallVector<SDValue, 8> Ops;
6439     for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6440       SDValue Op = BV->getOperand(i);
6441       // If the vector element type is not legal, the BUILD_VECTOR operands
6442       // are promoted and implicitly truncated.  Make that explicit here.
6443       if (Op.getValueType() != SrcEltVT)
6444         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
6445       Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
6446                                 DstEltVT, Op));
6447       AddToWorklist(Ops.back().getNode());
6448     }
6449     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6450   }
6451
6452   // Otherwise, we're growing or shrinking the elements.  To avoid having to
6453   // handle annoying details of growing/shrinking FP values, we convert them to
6454   // int first.
6455   if (SrcEltVT.isFloatingPoint()) {
6456     // Convert the input float vector to a int vector where the elements are the
6457     // same sizes.
6458     assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!");
6459     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
6460     BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
6461     SrcEltVT = IntVT;
6462   }
6463
6464   // Now we know the input is an integer vector.  If the output is a FP type,
6465   // convert to integer first, then to FP of the right size.
6466   if (DstEltVT.isFloatingPoint()) {
6467     assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!");
6468     EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
6469     SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
6470
6471     // Next, convert to FP elements of the same size.
6472     return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
6473   }
6474
6475   // Okay, we know the src/dst types are both integers of differing types.
6476   // Handling growing first.
6477   assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
6478   if (SrcBitSize < DstBitSize) {
6479     unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
6480
6481     SmallVector<SDValue, 8> Ops;
6482     for (unsigned i = 0, e = BV->getNumOperands(); i != e;
6483          i += NumInputsPerOutput) {
6484       bool isLE = TLI.isLittleEndian();
6485       APInt NewBits = APInt(DstBitSize, 0);
6486       bool EltIsUndef = true;
6487       for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
6488         // Shift the previously computed bits over.
6489         NewBits <<= SrcBitSize;
6490         SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
6491         if (Op.getOpcode() == ISD::UNDEF) continue;
6492         EltIsUndef = false;
6493
6494         NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
6495                    zextOrTrunc(SrcBitSize).zext(DstBitSize);
6496       }
6497
6498       if (EltIsUndef)
6499         Ops.push_back(DAG.getUNDEF(DstEltVT));
6500       else
6501         Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
6502     }
6503
6504     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
6505     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6506   }
6507
6508   // Finally, this must be the case where we are shrinking elements: each input
6509   // turns into multiple outputs.
6510   bool isS2V = ISD::isScalarToVector(BV);
6511   unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
6512   EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6513                             NumOutputsPerInput*BV->getNumOperands());
6514   SmallVector<SDValue, 8> Ops;
6515
6516   for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6517     if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
6518       for (unsigned j = 0; j != NumOutputsPerInput; ++j)
6519         Ops.push_back(DAG.getUNDEF(DstEltVT));
6520       continue;
6521     }
6522
6523     APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
6524                   getAPIntValue().zextOrTrunc(SrcBitSize);
6525
6526     for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
6527       APInt ThisVal = OpVal.trunc(DstBitSize);
6528       Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
6529       if (isS2V && i == 0 && j == 0 && ThisVal.zext(SrcBitSize) == OpVal)
6530         // Simply turn this into a SCALAR_TO_VECTOR of the new type.
6531         return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6532                            Ops[0]);
6533       OpVal = OpVal.lshr(DstBitSize);
6534     }
6535
6536     // For big endian targets, swap the order of the pieces of each element.
6537     if (TLI.isBigEndian())
6538       std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
6539   }
6540
6541   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6542 }
6543
6544 SDValue DAGCombiner::visitFADD(SDNode *N) {
6545   SDValue N0 = N->getOperand(0);
6546   SDValue N1 = N->getOperand(1);
6547   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6548   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6549   EVT VT = N->getValueType(0);
6550
6551   // fold vector ops
6552   if (VT.isVector()) {
6553     SDValue FoldedVOp = SimplifyVBinOp(N);
6554     if (FoldedVOp.getNode()) return FoldedVOp;
6555   }
6556
6557   // fold (fadd c1, c2) -> c1 + c2
6558   if (N0CFP && N1CFP)
6559     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N1);
6560   // canonicalize constant to RHS
6561   if (N0CFP && !N1CFP)
6562     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N0);
6563   // fold (fadd A, 0) -> A
6564   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6565       N1CFP->getValueAPF().isZero())
6566     return N0;
6567   // fold (fadd A, (fneg B)) -> (fsub A, B)
6568   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6569     isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
6570     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0,
6571                        GetNegatedExpression(N1, DAG, LegalOperations));
6572   // fold (fadd (fneg A), B) -> (fsub B, A)
6573   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6574     isNegatibleForFree(N0, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
6575     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N1,
6576                        GetNegatedExpression(N0, DAG, LegalOperations));
6577
6578   // If allowed, fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
6579   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6580       N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
6581       isa<ConstantFPSDNode>(N0.getOperand(1)))
6582     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0.getOperand(0),
6583                        DAG.getNode(ISD::FADD, SDLoc(N), VT,
6584                                    N0.getOperand(1), N1));
6585
6586   // No FP constant should be created after legalization as Instruction
6587   // Selection pass has hard time in dealing with FP constant.
6588   //
6589   // We don't need test this condition for transformation like following, as
6590   // the DAG being transformed implies it is legal to take FP constant as
6591   // operand.
6592   //
6593   //  (fadd (fmul c, x), x) -> (fmul c+1, x)
6594   //
6595   bool AllowNewFpConst = (Level < AfterLegalizeDAG);
6596
6597   // If allow, fold (fadd (fneg x), x) -> 0.0
6598   if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
6599       N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
6600     return DAG.getConstantFP(0.0, VT);
6601
6602     // If allow, fold (fadd x, (fneg x)) -> 0.0
6603   if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
6604       N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
6605     return DAG.getConstantFP(0.0, VT);
6606
6607   // In unsafe math mode, we can fold chains of FADD's of the same value
6608   // into multiplications.  This transform is not safe in general because
6609   // we are reducing the number of rounding steps.
6610   if (DAG.getTarget().Options.UnsafeFPMath &&
6611       TLI.isOperationLegalOrCustom(ISD::FMUL, VT) &&
6612       !N0CFP && !N1CFP) {
6613     if (N0.getOpcode() == ISD::FMUL) {
6614       ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6615       ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
6616
6617       // (fadd (fmul c, x), x) -> (fmul x, c+1)
6618       if (CFP00 && !CFP01 && N0.getOperand(1) == N1) {
6619         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6620                                      SDValue(CFP00, 0),
6621                                      DAG.getConstantFP(1.0, VT));
6622         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6623                            N1, NewCFP);
6624       }
6625
6626       // (fadd (fmul x, c), x) -> (fmul x, c+1)
6627       if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
6628         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6629                                      SDValue(CFP01, 0),
6630                                      DAG.getConstantFP(1.0, VT));
6631         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6632                            N1, NewCFP);
6633       }
6634
6635       // (fadd (fmul c, x), (fadd x, x)) -> (fmul x, c+2)
6636       if (CFP00 && !CFP01 && N1.getOpcode() == ISD::FADD &&
6637           N1.getOperand(0) == N1.getOperand(1) &&
6638           N0.getOperand(1) == N1.getOperand(0)) {
6639         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6640                                      SDValue(CFP00, 0),
6641                                      DAG.getConstantFP(2.0, VT));
6642         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6643                            N0.getOperand(1), NewCFP);
6644       }
6645
6646       // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
6647       if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
6648           N1.getOperand(0) == N1.getOperand(1) &&
6649           N0.getOperand(0) == N1.getOperand(0)) {
6650         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6651                                      SDValue(CFP01, 0),
6652                                      DAG.getConstantFP(2.0, VT));
6653         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6654                            N0.getOperand(0), NewCFP);
6655       }
6656     }
6657
6658     if (N1.getOpcode() == ISD::FMUL) {
6659       ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6660       ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
6661
6662       // (fadd x, (fmul c, x)) -> (fmul x, c+1)
6663       if (CFP10 && !CFP11 && N1.getOperand(1) == N0) {
6664         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6665                                      SDValue(CFP10, 0),
6666                                      DAG.getConstantFP(1.0, VT));
6667         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6668                            N0, NewCFP);
6669       }
6670
6671       // (fadd x, (fmul x, c)) -> (fmul x, c+1)
6672       if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
6673         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6674                                      SDValue(CFP11, 0),
6675                                      DAG.getConstantFP(1.0, VT));
6676         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6677                            N0, NewCFP);
6678       }
6679
6680
6681       // (fadd (fadd x, x), (fmul c, x)) -> (fmul x, c+2)
6682       if (CFP10 && !CFP11 && N0.getOpcode() == ISD::FADD &&
6683           N0.getOperand(0) == N0.getOperand(1) &&
6684           N1.getOperand(1) == N0.getOperand(0)) {
6685         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6686                                      SDValue(CFP10, 0),
6687                                      DAG.getConstantFP(2.0, VT));
6688         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6689                            N1.getOperand(1), NewCFP);
6690       }
6691
6692       // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
6693       if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
6694           N0.getOperand(0) == N0.getOperand(1) &&
6695           N1.getOperand(0) == N0.getOperand(0)) {
6696         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6697                                      SDValue(CFP11, 0),
6698                                      DAG.getConstantFP(2.0, VT));
6699         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6700                            N1.getOperand(0), NewCFP);
6701       }
6702     }
6703
6704     if (N0.getOpcode() == ISD::FADD && AllowNewFpConst) {
6705       ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6706       // (fadd (fadd x, x), x) -> (fmul x, 3.0)
6707       if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
6708           (N0.getOperand(0) == N1))
6709         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6710                            N1, DAG.getConstantFP(3.0, VT));
6711     }
6712
6713     if (N1.getOpcode() == ISD::FADD && AllowNewFpConst) {
6714       ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6715       // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
6716       if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
6717           N1.getOperand(0) == N0)
6718         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6719                            N0, DAG.getConstantFP(3.0, VT));
6720     }
6721
6722     // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
6723     if (AllowNewFpConst &&
6724         N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
6725         N0.getOperand(0) == N0.getOperand(1) &&
6726         N1.getOperand(0) == N1.getOperand(1) &&
6727         N0.getOperand(0) == N1.getOperand(0))
6728       return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6729                          N0.getOperand(0),
6730                          DAG.getConstantFP(4.0, VT));
6731   }
6732
6733   // FADD -> FMA combines:
6734   if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
6735        DAG.getTarget().Options.UnsafeFPMath) &&
6736       DAG.getTarget()
6737           .getSubtargetImpl()
6738           ->getTargetLowering()
6739           ->isFMAFasterThanFMulAndFAdd(VT) &&
6740       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6741
6742     // fold (fadd (fmul x, y), z) -> (fma x, y, z)
6743     if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
6744       return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6745                          N0.getOperand(0), N0.getOperand(1), N1);
6746
6747     // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
6748     // Note: Commutes FADD operands.
6749     if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
6750       return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6751                          N1.getOperand(0), N1.getOperand(1), N0);
6752   }
6753
6754   return SDValue();
6755 }
6756
6757 SDValue DAGCombiner::visitFSUB(SDNode *N) {
6758   SDValue N0 = N->getOperand(0);
6759   SDValue N1 = N->getOperand(1);
6760   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6761   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6762   EVT VT = N->getValueType(0);
6763   SDLoc dl(N);
6764
6765   // fold vector ops
6766   if (VT.isVector()) {
6767     SDValue FoldedVOp = SimplifyVBinOp(N);
6768     if (FoldedVOp.getNode()) return FoldedVOp;
6769   }
6770
6771   // fold (fsub c1, c2) -> c1-c2
6772   if (N0CFP && N1CFP)
6773     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0, N1);
6774   // fold (fsub A, 0) -> A
6775   if (DAG.getTarget().Options.UnsafeFPMath &&
6776       N1CFP && N1CFP->getValueAPF().isZero())
6777     return N0;
6778   // fold (fsub 0, B) -> -B
6779   if (DAG.getTarget().Options.UnsafeFPMath &&
6780       N0CFP && N0CFP->getValueAPF().isZero()) {
6781     if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
6782       return GetNegatedExpression(N1, DAG, LegalOperations);
6783     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6784       return DAG.getNode(ISD::FNEG, dl, VT, N1);
6785   }
6786   // fold (fsub A, (fneg B)) -> (fadd A, B)
6787   if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
6788     return DAG.getNode(ISD::FADD, dl, VT, N0,
6789                        GetNegatedExpression(N1, DAG, LegalOperations));
6790
6791   // If 'unsafe math' is enabled, fold
6792   //    (fsub x, x) -> 0.0 &
6793   //    (fsub x, (fadd x, y)) -> (fneg y) &
6794   //    (fsub x, (fadd y, x)) -> (fneg y)
6795   if (DAG.getTarget().Options.UnsafeFPMath) {
6796     if (N0 == N1)
6797       return DAG.getConstantFP(0.0f, VT);
6798
6799     if (N1.getOpcode() == ISD::FADD) {
6800       SDValue N10 = N1->getOperand(0);
6801       SDValue N11 = N1->getOperand(1);
6802
6803       if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI,
6804                                           &DAG.getTarget().Options))
6805         return GetNegatedExpression(N11, DAG, LegalOperations);
6806
6807       if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI,
6808                                           &DAG.getTarget().Options))
6809         return GetNegatedExpression(N10, DAG, LegalOperations);
6810     }
6811   }
6812
6813   // FSUB -> FMA combines:
6814   if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
6815        DAG.getTarget().Options.UnsafeFPMath) &&
6816       DAG.getTarget()
6817           .getSubtargetImpl()
6818           ->getTargetLowering()
6819           ->isFMAFasterThanFMulAndFAdd(VT) &&
6820       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6821
6822     // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
6823     if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
6824       return DAG.getNode(ISD::FMA, dl, VT,
6825                          N0.getOperand(0), N0.getOperand(1),
6826                          DAG.getNode(ISD::FNEG, dl, VT, N1));
6827
6828     // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
6829     // Note: Commutes FSUB operands.
6830     if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
6831       return DAG.getNode(ISD::FMA, dl, VT,
6832                          DAG.getNode(ISD::FNEG, dl, VT,
6833                          N1.getOperand(0)),
6834                          N1.getOperand(1), N0);
6835
6836     // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
6837     if (N0.getOpcode() == ISD::FNEG &&
6838         N0.getOperand(0).getOpcode() == ISD::FMUL &&
6839         N0->hasOneUse() && N0.getOperand(0).hasOneUse()) {
6840       SDValue N00 = N0.getOperand(0).getOperand(0);
6841       SDValue N01 = N0.getOperand(0).getOperand(1);
6842       return DAG.getNode(ISD::FMA, dl, VT,
6843                          DAG.getNode(ISD::FNEG, dl, VT, N00), N01,
6844                          DAG.getNode(ISD::FNEG, dl, VT, N1));
6845     }
6846   }
6847
6848   return SDValue();
6849 }
6850
6851 SDValue DAGCombiner::visitFMUL(SDNode *N) {
6852   SDValue N0 = N->getOperand(0);
6853   SDValue N1 = N->getOperand(1);
6854   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
6855   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
6856   EVT VT = N->getValueType(0);
6857   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6858
6859   // fold vector ops
6860   if (VT.isVector()) {
6861     SDValue FoldedVOp = SimplifyVBinOp(N);
6862     if (FoldedVOp.getNode()) return FoldedVOp;
6863   }
6864
6865   // fold (fmul c1, c2) -> c1*c2
6866   if (N0CFP && N1CFP)
6867     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, N1);
6868   // canonicalize constant to RHS
6869   if (N0CFP && !N1CFP)
6870     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, N0);
6871   // fold (fmul A, 0) -> 0
6872   if (DAG.getTarget().Options.UnsafeFPMath &&
6873       N1CFP && N1CFP->getValueAPF().isZero())
6874     return N1;
6875   // fold (fmul A, 1.0) -> A
6876   if (N1CFP && N1CFP->isExactlyValue(1.0))
6877     return N0;
6878
6879   // fold (fmul X, 2.0) -> (fadd X, X)
6880   if (N1CFP && N1CFP->isExactlyValue(+2.0))
6881     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N0);
6882   // fold (fmul X, -1.0) -> (fneg X)
6883   if (N1CFP && N1CFP->isExactlyValue(-1.0))
6884     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6885       return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
6886
6887   // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
6888   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
6889                                        &DAG.getTarget().Options)) {
6890     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
6891                                          &DAG.getTarget().Options)) {
6892       // Both can be negated for free, check to see if at least one is cheaper
6893       // negated.
6894       if (LHSNeg == 2 || RHSNeg == 2)
6895         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6896                            GetNegatedExpression(N0, DAG, LegalOperations),
6897                            GetNegatedExpression(N1, DAG, LegalOperations));
6898     }
6899   }
6900
6901   // If allowed, fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
6902   if (DAG.getTarget().Options.UnsafeFPMath &&
6903       N1CFP && N0.getOpcode() == ISD::FMUL &&
6904       N0.getNode()->hasOneUse() && isConstOrConstSplatFP(N0.getOperand(1))) {
6905     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
6906                        DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6907                                    N0.getOperand(1), N1));
6908   }
6909
6910   return SDValue();
6911 }
6912
6913 SDValue DAGCombiner::visitFMA(SDNode *N) {
6914   SDValue N0 = N->getOperand(0);
6915   SDValue N1 = N->getOperand(1);
6916   SDValue N2 = N->getOperand(2);
6917   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6918   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6919   EVT VT = N->getValueType(0);
6920   SDLoc dl(N);
6921
6922
6923   // Constant fold FMA.
6924   if (isa<ConstantFPSDNode>(N0) &&
6925       isa<ConstantFPSDNode>(N1) &&
6926       isa<ConstantFPSDNode>(N2)) {
6927     return DAG.getNode(ISD::FMA, dl, VT, N0, N1, N2);
6928   }
6929
6930   if (DAG.getTarget().Options.UnsafeFPMath) {
6931     if (N0CFP && N0CFP->isZero())
6932       return N2;
6933     if (N1CFP && N1CFP->isZero())
6934       return N2;
6935   }
6936   if (N0CFP && N0CFP->isExactlyValue(1.0))
6937     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
6938   if (N1CFP && N1CFP->isExactlyValue(1.0))
6939     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
6940
6941   // Canonicalize (fma c, x, y) -> (fma x, c, y)
6942   if (N0CFP && !N1CFP)
6943     return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
6944
6945   // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
6946   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6947       N2.getOpcode() == ISD::FMUL &&
6948       N0 == N2.getOperand(0) &&
6949       N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
6950     return DAG.getNode(ISD::FMUL, dl, VT, N0,
6951                        DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
6952   }
6953
6954
6955   // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
6956   if (DAG.getTarget().Options.UnsafeFPMath &&
6957       N0.getOpcode() == ISD::FMUL && N1CFP &&
6958       N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
6959     return DAG.getNode(ISD::FMA, dl, VT,
6960                        N0.getOperand(0),
6961                        DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
6962                        N2);
6963   }
6964
6965   // (fma x, 1, y) -> (fadd x, y)
6966   // (fma x, -1, y) -> (fadd (fneg x), y)
6967   if (N1CFP) {
6968     if (N1CFP->isExactlyValue(1.0))
6969       return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
6970
6971     if (N1CFP->isExactlyValue(-1.0) &&
6972         (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
6973       SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
6974       AddToWorklist(RHSNeg.getNode());
6975       return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
6976     }
6977   }
6978
6979   // (fma x, c, x) -> (fmul x, (c+1))
6980   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP && N0 == N2)
6981     return DAG.getNode(ISD::FMUL, dl, VT, N0,
6982                        DAG.getNode(ISD::FADD, dl, VT,
6983                                    N1, DAG.getConstantFP(1.0, VT)));
6984
6985   // (fma x, c, (fneg x)) -> (fmul x, (c-1))
6986   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6987       N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
6988     return DAG.getNode(ISD::FMUL, dl, VT, N0,
6989                        DAG.getNode(ISD::FADD, dl, VT,
6990                                    N1, DAG.getConstantFP(-1.0, VT)));
6991
6992
6993   return SDValue();
6994 }
6995
6996 SDValue DAGCombiner::visitFDIV(SDNode *N) {
6997   SDValue N0 = N->getOperand(0);
6998   SDValue N1 = N->getOperand(1);
6999   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7000   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7001   EVT VT = N->getValueType(0);
7002   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7003
7004   // fold vector ops
7005   if (VT.isVector()) {
7006     SDValue FoldedVOp = SimplifyVBinOp(N);
7007     if (FoldedVOp.getNode()) return FoldedVOp;
7008   }
7009
7010   // fold (fdiv c1, c2) -> c1/c2
7011   if (N0CFP && N1CFP)
7012     return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
7013
7014   // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
7015   if (N1CFP && DAG.getTarget().Options.UnsafeFPMath) {
7016     // Compute the reciprocal 1.0 / c2.
7017     APFloat N1APF = N1CFP->getValueAPF();
7018     APFloat Recip(N1APF.getSemantics(), 1); // 1.0
7019     APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
7020     // Only do the transform if the reciprocal is a legal fp immediate that
7021     // isn't too nasty (eg NaN, denormal, ...).
7022     if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
7023         (!LegalOperations ||
7024          // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
7025          // backend)... we should handle this gracefully after Legalize.
7026          // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
7027          TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
7028          TLI.isFPImmLegal(Recip, VT)))
7029       return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0,
7030                          DAG.getConstantFP(Recip, VT));
7031   }
7032
7033   // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
7034   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
7035                                        &DAG.getTarget().Options)) {
7036     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
7037                                          &DAG.getTarget().Options)) {
7038       // Both can be negated for free, check to see if at least one is cheaper
7039       // negated.
7040       if (LHSNeg == 2 || RHSNeg == 2)
7041         return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
7042                            GetNegatedExpression(N0, DAG, LegalOperations),
7043                            GetNegatedExpression(N1, DAG, LegalOperations));
7044     }
7045   }
7046
7047   return SDValue();
7048 }
7049
7050 SDValue DAGCombiner::visitFREM(SDNode *N) {
7051   SDValue N0 = N->getOperand(0);
7052   SDValue N1 = N->getOperand(1);
7053   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7054   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7055   EVT VT = N->getValueType(0);
7056
7057   // fold (frem c1, c2) -> fmod(c1,c2)
7058   if (N0CFP && N1CFP)
7059     return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
7060
7061   return SDValue();
7062 }
7063
7064 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
7065   SDValue N0 = N->getOperand(0);
7066   SDValue N1 = N->getOperand(1);
7067   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7068   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7069   EVT VT = N->getValueType(0);
7070
7071   if (N0CFP && N1CFP)  // Constant fold
7072     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
7073
7074   if (N1CFP) {
7075     const APFloat& V = N1CFP->getValueAPF();
7076     // copysign(x, c1) -> fabs(x)       iff ispos(c1)
7077     // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
7078     if (!V.isNegative()) {
7079       if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
7080         return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7081     } else {
7082       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
7083         return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
7084                            DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
7085     }
7086   }
7087
7088   // copysign(fabs(x), y) -> copysign(x, y)
7089   // copysign(fneg(x), y) -> copysign(x, y)
7090   // copysign(copysign(x,z), y) -> copysign(x, y)
7091   if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
7092       N0.getOpcode() == ISD::FCOPYSIGN)
7093     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7094                        N0.getOperand(0), N1);
7095
7096   // copysign(x, abs(y)) -> abs(x)
7097   if (N1.getOpcode() == ISD::FABS)
7098     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7099
7100   // copysign(x, copysign(y,z)) -> copysign(x, z)
7101   if (N1.getOpcode() == ISD::FCOPYSIGN)
7102     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7103                        N0, N1.getOperand(1));
7104
7105   // copysign(x, fp_extend(y)) -> copysign(x, y)
7106   // copysign(x, fp_round(y)) -> copysign(x, y)
7107   if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
7108     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7109                        N0, N1.getOperand(0));
7110
7111   return SDValue();
7112 }
7113
7114 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
7115   SDValue N0 = N->getOperand(0);
7116   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
7117   EVT VT = N->getValueType(0);
7118   EVT OpVT = N0.getValueType();
7119
7120   // fold (sint_to_fp c1) -> c1fp
7121   if (N0C &&
7122       // ...but only if the target supports immediate floating-point values
7123       (!LegalOperations ||
7124        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
7125     return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
7126
7127   // If the input is a legal type, and SINT_TO_FP is not legal on this target,
7128   // but UINT_TO_FP is legal on this target, try to convert.
7129   if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
7130       TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
7131     // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
7132     if (DAG.SignBitIsZero(N0))
7133       return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
7134   }
7135
7136   // The next optimizations are desirable only if SELECT_CC can be lowered.
7137   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
7138     // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
7139     if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
7140         !VT.isVector() &&
7141         (!LegalOperations ||
7142          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7143       SDValue Ops[] =
7144         { N0.getOperand(0), N0.getOperand(1),
7145           DAG.getConstantFP(-1.0, VT) , DAG.getConstantFP(0.0, VT),
7146           N0.getOperand(2) };
7147       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7148     }
7149
7150     // fold (sint_to_fp (zext (setcc x, y, cc))) ->
7151     //      (select_cc x, y, 1.0, 0.0,, cc)
7152     if (N0.getOpcode() == ISD::ZERO_EXTEND &&
7153         N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
7154         (!LegalOperations ||
7155          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7156       SDValue Ops[] =
7157         { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
7158           DAG.getConstantFP(1.0, VT) , DAG.getConstantFP(0.0, VT),
7159           N0.getOperand(0).getOperand(2) };
7160       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7161     }
7162   }
7163
7164   return SDValue();
7165 }
7166
7167 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
7168   SDValue N0 = N->getOperand(0);
7169   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
7170   EVT VT = N->getValueType(0);
7171   EVT OpVT = N0.getValueType();
7172
7173   // fold (uint_to_fp c1) -> c1fp
7174   if (N0C &&
7175       // ...but only if the target supports immediate floating-point values
7176       (!LegalOperations ||
7177        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
7178     return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
7179
7180   // If the input is a legal type, and UINT_TO_FP is not legal on this target,
7181   // but SINT_TO_FP is legal on this target, try to convert.
7182   if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
7183       TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
7184     // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
7185     if (DAG.SignBitIsZero(N0))
7186       return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
7187   }
7188
7189   // The next optimizations are desirable only if SELECT_CC can be lowered.
7190   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
7191     // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
7192
7193     if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
7194         (!LegalOperations ||
7195          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7196       SDValue Ops[] =
7197         { N0.getOperand(0), N0.getOperand(1),
7198           DAG.getConstantFP(1.0, VT),  DAG.getConstantFP(0.0, VT),
7199           N0.getOperand(2) };
7200       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7201     }
7202   }
7203
7204   return SDValue();
7205 }
7206
7207 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
7208   SDValue N0 = N->getOperand(0);
7209   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7210   EVT VT = N->getValueType(0);
7211
7212   // fold (fp_to_sint c1fp) -> c1
7213   if (N0CFP)
7214     return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
7215
7216   return SDValue();
7217 }
7218
7219 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
7220   SDValue N0 = N->getOperand(0);
7221   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7222   EVT VT = N->getValueType(0);
7223
7224   // fold (fp_to_uint c1fp) -> c1
7225   if (N0CFP)
7226     return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
7227
7228   return SDValue();
7229 }
7230
7231 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
7232   SDValue N0 = N->getOperand(0);
7233   SDValue N1 = N->getOperand(1);
7234   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7235   EVT VT = N->getValueType(0);
7236
7237   // fold (fp_round c1fp) -> c1fp
7238   if (N0CFP)
7239     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
7240
7241   // fold (fp_round (fp_extend x)) -> x
7242   if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
7243     return N0.getOperand(0);
7244
7245   // fold (fp_round (fp_round x)) -> (fp_round x)
7246   if (N0.getOpcode() == ISD::FP_ROUND) {
7247     // This is a value preserving truncation if both round's are.
7248     bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
7249                    N0.getNode()->getConstantOperandVal(1) == 1;
7250     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0.getOperand(0),
7251                        DAG.getIntPtrConstant(IsTrunc));
7252   }
7253
7254   // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
7255   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
7256     SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
7257                               N0.getOperand(0), N1);
7258     AddToWorklist(Tmp.getNode());
7259     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7260                        Tmp, N0.getOperand(1));
7261   }
7262
7263   return SDValue();
7264 }
7265
7266 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
7267   SDValue N0 = N->getOperand(0);
7268   EVT VT = N->getValueType(0);
7269   EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
7270   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7271
7272   // fold (fp_round_inreg c1fp) -> c1fp
7273   if (N0CFP && isTypeLegal(EVT)) {
7274     SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
7275     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, Round);
7276   }
7277
7278   return SDValue();
7279 }
7280
7281 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
7282   SDValue N0 = N->getOperand(0);
7283   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7284   EVT VT = N->getValueType(0);
7285
7286   // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
7287   if (N->hasOneUse() &&
7288       N->use_begin()->getOpcode() == ISD::FP_ROUND)
7289     return SDValue();
7290
7291   // fold (fp_extend c1fp) -> c1fp
7292   if (N0CFP)
7293     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
7294
7295   // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
7296   // value of X.
7297   if (N0.getOpcode() == ISD::FP_ROUND
7298       && N0.getNode()->getConstantOperandVal(1) == 1) {
7299     SDValue In = N0.getOperand(0);
7300     if (In.getValueType() == VT) return In;
7301     if (VT.bitsLT(In.getValueType()))
7302       return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
7303                          In, N0.getOperand(1));
7304     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
7305   }
7306
7307   // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
7308   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7309        TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType())) {
7310     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7311     SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
7312                                      LN0->getChain(),
7313                                      LN0->getBasePtr(), N0.getValueType(),
7314                                      LN0->getMemOperand());
7315     CombineTo(N, ExtLoad);
7316     CombineTo(N0.getNode(),
7317               DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
7318                           N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
7319               ExtLoad.getValue(1));
7320     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7321   }
7322
7323   return SDValue();
7324 }
7325
7326 SDValue DAGCombiner::visitFNEG(SDNode *N) {
7327   SDValue N0 = N->getOperand(0);
7328   EVT VT = N->getValueType(0);
7329
7330   // Constant fold FNEG.
7331   if (isa<ConstantFPSDNode>(N0))
7332     return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N->getOperand(0));
7333
7334   if (VT.isVector()) {
7335     SDValue FoldedVOp = SimplifyVUnaryOp(N);
7336     if (FoldedVOp.getNode()) return FoldedVOp;
7337   }
7338
7339   if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
7340                          &DAG.getTarget().Options))
7341     return GetNegatedExpression(N0, DAG, LegalOperations);
7342
7343   // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading
7344   // constant pool values.
7345   if (!TLI.isFNegFree(VT) && N0.getOpcode() == ISD::BITCAST &&
7346       N0.getNode()->hasOneUse()) {
7347     SDValue Int = N0.getOperand(0);
7348     EVT IntVT = Int.getValueType();
7349     if (IntVT.isInteger() && !IntVT.isVector()) {
7350       APInt SignMask;
7351       if (N0.getValueType().isVector()) {
7352         // For a vector, get a mask such as 0x80... per scalar element
7353         // and splat it.
7354         SignMask = APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
7355         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
7356       } else {
7357         // For a scalar, just generate 0x80...
7358         SignMask = APInt::getSignBit(IntVT.getSizeInBits());
7359       }
7360       Int = DAG.getNode(ISD::XOR, SDLoc(N0), IntVT, Int,
7361                         DAG.getConstant(SignMask, IntVT));
7362       AddToWorklist(Int.getNode());
7363       return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Int);
7364     }
7365   }
7366
7367   // (fneg (fmul c, x)) -> (fmul -c, x)
7368   if (N0.getOpcode() == ISD::FMUL) {
7369     ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
7370     if (CFP1) {
7371       APFloat CVal = CFP1->getValueAPF();
7372       CVal.changeSign();
7373       if (Level >= AfterLegalizeDAG &&
7374           (TLI.isFPImmLegal(CVal, N->getValueType(0)) ||
7375            TLI.isOperationLegal(ISD::ConstantFP, N->getValueType(0))))
7376         return DAG.getNode(
7377             ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
7378             DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0.getOperand(1)));
7379     }
7380   }
7381
7382   return SDValue();
7383 }
7384
7385 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
7386   SDValue N0 = N->getOperand(0);
7387   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7388   EVT VT = N->getValueType(0);
7389
7390   // fold (fceil c1) -> fceil(c1)
7391   if (N0CFP)
7392     return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
7393
7394   return SDValue();
7395 }
7396
7397 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
7398   SDValue N0 = N->getOperand(0);
7399   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7400   EVT VT = N->getValueType(0);
7401
7402   // fold (ftrunc c1) -> ftrunc(c1)
7403   if (N0CFP)
7404     return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
7405
7406   return SDValue();
7407 }
7408
7409 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
7410   SDValue N0 = N->getOperand(0);
7411   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7412   EVT VT = N->getValueType(0);
7413
7414   // fold (ffloor c1) -> ffloor(c1)
7415   if (N0CFP)
7416     return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
7417
7418   return SDValue();
7419 }
7420
7421 SDValue DAGCombiner::visitFABS(SDNode *N) {
7422   SDValue N0 = N->getOperand(0);
7423   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7424   EVT VT = N->getValueType(0);
7425
7426   if (VT.isVector()) {
7427     SDValue FoldedVOp = SimplifyVUnaryOp(N);
7428     if (FoldedVOp.getNode()) return FoldedVOp;
7429   }
7430
7431   // fold (fabs c1) -> fabs(c1)
7432   if (N0CFP)
7433     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7434   // fold (fabs (fabs x)) -> (fabs x)
7435   if (N0.getOpcode() == ISD::FABS)
7436     return N->getOperand(0);
7437   // fold (fabs (fneg x)) -> (fabs x)
7438   // fold (fabs (fcopysign x, y)) -> (fabs x)
7439   if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
7440     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
7441
7442   // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading
7443   // constant pool values.
7444   if (!TLI.isFAbsFree(VT) &&
7445       N0.getOpcode() == ISD::BITCAST &&
7446       N0.getNode()->hasOneUse()) {
7447     SDValue Int = N0.getOperand(0);
7448     EVT IntVT = Int.getValueType();
7449     if (IntVT.isInteger() && !IntVT.isVector()) {
7450       APInt SignMask;
7451       if (N0.getValueType().isVector()) {
7452         // For a vector, get a mask such as 0x7f... per scalar element
7453         // and splat it.
7454         SignMask = ~APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
7455         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
7456       } else {
7457         // For a scalar, just generate 0x7f...
7458         SignMask = ~APInt::getSignBit(IntVT.getSizeInBits());
7459       }
7460       Int = DAG.getNode(ISD::AND, SDLoc(N0), IntVT, Int,
7461                         DAG.getConstant(SignMask, IntVT));
7462       AddToWorklist(Int.getNode());
7463       return DAG.getNode(ISD::BITCAST, SDLoc(N), N->getValueType(0), Int);
7464     }
7465   }
7466
7467   return SDValue();
7468 }
7469
7470 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
7471   SDValue Chain = N->getOperand(0);
7472   SDValue N1 = N->getOperand(1);
7473   SDValue N2 = N->getOperand(2);
7474
7475   // If N is a constant we could fold this into a fallthrough or unconditional
7476   // branch. However that doesn't happen very often in normal code, because
7477   // Instcombine/SimplifyCFG should have handled the available opportunities.
7478   // If we did this folding here, it would be necessary to update the
7479   // MachineBasicBlock CFG, which is awkward.
7480
7481   // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
7482   // on the target.
7483   if (N1.getOpcode() == ISD::SETCC &&
7484       TLI.isOperationLegalOrCustom(ISD::BR_CC,
7485                                    N1.getOperand(0).getValueType())) {
7486     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7487                        Chain, N1.getOperand(2),
7488                        N1.getOperand(0), N1.getOperand(1), N2);
7489   }
7490
7491   if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
7492       ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
7493        (N1.getOperand(0).hasOneUse() &&
7494         N1.getOperand(0).getOpcode() == ISD::SRL))) {
7495     SDNode *Trunc = nullptr;
7496     if (N1.getOpcode() == ISD::TRUNCATE) {
7497       // Look pass the truncate.
7498       Trunc = N1.getNode();
7499       N1 = N1.getOperand(0);
7500     }
7501
7502     // Match this pattern so that we can generate simpler code:
7503     //
7504     //   %a = ...
7505     //   %b = and i32 %a, 2
7506     //   %c = srl i32 %b, 1
7507     //   brcond i32 %c ...
7508     //
7509     // into
7510     //
7511     //   %a = ...
7512     //   %b = and i32 %a, 2
7513     //   %c = setcc eq %b, 0
7514     //   brcond %c ...
7515     //
7516     // This applies only when the AND constant value has one bit set and the
7517     // SRL constant is equal to the log2 of the AND constant. The back-end is
7518     // smart enough to convert the result into a TEST/JMP sequence.
7519     SDValue Op0 = N1.getOperand(0);
7520     SDValue Op1 = N1.getOperand(1);
7521
7522     if (Op0.getOpcode() == ISD::AND &&
7523         Op1.getOpcode() == ISD::Constant) {
7524       SDValue AndOp1 = Op0.getOperand(1);
7525
7526       if (AndOp1.getOpcode() == ISD::Constant) {
7527         const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
7528
7529         if (AndConst.isPowerOf2() &&
7530             cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
7531           SDValue SetCC =
7532             DAG.getSetCC(SDLoc(N),
7533                          getSetCCResultType(Op0.getValueType()),
7534                          Op0, DAG.getConstant(0, Op0.getValueType()),
7535                          ISD::SETNE);
7536
7537           SDValue NewBRCond = DAG.getNode(ISD::BRCOND, SDLoc(N),
7538                                           MVT::Other, Chain, SetCC, N2);
7539           // Don't add the new BRCond into the worklist or else SimplifySelectCC
7540           // will convert it back to (X & C1) >> C2.
7541           CombineTo(N, NewBRCond, false);
7542           // Truncate is dead.
7543           if (Trunc)
7544             deleteAndRecombine(Trunc);
7545           // Replace the uses of SRL with SETCC
7546           WorklistRemover DeadNodes(*this);
7547           DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
7548           deleteAndRecombine(N1.getNode());
7549           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7550         }
7551       }
7552     }
7553
7554     if (Trunc)
7555       // Restore N1 if the above transformation doesn't match.
7556       N1 = N->getOperand(1);
7557   }
7558
7559   // Transform br(xor(x, y)) -> br(x != y)
7560   // Transform br(xor(xor(x,y), 1)) -> br (x == y)
7561   if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
7562     SDNode *TheXor = N1.getNode();
7563     SDValue Op0 = TheXor->getOperand(0);
7564     SDValue Op1 = TheXor->getOperand(1);
7565     if (Op0.getOpcode() == Op1.getOpcode()) {
7566       // Avoid missing important xor optimizations.
7567       SDValue Tmp = visitXOR(TheXor);
7568       if (Tmp.getNode()) {
7569         if (Tmp.getNode() != TheXor) {
7570           DEBUG(dbgs() << "\nReplacing.8 ";
7571                 TheXor->dump(&DAG);
7572                 dbgs() << "\nWith: ";
7573                 Tmp.getNode()->dump(&DAG);
7574                 dbgs() << '\n');
7575           WorklistRemover DeadNodes(*this);
7576           DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
7577           deleteAndRecombine(TheXor);
7578           return DAG.getNode(ISD::BRCOND, SDLoc(N),
7579                              MVT::Other, Chain, Tmp, N2);
7580         }
7581
7582         // visitXOR has changed XOR's operands or replaced the XOR completely,
7583         // bail out.
7584         return SDValue(N, 0);
7585       }
7586     }
7587
7588     if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
7589       bool Equal = false;
7590       if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
7591         if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
7592             Op0.getOpcode() == ISD::XOR) {
7593           TheXor = Op0.getNode();
7594           Equal = true;
7595         }
7596
7597       EVT SetCCVT = N1.getValueType();
7598       if (LegalTypes)
7599         SetCCVT = getSetCCResultType(SetCCVT);
7600       SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
7601                                    SetCCVT,
7602                                    Op0, Op1,
7603                                    Equal ? ISD::SETEQ : ISD::SETNE);
7604       // Replace the uses of XOR with SETCC
7605       WorklistRemover DeadNodes(*this);
7606       DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
7607       deleteAndRecombine(N1.getNode());
7608       return DAG.getNode(ISD::BRCOND, SDLoc(N),
7609                          MVT::Other, Chain, SetCC, N2);
7610     }
7611   }
7612
7613   return SDValue();
7614 }
7615
7616 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
7617 //
7618 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
7619   CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
7620   SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
7621
7622   // If N is a constant we could fold this into a fallthrough or unconditional
7623   // branch. However that doesn't happen very often in normal code, because
7624   // Instcombine/SimplifyCFG should have handled the available opportunities.
7625   // If we did this folding here, it would be necessary to update the
7626   // MachineBasicBlock CFG, which is awkward.
7627
7628   // Use SimplifySetCC to simplify SETCC's.
7629   SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
7630                                CondLHS, CondRHS, CC->get(), SDLoc(N),
7631                                false);
7632   if (Simp.getNode()) AddToWorklist(Simp.getNode());
7633
7634   // fold to a simpler setcc
7635   if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
7636     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7637                        N->getOperand(0), Simp.getOperand(2),
7638                        Simp.getOperand(0), Simp.getOperand(1),
7639                        N->getOperand(4));
7640
7641   return SDValue();
7642 }
7643
7644 /// canFoldInAddressingMode - Return true if 'Use' is a load or a store that
7645 /// uses N as its base pointer and that N may be folded in the load / store
7646 /// addressing mode.
7647 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
7648                                     SelectionDAG &DAG,
7649                                     const TargetLowering &TLI) {
7650   EVT VT;
7651   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(Use)) {
7652     if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
7653       return false;
7654     VT = Use->getValueType(0);
7655   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(Use)) {
7656     if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
7657       return false;
7658     VT = ST->getValue().getValueType();
7659   } else
7660     return false;
7661
7662   TargetLowering::AddrMode AM;
7663   if (N->getOpcode() == ISD::ADD) {
7664     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7665     if (Offset)
7666       // [reg +/- imm]
7667       AM.BaseOffs = Offset->getSExtValue();
7668     else
7669       // [reg +/- reg]
7670       AM.Scale = 1;
7671   } else if (N->getOpcode() == ISD::SUB) {
7672     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7673     if (Offset)
7674       // [reg +/- imm]
7675       AM.BaseOffs = -Offset->getSExtValue();
7676     else
7677       // [reg +/- reg]
7678       AM.Scale = 1;
7679   } else
7680     return false;
7681
7682   return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
7683 }
7684
7685 /// CombineToPreIndexedLoadStore - Try turning a load / store into a
7686 /// pre-indexed load / store when the base pointer is an add or subtract
7687 /// and it has other uses besides the load / store. After the
7688 /// transformation, the new indexed load / store has effectively folded
7689 /// the add / subtract in and all of its other uses are redirected to the
7690 /// new load / store.
7691 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
7692   if (Level < AfterLegalizeDAG)
7693     return false;
7694
7695   bool isLoad = true;
7696   SDValue Ptr;
7697   EVT VT;
7698   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
7699     if (LD->isIndexed())
7700       return false;
7701     VT = LD->getMemoryVT();
7702     if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
7703         !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
7704       return false;
7705     Ptr = LD->getBasePtr();
7706   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
7707     if (ST->isIndexed())
7708       return false;
7709     VT = ST->getMemoryVT();
7710     if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
7711         !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
7712       return false;
7713     Ptr = ST->getBasePtr();
7714     isLoad = false;
7715   } else {
7716     return false;
7717   }
7718
7719   // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
7720   // out.  There is no reason to make this a preinc/predec.
7721   if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
7722       Ptr.getNode()->hasOneUse())
7723     return false;
7724
7725   // Ask the target to do addressing mode selection.
7726   SDValue BasePtr;
7727   SDValue Offset;
7728   ISD::MemIndexedMode AM = ISD::UNINDEXED;
7729   if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
7730     return false;
7731
7732   // Backends without true r+i pre-indexed forms may need to pass a
7733   // constant base with a variable offset so that constant coercion
7734   // will work with the patterns in canonical form.
7735   bool Swapped = false;
7736   if (isa<ConstantSDNode>(BasePtr)) {
7737     std::swap(BasePtr, Offset);
7738     Swapped = true;
7739   }
7740
7741   // Don't create a indexed load / store with zero offset.
7742   if (isa<ConstantSDNode>(Offset) &&
7743       cast<ConstantSDNode>(Offset)->isNullValue())
7744     return false;
7745
7746   // Try turning it into a pre-indexed load / store except when:
7747   // 1) The new base ptr is a frame index.
7748   // 2) If N is a store and the new base ptr is either the same as or is a
7749   //    predecessor of the value being stored.
7750   // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
7751   //    that would create a cycle.
7752   // 4) All uses are load / store ops that use it as old base ptr.
7753
7754   // Check #1.  Preinc'ing a frame index would require copying the stack pointer
7755   // (plus the implicit offset) to a register to preinc anyway.
7756   if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7757     return false;
7758
7759   // Check #2.
7760   if (!isLoad) {
7761     SDValue Val = cast<StoreSDNode>(N)->getValue();
7762     if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
7763       return false;
7764   }
7765
7766   // If the offset is a constant, there may be other adds of constants that
7767   // can be folded with this one. We should do this to avoid having to keep
7768   // a copy of the original base pointer.
7769   SmallVector<SDNode *, 16> OtherUses;
7770   if (isa<ConstantSDNode>(Offset))
7771     for (SDNode *Use : BasePtr.getNode()->uses()) {
7772       if (Use == Ptr.getNode())
7773         continue;
7774
7775       if (Use->isPredecessorOf(N))
7776         continue;
7777
7778       if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) {
7779         OtherUses.clear();
7780         break;
7781       }
7782
7783       SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1);
7784       if (Op1.getNode() == BasePtr.getNode())
7785         std::swap(Op0, Op1);
7786       assert(Op0.getNode() == BasePtr.getNode() &&
7787              "Use of ADD/SUB but not an operand");
7788
7789       if (!isa<ConstantSDNode>(Op1)) {
7790         OtherUses.clear();
7791         break;
7792       }
7793
7794       // FIXME: In some cases, we can be smarter about this.
7795       if (Op1.getValueType() != Offset.getValueType()) {
7796         OtherUses.clear();
7797         break;
7798       }
7799
7800       OtherUses.push_back(Use);
7801     }
7802
7803   if (Swapped)
7804     std::swap(BasePtr, Offset);
7805
7806   // Now check for #3 and #4.
7807   bool RealUse = false;
7808
7809   // Caches for hasPredecessorHelper
7810   SmallPtrSet<const SDNode *, 32> Visited;
7811   SmallVector<const SDNode *, 16> Worklist;
7812
7813   for (SDNode *Use : Ptr.getNode()->uses()) {
7814     if (Use == N)
7815       continue;
7816     if (N->hasPredecessorHelper(Use, Visited, Worklist))
7817       return false;
7818
7819     // If Ptr may be folded in addressing mode of other use, then it's
7820     // not profitable to do this transformation.
7821     if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
7822       RealUse = true;
7823   }
7824
7825   if (!RealUse)
7826     return false;
7827
7828   SDValue Result;
7829   if (isLoad)
7830     Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
7831                                 BasePtr, Offset, AM);
7832   else
7833     Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
7834                                  BasePtr, Offset, AM);
7835   ++PreIndexedNodes;
7836   ++NodesCombined;
7837   DEBUG(dbgs() << "\nReplacing.4 ";
7838         N->dump(&DAG);
7839         dbgs() << "\nWith: ";
7840         Result.getNode()->dump(&DAG);
7841         dbgs() << '\n');
7842   WorklistRemover DeadNodes(*this);
7843   if (isLoad) {
7844     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7845     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
7846   } else {
7847     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
7848   }
7849
7850   // Finally, since the node is now dead, remove it from the graph.
7851   deleteAndRecombine(N);
7852
7853   if (Swapped)
7854     std::swap(BasePtr, Offset);
7855
7856   // Replace other uses of BasePtr that can be updated to use Ptr
7857   for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
7858     unsigned OffsetIdx = 1;
7859     if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
7860       OffsetIdx = 0;
7861     assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
7862            BasePtr.getNode() && "Expected BasePtr operand");
7863
7864     // We need to replace ptr0 in the following expression:
7865     //   x0 * offset0 + y0 * ptr0 = t0
7866     // knowing that
7867     //   x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
7868     //
7869     // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
7870     // indexed load/store and the expresion that needs to be re-written.
7871     //
7872     // Therefore, we have:
7873     //   t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
7874
7875     ConstantSDNode *CN =
7876       cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
7877     int X0, X1, Y0, Y1;
7878     APInt Offset0 = CN->getAPIntValue();
7879     APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
7880
7881     X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
7882     Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
7883     X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
7884     Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
7885
7886     unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
7887
7888     APInt CNV = Offset0;
7889     if (X0 < 0) CNV = -CNV;
7890     if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
7891     else CNV = CNV - Offset1;
7892
7893     // We can now generate the new expression.
7894     SDValue NewOp1 = DAG.getConstant(CNV, CN->getValueType(0));
7895     SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
7896
7897     SDValue NewUse = DAG.getNode(Opcode,
7898                                  SDLoc(OtherUses[i]),
7899                                  OtherUses[i]->getValueType(0), NewOp1, NewOp2);
7900     DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
7901     deleteAndRecombine(OtherUses[i]);
7902   }
7903
7904   // Replace the uses of Ptr with uses of the updated base value.
7905   DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
7906   deleteAndRecombine(Ptr.getNode());
7907
7908   return true;
7909 }
7910
7911 /// CombineToPostIndexedLoadStore - Try to combine a load / store with a
7912 /// add / sub of the base pointer node into a post-indexed load / store.
7913 /// The transformation folded the add / subtract into the new indexed
7914 /// load / store effectively and all of its uses are redirected to the
7915 /// new load / store.
7916 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
7917   if (Level < AfterLegalizeDAG)
7918     return false;
7919
7920   bool isLoad = true;
7921   SDValue Ptr;
7922   EVT VT;
7923   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
7924     if (LD->isIndexed())
7925       return false;
7926     VT = LD->getMemoryVT();
7927     if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
7928         !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
7929       return false;
7930     Ptr = LD->getBasePtr();
7931   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
7932     if (ST->isIndexed())
7933       return false;
7934     VT = ST->getMemoryVT();
7935     if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
7936         !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
7937       return false;
7938     Ptr = ST->getBasePtr();
7939     isLoad = false;
7940   } else {
7941     return false;
7942   }
7943
7944   if (Ptr.getNode()->hasOneUse())
7945     return false;
7946
7947   for (SDNode *Op : Ptr.getNode()->uses()) {
7948     if (Op == N ||
7949         (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
7950       continue;
7951
7952     SDValue BasePtr;
7953     SDValue Offset;
7954     ISD::MemIndexedMode AM = ISD::UNINDEXED;
7955     if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
7956       // Don't create a indexed load / store with zero offset.
7957       if (isa<ConstantSDNode>(Offset) &&
7958           cast<ConstantSDNode>(Offset)->isNullValue())
7959         continue;
7960
7961       // Try turning it into a post-indexed load / store except when
7962       // 1) All uses are load / store ops that use it as base ptr (and
7963       //    it may be folded as addressing mmode).
7964       // 2) Op must be independent of N, i.e. Op is neither a predecessor
7965       //    nor a successor of N. Otherwise, if Op is folded that would
7966       //    create a cycle.
7967
7968       if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7969         continue;
7970
7971       // Check for #1.
7972       bool TryNext = false;
7973       for (SDNode *Use : BasePtr.getNode()->uses()) {
7974         if (Use == Ptr.getNode())
7975           continue;
7976
7977         // If all the uses are load / store addresses, then don't do the
7978         // transformation.
7979         if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
7980           bool RealUse = false;
7981           for (SDNode *UseUse : Use->uses()) {
7982             if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
7983               RealUse = true;
7984           }
7985
7986           if (!RealUse) {
7987             TryNext = true;
7988             break;
7989           }
7990         }
7991       }
7992
7993       if (TryNext)
7994         continue;
7995
7996       // Check for #2
7997       if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
7998         SDValue Result = isLoad
7999           ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
8000                                BasePtr, Offset, AM)
8001           : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
8002                                 BasePtr, Offset, AM);
8003         ++PostIndexedNodes;
8004         ++NodesCombined;
8005         DEBUG(dbgs() << "\nReplacing.5 ";
8006               N->dump(&DAG);
8007               dbgs() << "\nWith: ";
8008               Result.getNode()->dump(&DAG);
8009               dbgs() << '\n');
8010         WorklistRemover DeadNodes(*this);
8011         if (isLoad) {
8012           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
8013           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
8014         } else {
8015           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
8016         }
8017
8018         // Finally, since the node is now dead, remove it from the graph.
8019         deleteAndRecombine(N);
8020
8021         // Replace the uses of Use with uses of the updated base value.
8022         DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
8023                                       Result.getValue(isLoad ? 1 : 0));
8024         deleteAndRecombine(Op);
8025         return true;
8026       }
8027     }
8028   }
8029
8030   return false;
8031 }
8032
8033 SDValue DAGCombiner::visitLOAD(SDNode *N) {
8034   LoadSDNode *LD  = cast<LoadSDNode>(N);
8035   SDValue Chain = LD->getChain();
8036   SDValue Ptr   = LD->getBasePtr();
8037
8038   // If load is not volatile and there are no uses of the loaded value (and
8039   // the updated indexed value in case of indexed loads), change uses of the
8040   // chain value into uses of the chain input (i.e. delete the dead load).
8041   if (!LD->isVolatile()) {
8042     if (N->getValueType(1) == MVT::Other) {
8043       // Unindexed loads.
8044       if (!N->hasAnyUseOfValue(0)) {
8045         // It's not safe to use the two value CombineTo variant here. e.g.
8046         // v1, chain2 = load chain1, loc
8047         // v2, chain3 = load chain2, loc
8048         // v3         = add v2, c
8049         // Now we replace use of chain2 with chain1.  This makes the second load
8050         // isomorphic to the one we are deleting, and thus makes this load live.
8051         DEBUG(dbgs() << "\nReplacing.6 ";
8052               N->dump(&DAG);
8053               dbgs() << "\nWith chain: ";
8054               Chain.getNode()->dump(&DAG);
8055               dbgs() << "\n");
8056         WorklistRemover DeadNodes(*this);
8057         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
8058
8059         if (N->use_empty())
8060           deleteAndRecombine(N);
8061
8062         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
8063       }
8064     } else {
8065       // Indexed loads.
8066       assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
8067       if (!N->hasAnyUseOfValue(0) && !N->hasAnyUseOfValue(1)) {
8068         SDValue Undef = DAG.getUNDEF(N->getValueType(0));
8069         DEBUG(dbgs() << "\nReplacing.7 ";
8070               N->dump(&DAG);
8071               dbgs() << "\nWith: ";
8072               Undef.getNode()->dump(&DAG);
8073               dbgs() << " and 2 other values\n");
8074         WorklistRemover DeadNodes(*this);
8075         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
8076         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1),
8077                                       DAG.getUNDEF(N->getValueType(1)));
8078         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
8079         deleteAndRecombine(N);
8080         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
8081       }
8082     }
8083   }
8084
8085   // If this load is directly stored, replace the load value with the stored
8086   // value.
8087   // TODO: Handle store large -> read small portion.
8088   // TODO: Handle TRUNCSTORE/LOADEXT
8089   if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
8090     if (ISD::isNON_TRUNCStore(Chain.getNode())) {
8091       StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
8092       if (PrevST->getBasePtr() == Ptr &&
8093           PrevST->getValue().getValueType() == N->getValueType(0))
8094       return CombineTo(N, Chain.getOperand(1), Chain);
8095     }
8096   }
8097
8098   // Try to infer better alignment information than the load already has.
8099   if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
8100     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
8101       if (Align > LD->getMemOperand()->getBaseAlignment()) {
8102         SDValue NewLoad =
8103                DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
8104                               LD->getValueType(0),
8105                               Chain, Ptr, LD->getPointerInfo(),
8106                               LD->getMemoryVT(),
8107                               LD->isVolatile(), LD->isNonTemporal(),
8108                               LD->isInvariant(), Align, LD->getAAInfo());
8109         return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
8110       }
8111     }
8112   }
8113
8114   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
8115     TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
8116 #ifndef NDEBUG
8117   if (CombinerAAOnlyFunc.getNumOccurrences() &&
8118       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
8119     UseAA = false;
8120 #endif
8121   if (UseAA && LD->isUnindexed()) {
8122     // Walk up chain skipping non-aliasing memory nodes.
8123     SDValue BetterChain = FindBetterChain(N, Chain);
8124
8125     // If there is a better chain.
8126     if (Chain != BetterChain) {
8127       SDValue ReplLoad;
8128
8129       // Replace the chain to void dependency.
8130       if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
8131         ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
8132                                BetterChain, Ptr, LD->getMemOperand());
8133       } else {
8134         ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
8135                                   LD->getValueType(0),
8136                                   BetterChain, Ptr, LD->getMemoryVT(),
8137                                   LD->getMemOperand());
8138       }
8139
8140       // Create token factor to keep old chain connected.
8141       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
8142                                   MVT::Other, Chain, ReplLoad.getValue(1));
8143
8144       // Make sure the new and old chains are cleaned up.
8145       AddToWorklist(Token.getNode());
8146
8147       // Replace uses with load result and token factor. Don't add users
8148       // to work list.
8149       return CombineTo(N, ReplLoad.getValue(0), Token, false);
8150     }
8151   }
8152
8153   // Try transforming N to an indexed load.
8154   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
8155     return SDValue(N, 0);
8156
8157   // Try to slice up N to more direct loads if the slices are mapped to
8158   // different register banks or pairing can take place.
8159   if (SliceUpLoad(N))
8160     return SDValue(N, 0);
8161
8162   return SDValue();
8163 }
8164
8165 namespace {
8166 /// \brief Helper structure used to slice a load in smaller loads.
8167 /// Basically a slice is obtained from the following sequence:
8168 /// Origin = load Ty1, Base
8169 /// Shift = srl Ty1 Origin, CstTy Amount
8170 /// Inst = trunc Shift to Ty2
8171 ///
8172 /// Then, it will be rewriten into:
8173 /// Slice = load SliceTy, Base + SliceOffset
8174 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
8175 ///
8176 /// SliceTy is deduced from the number of bits that are actually used to
8177 /// build Inst.
8178 struct LoadedSlice {
8179   /// \brief Helper structure used to compute the cost of a slice.
8180   struct Cost {
8181     /// Are we optimizing for code size.
8182     bool ForCodeSize;
8183     /// Various cost.
8184     unsigned Loads;
8185     unsigned Truncates;
8186     unsigned CrossRegisterBanksCopies;
8187     unsigned ZExts;
8188     unsigned Shift;
8189
8190     Cost(bool ForCodeSize = false)
8191         : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
8192           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
8193
8194     /// \brief Get the cost of one isolated slice.
8195     Cost(const LoadedSlice &LS, bool ForCodeSize = false)
8196         : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
8197           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
8198       EVT TruncType = LS.Inst->getValueType(0);
8199       EVT LoadedType = LS.getLoadedType();
8200       if (TruncType != LoadedType &&
8201           !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
8202         ZExts = 1;
8203     }
8204
8205     /// \brief Account for slicing gain in the current cost.
8206     /// Slicing provide a few gains like removing a shift or a
8207     /// truncate. This method allows to grow the cost of the original
8208     /// load with the gain from this slice.
8209     void addSliceGain(const LoadedSlice &LS) {
8210       // Each slice saves a truncate.
8211       const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
8212       if (!TLI.isTruncateFree(LS.Inst->getValueType(0),
8213                               LS.Inst->getOperand(0).getValueType()))
8214         ++Truncates;
8215       // If there is a shift amount, this slice gets rid of it.
8216       if (LS.Shift)
8217         ++Shift;
8218       // If this slice can merge a cross register bank copy, account for it.
8219       if (LS.canMergeExpensiveCrossRegisterBankCopy())
8220         ++CrossRegisterBanksCopies;
8221     }
8222
8223     Cost &operator+=(const Cost &RHS) {
8224       Loads += RHS.Loads;
8225       Truncates += RHS.Truncates;
8226       CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
8227       ZExts += RHS.ZExts;
8228       Shift += RHS.Shift;
8229       return *this;
8230     }
8231
8232     bool operator==(const Cost &RHS) const {
8233       return Loads == RHS.Loads && Truncates == RHS.Truncates &&
8234              CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
8235              ZExts == RHS.ZExts && Shift == RHS.Shift;
8236     }
8237
8238     bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
8239
8240     bool operator<(const Cost &RHS) const {
8241       // Assume cross register banks copies are as expensive as loads.
8242       // FIXME: Do we want some more target hooks?
8243       unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
8244       unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
8245       // Unless we are optimizing for code size, consider the
8246       // expensive operation first.
8247       if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
8248         return ExpensiveOpsLHS < ExpensiveOpsRHS;
8249       return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
8250              (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
8251     }
8252
8253     bool operator>(const Cost &RHS) const { return RHS < *this; }
8254
8255     bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
8256
8257     bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
8258   };
8259   // The last instruction that represent the slice. This should be a
8260   // truncate instruction.
8261   SDNode *Inst;
8262   // The original load instruction.
8263   LoadSDNode *Origin;
8264   // The right shift amount in bits from the original load.
8265   unsigned Shift;
8266   // The DAG from which Origin came from.
8267   // This is used to get some contextual information about legal types, etc.
8268   SelectionDAG *DAG;
8269
8270   LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
8271               unsigned Shift = 0, SelectionDAG *DAG = nullptr)
8272       : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
8273
8274   LoadedSlice(const LoadedSlice &LS)
8275       : Inst(LS.Inst), Origin(LS.Origin), Shift(LS.Shift), DAG(LS.DAG) {}
8276
8277   /// \brief Get the bits used in a chunk of bits \p BitWidth large.
8278   /// \return Result is \p BitWidth and has used bits set to 1 and
8279   ///         not used bits set to 0.
8280   APInt getUsedBits() const {
8281     // Reproduce the trunc(lshr) sequence:
8282     // - Start from the truncated value.
8283     // - Zero extend to the desired bit width.
8284     // - Shift left.
8285     assert(Origin && "No original load to compare against.");
8286     unsigned BitWidth = Origin->getValueSizeInBits(0);
8287     assert(Inst && "This slice is not bound to an instruction");
8288     assert(Inst->getValueSizeInBits(0) <= BitWidth &&
8289            "Extracted slice is bigger than the whole type!");
8290     APInt UsedBits(Inst->getValueSizeInBits(0), 0);
8291     UsedBits.setAllBits();
8292     UsedBits = UsedBits.zext(BitWidth);
8293     UsedBits <<= Shift;
8294     return UsedBits;
8295   }
8296
8297   /// \brief Get the size of the slice to be loaded in bytes.
8298   unsigned getLoadedSize() const {
8299     unsigned SliceSize = getUsedBits().countPopulation();
8300     assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
8301     return SliceSize / 8;
8302   }
8303
8304   /// \brief Get the type that will be loaded for this slice.
8305   /// Note: This may not be the final type for the slice.
8306   EVT getLoadedType() const {
8307     assert(DAG && "Missing context");
8308     LLVMContext &Ctxt = *DAG->getContext();
8309     return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
8310   }
8311
8312   /// \brief Get the alignment of the load used for this slice.
8313   unsigned getAlignment() const {
8314     unsigned Alignment = Origin->getAlignment();
8315     unsigned Offset = getOffsetFromBase();
8316     if (Offset != 0)
8317       Alignment = MinAlign(Alignment, Alignment + Offset);
8318     return Alignment;
8319   }
8320
8321   /// \brief Check if this slice can be rewritten with legal operations.
8322   bool isLegal() const {
8323     // An invalid slice is not legal.
8324     if (!Origin || !Inst || !DAG)
8325       return false;
8326
8327     // Offsets are for indexed load only, we do not handle that.
8328     if (Origin->getOffset().getOpcode() != ISD::UNDEF)
8329       return false;
8330
8331     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8332
8333     // Check that the type is legal.
8334     EVT SliceType = getLoadedType();
8335     if (!TLI.isTypeLegal(SliceType))
8336       return false;
8337
8338     // Check that the load is legal for this type.
8339     if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
8340       return false;
8341
8342     // Check that the offset can be computed.
8343     // 1. Check its type.
8344     EVT PtrType = Origin->getBasePtr().getValueType();
8345     if (PtrType == MVT::Untyped || PtrType.isExtended())
8346       return false;
8347
8348     // 2. Check that it fits in the immediate.
8349     if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
8350       return false;
8351
8352     // 3. Check that the computation is legal.
8353     if (!TLI.isOperationLegal(ISD::ADD, PtrType))
8354       return false;
8355
8356     // Check that the zext is legal if it needs one.
8357     EVT TruncateType = Inst->getValueType(0);
8358     if (TruncateType != SliceType &&
8359         !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
8360       return false;
8361
8362     return true;
8363   }
8364
8365   /// \brief Get the offset in bytes of this slice in the original chunk of
8366   /// bits.
8367   /// \pre DAG != nullptr.
8368   uint64_t getOffsetFromBase() const {
8369     assert(DAG && "Missing context.");
8370     bool IsBigEndian =
8371         DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian();
8372     assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
8373     uint64_t Offset = Shift / 8;
8374     unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
8375     assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
8376            "The size of the original loaded type is not a multiple of a"
8377            " byte.");
8378     // If Offset is bigger than TySizeInBytes, it means we are loading all
8379     // zeros. This should have been optimized before in the process.
8380     assert(TySizeInBytes > Offset &&
8381            "Invalid shift amount for given loaded size");
8382     if (IsBigEndian)
8383       Offset = TySizeInBytes - Offset - getLoadedSize();
8384     return Offset;
8385   }
8386
8387   /// \brief Generate the sequence of instructions to load the slice
8388   /// represented by this object and redirect the uses of this slice to
8389   /// this new sequence of instructions.
8390   /// \pre this->Inst && this->Origin are valid Instructions and this
8391   /// object passed the legal check: LoadedSlice::isLegal returned true.
8392   /// \return The last instruction of the sequence used to load the slice.
8393   SDValue loadSlice() const {
8394     assert(Inst && Origin && "Unable to replace a non-existing slice.");
8395     const SDValue &OldBaseAddr = Origin->getBasePtr();
8396     SDValue BaseAddr = OldBaseAddr;
8397     // Get the offset in that chunk of bytes w.r.t. the endianess.
8398     int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
8399     assert(Offset >= 0 && "Offset too big to fit in int64_t!");
8400     if (Offset) {
8401       // BaseAddr = BaseAddr + Offset.
8402       EVT ArithType = BaseAddr.getValueType();
8403       BaseAddr = DAG->getNode(ISD::ADD, SDLoc(Origin), ArithType, BaseAddr,
8404                               DAG->getConstant(Offset, ArithType));
8405     }
8406
8407     // Create the type of the loaded slice according to its size.
8408     EVT SliceType = getLoadedType();
8409
8410     // Create the load for the slice.
8411     SDValue LastInst = DAG->getLoad(
8412         SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
8413         Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
8414         Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
8415     // If the final type is not the same as the loaded type, this means that
8416     // we have to pad with zero. Create a zero extend for that.
8417     EVT FinalType = Inst->getValueType(0);
8418     if (SliceType != FinalType)
8419       LastInst =
8420           DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
8421     return LastInst;
8422   }
8423
8424   /// \brief Check if this slice can be merged with an expensive cross register
8425   /// bank copy. E.g.,
8426   /// i = load i32
8427   /// f = bitcast i32 i to float
8428   bool canMergeExpensiveCrossRegisterBankCopy() const {
8429     if (!Inst || !Inst->hasOneUse())
8430       return false;
8431     SDNode *Use = *Inst->use_begin();
8432     if (Use->getOpcode() != ISD::BITCAST)
8433       return false;
8434     assert(DAG && "Missing context");
8435     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8436     EVT ResVT = Use->getValueType(0);
8437     const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
8438     const TargetRegisterClass *ArgRC =
8439         TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
8440     if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
8441       return false;
8442
8443     // At this point, we know that we perform a cross-register-bank copy.
8444     // Check if it is expensive.
8445     const TargetRegisterInfo *TRI =
8446         TLI.getTargetMachine().getSubtargetImpl()->getRegisterInfo();
8447     // Assume bitcasts are cheap, unless both register classes do not
8448     // explicitly share a common sub class.
8449     if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
8450       return false;
8451
8452     // Check if it will be merged with the load.
8453     // 1. Check the alignment constraint.
8454     unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment(
8455         ResVT.getTypeForEVT(*DAG->getContext()));
8456
8457     if (RequiredAlignment > getAlignment())
8458       return false;
8459
8460     // 2. Check that the load is a legal operation for that type.
8461     if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
8462       return false;
8463
8464     // 3. Check that we do not have a zext in the way.
8465     if (Inst->getValueType(0) != getLoadedType())
8466       return false;
8467
8468     return true;
8469   }
8470 };
8471 }
8472
8473 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
8474 /// \p UsedBits looks like 0..0 1..1 0..0.
8475 static bool areUsedBitsDense(const APInt &UsedBits) {
8476   // If all the bits are one, this is dense!
8477   if (UsedBits.isAllOnesValue())
8478     return true;
8479
8480   // Get rid of the unused bits on the right.
8481   APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
8482   // Get rid of the unused bits on the left.
8483   if (NarrowedUsedBits.countLeadingZeros())
8484     NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
8485   // Check that the chunk of bits is completely used.
8486   return NarrowedUsedBits.isAllOnesValue();
8487 }
8488
8489 /// \brief Check whether or not \p First and \p Second are next to each other
8490 /// in memory. This means that there is no hole between the bits loaded
8491 /// by \p First and the bits loaded by \p Second.
8492 static bool areSlicesNextToEachOther(const LoadedSlice &First,
8493                                      const LoadedSlice &Second) {
8494   assert(First.Origin == Second.Origin && First.Origin &&
8495          "Unable to match different memory origins.");
8496   APInt UsedBits = First.getUsedBits();
8497   assert((UsedBits & Second.getUsedBits()) == 0 &&
8498          "Slices are not supposed to overlap.");
8499   UsedBits |= Second.getUsedBits();
8500   return areUsedBitsDense(UsedBits);
8501 }
8502
8503 /// \brief Adjust the \p GlobalLSCost according to the target
8504 /// paring capabilities and the layout of the slices.
8505 /// \pre \p GlobalLSCost should account for at least as many loads as
8506 /// there is in the slices in \p LoadedSlices.
8507 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8508                                  LoadedSlice::Cost &GlobalLSCost) {
8509   unsigned NumberOfSlices = LoadedSlices.size();
8510   // If there is less than 2 elements, no pairing is possible.
8511   if (NumberOfSlices < 2)
8512     return;
8513
8514   // Sort the slices so that elements that are likely to be next to each
8515   // other in memory are next to each other in the list.
8516   std::sort(LoadedSlices.begin(), LoadedSlices.end(),
8517             [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
8518     assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
8519     return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
8520   });
8521   const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
8522   // First (resp. Second) is the first (resp. Second) potentially candidate
8523   // to be placed in a paired load.
8524   const LoadedSlice *First = nullptr;
8525   const LoadedSlice *Second = nullptr;
8526   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
8527                 // Set the beginning of the pair.
8528                                                            First = Second) {
8529
8530     Second = &LoadedSlices[CurrSlice];
8531
8532     // If First is NULL, it means we start a new pair.
8533     // Get to the next slice.
8534     if (!First)
8535       continue;
8536
8537     EVT LoadedType = First->getLoadedType();
8538
8539     // If the types of the slices are different, we cannot pair them.
8540     if (LoadedType != Second->getLoadedType())
8541       continue;
8542
8543     // Check if the target supplies paired loads for this type.
8544     unsigned RequiredAlignment = 0;
8545     if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
8546       // move to the next pair, this type is hopeless.
8547       Second = nullptr;
8548       continue;
8549     }
8550     // Check if we meet the alignment requirement.
8551     if (RequiredAlignment > First->getAlignment())
8552       continue;
8553
8554     // Check that both loads are next to each other in memory.
8555     if (!areSlicesNextToEachOther(*First, *Second))
8556       continue;
8557
8558     assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
8559     --GlobalLSCost.Loads;
8560     // Move to the next pair.
8561     Second = nullptr;
8562   }
8563 }
8564
8565 /// \brief Check the profitability of all involved LoadedSlice.
8566 /// Currently, it is considered profitable if there is exactly two
8567 /// involved slices (1) which are (2) next to each other in memory, and
8568 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
8569 ///
8570 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
8571 /// the elements themselves.
8572 ///
8573 /// FIXME: When the cost model will be mature enough, we can relax
8574 /// constraints (1) and (2).
8575 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8576                                 const APInt &UsedBits, bool ForCodeSize) {
8577   unsigned NumberOfSlices = LoadedSlices.size();
8578   if (StressLoadSlicing)
8579     return NumberOfSlices > 1;
8580
8581   // Check (1).
8582   if (NumberOfSlices != 2)
8583     return false;
8584
8585   // Check (2).
8586   if (!areUsedBitsDense(UsedBits))
8587     return false;
8588
8589   // Check (3).
8590   LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
8591   // The original code has one big load.
8592   OrigCost.Loads = 1;
8593   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
8594     const LoadedSlice &LS = LoadedSlices[CurrSlice];
8595     // Accumulate the cost of all the slices.
8596     LoadedSlice::Cost SliceCost(LS, ForCodeSize);
8597     GlobalSlicingCost += SliceCost;
8598
8599     // Account as cost in the original configuration the gain obtained
8600     // with the current slices.
8601     OrigCost.addSliceGain(LS);
8602   }
8603
8604   // If the target supports paired load, adjust the cost accordingly.
8605   adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
8606   return OrigCost > GlobalSlicingCost;
8607 }
8608
8609 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
8610 /// operations, split it in the various pieces being extracted.
8611 ///
8612 /// This sort of thing is introduced by SROA.
8613 /// This slicing takes care not to insert overlapping loads.
8614 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
8615 bool DAGCombiner::SliceUpLoad(SDNode *N) {
8616   if (Level < AfterLegalizeDAG)
8617     return false;
8618
8619   LoadSDNode *LD = cast<LoadSDNode>(N);
8620   if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
8621       !LD->getValueType(0).isInteger())
8622     return false;
8623
8624   // Keep track of already used bits to detect overlapping values.
8625   // In that case, we will just abort the transformation.
8626   APInt UsedBits(LD->getValueSizeInBits(0), 0);
8627
8628   SmallVector<LoadedSlice, 4> LoadedSlices;
8629
8630   // Check if this load is used as several smaller chunks of bits.
8631   // Basically, look for uses in trunc or trunc(lshr) and record a new chain
8632   // of computation for each trunc.
8633   for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
8634        UI != UIEnd; ++UI) {
8635     // Skip the uses of the chain.
8636     if (UI.getUse().getResNo() != 0)
8637       continue;
8638
8639     SDNode *User = *UI;
8640     unsigned Shift = 0;
8641
8642     // Check if this is a trunc(lshr).
8643     if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
8644         isa<ConstantSDNode>(User->getOperand(1))) {
8645       Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
8646       User = *User->use_begin();
8647     }
8648
8649     // At this point, User is a Truncate, iff we encountered, trunc or
8650     // trunc(lshr).
8651     if (User->getOpcode() != ISD::TRUNCATE)
8652       return false;
8653
8654     // The width of the type must be a power of 2 and greater than 8-bits.
8655     // Otherwise the load cannot be represented in LLVM IR.
8656     // Moreover, if we shifted with a non-8-bits multiple, the slice
8657     // will be across several bytes. We do not support that.
8658     unsigned Width = User->getValueSizeInBits(0);
8659     if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
8660       return 0;
8661
8662     // Build the slice for this chain of computations.
8663     LoadedSlice LS(User, LD, Shift, &DAG);
8664     APInt CurrentUsedBits = LS.getUsedBits();
8665
8666     // Check if this slice overlaps with another.
8667     if ((CurrentUsedBits & UsedBits) != 0)
8668       return false;
8669     // Update the bits used globally.
8670     UsedBits |= CurrentUsedBits;
8671
8672     // Check if the new slice would be legal.
8673     if (!LS.isLegal())
8674       return false;
8675
8676     // Record the slice.
8677     LoadedSlices.push_back(LS);
8678   }
8679
8680   // Abort slicing if it does not seem to be profitable.
8681   if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
8682     return false;
8683
8684   ++SlicedLoads;
8685
8686   // Rewrite each chain to use an independent load.
8687   // By construction, each chain can be represented by a unique load.
8688
8689   // Prepare the argument for the new token factor for all the slices.
8690   SmallVector<SDValue, 8> ArgChains;
8691   for (SmallVectorImpl<LoadedSlice>::const_iterator
8692            LSIt = LoadedSlices.begin(),
8693            LSItEnd = LoadedSlices.end();
8694        LSIt != LSItEnd; ++LSIt) {
8695     SDValue SliceInst = LSIt->loadSlice();
8696     CombineTo(LSIt->Inst, SliceInst, true);
8697     if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
8698       SliceInst = SliceInst.getOperand(0);
8699     assert(SliceInst->getOpcode() == ISD::LOAD &&
8700            "It takes more than a zext to get to the loaded slice!!");
8701     ArgChains.push_back(SliceInst.getValue(1));
8702   }
8703
8704   SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
8705                               ArgChains);
8706   DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
8707   return true;
8708 }
8709
8710 /// CheckForMaskedLoad - Check to see if V is (and load (ptr), imm), where the
8711 /// load is having specific bytes cleared out.  If so, return the byte size
8712 /// being masked out and the shift amount.
8713 static std::pair<unsigned, unsigned>
8714 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
8715   std::pair<unsigned, unsigned> Result(0, 0);
8716
8717   // Check for the structure we're looking for.
8718   if (V->getOpcode() != ISD::AND ||
8719       !isa<ConstantSDNode>(V->getOperand(1)) ||
8720       !ISD::isNormalLoad(V->getOperand(0).getNode()))
8721     return Result;
8722
8723   // Check the chain and pointer.
8724   LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
8725   if (LD->getBasePtr() != Ptr) return Result;  // Not from same pointer.
8726
8727   // The store should be chained directly to the load or be an operand of a
8728   // tokenfactor.
8729   if (LD == Chain.getNode())
8730     ; // ok.
8731   else if (Chain->getOpcode() != ISD::TokenFactor)
8732     return Result; // Fail.
8733   else {
8734     bool isOk = false;
8735     for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
8736       if (Chain->getOperand(i).getNode() == LD) {
8737         isOk = true;
8738         break;
8739       }
8740     if (!isOk) return Result;
8741   }
8742
8743   // This only handles simple types.
8744   if (V.getValueType() != MVT::i16 &&
8745       V.getValueType() != MVT::i32 &&
8746       V.getValueType() != MVT::i64)
8747     return Result;
8748
8749   // Check the constant mask.  Invert it so that the bits being masked out are
8750   // 0 and the bits being kept are 1.  Use getSExtValue so that leading bits
8751   // follow the sign bit for uniformity.
8752   uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
8753   unsigned NotMaskLZ = countLeadingZeros(NotMask);
8754   if (NotMaskLZ & 7) return Result;  // Must be multiple of a byte.
8755   unsigned NotMaskTZ = countTrailingZeros(NotMask);
8756   if (NotMaskTZ & 7) return Result;  // Must be multiple of a byte.
8757   if (NotMaskLZ == 64) return Result;  // All zero mask.
8758
8759   // See if we have a continuous run of bits.  If so, we have 0*1+0*
8760   if (CountTrailingOnes_64(NotMask >> NotMaskTZ)+NotMaskTZ+NotMaskLZ != 64)
8761     return Result;
8762
8763   // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
8764   if (V.getValueType() != MVT::i64 && NotMaskLZ)
8765     NotMaskLZ -= 64-V.getValueSizeInBits();
8766
8767   unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
8768   switch (MaskedBytes) {
8769   case 1:
8770   case 2:
8771   case 4: break;
8772   default: return Result; // All one mask, or 5-byte mask.
8773   }
8774
8775   // Verify that the first bit starts at a multiple of mask so that the access
8776   // is aligned the same as the access width.
8777   if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
8778
8779   Result.first = MaskedBytes;
8780   Result.second = NotMaskTZ/8;
8781   return Result;
8782 }
8783
8784
8785 /// ShrinkLoadReplaceStoreWithStore - Check to see if IVal is something that
8786 /// provides a value as specified by MaskInfo.  If so, replace the specified
8787 /// store with a narrower store of truncated IVal.
8788 static SDNode *
8789 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
8790                                 SDValue IVal, StoreSDNode *St,
8791                                 DAGCombiner *DC) {
8792   unsigned NumBytes = MaskInfo.first;
8793   unsigned ByteShift = MaskInfo.second;
8794   SelectionDAG &DAG = DC->getDAG();
8795
8796   // Check to see if IVal is all zeros in the part being masked in by the 'or'
8797   // that uses this.  If not, this is not a replacement.
8798   APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
8799                                   ByteShift*8, (ByteShift+NumBytes)*8);
8800   if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
8801
8802   // Check that it is legal on the target to do this.  It is legal if the new
8803   // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
8804   // legalization.
8805   MVT VT = MVT::getIntegerVT(NumBytes*8);
8806   if (!DC->isTypeLegal(VT))
8807     return nullptr;
8808
8809   // Okay, we can do this!  Replace the 'St' store with a store of IVal that is
8810   // shifted by ByteShift and truncated down to NumBytes.
8811   if (ByteShift)
8812     IVal = DAG.getNode(ISD::SRL, SDLoc(IVal), IVal.getValueType(), IVal,
8813                        DAG.getConstant(ByteShift*8,
8814                                     DC->getShiftAmountTy(IVal.getValueType())));
8815
8816   // Figure out the offset for the store and the alignment of the access.
8817   unsigned StOffset;
8818   unsigned NewAlign = St->getAlignment();
8819
8820   if (DAG.getTargetLoweringInfo().isLittleEndian())
8821     StOffset = ByteShift;
8822   else
8823     StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
8824
8825   SDValue Ptr = St->getBasePtr();
8826   if (StOffset) {
8827     Ptr = DAG.getNode(ISD::ADD, SDLoc(IVal), Ptr.getValueType(),
8828                       Ptr, DAG.getConstant(StOffset, Ptr.getValueType()));
8829     NewAlign = MinAlign(NewAlign, StOffset);
8830   }
8831
8832   // Truncate down to the new size.
8833   IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
8834
8835   ++OpsNarrowed;
8836   return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
8837                       St->getPointerInfo().getWithOffset(StOffset),
8838                       false, false, NewAlign).getNode();
8839 }
8840
8841
8842 /// ReduceLoadOpStoreWidth - Look for sequence of load / op / store where op is
8843 /// one of 'or', 'xor', and 'and' of immediates. If 'op' is only touching some
8844 /// of the loaded bits, try narrowing the load and store if it would end up
8845 /// being a win for performance or code size.
8846 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
8847   StoreSDNode *ST  = cast<StoreSDNode>(N);
8848   if (ST->isVolatile())
8849     return SDValue();
8850
8851   SDValue Chain = ST->getChain();
8852   SDValue Value = ST->getValue();
8853   SDValue Ptr   = ST->getBasePtr();
8854   EVT VT = Value.getValueType();
8855
8856   if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
8857     return SDValue();
8858
8859   unsigned Opc = Value.getOpcode();
8860
8861   // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
8862   // is a byte mask indicating a consecutive number of bytes, check to see if
8863   // Y is known to provide just those bytes.  If so, we try to replace the
8864   // load + replace + store sequence with a single (narrower) store, which makes
8865   // the load dead.
8866   if (Opc == ISD::OR) {
8867     std::pair<unsigned, unsigned> MaskedLoad;
8868     MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
8869     if (MaskedLoad.first)
8870       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8871                                                   Value.getOperand(1), ST,this))
8872         return SDValue(NewST, 0);
8873
8874     // Or is commutative, so try swapping X and Y.
8875     MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
8876     if (MaskedLoad.first)
8877       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8878                                                   Value.getOperand(0), ST,this))
8879         return SDValue(NewST, 0);
8880   }
8881
8882   if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
8883       Value.getOperand(1).getOpcode() != ISD::Constant)
8884     return SDValue();
8885
8886   SDValue N0 = Value.getOperand(0);
8887   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8888       Chain == SDValue(N0.getNode(), 1)) {
8889     LoadSDNode *LD = cast<LoadSDNode>(N0);
8890     if (LD->getBasePtr() != Ptr ||
8891         LD->getPointerInfo().getAddrSpace() !=
8892         ST->getPointerInfo().getAddrSpace())
8893       return SDValue();
8894
8895     // Find the type to narrow it the load / op / store to.
8896     SDValue N1 = Value.getOperand(1);
8897     unsigned BitWidth = N1.getValueSizeInBits();
8898     APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
8899     if (Opc == ISD::AND)
8900       Imm ^= APInt::getAllOnesValue(BitWidth);
8901     if (Imm == 0 || Imm.isAllOnesValue())
8902       return SDValue();
8903     unsigned ShAmt = Imm.countTrailingZeros();
8904     unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
8905     unsigned NewBW = NextPowerOf2(MSB - ShAmt);
8906     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
8907     while (NewBW < BitWidth &&
8908            !(TLI.isOperationLegalOrCustom(Opc, NewVT) &&
8909              TLI.isNarrowingProfitable(VT, NewVT))) {
8910       NewBW = NextPowerOf2(NewBW);
8911       NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
8912     }
8913     if (NewBW >= BitWidth)
8914       return SDValue();
8915
8916     // If the lsb changed does not start at the type bitwidth boundary,
8917     // start at the previous one.
8918     if (ShAmt % NewBW)
8919       ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
8920     APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
8921                                    std::min(BitWidth, ShAmt + NewBW));
8922     if ((Imm & Mask) == Imm) {
8923       APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
8924       if (Opc == ISD::AND)
8925         NewImm ^= APInt::getAllOnesValue(NewBW);
8926       uint64_t PtrOff = ShAmt / 8;
8927       // For big endian targets, we need to adjust the offset to the pointer to
8928       // load the correct bytes.
8929       if (TLI.isBigEndian())
8930         PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
8931
8932       unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
8933       Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
8934       if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
8935         return SDValue();
8936
8937       SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
8938                                    Ptr.getValueType(), Ptr,
8939                                    DAG.getConstant(PtrOff, Ptr.getValueType()));
8940       SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
8941                                   LD->getChain(), NewPtr,
8942                                   LD->getPointerInfo().getWithOffset(PtrOff),
8943                                   LD->isVolatile(), LD->isNonTemporal(),
8944                                   LD->isInvariant(), NewAlign,
8945                                   LD->getAAInfo());
8946       SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
8947                                    DAG.getConstant(NewImm, NewVT));
8948       SDValue NewST = DAG.getStore(Chain, SDLoc(N),
8949                                    NewVal, NewPtr,
8950                                    ST->getPointerInfo().getWithOffset(PtrOff),
8951                                    false, false, NewAlign);
8952
8953       AddToWorklist(NewPtr.getNode());
8954       AddToWorklist(NewLD.getNode());
8955       AddToWorklist(NewVal.getNode());
8956       WorklistRemover DeadNodes(*this);
8957       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
8958       ++OpsNarrowed;
8959       return NewST;
8960     }
8961   }
8962
8963   return SDValue();
8964 }
8965
8966 /// TransformFPLoadStorePair - For a given floating point load / store pair,
8967 /// if the load value isn't used by any other operations, then consider
8968 /// transforming the pair to integer load / store operations if the target
8969 /// deems the transformation profitable.
8970 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
8971   StoreSDNode *ST  = cast<StoreSDNode>(N);
8972   SDValue Chain = ST->getChain();
8973   SDValue Value = ST->getValue();
8974   if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
8975       Value.hasOneUse() &&
8976       Chain == SDValue(Value.getNode(), 1)) {
8977     LoadSDNode *LD = cast<LoadSDNode>(Value);
8978     EVT VT = LD->getMemoryVT();
8979     if (!VT.isFloatingPoint() ||
8980         VT != ST->getMemoryVT() ||
8981         LD->isNonTemporal() ||
8982         ST->isNonTemporal() ||
8983         LD->getPointerInfo().getAddrSpace() != 0 ||
8984         ST->getPointerInfo().getAddrSpace() != 0)
8985       return SDValue();
8986
8987     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
8988     if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
8989         !TLI.isOperationLegal(ISD::STORE, IntVT) ||
8990         !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
8991         !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
8992       return SDValue();
8993
8994     unsigned LDAlign = LD->getAlignment();
8995     unsigned STAlign = ST->getAlignment();
8996     Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
8997     unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
8998     if (LDAlign < ABIAlign || STAlign < ABIAlign)
8999       return SDValue();
9000
9001     SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
9002                                 LD->getChain(), LD->getBasePtr(),
9003                                 LD->getPointerInfo(),
9004                                 false, false, false, LDAlign);
9005
9006     SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
9007                                  NewLD, ST->getBasePtr(),
9008                                  ST->getPointerInfo(),
9009                                  false, false, STAlign);
9010
9011     AddToWorklist(NewLD.getNode());
9012     AddToWorklist(NewST.getNode());
9013     WorklistRemover DeadNodes(*this);
9014     DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
9015     ++LdStFP2Int;
9016     return NewST;
9017   }
9018
9019   return SDValue();
9020 }
9021
9022 /// Helper struct to parse and store a memory address as base + index + offset.
9023 /// We ignore sign extensions when it is safe to do so.
9024 /// The following two expressions are not equivalent. To differentiate we need
9025 /// to store whether there was a sign extension involved in the index
9026 /// computation.
9027 ///  (load (i64 add (i64 copyfromreg %c)
9028 ///                 (i64 signextend (add (i8 load %index)
9029 ///                                      (i8 1))))
9030 /// vs
9031 ///
9032 /// (load (i64 add (i64 copyfromreg %c)
9033 ///                (i64 signextend (i32 add (i32 signextend (i8 load %index))
9034 ///                                         (i32 1)))))
9035 struct BaseIndexOffset {
9036   SDValue Base;
9037   SDValue Index;
9038   int64_t Offset;
9039   bool IsIndexSignExt;
9040
9041   BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
9042
9043   BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
9044                   bool IsIndexSignExt) :
9045     Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
9046
9047   bool equalBaseIndex(const BaseIndexOffset &Other) {
9048     return Other.Base == Base && Other.Index == Index &&
9049       Other.IsIndexSignExt == IsIndexSignExt;
9050   }
9051
9052   /// Parses tree in Ptr for base, index, offset addresses.
9053   static BaseIndexOffset match(SDValue Ptr) {
9054     bool IsIndexSignExt = false;
9055
9056     // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
9057     // instruction, then it could be just the BASE or everything else we don't
9058     // know how to handle. Just use Ptr as BASE and give up.
9059     if (Ptr->getOpcode() != ISD::ADD)
9060       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9061
9062     // We know that we have at least an ADD instruction. Try to pattern match
9063     // the simple case of BASE + OFFSET.
9064     if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
9065       int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
9066       return  BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
9067                               IsIndexSignExt);
9068     }
9069
9070     // Inside a loop the current BASE pointer is calculated using an ADD and a
9071     // MUL instruction. In this case Ptr is the actual BASE pointer.
9072     // (i64 add (i64 %array_ptr)
9073     //          (i64 mul (i64 %induction_var)
9074     //                   (i64 %element_size)))
9075     if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
9076       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9077
9078     // Look at Base + Index + Offset cases.
9079     SDValue Base = Ptr->getOperand(0);
9080     SDValue IndexOffset = Ptr->getOperand(1);
9081
9082     // Skip signextends.
9083     if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
9084       IndexOffset = IndexOffset->getOperand(0);
9085       IsIndexSignExt = true;
9086     }
9087
9088     // Either the case of Base + Index (no offset) or something else.
9089     if (IndexOffset->getOpcode() != ISD::ADD)
9090       return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
9091
9092     // Now we have the case of Base + Index + offset.
9093     SDValue Index = IndexOffset->getOperand(0);
9094     SDValue Offset = IndexOffset->getOperand(1);
9095
9096     if (!isa<ConstantSDNode>(Offset))
9097       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9098
9099     // Ignore signextends.
9100     if (Index->getOpcode() == ISD::SIGN_EXTEND) {
9101       Index = Index->getOperand(0);
9102       IsIndexSignExt = true;
9103     } else IsIndexSignExt = false;
9104
9105     int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
9106     return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
9107   }
9108 };
9109
9110 /// Holds a pointer to an LSBaseSDNode as well as information on where it
9111 /// is located in a sequence of memory operations connected by a chain.
9112 struct MemOpLink {
9113   MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
9114     MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
9115   // Ptr to the mem node.
9116   LSBaseSDNode *MemNode;
9117   // Offset from the base ptr.
9118   int64_t OffsetFromBase;
9119   // What is the sequence number of this mem node.
9120   // Lowest mem operand in the DAG starts at zero.
9121   unsigned SequenceNum;
9122 };
9123
9124 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
9125   EVT MemVT = St->getMemoryVT();
9126   int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
9127   bool NoVectors = DAG.getMachineFunction().getFunction()->getAttributes().
9128     hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
9129
9130   // Don't merge vectors into wider inputs.
9131   if (MemVT.isVector() || !MemVT.isSimple())
9132     return false;
9133
9134   // Perform an early exit check. Do not bother looking at stored values that
9135   // are not constants or loads.
9136   SDValue StoredVal = St->getValue();
9137   bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
9138   if (!isa<ConstantSDNode>(StoredVal) && !isa<ConstantFPSDNode>(StoredVal) &&
9139       !IsLoadSrc)
9140     return false;
9141
9142   // Only look at ends of store sequences.
9143   SDValue Chain = SDValue(St, 0);
9144   if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
9145     return false;
9146
9147   // This holds the base pointer, index, and the offset in bytes from the base
9148   // pointer.
9149   BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
9150
9151   // We must have a base and an offset.
9152   if (!BasePtr.Base.getNode())
9153     return false;
9154
9155   // Do not handle stores to undef base pointers.
9156   if (BasePtr.Base.getOpcode() == ISD::UNDEF)
9157     return false;
9158
9159   // Save the LoadSDNodes that we find in the chain.
9160   // We need to make sure that these nodes do not interfere with
9161   // any of the store nodes.
9162   SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
9163
9164   // Save the StoreSDNodes that we find in the chain.
9165   SmallVector<MemOpLink, 8> StoreNodes;
9166
9167   // Walk up the chain and look for nodes with offsets from the same
9168   // base pointer. Stop when reaching an instruction with a different kind
9169   // or instruction which has a different base pointer.
9170   unsigned Seq = 0;
9171   StoreSDNode *Index = St;
9172   while (Index) {
9173     // If the chain has more than one use, then we can't reorder the mem ops.
9174     if (Index != St && !SDValue(Index, 0)->hasOneUse())
9175       break;
9176
9177     // Find the base pointer and offset for this memory node.
9178     BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
9179
9180     // Check that the base pointer is the same as the original one.
9181     if (!Ptr.equalBaseIndex(BasePtr))
9182       break;
9183
9184     // Check that the alignment is the same.
9185     if (Index->getAlignment() != St->getAlignment())
9186       break;
9187
9188     // The memory operands must not be volatile.
9189     if (Index->isVolatile() || Index->isIndexed())
9190       break;
9191
9192     // No truncation.
9193     if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
9194       if (St->isTruncatingStore())
9195         break;
9196
9197     // The stored memory type must be the same.
9198     if (Index->getMemoryVT() != MemVT)
9199       break;
9200
9201     // We do not allow unaligned stores because we want to prevent overriding
9202     // stores.
9203     if (Index->getAlignment()*8 != MemVT.getSizeInBits())
9204       break;
9205
9206     // We found a potential memory operand to merge.
9207     StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
9208
9209     // Find the next memory operand in the chain. If the next operand in the
9210     // chain is a store then move up and continue the scan with the next
9211     // memory operand. If the next operand is a load save it and use alias
9212     // information to check if it interferes with anything.
9213     SDNode *NextInChain = Index->getChain().getNode();
9214     while (1) {
9215       if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
9216         // We found a store node. Use it for the next iteration.
9217         Index = STn;
9218         break;
9219       } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
9220         if (Ldn->isVolatile()) {
9221           Index = nullptr;
9222           break;
9223         }
9224
9225         // Save the load node for later. Continue the scan.
9226         AliasLoadNodes.push_back(Ldn);
9227         NextInChain = Ldn->getChain().getNode();
9228         continue;
9229       } else {
9230         Index = nullptr;
9231         break;
9232       }
9233     }
9234   }
9235
9236   // Check if there is anything to merge.
9237   if (StoreNodes.size() < 2)
9238     return false;
9239
9240   // Sort the memory operands according to their distance from the base pointer.
9241   std::sort(StoreNodes.begin(), StoreNodes.end(),
9242             [](MemOpLink LHS, MemOpLink RHS) {
9243     return LHS.OffsetFromBase < RHS.OffsetFromBase ||
9244            (LHS.OffsetFromBase == RHS.OffsetFromBase &&
9245             LHS.SequenceNum > RHS.SequenceNum);
9246   });
9247
9248   // Scan the memory operations on the chain and find the first non-consecutive
9249   // store memory address.
9250   unsigned LastConsecutiveStore = 0;
9251   int64_t StartAddress = StoreNodes[0].OffsetFromBase;
9252   for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
9253
9254     // Check that the addresses are consecutive starting from the second
9255     // element in the list of stores.
9256     if (i > 0) {
9257       int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
9258       if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9259         break;
9260     }
9261
9262     bool Alias = false;
9263     // Check if this store interferes with any of the loads that we found.
9264     for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
9265       if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
9266         Alias = true;
9267         break;
9268       }
9269     // We found a load that alias with this store. Stop the sequence.
9270     if (Alias)
9271       break;
9272
9273     // Mark this node as useful.
9274     LastConsecutiveStore = i;
9275   }
9276
9277   // The node with the lowest store address.
9278   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
9279
9280   // Store the constants into memory as one consecutive store.
9281   if (!IsLoadSrc) {
9282     unsigned LastLegalType = 0;
9283     unsigned LastLegalVectorType = 0;
9284     bool NonZero = false;
9285     for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9286       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
9287       SDValue StoredVal = St->getValue();
9288
9289       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
9290         NonZero |= !C->isNullValue();
9291       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
9292         NonZero |= !C->getConstantFPValue()->isNullValue();
9293       } else {
9294         // Non-constant.
9295         break;
9296       }
9297
9298       // Find a legal type for the constant store.
9299       unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9300       EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9301       if (TLI.isTypeLegal(StoreTy))
9302         LastLegalType = i+1;
9303       // Or check whether a truncstore is legal.
9304       else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9305                TargetLowering::TypePromoteInteger) {
9306         EVT LegalizedStoredValueTy =
9307           TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
9308         if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy))
9309           LastLegalType = i+1;
9310       }
9311
9312       // Find a legal type for the vector store.
9313       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9314       if (TLI.isTypeLegal(Ty))
9315         LastLegalVectorType = i + 1;
9316     }
9317
9318     // We only use vectors if the constant is known to be zero and the
9319     // function is not marked with the noimplicitfloat attribute.
9320     if (NonZero || NoVectors)
9321       LastLegalVectorType = 0;
9322
9323     // Check if we found a legal integer type to store.
9324     if (LastLegalType == 0 && LastLegalVectorType == 0)
9325       return false;
9326
9327     bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
9328     unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
9329
9330     // Make sure we have something to merge.
9331     if (NumElem < 2)
9332       return false;
9333
9334     unsigned EarliestNodeUsed = 0;
9335     for (unsigned i=0; i < NumElem; ++i) {
9336       // Find a chain for the new wide-store operand. Notice that some
9337       // of the store nodes that we found may not be selected for inclusion
9338       // in the wide store. The chain we use needs to be the chain of the
9339       // earliest store node which is *used* and replaced by the wide store.
9340       if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9341         EarliestNodeUsed = i;
9342     }
9343
9344     // The earliest Node in the DAG.
9345     LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9346     SDLoc DL(StoreNodes[0].MemNode);
9347
9348     SDValue StoredVal;
9349     if (UseVector) {
9350       // Find a legal type for the vector store.
9351       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9352       assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
9353       StoredVal = DAG.getConstant(0, Ty);
9354     } else {
9355       unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9356       APInt StoreInt(StoreBW, 0);
9357
9358       // Construct a single integer constant which is made of the smaller
9359       // constant inputs.
9360       bool IsLE = TLI.isLittleEndian();
9361       for (unsigned i = 0; i < NumElem ; ++i) {
9362         unsigned Idx = IsLE ?(NumElem - 1 - i) : i;
9363         StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
9364         SDValue Val = St->getValue();
9365         StoreInt<<=ElementSizeBytes*8;
9366         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
9367           StoreInt|=C->getAPIntValue().zext(StoreBW);
9368         } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
9369           StoreInt|= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
9370         } else {
9371           assert(false && "Invalid constant element type");
9372         }
9373       }
9374
9375       // Create the new Load and Store operations.
9376       EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9377       StoredVal = DAG.getConstant(StoreInt, StoreTy);
9378     }
9379
9380     SDValue NewStore = DAG.getStore(EarliestOp->getChain(), DL, StoredVal,
9381                                     FirstInChain->getBasePtr(),
9382                                     FirstInChain->getPointerInfo(),
9383                                     false, false,
9384                                     FirstInChain->getAlignment());
9385
9386     // Replace the first store with the new store
9387     CombineTo(EarliestOp, NewStore);
9388     // Erase all other stores.
9389     for (unsigned i = 0; i < NumElem ; ++i) {
9390       if (StoreNodes[i].MemNode == EarliestOp)
9391         continue;
9392       StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9393       // ReplaceAllUsesWith will replace all uses that existed when it was
9394       // called, but graph optimizations may cause new ones to appear. For
9395       // example, the case in pr14333 looks like
9396       //
9397       //  St's chain -> St -> another store -> X
9398       //
9399       // And the only difference from St to the other store is the chain.
9400       // When we change it's chain to be St's chain they become identical,
9401       // get CSEed and the net result is that X is now a use of St.
9402       // Since we know that St is redundant, just iterate.
9403       while (!St->use_empty())
9404         DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
9405       deleteAndRecombine(St);
9406     }
9407
9408     return true;
9409   }
9410
9411   // Below we handle the case of multiple consecutive stores that
9412   // come from multiple consecutive loads. We merge them into a single
9413   // wide load and a single wide store.
9414
9415   // Look for load nodes which are used by the stored values.
9416   SmallVector<MemOpLink, 8> LoadNodes;
9417
9418   // Find acceptable loads. Loads need to have the same chain (token factor),
9419   // must not be zext, volatile, indexed, and they must be consecutive.
9420   BaseIndexOffset LdBasePtr;
9421   for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9422     StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
9423     LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
9424     if (!Ld) break;
9425
9426     // Loads must only have one use.
9427     if (!Ld->hasNUsesOfValue(1, 0))
9428       break;
9429
9430     // Check that the alignment is the same as the stores.
9431     if (Ld->getAlignment() != St->getAlignment())
9432       break;
9433
9434     // The memory operands must not be volatile.
9435     if (Ld->isVolatile() || Ld->isIndexed())
9436       break;
9437
9438     // We do not accept ext loads.
9439     if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
9440       break;
9441
9442     // The stored memory type must be the same.
9443     if (Ld->getMemoryVT() != MemVT)
9444       break;
9445
9446     BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
9447     // If this is not the first ptr that we check.
9448     if (LdBasePtr.Base.getNode()) {
9449       // The base ptr must be the same.
9450       if (!LdPtr.equalBaseIndex(LdBasePtr))
9451         break;
9452     } else {
9453       // Check that all other base pointers are the same as this one.
9454       LdBasePtr = LdPtr;
9455     }
9456
9457     // We found a potential memory operand to merge.
9458     LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
9459   }
9460
9461   if (LoadNodes.size() < 2)
9462     return false;
9463
9464   // If we have load/store pair instructions and we only have two values,
9465   // don't bother.
9466   unsigned RequiredAlignment;
9467   if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) &&
9468       St->getAlignment() >= RequiredAlignment)
9469     return false;
9470
9471   // Scan the memory operations on the chain and find the first non-consecutive
9472   // load memory address. These variables hold the index in the store node
9473   // array.
9474   unsigned LastConsecutiveLoad = 0;
9475   // This variable refers to the size and not index in the array.
9476   unsigned LastLegalVectorType = 0;
9477   unsigned LastLegalIntegerType = 0;
9478   StartAddress = LoadNodes[0].OffsetFromBase;
9479   SDValue FirstChain = LoadNodes[0].MemNode->getChain();
9480   for (unsigned i = 1; i < LoadNodes.size(); ++i) {
9481     // All loads much share the same chain.
9482     if (LoadNodes[i].MemNode->getChain() != FirstChain)
9483       break;
9484
9485     int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
9486     if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9487       break;
9488     LastConsecutiveLoad = i;
9489
9490     // Find a legal type for the vector store.
9491     EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9492     if (TLI.isTypeLegal(StoreTy))
9493       LastLegalVectorType = i + 1;
9494
9495     // Find a legal type for the integer store.
9496     unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9497     StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9498     if (TLI.isTypeLegal(StoreTy))
9499       LastLegalIntegerType = i + 1;
9500     // Or check whether a truncstore and extload is legal.
9501     else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9502              TargetLowering::TypePromoteInteger) {
9503       EVT LegalizedStoredValueTy =
9504         TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
9505       if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
9506           TLI.isLoadExtLegal(ISD::ZEXTLOAD, StoreTy) &&
9507           TLI.isLoadExtLegal(ISD::SEXTLOAD, StoreTy) &&
9508           TLI.isLoadExtLegal(ISD::EXTLOAD, StoreTy))
9509         LastLegalIntegerType = i+1;
9510     }
9511   }
9512
9513   // Only use vector types if the vector type is larger than the integer type.
9514   // If they are the same, use integers.
9515   bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
9516   unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
9517
9518   // We add +1 here because the LastXXX variables refer to location while
9519   // the NumElem refers to array/index size.
9520   unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
9521   NumElem = std::min(LastLegalType, NumElem);
9522
9523   if (NumElem < 2)
9524     return false;
9525
9526   // The earliest Node in the DAG.
9527   unsigned EarliestNodeUsed = 0;
9528   LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9529   for (unsigned i=1; i<NumElem; ++i) {
9530     // Find a chain for the new wide-store operand. Notice that some
9531     // of the store nodes that we found may not be selected for inclusion
9532     // in the wide store. The chain we use needs to be the chain of the
9533     // earliest store node which is *used* and replaced by the wide store.
9534     if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9535       EarliestNodeUsed = i;
9536   }
9537
9538   // Find if it is better to use vectors or integers to load and store
9539   // to memory.
9540   EVT JointMemOpVT;
9541   if (UseVectorTy) {
9542     JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9543   } else {
9544     unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9545     JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9546   }
9547
9548   SDLoc LoadDL(LoadNodes[0].MemNode);
9549   SDLoc StoreDL(StoreNodes[0].MemNode);
9550
9551   LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
9552   SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL,
9553                                 FirstLoad->getChain(),
9554                                 FirstLoad->getBasePtr(),
9555                                 FirstLoad->getPointerInfo(),
9556                                 false, false, false,
9557                                 FirstLoad->getAlignment());
9558
9559   SDValue NewStore = DAG.getStore(EarliestOp->getChain(), StoreDL, NewLoad,
9560                                   FirstInChain->getBasePtr(),
9561                                   FirstInChain->getPointerInfo(), false, false,
9562                                   FirstInChain->getAlignment());
9563
9564   // Replace one of the loads with the new load.
9565   LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
9566   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
9567                                 SDValue(NewLoad.getNode(), 1));
9568
9569   // Remove the rest of the load chains.
9570   for (unsigned i = 1; i < NumElem ; ++i) {
9571     // Replace all chain users of the old load nodes with the chain of the new
9572     // load node.
9573     LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
9574     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
9575   }
9576
9577   // Replace the first store with the new store.
9578   CombineTo(EarliestOp, NewStore);
9579   // Erase all other stores.
9580   for (unsigned i = 0; i < NumElem ; ++i) {
9581     // Remove all Store nodes.
9582     if (StoreNodes[i].MemNode == EarliestOp)
9583       continue;
9584     StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9585     DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
9586     deleteAndRecombine(St);
9587   }
9588
9589   return true;
9590 }
9591
9592 SDValue DAGCombiner::visitSTORE(SDNode *N) {
9593   StoreSDNode *ST  = cast<StoreSDNode>(N);
9594   SDValue Chain = ST->getChain();
9595   SDValue Value = ST->getValue();
9596   SDValue Ptr   = ST->getBasePtr();
9597
9598   // If this is a store of a bit convert, store the input value if the
9599   // resultant store does not need a higher alignment than the original.
9600   if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
9601       ST->isUnindexed()) {
9602     unsigned OrigAlign = ST->getAlignment();
9603     EVT SVT = Value.getOperand(0).getValueType();
9604     unsigned Align = TLI.getDataLayout()->
9605       getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
9606     if (Align <= OrigAlign &&
9607         ((!LegalOperations && !ST->isVolatile()) ||
9608          TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
9609       return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
9610                           Ptr, ST->getPointerInfo(), ST->isVolatile(),
9611                           ST->isNonTemporal(), OrigAlign,
9612                           ST->getAAInfo());
9613   }
9614
9615   // Turn 'store undef, Ptr' -> nothing.
9616   if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
9617     return Chain;
9618
9619   // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
9620   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
9621     // NOTE: If the original store is volatile, this transform must not increase
9622     // the number of stores.  For example, on x86-32 an f64 can be stored in one
9623     // processor operation but an i64 (which is not legal) requires two.  So the
9624     // transform should not be done in this case.
9625     if (Value.getOpcode() != ISD::TargetConstantFP) {
9626       SDValue Tmp;
9627       switch (CFP->getSimpleValueType(0).SimpleTy) {
9628       default: llvm_unreachable("Unknown FP type");
9629       case MVT::f16:    // We don't do this for these yet.
9630       case MVT::f80:
9631       case MVT::f128:
9632       case MVT::ppcf128:
9633         break;
9634       case MVT::f32:
9635         if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
9636             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
9637           Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
9638                               bitcastToAPInt().getZExtValue(), MVT::i32);
9639           return DAG.getStore(Chain, SDLoc(N), Tmp,
9640                               Ptr, ST->getMemOperand());
9641         }
9642         break;
9643       case MVT::f64:
9644         if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
9645              !ST->isVolatile()) ||
9646             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
9647           Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
9648                                 getZExtValue(), MVT::i64);
9649           return DAG.getStore(Chain, SDLoc(N), Tmp,
9650                               Ptr, ST->getMemOperand());
9651         }
9652
9653         if (!ST->isVolatile() &&
9654             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
9655           // Many FP stores are not made apparent until after legalize, e.g. for
9656           // argument passing.  Since this is so common, custom legalize the
9657           // 64-bit integer store into two 32-bit stores.
9658           uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
9659           SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
9660           SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
9661           if (TLI.isBigEndian()) std::swap(Lo, Hi);
9662
9663           unsigned Alignment = ST->getAlignment();
9664           bool isVolatile = ST->isVolatile();
9665           bool isNonTemporal = ST->isNonTemporal();
9666           AAMDNodes AAInfo = ST->getAAInfo();
9667
9668           SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
9669                                      Ptr, ST->getPointerInfo(),
9670                                      isVolatile, isNonTemporal,
9671                                      ST->getAlignment(), AAInfo);
9672           Ptr = DAG.getNode(ISD::ADD, SDLoc(N), Ptr.getValueType(), Ptr,
9673                             DAG.getConstant(4, Ptr.getValueType()));
9674           Alignment = MinAlign(Alignment, 4U);
9675           SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
9676                                      Ptr, ST->getPointerInfo().getWithOffset(4),
9677                                      isVolatile, isNonTemporal,
9678                                      Alignment, AAInfo);
9679           return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
9680                              St0, St1);
9681         }
9682
9683         break;
9684       }
9685     }
9686   }
9687
9688   // Try to infer better alignment information than the store already has.
9689   if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
9690     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
9691       if (Align > ST->getAlignment())
9692         return DAG.getTruncStore(Chain, SDLoc(N), Value,
9693                                  Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
9694                                  ST->isVolatile(), ST->isNonTemporal(), Align,
9695                                  ST->getAAInfo());
9696     }
9697   }
9698
9699   // Try transforming a pair floating point load / store ops to integer
9700   // load / store ops.
9701   SDValue NewST = TransformFPLoadStorePair(N);
9702   if (NewST.getNode())
9703     return NewST;
9704
9705   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
9706     TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
9707 #ifndef NDEBUG
9708   if (CombinerAAOnlyFunc.getNumOccurrences() &&
9709       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
9710     UseAA = false;
9711 #endif
9712   if (UseAA && ST->isUnindexed()) {
9713     // Walk up chain skipping non-aliasing memory nodes.
9714     SDValue BetterChain = FindBetterChain(N, Chain);
9715
9716     // If there is a better chain.
9717     if (Chain != BetterChain) {
9718       SDValue ReplStore;
9719
9720       // Replace the chain to avoid dependency.
9721       if (ST->isTruncatingStore()) {
9722         ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
9723                                       ST->getMemoryVT(), ST->getMemOperand());
9724       } else {
9725         ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
9726                                  ST->getMemOperand());
9727       }
9728
9729       // Create token to keep both nodes around.
9730       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
9731                                   MVT::Other, Chain, ReplStore);
9732
9733       // Make sure the new and old chains are cleaned up.
9734       AddToWorklist(Token.getNode());
9735
9736       // Don't add users to work list.
9737       return CombineTo(N, Token, false);
9738     }
9739   }
9740
9741   // Try transforming N to an indexed store.
9742   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
9743     return SDValue(N, 0);
9744
9745   // FIXME: is there such a thing as a truncating indexed store?
9746   if (ST->isTruncatingStore() && ST->isUnindexed() &&
9747       Value.getValueType().isInteger()) {
9748     // See if we can simplify the input to this truncstore with knowledge that
9749     // only the low bits are being used.  For example:
9750     // "truncstore (or (shl x, 8), y), i8"  -> "truncstore y, i8"
9751     SDValue Shorter =
9752       GetDemandedBits(Value,
9753                       APInt::getLowBitsSet(
9754                         Value.getValueType().getScalarType().getSizeInBits(),
9755                         ST->getMemoryVT().getScalarType().getSizeInBits()));
9756     AddToWorklist(Value.getNode());
9757     if (Shorter.getNode())
9758       return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
9759                                Ptr, ST->getMemoryVT(), ST->getMemOperand());
9760
9761     // Otherwise, see if we can simplify the operation with
9762     // SimplifyDemandedBits, which only works if the value has a single use.
9763     if (SimplifyDemandedBits(Value,
9764                         APInt::getLowBitsSet(
9765                           Value.getValueType().getScalarType().getSizeInBits(),
9766                           ST->getMemoryVT().getScalarType().getSizeInBits())))
9767       return SDValue(N, 0);
9768   }
9769
9770   // If this is a load followed by a store to the same location, then the store
9771   // is dead/noop.
9772   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
9773     if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
9774         ST->isUnindexed() && !ST->isVolatile() &&
9775         // There can't be any side effects between the load and store, such as
9776         // a call or store.
9777         Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
9778       // The store is dead, remove it.
9779       return Chain;
9780     }
9781   }
9782
9783   // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
9784   // truncating store.  We can do this even if this is already a truncstore.
9785   if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
9786       && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
9787       TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
9788                             ST->getMemoryVT())) {
9789     return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
9790                              Ptr, ST->getMemoryVT(), ST->getMemOperand());
9791   }
9792
9793   // Only perform this optimization before the types are legal, because we
9794   // don't want to perform this optimization on every DAGCombine invocation.
9795   if (!LegalTypes) {
9796     bool EverChanged = false;
9797
9798     do {
9799       // There can be multiple store sequences on the same chain.
9800       // Keep trying to merge store sequences until we are unable to do so
9801       // or until we merge the last store on the chain.
9802       bool Changed = MergeConsecutiveStores(ST);
9803       EverChanged |= Changed;
9804       if (!Changed) break;
9805     } while (ST->getOpcode() != ISD::DELETED_NODE);
9806
9807     if (EverChanged)
9808       return SDValue(N, 0);
9809   }
9810
9811   return ReduceLoadOpStoreWidth(N);
9812 }
9813
9814 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
9815   SDValue InVec = N->getOperand(0);
9816   SDValue InVal = N->getOperand(1);
9817   SDValue EltNo = N->getOperand(2);
9818   SDLoc dl(N);
9819
9820   // If the inserted element is an UNDEF, just use the input vector.
9821   if (InVal.getOpcode() == ISD::UNDEF)
9822     return InVec;
9823
9824   EVT VT = InVec.getValueType();
9825
9826   // If we can't generate a legal BUILD_VECTOR, exit
9827   if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
9828     return SDValue();
9829
9830   // Check that we know which element is being inserted
9831   if (!isa<ConstantSDNode>(EltNo))
9832     return SDValue();
9833   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9834
9835   // Canonicalize insert_vector_elt dag nodes.
9836   // Example:
9837   // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
9838   // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
9839   //
9840   // Do this only if the child insert_vector node has one use; also
9841   // do this only if indices are both constants and Idx1 < Idx0.
9842   if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
9843       && isa<ConstantSDNode>(InVec.getOperand(2))) {
9844     unsigned OtherElt =
9845       cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue();
9846     if (Elt < OtherElt) {
9847       // Swap nodes.
9848       SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT,
9849                                   InVec.getOperand(0), InVal, EltNo);
9850       AddToWorklist(NewOp.getNode());
9851       return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
9852                          VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
9853     }
9854   }
9855
9856   // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
9857   // be converted to a BUILD_VECTOR).  Fill in the Ops vector with the
9858   // vector elements.
9859   SmallVector<SDValue, 8> Ops;
9860   // Do not combine these two vectors if the output vector will not replace
9861   // the input vector.
9862   if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
9863     Ops.append(InVec.getNode()->op_begin(),
9864                InVec.getNode()->op_end());
9865   } else if (InVec.getOpcode() == ISD::UNDEF) {
9866     unsigned NElts = VT.getVectorNumElements();
9867     Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
9868   } else {
9869     return SDValue();
9870   }
9871
9872   // Insert the element
9873   if (Elt < Ops.size()) {
9874     // All the operands of BUILD_VECTOR must have the same type;
9875     // we enforce that here.
9876     EVT OpVT = Ops[0].getValueType();
9877     if (InVal.getValueType() != OpVT)
9878       InVal = OpVT.bitsGT(InVal.getValueType()) ?
9879                 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
9880                 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
9881     Ops[Elt] = InVal;
9882   }
9883
9884   // Return the new vector
9885   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
9886 }
9887
9888 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
9889     SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) {
9890   EVT ResultVT = EVE->getValueType(0);
9891   EVT VecEltVT = InVecVT.getVectorElementType();
9892   unsigned Align = OriginalLoad->getAlignment();
9893   unsigned NewAlign = TLI.getDataLayout()->getABITypeAlignment(
9894       VecEltVT.getTypeForEVT(*DAG.getContext()));
9895
9896   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
9897     return SDValue();
9898
9899   Align = NewAlign;
9900
9901   SDValue NewPtr = OriginalLoad->getBasePtr();
9902   SDValue Offset;
9903   EVT PtrType = NewPtr.getValueType();
9904   MachinePointerInfo MPI;
9905   if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
9906     int Elt = ConstEltNo->getZExtValue();
9907     unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
9908     if (TLI.isBigEndian())
9909       PtrOff = InVecVT.getSizeInBits() / 8 - PtrOff;
9910     Offset = DAG.getConstant(PtrOff, PtrType);
9911     MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
9912   } else {
9913     Offset = DAG.getNode(
9914         ISD::MUL, SDLoc(EVE), EltNo.getValueType(), EltNo,
9915         DAG.getConstant(VecEltVT.getStoreSize(), EltNo.getValueType()));
9916     if (TLI.isBigEndian())
9917       Offset = DAG.getNode(
9918           ISD::SUB, SDLoc(EVE), EltNo.getValueType(),
9919           DAG.getConstant(InVecVT.getStoreSize(), EltNo.getValueType()), Offset);
9920     MPI = OriginalLoad->getPointerInfo();
9921   }
9922   NewPtr = DAG.getNode(ISD::ADD, SDLoc(EVE), PtrType, NewPtr, Offset);
9923
9924   // The replacement we need to do here is a little tricky: we need to
9925   // replace an extractelement of a load with a load.
9926   // Use ReplaceAllUsesOfValuesWith to do the replacement.
9927   // Note that this replacement assumes that the extractvalue is the only
9928   // use of the load; that's okay because we don't want to perform this
9929   // transformation in other cases anyway.
9930   SDValue Load;
9931   SDValue Chain;
9932   if (ResultVT.bitsGT(VecEltVT)) {
9933     // If the result type of vextract is wider than the load, then issue an
9934     // extending load instead.
9935     ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, VecEltVT)
9936                                    ? ISD::ZEXTLOAD
9937                                    : ISD::EXTLOAD;
9938     Load = DAG.getExtLoad(
9939         ExtType, SDLoc(EVE), ResultVT, OriginalLoad->getChain(), NewPtr, MPI,
9940         VecEltVT, OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
9941         OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
9942     Chain = Load.getValue(1);
9943   } else {
9944     Load = DAG.getLoad(
9945         VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, MPI,
9946         OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
9947         OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
9948     Chain = Load.getValue(1);
9949     if (ResultVT.bitsLT(VecEltVT))
9950       Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
9951     else
9952       Load = DAG.getNode(ISD::BITCAST, SDLoc(EVE), ResultVT, Load);
9953   }
9954   WorklistRemover DeadNodes(*this);
9955   SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
9956   SDValue To[] = { Load, Chain };
9957   DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
9958   // Since we're explicitly calling ReplaceAllUses, add the new node to the
9959   // worklist explicitly as well.
9960   AddToWorklist(Load.getNode());
9961   AddUsersToWorklist(Load.getNode()); // Add users too
9962   // Make sure to revisit this node to clean it up; it will usually be dead.
9963   AddToWorklist(EVE);
9964   ++OpsNarrowed;
9965   return SDValue(EVE, 0);
9966 }
9967
9968 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
9969   // (vextract (scalar_to_vector val, 0) -> val
9970   SDValue InVec = N->getOperand(0);
9971   EVT VT = InVec.getValueType();
9972   EVT NVT = N->getValueType(0);
9973
9974   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
9975     // Check if the result type doesn't match the inserted element type. A
9976     // SCALAR_TO_VECTOR may truncate the inserted element and the
9977     // EXTRACT_VECTOR_ELT may widen the extracted vector.
9978     SDValue InOp = InVec.getOperand(0);
9979     if (InOp.getValueType() != NVT) {
9980       assert(InOp.getValueType().isInteger() && NVT.isInteger());
9981       return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
9982     }
9983     return InOp;
9984   }
9985
9986   SDValue EltNo = N->getOperand(1);
9987   bool ConstEltNo = isa<ConstantSDNode>(EltNo);
9988
9989   // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
9990   // We only perform this optimization before the op legalization phase because
9991   // we may introduce new vector instructions which are not backed by TD
9992   // patterns. For example on AVX, extracting elements from a wide vector
9993   // without using extract_subvector. However, if we can find an underlying
9994   // scalar value, then we can always use that.
9995   if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
9996       && ConstEltNo) {
9997     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9998     int NumElem = VT.getVectorNumElements();
9999     ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
10000     // Find the new index to extract from.
10001     int OrigElt = SVOp->getMaskElt(Elt);
10002
10003     // Extracting an undef index is undef.
10004     if (OrigElt == -1)
10005       return DAG.getUNDEF(NVT);
10006
10007     // Select the right vector half to extract from.
10008     SDValue SVInVec;
10009     if (OrigElt < NumElem) {
10010       SVInVec = InVec->getOperand(0);
10011     } else {
10012       SVInVec = InVec->getOperand(1);
10013       OrigElt -= NumElem;
10014     }
10015
10016     if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
10017       SDValue InOp = SVInVec.getOperand(OrigElt);
10018       if (InOp.getValueType() != NVT) {
10019         assert(InOp.getValueType().isInteger() && NVT.isInteger());
10020         InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
10021       }
10022
10023       return InOp;
10024     }
10025
10026     // FIXME: We should handle recursing on other vector shuffles and
10027     // scalar_to_vector here as well.
10028
10029     if (!LegalOperations) {
10030       EVT IndexTy = TLI.getVectorIdxTy();
10031       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT,
10032                          SVInVec, DAG.getConstant(OrigElt, IndexTy));
10033     }
10034   }
10035
10036   bool BCNumEltsChanged = false;
10037   EVT ExtVT = VT.getVectorElementType();
10038   EVT LVT = ExtVT;
10039
10040   // If the result of load has to be truncated, then it's not necessarily
10041   // profitable.
10042   if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
10043     return SDValue();
10044
10045   if (InVec.getOpcode() == ISD::BITCAST) {
10046     // Don't duplicate a load with other uses.
10047     if (!InVec.hasOneUse())
10048       return SDValue();
10049
10050     EVT BCVT = InVec.getOperand(0).getValueType();
10051     if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
10052       return SDValue();
10053     if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
10054       BCNumEltsChanged = true;
10055     InVec = InVec.getOperand(0);
10056     ExtVT = BCVT.getVectorElementType();
10057   }
10058
10059   // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size)
10060   if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() &&
10061       ISD::isNormalLoad(InVec.getNode()) &&
10062       !N->getOperand(1)->hasPredecessor(InVec.getNode())) {
10063     SDValue Index = N->getOperand(1);
10064     if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec))
10065       return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index,
10066                                                            OrigLoad);
10067   }
10068
10069   // Perform only after legalization to ensure build_vector / vector_shuffle
10070   // optimizations have already been done.
10071   if (!LegalOperations) return SDValue();
10072
10073   // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
10074   // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
10075   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
10076
10077   if (ConstEltNo) {
10078     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
10079
10080     LoadSDNode *LN0 = nullptr;
10081     const ShuffleVectorSDNode *SVN = nullptr;
10082     if (ISD::isNormalLoad(InVec.getNode())) {
10083       LN0 = cast<LoadSDNode>(InVec);
10084     } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
10085                InVec.getOperand(0).getValueType() == ExtVT &&
10086                ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
10087       // Don't duplicate a load with other uses.
10088       if (!InVec.hasOneUse())
10089         return SDValue();
10090
10091       LN0 = cast<LoadSDNode>(InVec.getOperand(0));
10092     } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
10093       // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
10094       // =>
10095       // (load $addr+1*size)
10096
10097       // Don't duplicate a load with other uses.
10098       if (!InVec.hasOneUse())
10099         return SDValue();
10100
10101       // If the bit convert changed the number of elements, it is unsafe
10102       // to examine the mask.
10103       if (BCNumEltsChanged)
10104         return SDValue();
10105
10106       // Select the input vector, guarding against out of range extract vector.
10107       unsigned NumElems = VT.getVectorNumElements();
10108       int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
10109       InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
10110
10111       if (InVec.getOpcode() == ISD::BITCAST) {
10112         // Don't duplicate a load with other uses.
10113         if (!InVec.hasOneUse())
10114           return SDValue();
10115
10116         InVec = InVec.getOperand(0);
10117       }
10118       if (ISD::isNormalLoad(InVec.getNode())) {
10119         LN0 = cast<LoadSDNode>(InVec);
10120         Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
10121         EltNo = DAG.getConstant(Elt, EltNo.getValueType());
10122       }
10123     }
10124
10125     // Make sure we found a non-volatile load and the extractelement is
10126     // the only use.
10127     if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
10128       return SDValue();
10129
10130     // If Idx was -1 above, Elt is going to be -1, so just return undef.
10131     if (Elt == -1)
10132       return DAG.getUNDEF(LVT);
10133
10134     return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0);
10135   }
10136
10137   return SDValue();
10138 }
10139
10140 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
10141 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
10142   // We perform this optimization post type-legalization because
10143   // the type-legalizer often scalarizes integer-promoted vectors.
10144   // Performing this optimization before may create bit-casts which
10145   // will be type-legalized to complex code sequences.
10146   // We perform this optimization only before the operation legalizer because we
10147   // may introduce illegal operations.
10148   if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
10149     return SDValue();
10150
10151   unsigned NumInScalars = N->getNumOperands();
10152   SDLoc dl(N);
10153   EVT VT = N->getValueType(0);
10154
10155   // Check to see if this is a BUILD_VECTOR of a bunch of values
10156   // which come from any_extend or zero_extend nodes. If so, we can create
10157   // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
10158   // optimizations. We do not handle sign-extend because we can't fill the sign
10159   // using shuffles.
10160   EVT SourceType = MVT::Other;
10161   bool AllAnyExt = true;
10162
10163   for (unsigned i = 0; i != NumInScalars; ++i) {
10164     SDValue In = N->getOperand(i);
10165     // Ignore undef inputs.
10166     if (In.getOpcode() == ISD::UNDEF) continue;
10167
10168     bool AnyExt  = In.getOpcode() == ISD::ANY_EXTEND;
10169     bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
10170
10171     // Abort if the element is not an extension.
10172     if (!ZeroExt && !AnyExt) {
10173       SourceType = MVT::Other;
10174       break;
10175     }
10176
10177     // The input is a ZeroExt or AnyExt. Check the original type.
10178     EVT InTy = In.getOperand(0).getValueType();
10179
10180     // Check that all of the widened source types are the same.
10181     if (SourceType == MVT::Other)
10182       // First time.
10183       SourceType = InTy;
10184     else if (InTy != SourceType) {
10185       // Multiple income types. Abort.
10186       SourceType = MVT::Other;
10187       break;
10188     }
10189
10190     // Check if all of the extends are ANY_EXTENDs.
10191     AllAnyExt &= AnyExt;
10192   }
10193
10194   // In order to have valid types, all of the inputs must be extended from the
10195   // same source type and all of the inputs must be any or zero extend.
10196   // Scalar sizes must be a power of two.
10197   EVT OutScalarTy = VT.getScalarType();
10198   bool ValidTypes = SourceType != MVT::Other &&
10199                  isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
10200                  isPowerOf2_32(SourceType.getSizeInBits());
10201
10202   // Create a new simpler BUILD_VECTOR sequence which other optimizations can
10203   // turn into a single shuffle instruction.
10204   if (!ValidTypes)
10205     return SDValue();
10206
10207   bool isLE = TLI.isLittleEndian();
10208   unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
10209   assert(ElemRatio > 1 && "Invalid element size ratio");
10210   SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
10211                                DAG.getConstant(0, SourceType);
10212
10213   unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
10214   SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
10215
10216   // Populate the new build_vector
10217   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
10218     SDValue Cast = N->getOperand(i);
10219     assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
10220             Cast.getOpcode() == ISD::ZERO_EXTEND ||
10221             Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
10222     SDValue In;
10223     if (Cast.getOpcode() == ISD::UNDEF)
10224       In = DAG.getUNDEF(SourceType);
10225     else
10226       In = Cast->getOperand(0);
10227     unsigned Index = isLE ? (i * ElemRatio) :
10228                             (i * ElemRatio + (ElemRatio - 1));
10229
10230     assert(Index < Ops.size() && "Invalid index");
10231     Ops[Index] = In;
10232   }
10233
10234   // The type of the new BUILD_VECTOR node.
10235   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
10236   assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
10237          "Invalid vector size");
10238   // Check if the new vector type is legal.
10239   if (!isTypeLegal(VecVT)) return SDValue();
10240
10241   // Make the new BUILD_VECTOR.
10242   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
10243
10244   // The new BUILD_VECTOR node has the potential to be further optimized.
10245   AddToWorklist(BV.getNode());
10246   // Bitcast to the desired type.
10247   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
10248 }
10249
10250 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
10251   EVT VT = N->getValueType(0);
10252
10253   unsigned NumInScalars = N->getNumOperands();
10254   SDLoc dl(N);
10255
10256   EVT SrcVT = MVT::Other;
10257   unsigned Opcode = ISD::DELETED_NODE;
10258   unsigned NumDefs = 0;
10259
10260   for (unsigned i = 0; i != NumInScalars; ++i) {
10261     SDValue In = N->getOperand(i);
10262     unsigned Opc = In.getOpcode();
10263
10264     if (Opc == ISD::UNDEF)
10265       continue;
10266
10267     // If all scalar values are floats and converted from integers.
10268     if (Opcode == ISD::DELETED_NODE &&
10269         (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
10270       Opcode = Opc;
10271     }
10272
10273     if (Opc != Opcode)
10274       return SDValue();
10275
10276     EVT InVT = In.getOperand(0).getValueType();
10277
10278     // If all scalar values are typed differently, bail out. It's chosen to
10279     // simplify BUILD_VECTOR of integer types.
10280     if (SrcVT == MVT::Other)
10281       SrcVT = InVT;
10282     if (SrcVT != InVT)
10283       return SDValue();
10284     NumDefs++;
10285   }
10286
10287   // If the vector has just one element defined, it's not worth to fold it into
10288   // a vectorized one.
10289   if (NumDefs < 2)
10290     return SDValue();
10291
10292   assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
10293          && "Should only handle conversion from integer to float.");
10294   assert(SrcVT != MVT::Other && "Cannot determine source type!");
10295
10296   EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
10297
10298   if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
10299     return SDValue();
10300
10301   SmallVector<SDValue, 8> Opnds;
10302   for (unsigned i = 0; i != NumInScalars; ++i) {
10303     SDValue In = N->getOperand(i);
10304
10305     if (In.getOpcode() == ISD::UNDEF)
10306       Opnds.push_back(DAG.getUNDEF(SrcVT));
10307     else
10308       Opnds.push_back(In.getOperand(0));
10309   }
10310   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds);
10311   AddToWorklist(BV.getNode());
10312
10313   return DAG.getNode(Opcode, dl, VT, BV);
10314 }
10315
10316 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
10317   unsigned NumInScalars = N->getNumOperands();
10318   SDLoc dl(N);
10319   EVT VT = N->getValueType(0);
10320
10321   // A vector built entirely of undefs is undef.
10322   if (ISD::allOperandsUndef(N))
10323     return DAG.getUNDEF(VT);
10324
10325   SDValue V = reduceBuildVecExtToExtBuildVec(N);
10326   if (V.getNode())
10327     return V;
10328
10329   V = reduceBuildVecConvertToConvertBuildVec(N);
10330   if (V.getNode())
10331     return V;
10332
10333   // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
10334   // operations.  If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
10335   // at most two distinct vectors, turn this into a shuffle node.
10336
10337   // May only combine to shuffle after legalize if shuffle is legal.
10338   if (LegalOperations &&
10339       !TLI.isOperationLegalOrCustom(ISD::VECTOR_SHUFFLE, VT))
10340     return SDValue();
10341
10342   SDValue VecIn1, VecIn2;
10343   for (unsigned i = 0; i != NumInScalars; ++i) {
10344     // Ignore undef inputs.
10345     if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
10346
10347     // If this input is something other than a EXTRACT_VECTOR_ELT with a
10348     // constant index, bail out.
10349     if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10350         !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) {
10351       VecIn1 = VecIn2 = SDValue(nullptr, 0);
10352       break;
10353     }
10354
10355     // We allow up to two distinct input vectors.
10356     SDValue ExtractedFromVec = N->getOperand(i).getOperand(0);
10357     if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
10358       continue;
10359
10360     if (!VecIn1.getNode()) {
10361       VecIn1 = ExtractedFromVec;
10362     } else if (!VecIn2.getNode()) {
10363       VecIn2 = ExtractedFromVec;
10364     } else {
10365       // Too many inputs.
10366       VecIn1 = VecIn2 = SDValue(nullptr, 0);
10367       break;
10368     }
10369   }
10370
10371   // If everything is good, we can make a shuffle operation.
10372   if (VecIn1.getNode()) {
10373     SmallVector<int, 8> Mask;
10374     for (unsigned i = 0; i != NumInScalars; ++i) {
10375       if (N->getOperand(i).getOpcode() == ISD::UNDEF) {
10376         Mask.push_back(-1);
10377         continue;
10378       }
10379
10380       // If extracting from the first vector, just use the index directly.
10381       SDValue Extract = N->getOperand(i);
10382       SDValue ExtVal = Extract.getOperand(1);
10383       if (Extract.getOperand(0) == VecIn1) {
10384         unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
10385         if (ExtIndex > VT.getVectorNumElements())
10386           return SDValue();
10387
10388         Mask.push_back(ExtIndex);
10389         continue;
10390       }
10391
10392       // Otherwise, use InIdx + VecSize
10393       unsigned Idx = cast<ConstantSDNode>(ExtVal)->getZExtValue();
10394       Mask.push_back(Idx+NumInScalars);
10395     }
10396
10397     // We can't generate a shuffle node with mismatched input and output types.
10398     // Attempt to transform a single input vector to the correct type.
10399     if ((VT != VecIn1.getValueType())) {
10400       // We don't support shuffeling between TWO values of different types.
10401       if (VecIn2.getNode())
10402         return SDValue();
10403
10404       // We only support widening of vectors which are half the size of the
10405       // output registers. For example XMM->YMM widening on X86 with AVX.
10406       if (VecIn1.getValueType().getSizeInBits()*2 != VT.getSizeInBits())
10407         return SDValue();
10408
10409       // If the input vector type has a different base type to the output
10410       // vector type, bail out.
10411       if (VecIn1.getValueType().getVectorElementType() !=
10412           VT.getVectorElementType())
10413         return SDValue();
10414
10415       // Widen the input vector by adding undef values.
10416       VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10417                            VecIn1, DAG.getUNDEF(VecIn1.getValueType()));
10418     }
10419
10420     // If VecIn2 is unused then change it to undef.
10421     VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
10422
10423     // Check that we were able to transform all incoming values to the same
10424     // type.
10425     if (VecIn2.getValueType() != VecIn1.getValueType() ||
10426         VecIn1.getValueType() != VT)
10427           return SDValue();
10428
10429     // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
10430     if (!isTypeLegal(VT))
10431       return SDValue();
10432
10433     // Return the new VECTOR_SHUFFLE node.
10434     SDValue Ops[2];
10435     Ops[0] = VecIn1;
10436     Ops[1] = VecIn2;
10437     return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
10438   }
10439
10440   return SDValue();
10441 }
10442
10443 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
10444   // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
10445   // EXTRACT_SUBVECTOR operations.  If so, and if the EXTRACT_SUBVECTOR vector
10446   // inputs come from at most two distinct vectors, turn this into a shuffle
10447   // node.
10448
10449   // If we only have one input vector, we don't need to do any concatenation.
10450   if (N->getNumOperands() == 1)
10451     return N->getOperand(0);
10452
10453   // Check if all of the operands are undefs.
10454   EVT VT = N->getValueType(0);
10455   if (ISD::allOperandsUndef(N))
10456     return DAG.getUNDEF(VT);
10457
10458   // Optimize concat_vectors where one of the vectors is undef.
10459   if (N->getNumOperands() == 2 &&
10460       N->getOperand(1)->getOpcode() == ISD::UNDEF) {
10461     SDValue In = N->getOperand(0);
10462     assert(In.getValueType().isVector() && "Must concat vectors");
10463
10464     // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
10465     if (In->getOpcode() == ISD::BITCAST &&
10466         !In->getOperand(0)->getValueType(0).isVector()) {
10467       SDValue Scalar = In->getOperand(0);
10468       EVT SclTy = Scalar->getValueType(0);
10469
10470       if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
10471         return SDValue();
10472
10473       EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
10474                                  VT.getSizeInBits() / SclTy.getSizeInBits());
10475       if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
10476         return SDValue();
10477
10478       SDLoc dl = SDLoc(N);
10479       SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
10480       return DAG.getNode(ISD::BITCAST, dl, VT, Res);
10481     }
10482   }
10483
10484   // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
10485   // -> (BUILD_VECTOR A, B, ..., C, D, ...)
10486   if (N->getNumOperands() == 2 &&
10487       N->getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
10488       N->getOperand(1).getOpcode() == ISD::BUILD_VECTOR) {
10489     EVT VT = N->getValueType(0);
10490     SDValue N0 = N->getOperand(0);
10491     SDValue N1 = N->getOperand(1);
10492     SmallVector<SDValue, 8> Opnds;
10493     unsigned BuildVecNumElts =  N0.getNumOperands();
10494
10495     EVT SclTy0 = N0.getOperand(0)->getValueType(0);
10496     EVT SclTy1 = N1.getOperand(0)->getValueType(0);
10497     if (SclTy0.isFloatingPoint()) {
10498       for (unsigned i = 0; i != BuildVecNumElts; ++i)
10499         Opnds.push_back(N0.getOperand(i));
10500       for (unsigned i = 0; i != BuildVecNumElts; ++i)
10501         Opnds.push_back(N1.getOperand(i));
10502     } else {
10503       // If BUILD_VECTOR are from built from integer, they may have different
10504       // operand types. Get the smaller type and truncate all operands to it.
10505       EVT MinTy = SclTy0.bitsLE(SclTy1) ? SclTy0 : SclTy1;
10506       for (unsigned i = 0; i != BuildVecNumElts; ++i)
10507         Opnds.push_back(DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinTy,
10508                         N0.getOperand(i)));
10509       for (unsigned i = 0; i != BuildVecNumElts; ++i)
10510         Opnds.push_back(DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinTy,
10511                         N1.getOperand(i)));
10512     }
10513
10514     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
10515   }
10516
10517   // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
10518   // nodes often generate nop CONCAT_VECTOR nodes.
10519   // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
10520   // place the incoming vectors at the exact same location.
10521   SDValue SingleSource = SDValue();
10522   unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
10523
10524   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
10525     SDValue Op = N->getOperand(i);
10526
10527     if (Op.getOpcode() == ISD::UNDEF)
10528       continue;
10529
10530     // Check if this is the identity extract:
10531     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
10532       return SDValue();
10533
10534     // Find the single incoming vector for the extract_subvector.
10535     if (SingleSource.getNode()) {
10536       if (Op.getOperand(0) != SingleSource)
10537         return SDValue();
10538     } else {
10539       SingleSource = Op.getOperand(0);
10540
10541       // Check the source type is the same as the type of the result.
10542       // If not, this concat may extend the vector, so we can not
10543       // optimize it away.
10544       if (SingleSource.getValueType() != N->getValueType(0))
10545         return SDValue();
10546     }
10547
10548     unsigned IdentityIndex = i * PartNumElem;
10549     ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
10550     // The extract index must be constant.
10551     if (!CS)
10552       return SDValue();
10553
10554     // Check that we are reading from the identity index.
10555     if (CS->getZExtValue() != IdentityIndex)
10556       return SDValue();
10557   }
10558
10559   if (SingleSource.getNode())
10560     return SingleSource;
10561
10562   return SDValue();
10563 }
10564
10565 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
10566   EVT NVT = N->getValueType(0);
10567   SDValue V = N->getOperand(0);
10568
10569   if (V->getOpcode() == ISD::CONCAT_VECTORS) {
10570     // Combine:
10571     //    (extract_subvec (concat V1, V2, ...), i)
10572     // Into:
10573     //    Vi if possible
10574     // Only operand 0 is checked as 'concat' assumes all inputs of the same
10575     // type.
10576     if (V->getOperand(0).getValueType() != NVT)
10577       return SDValue();
10578     unsigned Idx = dyn_cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
10579     unsigned NumElems = NVT.getVectorNumElements();
10580     assert((Idx % NumElems) == 0 &&
10581            "IDX in concat is not a multiple of the result vector length.");
10582     return V->getOperand(Idx / NumElems);
10583   }
10584
10585   // Skip bitcasting
10586   if (V->getOpcode() == ISD::BITCAST)
10587     V = V.getOperand(0);
10588
10589   if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
10590     SDLoc dl(N);
10591     // Handle only simple case where vector being inserted and vector
10592     // being extracted are of same type, and are half size of larger vectors.
10593     EVT BigVT = V->getOperand(0).getValueType();
10594     EVT SmallVT = V->getOperand(1).getValueType();
10595     if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
10596       return SDValue();
10597
10598     // Only handle cases where both indexes are constants with the same type.
10599     ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
10600     ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
10601
10602     if (InsIdx && ExtIdx &&
10603         InsIdx->getValueType(0).getSizeInBits() <= 64 &&
10604         ExtIdx->getValueType(0).getSizeInBits() <= 64) {
10605       // Combine:
10606       //    (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
10607       // Into:
10608       //    indices are equal or bit offsets are equal => V1
10609       //    otherwise => (extract_subvec V1, ExtIdx)
10610       if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
10611           ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
10612         return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
10613       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
10614                          DAG.getNode(ISD::BITCAST, dl,
10615                                      N->getOperand(0).getValueType(),
10616                                      V->getOperand(0)), N->getOperand(1));
10617     }
10618   }
10619
10620   return SDValue();
10621 }
10622
10623 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat.
10624 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
10625   EVT VT = N->getValueType(0);
10626   unsigned NumElts = VT.getVectorNumElements();
10627
10628   SDValue N0 = N->getOperand(0);
10629   SDValue N1 = N->getOperand(1);
10630   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10631
10632   SmallVector<SDValue, 4> Ops;
10633   EVT ConcatVT = N0.getOperand(0).getValueType();
10634   unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
10635   unsigned NumConcats = NumElts / NumElemsPerConcat;
10636
10637   // Look at every vector that's inserted. We're looking for exact
10638   // subvector-sized copies from a concatenated vector
10639   for (unsigned I = 0; I != NumConcats; ++I) {
10640     // Make sure we're dealing with a copy.
10641     unsigned Begin = I * NumElemsPerConcat;
10642     bool AllUndef = true, NoUndef = true;
10643     for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
10644       if (SVN->getMaskElt(J) >= 0)
10645         AllUndef = false;
10646       else
10647         NoUndef = false;
10648     }
10649
10650     if (NoUndef) {
10651       if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
10652         return SDValue();
10653
10654       for (unsigned J = 1; J != NumElemsPerConcat; ++J)
10655         if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
10656           return SDValue();
10657
10658       unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
10659       if (FirstElt < N0.getNumOperands())
10660         Ops.push_back(N0.getOperand(FirstElt));
10661       else
10662         Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
10663
10664     } else if (AllUndef) {
10665       Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
10666     } else { // Mixed with general masks and undefs, can't do optimization.
10667       return SDValue();
10668     }
10669   }
10670
10671   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
10672 }
10673
10674 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
10675   EVT VT = N->getValueType(0);
10676   unsigned NumElts = VT.getVectorNumElements();
10677
10678   SDValue N0 = N->getOperand(0);
10679   SDValue N1 = N->getOperand(1);
10680
10681   assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
10682
10683   // Canonicalize shuffle undef, undef -> undef
10684   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
10685     return DAG.getUNDEF(VT);
10686
10687   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10688
10689   // Canonicalize shuffle v, v -> v, undef
10690   if (N0 == N1) {
10691     SmallVector<int, 8> NewMask;
10692     for (unsigned i = 0; i != NumElts; ++i) {
10693       int Idx = SVN->getMaskElt(i);
10694       if (Idx >= (int)NumElts) Idx -= NumElts;
10695       NewMask.push_back(Idx);
10696     }
10697     return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
10698                                 &NewMask[0]);
10699   }
10700
10701   // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
10702   if (N0.getOpcode() == ISD::UNDEF) {
10703     SmallVector<int, 8> NewMask;
10704     for (unsigned i = 0; i != NumElts; ++i) {
10705       int Idx = SVN->getMaskElt(i);
10706       if (Idx >= 0) {
10707         if (Idx >= (int)NumElts)
10708           Idx -= NumElts;
10709         else
10710           Idx = -1; // remove reference to lhs
10711       }
10712       NewMask.push_back(Idx);
10713     }
10714     return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
10715                                 &NewMask[0]);
10716   }
10717
10718   // Remove references to rhs if it is undef
10719   if (N1.getOpcode() == ISD::UNDEF) {
10720     bool Changed = false;
10721     SmallVector<int, 8> NewMask;
10722     for (unsigned i = 0; i != NumElts; ++i) {
10723       int Idx = SVN->getMaskElt(i);
10724       if (Idx >= (int)NumElts) {
10725         Idx = -1;
10726         Changed = true;
10727       }
10728       NewMask.push_back(Idx);
10729     }
10730     if (Changed)
10731       return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
10732   }
10733
10734   // If it is a splat, check if the argument vector is another splat or a
10735   // build_vector with all scalar elements the same.
10736   if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
10737     SDNode *V = N0.getNode();
10738
10739     // If this is a bit convert that changes the element type of the vector but
10740     // not the number of vector elements, look through it.  Be careful not to
10741     // look though conversions that change things like v4f32 to v2f64.
10742     if (V->getOpcode() == ISD::BITCAST) {
10743       SDValue ConvInput = V->getOperand(0);
10744       if (ConvInput.getValueType().isVector() &&
10745           ConvInput.getValueType().getVectorNumElements() == NumElts)
10746         V = ConvInput.getNode();
10747     }
10748
10749     if (V->getOpcode() == ISD::BUILD_VECTOR) {
10750       assert(V->getNumOperands() == NumElts &&
10751              "BUILD_VECTOR has wrong number of operands");
10752       SDValue Base;
10753       bool AllSame = true;
10754       for (unsigned i = 0; i != NumElts; ++i) {
10755         if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
10756           Base = V->getOperand(i);
10757           break;
10758         }
10759       }
10760       // Splat of <u, u, u, u>, return <u, u, u, u>
10761       if (!Base.getNode())
10762         return N0;
10763       for (unsigned i = 0; i != NumElts; ++i) {
10764         if (V->getOperand(i) != Base) {
10765           AllSame = false;
10766           break;
10767         }
10768       }
10769       // Splat of <x, x, x, x>, return <x, x, x, x>
10770       if (AllSame)
10771         return N0;
10772     }
10773   }
10774
10775   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
10776       Level < AfterLegalizeVectorOps &&
10777       (N1.getOpcode() == ISD::UNDEF ||
10778       (N1.getOpcode() == ISD::CONCAT_VECTORS &&
10779        N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
10780     SDValue V = partitionShuffleOfConcats(N, DAG);
10781
10782     if (V.getNode())
10783       return V;
10784   }
10785
10786   // If this shuffle node is simply a swizzle of another shuffle node,
10787   // then try to simplify it.
10788   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
10789       N1.getOpcode() == ISD::UNDEF) {
10790
10791     ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
10792
10793     // The incoming shuffle must be of the same type as the result of the
10794     // current shuffle.
10795     assert(OtherSV->getOperand(0).getValueType() == VT &&
10796            "Shuffle types don't match");
10797
10798     SmallVector<int, 4> Mask;
10799     // Compute the combined shuffle mask.
10800     for (unsigned i = 0; i != NumElts; ++i) {
10801       int Idx = SVN->getMaskElt(i);
10802       assert(Idx < (int)NumElts && "Index references undef operand");
10803       // Next, this index comes from the first value, which is the incoming
10804       // shuffle. Adopt the incoming index.
10805       if (Idx >= 0)
10806         Idx = OtherSV->getMaskElt(Idx);
10807       Mask.push_back(Idx);
10808     }
10809
10810     // Check if all indices in Mask are Undef. In case, propagate Undef.
10811     bool isUndefMask = true;
10812     for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
10813       isUndefMask &= Mask[i] < 0;
10814
10815     if (isUndefMask)
10816       return DAG.getUNDEF(VT);
10817     
10818     bool CommuteOperands = false;
10819     if (N0.getOperand(1).getOpcode() != ISD::UNDEF) {
10820       // To be valid, the combine shuffle mask should only reference elements
10821       // from one of the two vectors in input to the inner shufflevector.
10822       bool IsValidMask = true;
10823       for (unsigned i = 0; i != NumElts && IsValidMask; ++i)
10824         // See if the combined mask only reference undefs or elements coming
10825         // from the first shufflevector operand.
10826         IsValidMask = Mask[i] < 0 || (unsigned)Mask[i] < NumElts;
10827
10828       if (!IsValidMask) {
10829         IsValidMask = true;
10830         for (unsigned i = 0; i != NumElts && IsValidMask; ++i)
10831           // Check that all the elements come from the second shuffle operand.
10832           IsValidMask = Mask[i] < 0 || (unsigned)Mask[i] >= NumElts;
10833         CommuteOperands = IsValidMask;
10834       }
10835
10836       // Early exit if the combined shuffle mask is not valid.
10837       if (!IsValidMask)
10838         return SDValue();
10839     }
10840
10841     // See if this pair of shuffles can be safely folded according to either
10842     // of the following rules:
10843     //   shuffle(shuffle(x, y), undef) -> x
10844     //   shuffle(shuffle(x, undef), undef) -> x
10845     //   shuffle(shuffle(x, y), undef) -> y
10846     bool IsIdentityMask = true;
10847     unsigned BaseMaskIndex = CommuteOperands ? NumElts : 0;
10848     for (unsigned i = 0; i != NumElts && IsIdentityMask; ++i) {
10849       // Skip Undefs.
10850       if (Mask[i] < 0)
10851         continue;
10852
10853       // The combined shuffle must map each index to itself.
10854       IsIdentityMask = (unsigned)Mask[i] == i + BaseMaskIndex;
10855     }
10856     
10857     if (IsIdentityMask) {
10858       if (CommuteOperands)
10859         // optimize shuffle(shuffle(x, y), undef) -> y.
10860         return OtherSV->getOperand(1);
10861       
10862       // optimize shuffle(shuffle(x, undef), undef) -> x
10863       // optimize shuffle(shuffle(x, y), undef) -> x
10864       return OtherSV->getOperand(0);
10865     }
10866
10867     // It may still be beneficial to combine the two shuffles if the
10868     // resulting shuffle is legal.
10869     if (TLI.isTypeLegal(VT)) {
10870       if (!CommuteOperands) {
10871         if (TLI.isShuffleMaskLegal(Mask, VT))
10872           // shuffle(shuffle(x, undef, M1), undef, M2) -> shuffle(x, undef, M3).
10873           // shuffle(shuffle(x, y, M1), undef, M2) -> shuffle(x, undef, M3)
10874           return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0), N1,
10875                                       &Mask[0]);
10876       } else {
10877         // Compute the commuted shuffle mask.
10878         for (unsigned i = 0; i != NumElts; ++i) {
10879           int idx = Mask[i];
10880           if (idx < 0)
10881             continue;
10882           else if (idx < (int)NumElts)
10883             Mask[i] = idx + NumElts;
10884           else
10885             Mask[i] = idx - NumElts;
10886         }
10887
10888         if (TLI.isShuffleMaskLegal(Mask, VT))
10889           //   shuffle(shuffle(x, y, M1), undef, M2) -> shuffle(y, undef, M3)
10890           return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(1), N1,
10891                                       &Mask[0]);
10892       }
10893     }
10894   }
10895
10896   // Canonicalize shuffles according to rules:
10897   //  shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
10898   //  shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
10899   //  shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
10900   if (N1.getOpcode() == ISD::VECTOR_SHUFFLE && N0.getOpcode() != ISD::UNDEF &&
10901       N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
10902       TLI.isTypeLegal(VT)) {
10903     // The incoming shuffle must be of the same type as the result of the
10904     // current shuffle.
10905     assert(N1->getOperand(0).getValueType() == VT &&
10906            "Shuffle types don't match");
10907
10908     SDValue SV0 = N1->getOperand(0);
10909     SDValue SV1 = N1->getOperand(1);
10910     bool HasSameOp0 = N0 == SV0;
10911     bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
10912     if (HasSameOp0 || IsSV1Undef || N0 == SV1)
10913       // Commute the operands of this shuffle so that next rule
10914       // will trigger.
10915       return DAG.getCommutedVectorShuffle(*SVN);
10916   }
10917
10918   // Try to fold according to rules:
10919   //   shuffle(shuffle(A, B, M0), B, M1) -> shuffle(A, B, M2)
10920   //   shuffle(shuffle(A, B, M0), A, M1) -> shuffle(A, B, M2)
10921   //   shuffle(shuffle(A, Undef, M0), B, M1) -> shuffle(A, B, M2)
10922   //   shuffle(shuffle(A, Undef, M0), A, M1) -> shuffle(A, Undef, M2)
10923   // Don't try to fold shuffles with illegal type.
10924   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
10925       N1.getOpcode() != ISD::UNDEF && TLI.isTypeLegal(VT)) {
10926     ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
10927
10928     // The incoming shuffle must be of the same type as the result of the
10929     // current shuffle.
10930     assert(OtherSV->getOperand(0).getValueType() == VT &&
10931            "Shuffle types don't match");
10932
10933     SDValue SV0 = OtherSV->getOperand(0);
10934     SDValue SV1 = OtherSV->getOperand(1);
10935     bool HasSameOp0 = N1 == SV0;
10936     bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
10937     if (!HasSameOp0 && !IsSV1Undef && N1 != SV1)
10938       // Early exit.
10939       return SDValue();
10940
10941     SmallVector<int, 4> Mask;
10942     // Compute the combined shuffle mask for a shuffle with SV0 as the first
10943     // operand, and SV1 as the second operand.
10944     for (unsigned i = 0; i != NumElts; ++i) {
10945       int Idx = SVN->getMaskElt(i);
10946       if (Idx < 0) {
10947         // Propagate Undef.
10948         Mask.push_back(Idx);
10949         continue;
10950       }
10951
10952       if (Idx < (int)NumElts) {
10953         Idx = OtherSV->getMaskElt(Idx);
10954         if (IsSV1Undef && Idx >= (int) NumElts)
10955           Idx = -1;  // Propagate Undef.
10956       } else
10957         Idx = HasSameOp0 ? Idx - NumElts : Idx;
10958
10959       Mask.push_back(Idx);
10960     }
10961
10962     // Check if all indices in Mask are Undef. In case, propagate Undef.
10963     bool isUndefMask = true;
10964     for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
10965       isUndefMask &= Mask[i] < 0;
10966
10967     if (isUndefMask)
10968       return DAG.getUNDEF(VT);
10969
10970     // Avoid introducing shuffles with illegal mask.
10971     if (TLI.isShuffleMaskLegal(Mask, VT)) {
10972       if (IsSV1Undef)
10973         //   shuffle(shuffle(A, Undef, M0), B, M1) -> shuffle(A, B, M2)
10974         //   shuffle(shuffle(A, Undef, M0), A, M1) -> shuffle(A, Undef, M2)
10975         return DAG.getVectorShuffle(VT, SDLoc(N), SV0, N1, &Mask[0]);
10976       return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, &Mask[0]);
10977     }
10978   }
10979
10980   return SDValue();
10981 }
10982
10983 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
10984   SDValue N0 = N->getOperand(0);
10985   SDValue N2 = N->getOperand(2);
10986
10987   // If the input vector is a concatenation, and the insert replaces
10988   // one of the halves, we can optimize into a single concat_vectors.
10989   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
10990       N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
10991     APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
10992     EVT VT = N->getValueType(0);
10993
10994     // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
10995     // (concat_vectors Z, Y)
10996     if (InsIdx == 0)
10997       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
10998                          N->getOperand(1), N0.getOperand(1));
10999
11000     // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
11001     // (concat_vectors X, Z)
11002     if (InsIdx == VT.getVectorNumElements()/2)
11003       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
11004                          N0.getOperand(0), N->getOperand(1));
11005   }
11006
11007   return SDValue();
11008 }
11009
11010 /// XformToShuffleWithZero - Returns a vector_shuffle if it able to transform
11011 /// an AND to a vector_shuffle with the destination vector and a zero vector.
11012 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
11013 ///      vector_shuffle V, Zero, <0, 4, 2, 4>
11014 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
11015   EVT VT = N->getValueType(0);
11016   SDLoc dl(N);
11017   SDValue LHS = N->getOperand(0);
11018   SDValue RHS = N->getOperand(1);
11019   if (N->getOpcode() == ISD::AND) {
11020     if (RHS.getOpcode() == ISD::BITCAST)
11021       RHS = RHS.getOperand(0);
11022     if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
11023       SmallVector<int, 8> Indices;
11024       unsigned NumElts = RHS.getNumOperands();
11025       for (unsigned i = 0; i != NumElts; ++i) {
11026         SDValue Elt = RHS.getOperand(i);
11027         if (!isa<ConstantSDNode>(Elt))
11028           return SDValue();
11029
11030         if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
11031           Indices.push_back(i);
11032         else if (cast<ConstantSDNode>(Elt)->isNullValue())
11033           Indices.push_back(NumElts);
11034         else
11035           return SDValue();
11036       }
11037
11038       // Let's see if the target supports this vector_shuffle.
11039       EVT RVT = RHS.getValueType();
11040       if (!TLI.isVectorClearMaskLegal(Indices, RVT))
11041         return SDValue();
11042
11043       // Return the new VECTOR_SHUFFLE node.
11044       EVT EltVT = RVT.getVectorElementType();
11045       SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
11046                                      DAG.getConstant(0, EltVT));
11047       SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), RVT, ZeroOps);
11048       LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
11049       SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
11050       return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
11051     }
11052   }
11053
11054   return SDValue();
11055 }
11056
11057 /// SimplifyVBinOp - Visit a binary vector operation, like ADD.
11058 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
11059   assert(N->getValueType(0).isVector() &&
11060          "SimplifyVBinOp only works on vectors!");
11061
11062   SDValue LHS = N->getOperand(0);
11063   SDValue RHS = N->getOperand(1);
11064   SDValue Shuffle = XformToShuffleWithZero(N);
11065   if (Shuffle.getNode()) return Shuffle;
11066
11067   // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
11068   // this operation.
11069   if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
11070       RHS.getOpcode() == ISD::BUILD_VECTOR) {
11071     // Check if both vectors are constants. If not bail out.
11072     if (!(cast<BuildVectorSDNode>(LHS)->isConstant() &&
11073           cast<BuildVectorSDNode>(RHS)->isConstant()))
11074       return SDValue();
11075
11076     SmallVector<SDValue, 8> Ops;
11077     for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
11078       SDValue LHSOp = LHS.getOperand(i);
11079       SDValue RHSOp = RHS.getOperand(i);
11080
11081       // Can't fold divide by zero.
11082       if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
11083           N->getOpcode() == ISD::FDIV) {
11084         if ((RHSOp.getOpcode() == ISD::Constant &&
11085              cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
11086             (RHSOp.getOpcode() == ISD::ConstantFP &&
11087              cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
11088           break;
11089       }
11090
11091       EVT VT = LHSOp.getValueType();
11092       EVT RVT = RHSOp.getValueType();
11093       if (RVT != VT) {
11094         // Integer BUILD_VECTOR operands may have types larger than the element
11095         // size (e.g., when the element type is not legal).  Prior to type
11096         // legalization, the types may not match between the two BUILD_VECTORS.
11097         // Truncate one of the operands to make them match.
11098         if (RVT.getSizeInBits() > VT.getSizeInBits()) {
11099           RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
11100         } else {
11101           LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
11102           VT = RVT;
11103         }
11104       }
11105       SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
11106                                    LHSOp, RHSOp);
11107       if (FoldOp.getOpcode() != ISD::UNDEF &&
11108           FoldOp.getOpcode() != ISD::Constant &&
11109           FoldOp.getOpcode() != ISD::ConstantFP)
11110         break;
11111       Ops.push_back(FoldOp);
11112       AddToWorklist(FoldOp.getNode());
11113     }
11114
11115     if (Ops.size() == LHS.getNumOperands())
11116       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), LHS.getValueType(), Ops);
11117   }
11118
11119   // Type legalization might introduce new shuffles in the DAG.
11120   // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
11121   //   -> (shuffle (VBinOp (A, B)), Undef, Mask).
11122   if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
11123       isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
11124       LHS.getOperand(1).getOpcode() == ISD::UNDEF &&
11125       RHS.getOperand(1).getOpcode() == ISD::UNDEF) {
11126     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
11127     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
11128
11129     if (SVN0->getMask().equals(SVN1->getMask())) {
11130       EVT VT = N->getValueType(0);
11131       SDValue UndefVector = LHS.getOperand(1);
11132       SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
11133                                      LHS.getOperand(0), RHS.getOperand(0));
11134       AddUsersToWorklist(N);
11135       return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
11136                                   &SVN0->getMask()[0]);
11137     }
11138   }
11139
11140   return SDValue();
11141 }
11142
11143 /// SimplifyVUnaryOp - Visit a binary vector operation, like FABS/FNEG.
11144 SDValue DAGCombiner::SimplifyVUnaryOp(SDNode *N) {
11145   assert(N->getValueType(0).isVector() &&
11146          "SimplifyVUnaryOp only works on vectors!");
11147
11148   SDValue N0 = N->getOperand(0);
11149
11150   if (N0.getOpcode() != ISD::BUILD_VECTOR)
11151     return SDValue();
11152
11153   // Operand is a BUILD_VECTOR node, see if we can constant fold it.
11154   SmallVector<SDValue, 8> Ops;
11155   for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
11156     SDValue Op = N0.getOperand(i);
11157     if (Op.getOpcode() != ISD::UNDEF &&
11158         Op.getOpcode() != ISD::ConstantFP)
11159       break;
11160     EVT EltVT = Op.getValueType();
11161     SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(N0), EltVT, Op);
11162     if (FoldOp.getOpcode() != ISD::UNDEF &&
11163         FoldOp.getOpcode() != ISD::ConstantFP)
11164       break;
11165     Ops.push_back(FoldOp);
11166     AddToWorklist(FoldOp.getNode());
11167   }
11168
11169   if (Ops.size() != N0.getNumOperands())
11170     return SDValue();
11171
11172   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), N0.getValueType(), Ops);
11173 }
11174
11175 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
11176                                     SDValue N1, SDValue N2){
11177   assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
11178
11179   SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
11180                                  cast<CondCodeSDNode>(N0.getOperand(2))->get());
11181
11182   // If we got a simplified select_cc node back from SimplifySelectCC, then
11183   // break it down into a new SETCC node, and a new SELECT node, and then return
11184   // the SELECT node, since we were called with a SELECT node.
11185   if (SCC.getNode()) {
11186     // Check to see if we got a select_cc back (to turn into setcc/select).
11187     // Otherwise, just return whatever node we got back, like fabs.
11188     if (SCC.getOpcode() == ISD::SELECT_CC) {
11189       SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
11190                                   N0.getValueType(),
11191                                   SCC.getOperand(0), SCC.getOperand(1),
11192                                   SCC.getOperand(4));
11193       AddToWorklist(SETCC.getNode());
11194       return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC,
11195                            SCC.getOperand(2), SCC.getOperand(3));
11196     }
11197
11198     return SCC;
11199   }
11200   return SDValue();
11201 }
11202
11203 /// SimplifySelectOps - Given a SELECT or a SELECT_CC node, where LHS and RHS
11204 /// are the two values being selected between, see if we can simplify the
11205 /// select.  Callers of this should assume that TheSelect is deleted if this
11206 /// returns true.  As such, they should return the appropriate thing (e.g. the
11207 /// node) back to the top-level of the DAG combiner loop to avoid it being
11208 /// looked at.
11209 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
11210                                     SDValue RHS) {
11211
11212   // Cannot simplify select with vector condition
11213   if (TheSelect->getOperand(0).getValueType().isVector()) return false;
11214
11215   // If this is a select from two identical things, try to pull the operation
11216   // through the select.
11217   if (LHS.getOpcode() != RHS.getOpcode() ||
11218       !LHS.hasOneUse() || !RHS.hasOneUse())
11219     return false;
11220
11221   // If this is a load and the token chain is identical, replace the select
11222   // of two loads with a load through a select of the address to load from.
11223   // This triggers in things like "select bool X, 10.0, 123.0" after the FP
11224   // constants have been dropped into the constant pool.
11225   if (LHS.getOpcode() == ISD::LOAD) {
11226     LoadSDNode *LLD = cast<LoadSDNode>(LHS);
11227     LoadSDNode *RLD = cast<LoadSDNode>(RHS);
11228
11229     // Token chains must be identical.
11230     if (LHS.getOperand(0) != RHS.getOperand(0) ||
11231         // Do not let this transformation reduce the number of volatile loads.
11232         LLD->isVolatile() || RLD->isVolatile() ||
11233         // If this is an EXTLOAD, the VT's must match.
11234         LLD->getMemoryVT() != RLD->getMemoryVT() ||
11235         // If this is an EXTLOAD, the kind of extension must match.
11236         (LLD->getExtensionType() != RLD->getExtensionType() &&
11237          // The only exception is if one of the extensions is anyext.
11238          LLD->getExtensionType() != ISD::EXTLOAD &&
11239          RLD->getExtensionType() != ISD::EXTLOAD) ||
11240         // FIXME: this discards src value information.  This is
11241         // over-conservative. It would be beneficial to be able to remember
11242         // both potential memory locations.  Since we are discarding
11243         // src value info, don't do the transformation if the memory
11244         // locations are not in the default address space.
11245         LLD->getPointerInfo().getAddrSpace() != 0 ||
11246         RLD->getPointerInfo().getAddrSpace() != 0 ||
11247         !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
11248                                       LLD->getBasePtr().getValueType()))
11249       return false;
11250
11251     // Check that the select condition doesn't reach either load.  If so,
11252     // folding this will induce a cycle into the DAG.  If not, this is safe to
11253     // xform, so create a select of the addresses.
11254     SDValue Addr;
11255     if (TheSelect->getOpcode() == ISD::SELECT) {
11256       SDNode *CondNode = TheSelect->getOperand(0).getNode();
11257       if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
11258           (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
11259         return false;
11260       // The loads must not depend on one another.
11261       if (LLD->isPredecessorOf(RLD) ||
11262           RLD->isPredecessorOf(LLD))
11263         return false;
11264       Addr = DAG.getSelect(SDLoc(TheSelect),
11265                            LLD->getBasePtr().getValueType(),
11266                            TheSelect->getOperand(0), LLD->getBasePtr(),
11267                            RLD->getBasePtr());
11268     } else {  // Otherwise SELECT_CC
11269       SDNode *CondLHS = TheSelect->getOperand(0).getNode();
11270       SDNode *CondRHS = TheSelect->getOperand(1).getNode();
11271
11272       if ((LLD->hasAnyUseOfValue(1) &&
11273            (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
11274           (RLD->hasAnyUseOfValue(1) &&
11275            (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
11276         return false;
11277
11278       Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
11279                          LLD->getBasePtr().getValueType(),
11280                          TheSelect->getOperand(0),
11281                          TheSelect->getOperand(1),
11282                          LLD->getBasePtr(), RLD->getBasePtr(),
11283                          TheSelect->getOperand(4));
11284     }
11285
11286     SDValue Load;
11287     // It is safe to replace the two loads if they have different alignments,
11288     // but the new load must be the minimum (most restrictive) alignment of the
11289     // inputs.
11290     bool isInvariant = LLD->getAlignment() & RLD->getAlignment();
11291     unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment());
11292     if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
11293       Load = DAG.getLoad(TheSelect->getValueType(0),
11294                          SDLoc(TheSelect),
11295                          // FIXME: Discards pointer and AA info.
11296                          LLD->getChain(), Addr, MachinePointerInfo(),
11297                          LLD->isVolatile(), LLD->isNonTemporal(),
11298                          isInvariant, Alignment);
11299     } else {
11300       Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
11301                             RLD->getExtensionType() : LLD->getExtensionType(),
11302                             SDLoc(TheSelect),
11303                             TheSelect->getValueType(0),
11304                             // FIXME: Discards pointer and AA info.
11305                             LLD->getChain(), Addr, MachinePointerInfo(),
11306                             LLD->getMemoryVT(), LLD->isVolatile(),
11307                             LLD->isNonTemporal(), isInvariant, Alignment);
11308     }
11309
11310     // Users of the select now use the result of the load.
11311     CombineTo(TheSelect, Load);
11312
11313     // Users of the old loads now use the new load's chain.  We know the
11314     // old-load value is dead now.
11315     CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
11316     CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
11317     return true;
11318   }
11319
11320   return false;
11321 }
11322
11323 /// SimplifySelectCC - Simplify an expression of the form (N0 cond N1) ? N2 : N3
11324 /// where 'cond' is the comparison specified by CC.
11325 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
11326                                       SDValue N2, SDValue N3,
11327                                       ISD::CondCode CC, bool NotExtCompare) {
11328   // (x ? y : y) -> y.
11329   if (N2 == N3) return N2;
11330
11331   EVT VT = N2.getValueType();
11332   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
11333   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
11334   ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
11335
11336   // Determine if the condition we're dealing with is constant
11337   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
11338                               N0, N1, CC, DL, false);
11339   if (SCC.getNode()) AddToWorklist(SCC.getNode());
11340   ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
11341
11342   // fold select_cc true, x, y -> x
11343   if (SCCC && !SCCC->isNullValue())
11344     return N2;
11345   // fold select_cc false, x, y -> y
11346   if (SCCC && SCCC->isNullValue())
11347     return N3;
11348
11349   // Check to see if we can simplify the select into an fabs node
11350   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
11351     // Allow either -0.0 or 0.0
11352     if (CFP->getValueAPF().isZero()) {
11353       // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
11354       if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
11355           N0 == N2 && N3.getOpcode() == ISD::FNEG &&
11356           N2 == N3.getOperand(0))
11357         return DAG.getNode(ISD::FABS, DL, VT, N0);
11358
11359       // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
11360       if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
11361           N0 == N3 && N2.getOpcode() == ISD::FNEG &&
11362           N2.getOperand(0) == N3)
11363         return DAG.getNode(ISD::FABS, DL, VT, N3);
11364     }
11365   }
11366
11367   // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
11368   // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
11369   // in it.  This is a win when the constant is not otherwise available because
11370   // it replaces two constant pool loads with one.  We only do this if the FP
11371   // type is known to be legal, because if it isn't, then we are before legalize
11372   // types an we want the other legalization to happen first (e.g. to avoid
11373   // messing with soft float) and if the ConstantFP is not legal, because if
11374   // it is legal, we may not need to store the FP constant in a constant pool.
11375   if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
11376     if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
11377       if (TLI.isTypeLegal(N2.getValueType()) &&
11378           (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
11379                TargetLowering::Legal &&
11380            !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
11381            !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
11382           // If both constants have multiple uses, then we won't need to do an
11383           // extra load, they are likely around in registers for other users.
11384           (TV->hasOneUse() || FV->hasOneUse())) {
11385         Constant *Elts[] = {
11386           const_cast<ConstantFP*>(FV->getConstantFPValue()),
11387           const_cast<ConstantFP*>(TV->getConstantFPValue())
11388         };
11389         Type *FPTy = Elts[0]->getType();
11390         const DataLayout &TD = *TLI.getDataLayout();
11391
11392         // Create a ConstantArray of the two constants.
11393         Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
11394         SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
11395                                             TD.getPrefTypeAlignment(FPTy));
11396         unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
11397
11398         // Get the offsets to the 0 and 1 element of the array so that we can
11399         // select between them.
11400         SDValue Zero = DAG.getIntPtrConstant(0);
11401         unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
11402         SDValue One = DAG.getIntPtrConstant(EltSize);
11403
11404         SDValue Cond = DAG.getSetCC(DL,
11405                                     getSetCCResultType(N0.getValueType()),
11406                                     N0, N1, CC);
11407         AddToWorklist(Cond.getNode());
11408         SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
11409                                           Cond, One, Zero);
11410         AddToWorklist(CstOffset.getNode());
11411         CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
11412                             CstOffset);
11413         AddToWorklist(CPIdx.getNode());
11414         return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
11415                            MachinePointerInfo::getConstantPool(), false,
11416                            false, false, Alignment);
11417
11418       }
11419     }
11420
11421   // Check to see if we can perform the "gzip trick", transforming
11422   // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
11423   if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
11424       (N1C->isNullValue() ||                         // (a < 0) ? b : 0
11425        (N1C->getAPIntValue() == 1 && N0 == N2))) {   // (a < 1) ? a : 0
11426     EVT XType = N0.getValueType();
11427     EVT AType = N2.getValueType();
11428     if (XType.bitsGE(AType)) {
11429       // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
11430       // single-bit constant.
11431       if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
11432         unsigned ShCtV = N2C->getAPIntValue().logBase2();
11433         ShCtV = XType.getSizeInBits()-ShCtV-1;
11434         SDValue ShCt = DAG.getConstant(ShCtV,
11435                                        getShiftAmountTy(N0.getValueType()));
11436         SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
11437                                     XType, N0, ShCt);
11438         AddToWorklist(Shift.getNode());
11439
11440         if (XType.bitsGT(AType)) {
11441           Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
11442           AddToWorklist(Shift.getNode());
11443         }
11444
11445         return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
11446       }
11447
11448       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
11449                                   XType, N0,
11450                                   DAG.getConstant(XType.getSizeInBits()-1,
11451                                          getShiftAmountTy(N0.getValueType())));
11452       AddToWorklist(Shift.getNode());
11453
11454       if (XType.bitsGT(AType)) {
11455         Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
11456         AddToWorklist(Shift.getNode());
11457       }
11458
11459       return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
11460     }
11461   }
11462
11463   // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
11464   // where y is has a single bit set.
11465   // A plaintext description would be, we can turn the SELECT_CC into an AND
11466   // when the condition can be materialized as an all-ones register.  Any
11467   // single bit-test can be materialized as an all-ones register with
11468   // shift-left and shift-right-arith.
11469   if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
11470       N0->getValueType(0) == VT &&
11471       N1C && N1C->isNullValue() &&
11472       N2C && N2C->isNullValue()) {
11473     SDValue AndLHS = N0->getOperand(0);
11474     ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
11475     if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
11476       // Shift the tested bit over the sign bit.
11477       APInt AndMask = ConstAndRHS->getAPIntValue();
11478       SDValue ShlAmt =
11479         DAG.getConstant(AndMask.countLeadingZeros(),
11480                         getShiftAmountTy(AndLHS.getValueType()));
11481       SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
11482
11483       // Now arithmetic right shift it all the way over, so the result is either
11484       // all-ones, or zero.
11485       SDValue ShrAmt =
11486         DAG.getConstant(AndMask.getBitWidth()-1,
11487                         getShiftAmountTy(Shl.getValueType()));
11488       SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
11489
11490       return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
11491     }
11492   }
11493
11494   // fold select C, 16, 0 -> shl C, 4
11495   if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
11496       TLI.getBooleanContents(N0.getValueType()) ==
11497           TargetLowering::ZeroOrOneBooleanContent) {
11498
11499     // If the caller doesn't want us to simplify this into a zext of a compare,
11500     // don't do it.
11501     if (NotExtCompare && N2C->getAPIntValue() == 1)
11502       return SDValue();
11503
11504     // Get a SetCC of the condition
11505     // NOTE: Don't create a SETCC if it's not legal on this target.
11506     if (!LegalOperations ||
11507         TLI.isOperationLegal(ISD::SETCC,
11508           LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
11509       SDValue Temp, SCC;
11510       // cast from setcc result type to select result type
11511       if (LegalTypes) {
11512         SCC  = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
11513                             N0, N1, CC);
11514         if (N2.getValueType().bitsLT(SCC.getValueType()))
11515           Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
11516                                         N2.getValueType());
11517         else
11518           Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
11519                              N2.getValueType(), SCC);
11520       } else {
11521         SCC  = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
11522         Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
11523                            N2.getValueType(), SCC);
11524       }
11525
11526       AddToWorklist(SCC.getNode());
11527       AddToWorklist(Temp.getNode());
11528
11529       if (N2C->getAPIntValue() == 1)
11530         return Temp;
11531
11532       // shl setcc result by log2 n2c
11533       return DAG.getNode(
11534           ISD::SHL, DL, N2.getValueType(), Temp,
11535           DAG.getConstant(N2C->getAPIntValue().logBase2(),
11536                           getShiftAmountTy(Temp.getValueType())));
11537     }
11538   }
11539
11540   // Check to see if this is the equivalent of setcc
11541   // FIXME: Turn all of these into setcc if setcc if setcc is legal
11542   // otherwise, go ahead with the folds.
11543   if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
11544     EVT XType = N0.getValueType();
11545     if (!LegalOperations ||
11546         TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
11547       SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
11548       if (Res.getValueType() != VT)
11549         Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
11550       return Res;
11551     }
11552
11553     // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
11554     if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
11555         (!LegalOperations ||
11556          TLI.isOperationLegal(ISD::CTLZ, XType))) {
11557       SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
11558       return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
11559                          DAG.getConstant(Log2_32(XType.getSizeInBits()),
11560                                        getShiftAmountTy(Ctlz.getValueType())));
11561     }
11562     // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
11563     if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
11564       SDValue NegN0 = DAG.getNode(ISD::SUB, SDLoc(N0),
11565                                   XType, DAG.getConstant(0, XType), N0);
11566       SDValue NotN0 = DAG.getNOT(SDLoc(N0), N0, XType);
11567       return DAG.getNode(ISD::SRL, DL, XType,
11568                          DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
11569                          DAG.getConstant(XType.getSizeInBits()-1,
11570                                          getShiftAmountTy(XType)));
11571     }
11572     // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
11573     if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
11574       SDValue Sign = DAG.getNode(ISD::SRL, SDLoc(N0), XType, N0,
11575                                  DAG.getConstant(XType.getSizeInBits()-1,
11576                                          getShiftAmountTy(N0.getValueType())));
11577       return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
11578     }
11579   }
11580
11581   // Check to see if this is an integer abs.
11582   // select_cc setg[te] X,  0,  X, -X ->
11583   // select_cc setgt    X, -1,  X, -X ->
11584   // select_cc setl[te] X,  0, -X,  X ->
11585   // select_cc setlt    X,  1, -X,  X ->
11586   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
11587   if (N1C) {
11588     ConstantSDNode *SubC = nullptr;
11589     if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
11590          (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
11591         N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
11592       SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
11593     else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
11594               (N1C->isOne() && CC == ISD::SETLT)) &&
11595              N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
11596       SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
11597
11598     EVT XType = N0.getValueType();
11599     if (SubC && SubC->isNullValue() && XType.isInteger()) {
11600       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), XType,
11601                                   N0,
11602                                   DAG.getConstant(XType.getSizeInBits()-1,
11603                                          getShiftAmountTy(N0.getValueType())));
11604       SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0),
11605                                 XType, N0, Shift);
11606       AddToWorklist(Shift.getNode());
11607       AddToWorklist(Add.getNode());
11608       return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
11609     }
11610   }
11611
11612   return SDValue();
11613 }
11614
11615 /// SimplifySetCC - This is a stub for TargetLowering::SimplifySetCC.
11616 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
11617                                    SDValue N1, ISD::CondCode Cond,
11618                                    SDLoc DL, bool foldBooleans) {
11619   TargetLowering::DAGCombinerInfo
11620     DagCombineInfo(DAG, Level, false, this);
11621   return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
11622 }
11623
11624 /// BuildSDIV - Given an ISD::SDIV node expressing a divide by constant, return
11625 /// a DAG expression to select that will generate the same value by multiplying
11626 /// by a magic number.  See:
11627 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
11628 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
11629   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
11630   if (!C)
11631     return SDValue();
11632
11633   // Avoid division by zero.
11634   if (!C->getAPIntValue())
11635     return SDValue();
11636
11637   std::vector<SDNode*> Built;
11638   SDValue S =
11639       TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
11640
11641   for (SDNode *N : Built)
11642     AddToWorklist(N);
11643   return S;
11644 }
11645
11646 /// BuildSDIVPow2 - Given an ISD::SDIV node expressing a divide by constant
11647 /// power of 2, return a DAG expression to select that will generate the same
11648 /// value by right shifting.
11649 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
11650   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
11651   if (!C)
11652     return SDValue();
11653
11654   // Avoid division by zero.
11655   if (!C->getAPIntValue())
11656     return SDValue();
11657
11658   std::vector<SDNode *> Built;
11659   SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
11660
11661   for (SDNode *N : Built)
11662     AddToWorklist(N);
11663   return S;
11664 }
11665
11666 /// BuildUDIV - Given an ISD::UDIV node expressing a divide by constant,
11667 /// return a DAG expression to select that will generate the same value by
11668 /// multiplying by a magic number.  See:
11669 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
11670 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
11671   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
11672   if (!C)
11673     return SDValue();
11674
11675   // Avoid division by zero.
11676   if (!C->getAPIntValue())
11677     return SDValue();
11678
11679   std::vector<SDNode*> Built;
11680   SDValue S =
11681       TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
11682
11683   for (SDNode *N : Built)
11684     AddToWorklist(N);
11685   return S;
11686 }
11687
11688 /// FindBaseOffset - Return true if base is a frame index, which is known not
11689 // to alias with anything but itself.  Provides base object and offset as
11690 // results.
11691 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
11692                            const GlobalValue *&GV, const void *&CV) {
11693   // Assume it is a primitive operation.
11694   Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
11695
11696   // If it's an adding a simple constant then integrate the offset.
11697   if (Base.getOpcode() == ISD::ADD) {
11698     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
11699       Base = Base.getOperand(0);
11700       Offset += C->getZExtValue();
11701     }
11702   }
11703
11704   // Return the underlying GlobalValue, and update the Offset.  Return false
11705   // for GlobalAddressSDNode since the same GlobalAddress may be represented
11706   // by multiple nodes with different offsets.
11707   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
11708     GV = G->getGlobal();
11709     Offset += G->getOffset();
11710     return false;
11711   }
11712
11713   // Return the underlying Constant value, and update the Offset.  Return false
11714   // for ConstantSDNodes since the same constant pool entry may be represented
11715   // by multiple nodes with different offsets.
11716   if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
11717     CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
11718                                          : (const void *)C->getConstVal();
11719     Offset += C->getOffset();
11720     return false;
11721   }
11722   // If it's any of the following then it can't alias with anything but itself.
11723   return isa<FrameIndexSDNode>(Base);
11724 }
11725
11726 /// isAlias - Return true if there is any possibility that the two addresses
11727 /// overlap.
11728 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
11729   // If they are the same then they must be aliases.
11730   if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
11731
11732   // If they are both volatile then they cannot be reordered.
11733   if (Op0->isVolatile() && Op1->isVolatile()) return true;
11734
11735   // Gather base node and offset information.
11736   SDValue Base1, Base2;
11737   int64_t Offset1, Offset2;
11738   const GlobalValue *GV1, *GV2;
11739   const void *CV1, *CV2;
11740   bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
11741                                       Base1, Offset1, GV1, CV1);
11742   bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
11743                                       Base2, Offset2, GV2, CV2);
11744
11745   // If they have a same base address then check to see if they overlap.
11746   if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
11747     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
11748              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
11749
11750   // It is possible for different frame indices to alias each other, mostly
11751   // when tail call optimization reuses return address slots for arguments.
11752   // To catch this case, look up the actual index of frame indices to compute
11753   // the real alias relationship.
11754   if (isFrameIndex1 && isFrameIndex2) {
11755     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11756     Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
11757     Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
11758     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
11759              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
11760   }
11761
11762   // Otherwise, if we know what the bases are, and they aren't identical, then
11763   // we know they cannot alias.
11764   if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
11765     return false;
11766
11767   // If we know required SrcValue1 and SrcValue2 have relatively large alignment
11768   // compared to the size and offset of the access, we may be able to prove they
11769   // do not alias.  This check is conservative for now to catch cases created by
11770   // splitting vector types.
11771   if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
11772       (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
11773       (Op0->getMemoryVT().getSizeInBits() >> 3 ==
11774        Op1->getMemoryVT().getSizeInBits() >> 3) &&
11775       (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) {
11776     int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
11777     int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
11778
11779     // There is no overlap between these relatively aligned accesses of similar
11780     // size, return no alias.
11781     if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
11782         (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
11783       return false;
11784   }
11785
11786   bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0 ? CombinerGlobalAA :
11787     TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
11788 #ifndef NDEBUG
11789   if (CombinerAAOnlyFunc.getNumOccurrences() &&
11790       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
11791     UseAA = false;
11792 #endif
11793   if (UseAA &&
11794       Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
11795     // Use alias analysis information.
11796     int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
11797                                  Op1->getSrcValueOffset());
11798     int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
11799         Op0->getSrcValueOffset() - MinOffset;
11800     int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
11801         Op1->getSrcValueOffset() - MinOffset;
11802     AliasAnalysis::AliasResult AAResult =
11803         AA.alias(AliasAnalysis::Location(Op0->getMemOperand()->getValue(),
11804                                          Overlap1,
11805                                          UseTBAA ? Op0->getAAInfo() : AAMDNodes()),
11806                  AliasAnalysis::Location(Op1->getMemOperand()->getValue(),
11807                                          Overlap2,
11808                                          UseTBAA ? Op1->getAAInfo() : AAMDNodes()));
11809     if (AAResult == AliasAnalysis::NoAlias)
11810       return false;
11811   }
11812
11813   // Otherwise we have to assume they alias.
11814   return true;
11815 }
11816
11817 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
11818 /// looking for aliasing nodes and adding them to the Aliases vector.
11819 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
11820                                    SmallVectorImpl<SDValue> &Aliases) {
11821   SmallVector<SDValue, 8> Chains;     // List of chains to visit.
11822   SmallPtrSet<SDNode *, 16> Visited;  // Visited node set.
11823
11824   // Get alias information for node.
11825   bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
11826
11827   // Starting off.
11828   Chains.push_back(OriginalChain);
11829   unsigned Depth = 0;
11830
11831   // Look at each chain and determine if it is an alias.  If so, add it to the
11832   // aliases list.  If not, then continue up the chain looking for the next
11833   // candidate.
11834   while (!Chains.empty()) {
11835     SDValue Chain = Chains.back();
11836     Chains.pop_back();
11837
11838     // For TokenFactor nodes, look at each operand and only continue up the
11839     // chain until we find two aliases.  If we've seen two aliases, assume we'll
11840     // find more and revert to original chain since the xform is unlikely to be
11841     // profitable.
11842     //
11843     // FIXME: The depth check could be made to return the last non-aliasing
11844     // chain we found before we hit a tokenfactor rather than the original
11845     // chain.
11846     if (Depth > 6 || Aliases.size() == 2) {
11847       Aliases.clear();
11848       Aliases.push_back(OriginalChain);
11849       return;
11850     }
11851
11852     // Don't bother if we've been before.
11853     if (!Visited.insert(Chain.getNode()))
11854       continue;
11855
11856     switch (Chain.getOpcode()) {
11857     case ISD::EntryToken:
11858       // Entry token is ideal chain operand, but handled in FindBetterChain.
11859       break;
11860
11861     case ISD::LOAD:
11862     case ISD::STORE: {
11863       // Get alias information for Chain.
11864       bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
11865           !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
11866
11867       // If chain is alias then stop here.
11868       if (!(IsLoad && IsOpLoad) &&
11869           isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
11870         Aliases.push_back(Chain);
11871       } else {
11872         // Look further up the chain.
11873         Chains.push_back(Chain.getOperand(0));
11874         ++Depth;
11875       }
11876       break;
11877     }
11878
11879     case ISD::TokenFactor:
11880       // We have to check each of the operands of the token factor for "small"
11881       // token factors, so we queue them up.  Adding the operands to the queue
11882       // (stack) in reverse order maintains the original order and increases the
11883       // likelihood that getNode will find a matching token factor (CSE.)
11884       if (Chain.getNumOperands() > 16) {
11885         Aliases.push_back(Chain);
11886         break;
11887       }
11888       for (unsigned n = Chain.getNumOperands(); n;)
11889         Chains.push_back(Chain.getOperand(--n));
11890       ++Depth;
11891       break;
11892
11893     default:
11894       // For all other instructions we will just have to take what we can get.
11895       Aliases.push_back(Chain);
11896       break;
11897     }
11898   }
11899
11900   // We need to be careful here to also search for aliases through the
11901   // value operand of a store, etc. Consider the following situation:
11902   //   Token1 = ...
11903   //   L1 = load Token1, %52
11904   //   S1 = store Token1, L1, %51
11905   //   L2 = load Token1, %52+8
11906   //   S2 = store Token1, L2, %51+8
11907   //   Token2 = Token(S1, S2)
11908   //   L3 = load Token2, %53
11909   //   S3 = store Token2, L3, %52
11910   //   L4 = load Token2, %53+8
11911   //   S4 = store Token2, L4, %52+8
11912   // If we search for aliases of S3 (which loads address %52), and we look
11913   // only through the chain, then we'll miss the trivial dependence on L1
11914   // (which also loads from %52). We then might change all loads and
11915   // stores to use Token1 as their chain operand, which could result in
11916   // copying %53 into %52 before copying %52 into %51 (which should
11917   // happen first).
11918   //
11919   // The problem is, however, that searching for such data dependencies
11920   // can become expensive, and the cost is not directly related to the
11921   // chain depth. Instead, we'll rule out such configurations here by
11922   // insisting that we've visited all chain users (except for users
11923   // of the original chain, which is not necessary). When doing this,
11924   // we need to look through nodes we don't care about (otherwise, things
11925   // like register copies will interfere with trivial cases).
11926
11927   SmallVector<const SDNode *, 16> Worklist;
11928   for (SmallPtrSet<SDNode *, 16>::iterator I = Visited.begin(),
11929        IE = Visited.end(); I != IE; ++I)
11930     if (*I != OriginalChain.getNode())
11931       Worklist.push_back(*I);
11932
11933   while (!Worklist.empty()) {
11934     const SDNode *M = Worklist.pop_back_val();
11935
11936     // We have already visited M, and want to make sure we've visited any uses
11937     // of M that we care about. For uses that we've not visisted, and don't
11938     // care about, queue them to the worklist.
11939
11940     for (SDNode::use_iterator UI = M->use_begin(),
11941          UIE = M->use_end(); UI != UIE; ++UI)
11942       if (UI.getUse().getValueType() == MVT::Other && Visited.insert(*UI)) {
11943         if (isa<MemIntrinsicSDNode>(*UI) || isa<MemSDNode>(*UI)) {
11944           // We've not visited this use, and we care about it (it could have an
11945           // ordering dependency with the original node).
11946           Aliases.clear();
11947           Aliases.push_back(OriginalChain);
11948           return;
11949         }
11950
11951         // We've not visited this use, but we don't care about it. Mark it as
11952         // visited and enqueue it to the worklist.
11953         Worklist.push_back(*UI);
11954       }
11955   }
11956 }
11957
11958 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes, looking
11959 /// for a better chain (aliasing node.)
11960 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
11961   SmallVector<SDValue, 8> Aliases;  // Ops for replacing token factor.
11962
11963   // Accumulate all the aliases to this node.
11964   GatherAllAliases(N, OldChain, Aliases);
11965
11966   // If no operands then chain to entry token.
11967   if (Aliases.size() == 0)
11968     return DAG.getEntryNode();
11969
11970   // If a single operand then chain to it.  We don't need to revisit it.
11971   if (Aliases.size() == 1)
11972     return Aliases[0];
11973
11974   // Construct a custom tailored token factor.
11975   return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
11976 }
11977
11978 // SelectionDAG::Combine - This is the entry point for the file.
11979 //
11980 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
11981                            CodeGenOpt::Level OptLevel) {
11982   /// run - This is the main entry point to this class.
11983   ///
11984   DAGCombiner(*this, AA, OptLevel).Run(Level);
11985 }